text
stringlengths 10
2.72M
|
|---|
/*
* 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 controller.admin;
import entity.Products;
import entity.Sizes;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import model.admin.AdminProductModel;
import model.admin.AdminSizeModel;
import model.admin.AdminUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author NamPA
*/
@Controller
@RequestMapping(value = "/adminSizesController")
public class AdminSizesController {
@RequestMapping(value = "/getAll")
public ModelAndView getAllSizes() {
ModelAndView mav = new ModelAndView("admin/size/sizes");
List<Sizes> listSize = AdminSizeModel.getAllSizes();
mav.addObject("listSize", listSize);
return mav;
}
@RequestMapping(value = "/doSearch")
public ModelAndView doSearch(HttpServletRequest request) {
ModelAndView mav = new ModelAndView("admin/size/sizes");
String name = request.getParameter("search");
List<Sizes> listSize = AdminSizeModel.findSizeByName(name);
mav.addObject("listSize", listSize);
return mav;
}
@RequestMapping(value = "/initInsert")
public ModelAndView initInsert() {
ModelAndView mav = new ModelAndView("admin/size/newSize");
Sizes sizeInsert = new Sizes();
List<Products> listProduct = AdminProductModel.getAllProducts();
mav.addObject("listProduct", listProduct);
mav.addObject("sizeInsert", sizeInsert);
return mav;
}
@RequestMapping(value = "/insert")
public String insertSize(Sizes sizeInsert, HttpServletRequest request) {
sizeInsert.setCreated(AdminUtil.getCurrentDate());
Products product = AdminProductModel.getProductById(request.getParameter("product"));
sizeInsert.setProducts(product);
return (AdminSizeModel.addSize(sizeInsert)) ? "redirect:getAll.htm" : "admin/error";
}
@RequestMapping(value = "/initUpdate")
public ModelAndView initUpdate(String sizeId) {
ModelAndView mav = new ModelAndView("admin/size/updateSize");
List<Products> listProduct = AdminProductModel.getAllProducts();
Sizes sizeUpdate = AdminSizeModel.getSizeById(sizeId);
mav.addObject("sizeUpdate", sizeUpdate);
mav.addObject("listProduct", listProduct);
return mav;
}
@RequestMapping(value = "/update")
public String updateSize(Sizes sizeUpdate, HttpServletRequest request) {
Sizes size = AdminSizeModel.getSizeById(String.valueOf(sizeUpdate.getSizeId()));
Products product = AdminProductModel.getProductById(request.getParameter("product"));
sizeUpdate.setCreated(size.getCreated());
sizeUpdate.setProducts(product);
return AdminSizeModel.updateSize(sizeUpdate) ? "redirect:getAll.htm" : "admin/error";
}
@RequestMapping(value = "/delete")
public String deleteSize(String sizeId, HttpServletRequest request) throws SQLException {
if (request.getSession().getAttribute("adminName") == null) {
return "redirect:/adminIndexController/login.htm";
}
return AdminSizeModel.deleteSize(sizeId) ? "redirect:getAll.htm" : "admin/error";
}
}
|
package com.example.mergetablelayout_slidelayout_inflater;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TableLayout;
public class TableLayoutChild extends TableLayout {
public TableLayoutChild(Context context) {
super(context);
}
public TableLayoutChild(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
|
package ftnbooking.rating.service;
import javax.jws.WebService;
import ftnbooking.rating.contracts.IRatingService;
import ftnbooking.rating.model.RatingData;
@WebService(endpointInterface = "ftnbooking.rating.contracts.IRatingService")
public class RatingService implements IRatingService{
@Override
public double CalculateRating(RatingData ratingData) {
// TODO Auto-generated method stub
double sumOfGrades = ratingData.getOldGrade() * ratingData.getNumberOfGrades();
sumOfGrades += ratingData.getNewGrade();
double retVal = sumOfGrades / (ratingData.getNumberOfGrades() + 1);
return retVal;
}
}
|
package br.ufs.livraria.dao;
import javax.ejb.Stateless;
import br.ufs.livraria.modelo.Endereco;
@Stateless
public class EnderecoDAO extends DAO<Endereco> {
private static final long serialVersionUID = 1L;
public EnderecoDAO() {
super(Endereco.class);
}
}
|
package com.osce.api.biz.plan.template;
import com.osce.dto.biz.plan.template.TdInsStationDto;
import com.osce.dto.biz.plan.template.TdModelInfo;
import com.osce.dto.biz.plan.template.TemplateDto;
import com.osce.dto.common.PfBachChangeStatusDto;
import com.osce.result.PageResult;
import com.osce.vo.biz.plan.template.TdInsStationDetailVo;
import com.osce.vo.biz.plan.template.TdInsStationVo;
import com.osce.vo.biz.plan.template.TdModelVo;
import java.util.List;
/**
* @ClassName: PfTemplateService
* @Description: 实训模板接口
* @Author yangtongbin
* @Date 2019-05-25
*/
public interface PfTemplateService {
/**
* 列表
*
* @param dto
* @return
*/
PageResult pageTemplate(TemplateDto dto);
/**
* 考站定义
*
* @param dto
* @return
*/
TdModelVo addTemplate(TdModelInfo dto);
/**
* 删除
*
* @param dto
* @return
*/
boolean delTemplate(PfBachChangeStatusDto dto);
/**
* 获取考站定义信息
*
* @param idModel 模板id
* @return
*/
TdModelInfo selectTdModelInfo(Long idModel);
/**
* 获取排站信息
*
* @param idModel 模板id
* @return
*/
List<TdInsStationVo> selectStationInfo(Long idModel);
/**
* 排站信息 - 修改技能
*
* @param dto
* @return
*/
boolean editSkill(TdInsStationDto dto);
/**
* 获取模拟排考信息
*
* @param idModel 模板id
* @return
*/
List<TdInsStationDetailVo> selectStationDetail(Long idModel);
}
|
package com.microsilver.mrcard.basicservice.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class UserSimpleDto {
@ApiModelProperty(value = "用户id")
private Long userId;
@ApiModelProperty(value = "用户token")
private String userToken;
@ApiModelProperty(value = "是否启用")
private Integer status;
}
|
package stubs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.CompressionType;
import org.apache.hadoop.io.SequenceFile.Writer;
import org.apache.hadoop.io.SequenceFile.Writer.Option;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
//@SuppressWarnings("unused")
public class SequenceFileWriter extends Configured implements Tool{
// static private enum exitCode {
static private final int
Success = 0,
InputFileNotExists = 1,
OutputFileExists = 2,
WrongArgumentsNumber = 3;
// };
private static FileSystem fs;
private static Configuration conf;
@Override
public int run(String[] args) throws Exception {
int exitCode = Success;
if (args.length != 2) {
System.err.printf("Usage: SequenceFileWriter <input dir> <output dir>\n");
exitCode = WrongArgumentsNumber;
return exitCode;
}
Path inPath = new Path(args[0]);
Path outPath = new Path(args[1]);
conf = getConf();
fs = FileSystem.get(conf);
if (fs.exists(outPath)) {
System.err.println("Output file exists");
exitCode = OutputFileExists;
return exitCode;
}
if (fs.exists(inPath)) {
ArrayList<FileStatus> listOfFiles = null;
if (fs.isDirectory(inPath)) {
listOfFiles = new ArrayList<FileStatus>(Arrays.asList(fs.listStatus(inPath)));
}
if (fs.isFile(inPath)) {
listOfFiles = new ArrayList<FileStatus>();
listOfFiles.add(fs.getFileStatus(inPath));
}
if (listOfFiles != null) {
writeSequenceFile(listOfFiles, args[1]);
}
} else {
System.err.println(args[0] + " does not exist");
exitCode = InputFileNotExists;
return exitCode;
}
System.out.println("Job Done! Check out result.seq in " + args[1] + "/");
return exitCode;
}
private static void writeSequenceFile(ArrayList<FileStatus> listOfFiles, String outPath) throws IOException {
Text key = new Text();
Text value = new Text();
Pattern pattern = Pattern.compile("(\\d{1,3}(?:\\.\\d{1,3}){3})");
Option compressOption = Writer.compression(CompressionType.NONE);//, new DefaultCodec());
SequenceFile.Writer writer = null;
try {
writer = SequenceFile.createWriter(
conf,
SequenceFile.Writer.file(new Path(outPath + "//result.seq")),
SequenceFile.Writer.keyClass(key.getClass()),
SequenceFile.Writer.valueClass(value.getClass()),
compressOption
);
for (FileStatus f : listOfFiles) {
if (f.isFile()) {
BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(f.getPath())));
String line;
line = br.readLine();
while (line != null) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
key.set(matcher.group(0));
value.set(line);
writer.append(key, value);
}
line = br.readLine();
}
}
}
}
finally {
IOUtils.closeStream(writer);
}
}
public static void main(String[] args) throws Exception {
int exitCode = ToolRunner.run(new Configuration(), new SequenceFileWriter(), args);
System.exit(exitCode);
}
}
|
package com.kodilla.good.patterns.challenges.firstChallenge;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MainRunner {
private static final String SEPARATOR = " ! ";
public static void main(String[] args){
Map<String, List<String>> listMap = new MovieStore().getMovies();
String result = listMap.values()
.stream()
.flatMap(Collection::stream)
.collect(Collectors.joining(SEPARATOR));
System.out.println(result);
}
}
|
package principal;
public class Constantes {
public static final int LADO_CARTA = 72;
public static final int ALTO_CARTA = 96;
public static final String RUTA_CARTAS = "/Assets/cartas/naipes.png";
public static final String NOMBRE_JUEGO = "Truco UCAB";
public static final int ALTO_PANTALLA = 512;
public static final int ANCHO_PANTALLA = 1024;
}
|
package com.smxknife.jvm.demo01;
/**
* 模拟java虚拟机抛出StackOverflowError
* 1 前提条件:
* 1.1 栈容量大小是固定的,通过-Xss128k来控制jvm为每个线程分配的内存大小
* 2 模拟的原理:
* 2.1 jvm对java虚拟机栈只会有两种操作,以栈帧为单位入栈和出栈
* 2.2 那么只需要控制每个线程内存的大小,禁止出栈,不断进行入栈操作,就会出现该错误
* 3 栈帧是在何时产生:
* 3.1 栈帧是随着方法调用而创建,方法结束而销毁(无论是否异常)
* 4 结论:
* 4.1 基于以上思路,采用递归的方式,不断的进行方法调用而不进行方法结束,肯定会模拟出该错误
*/
public class JvmStackOverflow {
int count = 0;
public static void main(String[] args) {
JvmStackOverflow jvm = new JvmStackOverflow();
try {
jvm.mockMethod();
} catch (StackOverflowError e) {
System.out.println("count : " + jvm.count);
e.printStackTrace();
}
}
public void mockMethod() {
count++;
mockMethod();
}
}
|
package mx.com.azaelmorales.yurtaapp;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
public class PedidosActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pedidos);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation_pedidos);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_mod_pedidos);
setSupportActionBar(toolbar);
toolbar.setTitle("Pedidos");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//startActivity(new Intent(getApplicationContext(),HomeActivity.class));
finish();
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
FragmentManager fragmentManager=getSupportFragmentManager();
switch (item.getItemId()) {
case R.id.navigation_lista_pedidos:
fragmentManager.beginTransaction().replace(R.id.fragment_content_pedidos,
new PedidosViewFragment()).addToBackStack(null).commit();
return true;
case R.id.navigation_pedidos_conf:
fragmentManager.beginTransaction().replace(R.id.fragment_content_pedidos,
new PedidosConfirmadosFragment()).addToBackStack(null).commit();
return true;
case R.id.navigation_pedidos_sinConf:
fragmentManager.beginTransaction().replace(R.id.fragment_content_pedidos,
new PedidosEsperaFragment()).addToBackStack(null).commit();
return true;
}
return false;
}
};
}
|
package com.yixin.kepler.common;/**
* Created by liushuai2 on 2018/6/7.
*/
import com.yixin.kepler.common.enums.RuleTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.util.Map;
/**
* Package : com.yixin.kepler.common
*
* @author YixinCapital -- liushuai2
* 2018年06月07日 10:14
*/
public class RuleUtil {
private static final Logger logger = LoggerFactory.getLogger(RuleUtil.class);
public static Object exec(RuleTypeEnum ruleType, String rule, Object val){
Assert.notNull(ruleType, "ruleType is empty");
Assert.notNull(rule, "rule is empty");
Assert.notNull(val, "val is empty");
logger.info("规则校验结果,ruleType:{}, rule:{}, val:{}", ruleType, rule, JacksonUtil.fromObjectToJson(val));
Object out = null;
switch (ruleType){
case REG:
return execRegex(rule, val);
case JS:
return execScript(rule, val);
default:
}
logger.info("规则校验结果 out:{}", out);
return out;
}
// todo 执行javascript
private static Object execScript(String rule, Object val){
Assert.notNull(rule, "rule is empty");
Assert.isTrue( !(val instanceof Map), "参数异常。val 不是map格式的数据");
logger.info("执行script脚本规则 rule:{}, val:{}", rule, val);
Map<String, Object> valMap = (Map<String,Object>) val;
Object obj = ScriptEngineUtil.eval(rule, valMap);
logger.info("执行script脚本规则 rule:{},val:{},result:{}", rule, val, obj);
return obj;
}
private static boolean execRegex(String rule, Object val){
Assert.notNull(rule, "rule is empty");
Assert.notNull(val, "val is empty");
logger.info("执行regex脚本规则 rule:{} val:{}");
boolean matched = RegexUtil.pattern(rule, val);
logger.info("执行regex脚本规则 rule:{} val:{} matched:{}", matched);
return matched;
}
}
|
package it.polimi.se2019.model.grabbable;
/**
* Ammo tile represents an ammo tile that can be picked up from a square. It contains an ammo box and optionally a power up card
*
* @author Eugenio Ostrovan
* @author Fabio Mauri
*/
public class AmmoTile extends Grabbable{
/**
* The ammunition box contained in the ammo tile
*/
private Ammo ammo;
/**
* The boolean has value 1 if the ammo tile contains a power up card, 0 otherwise
*/
private boolean hasPowerUp;
/**
* Get the ammo contained in the ammo tile
* @return the ammo in the ammo tile
*/
public Ammo getAmmo() {
return new Ammo(this.ammo.getRed(), this.ammo.getBlue(), this.ammo.getYellow());
}
/**
*
* @return whether the ammo tile contains a power up card
*/
public boolean getPowerUp(){
return hasPowerUp;
}
/**
* Create a new ammo tile
* @param redAmount the amount of red ammunition that the ammo tile will contain
* @param blueAmount the amount of blue ammunition that the ammo tile will contain
* @param yellowAmount the amount of yellow ammunition that the ammo tile will contain
* @param containsPowerup specifies whether the ammo tile will contain a power up card
*/
public AmmoTile(int redAmount, int blueAmount, int yellowAmount, boolean containsPowerup) {
this.ammo = new Ammo(redAmount, blueAmount, yellowAmount);
this.hasPowerUp = containsPowerup;
}
}
|
package com.bnuz.outdooractivitymanagementsystem.Presenter.impl;
import android.os.Looper;
import com.bnuz.outdooractivitymanagementsystem.Model.impl.ManagementAModelImpl;
import com.bnuz.outdooractivitymanagementsystem.Model.inter.IManagementAModel;
import com.bnuz.outdooractivitymanagementsystem.Presenter.callback.CallBack;
import com.bnuz.outdooractivitymanagementsystem.Presenter.inter.IManagementAPresenter;
import com.bnuz.outdooractivitymanagementsystem.View.inter.IManagementAView;
public class ManagementAPresenterImpl implements IManagementAPresenter {
private IManagementAView mIManagementAView;
private IManagementAModel mIManagementAModel;
public ManagementAPresenterImpl(IManagementAView aIManagementAView) {
mIManagementAView = aIManagementAView;
mIManagementAModel = new ManagementAModelImpl();
}
@Override
public void getActivity(int ActId) {
mIManagementAModel.getById(ActId, new CallBack() {
@Override
public void onSuccess(Object response) {
mIManagementAView.response(response,IManagementAView.RESPONSE_ONE);
Looper.prepare();
mIManagementAView.showToast("活动获取成功");
Looper.loop();
}
@Override
public void onError(String t) {
mIManagementAView.response("获取活动失败", IManagementAView.RESPONSE_TWO);
Looper.prepare();
mIManagementAView.showToast(t);
Looper.loop();
}
});
}
}
|
/*
* Copyright (C), 2013-2014, 上海汽车集团股份有限公司
* FileName: UserLoginInfoVo.java
* Author: baowenzhou
* Date: 2015年08月27日 上午10:36:47
* Description: //模块目的、功能描述
* History: //修改记录
* <author> <time> <version> <desc>
* 修改人姓名 修改时间 版本号 描述
*/
package com.xjf.wemall.api.entity.user;
/**
* 用户登录表单信息<br>
* 〈功能详细描述〉
*
* @author baowenzhou
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class UserLoginInfoVo {
/** 手机 */
private String mobile;
/** 验证码 */
private String captcha;
/** 用户名 */
private String userName;
/** 密码 */
private String password;
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCaptcha() {
return captcha;
}
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
package com.pangpang6.hadoop.sort;
public interface ISegment extends Comparable<ISegment> {
}
|
package model;
import java.time.LocalDate;
public class Emprestimo {
private LocalDate dataInicial;
private LocalDate dataFinal;
private String identificacao;
private Equipamento equipamento;
private Funcionario funcionario;
public Emprestimo(LocalDate dataInicial, LocalDate dataFinal, String identificacao,
Equipamento equipamento, Funcionario funcionario){
this.dataInicial = dataInicial;
this.dataFinal = dataFinal;
this.identificacao = identificacao;
this.equipamento = equipamento;
this.funcionario = funcionario;
}
}
|
package universe;
public class Universe {
public static void main(String[] args) {
}
}
|
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Label;
import org.eclipse.wb.swt.SWTResourceManager;
public class Calculator {
private int count = 0;
protected Shell shell;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
Calculator window = new Calculator();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(844, 543);
shell.setText("Scientific Calculator");
shell.setLayout(null);
Label numberInput = new Label(shell, SWT.NONE);
numberInput.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
numberInput.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
numberInput.setAlignment(SWT.RIGHT);
numberInput.setBounds(12, 83, 798, 47);
Label layOver = new Label(shell, SWT.NONE);
layOver.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
layOver.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
layOver.setAlignment(SWT.RIGHT);
layOver.setBounds(12, 36, 798, 47);
Label memoryStatus = new Label(shell, SWT.NONE);
memoryStatus.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.NORMAL));
memoryStatus.setAlignment(SWT.CENTER);
memoryStatus.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
memoryStatus.setBounds(12, 104, 43, 26);
Button degreesCircle = new Button(shell, SWT.RADIO);
degreesCircle.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
}
});
degreesCircle.setBounds(141, 163, 87, 43);
degreesCircle.setText("Degrees");
Button radiansCircle = new Button(shell, SWT.RADIO);
radiansCircle.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
}
});
radiansCircle.setBounds(23, 161, 78, 47);
radiansCircle.setText("Radians");
radiansCircle.setSelection(true);
Button memorySubtract = new Button(shell, SWT.NONE);
memorySubtract.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
memoryStatus.setText("M");
CalculatorFunctions.memorySubtract(Double.parseDouble(numberInput.getText()));
}
});
memorySubtract.setBounds(741, 163, 69, 43);
memorySubtract.setText("M-");
Button memoryAdd = new Button(shell, SWT.NONE);
memoryAdd.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
memoryStatus.setText("M");
CalculatorFunctions.memoryAdd(Double.parseDouble(numberInput.getText()));
}
});
memoryAdd.setBounds(660, 163, 69, 43);
memoryAdd.setText("M+");
Button memoryRecall = new Button(shell, SWT.NONE);
memoryRecall.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.getMemory()));
}
});
memoryRecall.setBounds(498, 163, 69, 43);
memoryRecall.setText("MR");
Button memoryClear = new Button(shell, SWT.NONE);
memoryClear.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CalculatorFunctions.setMemory(0);
}
});
memoryClear.setBounds(417, 163, 69, 43);
memoryClear.setText("MC");
Button memoryStore = new Button(shell, SWT.NONE);
memoryStore.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.getMemory()));
}
});
memoryStore.setBounds(579, 163, 69, 43);
memoryStore.setText("MS");
Button secondRoot = new Button(shell, SWT.NONE);
secondRoot.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.secondRoot(Double.parseDouble(numberInput.getText()))));
}
});
secondRoot.setBounds(741, 219, 69, 43);
secondRoot.setText("\u221A");
Button plusMinus = new Button(shell, SWT.NONE);
plusMinus.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.plusMinus(Double.parseDouble(numberInput.getText()))));
}
});
plusMinus.setBounds(660, 219, 69, 43);
plusMinus.setText("\u00B1");
Button clear = new Button(shell, SWT.NONE);
clear.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CalculatorFunctions.setOperation("");
layOver.setText("");
numberInput.setText("");
}
});
clear.setBounds(579, 219, 69, 43);
clear.setText("C");
Button backspace = new Button(shell, SWT.NONE);
backspace.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText().substring(0,numberInput.getText().length()-1));
}
});
backspace.setBounds(417, 219, 69, 43);
backspace.setText("\u2190 ");
Button clearEntry = new Button(shell, SWT.NONE);
clearEntry.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText("");
}
});
clearEntry.setBounds(498, 219, 69, 43);
clearEntry.setText("CE");
Button eFour = new Button(shell, SWT.NONE);
eFour.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.ePower(4)));
}
});
eFour.setBounds(336, 218, 69, 43);
eFour.setText("e\u2074");
Button eThree = new Button(shell, SWT.NONE);
eThree.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.ePower(3)));
}
});
eThree.setBounds(255, 218, 69, 43);
eThree.setText("e\u00B3");
Button eTwo = new Button(shell, SWT.NONE);
eTwo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.ePower(2)));
}
});
eTwo.setBounds(174, 219, 69, 43);
eTwo.setText("e\u00B2");
Button eOne = new Button(shell, SWT.NONE);
eOne.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.ePower(1)));
}
});
eOne.setBounds(93, 219, 69, 43);
eOne.setText("e");
Button naturalLog = new Button(shell, SWT.NONE);
naturalLog.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.naturalLog(Double.parseDouble(numberInput.getText()))));
}
});
naturalLog.setBounds(12, 219, 69, 43);
naturalLog.setText("ln");
Button binary = new Button(shell, SWT.NONE);
binary.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(CalculatorFunctions.binary(Integer.parseInt(numberInput.getText())));
}
});
binary.setBounds(12, 275, 69, 43);
binary.setText("Bin");
Button sine = new Button(shell, SWT.NONE);
sine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(degreesCircle.getSelection() == true)
numberInput.setText(String.valueOf(CalculatorFunctions.sine(Double.parseDouble(numberInput.getText()),1)));
else
numberInput.setText(String.valueOf(CalculatorFunctions.sine(Double.parseDouble(numberInput.getText()),0)));
}
});
sine.setBounds(93, 275, 69, 43);
sine.setText("sin");
Button sineInverse = new Button(shell, SWT.NONE);
sineInverse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(degreesCircle.getSelection() == true)
numberInput.setText(String.valueOf(CalculatorFunctions.sineInverse(Double.parseDouble(numberInput.getText()),1)));
else
numberInput.setText(String.valueOf(CalculatorFunctions.sineInverse(Double.parseDouble(numberInput.getText()),0)));
}
});
sineInverse.setBounds(174, 276, 69, 43);
sineInverse.setText("sin\u207B\u00B9");
Button xSecond = new Button(shell, SWT.NONE);
xSecond.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.xPower(Double.parseDouble(numberInput.getText()),2)));
}
});
xSecond.setBounds(255, 276, 69, 43);
xSecond.setText("\u00D7\u00B2");
Button xFactorial = new Button(shell, SWT.NONE);
xFactorial.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.xFactorial(Double.parseDouble(numberInput.getText()))));
}
});
xFactorial.setBounds(336, 275, 69, 43);
xFactorial.setText("x!");
Button seven = new Button(shell, SWT.NONE);
seven.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText() + "7");
}
});
seven.setBounds(417, 275, 69, 43);
seven.setText("7");
Button eight = new Button(shell, SWT.NONE);
eight.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText() + "8");
}
});
eight.setBounds(498, 275, 69, 43);
eight.setText("8");
Button nine = new Button(shell, SWT.NONE);
nine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText() + "9");
}
});
nine.setBounds(579, 275, 69, 43);
nine.setText("9");
Button divide = new Button(shell, SWT.NONE);
divide.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CalculatorFunctions.setOperation("divide");
layOver.setText(numberInput.getText() + "/");
numberInput.setText("");
}
});
divide.setBounds(660, 275, 69, 43);
divide.setText("/");
Button percent = new Button(shell, SWT.NONE);
percent.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CalculatorFunctions.setOperation("percent");
layOver.setText(numberInput.getText() + "%");
numberInput.setText("");
}
});
percent.setBounds(741, 275, 69, 43);
percent.setText("%");
Button hexadecimal = new Button(shell, SWT.NONE);
hexadecimal.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(CalculatorFunctions.hexadecimal(Integer.parseInt(numberInput.getText())));
}
});
hexadecimal.setBounds(12, 331, 69, 43);
hexadecimal.setText("Hex");
Button cosine = new Button(shell, SWT.NONE);
cosine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(degreesCircle.getSelection() == true)
numberInput.setText(String.valueOf(CalculatorFunctions.cosine(Double.parseDouble(numberInput.getText()),1)));
else
numberInput.setText(String.valueOf(CalculatorFunctions.cosine(Double.parseDouble(numberInput.getText()),0)));
}
});
cosine.setBounds(93, 331, 69, 43);
cosine.setText("cos");
Button cosineInverse = new Button(shell, SWT.NONE);
cosineInverse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(degreesCircle.getSelection() == true)
numberInput.setText(String.valueOf(CalculatorFunctions.cosineInverse(Double.parseDouble(numberInput.getText()),1)));
else
numberInput.setText(String.valueOf(CalculatorFunctions.cosineInverse(Double.parseDouble(numberInput.getText()),0)));
}
});
cosineInverse.setBounds(174, 331, 69, 43);
cosineInverse.setText("cos\u207B\u00B9");
Button xThird = new Button(shell, SWT.NONE);
xThird.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.xPower(Double.parseDouble(numberInput.getText()),3)));
}
});
xThird.setBounds(255, 331, 69, 43);
xThird.setText("\u00D7\u00B3");
Button thirdRoot = new Button(shell, SWT.NONE);
thirdRoot.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.thirdRoot(Double.parseDouble(numberInput.getText()))));
}
});
thirdRoot.setBounds(336, 331, 69, 43);
thirdRoot.setText("\u221B");
Button random = new Button(shell, SWT.NONE);
random.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.random()));
}
});
random.setBounds(336, 387, 69, 43);
random.setText("rand");
Button xFourth = new Button(shell, SWT.NONE);
xFourth.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.xPower(Double.parseDouble(numberInput.getText()),4)));
}
});
xFourth.setBounds(255, 387, 69, 43);
xFourth.setText("x\u2074");
Button four = new Button(shell, SWT.NONE);
four.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText() + "4");
}
});
four.setBounds(417, 331, 69, 43);
four.setText("4");
Button five = new Button(shell, SWT.NONE);
five.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText() + "5");
}
});
five.setBounds(498, 331, 69, 43);
five.setText("5");
Button six = new Button(shell, SWT.NONE);
six.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText() + "6");
}
});
six.setBounds(579, 331, 69, 43);
six.setText("6");
Button one = new Button(shell, SWT.NONE);
one.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText() + "1");
}
});
one.setBounds(417, 387, 69, 43);
one.setText("1");
Button two = new Button(shell, SWT.NONE);
two.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText() + "2");
}
});
two.setBounds(498, 387, 69, 43);
two.setText("2");
Button three = new Button(shell, SWT.NONE);
three.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText() + "3");
}
});
three.setBounds(579, 387, 69, 43);
three.setText("3");
Button multiply = new Button(shell, SWT.NONE);
multiply.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CalculatorFunctions.setOperation("times");
layOver.setText(numberInput.getText() + "*");
numberInput.setText("");
}
});
multiply.setBounds(660, 331, 69, 43);
multiply.setText("*");
Button oneOverX = new Button(shell, SWT.NONE);
oneOverX.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.oneOverX(Double.parseDouble(numberInput.getText()))));
}
});
oneOverX.setBounds(741, 331, 69, 43);
oneOverX.setText("1/x");
Button subtract = new Button(shell, SWT.NONE);
subtract.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CalculatorFunctions.setOperation("minus");
layOver.setText(numberInput.getText() + "-");
numberInput.setText("");
}
});
subtract.setBounds(660, 387, 69, 43);
subtract.setText("-");
Button add = new Button(shell, SWT.NONE);
add.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CalculatorFunctions.setOperation("plus");
layOver.setText(numberInput.getText() + "+");
numberInput.setText("");
}
});
add.setBounds(660, 443, 69, 43);
add.setText("+");
Button decimalPoint = new Button(shell, SWT.NONE);
decimalPoint.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText()+".");
}
});
decimalPoint.setBounds(579, 443, 69, 43);
decimalPoint.setText(".");
Button equals = new Button(shell, SWT.NONE);
equals.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
double result = 0;
if(count == 1)
result = CalculatorFunctions.computation(layOver.getText().substring(0,layOver.getText().length()-3),numberInput.getText());
else
result = CalculatorFunctions.computation(layOver.getText().substring(0,layOver.getText().length()-1),numberInput.getText());
CalculatorFunctions.setOperation("");
layOver.setText("");
numberInput.setText(String.valueOf(result));
count = 0;
}
});
equals.setBounds(741, 387, 69, 99);
equals.setText("=");
Button octal = new Button(shell, SWT.NONE);
octal.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(CalculatorFunctions.octal(Integer.parseInt(numberInput.getText())));
}
});
octal.setBounds(12, 387, 69, 43);
octal.setText("Oct");
Button pi = new Button(shell, SWT.NONE);
pi.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.pi()));
}
});
pi.setBounds(12, 443, 69, 43);
pi.setText("\u03C0");
Button tangentInverse = new Button(shell, SWT.NONE);
tangentInverse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(degreesCircle.getSelection() == true)
numberInput.setText(String.valueOf(CalculatorFunctions.tangentInverse(Double.parseDouble(numberInput.getText()),1)));
else
numberInput.setText(String.valueOf(CalculatorFunctions.tangentInverse(Double.parseDouble(numberInput.getText()),0)));
}
});
tangentInverse.setBounds(174, 387, 69, 43);
tangentInverse.setText("tan\u207B\u00B9");
Button tangent = new Button(shell, SWT.NONE);
tangent.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(degreesCircle.getSelection() == true)
numberInput.setText(String.valueOf(CalculatorFunctions.tangent(Double.parseDouble(numberInput.getText()),1)));
else
numberInput.setText(String.valueOf(CalculatorFunctions.tangent(Double.parseDouble(numberInput.getText()),0)));
}
});
tangent.setBounds(93, 387, 69, 43);
tangent.setText("tan");
Button tau = new Button(shell, SWT.NONE);
tau.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.tau()));
}
});
tau.setBounds(93, 443, 69, 43);
tau.setText("\u03C4");
Button modulus = new Button(shell, SWT.NONE);
modulus.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
count = 1;
CalculatorFunctions.setOperation("modulus");
layOver.setText(numberInput.getText() + "mod");
numberInput.setText("");
}
});
modulus.setBounds(174, 443, 69, 43);
modulus.setText("Mod");
Button log = new Button(shell, SWT.NONE);
log.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.log(Double.parseDouble(numberInput.getText()))));
}
});
log.setBounds(255, 443, 69, 43);
log.setText("log");
Button tenToTheX = new Button(shell, SWT.NONE);
tenToTheX.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(String.valueOf(CalculatorFunctions.tenToTheX(Double.parseDouble(numberInput.getText()))));
}
});
tenToTheX.setBounds(336, 443, 69, 43);
tenToTheX.setText("10^x");
Button zero = new Button(shell, SWT.NONE);
zero.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
numberInput.setText(numberInput.getText() + "0");
}
});
zero.setBounds(417, 443, 150, 43);
zero.setText("0");
}
}
|
package com.codeapin.dicodingmovieapp.data.local;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
public final class DatabaseContract {
private DatabaseContract() {
}
public static class MovieColumns implements BaseColumns {
public static final Uri CONTENT_URI = new Uri.Builder().scheme("content")
.authority(AUTHORITY)
.appendPath(MovieColumns.TABLE_MOVIE)
.build();
public static final String TABLE_MOVIE = "movie";
public static final String COLUMN_NAME_OVERVIEW = "overview";
public static final String COLUMN_NAME_ORIGINAL_LANGUAGE = "originalLanguage";
public static final String COLUMN_NAME_ORIGINAL_TITLE = "originalTitle";
public static final String COLUMN_NAME_VIDEO = "video";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_GENRE_IDS = "genreIds";
public static final String COLUMN_NAME_POSTER_PATH = "posterPath";
public static final String COLUMN_NAME_BACKDROP_PATH = "backdropPath";
public static final String COLUMN_NAME_RELEASE_DATE = "releaseDate";
public static final String COLUMN_NAME_VOTE_AVERAGE = "voteAverage";
public static final String COLUMN_NAME_POPULARITY = "popularity";
public static final String COLUMN_NAME_ADULT = "adult";
public static final String COLUMN_NAME_VOTE_COUNT = "voteCount";
}
public static final String AUTHORITY = "com.codeapin.dicodingmovieapp";
public static String getColumnString(Cursor cursor, String columnName) {
return cursor.getString(cursor.getColumnIndex(columnName));
}
public static int getColumnInt(Cursor cursor, String columnName) {
return cursor.getInt(cursor.getColumnIndex(columnName));
}
public static long getColumnLong(Cursor cursor, String columnName) {
return cursor.getLong(cursor.getColumnIndex(columnName));
}
public static double getColumnDouble(Cursor cursor, String columnName) {
return cursor.getDouble(cursor.getColumnIndex(columnName));
}
}
|
/*
* Copyright (c) 2014 Anthony Benavente
*
* 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.ambenavente.origins.ui;
import com.ambenavente.origins.ui.events.MouseEventArgs;
import org.newdawn.slick.Font;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.geom.Vector2f;
/**
* Created with IntelliJ IDEA.
*
* @author Anthony Benavente
* @version 2/19/14
*/
public class Label extends Control {
private Vector2f lastMousePos;
private Vector2f currMousePos;
public Label(String title, String text) {
super(title);
setText(text);
lastMousePos = new Vector2f(0, 0);
currMousePos = new Vector2f(0, 0);
}
@Override
public void update(Input input, int delta) {
// Do stuff
currMousePos.set(input.getMouseX(), input.getMouseY());
// Set the last pos last
lastMousePos.set(input.getMouseX(), input.getMouseY());
}
@Override
public void render(Graphics g) {
Font tmpFont = g.getFont();
setWidth(tmpFont.getWidth(getText()));
setHeight(tmpFont.getHeight(getText()));
if (getFont() != null) {
g.setFont(getFont());
setWidth(getFont().getWidth(getText()));
setHeight(getFont().getHeight(getText()));
}
g.drawString(getText(), getX(), getY());
g.setFont(tmpFont);
}
}
|
package com.smxknife.java2.nio.selector;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
/**
* @author smxknife
* 2020/10/14
*/
public class _15_ServerSocketChannel_RegisterToSameSelector {
@Test
public void registerToSameSelectorTest() {
try(ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
ServerSocketChannel serverSocketChannel2 = ServerSocketChannel.open();
Selector selector1 = Selector.open()) {
serverSocketChannel.configureBlocking(false);
serverSocketChannel2.configureBlocking(false);
SelectionKey selectionKey1 = serverSocketChannel.register(selector1, SelectionKey.OP_ACCEPT);
SelectionKey selectionKey2 = serverSocketChannel2.register(selector1, SelectionKey.OP_ACCEPT);
System.out.println(selectionKey1);
System.out.println(selectionKey2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package laserlight;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public final class LaserGun extends GameObjects {
private Laser offspringLight;
private Point smerHlavne = new Point(1, 0);
private Color[] barvyLaseru = new Color[]{
Color.RED,};
private final Color barvaLaseru;
private boolean fired = false;
private Point ustiHlavne = null;
public LaserGun() {
BufferedImage cannon = null;
try {
cannon = ImageIO.read(getClass().getResource("/images/cannon.png"));
} catch (IOException ex) {
System.out.println("Chyba pri nacitani zbrane.");
}
initObjekt(cannon);
this.ustiHlavne = new Point(getImageSize().width / 2, getImageSize().height / 2);
this.barvaLaseru = barvyLaseru[new Random().nextInt(barvyLaseru.length)];
}
public void rotujLaserGun() {
if (this.fired) {
System.out.println("Delo nelze otacet, je v provozu.");
return;
}
smerHlavne = new Point(-smerHlavne.y, smerHlavne.x);
ustiHlavne = new Point(getImageSize().width / 2, getImageSize().height / 2);
BufferedImage novy = new BufferedImage(getImageObjekt().getHeight(), getImageObjekt().getWidth(), getImageObjekt().getType());
int radekT, sloupecT;
for (int radek = 0; radek < getImageObjekt().getHeight(); radek++) {
for (int sloupec = 0; sloupec < getImageObjekt().getWidth(); sloupec++) {
radekT = sloupec;
sloupecT = -radek + novy.getWidth() - 1;
novy.setRGB(sloupecT, radekT, getImageObjekt().getRGB(sloupec, radek));
}
}
super.initObjekt(novy);
}
private Point generujSmerHlavne(int imgW, int imgH) {
return new Point(
getSmerHlavne().x * imgW / 2 + imgW / 2,
getSmerHlavne().y * imgH / 2 + imgH / 2
);
}
public Point getPointOfStartLaser() {
return this.ustiHlavne;
}
public Color getBarvaLaseru() {
return this.barvaLaseru;
}
public Point getSmerHlavne() {
return new Point(this.smerHlavne.x, this.smerHlavne.y);
}
@Override
protected void initObjekt(BufferedImage buffImg) {
super.initObjekt(buffImg);
}
public void fireSwitch() {
this.fired = !this.fired;
if (this.fired) {
this.offspringLight = Laser.addLaser(getBarvaLaseru(),
genLocations(getPointOfStartLaser(),
new Point(getLocation().x * getImageSize().width,
getLocation().y * getImageSize().height)),
getLocation(),
getSmerHlavne(),
hashCode(),
getFather());
} else {
this.offspringLight.dispose();
}
}
public boolean isFired() {
return this.fired;
}
@Override
public Point transformujVektor(Point dir) {
return null;
}
private Point genLocations(Point a, Point b) {
return new Point(a.x + b.x, a.y + b.y);
}
}
|
package com.linda.framework.rpc.service;
import com.linda.framework.rpc.*;
import com.linda.framework.rpc.filter.RpcFilter;
import com.linda.framework.rpc.filter.RpcFilterChain;
import com.linda.framework.rpc.monitor.StatMonitor;
import com.linda.framework.rpc.net.RpcSender;
import com.linda.framework.rpc.server.AbstractRpcServer;
import com.linda.framework.rpc.server.ConcurrentRpcServer;
import com.linda.framework.rpc.utils.RpcUtils;
import org.apache.log4j.Logger;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class RpcServerTest {
private static Logger logger = Logger.getLogger(RpcServerTest.class);
private static class ClientFilter implements RpcFilter {
private HashSet<String> hosts = new HashSet<String>();
@Override
public void doFilter(RpcObject rpc, RemoteCall call, RpcSender sender,
RpcFilterChain chain) {
String host = rpc.getHost() + ":" + rpc.getPort();
hosts.add(host);
chain.nextFilter(rpc, call, sender);
}
}
private static class StatThread extends Thread {
public StatThread(StatMonitor monitor) {
this.monitor = monitor;
}
private StatMonitor monitor;
@Override
public void run() {
while (true) {
Map<Long, Long> stat = monitor.getRpcStat();
Set<Long> minutes = stat.keySet();
for (long minute : minutes) {
long cc = stat.get(minute);
long tps = cc / 60;
logger.info("time:" + new Date(minute) + " count:" + cc + " tps:" + tps);
}
try {
Thread.currentThread().sleep(RpcUtils.MINUTE);
} catch (InterruptedException e) {
break;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
long sleep = 300000;
String host = "0.0.0.0";
int port = 4332;
int threadCount = 20;
if (args != null) {
for (String arg : args) {
if (arg.startsWith("-h")) {
host = arg.substring(2);
} else if (arg.startsWith("-p")) {
port = Integer.parseInt(arg.substring(2));
} else if (arg.startsWith("-s")) {
sleep = Long.parseLong(arg.substring(2));
} else if (arg.startsWith("-th")) {
threadCount = Integer.parseInt(arg.substring(3));
}
}
}
AbstractRpcServer server = new ConcurrentRpcServer();
//server.setAcceptor(new RpcOioAcceptor());
server.setHost(host);
server.setPort(port);
server.setExecutorThreadCount(threadCount);
HelloRpcService helloRpcServiceImpl = new HelloRpcServiceImpl();
server.register(HelloRpcService.class, helloRpcServiceImpl);
HelloRpcTestServiceImpl obj2 = new HelloRpcTestServiceImpl();
server.register(HelloRpcTestService.class, obj2);
LoginRpcService loginService = new LoginRpcServiceImpl();
server.register(LoginRpcService.class, loginService);
//server.addRpcFilter(new MyTestRpcFilter());
//server.addRpcFilter(new RpcLoginCheckFilter());
ClientFilter clientFilter = new ClientFilter();
server.addRpcFilter(clientFilter);
StatisticsFilter statisticsFilter = new StatisticsFilter();
server.addRpcFilter(statisticsFilter);
StatThread thread = new StatThread(server.getStatMonitor());
thread.setDaemon(true);
server.startService();
thread.start();
statisticsFilter.startService();
logger.info("service started");
Thread.currentThread().sleep(sleep);
statisticsFilter.stopService();
server.stopService();
//logger.info("clients:"+clientFilter.hosts);
logger.info("clientsSize:" + clientFilter.hosts.size() + " time:" + statisticsFilter.getTime() + " calls:" +
statisticsFilter.getCall() + " tps:" + statisticsFilter.getTps());
System.exit(0);
}
}
|
package com.jim.multipos.utils.rxevents.product_events;
import com.jim.multipos.data.db.model.ProductClass;
import com.jim.multipos.data.db.model.products.Category;
/**
* Created by Sirojiddin on 27.02.2018.
*/
public class ProductClassEvent {
private ProductClass productClass;
private int type;
public ProductClassEvent(ProductClass productClass, int type) {
this.productClass = productClass;
this.type = type;
}
public ProductClass getProductClass() {
return productClass;
}
public void setProductClass(ProductClass productClass) {
this.productClass = productClass;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
|
import java.awt.*;
import javax.swing.*;
public class Line_Basic extends JPanel{
/**
* @param args
*/
public static void main(String[] args) {
JFrame theGUI = new JFrame();
theGUI.setTitle("Here's some lines");
theGUI.setSize(100, 100);
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theGUI.getContentPane().add(new Line_Basic());
theGUI.setVisible(true);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(20, 15, 90, 15);
g.drawString("<", 15, 20);
g.drawString(">", 90, 20);
g.drawLine(20, 30, 90, 30);
g.drawString(">", 15, 35);
g.drawString("<", 90, 35);
}
}
|
package fr.lteconsulting.formations;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet( "/raz" )
@SuppressWarnings( "serial" )
public class RazServlet extends HttpServlet
{
@Override
protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
{
req.getSession().setAttribute( Constantes.SESSION_COMPTEUR_KEY, 0 );
resp.sendRedirect( "compteur" );
}
}
|
package com.eluniversal.test.fragments;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.eluniversal.test.activities.DetailNewsActivity;
import com.eluniversal.test.activities.R;
import com.eluniversal.test.core.catalogs.Entity;
import com.eluniversal.test.core.catalogs.Function;
import com.eluniversal.test.core.catalogs.PetitionParams;
import com.eluniversal.test.core.entities.News;
import com.eluniversal.test.core.petitions.AsyncPetition;
import com.eluniversal.test.core.petitions.Petition;
public class DetailNewsFragment extends Fragment
{
private ImageView imageView;
private TextView titleNews;
private TextView subTitleNews;
private TextView pubDate;
private TextView body;
private TextView author;
private TextView link;
private int indexSelected = -1;
public static final String INDEX_SELECTED = "INDEX_SELECTED";
private News selected;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null)
{
if (extras.containsKey(INDEX_SELECTED))
indexSelected = (int)extras.get(INDEX_SELECTED);
selected = ((DetailNewsActivity)getActivity()).getNewsList().get(indexSelected);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_detail_news, parent, false);
imageView = (ImageView)view.findViewById(R.id.thumbnail_news);
titleNews = (TextView)view.findViewById(R.id.title_news);
subTitleNews = (TextView)view.findViewById(R.id.subtitle_news);
pubDate = (TextView)view.findViewById(R.id.pudate_news);
body = (TextView)view.findViewById(R.id.body_news);
author = (TextView)view.findViewById(R.id.author_news);
link = (TextView)view.findViewById(R.id.link_news);
showSelected(selected);
return view;
}
private void showSelected(News newsSelected)
{
selected = newsSelected;
if (selected.getImage() != null)
{
if (!selected.getImage().isEmpty())
{
Petition p = new Petition(Entity.image, Function.detail);
p.setPetitionParam(PetitionParams.imageUri, selected.getImage());
ImageNews imageNews = new ImageNews();
imageNews.execute(p);
}
}
body.setText(selected.getBody());
titleNews.setText(selected.getTitle());
subTitleNews.setText(selected.getSubTitle());
if (selected.getAuthor() != null)
author.setText(getResources().getString(R.string.author_label) + ": " + selected.getAuthor());
if (selected.getLink() != null)
{
link.setText(selected.getLink());
link.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(selected.getLink()));
startActivity(browserIntent);
}
});
}
String date = new String();
if (selected.getPubDate() != null)
date = selected.getPubDate();
if (selected.getPubTime() != null)
date += " " + selected.getPubTime();
pubDate.setText(date);
setTitleWindows();
}
private void setTitleWindows()
{
if (selected.getSection() != null)
{
if (!selected.getSection().isEmpty())
{
getActivity().setTitle(selected.getSection());
return;
}
}
}
public String getMessageShare()
{
if (selected != null)
{
if (selected.getCaption() != null)
return selected.getCaption();
else if (selected.getTitle() != null)
return selected.getTitle();
else
return selected.getSubTitle();
}
return new String();
}
public String getLink()
{
if (selected != null)
{
if (selected.getLink() != null)
return selected.getLink();
}
return null;
}
private class ImageNews extends AsyncPetition
{
@Override
public void onPostExecute(Object object)
{
super.onPostExecute(object);
if (object != null)
{
if (object instanceof Bitmap)
{
Bitmap bmp = (Bitmap)object;
imageView.setImageBitmap(bmp);
}
}
}
}
}
|
package digitalInnovation.javaBasico;
import java.util.Calendar;
public class Aula_02_Calendar {
public static void main(String[] args) {
//instanciando um objeto do tipo Calendar
Calendar agora = Calendar.getInstance();
System.out.println(agora);
System.out.println("A data de hoje: " + agora.getTime());
agora.add(Calendar.DATE, -15);
System.out.println("15 dias a tras: " + agora.getTime());
agora.add(Calendar.MONTH, 4);
System.out.println("4 meses depois: " + agora.getTime());
agora.add(Calendar.YEAR, 2);
System.out.println("2 anos depois: " + agora.getTime());
//Calendar com impressao formatada
Calendar hoje = Calendar.getInstance();
System.out.printf("%tc\n", hoje); //data completa detalhada
System.out.printf("%tF\n", hoje); //aaa-mm-dd
System.out.printf("%tD\n", hoje); //mm/dd/aa
System.out.printf("%tr\n", hoje); //hh:mm:ss AM/PM
System.out.printf("%tT\n", hoje); //HH:mm:ss (24hrs)
}
}
|
package com.angrykings;
import org.andengine.entity.scene.background.AutoParallaxBackground;
/**
* Created by Shivan on 24.01.14.
*/
public class AngryParallaxBackground extends AutoParallaxBackground {
public AngryParallaxBackground(float pRed, float pGreen, float pBlue, float pParallaxChangePerSecond) {
super(pRed, pGreen, pBlue, pParallaxChangePerSecond);
}
public float getParallaxValue() {
return this.mParallaxValue;
}
}
|
package de.madjosz.adventofcode.y2020;
import static org.junit.jupiter.api.Assertions.assertEquals;
import de.madjosz.adventofcode.AdventOfCodeUtil;
import java.util.List;
import org.junit.jupiter.api.Test;
class Day14Test {
@Test
void day14() {
List<String> lines = AdventOfCodeUtil.readLines(2020, 14);
Day14 day14 = new Day14(lines);
assertEquals(7611244640053L, day14.a1());
assertEquals(3705162613854L, day14.a2());
}
@Test
void day14_exampleInput() {
List<String> lines = AdventOfCodeUtil.readLines(2020, 14, "test1");
Day14 day14 = new Day14(lines);
assertEquals(165, day14.a1());
lines = AdventOfCodeUtil.readLines(2020, 14, "test2");
day14 = new Day14(lines);
assertEquals(208, day14.a2());
}
}
|
package com.example.amtis2;
public class Amtis {
private int id;
private String name;
private String address;
private String destination;
private String date;
public Amtis(int id, String name, String address, String destination, String date) {
this.id = id;
this.name = name;
this.address = address;
this.destination = destination;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
|
package ars.ramsey.interviewhelper.model;
import io.reactivex.Observable;
/**
* Created by Ramsey on 2017/5/9.
*/
public interface ArticalsSource {
Observable getTasks(String id,int limit,int offset);
}
|
package sample.artik.cloud.healthbook;
/**
* Constants for the Sample.
*
* @author Maneesh Sahu
*/
public class Constants {
public static final String CLIENT_ID = "4ac0a3bd4f7c4ecd8542bd6905197acb";
public static final String AUTHORIZATION_IMPLICIT_SERVER_URL = "https://accounts.artik.cloud/authorize";
public static final String REDIRECT_URL = "artikcloud://localhost";
public static final String DT_OPEN_WEATHER_MAP = "dt9ad7ecfd34324765a9b12ef98a51b29e";
public static final String DT_PEDOMETER = "dta8ad42083f33441b8677e5b36f049a4b";
public static final String[] DEVICE_TYPE_NAMES = { "OPEN_WEATHER_MAP", "PEDOMETER" };
public static final String[] DEVICE_TYPES = { DT_OPEN_WEATHER_MAP, DT_PEDOMETER };
private Constants() {
}
}
|
package Presentación;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import LN.Tablero;
import MD_Instrucción.Disparo;
import MD_Instrucción.Instrucción;
import MD_Instrucción.Movimiento;
import MD_Instrucción.Operación;
import MD_Tablero.Arquero;
import MD_Tablero.Bárbaro;
import MD_Tablero.Caballero;
import MD_Tablero.Casilla;
import MD_Tablero.Catapulta;
import MD_Tablero.Colina;
import MD_Tablero.Copa;
import MD_Tablero.Curación;
import MD_Tablero.Ficha;
import MD_Tablero.Guerrero;
import MD_Tablero.Lancero;
import Utilidades.Dirección;
import Utilidades.Facción;
public class TableroGrafico extends JFrame {
private JPanel contentPane;
private int turno;
private int maniobra;
private JButton btnMenu;
private final JButton btnDisparar= new JButton("");
private final JButton Mover= new JButton("");
private final JButton btnEsperar= new JButton("");
private final JButton btnCancelar= new JButton("");
private final JButton Listo= new JButton("");
/**/ private boolean introducirOperacionEnCurso= false;
private ActionListener al;
private List<Tablero> tableros;
// /**/ private Tablero[] tablerosRecibidos; //Lo ideal sería que se reutilizase la lista tableros.
private int tabI;
private JLabel lblNewLabel_3;
private JLabel lblNewLabel_4;
private JLabel Maniobra;
private JLabel Operaciones;
private Tablero tab;
private Tablero tabGuardado;
private String nombre;
private String oponente;
private final JButton[] casillas = new JButton[45];
private boolean azul;
private boolean acabado=false;
JLabel Turno;
private JTextArea txtCasilla;
private JTextArea txtFichaDef;
private JTextArea txtFichaAt;
private boolean catA=true,catR=true;
private Integer movsF=0,movsC=0,movsB=0,movsG=0,movsL =0;
private Facción faccion;
private Instrucción<Operación> inst;
private Socket s;
private ObjectOutputStream out;
private ObjectInputStream in;
/**
* Create the frame.
*/
//Este es el constructor, es un monstruo pero basicamente crea toda la interfaz principal y le añade a todos los botones los eventos necesarios para que todo funcione
// para siguiente y anterior una vez se ha pasado turno avanza o retorcede en la visualizacion de los tableros resultado
// para confirmar acaba el turno mandando las 6 operaciones al servidor y establece una comunicacion con el servidor para ver si se ha terminado la partida o si esta sigue.
// mover, disparar y esperar se espera lo que hacen, ademas está comentado mas abajo.
// menu vuelve al menu principal pero sin cerrar la interfaz.
public TableroGrafico(final ClienteGUI menu, Socket s, ObjectInputStream inPasado, ObjectOutputStream outPasado) {
setIconImage(Toolkit.getDefaultToolkit().getImage("Recursos\\iconoRefachero2.png"));
this.s = s;
this.in = inPasado;
this.out = outPasado;
setTitle("Divasonian Crusaders");
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
salir();
}
});
this.turno=0;
this.maniobra = 0;
this.s=s;
this.tableros = new ArrayList<Tablero>();
// /**/ this.tablerosRecibidos = new Tablero[7];
this.inst = new Instrucción();
tab = new Tablero();
tabGuardado = (Tablero) tab.clone();
this.tableros.add(tab);
setResizable(false);
final TableroGrafico tablero = this;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1080, 751);
contentPane = new JPanel();
contentPane.setBackground(new Color(240, 230, 140));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setIcon(new ImageIcon("Recursos\\LogoDivasonian.png"));
lblNewLabel.setBounds(60, 28, 618, 127);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setIcon(new ImageIcon("Recursos\\LogoBLS.png"));
lblNewLabel_1.setBounds(756, 21, 292, 156);
contentPane.add(lblNewLabel_1);
JPanel panel = new JPanel();
panel.setBounds(30, 236, 702, 390);
contentPane.add(panel);
panel.setLayout(new GridLayout(5, 9, 0, 0));
final JButton cas0 = new JButton("");
cas0.setBackground(new Color(245, 245, 220));
panel.add(cas0);
JButton cas1 = new JButton("");
cas1.setBackground(new Color(245, 245, 220));
panel.add(cas1);
JButton cas2 = new JButton("");
cas2.setBackground(new Color(245, 245, 220));
panel.add(cas2);
JButton cas3 = new JButton("");
cas3.setBackground(new Color(245, 245, 220));
panel.add(cas3);
JButton cas4 = new JButton("");
cas4.setBackground(new Color(245, 245, 220));
panel.add(cas4);
JButton cas5 = new JButton("");
cas5.setBackground(new Color(245, 245, 220));
panel.add(cas5);
JButton cas6 = new JButton("");
cas6.setBackground(new Color(245, 245, 220));
panel.add(cas6);
JButton cas7 = new JButton("");
cas7.setBackground(new Color(245, 245, 220));
panel.add(cas7);
final JButton cas8 = new JButton("");
cas8.setBackground(new Color(245, 245, 220));
panel.add(cas8);
final JButton cas9 = new JButton("");
cas9.setBackground(new Color(245, 245, 220));
panel.add(cas9);
JButton cas10 = new JButton("");
cas10.setBackground(new Color(245, 245, 220));
panel.add(cas10);
JButton cas11 = new JButton("");
cas11.setBackground(new Color(245, 245, 220));
panel.add(cas11);
JButton cas12 = new JButton("");
cas12.setBackground(new Color(245, 245, 220));
panel.add(cas12);
JButton cas13 = new JButton("");
cas13.setBackground(new Color(245, 245, 220));
panel.add(cas13);
JButton cas14 = new JButton("");
cas14.setBackground(new Color(245, 245, 220));
panel.add(cas14);
JButton cas15 = new JButton("");
cas15.setBackground(new Color(245, 245, 220));
panel.add(cas15);
JButton cas16 = new JButton("");
cas16.setBackground(new Color(245, 245, 220));
panel.add(cas16);
final JButton cas17 = new JButton("");
cas17.setBackground(new Color(245, 245, 220));
panel.add(cas17);
final JButton cas18 = new JButton("");
cas18.setBackground(new Color(245, 245, 220));
panel.add(cas18);
final JButton cas19 = new JButton("");
cas19.setBackground(new Color(245, 245, 220));
panel.add(cas19);
JButton cas20 = new JButton("");
cas20.setBackground(new Color(245, 245, 220));
panel.add(cas20);
JButton cas21 = new JButton("");
cas21.setBackground(new Color(245, 245, 220));
panel.add(cas21);
final JButton cas22 = new JButton("");
cas22.setBackground(new Color(245, 245, 220));
panel.add(cas22);
JButton cas23 = new JButton("");
cas23.setBackground(new Color(245, 245, 220));
panel.add(cas23);
JButton cas24 = new JButton("");
cas24.setBackground(new Color(245, 245, 220));
panel.add(cas24);
final JButton cas25 = new JButton("");
cas25.setBackground(new Color(245, 245, 220));
panel.add(cas25);
final JButton cas26 = new JButton("");
cas26.setBackground(new Color(245, 245, 220));
panel.add(cas26);
final JButton cas27 = new JButton("");
cas27.setBackground(new Color(245, 245, 220));
panel.add(cas27);
JButton cas28 = new JButton("");
cas28.setBackground(new Color(245, 245, 220));
panel.add(cas28);
JButton cas29 = new JButton("");
cas29.setBackground(new Color(245, 245, 220));
panel.add(cas29);
JButton cas30 = new JButton("");
cas30.setBackground(new Color(245, 245, 220));
panel.add(cas30);
JButton cas31 = new JButton("");
cas31.setBackground(new Color(245, 245, 220));
panel.add(cas31);
JButton cas32 = new JButton("");
cas32.setBackground(new Color(245, 245, 220));
panel.add(cas32);
JButton cas33 = new JButton("");
cas33.setBackground(new Color(245, 245, 220));
panel.add(cas33);
JButton cas34 = new JButton("");
cas34.setBackground(new Color(245, 245, 220));
panel.add(cas34);
final JButton cas35 = new JButton("");
cas35.setBackground(new Color(245, 245, 220));
panel.add(cas35);
final JButton cas36 = new JButton("");
cas36.setBackground(new Color(245, 245, 220));
panel.add(cas36);
JButton cas37 = new JButton("");
cas37.setBackground(new Color(245, 245, 220));
panel.add(cas37);
JButton cas38 = new JButton("");
cas38.setBackground(new Color(245, 245, 220));
panel.add(cas38);
JButton cas39 = new JButton("");
cas39.setBackground(new Color(245, 245, 220));
panel.add(cas39);
JButton cas40 = new JButton("");
cas40.setBackground(new Color(245, 245, 220));
panel.add(cas40);
JButton cas41 = new JButton("");
cas41.setBackground(new Color(245, 245, 220));
panel.add(cas41);
JButton cas42 = new JButton("");
cas42.setBackground(new Color(245, 245, 220));
panel.add(cas42);
JButton cas43 = new JButton("");
cas43.setBackground(new Color(245, 245, 220));
panel.add(cas43);
final JButton cas44 = new JButton("");
cas44.setBackground(new Color(245, 245, 220));
panel.add(cas44);
this.casillas[0] = cas0;
this.casillas[1] = cas1;
this.casillas[2] = cas2;
this.casillas[3] = cas3;
this.casillas[4] = cas4;
this.casillas[5] = cas5;
this.casillas[6] = cas6;
this.casillas[7] = cas7;
this.casillas[8] = cas8;
this.casillas[9] = cas9;
this.casillas[10] = cas10;
this.casillas[11] = cas11;
this.casillas[12] = cas12;
this.casillas[13] = cas13;
this.casillas[14] = cas14;
this.casillas[15] = cas15;
this.casillas[16] = cas16;
this.casillas[17] = cas17;
this.casillas[18] = cas18;
this.casillas[19] = cas19;
this.casillas[20] = cas20;
this.casillas[21] = cas21;
this.casillas[22] = cas22;
this.casillas[23] = cas23;
this.casillas[24] = cas24;
this.casillas[25] = cas25;
this.casillas[26] = cas26;
this.casillas[27] = cas27;
this.casillas[28] = cas28;
this.casillas[29] = cas29;
this.casillas[30] = cas30;
this.casillas[31] = cas31;
this.casillas[32] = cas32;
this.casillas[33] = cas33;
this.casillas[34] = cas34;
this.casillas[35] = cas35;
this.casillas[36] = cas36;
this.casillas[37] = cas37;
this.casillas[38] = cas38;
this.casillas[39] = cas39;
this.casillas[40] = cas40;
this.casillas[41] = cas41;
this.casillas[42] = cas42;
this.casillas[43] = cas43;
this.casillas[44] = cas44;
//-------------------------------------- MÉTODO Pintar() ---------------
this.pintar(tab);
//-------------------------------------- AQUÍ TERMINA ------------------
final JButton btnAnteriorMovimiento = new JButton("");
final JButton btnSiguienteMovimiento = new JButton("");
btnAnteriorMovimiento.setEnabled(false);
btnSiguienteMovimiento.setEnabled(false);
btnMenu = new JButton("");
btnMenu.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
btnMenu.setIcon(new ImageIcon("Recursos\\Menu2.png"));
}
@Override
public void mouseExited(MouseEvent e) {
btnMenu.setIcon(new ImageIcon("Recursos\\Menu.png"));
}
@Override
public void mouseClicked(MouseEvent e) {
// ClienteGUI frame = new ClienteGUI(false, tablero);
setVisible(false);
// frame.setVisible(true);
/**/ menu.setVisible(true);
}
});
btnMenu.setBackground(new Color(240, 230, 140));
btnMenu.setIcon(new ImageIcon("Recursos\\Menu.png"));
btnMenu.setBorder(null);
btnMenu.setBounds(35, 647, 179, 47);
contentPane.add(btnMenu);
Turno = new JLabel("Turno: "+this.turno);
Turno.setFont(new Font("Consolas", Font.PLAIN, 14));
Turno.setBounds(231, 651, 119, 29);
contentPane.add(Turno);
JSeparator separator = new JSeparator();
separator.setOrientation(SwingConstants.VERTICAL);
separator.setBounds(751, 204, 9, 490);
contentPane.add(separator);
lblNewLabel_3 = new JLabel("");
lblNewLabel_3.setFont(new Font("Consolas", Font.PLAIN, 15));
lblNewLabel_3.setBounds(40, 196, 287, 25);
contentPane.add(lblNewLabel_3);
lblNewLabel_4 = new JLabel("");
lblNewLabel_4.setFont(new Font("Consolas", Font.PLAIN, 15));
lblNewLabel_4.setBounds(337, 196, 292, 25);
contentPane.add(lblNewLabel_4);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(770, 478, 278, 14);
contentPane.add(separator_1);
JLabel lb_Casilla = new JLabel("Casilla:");
lb_Casilla.setFont(new Font("Consolas", Font.PLAIN, 12));
lb_Casilla.setBounds(769, 516, 77, 20);
contentPane.add(lb_Casilla);
JLabel lb_Info = new JLabel("Informaci\u00F3n:");
lb_Info.setFont(new Font("Consolas", Font.PLAIN, 12));
lb_Info.setBounds(770, 489, 89, 20);
contentPane.add(lb_Info);
JLabel lb_Ficha = new JLabel("Ficha:");
lb_Ficha.setFont(new Font("Consolas", Font.PLAIN, 12));
lb_Ficha.setBounds(770, 612, 46, 14);
contentPane.add(lb_Ficha);
txtCasilla = new JTextArea();
txtCasilla.setFont(new Font("Consolas", Font.PLAIN, 11));
txtCasilla.setEditable(false);
txtCasilla.setBounds(832, 514, 216, 82);
contentPane.add(txtCasilla);
txtFichaDef = new JTextArea();
txtFichaDef.setFont(new Font("Consolas", Font.PLAIN, 11));
txtFichaDef.setBounds(832, 609, 135, 71);
contentPane.add(txtFichaDef);
Mover.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
/**/ introducirOperacionEnCurso = true;
moverClick();
}
});
Mover.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
Mover.setIcon(new ImageIcon("Recursos\\MoverS.png"));
}
@Override
public void mouseExited(MouseEvent e) {
Mover.setIcon(new ImageIcon("Recursos\\Mover.png"));
}
});
Mover.setBackground(new Color(240, 230, 140));
Mover.setIcon(new ImageIcon("Recursos\\Mover.png"));
Mover.setBorder(null);
Mover.setBounds(823, 206, 179, 47);
contentPane.add(Mover);
btnDisparar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
/**/ introducirOperacionEnCurso = true;
boolean catVal = true;
final List<Integer> catapultas = tab.catapultasQuePuedesDisparar(faccion);
if(catapultas.size()>0) {
if(catapultas.size()==2) {
if(((catapultas.get(0)==20||catapultas.get(1)==20)&&!catA)&&((catapultas.get(0)==24||catapultas.get(1)==24)&&!catR)) {
catVal=false;
JOptionPane.showMessageDialog(null, "Ninguna de sus fichas están en una catapulta Válida", "Atención", JOptionPane.WARNING_MESSAGE);
}
if((catapultas.get(0)==20||catapultas.get(1)==20) && !catA) {
casillas[20].setEnabled(false);
catapultas.remove(new Integer(20));
}else if((catapultas.get(0)==24||catapultas.get(1)==24) && !catR) {
casillas[24].setEnabled(false);
catapultas.remove(new Integer(24));
}
}else if(catapultas.size()==1){
if(catapultas.get(0)==20&&!catA) {
catVal=false;
JOptionPane.showMessageDialog(null, "Ninguna de sus fichas están en una catapulta Válida", "Atención", JOptionPane.WARNING_MESSAGE);
}else if(catapultas.get(0)==24&&!catR){
catVal=false;
JOptionPane.showMessageDialog(null, "Ninguna de sus fichas están en una catapulta Válida", "Atención", JOptionPane.WARNING_MESSAGE);
}
}
if(catVal) {
bloquearCasillasDisparo(false,catapultas);
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
bloquearCasillasDisparo(true,catapultas);
}
});
}
}else {
JOptionPane.showMessageDialog(null, "Ninguna de sus fichas están en una catapulta", "Atención", JOptionPane.WARNING_MESSAGE);
}
}
});
btnDisparar.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
btnDisparar.setIcon(new ImageIcon("Recursos\\DispararS.png"));
}
@Override
public void mouseExited(MouseEvent e) {
btnDisparar.setIcon(new ImageIcon("Recursos\\Disparar.png"));
}
});
btnDisparar.setBackground(new Color(240, 230, 140));
btnDisparar.setIcon(new ImageIcon("Recursos\\Disparar.png"));
btnDisparar.setBounds(822, 264, 179, 47);
btnDisparar.setBorder(null);
contentPane.add(btnDisparar);
btnEsperar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
inst.add(null);
Tablero tab2 = tab;
tableros.add(tab2);
Operaciones.setText("Ops.: "+inst.size()+"/6");
if(inst.size()==6) {
btnDisparar.setEnabled(false);
btnEsperar.setEnabled(false);
Mover.setEnabled(false);
}
}
});
btnEsperar.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
btnEsperar.setIcon(new ImageIcon("Recursos\\EsperarS.png"));
}
@Override
public void mouseExited(MouseEvent e) {
btnEsperar.setIcon(new ImageIcon("Recursos\\Esperar.png"));
}
});
btnEsperar.setIcon(new ImageIcon("Recursos\\Esperar.png"));
btnEsperar.setBackground(new Color(240, 230, 140));
btnEsperar.setBorder(null);
btnEsperar.setBounds(822, 322, 179, 47);
contentPane.add(btnEsperar);
this.agregarFuncionalidadOriginalBtnCancelar();
btnCancelar.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
btnCancelar.setIcon(new ImageIcon("Recursos\\DeshacerS.png"));
}
@Override
public void mouseExited(MouseEvent e) {
btnCancelar.setIcon(new ImageIcon("Recursos\\Deshacer.png"));
}
});
btnCancelar.setBackground(new Color(240, 230, 140));
btnCancelar.setIcon(new ImageIcon("Recursos\\Deshacer.png"));
btnCancelar.setBounds(822, 380, 179, 47);
btnCancelar.setBorder(null);
contentPane.add(btnCancelar);
Listo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
boolean hacer = true;
if(inst.size()!=6) {
int resp = JOptionPane.showConfirmDialog(null, "Aún no ha realizado todas sus operaciones, ¿Está seguro?", "Atención", JOptionPane.YES_NO_OPTION);
if(resp == JOptionPane.YES_OPTION) {
for(int i = inst.size()-1; i<6;i++) {
inst.add(null);
tableros.add((Tablero)tab.clone());
}
}else {
hacer = false;
}
}
if(hacer) {
try {
out.writeBytes("OK-Todo bien bro\r\n");
out.flush();
String resultado = in.readLine();
String[] resultados = resultado.split("-");
if(resultados[0].equals("SURR")) {
acabado=true;
menu.limpiarTablero();
Victoria vic = new Victoria(nombre,menu,tablero);
vic.setVisible(true);
setVisible(false);
//HABRÁ QUE MANDAR UN MENSAJE DE VICTORIA O ALGO SIMILAR
}else {
maniobra=0;
Instrucción inst2 = (Instrucción)inst.clone();
out.writeObject(inst2);
out.flush();
System.out.println(inst.toString());
inst.clear();
/**/ tableros = (ArrayList<Tablero>) in.readObject();
tabI = 0;
acabado = (Boolean)in.readObject();
tab = tableros.get(0);
Operaciones.setText("Ops.:" + inst.size() + "/6");
limpiarActions();
pintar(tab);
btnSiguienteMovimiento.setEnabled(true);
resetearMovs();
casillasMenu(false);
resetearCatapultas();
System.out.println("nuevo turno -------------------");
}
}catch(IOException ex) {
JOptionPane.showMessageDialog(null, "Error inesperado con el servidor.", "Advertencia", JOptionPane.WARNING_MESSAGE);
ex.printStackTrace();
menu.restaurarMenu();
menu.setVisible(true);
setVisible(false);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, "Error inesperado con el servidor.", "Advertencia", JOptionPane.WARNING_MESSAGE);
e.printStackTrace();
menu.restaurarMenu();
menu.setVisible(true);
setVisible(false);
}
}
}
});
Listo.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
Listo.setIcon(new ImageIcon("Recursos\\ConfirmarS.png")); //ATENCIÓN, ESTO DEBERÍA SER ListoS
}
@Override
public void mouseExited(MouseEvent e) {
Listo.setIcon(new ImageIcon("Recursos\\Confirmar.png")); //ATENCIÓN, ESTO DEBERÍA SER Listo
}
});
Listo.setIcon(new ImageIcon("Recursos\\Confirmar.png")); //ATENCIÓN, ESTO DEBERÍA SER Listo
Listo.setBackground(new Color(240, 230, 140));
Listo.setBounds(902, 438, 100, 29);
Listo.setBorder(null);
contentPane.add(Listo);
Operaciones = new JLabel("Ops.: "+this.inst.size()+"/6");
Operaciones.setFont(new Font("Consolas", Font.PLAIN, 13));
Operaciones.setBounds(825, 438, 77, 29);
contentPane.add(Operaciones);
btnSiguienteMovimiento.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(tabI<7) {
// Tablero actual = tableros.get(tabI+1);
/**/ tab = (Tablero)tableros.get(tabI+1).clone();
tabGuardado = (Tablero)tableros.get(tabI+1).clone();
if(tabI==0) {
btnAnteriorMovimiento.setEnabled(true);
}
limpiarActions();
pintar(/*actual*/tab);
tabI++;
if(tabI==7) {
turno++;
Turno.setText("Turno: "+turno);
maniobra=0;
Maniobra.setText("Maniobra: "+maniobra);
}
else {
maniobra++;
Maniobra.setText("Maniobra: "+maniobra);
}
}
else if(tabI==7) {
int resp = JOptionPane.showConfirmDialog(null, "¿Desea introducir la nueva instrucción?", "Continuar", JOptionPane.YES_NO_OPTION);
if(resp == JOptionPane.YES_OPTION) {
if(acabado) {
menu.limpiarTablero();
Tablero tabVic = tableros.get(tableros.size()-1);
Facción faccionGanadora = tabVic.getGanador();
if(faccionGanadora == faccion) {
Victoria vic = new Victoria(nombre,menu,tablero);
vic.setVisible(true);
setVisible(false);
}else if(faccionGanadora != Facción.Ambos) {
Derrota der = new Derrota(nombre,menu,tablero);
der.setVisible(true);
setVisible(false);
}else {
Empate der = new Empate(nombre,menu,tablero);
der.setVisible(true);
setVisible(false);
}
}else {
btnSiguienteMovimiento.setEnabled(false);
btnAnteriorMovimiento.setEnabled(false);
casillasMenu(true);
// tab = (Tablero)actual.clone();
}
}
}
}
});
btnSiguienteMovimiento.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
btnSiguienteMovimiento.setIcon(new ImageIcon("Recursos\\SiguienteS.png"));
}
@Override
public void mouseExited(MouseEvent e) {
btnSiguienteMovimiento.setIcon(new ImageIcon("Recursos\\Siguiente.png"));
}
});
btnSiguienteMovimiento.setBackground(new Color(240, 230, 140));
btnSiguienteMovimiento.setIcon(new ImageIcon("Recursos\\Siguiente.png"));
btnSiguienteMovimiento.setBorder(null);
btnSiguienteMovimiento.setBounds(555, 647, 179, 47);
contentPane.add(btnSiguienteMovimiento);
Maniobra = new JLabel("Maniobra: "+/*this.inst.size()*/ this.maniobra);
Maniobra.setFont(new Font("Consolas", Font.PLAIN, 14));
Maniobra.setBounds(231, 673, 119, 29);
contentPane.add(Maniobra);
txtFichaAt = new JTextArea();
txtFichaAt.setFont(new Font("Consolas", Font.PLAIN, 11));
txtFichaAt.setBounds(977, 609, 71, 71);
contentPane.add(txtFichaAt);
btnAnteriorMovimiento.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(tabI!=0 && tabI != 8) {
// Tablero actual = tableros.get(tabI-1);
/**/ tab = (Tablero)tableros.get(tabI-1).clone();
tabGuardado = (Tablero)tableros.get(tabI-1).clone();
if(tabI==7) {
btnSiguienteMovimiento.setEnabled(true);
turno--;
Turno.setText("Turno: "+turno);
maniobra = 7; //A efectos prácticos es como si tuviese la maniobra 7 del turno anterior.
}
limpiarActions();
pintar(/*actual*/tab);
// /**/ tab = (Tablero)actual.clone();
tabI--;
maniobra--;
Maniobra.setText("Maniobra: "+maniobra);
if(tabI==0) {
btnAnteriorMovimiento.setEnabled(false);
}
}
else if(tabI == 8) {
}
}
});
btnAnteriorMovimiento.setBackground(new Color(240, 230, 140));
btnAnteriorMovimiento.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
btnAnteriorMovimiento.setIcon(new ImageIcon("Recursos\\AnteriorS.png"));
}
@Override
public void mouseExited(MouseEvent e) {
btnAnteriorMovimiento.setIcon(new ImageIcon("Recursos\\Anterior.png"));
}
});
btnAnteriorMovimiento.setIcon(new ImageIcon("Recursos\\Anterior.png"));
btnAnteriorMovimiento.setBounds(366, 647, 179, 47);
btnAnteriorMovimiento.setBorder(null);
contentPane.add(btnAnteriorMovimiento);
}
//pone los nombres y las facciones.
public void setNombre(String nombre1, String nombre2, boolean azul) {
if (azul) {
lblNewLabel_3.setText("Tú: " + nombre1 + " (Azul)");
lblNewLabel_4.setText("Oponente: " + nombre2 + " (Rojo)");
this.faccion = Facción.Facción1;
} else {
lblNewLabel_3.setText("Tú: " + nombre1 + " (Rojo)");
lblNewLabel_4.setText("Oponente: " + nombre2 + " (Azul)");
this.faccion = Facción.Facción2;
}
this.azul = azul;
System.out.println(this.azul);
this.nombre = nombre1;
this.oponente = nombre2;
}
//Este metodo añade eventos para que al poner el ratón encima del boton en cuestion muestre una informacion adicional sobre la vida y estado de una ficha o sobre una casilla.
public void ratonInNodo(int i) {
String casillaInfo = "";
String fichaDefInfo = "";
String fichaAtInfo = "";
Casilla casilla = this.tab.getNodo(i).getCasilla();
Ficha fichaDef = this.tab.getNodo(i).getFichaDefensora();
Ficha fichaAt = this.tab.getNodo(i).getFichaAtacante();
// Info. de la casilla
casillaInfo += casilla.getClass().getSimpleName() + "\r\n";
if(casillaInfo.equals("Copa\r\n")) {
casillaInfo = "Corona\r\n";
}
if (casilla instanceof Copa) {
if(((Copa) casilla).getFacción()== Facción.Facción1)
casillaInfo += "Azul" + "\r\n";
else
casillaInfo += "Rojo" + "\r\n";
casillaInfo += "Vida: " + ((Copa) casilla).getVida() + "\r\n";
} else if (casilla instanceof Curación) {
casillaInfo += "Identificador: " + ((Curación) casilla).getIdentificador() + "\r\n";
casillaInfo += "Curación: " + ((Curación) casilla).getCuración() + "\r\n";
} else if (casilla instanceof Catapulta) {
if(((Catapulta) casilla).getIdentificador() == 1)
casillaInfo += "Identificador: Azul \r\n";
else
casillaInfo += "Identificador: Rojo \r\n";
casillaInfo += "Uso: ";
if (fichaDef != null && fichaAt == null) {
if(fichaDef.getFacción().equals(Facción.Facción1))
casillaInfo += "Azul" + "\r\n";
else
casillaInfo += "Rojo" + "\r\n";
}
} else if (casilla instanceof Colina) {
casillaInfo += "Ataque defensivo: +" + ((Colina) casilla).getDañoExtra() + "\r\n";
}
if (casilla.tieneHacha()) {
casillaInfo += "Hacha Divasónica: Sí" + "\r\n";
} else {
casillaInfo += "Hacha Divasónica: No" + "\r\n";
}
if (casilla.casillaDeCura()) {
casillaInfo += "Curación (extra): +: " + casilla.getCuraciónAuxiliar();
}
// Info. de la/s ficha/s.
if(fichaDef == null) {
fichaDefInfo = "Ninguna";
}
else {
fichaDefInfo += fichaDef.getClass().getCanonicalName().split("\\.")[fichaDef.getClass().getCanonicalName().split("\\.").length-1];
if (fichaAt != null) {
fichaDefInfo += " vs." + "\r\n";
fichaAtInfo += fichaAt.getClass().getCanonicalName().split("\\.")[fichaAt.getClass().getCanonicalName().split("\\.").length-1] + "\r\n";
} else
fichaDefInfo += "\r\n";
if(fichaDef.getFacción().equals(Facción.Facción1))
fichaDefInfo += "Facción: Azul" + "\r\n";
else
fichaDefInfo += "Facción: Rojo" + "\r\n";
if (fichaAt != null) {
if(fichaAt.getFacción().equals(Facción.Facción1))
fichaAtInfo += "Azul" + "\r\n";
else
fichaAtInfo += "Rojo" + "\r\n";
}
fichaDefInfo += "Vida: " + fichaDef.getVida() + "\r\n";
if (fichaAt != null)
fichaAtInfo += fichaAt.getVida() + "\r\n";
if (fichaDef.tieneHacha()) {
fichaDefInfo += "Hacha Div.: Sí" + "\r\n";
} else {
fichaDefInfo += "Hacha Div.: No" + "\r\n";
}
if (fichaAt != null) {
if (fichaAt.tieneHacha())
fichaAtInfo += "Sí" + "\r\n";
else
fichaAtInfo += "No" + "\r\n";
}
}
this.txtCasilla.setText(casillaInfo);
this.txtFichaDef.setText(fichaDefInfo);
this.txtFichaAt.setText(fichaAtInfo);
}
//este metodo recorre todo el tablero tab dado y pinta las casillas y fichas correspondientes ademas de añadirles sus eventos correspondientes.
public void pintar(Tablero tab) {
//Representar gráficamente el tablero tab
for (int i = 0; i < 45; i++) {
//Con esto limpia lo que hay
this.casillas[i].setIcon(null);
this.casillas[i].setEnabled(true);
this.casillas[i].setBackground(new Color(245, 245, 220));
final Integer x = i;
Casilla cas = tab.getNodo(i).getCasilla();
Ficha f = tab.getNodo(i).getFichaDefensora();
Ficha fat = tab.getNodo(i).getFichaAtacante();
if(tab.getNodo(i).getCayóProyectil()) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\ImpactoProyectilBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInImpactoProyectil(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutImpactoProyectil(x);
}
});
}
else if (cas instanceof Catapulta) {
if (((Catapulta) cas).getIdentificador() == 1) {
if (f == null) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CatapultaAzul.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInCatapultaAzul(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutCatapultaAzul(x);
}
});
}
else {
this.pintarFicha(tab, i);
}
} else {
if (f == null) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CatapultaRoja.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInCatapultaRojo(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutCatapultaRojo(x);
}
});
} else {
this.pintarFicha(tab, i);
}
}
} else if (cas instanceof Colina) {
if(f == null) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\Colina.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInColina(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutColina(x);
}
});
}else {
this.pintarFicha(tab, i);
}
} else if (cas instanceof Curación) {
if(f == null) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\Curarse.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInCurarse(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutCurarse(x);
}
});
}else {
this.pintarFicha(tab, i);
}
} else if (cas instanceof Copa) {
if(f == null) {
if (((Copa) cas).getFacción().equals(Facción.Facción1)) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CoronaBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInCoronaAzul(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutCoronaAzul(x);
}
});
} else {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CoronaBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInCoronaRojo(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutCoronaRojo(x);
}
});
}
}else {
this.pintarFicha(tab, i);
}
}else if(cas.getHachaDivasónica() != null && f == null){
this.casillas[i].setIcon(new ImageIcon("Recursos\\HachaDivasonica.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInHacha(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutHacha(x);
}
});
}else {
this.pintarFicha(tab, i);
}
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInNodo(x);
}
});
}
}
//Para dado el tablero y una posicion pinta la ficha de la misma, y añade sus eventos visuales.
public void pintarFicha(Tablero tab, int i) {
Ficha f = tab.getNodo(i).getFichaDefensora();
Ficha f2 = tab.getNodo(i).getFichaAtacante();
final Integer x = i;
if (f instanceof Arquero) {
if(f2 == null) {
if (f.getFacción().equals(Facción.Facción1)) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\ArqueroAzulBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInArqueroAzul(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutArqueroAzul(x);
}
});
} else {
this.casillas[i].setIcon(new ImageIcon("Recursos\\ArqueroRojoBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInArqueroRojo(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutArqueroRojo(x);
}
});
}
}else {
this.pintarFichaCruzada(tab, i);
}
} else if (f instanceof Lancero) {
if(f2 == null) {
if (f.getFacción().equals(Facción.Facción1)) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LanceroAzulBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInLanceroAzul(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutLanceroAzul(x);
}
});
}
else {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LanceroRojoBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInLanceroRojo(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutLanceroRojo(x);
}
});
}
}else {
this.pintarFichaCruzada(tab, i);
}
} else if (f instanceof Guerrero) {
if(f2 == null) {
if (f.getFacción().equals(Facción.Facción1)) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GuerreroAzulBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInGuerreroAzul(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutGuerreroAzul(x);
}
});
}
else {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GuerreroRojoBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInGuerreroRojo(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutGuerreroRojo(x);
}
});
}
}else {
this.pintarFichaCruzada(tab, i);
}
} else if (f instanceof Bárbaro) {
if(f2 == null) {
if (f.getFacción().equals(Facción.Facción1)) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BarbaroAzulBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInBarbaroAzul(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutBarbaroAzul(x);
}
});
}
else {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BarbaroRojoBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInBarbaroRojo(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutBarbaroRojo(x);
}
});
}
}else {
this.pintarFichaCruzada(tab, i);
}
} else if (f instanceof Caballero) {
if(f2 == null) {
if (f.getFacción().equals(Facción.Facción1)) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CaballeroAzulBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInCaballeroAzul(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutCaballeroAzul(x);
}
});
}
else {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CaballeroRojoBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInCaballeroRojo(x);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutCaballeroRojo(x);
}
});
}
}else {
this.pintarFichaCruzada(tab, i);
}
}
}
//dado el tablero y una posicion pinta las dos fichas combatienes y añade sus respectivos eventos visuales.
public void pintarFichaCruzada(Tablero tab, int i) {
Ficha f1 = tab.getNodo(i).getFichaAtacante();
Ficha f2 = tab.getNodo(i).getFichaDefensora();
final Integer x = i;
if (f2 instanceof Arquero) {
if (f2.getFacción().equals(Facción.Facción1)) {
final String color = "A";
final String defensor= "F";
if(f1 instanceof Arquero) {
final String atacante = "F";
this.casillas[i].setIcon(new ImageIcon("Recursos\\FvFABC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Bárbaro) {
final String atacante = "B";
this.casillas[i].setIcon(new ImageIcon("Recursos\\FvBABC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Caballero) {
final String atacante = "C";
this.casillas[i].setIcon(new ImageIcon("Recursos\\FvCABC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Guerrero) {
final String atacante = "G";
this.casillas[i].setIcon(new ImageIcon("Recursos\\FvGABC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Lancero) {
final String atacante = "L";
this.casillas[i].setIcon(new ImageIcon("Recursos\\FvLABC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}
} else {
final String color = "R";
final String defensor= "F";
if(f1 instanceof Arquero) {
final String atacante = "F";
this.casillas[i].setIcon(new ImageIcon("Recursos\\FvFRBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Bárbaro) {
final String atacante = "B";
this.casillas[i].setIcon(new ImageIcon("Recursos\\FvBRBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Caballero) {
final String atacante = "C";
this.casillas[i].setIcon(new ImageIcon("Recursos\\FvCRBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Guerrero) {
final String atacante = "G";
this.casillas[i].setIcon(new ImageIcon("Recursos\\FvGRBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Lancero) {
final String atacante = "L";
this.casillas[i].setIcon(new ImageIcon("Recursos\\FvLRBC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}
}
} else if (f2 instanceof Bárbaro) {
final String defensor= "B";
if (f2.getFacción().equals(Facción.Facción1)) {
final String color = "A";
if(f1 instanceof Arquero) {
final String atacante = "F";
this.casillas[i].setIcon(new ImageIcon("Recursos\\BvFABC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Bárbaro) {
final String atacante = "B";
this.casillas[i].setIcon(new ImageIcon("Recursos\\BvBABC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Caballero) {
final String atacante = "C";
this.casillas[i].setIcon(new ImageIcon("Recursos\\BvCABC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Guerrero) {
final String atacante = "G";
this.casillas[i].setIcon(new ImageIcon("Recursos\\BvGABC.png"));
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Lancero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BvLABC.png"));
final String atacante = "L";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}
}else {
final String color = "R";
if(f1 instanceof Arquero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BvFRBC.png"));
final String atacante = "F";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Bárbaro) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BvBRBC.png"));
final String atacante = "B";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Caballero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BvCRBC.png"));
final String atacante = "C";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Guerrero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BvGRBC.png"));
final String atacante = "G";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Lancero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BvLRBC.png"));
final String atacante = "L";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}
}
} else if (f2 instanceof Guerrero) {
final String defensor= "G";
if (f2.getFacción().equals(Facción.Facción1)) {
final String color = "A";
if(f1 instanceof Arquero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GvFABC.png"));
final String atacante = "F";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Bárbaro) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GvBABC.png"));
final String atacante = "B";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Caballero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GvCABC.png"));
final String atacante = "C";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Guerrero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GvGABC.png"));
final String atacante = "G";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Lancero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GvLABC.png"));
final String atacante = "L";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}
}else {
final String color = "R";
if(f1 instanceof Arquero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GvFRBC.png"));
final String atacante = "F";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Bárbaro) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GvBRBC.png"));
final String atacante = "B";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Caballero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GvCRBC.png"));
final String atacante = "C";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Guerrero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GvGRBC.png"));
final String atacante = "G";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Lancero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GvLRBC.png"));
final String atacante = "L";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}
}
} else if (f2 instanceof Lancero) {
final String defensor= "L";
if (f2.getFacción().equals(Facción.Facción1)) {
final String color = "A";
if(f1 instanceof Arquero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LvFABC.png"));
final String atacante = "F";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Bárbaro) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LvBABC.png"));
final String atacante = "B";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Caballero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LvCABC.png"));
final String atacante = "C";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Guerrero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LvGaBC.png"));
final String atacante = "G";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Lancero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LvLABC.png"));
final String atacante = "L";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}
}else {
final String color = "R";
if(f1 instanceof Arquero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LvFRBC.png"));
final String atacante = "F";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Bárbaro) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LvBRBC.png"));
final String atacante = "B";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Caballero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LvCRBC.png"));
final String atacante = "C";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Guerrero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LvGRBC.png"));
final String atacante = "G";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Lancero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LvLRBC.png"));
final String atacante = "L";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}
}
} else if (f2 instanceof Caballero) {
System.out.println("He entrado caballero");
final String defensor= "C";
if (f2.getFacción().equals(Facción.Facción1)) {
final String color = "A";
if(f1 instanceof Arquero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CvFABC.png"));
final String atacante = "F";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Bárbaro) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CvBABC.png"));
final String atacante = "B";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Caballero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CvCABC.png"));
final String atacante = "C";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Guerrero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CvGABC.png"));
final String atacante = "G";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Lancero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CvLABC.png"));
final String atacante = "L";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}
}else {
final String color = "R";
if(f1 instanceof Arquero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CvFRBC.png"));
final String atacante = "F";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Bárbaro) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CvBRBC.png"));
final String atacante = "B";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Caballero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CvCRBC.png"));
final String atacante = "C";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Guerrero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CvGRBC.png"));
final String atacante = "G";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}else if(f1 instanceof Lancero) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CvLRBC.png"));
final String atacante = "L";
this.casillas[i].addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
ratonInConflicto(x, color, defensor, atacante);
}
@Override
public void mouseExited(MouseEvent e) {
ratonOutConflicto(x, color, defensor, atacante);
}
});
}
}
}
}
//Bandera blanca y se lo notifica al servidor.
public void rendirse() {
try {
out.writeBytes("SURR-Me he rendido.\r\n");
out.flush();
}catch(IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
//Todo este codigo está muerto en un princio era lo que hacia mover, pero debido a que daba errores y no fué diseñado demasiado bien se comentó y ahora permanece aqui para el recuerdo.
// public void moverClick() {
// List<Integer> casAModificar = this.tab.quiénesPuedenMover(this.faccion);
// for(Integer posicion: casAModificar) {
// final Integer x = posicion;
// this.casillas[posicion].addMouseListener(new MouseAdapter() {
// @Override
// public void mouseClicked(MouseEvent e) {
// botonesMoverFase2(false,tab.getNodo(x).getFicha(faccion));
// botonesClicarFase2(tab.getNodo(x).getFicha(faccion),x);
// btnCancelar.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent arg0) {
// pintar(tab);
// }
// });
// for(MouseListener ac : casillas[x].getMouseListeners()) {
// casillas[x].removeMouseListener(ac);
// }
// }
// });
// }
// this.botonesMoverFase1(false);
// this.btnCancelar.addActionListener(new ActionListener() {
//
// public void actionPerformed(ActionEvent arg0) {
// botonesMoverFase1(true);
// for( JButton boton : casillas) {
// for(ActionListener al : boton.getActionListeners()) {
// boton.removeActionListener( al );
// }
// }
// }
// });
//
// }
//
// public void botonesMoverFase1(boolean estado) {
// this.btnDisparar.setEnabled(estado);
// this.btnEsperar.setEnabled(estado);
// this.Mover.setEnabled(estado);
// List<Integer> casAModificar = this.tab.quiénesNOPuedenMover(this.faccion);
// for(Integer posicion : casAModificar) {
// this.casillas[posicion].setEnabled(estado);
// }
// casAModificar = this.tab.quiénesPuedenMover(this.faccion);
// for(Integer posicion : casAModificar) {
// Ficha efarda = this.tab.getNodo(posicion).getFicha(faccion);
// if(efarda instanceof Arquero) {
// if(this.movsF == this.tab.getNodo(posicion).getFicha(faccion).getMovs()) {
// this.casillas[posicion].setEnabled(estado);
// }
// }
// if(efarda instanceof Caballero) {
// if(this.movsC == this.tab.getNodo(posicion).getFicha(faccion).getMovs())
// this.casillas[posicion].setEnabled(estado);
// }
// if(efarda instanceof Bárbaro) {
// if(this.movsB == this.tab.getNodo(posicion).getFicha(faccion).getMovs())
// this.casillas[posicion].setEnabled(estado);
// }
// if(efarda instanceof Guerrero) {
// if(this.movsG == this.tab.getNodo(posicion).getFicha(faccion).getMovs())
// this.casillas[posicion].setEnabled(estado);
// }
// if(efarda instanceof Lancero) {
// if(this.movsL == this.tab.getNodo(posicion).getFicha(faccion).getMovs())
// this.casillas[posicion].setEnabled(estado);
// }
// }
// }
//
// public void botonesMoverFase2(boolean estado, Ficha f) {
// this.btnDisparar.setEnabled(estado);
// this.btnEsperar.setEnabled(estado);
// this.Mover.setEnabled(estado);
// List<Integer> casAModificar = this.tab.dóndePuedeMover(f);
// for(int i=0; i<45; i++) {
// this.casillas[i].setEnabled(estado);
// }
// for(Integer posicion : casAModificar) {
// this.casillas[posicion].setEnabled(!estado);
// }
//
// }
//
// public void botonesClicarFase2(Ficha f, int j) {
//
// List<Integer> casAModificar = tab.dóndePuedeMover(f);
// for(Integer posicion : casAModificar) {
// final Ficha efe = f;
// final int x = posicion;
// final int y = j;
// this.casillas[posicion].setBackground(Color.white);
// this.casillas[posicion].enable(true);
// for(MouseListener ms : this.casillas[posicion].getMouseListeners()) {
// this.casillas[posicion].removeMouseListener(ms);
// }
// this.casillas[posicion].addMouseListener(new MouseAdapter() {
// @Override
// public void mouseClicked(MouseEvent e) {
// System.out.println("Entré");
// moverEnSí(efe,y,x);
// }
// });
//
// }
// }
//
// //
// public void moverEnSí(Ficha f, int j , int posicion) {
// System.out.println("He entrado en mover en sí");
// int resta =posicion-j;
// Dirección direccion = null;
// switch(resta) {
// case -9:{
// direccion = Dirección.norte;
// break;
// }
// case 9:{
// direccion = Dirección.sur;
// break;
// }
// case -1:{
// direccion = Dirección.oeste;
// break;
// }
// case 1:{
// direccion = Dirección.este;
// break;
// }
// case 8:{
// direccion = Dirección.suroeste;
// break;
// }
// case 10:{
// direccion = Dirección.sureste;
// break;
// }
// case -8:{
// direccion = Dirección.noreste;
// break;
// }
// case -10:{
// direccion = Dirección.noroeste;
// break;
// }
//
// }
// Movimiento mov = new Movimiento(f,direccion);
// this.inst.add(mov);
// /**/ introducirOperacionEnCurso = false;
//// Tablero tab2 = tab;
// /**/ Tablero tab2 = (Tablero) tab.clone();
// this.tab = tab2;
// tab2.moverFichaGraficamente(f, direccion);
// this.tableros.add(tab2);
// botonesMoverFase1(true);
// for(int i=0; i<45;i++) {
// this.casillas[i].setIcon(null);
// for(MouseListener ac : this.casillas[i].getMouseListeners()) {
// this.casillas[i].removeMouseListener(ac);
// }
// }
// System.out.println(this.inst.size());
// Operaciones.setText("Ops.: "+this.inst.size()+"/6");
// if(this.inst.size()==6) {
// this.btnDisparar.setEnabled(false);
// this.btnEsperar.setEnabled(false);
// this.Mover.setEnabled(false);
// }
// pintar(tab2);
// for(ActionListener ac : this.btnCancelar.getActionListeners()) {
// this.btnCancelar.removeActionListener(ac);
// }
// this.agregarFuncionalidadOriginalBtnCancelar();
// if(f instanceof Arquero) {
// this.movsF++;
// }
// if(f instanceof Caballero) {
// this.movsC++;
// }
// if(f instanceof Bárbaro) {
// this.movsB++;
// }
// if(f instanceof Guerrero) {
// this.movsG++;
// }
// if(f instanceof Lancero) {
// this.movsL++;
//// }
// }
//el handler de mover, para ejercutarlo todo
public void moverClick() {
this.botonesCasillasMover(false);
this.introducirOperacionEnCurso=true;
this.btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
botonesCasillasMover(true);
}
});
}
//Habilita solo los botones de las fichas que la faccion correspondiente que pueden mover.
public void botonesCasillasMover(boolean estado) {
this.btnDisparar.setEnabled(estado);
this.btnEsperar.setEnabled(estado);
this.Mover.setEnabled(estado);
List<Integer> casAModificar = this.tab.quiénesNOPuedenMover(this.faccion);
for(Integer posicion : casAModificar) {
this.casillas[posicion].setEnabled(estado);
}
List<Integer> casFichas = this.tab.quiénesPuedenMover(this.faccion);
/**/ if(!estado)
for(final Integer posicion : casFichas) {
if(!this.botonFichaPuedeMover(posicion)) {
this.casillas[posicion].setEnabled(estado);
}else {
MouseListener eventoFicha = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
botonesCasillasAMover(tab.getNodo(posicion).getFicha(faccion),true);
deshabilitarTodoMenosI(posicion,false);
btnCancelar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
deshabilitarTodoMenosI(posicion,true);
botonesCasillasAMover(tab.getNodo(posicion).getFicha(faccion),false);
}
});
}
};
if(!estado) {
this.casillas[posicion].addMouseListener(eventoFicha);
}else {
// this.casillas[posicion].removeMouseListener(eventoFicha);
}
}
}
if(/*!*/estado) {
/**/ this.limpiarActionFichas(casFichas);
this.limpiarActionDeshacer();
/**/ this.pintar(tab);
}
}
//lo mismo que deshabilitar todo pero el boton de la posicion i no.
public void deshabilitarTodoMenosI (int i,boolean estado) {
List<Integer> casFichas = this.tab.quiénesPuedenMover(this.faccion);
for(Integer pos: casFichas) {
if(pos!=i) {
this.casillas[pos].setEnabled(estado);
for(MouseListener ml :this.casillas[pos].getMouseListeners()) {
this.casillas[pos].removeMouseListener(ml);
}
}
}
}
//Todo es todos los botones del tablero.
public void deshabilitarTodo (boolean estado) {
for(Integer pos = 0; pos < 45; pos++) {
this.casillas[pos].setEnabled(estado);
for(MouseListener ml :this.casillas[pos].getMouseListeners()) {
this.casillas[pos].removeMouseListener(ml);
}
}
}
//mira si la ficha que se encuentra en la posicion i puede mover, si sus movimientos se han agotado devolverá false.
public boolean botonFichaPuedeMover(int i){
Ficha f = this.tab.getNodo(i).getFicha(faccion);
if(f instanceof Arquero) {
if(this.movsF == this.tab.getNodo(i).getFicha(faccion).getMovs())
return false;
}else if(f instanceof Caballero) {
if(this.movsC == this.tab.getNodo(i).getFicha(faccion).getMovs())
return false;
}else if(f instanceof Bárbaro) {
if(this.movsB == this.tab.getNodo(i).getFicha(faccion).getMovs())
return false;
}else if(f instanceof Guerrero) {
if(this.movsG == this.tab.getNodo(i).getFicha(faccion).getMovs())
return false;
}else if(f instanceof Lancero) {
if(this.movsL == this.tab.getNodo(i).getFicha(faccion).getMovs())
return false;
}
return true;
}
//Pinta de blanco las casillas o no donde puede mover una ficha
public void botonesCasillasAMover(Ficha f,boolean estado) {
List<Integer> posiciones = this.tab.dóndePuedeMover(f);
final Movimiento mov;
final Ficha fFinal = f;
final int posicionFicha = this.tab.dóndeEstá(f);
/**/ if(estado)
for(final Integer pos : posiciones) {
MouseListener eventoCasilla = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
añadirMov(fFinal,calcularDireccion(posicionFicha,pos));
}
};
if(estado) {
this.casillas[pos].setBackground(Color.white);
for(MouseListener ml :this.casillas[pos].getMouseListeners()) {
this.casillas[pos].removeMouseListener(ml);
}
this.casillas[pos].addMouseListener(eventoCasilla);
}else {
this.casillas[pos].setBackground(new Color(245, 245, 220));
this.casillas[pos].removeMouseListener(eventoCasilla);
}
}
if(!estado) {
// this.limpiarActionFichas();
/**/ this.limpiarActionFichas(posiciones);
this.limpiarActionDeshacer();
this.pintar(tab);
}
}
//añade el movimiento adecuado a la instrucción y restaura el tablero.
public void añadirMov (Ficha f, Dirección direccion) {
this.inst.add(new Movimiento(f,direccion));
this.Operaciones.setText("Ops.: "+this.inst.size()+"/6");
Tablero tabCopia = (Tablero)this.tab.clone();
tabCopia.moverFichaGraficamente(f, direccion);
this.tableros.add(tabCopia);
this.tab = tabCopia;
if(this.inst.size()!=6) {
this.btnDisparar.setEnabled(true);
this.btnEsperar.setEnabled(true);
this.Mover.setEnabled(true);
}
this.limpiarActions();
this.pintar(tabCopia);
if(f instanceof Arquero) {
this.movsF++;
}else if(f instanceof Caballero) {
this.movsC++;
}else if(f instanceof Bárbaro) {
this.movsB++;
}else if(f instanceof Guerrero) {
this.movsG++;
}else if(f instanceof Lancero) {
this.movsL++;
}
this.limpiarActionDeshacer();
this.introducirOperacionEnCurso=false;
}
//En un principio fueron actions pero como no iban muy bien pues pasó a limpiar mouselisteners de las fichas de la facción correspondiente.
public void limpiarActionFichas() {
List<Integer> posFichas = this.tab.quiénesPuedenMover(this.faccion);
for(Integer posficha : posFichas) {
for(MouseListener al : this.casillas[posficha].getMouseListeners()) {
this.casillas[posficha].removeMouseListener(al);
}
}
}
//Con el método anterior limpiabas la acción de las que pueden mover. Con este, a las que se puede mover (que es lo que deseamos).
public void limpiarActionFichas(List<Integer> posiciones) {
for(Integer posficha : posiciones) {
for(MouseListener al : this.casillas[posficha].getMouseListeners()) {
this.casillas[posficha].removeMouseListener(al);
}
}
}
//eso, limpia los actions del boton deshacer.
public void limpiarActionDeshacer() {
for(ActionListener al : this.btnCancelar.getActionListeners()) {
this.btnCancelar.removeActionListener(al);
}
this.agregarFuncionalidadOriginalBtnCancelar();
}
//Aunque pone actions limpia mouse listeners.
public void limpiarActions() {
for(int i = 0 ; i<45; i++) {
this.casillas[i].setEnabled(true);
for(MouseListener al : this.casillas[i].getMouseListeners()) {
this.casillas[i].removeMouseListener(al);
}
}
}
//Calcula la direaccion a partir de la posicion de la ficha y la posicion de la casilla a donde quiere moverse.
public Dirección calcularDireccion(int posicionFicha, int posicionCasilla) {
System.out.println(posicionFicha+" "+posicionCasilla);
int resta =posicionCasilla-posicionFicha;
Dirección direccion = null;
switch(resta) {
case -9:{
direccion = Dirección.norte;
break;
}
case 9:{
direccion = Dirección.sur;
break;
}
case -1:{
direccion = Dirección.oeste;
break;
}
case 1:{
direccion = Dirección.este;
break;
}
case 8:{
direccion = Dirección.suroeste;
break;
}
case 10:{
direccion = Dirección.sureste;
break;
}
case -8:{
direccion = Dirección.noreste;
break;
}
case -10:{
direccion = Dirección.noroeste;
break;
}
}
System.out.println(direccion.toString());
return direccion;
}
//los peina y cepilla para no tener problemas luego al visualizar el tablero, muy util en muchas circunstancia.
public void peinarEventos(int i) {
for(MouseListener ls : this.casillas[i].getMouseListeners()) {
this.casillas[i].removeMouseListener(ls);
}
}
//Manda al servidor un mensaje de que se ha rendido
public void salir() {
try {
if(out!=null) {
out.writeBytes("SURR-Me he rendido.\r\n");
out.flush();
}
}catch(IOException ex) {
ex.printStackTrace();
}
finally {
System.exit(0);
}
}
//Bloquea todos los botones excepto las catapultas disponibles.
public void bloquearCasillasDisparo(boolean estado, final List<Integer> catapultas) {
this.btnDisparar.setEnabled(estado);
this.btnEsperar.setEnabled(estado);
this.Mover.setEnabled(estado);
if(catapultas.size()==2) {
for(int i=0; i<45; i++) {
final int x = i;
if(this.casillas[i].equals(this.casillas[catapultas.get(0)])||this.casillas[i].equals(this.casillas[catapultas.get(1)])){
this.casillas[i].addMouseListener( new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(x==catapultas.get(0)) {
casillas[catapultas.get(1)].setEnabled(false);
peinarEventos(catapultas.get(1));
}else {
casillas[catapultas.get(0)].setEnabled(false);
peinarEventos(catapultas.get(0));
}
pintarCasillasDisparo(true,x);
}
});
this.btnCancelar.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
pintarCasillasDisparo(false,x);
}
});
}else {
this.casillas[i].setEnabled(estado);
}
}
}else {
for(int i=0; i<45; i++) {
final int x = i;
if(this.casillas[i].equals(this.casillas[catapultas.get(0)])) {
this.casillas[i].addMouseListener( new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
pintarCasillasDisparo(true,x);
}
});
this.btnCancelar.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
pintarCasillasDisparo(false,x);
}
});
}else {
this.casillas[i].setEnabled(estado);
}
}
}
if(/*!*/estado) {
/**/ this.limpiarActions();
this.limpiarActionDeshacer();
/**/ this.pintar(tab);
}
}
//Pintar o no las casillas a las que se puede disparar con las catapultas.
public void pintarCasillasDisparo(boolean estado, final Integer posicionCat) {
if(estado) {
List<Integer> casillasCat1 =this.tab.dóndeDispararProyectiles((Catapulta)this.tab.getNodo(posicionCat).getCasilla());
for(final Integer cat1 : casillasCat1) {
this.casillas[cat1].setBackground(Color.white);
for(MouseListener ac : casillas[cat1].getMouseListeners()) {
casillas[cat1].removeMouseListener(ac);
}
final Ficha f = this.tab.getNodo(/*cat1*/ posicionCat).getFichaDefensora();
final Integer x = cat1;
final Catapulta cas = (Catapulta) this.tab.getNodo(posicionCat).getCasilla();
this.casillas[cat1].addMouseListener( new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// System.out.println("1. f es null? " + f == null);
disparar(f,cas,x,posicionCat);
}
});
}
//Devuelve a los botones a la situación original.
}else {
// for(int i=0; i<45;i++) {
// casillas[i].setIcon(null);
// for(MouseListener ac : casillas[i].getMouseListeners()) {
// casillas[i].removeMouseListener(ac);
// }
// this.casillas[i].setBackground(new Color(240, 230, 140));
// this.casillas[i].setEnabled(!estado);
// }
// pintar(tab);
if(!estado) {
/**/ this.limpiarActions();
this.limpiarActionDeshacer();
/**/ this.pintar(tab);
}
}
}
//Dada una ficha y una catapulta ademas del lugar de disparo y la posicion de la cata pulta crea un objeto Disparo y lo añade a las instrucciones a mandar, ademas de restaurar el tablero a su forma anterior
//quitando los eventos y los botones deshabilitados
public void disparar(Ficha f, Catapulta cas, int lugarDisparo, int posicion) {
// System.out.println("2. f es null? " + f == null);
Disparo disp = new Disparo(f,cas,lugarDisparo);
inst.add(disp);
/**/ introducirOperacionEnCurso = false;
if(inst.size()==6) {
btnDisparar.setEnabled(false);
btnEsperar.setEnabled(false);
Mover.setEnabled(false);
}else {
btnDisparar.setEnabled(true);
btnEsperar.setEnabled(true);
Mover.setEnabled(true);
}
for(ActionListener ac : btnCancelar.getActionListeners()) {
btnCancelar.removeActionListener(ac);
}
agregarFuncionalidadOriginalBtnCancelar();
for(int i=0; i<45;i++) {
casillas[i].setIcon(null);
for(MouseListener ac : casillas[i].getMouseListeners()) {
casillas[i].removeMouseListener(ac);
}
}
if(posicion==24) {
catR=false;
}else {
catA=false;
}
Tablero tab2 = (Tablero)tab.clone();
Operaciones.setText("Ops.: "+inst.size()+"/6");
tableros.add(tab2);
pintar(tab2);
}
//Restaura la funcionalidad original (deshacer la última operación) del botón Deshacer.
private void agregarFuncionalidadOriginalBtnCancelar() {
/**/ btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(introducirOperacionEnCurso == false) {
if(inst.size()>0) {
Operación op = inst.get(inst.size()-1);
if(op instanceof Movimiento) {
Movimiento mov = (Movimiento)inst.get(inst.size()-1);
Ficha f = mov.getFicha();
if(f instanceof Arquero) {
movsF--;
}else if(f instanceof Caballero) {
movsC--;
}else if(f instanceof Bárbaro) {
movsB--;
}else if(f instanceof Guerrero) {
movsG--;
}else if(f instanceof Lancero) {
movsL--;
}
}else if(op instanceof Disparo) {
Disparo disp = (Disparo)inst.get(inst.size()-1);
if(disp.getCatapulta().getIdentificador()==1) {
catA=true;
}else if(disp.getCatapulta().getIdentificador()==2){
catR=true;
}
}
if(inst.size()==6) {
btnDisparar.setEnabled(true);
btnEsperar.setEnabled(true);
Mover.setEnabled(true);
}
inst.remove(inst.size()-1);
tableros.remove(tableros.size()-1);
tab = tableros.get(tableros.size()-1);
limpiarActions();
pintar(tableros.get(tableros.size()-1));
Operaciones.setText("Ops.:" + inst.size() + "/6");
}
else {
JOptionPane.showMessageDialog(null, "No hay ninguna operación por deshacer.", "Atención", JOptionPane.WARNING_MESSAGE);
}
}
else {
//ESTA ES UNA SOLUCIÓN PARA ELIMINAR TODOS LOS CAPTURADORES DE EVENTOS AL DESHACER:
// for(int i=0; i<45;i++) {
// for(MouseListener ac : casillas[i].getMouseListeners()) {
// casillas[i].removeMouseListener(ac);
// }
// }
introducirOperacionEnCurso = false;
}
}
});
}
//Resetea los movimientos de las fichas, para que al comenzar un turno vuelvan a estar frescas.
public void resetearMovs() {
this.movsB=0;
this.movsF=0;
this.movsC=0;
this.movsG=0;
this.movsL=0;
}
//Con el booleano estado habilita o deshabilita los botones del menu
public void casillasMenu(boolean estado) {
this.btnCancelar.setEnabled(estado);
this.btnDisparar.setEnabled(estado);
this.btnEsperar.setEnabled(estado);
this.Mover.setEnabled(estado);
this.Listo.setEnabled(estado);
}
//Resetea las catapultas para que en un turno nuevo vuelvan a estar funcionales
public void resetearCatapultas() {
this.catA =true;
this.catR =true;
}
// -------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------
// --------------------------- RATÓN ENTRA O SALE DE CASILLAS (BRILLO EN LAS IMÁGENES) -------------------------
// -------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------
//Básicamente añade fondo de color blanco y una imagen con o sin color a el botón correspondiente que puede representar una ficha o una casilla.
public void ratonInCoronaAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CoronaAzul.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutCoronaAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CoronaBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInCoronaRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CoronaRojo.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutCoronaRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CoronaBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInCatapultaAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CatapultaAzulC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutCatapultaAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CatapultaAzul.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInCatapultaRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CatapultaRojaC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutCatapultaRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CatapultaRoja.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInColina(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\ColinaC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutColina(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\Colina.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInCurarse(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CurarseC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutCurarse(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\Curarse.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInHacha(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\HachaDivasonicaS.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutHacha(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\HachaDivasonica.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInArqueroAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\ArqueroAzulC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutArqueroAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\ArqueroAzulBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInArqueroRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\ArqueroRojoC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutArqueroRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\ArqueroRojoBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInBarbaroAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BarbaroAzulC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutBarbaroAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BarbaroAzulBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInBarbaroRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BarbaroRojoC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutBarbaroRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\BarbaroRojoBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInCaballeroAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CaballeroAzulC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutCaballeroAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CaballeroAzulBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInCaballeroRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CaballeroRojoC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutCaballeroRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\CaballeroRojoBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInGuerreroAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GuerreroAzulC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutGuerreroAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GuerreroAzulBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInGuerreroRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GuerreroRojoC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutGuerreroRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\GuerreroRojoBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInLanceroAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LanceroAzulC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutLanceroAzul(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LanceroAzulBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInLanceroRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LanceroRojoC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutLanceroRojo(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\LanceroRojoBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
public void ratonInConflicto(int i, String color, String defensor, String atacante) {
String todo = "Recursos\\"+defensor+"v"+atacante+color+"C.png";
this.casillas[i].setIcon(new ImageIcon(todo));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutConflicto(int i, String color, String defensor, String atacante) {
String todo = "Recursos\\"+defensor+"v"+atacante+color+"BC.png";
this.casillas[i].setIcon(new ImageIcon(todo));
this.casillas[i].setBackground(Color.white);
}
public void ratonInImpactoProyectil(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\ImpactoProyectilC.png"));
this.casillas[i].setBackground(Color.white);
}
public void ratonOutImpactoProyectil(int i) {
this.casillas[i].setIcon(new ImageIcon("Recursos\\ImpactoProyectilBC.png"));
this.casillas[i].setBackground(new Color(245, 245, 220));
}
//__________________________________________________________________________________________________________
//Para conseguir los object Input y Output Streams.
public void setIn(DataInputStream in) {
try {
this.in= new ObjectInputStream(in);
}catch(IOException ex) {
ex.printStackTrace();
}
}
public void setOut(DataOutputStream out) {
try {
this.out= new ObjectOutputStream(out);
}catch(IOException ex) {
ex.printStackTrace();
}
}
//A través de un arbol DOM creamos un archivo XML a partir del primer tablero de la partida y lo guradamos en 'PARTIDAS GUARDADAS'
public void guardarPartida() throws ParserConfigurationException, TransformerException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element tableroElemento = this.tabGuardado.getElemento(doc);
tableroElemento.setAttribute("turno", this.turno + "");
doc.appendChild(tableroElemento);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
DOMSource source = new DOMSource(doc);
File carpeta = new File("PartidasGuardadas");
if (!carpeta.exists()) {
if (carpeta.mkdirs()) {
System.out.println("Directorio creado");
} else {
System.out.println("Error al crear directorio");
}
}
SimpleDateFormat formato = new SimpleDateFormat("yyyy-MMMMM-dd_hh-mm-ss");
String fechaString = formato.format(Calendar.getInstance().getTime());
File archivoXML = new File("PartidasGuardadas//"+fechaString +"_"+ this.nombre +"VS" +this.oponente +".xml");
StreamResult result = new StreamResult(archivoXML);
t.transform(source , result);
}
public void setTablero() {
try {
this.tab = (Tablero)in.readObject();
this.tabGuardado = (Tablero)tab.clone();
this.tableros.clear();
this.limpiarActions();
this.pintar(tab);
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setTurno(int x) {
this.turno= x;
Turno.setText("Turno: "+turno);
}
}
|
package com.dollarapi.demo.repository;
import com.dollarapi.demo.model.Dollar;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace.NONE;
@DataJpaTest
@AutoConfigureTestDatabase(replace = NONE)
class DollarRepositoryTest {
@Autowired
private DollarRepository dollarRepository;
private Dollar expectedDollar = new Dollar();
private String dateString = "2020-08-06";
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@BeforeEach
void setUp() throws ParseException {
dollarRepository.deleteAll();
expectedDollar.setSell(new BigDecimal("4.5"));
expectedDollar.setBuy(new BigDecimal("4.6"));
expectedDollar.setDollarDate(dateFormat.parse(dateString));
dollarRepository.save(expectedDollar);
}
@Test
void shouldFindDollarByDate() throws ParseException {
Optional<Dollar> dollarValue = dollarRepository.findByDollarDate(dateFormat.parse(dateString));
assertThat(dollarValue.get()).isEqualTo(expectedDollar);
}
}
|
package eleccionesunimet;
import java.io.*;
public class Vectores implements Serializable {
private int[]indexCedula = new int[6000];
private int[]indexNombre = new int[6000];
private int[]indexApellido = new int[6000];
private Estudiantes[] vecEstudiantes = new Estudiantes[6000];
private int cont=0;
public Vectores(){
}
public int getCont() {
return cont;
}
public void setCont(int cont) {
this.cont = cont;
}
public Estudiantes[] getVecEstudiantes() {
return vecEstudiantes;
}
public void setVecEstudiantes(Estudiantes[] vecEstudiantes) {
this.vecEstudiantes = vecEstudiantes;
}
public int[] getIndexCedula() {
return indexCedula;
}
public void setIndexCedula(int[] indexCedula) {
this.indexCedula = indexCedula;
}
public int[] getIndexNombre() {
return indexNombre;
}
public void setIndexNombre(int[] indexNombre) {
this.indexNombre = indexNombre;
}
public int[] getIndexApellido() {
return indexApellido;
}
public void setIndexApellido(int[] indexApellido) {
this.indexApellido = indexApellido;
}
}
|
package com.sky.grpc;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
/**
* DESCRIPTION:
* <P>
* </p>
*
* @author WangMin
* @since 2019/12/19 7:27 下午
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = {GrpcApplication.class})
@PropertySource(value = "classpath*:application.yml")
@ComponentScan(basePackages = { "com.sky.grpc"})
public class TestControllerTest {
private MockMvc mockMvc;
@Autowired
WebApplicationContext webApplicationContext;
private static String path;
@Before
public void setup() {
path = TestControllerTest.class.getResource("/").getPath();
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).dispatchOptions(true).build();
}
@Test
public void queryIntentionCustomerPageInfo() throws Exception {
String url = "/grpc";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("message", "message");
//准备参数
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get(url).accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON).params(params)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print()).andReturn();
String result = mvcResult.getResponse().getContentAsString();
System.out.println("=====客户端获得反馈数据:" + result);
}
}
|
package Creational.SIngleton;
// Pitfalls : this implementation is lazy loading.
// This can be broken in multithreaded environment as access to getInstance method is not synchronized
// to make this thread safe, use Synchronized keyword on getInstance method.
public class SingletonLazy {
private static SingletonLazy INSTANCE;
private SingletonLazy(){
}
/* public static SingletonLazy getInstance(){
if ( INSTANCE == null)
INSTANCE = new SingletonLazy();
return INSTANCE;
}
*/
public static SingletonLazy getInstance(){
synchronized (SingletonLazy.class)
{
if ( INSTANCE == null)
INSTANCE = new SingletonLazy();
}
return INSTANCE;
}
}
|
package beans;
import lombok.Data;
import util.Default;
@Data
public class StudentHirerehire {
private String id;
private String rowstamp;
private String firstname;
private String middlename;
private String lastname;
private String employeeid;
private String department;
private String title;
private java.sql.Date startdate;
private java.sql.Date enddate;
private String supervisorname;
private String isautoterminated;
private String hoursperweek;
private String rateOfpayMonthly;
private String rateOfpayHourly;
private String isfulltime;
private String workaddress;
private String workphone;
private String notes;
private String submittedBy;
private java.sql.Timestamp submitted;
private String isactive;
public StudentHirerehire(){
rowstamp = Default.getInstance().getDefaultRawstramp();
isactive = Default.getInstance().getDefaultIsActive();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRowstamp() {
return rowstamp;
}
public void setRowstamp(String rowstamp) {
this.rowstamp = rowstamp;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmployeeid() {
return employeeid;
}
public void setEmployeeid(String employeeid) {
this.employeeid = employeeid;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public java.sql.Date getStartdate() {
return startdate;
}
public void setStartdate(java.sql.Date startdate) {
this.startdate = startdate;
}
public java.sql.Date getEnddate() {
return enddate;
}
public void setEnddate(java.sql.Date enddate) {
this.enddate = enddate;
}
public String getSupervisorname() {
return supervisorname;
}
public void setSupervisorname(String supervisorname) {
this.supervisorname = supervisorname;
}
public String getIsautoterminated() {
return isautoterminated;
}
public void setIsautoterminated(String isautoterminated) {
this.isautoterminated = isautoterminated;
}
public String getHoursperweek() {
return hoursperweek;
}
public void setHoursperweek(String hoursperweek) {
this.hoursperweek = hoursperweek;
}
public String getRateOfpayMonthly() {
return rateOfpayMonthly;
}
public void setRateOfpayMonthly(String rateOfpayMonthly) {
this.rateOfpayMonthly = rateOfpayMonthly;
}
public String getRateOfpayHourly() {
return rateOfpayHourly;
}
public void setRateOfpayHourly(String rateOfpayHourly) {
this.rateOfpayHourly = rateOfpayHourly;
}
public String getIsfulltime() {
return isfulltime;
}
public void setIsfulltime(String isfulltime) {
this.isfulltime = isfulltime;
}
public String getWorkaddress() {
return workaddress;
}
public void setWorkaddress(String workaddress) {
this.workaddress = workaddress;
}
public String getWorkphone() {
return workphone;
}
public void setWorkphone(String workphone) {
this.workphone = workphone;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getSubmittedBy() {
return submittedBy;
}
public void setSubmittedBy(String submittedBy) {
this.submittedBy = submittedBy;
}
public java.sql.Timestamp getSubmitted() {
return submitted;
}
public void setSubmitted(java.sql.Timestamp submitted) {
this.submitted = submitted;
}
public String getIsactive() {
return isactive;
}
public void setIsactive(String isactive) {
this.isactive = isactive;
}
}
|
package com.hb.rssai.presenter;
import com.hb.rssai.constants.Constant;
import com.hb.rssai.view.iView.ICollectionView;
import java.util.HashMap;
import java.util.Map;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by Administrator on 2017/8/15.
*/
public class CollectionPresenter extends BasePresenter<ICollectionView> {
private ICollectionView iCollectionView;
public CollectionPresenter(ICollectionView iCollectionView) {
this.iCollectionView = iCollectionView;
}
public void getList() {
collectionApi.list(getListParams())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resCollection -> iCollectionView.setListResult(resCollection), iCollectionView::loadError);
}
public void del() {
collectionApi.del(getDelParams())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resBase -> iCollectionView.setDelResult(resBase), iCollectionView::loadError);
}
public void getInformation() {
informationApi.getInformation(getInfoParams())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resInfo -> iCollectionView.setInfoResult(resInfo), iCollectionView::loadError);
}
public Map<String, String> getListParams() {
Map<String, String> map = new HashMap<>();
String userId = iCollectionView.getUserId();
int pagNum = iCollectionView.getPageNum();
String jsonParams = "{\"userId\":\"" + userId + "\",\"page\":\"" + pagNum + "\",\"size\":\"" + Constant.PAGE_SIZE + "\"}";
map.put(Constant.KEY_JSON_PARAMS, jsonParams);
System.out.println(map);
return map;
}
public Map<String, String> getDelParams() {
Map<String, String> map = new HashMap<>();
String userId = iCollectionView.getUserId();
String id = iCollectionView.getCollectionId();
String jsonParams = "{\"userId\":\"" + userId + "\",\"id\":\"" + id + "\"}";
map.put(Constant.KEY_JSON_PARAMS, jsonParams);
System.out.println(map);
return map;
}
public Map<String, String> getInfoParams() {
Map<String, String> map = new HashMap<>();
String informationId = iCollectionView.getInfoId();
String jsonParams = "{\"informationId\":\"" + informationId + "\"}";
map.put(Constant.KEY_JSON_PARAMS, jsonParams);
return map;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.rendering.impl;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException;
import de.hybris.platform.cms2.model.contents.components.AbstractCMSComponentModel;
import de.hybris.platform.cms2.servicelayer.data.CMSDataFactory;
import de.hybris.platform.cms2.servicelayer.data.RestrictionData;
import de.hybris.platform.cms2.servicelayer.services.CMSComponentService;
import de.hybris.platform.cmsfacades.common.service.RestrictionAwareService;
import de.hybris.platform.cmsfacades.common.validator.FacadeValidationService;
import de.hybris.platform.cmsfacades.data.AbstractCMSComponentData;
import de.hybris.platform.cmsfacades.exception.ValidationException;
import de.hybris.platform.cmsfacades.rendering.visibility.RenderingVisibilityService;
import de.hybris.platform.core.servicelayer.data.SearchPageData;
import de.hybris.platform.servicelayer.dto.converter.Converter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.validation.Errors;
import java.util.Arrays;
import java.util.Collections;
import java.util.Optional;
import java.util.function.Supplier;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class DefaultComponentRenderingServiceTest
{
public static final String COMPONENT_UID = "test-component-uid";
public static final String CATALOG_CODE = "catalog-electronics";
public static final String CATEGORY_CODE = "category-camera";
public static final String PRODUCT_CODE = "product-camera-battery";
@InjectMocks
private DefaultComponentRenderingService componentRenderingService;
@Mock
private FacadeValidationService facadeValidationService;
@Mock
private CMSDataFactory cmsDataFactory;
@Mock
private CMSComponentService cmsComponentService;
@Mock
private Converter<AbstractCMSComponentModel, AbstractCMSComponentData> componentRenderingConverter;
@Mock
private RestrictionAwareService restrictionAwareService;
@Mock
private RenderingVisibilityService renderingVisibilityService;
@Mock
private Errors errors;
@Mock
private AbstractCMSComponentModel componentModel;
@Mock
private AbstractCMSComponentData componentData;
@Mock
private RestrictionData restrictionData;
@Mock
private SearchPageData searchPageData;
@Before
public void setUp()
{
doAnswer((invocationOnMock) -> {
final Object[] args = invocationOnMock.getArguments();
return ((Supplier<?>) args[1]).get();
}).when(restrictionAwareService).execute(any(), any());
}
@Test(expected = ValidationException.class)
public void shouldFailGetComponentByIdWithValidationError() throws CMSItemNotFoundException
{
doThrow(new ValidationException(errors)).when(facadeValidationService).validate(any(), any());
componentRenderingService.getComponentById(COMPONENT_UID, CATEGORY_CODE, PRODUCT_CODE, CATALOG_CODE);
verifyZeroInteractions(cmsDataFactory);
}
@Test(expected = CMSItemNotFoundException.class)
public void shouldFailGetComponentByIdWithNotFoundError() throws CMSItemNotFoundException
{
when(cmsComponentService.getAbstractCMSComponent(COMPONENT_UID)).thenThrow(new CMSItemNotFoundException("invalid id"));
componentRenderingService.getComponentById(COMPONENT_UID, CATEGORY_CODE, PRODUCT_CODE, CATALOG_CODE);
verifyZeroInteractions(cmsDataFactory);
}
@Test
public void shouldGetComponentById() throws CMSItemNotFoundException
{
when(cmsComponentService.getAbstractCMSComponent(COMPONENT_UID)).thenReturn(componentModel);
doReturn(Optional.of(componentData)).when(restrictionAwareService).execute(any(), any());
componentRenderingService.getComponentById(COMPONENT_UID, CATEGORY_CODE, null, null);
verify(cmsDataFactory).createRestrictionData(CATEGORY_CODE, null, null);
verify(restrictionAwareService).execute(any(), any());
}
@Test
public void shouldGetComponentData()
{
when(renderingVisibilityService.isVisible(componentModel)).thenReturn(Boolean.TRUE);
when(componentRenderingConverter.convert(componentModel)).thenReturn(componentData);
final Optional<AbstractCMSComponentData> optionalData = componentRenderingService.getComponentData(componentModel,
restrictionData);
assertThat(optionalData.get(), not(nullValue()));
}
@Test
public void shouldGetEmptyComponentDataWhenComponentIsNotVisible()
{
when(renderingVisibilityService.isVisible(componentModel)).thenReturn(Boolean.FALSE);
final Optional<AbstractCMSComponentData> optionalData = componentRenderingService.getComponentData(componentModel,
restrictionData);
assertThat(optionalData, is(Optional.empty()));
verifyZeroInteractions(componentRenderingConverter);
}
@Test(expected = ValidationException.class)
public void shouldFailGetComponentsByIdsWithValidationError() throws CMSItemNotFoundException
{
doThrow(new ValidationException(errors)).when(facadeValidationService).validate(any(), any());
componentRenderingService.getComponentsByIds(Arrays.asList(COMPONENT_UID), CATEGORY_CODE, PRODUCT_CODE, CATALOG_CODE,
searchPageData);
verifyZeroInteractions(cmsDataFactory);
}
@Test
public void shouldGetZeroComponentsByIdsWhenItemsNotFound() throws CMSItemNotFoundException
{
final SearchPageData<AbstractCMSComponentModel> emptySearchPageData = mock(SearchPageData.class);
when(emptySearchPageData.getResults()).thenReturn(Collections.emptyList());
when(cmsComponentService.getAbstractCMSComponents(Arrays.asList(COMPONENT_UID), searchPageData))
.thenReturn(emptySearchPageData);
final SearchPageData<AbstractCMSComponentData> results = componentRenderingService
.getComponentsByIds(Arrays.asList(COMPONENT_UID), CATEGORY_CODE, PRODUCT_CODE, CATALOG_CODE, searchPageData);
assertThat(results.getResults(), empty());
verify(emptySearchPageData).getPagination();
verify(emptySearchPageData).getSorts();
}
@Test
public void shouldGetComponentsByIds() throws CMSItemNotFoundException
{
final SearchPageData<AbstractCMSComponentModel> mockSearchPageData = mock(SearchPageData.class);
when(mockSearchPageData.getResults()).thenReturn(Arrays.asList(componentModel));
when(cmsComponentService.getAbstractCMSComponents(Arrays.asList(COMPONENT_UID), searchPageData))
.thenReturn(mockSearchPageData);
when(renderingVisibilityService.isVisible(componentModel)).thenReturn(Boolean.TRUE);
when(componentRenderingConverter.convert(componentModel)).thenReturn(componentData);
final SearchPageData<AbstractCMSComponentData> results = componentRenderingService
.getComponentsByIds(Arrays.asList(COMPONENT_UID), CATEGORY_CODE, PRODUCT_CODE, CATALOG_CODE, searchPageData);
assertThat(results.getResults(), hasSize(1));
verify(mockSearchPageData).getPagination();
verify(mockSearchPageData).getSorts();
}
}
|
package textrpg.rooms;
/**
* User: katchk
* Date: 05.04.14
* Time: 18:10
*/
/*
* In the future this one and another one scenarios will be
* described in .txt or in other file format
* and will be readed and created dynamically using
* the JSON or other tools.
* I think it will be cool, because other users will
* be able to create and exchange their scenarios.
* */
public class ScenarioA {
Room startingRoom = new Room();
Room village = new Room();
Room wood = new Room();
Room lake = new Room();
public ScenarioA(){
startingRoom.setExits(village, null, null, null);
village.setExits(wood, startingRoom, lake, null);
wood.setExits(null, village, null, null );
lake.setExits(null, null, null, village);
setRoomsName();
setRoomsDescription();
}
private void setRoomsName(){
startingRoom.setRoomName("Training ground");
village.setRoomName("STARFIELD Village");
wood.setRoomName("The SHADOW GROVE");
lake.setRoomName("LAKE Of SOFIREAL");
}
private void setRoomsDescription(){
startingRoom.setRoomDescription("You are at the training ground, near some village. Your adventure starts!");
village.setRoomDescription("Gods forgotten place, near the SHADOW GROVE");
wood.setRoomDescription("Impregnated by rot and evilness air disturbs your mind...\nAnd it seems that you aren't alone here!");
lake.setRoomDescription("A warm breeze encircles your face ... and you fall in love with place");
}
public Room getStartingRoom(){
return startingRoom;
}
}
|
package com.cyyz.cy_system.common.mapper;
import com.cyyz.cy_system.domain.*;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @Author: SHZ
* @Description:
* @Date: Created in 2018-03-22 12:21
*/
public interface TestRepo {
@Select("SELECT * FROM sa_stampquote")
List<sa_StampQuote> CGetAllList();
@Delete("DELETE FROM sa_stampquote WHERE id =#{id}")
void delete(Long id);
}
|
package life;
import java.util.ArrayList;
import java.util.List;
public class Cell {
private final List<Cell> neigbours = new ArrayList<Cell>();
private final char c;
public Cell(char c) {
this.c = c;
}
public char value() {
return c;
}
public void addNeigbour(Cell cell) {
neigbours.add(cell);
}
}
|
package com.in_prototype.sample_android_image_creator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
/**
* Created by Dawid Konarkowski on 20.01.2016.
*/
public class MoveView extends FrameLayout {
boolean isMenu = true;
boolean isMenuCut = false;
MainActivity activity;
OnClickListener click = new OnClickListener() {
@Override
public void onClick(View view) {
showMenu();
}
};
ImageView main_image;
ImageView move_image;
FrameLayout move_menu;
FrameLayout move_menu_cut;
IcoTextView move_cut;
IcoTextView move_cut_yes;
IcoTextView move_cut_no;
IcoTextView move_trash;
IcoTextView move_center;
IcoTextView move_rotate;
IcoTextView move_size;
LayoutParams layoutParams;
float rotation = 0;
float centerX;
float centerY;
Bitmap showImage;
Bitmap imageTemp;
Bitmap imageStart;
Context context_;
public MoveView(Context context) {
super(context);
init(context);
}
public MoveView(Context context, MainActivity mainActivity) {
super(context);
activity = mainActivity;
init(context);
}
public MoveView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MoveView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
public static Bitmap makeTransparent(Bitmap bit, int transparentColor, int amplitude) {
int width = bit.getWidth();
int height = bit.getHeight();
Bitmap myBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int[] allpixels = new int[myBitmap.getHeight() * myBitmap.getWidth()];
bit.getPixels(allpixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
myBitmap.setPixels(allpixels, 0, width, 0, 0, width, height);
int //A,
R, G, B;
int //a = Color.alpha(transparentColor),
r = Color.red(transparentColor),
g = Color.green(transparentColor),
b = Color.blue(transparentColor);
for (int i = 0; i < myBitmap.getHeight() * myBitmap.getWidth(); i++) {
//A = Color.alpha(allpixels[i]);
R = Color.red(allpixels[i]);
G = Color.green(allpixels[i]);
B = Color.blue(allpixels[i]);
if (allpixels[i] == transparentColor
|| (
//(a-amplitude<=A && a+amplitude>=A)
(r - amplitude <= R && r + amplitude >= R)
&& (g - amplitude <= G && g + amplitude >= G)
&& (b - amplitude <= B && b + amplitude >= B)
)
)
allpixels[i] = Color.alpha(Color.TRANSPARENT);
}
myBitmap.setPixels(allpixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
return myBitmap;
}
void init(Context context) {
context_ = context;
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
move_image = new ImageView(context);
move_image.setLayoutParams(lp);
move_image.setImageBitmap(showImage);
addView(move_image);
move_menu = new FrameLayout(context);
move_menu.setLayoutParams(lp);
addView(move_menu);
move_menu_cut = new FrameLayout(context);
move_menu_cut.setLayoutParams(lp);
move_menu_cut.setVisibility(GONE);
addView(move_menu_cut);
lp = new LayoutParams((int) ImageUnit.dp_px(40, context), (int) ImageUnit.dp_px(40, context));
lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;
move_size = new IcoTextView(context);
move_size.setTextTypface("icomoon");
move_size.setTextSize((int) ImageUnit.dp_px(15, context));
move_size.setGravity(Gravity.CENTER);
move_size.setText("");
move_size.setTextColor(0xffffffff);
move_size.setLayoutParams(lp);
move_size.setBackgroundColor(0x66000000);
move_menu.addView(move_size);
lp = new LayoutParams((int) ImageUnit.dp_px(40, context), (int) ImageUnit.dp_px(40, context));
lp.gravity = Gravity.CENTER;
move_center = new IcoTextView(context);
move_center.setTextTypface("icomoon");
move_center.setTextSize((int) ImageUnit.dp_px(15, context));
move_center.setGravity(Gravity.CENTER);
move_center.setText("");
move_center.setTextColor(0xffffffff);
move_center.setLayoutParams(lp);
move_center.setBackgroundColor(0x66000000);
move_menu.addView(move_center);
lp = new LayoutParams((int) ImageUnit.dp_px(40, context), (int) ImageUnit.dp_px(40, context));
lp.gravity = Gravity.CENTER_HORIZONTAL;
move_rotate = new IcoTextView(context);
move_rotate.setTextTypface("icomoon");
move_rotate.setTextSize((int) ImageUnit.dp_px(15, context));
move_rotate.setGravity(Gravity.CENTER);
move_rotate.setText("");
move_rotate.setTextColor(0xffffffff);
move_rotate.setLayoutParams(lp);
move_rotate.setBackgroundColor(0x66000000);
move_menu.addView(move_rotate);
lp = new LayoutParams((int) ImageUnit.dp_px(40, context), (int) ImageUnit.dp_px(40, context));
move_cut = new IcoTextView(context);
move_cut.setTextTypface("icomoon");
move_cut.setTextSize((int) ImageUnit.dp_px(15, context));
move_cut.setGravity(Gravity.CENTER);
move_cut.setText("");
move_cut.setTextColor(0xffffffff);
move_cut.setLayoutParams(lp);
move_cut.setBackgroundColor(0x66000000);
move_menu.addView(move_cut);
lp = new LayoutParams((int) ImageUnit.dp_px(40, context), (int) ImageUnit.dp_px(40, context));
lp.gravity = Gravity.RIGHT;
move_trash = new IcoTextView(context);
move_trash.setTextTypface("icomoon");
move_trash.setTextSize((int) ImageUnit.dp_px(15, context));
move_trash.setGravity(Gravity.CENTER);
move_trash.setText("");
move_trash.setTextColor(0xffffffff);
move_trash.setLayoutParams(lp);
move_trash.setBackgroundColor(0x66000000);
move_menu.addView(move_trash);
lp = new LayoutParams((int) ImageUnit.dp_px(40, context), (int) ImageUnit.dp_px(40, context));
move_cut_no = new IcoTextView(context);
move_cut_no.setTextTypface("icomoon");
move_cut_no.setTextSize((int) ImageUnit.dp_px(15, context));
move_cut_no.setGravity(Gravity.CENTER);
move_cut_no.setText("");
move_cut_no.setTextColor(0xffffffff);
move_cut_no.setLayoutParams(lp);
move_cut_no.setBackgroundColor(0x66ff0000);
move_menu_cut.addView(move_cut_no);
lp = new LayoutParams((int) ImageUnit.dp_px(40, context), (int) ImageUnit.dp_px(40, context));
lp.leftMargin = (int) ImageUnit.dp_px(40, context);
move_cut_yes = new IcoTextView(context);
move_cut_yes.setTextTypface("icomoon");
move_cut_yes.setTextSize((int) ImageUnit.dp_px(15, context));
move_cut_yes.setGravity(Gravity.CENTER);
move_cut_yes.setText("");
move_cut_yes.setTextColor(0xffffffff);
move_cut_yes.setLayoutParams(lp);
move_cut_yes.setBackgroundColor(0x6600ff00);
move_menu_cut.addView(move_cut_yes);
setOnClickListener(click);
move_size.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
layoutParams = (LayoutParams) getLayoutParams();
centerX = (float) (layoutParams.leftMargin + getMeasuredWidth() / 2.0);
centerY = (float) (layoutParams.topMargin + getMeasuredHeight() / 2.0);
}
float alpha = direction(centerX, centerY + 120, motionEvent.getRawX(), motionEvent.getRawY());
float rotate = (alpha + rotation) % 360;
float vector = vector(centerX, centerY + 120, motionEvent.getRawX(), motionEvent.getRawY());
float height = (float) (Math.cos(Math.toRadians(rotate)) * vector * 2 + move_size.getMeasuredWidth() / 2.0);
float width = (float) (Math.sin(Math.toRadians(rotate)) * vector * 2 + move_size.getMeasuredHeight() / 2.0);
if (width < ImageUnit.dp_px(150, context_)) width = ImageUnit.dp_px(150, context_);
if (height < ImageUnit.dp_px(150, context_))
height = ImageUnit.dp_px(150, context_);
resize(centerX, centerY, width, height);
return true;
}
});
move_center.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
layoutParams = (LayoutParams) getLayoutParams();
}
layoutParams.leftMargin = (int) (motionEvent.getRawX() - getWidth() / 2.0);
layoutParams.topMargin = (int) (motionEvent.getRawY() - getHeight() / 2.0 - 120);
setLayoutParams(layoutParams);
return true;
}
});
move_rotate.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
layoutParams = (LayoutParams) getLayoutParams();
centerX = (float) (layoutParams.leftMargin + getMeasuredWidth() / 2.0);
centerY = (float) (layoutParams.topMargin + getMeasuredHeight() / 2.0 + 120);
}
float alpha = direction(centerX, centerY, motionEvent.getRawX(), motionEvent.getRawY());
float rotate = 360 - (alpha + 180) % 360;
rotation = rotate;
setRotation(rotation);
return true;
}
});
move_cut.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
imageStart = showImage;
showMenuCut();
return true;
}
});
move_cut_no.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
imageTemp = null;
move_image.setImageBitmap(showImage);
showMenuCut();
}
});
move_cut_yes.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
showImage = imageTemp;
imageTemp = null;
move_image.setImageBitmap(showImage);
showMenuCut();
}
});
move_trash.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
activity.removeItem(MoveView.this);
}
});
move_menu_cut.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Bitmap viewBitmap = ImageUnit.getViewBitmap(MoveView.this);
try {
if (viewBitmap != null) {
//Log.e("position", String.format("x = %8.2f | y = %8.2f", motionEvent.getX(), motionEvent.getY()));
int pixel = viewBitmap.getPixel((int) motionEvent.getX(), (int) motionEvent.getY());
//removeColor(imageTemp!=null?imageTemp:showImage,pixel);
imageTemp = makeTransparent(imageTemp != null ? imageTemp : imageStart, pixel, (int) (255 * 0.01));
//changeColor(imageTemp!=null?imageTemp:showImage,pixel+0xff000000,0x00000000);
move_image.setImageBitmap(imageTemp);
}
} catch (Exception e) {
}
return true;
}
});
}
public void setImage(Bitmap bitmap) {
showImage = bitmap;
move_image.setImageBitmap(showImage);
layoutParams = (LayoutParams) getLayoutParams();
centerX = (float) (layoutParams.leftMargin + layoutParams.width / 2.0);
centerY = (float) (layoutParams.topMargin + layoutParams.height / 2.0);
resize(centerX, centerY + 120, layoutParams.width, layoutParams.height);
}
float vector(float xA, float yA, float xB, float yB) {
float a, b = 0;
a = xB - xA;
b = yB - yA;
return (float) Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
void resize(float centerX, float centerY, float wight, float height) {
int w = showImage.getWidth();
int h = showImage.getHeight();
float resizeW = wight / w;
float resizeH = height / h;
float resize = Math.min(resizeW, resizeH);
wight = resize * w;
height = resize * h;
layoutParams.leftMargin = (int) (centerX - (wight / 2.0));
layoutParams.topMargin = (int) (centerY - (height / 2.0));
layoutParams.height = (int) height;
layoutParams.width = (int) wight;
setLayoutParams(layoutParams);
}
float direction(float xA, float yA, float xB, float yB) {
float beta = 0;
float a, b = 0;
a = xB - xA;
b = yB - yA;
beta = (float) (Math.atan2(a, b) * 180.0 / Math.PI);
if (beta < 0.0)
beta += 360.0;
else if (beta > 360.0)
beta -= 360;
return beta;
}
void showMenu() {
if (isMenu) {
isMenu = false;
move_menu.setVisibility(GONE);
} else {
if (activity != null)
for (MoveView object : activity.items) {
object.hideMenu();
}
isMenu = true;
move_menu.setVisibility(VISIBLE);
activity.setItemTop(this);
}
}
void hideMenu() {
if (isMenu) {
isMenu = false;
move_menu.setVisibility(GONE);
}
if (isMenuCut) {
isMenuCut = false;
move_menu_cut.setVisibility(GONE);
}
}
void showMenuCut() {
if (isMenuCut) {
isMenuCut = false;
move_menu_cut.setVisibility(GONE);
showMenu();
} else {
showMenu();
isMenuCut = true;
move_menu_cut.setVisibility(VISIBLE);
}
}
////
@Override
public Parcelable onSaveInstanceState() {
Log.e("MoveView", "onSaveInstanceState");
Bundle bundle = new Bundle();
bundle.putParcelable("instanceState", super.onSaveInstanceState());
bundle.putFloat("rotation", rotation);
layoutParams = (LayoutParams) getLayoutParams();
bundle.putInt("leftMargin", layoutParams.leftMargin);
bundle.putInt("topMargin", layoutParams.topMargin);
bundle.putInt("height", layoutParams.height);
bundle.putInt("width", layoutParams.width);
bundle.putParcelable("image", showImage);
// ... save everything
return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
Log.e("MoveView", "onRestoreInstanceState");
if (state instanceof Bundle) {
Bundle bundle = (Bundle) state;
layoutParams = (LayoutParams) getLayoutParams();
layoutParams.leftMargin = bundle.getInt("leftMargin");
layoutParams.topMargin = bundle.getInt("topMargin");
layoutParams.height = bundle.getInt("height");
layoutParams.width = bundle.getInt("width");
setLayoutParams(layoutParams);
rotation = bundle.getFloat("rotation");
setRotation(rotation);
showImage = bundle.getParcelable("image");
move_image.setImageBitmap(showImage);
state = bundle.getParcelable("instanceState");
}
super.onRestoreInstanceState(state);
}
}
|
package com.rudecrab.springsecurity.security;
import com.rudecrab.springsecurity.model.entity.Resource;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
* @author RudeCrab
*/
@Slf4j
@Component
public class MySecurityMetadataSource implements SecurityMetadataSource {
/**
* 当前系统所有url资源
*/
@Getter
private static final Set<Resource> RESOURCES = new HashSet<>();
@Override
public Collection<ConfigAttribute> getAttributes(Object object) {
log.info("---MySecurityMetadataSource---");
// 该对象是Spring Security帮我们封装好的,可以通过该对象获取request等信息
FilterInvocation filterInvocation = (FilterInvocation) object;
HttpServletRequest request = filterInvocation.getRequest();
// 遍历所有权限资源,以和当前请求所需的权限进行匹配
for (Resource resource : RESOURCES) {
// 因为我们url资源是这种格式:GET:/API/user/test/{id},冒号前面是请求方法,冒号后面是请求路径,所以要字符串拆分
String[] split = resource.getPath().split(":");
// 因为/API/user/test/{id}这种路径参数不能直接equals来判断请求路径是否匹配,所以需要用Ant类来匹配
AntPathRequestMatcher ant = new AntPathRequestMatcher(split[1]);
// 如果请求方法和请求路径都匹配上了,则代表找到了这个请求所需的权限资源
if (request.getMethod().equals(split[0]) && ant.matches(request)) {
// 将我们权限资源id返回
return Collections.singletonList(new SecurityConfig(resource.getId().toString()));
}
}
// 走到这里就代表该请求无需授权即可访问,返回空
return null;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> clazz) {
return true;
}
}
|
package trivago.util;
import trivagoTestPages.BaseTest;
public class TestUtil extends BaseTest{
public TestUtil() {
super();
}
public static long PAGE_LOAD_TIMEOUT = 20;
public static long IMPLICIT_WAIT = 10;
}
|
package auth;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.net.Socket;
import org.apache.commons.io.IOUtils;
/**
*
* Ejecuta un nuevo hilo para procesar una conexion entrante
*/
public class Hilo implements Runnable {
/** Referencia a la conexion entrante */
protected Socket clientSocket = null;
/** Texto informando un cambio de estado */
protected String serverText = null;
/**
* Método constructor.
* @param clientSocket socket inicializado en Servidor
* @param serverText texto informativo con propositos de logging
*/
public Hilo(Socket clientSocket, String serverText) {
this.clientSocket = clientSocket;
this.serverText = serverText;
}
/**
* Corre un nuevo hilo.
*/
public void run() {
try {
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
// usando libs de apache IOUtils
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
String inputString = writer.toString();
String ip = clientSocket.getInetAddress().toString().substring(1);
CreadorMensaje factory= new CreadorMensaje();
Mensaje mensaje = factory.crearMensaje(inputString, ip);
output.write(mensaje.getRespuesta().getBytes());
output.close();
input.close();
System.out.println("Request processed: " + time);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
/**
*
*/
package com.cnk.travelogix.v2.controller;
import de.hybris.platform.commercefacades.user.data.CountryData;
import de.hybris.platform.commercewebservicescommons.dto.user.CountryWsDTO;
import de.hybris.platform.webservicescommons.cache.CacheControl;
import de.hybris.platform.webservicescommons.cache.CacheControlDirective;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cnk.travelogix.supplier.credentials.data.SupplierCredentialsData;
import com.cnk.travelogix.supplier.credentials.dto.SupplierCredentialsWsDTO;
import com.cnk.travelogix.supplier.credentials.facade.SupplierCredentialsFacade;
import com.cnk.travelogix.supplier.mapping.data.CityData;
import com.cnk.travelogix.supplier.mapping.dto.CityWsDTO;
import com.cnk.travelogix.supplier.mapping.facade.SupplierMappingFacade;
/**
* This controller class manages supplier related functionalities
*
* @author I077988
*
*/
@Controller
@RequestMapping(value = "/{baseSiteId}/suppliers")
@CacheControl(directive = CacheControlDirective.PRIVATE)
public class CustomSupplierController extends BaseCommerceController {
private static final Logger LOG = LoggerFactory.getLogger(CustomSupplierController.class);
@Autowired
private SupplierMappingFacade supplierMappingFacade;
@Autowired
private SupplierCredentialsFacade supplierCredentialsFacade;
@Secured({ "ROLE_CUSTOMERGROUP", "ROLE_TRUSTED_CLIENT", "ROLE_CUSTOMERMANAGERGROUP" })
@RequestMapping(value = "/credentials/{supplierCredId}", method = RequestMethod.GET)
@ResponseBody
public SupplierCredentialsWsDTO getSupplierCredentials(@PathVariable final String supplierCredId) {
LOG.info("#getSupplierCredentials - Start");
LOG.debug("#getSupplierCredentials - SupplierCredId:{}", supplierCredId);
final SupplierCredentialsData supplierCredentialsData = supplierCredentialsFacade.getSupplierCredentialsById(supplierCredId);
final SupplierCredentialsWsDTO supplierCredentialsWsDTO = getDataMapper().map(supplierCredentialsData, SupplierCredentialsWsDTO.class);
LOG.info("#getSupplierCredentials - Finish");
return supplierCredentialsWsDTO;
}
@Secured({ "ROLE_CUSTOMERGROUP", "ROLE_TRUSTED_CLIENT", "ROLE_CUSTOMERMANAGERGROUP" })
@RequestMapping(value = "/{supplierId}/citymapping/{supplierCity}", method = RequestMethod.GET)
@ResponseBody
public CityWsDTO getSupplierCityMapping(@PathVariable("supplierId") final String supplierId,
@PathVariable("supplierCity") final String supplierCity,
@RequestParam(value = "supplierCountry", required = false) String supplierCountry) {
LOG.info("#getSupplierCityMapping - Start");
LOG.debug("#getSupplierCityMapping - SupplierId:{}, SupplierCity:{}, SupplierCountry:{}", supplierId, supplierCity, supplierCountry);
final CityData cityData = supplierMappingFacade.getSupplierCityMapping(supplierId, supplierCity, supplierCountry);
final CityWsDTO cityWsDto = getDataMapper().map(cityData, CityWsDTO.class);
LOG.info("#getSupplierCityMapping - Finish");
return cityWsDto;
}
@Secured({ "ROLE_CUSTOMERGROUP", "ROLE_TRUSTED_CLIENT", "ROLE_CUSTOMERMANAGERGROUP" })
@RequestMapping(value = "/{supplierId}/countrymapping/{supplierCountry}", method = RequestMethod.GET)
@ResponseBody
public CountryWsDTO getSupplierCountryMapping(@PathVariable("supplierId") final String supplierId,
@PathVariable("supplierCountry") final String supplierCountry) {
LOG.info("#getSupplierCountryMapping - Start");
LOG.debug("#getSupplierCountryMapping - SupplierId:{}, SupplierCountry:{}", supplierId, supplierCountry);
final CountryData countData = supplierMappingFacade.getSupplierCountryMapping(supplierId, supplierCountry);
final CountryWsDTO countryWsDto = getDataMapper().map(countData, CountryWsDTO.class);
LOG.info("#getSupplierCountryMapping - Finish");
return countryWsDto;
}
}
|
package lecture14Cuncurrent;
import java.io.File;
import java.lang.reflect.Proxy;
import java.util.concurrent.atomic.AtomicInteger;
public class CacheProxy {
public static volatile AtomicInteger ramCacheCount = new AtomicInteger(0);
public static volatile AtomicInteger fileCacheCount = new AtomicInteger(0);
public static Object cache (Object delegate){
return cache (delegate, new File ("cache"));
}
public static Object cache (Object delegate , File directoryCache){
return Proxy.newProxyInstance (ClassLoader.getSystemClassLoader(), delegate.getClass().getInterfaces(),
new CacheableInvocationHandler(delegate ,directoryCache));
}
}
|
package com.yinghai.a24divine_user.module.order.detail.mvp;
import com.example.fansonlib.base.BaseModel;
import com.example.fansonlib.http.HttpResponseCallback;
import com.example.fansonlib.http.HttpUtils;
import com.example.fansonlib.utils.SharePreferenceHelper;
import com.yinghai.a24divine_user.bean.NoDataBean;
import com.yinghai.a24divine_user.constant.ConHttp;
import com.yinghai.a24divine_user.constant.ConResultCode;
import com.yinghai.a24divine_user.constant.ConstantPreference;
import com.yinghai.a24divine_user.utils.ValidateAPITokenUtil;
import java.util.HashMap;
import java.util.Map;
/**
* @author Created by:fanson
* Created Time: 2017/11/18 18:10
* Describe:取消占卜订单M层
*/
public class CancelOrderModel extends BaseModel implements ContractOrderDetail.IModel{
private ICancelCallback mCallback;
@Override
public void cancelOrder(int orderId,int type, ICancelCallback callback) {
mCallback = callback;
String time = String.valueOf(System.currentTimeMillis());
Map<String,Object> maps = new HashMap<>(4);
maps.put("userId", SharePreferenceHelper.getInt(ConstantPreference.I_USER_ID,0));
maps.put("orderId",orderId);
maps.put("type",type);
maps.put("apiSendTime", time);
maps.put("apiToken", ValidateAPITokenUtil.ctreatTokenStringByTimeString(time));
HttpUtils.getHttpUtils().post(ConHttp.CANCEL_ORDER,maps, new HttpResponseCallback<NoDataBean>() {
@Override
public void onSuccess(NoDataBean bean) {
if (mCallback ==null){
return;
}
switch (bean.getCode()) {
case ConResultCode.SUCCESS:
mCallback.onCancelSuccess(bean);
break;
default:
mCallback.handlerResultCode(bean.getCode());
break;
}
}
@Override
public void onFailure(String errorMsg) {
if (mCallback!=null){
mCallback.onCancelFailure(errorMsg);
}
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
mCallback = null;
}
}
|
/*
* 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 pt.mleiria.mlalgo.preprocess;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import static java.lang.Math.sqrt;
/**
* is a transformer and a estimator
*
* @author manuel
*/
public class StandardScaler extends BaseTransformer {
/**
* Compute the mean and std to be used for later scaling.
*
* @param xTrain
* @return
*/
@Override
public StandardScaler fit(final Double[][] xTrain) {
final int rows = xTrain.length;
final int cols = xTrain[0].length;
sm = new SummaryStatistics[cols];
for (int j = 0; j < cols; j++) {
sm[j] = new SummaryStatistics();
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sm[j].addValue(xTrain[i][j]);
}
}
return this;
}
/**
*
*/
@Override
public Double[][] transform(Double[][] xTrain) {
final int rows = xTrain.length;
final int cols = xTrain[0].length;
final Double[][] transformed = new Double[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transformed[i][j] = (xTrain[i][j] - sm[j].getMean()) / sqrt(sm[j].getPopulationVariance());
}
}
return transformed;
}
/**
*
*/
@Override
public Double[][] fitTransform(Double[][] xTrain) {
return fit(xTrain).transform(xTrain);
}
}
|
package net.exacode.bootstrap.web.config;
public class ApplicationProfiles {
public static final String DEVELOPMENT = "development";
public static final String TEST = "test";
public static final String PRODUCTION = "production";
}
|
package rontikeky.beraspakone.Fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import rontikeky.beraspakone.R;
/**
* A simple {@link Fragment} subclass.
*/
public class fragment_riwayat_pemesanan extends Fragment {
Button btnCari, btnDetail;
Spinner cmbTahun, cmbBulan;
TextView dateHistory;
TableLayout tblHistory;
public fragment_riwayat_pemesanan() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_riwayat_pemesanan, container, false);
dateHistory = view.findViewById(R.id.txtDate);
btnCari = view.findViewById(R.id.sbmtHistory);
btnCari.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
history(view);
}
});
btnDetail = view.findViewById(R.id.btnDetailHistory);
btnCari.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DetailHistory(view);
}
});
return view;
}
public void history(View view) {
}
public void DetailHistory (View view) {
}
}
|
package com.houzhi.send.analyse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.jfree.data.time.Millisecond;
import com.houzhi.show.jfreeChar.LinePicturePerTime;
import be.ac.ulg.montefiore.run.jahmm.Hmm;
import be.ac.ulg.montefiore.run.jahmm.ObservationInteger;
import be.ac.ulg.montefiore.run.jahmm.ObservationVector;
import be.ac.ulg.montefiore.run.jahmm.OpdfMultiGaussianFactory;
import be.ac.ulg.montefiore.run.jahmm.io.FileFormatException;
import be.ac.ulg.montefiore.run.jahmm.io.HmmReader;
import be.ac.ulg.montefiore.run.jahmm.io.OpdfIntegerReader;
import be.ac.ulg.montefiore.run.jahmm.io.OpdfMultiGaussianReader;
import be.ac.ulg.montefiore.run.jahmm.learn.KMeansLearner;
public class OldManDetection {
private Hmm<ObservationVector> hmm;
/**
* 利用k-means 算法获取初始的隐马尔科夫模型
* @param sequences 观察序列
* @return
*/
public Hmm<ObservationVector> kMeansLearn(List<List<? extends ObservationVector>> sequences){
KMeansLearner<ObservationVector> kmlVec =
new KMeansLearner<>(Constant.STATES_NUMS, new OpdfOldManDetectionFactory(3),
sequences);
hmm = kmlVec.iterate();
return hmm;
}
public OldManDetection(String filename){
Reader r;
try {
r = new InputStreamReader(new FileInputStream(filename));
hmm = HmmReader.read(r, new OpdfMultiGaussianReader());
System.out.println(hmm);
} catch (FileFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int analysis(LinkedHashMap<String, Long> data){
List<ObservationVector> seq = new ArrayList<ObservationVector>(); //内存的List
System.out.println("map size:"+data.size());
double[] d = new double[data.size()];
int i = 0;
for(Map.Entry<String, Long> entry : data.entrySet()){//按顺序否?
d[i++] = entry.getValue();
}
ObservationVector vector = new ObservationVector(d);
seq.add(vector);
System.out.println("seq 长度:"+seq.size());
System.out.println(seq);
Map<String, Long> mapTemp = new HashMap<>();
mapTemp.put("status", 0l);
LinePicturePerTime linePicturePerTime =null;
int [] r = hmm.mostLikelyStateSequence(seq);
return r[0];
// for(i=0;i!=r.length;++i){
// for(int j = 0; j!=Constant.STATES_NUMS;++j){
// mapTemp.put("status"+j, new Long(j));
// }
// mapTemp.put("status", new Long(r[i]));
// if(linePicturePerTime ==null){
//
// linePicturePerTime = new LinePicturePerTime(mapTemp);
// }else{
// linePicturePerTime.addData(new Millisecond(listDate.get(i)), mapTemp);
// }
// }
}
}
|
/**
* MainMenuState
*
* This is the state for the main menu
* Makes clickable menu button things
* Mostly taken from a tutorial
*
*/
package com.cyclight;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class MainMenuState extends BasicGameState {
int stateID = -1;
Image background = null;
Image startGameOption = null;
Image exitOption = null;
float scaleStep = 0.0001f;
private static int titleX = 112;
private static int titleY = 84;
private static int menuX = titleX + 210;
private static int menuY = titleY + 325;
private static int menuOffset = 100;
float startGameScale = 1;
float exitScale = 1;
MainMenuState(int stateID) {
this.stateID = stateID;
}
@Override
public int getID() {
return stateID;
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
// load the menu images
background = new Image("res/menu.png");
Image menuOptions = new Image("res/menuoptions.png");
// Image (startX, startY, height, width)
startGameOption = menuOptions.getSubImage(0, 0, 377, 71);
exitOption = menuOptions.getSubImage(0, 71, 377, 71);
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
// render the background
background.draw(112, 84);
// Draw menu
startGameOption.draw(menuX, menuY, startGameScale);
exitOption.draw(menuX - menuOffset, menuY + menuOffset, exitScale);
}
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
int mouseX = input.getMouseX();
int mouseY = input.getMouseY();
boolean insideStartGame = false;
boolean insideExit = false;
insideStartGame = collidesWith(mouseX, mouseY, menuX, menuY, startGameOption.getWidth(),
startGameOption.getHeight());
insideExit = collidesWith(mouseX, mouseY, menuX + menuOffset, menuY + menuOffset, exitOption.getWidth(),
exitOption.getHeight());
if (insideStartGame)
{
if (startGameScale < 1.05f)
startGameScale += (scaleStep * delta);
if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON))
{
sbg.enterState(stateBasedGameTest.GAMEPLAYSTATE);
}
}
else
{
if (startGameScale > 1.0f)
startGameScale -= scaleStep * delta;
}
if (insideExit)
{
if (exitScale < 1.05f)
exitScale += scaleStep * delta;
if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON))
gc.exit();
}
else
{
if (exitScale > 1.0f)
exitScale -= scaleStep * delta;
}
}
public boolean collidesWith(int mouseX, int mouseY, int menuX, int menuY, int width, int height) {
boolean collision = false;
if ((mouseX >= menuX && mouseX <= menuX + width) && (mouseY >= menuY && mouseY <= menuY + height))
collision = true;
return collision;
}
}
|
/*
* Copyright (c) 2020, Matthew Weis, Kansas State University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.sireum.hamr.inspector.services.jvm;
import art.Bridge;
import art.DataContent;
import art.UPort;
import org.jetbrains.annotations.NotNull;
import org.sireum.hamr.inspector.capabilities.jvm.JvmProjectListener;
import org.sireum.hamr.inspector.common.ArtUtils;
import org.sireum.hamr.inspector.common.Msg;
import org.sireum.hamr.inspector.services.MsgService;
import org.sireum.hamr.inspector.services.RecordId;
import org.sireum.hamr.inspector.services.Session;
import org.springframework.data.domain.Range;
import org.springframework.stereotype.Component;
import reactor.core.publisher.*;
import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicLong;
@Component
public class MsgServiceJvm implements MsgService {
private static AtomicLong msgCounter = new AtomicLong();
private static final Flux<Msg> msgFlux;
private static final FluxSink<Msg> msgSink;
static {
final FluxProcessor<Msg, Msg> msgProcessor = ReplayProcessor.create();
msgSink = msgProcessor.sink(FluxSink.OverflowStrategy.BUFFER);
msgFlux = msgProcessor.takeUntilOther(SessionServiceJvm.stopProcessor.then());
}
private static volatile ArtUtils artUtils;
@PostConstruct
private void postConstruct() {
JvmProjectListener.serviceCountDownLatch().countDown();
}
public MsgServiceJvm(ArtUtils artUtils) {
MsgServiceJvm.artUtils = artUtils;
}
public synchronized static void commitNextMsg(int srcPortId, int dstPortId, @NotNull DataContent data, long time) {
final long uid = msgCounter.getAndIncrement();
final UPort src = artUtils.getPort(srcPortId);
final UPort dst = artUtils.getPort(dstPortId);
final Bridge srcBridge = artUtils.getBridge(src);
final Bridge dstBridge = artUtils.getBridge(dst);
msgSink.next(new Msg(src, dst, srcBridge, dstBridge, data, time, uid));
}
@Override
public @NotNull Mono<Long> count(@NotNull Session session) {
return Mono.just(msgCounter.longValue());
}
// todo mock range on jvm - currently just returns all for jvm impl
@Override
public @NotNull Flux<Msg> live(@NotNull Session session, @NotNull Range<RecordId> range) {
return msgFlux;
}
@Override
public @NotNull Flux<Msg> replay(@NotNull Session session, @NotNull Range<RecordId> range) {
return msgFlux.take(msgCounter.longValue());
}
@Override
public @NotNull Flux<Msg> replayReverse(@NotNull Session session, @NotNull Range<RecordId> range) {
throw new UnsupportedOperationException("todo for jvm");
}
}
|
public class NodeList{
Node nextNode = null;
Node previousNode = null;
}
|
package cn.creable.android.demo2;
import java.util.Timer;
import java.util.TimerTask;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.Toast;
import cn.creable.gridgis.controls.App;
import cn.creable.gridgis.controls.ICustomDraw;
import cn.creable.gridgis.controls.ICustomDrawDataCenter;
import cn.creable.gridgis.controls.MapControl;
import cn.creable.gridgis.display.IDisplayTransformation;
import cn.creable.gridgis.geometry.IEnvelope;
import cn.creable.gridgis.geometry.IGeometry;
import cn.creable.gridgis.geometry.Point;
import cn.creable.gridgis.util.Image;
import cn.creable.ucmap.LBS;
import cn.creable.ucmap.OpenSourceMapLayer;
public class GPSCustomDraw implements ICustomDraw,LocationListener,ICustomDrawDataCenter {
private MapControl mapControl;
public double lon,lat;
public double acc;//是范围,只有基站定位的数据才有这个值
public double x,y;
private Image gps;
// private Image gps1;
// private boolean flag;
private Paint paint;
private IDisplayTransformation dt;
// private MyTimerTask timer;
private LBS lbs;
// private class MyTimerTask extends TimerTask
// {
//
// @Override
// public void run() {
// if (lon!=0 && lat!=0 && mapControl.noCustomDraw==false)
// mapControl.repaint();
// }
//
// }
/**
* 根据给定的中心点和半径,在地图上画一个圆
* @param layer google图层
* @param dt 转换坐标对象
* @param g Canvas对象
* @param paint paint对象
* @param x 中心点,单位是度
* @param y 中心点
* @param radius 半径,单位是米
*/
private void drawCircle(OpenSourceMapLayer layer,IDisplayTransformation dt,Canvas g,Paint paint,double x,double y,float radius)
{
if (layer==null)
{//不含有google图层时的处理
double dis=0;
float radius1=0;
if (mapControl.getMap().getMapUnits()==1)//如果地图采用度为单位
{
dis=radius*180/(6370693.4856530580439461631130889*Math.PI);//将以米为单位的距离转换为以度为单位的距离
}
else//如果地图不采用度为单位
dis=radius;
radius1=dt.TransformMeasures((float)dis, false);//将以地图上距离转换为屏幕上距离
Point result=new Point();
Point pt=new Point(x,y);
dt.fromMapPoint(pt, result);//将中心点转换为屏幕上的点
paint.setStyle(Paint.Style.FILL);
paint.setColor(0x2E0087FF);
g.drawCircle((float)result.getX(), (float)result.getY(), radius1, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(0xBF84B6D6);
g.drawCircle((float)result.getX(), (float)result.getY(), radius1, paint);
}
else
{//含有google图层时的处理
double dis=radius*180/(6370693.4856530580439461631130889*Math.PI);//将以米为单位的距离转换为以度为单位的距离
Point pt1=layer.fromLonLat(x, y);
Point pt2=layer.fromLonLat(x+dis, y);
double dis2=Math.abs(pt2.getX()-pt1.getX());//将以度为单位的距离转换为google坐标上的距离
float radius1=dt.TransformMeasures((float)dis2, false);//将以google坐标为单位的距离转换为屏幕上距离
Point result=new Point();
Point pt=layer.fromLonLat(x, y);
Point offset=layer.getOffset(x, y);
pt.setX(pt.getX()+offset.getX());
pt.setY(pt.getY()+offset.getY());
dt.fromMapPoint(pt, result);//将中心点转换为屏幕上的点
paint.setStyle(Paint.Style.FILL);
paint.setColor(0x2E0087FF);
g.drawCircle((float)result.getX(), (float)result.getY(), radius1, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(0xBF84B6D6);
g.drawCircle((float)result.getX(), (float)result.getY(), radius1, paint);
}
}
public GPSCustomDraw(MapControl mapControl)
{
this.mapControl=mapControl;
dt=mapControl.getDisplay().getDisplayTransformation();
paint=new Paint();
paint.setAntiAlias(true);
BitmapDrawable bmpDraw=(BitmapDrawable)App.getInstance().getResources().getDrawable(R.drawable.gps);
gps=new Image(bmpDraw.getBitmap());
// bmpDraw=(BitmapDrawable)App.getInstance().getResources().getDrawable(R.drawable.gps1);
// gps1=new Image(bmpDraw.getBitmap());
// Timer myTimer = new Timer();
// timer=new MyTimerTask();
// myTimer.schedule(timer, 500, 500);
lbs=new LBS(App.getInstance());
lbs.openGPS(1000, 0.01f, this);
lbs.getPositionByNetwork(this);
}
public void close()
{
lbs.closeGPS(this);
x=0;
y=0;
mapControl.repaint();
}
@Override
public void draw(Canvas g) {
if (x!=0 && y!=0)
{
Point pt=new Point(x,y);
Point result=new Point();
dt=mapControl.getDisplay().getDisplayTransformation();
dt.fromMapPoint(pt, result);//将图上坐标转换为屏幕坐标
gps.draw(g, (int)result.getX()-gps.getWidth()/2, (int)result.getY()-gps.getWidth()/2, null);
OpenSourceMapLayer oslayer=null;
if (mapControl.getMap().getLayerCount()>0 && mapControl.getMap().getLayer(0) instanceof OpenSourceMapLayer)
oslayer=(OpenSourceMapLayer)mapControl.getMap().getLayer(0);
if (acc>0) drawCircle(oslayer,dt,g,paint,lon,lat,(float)acc);
pt=null;
result=null;
}
}
@Override
public void onLocationChanged(Location location) {
lon=location.getLongitude();
lat=location.getLatitude();
acc=location.getAccuracy();
//将经纬度转换为图上坐标
if (mapControl.getMap().getLayerCount()>0 && mapControl.getMap().getLayer(0) instanceof OpenSourceMapLayer)
{
OpenSourceMapLayer oslayer=(OpenSourceMapLayer)mapControl.getMap().getLayer(0);
Point offset=oslayer.getOffset(lon, lat);
Point pt=oslayer.fromLonLat(lon, lat);
x=pt.getX()+offset.getX();
y=pt.getY()+offset.getY();
}
else
{
x=lon;
y=lat;
}
IEnvelope env=mapControl.getExtent();
if (env.getXMin()>x || env.getYMax()<x || env.getYMin()>y || env.getYMax()<y)
{
Point pt=new Point(x,y);
env.centerAt(pt);
mapControl.refresh(env);
}
else
mapControl.repaint();
}
@Override
public void onProviderDisabled(String arg0) {
}
@Override
public void onProviderEnabled(String arg0) {
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
@Override
public IGeometry getGeometry(int index) {
return new Point(x,y);
}
@Override
public int getGeometryNum() {
return 1;
}
@Override
public void onGeometrySelected(int index, IGeometry geometry) {
Toast.makeText(App.getInstance().getApplicationContext(), index+" "+geometry, 100).show();
}
}
|
package api.longpoll.bots.methods.impl.messages;
import api.longpoll.bots.http.params.AttachableParam;
import api.longpoll.bots.http.params.BoolInt;
import api.longpoll.bots.methods.AuthorizedVkApiMethod;
import api.longpoll.bots.methods.VkApiProperties;
import api.longpoll.bots.model.response.IntegerResponse;
import java.util.Arrays;
import java.util.List;
/**
* Implements <b>messages.edit</b> method.
* <p>
* Edits the message.
*
* @see <a href="https://vk.com/dev/messages.edit">https://vk.com/dev/messages.edit</a>
*/
public class Edit extends AuthorizedVkApiMethod<IntegerResponse> {
public Edit(String accessToken) {
super(accessToken);
}
@Override
protected String getUrl() {
return VkApiProperties.get("messages.edit");
}
@Override
protected Class<IntegerResponse> getResponseType() {
return IntegerResponse.class;
}
public Edit setAttachments(AttachableParam... attachments) {
return setAttachments(Arrays.asList(attachments));
}
public Edit setAttachments(List<AttachableParam> attachments) {
return addParam("attachment", attachments);
}
public Edit setPeerId(int peerId) {
return addParam("peer_id", peerId);
}
public Edit setMessage(String message) {
return addParam("message", message);
}
public Edit setLatitude(float latitude) {
return addParam("lat", latitude);
}
public Edit setLongitude(float longitude) {
return addParam("long", longitude);
}
public Edit setKeepForwardMessages(boolean keepForwardMessages) {
return addParam("keep_forward_messages", new BoolInt(keepForwardMessages));
}
public Edit setKeepSnippets(boolean keepSnippets) {
return addParam("keep_snippets", new BoolInt(keepSnippets));
}
public Edit setGroupId(int groupId) {
return addParam("group_id", groupId);
}
public Edit setDontParseLinks(boolean dontParseLinks) {
return addParam("dont_parse_links", new BoolInt(dontParseLinks));
}
public Edit setMessageId(int messageId) {
return addParam("message_id", messageId);
}
public Edit setConversationMessageId(int conversationMessageId) {
return addParam("conversation_message_id", conversationMessageId);
}
@Override
public Edit addParam(String key, Object value) {
return (Edit) super.addParam(key, value);
}
}
|
package pl.sidor;
import pl.sidor.model.Book;
import pl.sidor.service.BookDAOImpl;
import java.util.List;
public class Test {
public static void main(String[] args) {
// AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(WebConfig.class);
BookDAOImpl bookDAO = new BookDAOImpl();
List<Book> allBook = bookDAO.getAllBook();
allBook.forEach(e -> System.out.println(e.getTitle()));
Book book = bookDAO.findBook("Java Podstawy");
System.out.println(book.getAuthor());
// Kontekst
}
}
|
package welcome;
public class StackImp {
int sizeMax;
int top;
String arr[];
public StackImp(int n)
{
sizeMax=n;
arr=new String[sizeMax];
top=0;
}
public void push(String str)
{
if(top<sizeMax)
{
arr[top]=str;
top++;
System.out.println("element is pushed "+str);
}
else
{
System.out.println("Stack overflow..");
}
}
public String peek()
{
if(top>0)
return arr[top-1];
else
return null;
}
public boolean empty()
{
if(top==0)
{
return true;
}
else
{
return false;
}
}
public String pop()
{
if(!this.empty())
{
String temp=this.peek();
arr[top-1]=null;
top--;
return temp="elment is deleted";
}
else
{
return "stack is underflow..";
}
}
public static void main(String args[])
{
StackImp ob=new StackImp(4);
ob.push("1");
ob.push("55");
System.out.println(ob.pop());
System.out.println(ob.pop());
System.out.println(ob.pop());
//ob.push("2");
//ob.push("3");
//ob.push("4");
//System.out.println(ob.peek());
//System.out.println(ob.empty());
}
}
|
package com.dealership.util;
import java.util.Calendar;
/**
* Created by alpha on 2015/1/4.
*/
public class Tools {
public static String getCurrentDate(){
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
System.out.println(calendar.get(Calendar.MONTH) + 1);
System.out.println(calendar.get(Calendar.YEAR));
return null;
}
public static void getCurrent(){
return;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.component.creation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import jakarta.decorator.Decorator;
import jakarta.enterprise.context.Dependent;
import jakarta.enterprise.context.NormalScope;
import jakarta.enterprise.inject.Any;
import jakarta.enterprise.inject.Specializes;
import jakarta.enterprise.inject.Typed;
import jakarta.enterprise.inject.spi.Annotated;
import jakarta.enterprise.inject.spi.AnnotatedField;
import jakarta.enterprise.inject.spi.AnnotatedMember;
import jakarta.enterprise.inject.spi.AnnotatedMethod;
import jakarta.enterprise.inject.spi.AnnotatedParameter;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.inject.Named;
import jakarta.inject.Scope;
import jakarta.interceptor.Interceptor;
import org.apache.webbeans.annotation.AnnotationManager;
import org.apache.webbeans.annotation.AnyLiteral;
import org.apache.webbeans.annotation.DefaultLiteral;
import org.apache.webbeans.annotation.NamedLiteral;
import org.apache.webbeans.component.BeanAttributesImpl;
import org.apache.webbeans.config.OWBLogConst;
import org.apache.webbeans.config.WebBeansContext;
import org.apache.webbeans.container.ExternalScope;
import org.apache.webbeans.exception.WebBeansConfigurationException;
import org.apache.webbeans.logger.WebBeansLoggerFacade;
import org.apache.webbeans.portable.AbstractAnnotated;
import org.apache.webbeans.util.AnnotationUtil;
import org.apache.webbeans.util.Asserts;
import org.apache.webbeans.util.ClassUtil;
import org.apache.webbeans.util.WebBeansUtil;
/**
* Abstract implementation.
*
* @version $Rev$ $Date$
*
* @param <T> bean class info
*/
public abstract class BeanAttributesBuilder<T, A extends Annotated>
{
protected A annotated;
protected WebBeansContext webBeansContext;
protected Set<Type> types = new HashSet<>();
protected Set<Annotation> qualifiers = new HashSet<>();
protected Class<? extends Annotation> scope;
protected String name;
protected Set<Class<? extends Annotation>> stereotypes;
protected Boolean alternative;
public static BeanAttributesBuilderFactory forContext(WebBeansContext webBeansContext)
{
return new BeanAttributesBuilderFactory(webBeansContext);
}
/**
* Creates a bean instance.
*
* @param annotated
*/
protected BeanAttributesBuilder(WebBeansContext webBeansContext, A annotated)
{
this.annotated = annotated;
this.webBeansContext = webBeansContext;
}
public BeanAttributesBuilder<T, A> alternative(boolean alternative)
{
this.alternative = alternative;
return this;
}
public BeanAttributesImpl<T> build()
{
// we need to check the stereotypes first because we might need it to determine the scope
stereotypes = defineStereotypes(annotated);
defineScope();
if (scope == null)
{
// this indicates that we shall not use this AnnotatedType to create Beans from it.
return null;
}
defineTypes();
defineName();
defineQualifiers();
defineAlternative();
return new BeanAttributesImpl<>(types, qualifiers, scope, name, stereotypes, alternative);
}
protected A getAnnotated()
{
return annotated;
}
/**
* {@inheritDoc}
*/
protected void defineTypes()
{
Class<?> baseType = ClassUtil.getClass(annotated.getBaseType());
if (baseType.isArray())
{
// 3.3.1
types.add(Object.class);
types.add(baseType);
}
else
{
Typed beanTypes = annotated.getAnnotation(Typed.class);
if (beanTypes != null)
{
Class<?>[] typedTypes = beanTypes.value();
//New api types
Set<Type> newTypes = new HashSet<>();
for (Class<?> type : typedTypes)
{
Type foundType = null;
for (Type apiType : annotated.getTypeClosure())
{
if(ClassUtil.getClazz(apiType) == type)
{
foundType = apiType;
break;
}
}
if(foundType == null)
{
throw new WebBeansConfigurationException("@Type values must be in bean api types of class: " + baseType);
}
newTypes.add(foundType);
}
this.types.addAll(newTypes);
this.types.add(Object.class);
}
else
{
this.types.addAll(annotated.getTypeClosure());
}
Set<String> ignored = webBeansContext.getOpenWebBeansConfiguration().getIgnoredInterfaces();
if (!ignored.isEmpty())
{
this.types.removeIf(t -> t instanceof Class && ignored.contains(((Class<?>) t).getName()));
}
}
}
/**
* {@inheritDoc}
*/
protected void
defineQualifiers()
{
HashSet<Class<? extends Annotation>> qualifiedTypes = new HashSet<>();
if (annotated.isAnnotationPresent(Specializes.class))
{
defineQualifiers(getSuperAnnotated(), qualifiedTypes);
}
defineQualifiers(annotated, qualifiedTypes);
}
private void defineQualifiers(Annotated annotated, Set<Class<? extends Annotation>> qualifiedTypes)
{
Annotation[] annotations = AnnotationUtil.asArray(annotated.getAnnotations());
AnnotationManager annotationManager = webBeansContext.getAnnotationManager();
for (Annotation annotation : annotations)
{
Class<? extends Annotation> type = annotation.annotationType();
if (annotationManager.isQualifierAnnotation(type))
{
annotationManager.checkQualifierConditions(annotation);
if (qualifiedTypes.contains(annotation.annotationType()) && !isRepetable(annotated, annotation))
{
continue;
}
else
{
qualifiedTypes.add(annotation.annotationType());
}
if (annotation.annotationType().equals(Named.class) && name != null)
{
qualifiers.add(new NamedLiteral(name));
}
else
{
qualifiers.add(annotation);
}
}
}
// No-binding annotation
if (qualifiers.isEmpty())
{
qualifiers.add(DefaultLiteral.INSTANCE);
}
else if (qualifiers.size() == 1)
{
// section 2.3.1
// If a bean does not explicitly declare a qualifier other than @Named or @Any,
// the bean has exactly one additional qualifier, of type @Default.
Annotation annot = qualifiers.iterator().next();
if(annot.annotationType().equals(Named.class) || annot.annotationType().equals(Any.class))
{
qualifiers.add(DefaultLiteral.INSTANCE);
}
}
else if (qualifiers.size() == 2)
{
Iterator<Annotation> qualiIt = qualifiers.iterator();
Class<? extends Annotation> q1 = qualiIt.next().annotationType();
Class<? extends Annotation> q2 = qualiIt.next().annotationType();
if (q1.equals(Named.class) && q2.equals(Any.class) ||
q2.equals(Named.class) && q1.equals(Any.class) )
{
qualifiers.add(DefaultLiteral.INSTANCE);
}
}
//Add @Any support
if(!hasAnyQualifier())
{
qualifiers.add(AnyLiteral.INSTANCE);
}
}
// we don't want to do the getRepeatableMethod() logic *again* if we can but we can need for custom AT
private boolean isRepetable(Annotated annotated, Annotation annotation)
{
return AbstractAnnotated.class.isInstance(annotated) ?
AbstractAnnotated.class.cast(annotated).getRepeatables().contains(annotation.annotationType()) :
webBeansContext.getAnnotationManager().getRepeatableMethod(annotation.annotationType()).isPresent();
}
/**
* Returns true if any binding exist
*
* @return true if any binding exist
*/
private boolean hasAnyQualifier()
{
return AnnotationUtil.getAnnotation(qualifiers, Any.class) != null;
}
protected abstract void defineScope();
protected void defineScope(String errorMessage)
{
defineScope(null, false, errorMessage);
}
protected void defineScope(Class<?> declaringClass, boolean onlyScopedBeans, String errorMessage)
{
Annotation[] annotations = AnnotationUtil.asArray(annotated.getAnnotations());
boolean found = false;
List<ExternalScope> additionalScopes = webBeansContext.getBeanManagerImpl().getAdditionalScopes();
for (Annotation annotation : annotations)
{
if (declaringClass != null && AnnotationUtil.getDeclaringClass(annotation, declaringClass) != null && !AnnotationUtil.isDeclaringClass(declaringClass, annotation))
{
continue;
}
Class<? extends Annotation> annotationType = annotation.annotationType();
if (!webBeansContext.getBeanManagerImpl().isScope(annotationType))
{
continue;
}
/*Normal scope*/
Annotation var = annotationType.getAnnotation(NormalScope.class);
/*Pseudo scope*/
Annotation pseudo = annotationType.getAnnotation(Scope.class);
if (var == null && pseudo == null)
{
// check for additional scopes registered via a CDI Extension
for (ExternalScope additionalScope : additionalScopes)
{
if (annotationType.equals(additionalScope.getScope()))
{
// create a proxy which implements the given annotation
Annotation scopeAnnotation = additionalScope.getScopeAnnotation();
if (additionalScope.isNormal())
{
var = scopeAnnotation;
}
else
{
pseudo = scopeAnnotation;
}
}
}
}
if (var != null)
{
if(pseudo != null)
{
throw new WebBeansConfigurationException("Not to define both @Scope and @NormalScope on bean : " + ClassUtil.getClass(annotated.getBaseType()).getName());
}
if (found)
{
throw new WebBeansConfigurationException(errorMessage);
}
found = true;
scope = annotation.annotationType();
}
else
{
if(pseudo != null)
{
if (found)
{
throw new WebBeansConfigurationException(errorMessage);
}
found = true;
scope = annotation.annotationType();
}
}
}
if (found && annotated.getAnnotation(Interceptor.class) != null && scope != Dependent.class)
{
throw new WebBeansConfigurationException("An Interceptor must declare any other Scope than @Dependent: " + ClassUtil.getClass(annotated.getBaseType()).getName());
}
if (found && annotated.getAnnotation(Decorator.class) != null && scope != Dependent.class)
{
throw new WebBeansConfigurationException("A Decorator must declare any other Scope than @Dependent: " + ClassUtil.getClass(annotated.getBaseType()).getName());
}
if (!found && declaringClass != null && !hasDeclaredNonInheritedScope(declaringClass))
{
defineScope(declaringClass.getSuperclass(), onlyScopedBeans, errorMessage);
}
else if (!found)
{
defineDefaultScope(errorMessage, onlyScopedBeans);
}
}
private void defineDefaultScope(String exceptionMessage, boolean onlyScopedBeans)
{
if (scope == null)
{
Set<Class<? extends Annotation>> stereos = stereotypes;
if (stereos != null && stereos.size() > 0)
{
Annotation defined = null;
Set<Class<? extends Annotation>> anns = stereotypes;
for (Class<? extends Annotation> stero : anns)
{
boolean containsNormal = AnnotationUtil.hasMetaAnnotation(stero.getDeclaredAnnotations(), NormalScope.class);
if (AnnotationUtil.hasMetaAnnotation(stero.getDeclaredAnnotations(), NormalScope.class) ||
AnnotationUtil.hasMetaAnnotation(stero.getDeclaredAnnotations(), Scope.class))
{
Annotation next;
if(containsNormal)
{
next = AnnotationUtil.getMetaAnnotations(stero.getDeclaredAnnotations(), NormalScope.class)[0];
}
else
{
next = AnnotationUtil.getMetaAnnotations(stero.getDeclaredAnnotations(), Scope.class)[0];
}
if (defined == null)
{
defined = next;
}
else
{
if (!defined.equals(next))
{
throw new WebBeansConfigurationException(exceptionMessage);
}
}
}
}
if (defined != null)
{
scope = defined.annotationType();
}
else
{
scope = Dependent.class;
}
}
if (scope == null)
{
if (annotated instanceof AnnotatedType)
{
Constructor<Object> defaultCt = webBeansContext.getWebBeansUtil().getNoArgConstructor(((AnnotatedType) annotated).getJavaClass());
if (defaultCt != null && Modifier.isPrivate(defaultCt.getModifiers()))
{
// basically ignore this class by not adding a scope
return;
}
}
}
if (scope == null &&
(!onlyScopedBeans ||
annotated.getAnnotation(Interceptor.class) != null ||
annotated.getAnnotation(Decorator.class) != null))
{
// only add a 'default' Dependent scope
// * if it's not in a bean-discovery-mode='scoped' module, or
// * if it's a Decorator or Interceptor
scope = Dependent.class;
}
}
}
private boolean hasDeclaredNonInheritedScope(Class<?> type)
{
return webBeansContext.getAnnotationManager().getDeclaredScopeAnnotation(type) != null;
}
protected abstract void defineName();
protected void defineName(Annotated annotated, Supplier<String> name)
{
Named nameAnnot = annotated.getAnnotation(Named.class);
boolean isDefault = false;
if (nameAnnot == null)
{
// no @Named
// Check for stereottype
if (webBeansContext.getAnnotationManager().hasNamedOnStereoTypes(stereotypes))
{
isDefault = true;
}
}
else
{
// yes @Named
if (nameAnnot.value().length() == 0)
{
isDefault = true;
}
else
{
this.name = nameAnnot.value();
}
}
if (isDefault)
{
this.name = name.get();
}
}
/**
* @return the AnnotatedType of the next non-Specialized superclass
*/
protected abstract Annotated getSuperAnnotated();
/**
* {@inheritDoc}
*/
protected Set<Class<? extends Annotation>> defineStereotypes(Annotated annot)
{
Set<Class<? extends Annotation>> stereos = null;
Annotation[] anns = AnnotationUtil.asArray(annot.getAnnotations());
AnnotationManager annotationManager = webBeansContext.getAnnotationManager();
if (annotationManager.hasStereoTypeMetaAnnotation(anns))
{
Annotation[] steroAnns =
annotationManager.getStereotypeMetaAnnotations(anns);
for (Annotation stereo : steroAnns)
{
if (stereos == null)
{
stereos = new HashSet<>();
}
stereos.add(stereo.annotationType());
}
}
return stereos != null ? stereos : Collections.EMPTY_SET;
}
// these alternatives can be not activated
protected void defineAlternative()
{
if (alternative == null)
{
alternative = WebBeansUtil.isAlternative(annotated, stereotypes);
}
}
public static class BeanAttributesBuilderFactory
{
private WebBeansContext webBeansContext;
private BeanAttributesBuilderFactory(WebBeansContext webBeansContext)
{
Asserts.assertNotNull(webBeansContext, Asserts.PARAM_NAME_WEBBEANSCONTEXT);
this.webBeansContext = webBeansContext;
}
public <T> BeanAttributesBuilder<T, AnnotatedType<T>> newBeanAttibutes(AnnotatedType<T> annotatedType)
{
return newBeanAttibutes(annotatedType, false);
}
public <T> BeanAttributesBuilder<T, AnnotatedType<T>> newBeanAttibutes(AnnotatedType<T> annotatedType, boolean onlyScopedBeans)
{
return new AnnotatedTypeBeanAttributesBuilder<>(webBeansContext, annotatedType, onlyScopedBeans);
}
public <T> BeanAttributesBuilder<T, AnnotatedField<T>> newBeanAttibutes(AnnotatedField<T> annotatedField)
{
return new AnnotatedFieldBeanAttributesBuilder<>(webBeansContext, annotatedField);
}
public <T> BeanAttributesBuilder<T, AnnotatedMethod<T>> newBeanAttibutes(AnnotatedMethod<T> annotatedMethod)
{
return new AnnotatedMethodBeanAttributesBuilder<>(webBeansContext, annotatedMethod);
}
}
private static class AnnotatedTypeBeanAttributesBuilder<C> extends BeanAttributesBuilder<C, AnnotatedType<C>>
{
private final boolean onlyScopedBeans;
public AnnotatedTypeBeanAttributesBuilder(WebBeansContext webBeansContext, AnnotatedType<C> annotated, boolean onlyScopedBeans)
{
super(webBeansContext, annotated);
this.onlyScopedBeans = onlyScopedBeans;
}
@Override
protected void defineScope()
{
defineScope(getAnnotated().getJavaClass(), onlyScopedBeans,
WebBeansLoggerFacade.getTokenString(OWBLogConst.TEXT_MB_IMPL) + getAnnotated().getJavaClass().getName() +
WebBeansLoggerFacade.getTokenString(OWBLogConst.TEXT_SAME_SCOPE));
}
@Override
protected void defineName()
{
if (getAnnotated().isAnnotationPresent(Specializes.class))
{
AnnotatedType<? super C> annotatedToSpecialize = getAnnotated();
do
{
Class<? super C> superclass = annotatedToSpecialize.getJavaClass().getSuperclass();
if (superclass.equals(Object.class))
{
throw new WebBeansConfigurationException("@Specialized Class : " + getAnnotated().getJavaClass().getName()
+ " must not directly extend Object.class");
}
annotatedToSpecialize = webBeansContext.getAnnotatedElementFactory().newAnnotatedType(superclass);
} while(annotatedToSpecialize.getAnnotation(Specializes.class) != null);
AnnotatedType<? super C> finalAnnotatedToSpecialize = annotatedToSpecialize;
defineName(annotatedToSpecialize, () -> getManagedBeanDefaultName(finalAnnotatedToSpecialize));
}
if (name == null)
{
defineName(getAnnotated(), () -> getManagedBeanDefaultName(getAnnotated()));
}
else
{
// TODO XXX We have to check stereotypes here, too
if (getAnnotated().getJavaClass().isAnnotationPresent(Named.class))
{
throw new WebBeansConfigurationException("@Specialized Class : " + getAnnotated().getJavaClass().getName()
+ " may not explicitly declare a bean name");
}
}
}
@Override
protected AnnotatedType<? super C> getSuperAnnotated()
{
AnnotatedType<? super C> annotatedType = getAnnotated();
do
{
Class<? super C> superclass = annotatedType.getJavaClass().getSuperclass();
if (superclass == null || superclass.equals(Object.class))
{
return null;
}
annotatedType = webBeansContext.getAnnotatedElementFactory().newAnnotatedType(superclass);
} while (annotatedType.getAnnotation(Specializes.class) != null);
return annotatedType;
}
}
private static class AnnotatedFieldBeanAttributesBuilder<M> extends AnnotatedMemberBeanAttributesBuilder<M, AnnotatedField<M>>
{
protected AnnotatedFieldBeanAttributesBuilder(WebBeansContext webBeansContext, AnnotatedField<M> annotated)
{
super(webBeansContext, annotated);
}
@Override
protected void defineScope()
{
defineScope("Annotated producer field: " + getAnnotated().getJavaMember() + "must declare default @Scope annotation");
}
@Override
protected void defineName()
{
defineName(getAnnotated(), () -> getProducerDefaultName(getAnnotated()));
}
@Override
protected AnnotatedField<? super M> getSuperAnnotated()
{
AnnotatedField<M> thisField = getAnnotated();
for (AnnotatedField<? super M> superField: getSuperType().getFields())
{
if (thisField.getJavaMember().getName().equals(superField.getJavaMember().getName())
&& thisField.getBaseType().equals(superField.getBaseType()))
{
return superField;
}
}
return null;
}
}
private static class AnnotatedMethodBeanAttributesBuilder<M> extends AnnotatedMemberBeanAttributesBuilder<M, AnnotatedMethod<M>>
{
protected AnnotatedMethodBeanAttributesBuilder(WebBeansContext webBeansContext, AnnotatedMethod<M> annotated)
{
super(webBeansContext, annotated);
}
@Override
protected void defineScope()
{
defineScope("Annotated producer method : " + getAnnotated().getJavaMember() + "must declare default @Scope annotation");
}
@Override
protected void defineName()
{
if (getAnnotated().isAnnotationPresent(Specializes.class))
{
AnnotatedMethod<? super M> superAnnotated = getSuperAnnotated();
defineName(superAnnotated, () -> getProducerDefaultName(superAnnotated));
}
if (name == null)
{
defineName(getAnnotated(), () -> getProducerDefaultName(getAnnotated()));
}
else
{
// TODO XXX We have to check stereotypes here, too
if (getAnnotated().isAnnotationPresent(Named.class))
{
throw new WebBeansConfigurationException("@Specialized Producer method : " + getAnnotated().getJavaMember().getName()
+ " may not explicitly declare a bean name");
}
}
}
@Override
protected AnnotatedMethod<? super M> getSuperAnnotated()
{
AnnotatedMethod<M> thisMethod = getAnnotated();
for (AnnotatedMethod<? super M> superMethod: webBeansContext.getAnnotatedElementFactory().getFilteredAnnotatedMethods(getSuperType()))
{
List<AnnotatedParameter<M>> thisParameters = thisMethod.getParameters();
if (thisMethod.getJavaMember().getName().equals(superMethod.getJavaMember().getName())
&& thisMethod.getBaseType().equals(superMethod.getBaseType())
&& thisParameters.size() == superMethod.getParameters().size())
{
List<AnnotatedParameter<?>> superParameters = (List<AnnotatedParameter<?>>)(List<?>)superMethod.getParameters();
boolean match = true;
for (int i = 0; i < thisParameters.size(); i++)
{
if (!thisParameters.get(i).getBaseType().equals(superParameters.get(i).getBaseType()))
{
match = false;
break;
}
}
if (match)
{
return superMethod;
}
}
}
return null;
}
}
protected String getManagedBeanDefaultName(AnnotatedType<?> annotatedType)
{
String clazzName = annotatedType.getJavaClass().getSimpleName();
Asserts.assertNotNull(annotatedType);
if(clazzName.length() > 0)
{
StringBuilder name = new StringBuilder(clazzName);
name.setCharAt(0, Character.toLowerCase(name.charAt(0)));
return name.toString();
}
return clazzName;
}
protected String getProducerDefaultName(AnnotatedMember<?> annotatedMember)
{
String memberName = annotatedMember.getJavaMember().getName();
StringBuilder buffer = new StringBuilder(memberName);
if (buffer.length() > 3 && (buffer.substring(0, 3).equals("get") || buffer.substring(0, 3).equals("set")))
{
if(Character.isUpperCase(buffer.charAt(3)))
{
buffer.setCharAt(3, Character.toLowerCase(buffer.charAt(3)));
}
return buffer.substring(3);
}
else if ((buffer.length() > 2 && buffer.substring(0, 2).equals("is")))
{
if(Character.isUpperCase(buffer.charAt(2)))
{
buffer.setCharAt(2, Character.toLowerCase(buffer.charAt(2)));
}
return buffer.substring(2);
}
else
{
buffer.setCharAt(0, Character.toLowerCase(buffer.charAt(0)));
return buffer.toString();
}
}
private abstract static class AnnotatedMemberBeanAttributesBuilder<M, A extends AnnotatedMember<M>> extends BeanAttributesBuilder<M, A>
{
protected AnnotatedMemberBeanAttributesBuilder(WebBeansContext webBeansContext, A annotated)
{
super(webBeansContext, annotated);
}
protected AnnotatedType<? super M> getSuperType()
{
Class<? super M> superclass = getAnnotated().getDeclaringType().getJavaClass().getSuperclass();
if (superclass == null)
{
return null;
}
return webBeansContext.getAnnotatedElementFactory().getAnnotatedType(superclass);
}
}
}
|
package replace;
public class replaceSpace{
String str;
int count;
public replaceSpace(String s, int n){
str = s;
count = n;
}
public String replace(){
String newString = "";
for(int i = 0;i<count;i++){
if(str.charAt(i) == 32){
newString = newString +"%20";
}
else{
newString = newString+str.charAt(i);
}
}
return newString;
}
public static void main(String args[]){
String s = "Mr John Smith";
int n = 13;
replaceSpace rep = new replaceSpace(s,n);
System.out.println("The result after replacemant is:" + rep.replace());
}
}
|
package com.andy.springbootcasclient.service;
import com.andy.springbootcasclient.domain.Student;
import com.andy.springbootcasclient.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* User: andy
* Date: 2019/7/31
* Time: 15:10
*/
@Service
public class StudentService {
@Autowired
StudentMapper studentMapper;
public Student selectStudentById(String id){
return studentMapper.selectStudentById(id);
}
}
|
package br.udesc.model.dao.GLPK;
import br.udesc.model.dao.CursoJpaController;
import br.udesc.model.dao.DisciplinaJpaController;
import br.udesc.model.dao.PessoaHorarioPreferenciaJpaController;
import br.udesc.model.dao.ProfessorJpaController;
import br.udesc.model.dao.RestricaoDisciplinaJpaController;
import br.udesc.model.entidade.Disciplina;
import br.udesc.model.entidade.Professor;
import br.udesc.model.entidade.RestricaoDisciplina;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
/**
* Classe responsável por gerar arquivo de restrições utilizado pelo GLPK.
*
* @author PIN2
*/
public class GerarGLPK {
private File arquivo = new File("./teste.mod");
private CursoJpaController cjc = new CursoJpaController();
private DisciplinaJpaController djc = new DisciplinaJpaController();
private ProfessorJpaController pjc = new ProfessorJpaController();
private FileWriter fw;
private BufferedWriter bw;
private String solve = "";
/**
* Método responsável por centralizar a chamada de todos os métodos
* utilizados para a geração do arquivo.
*/
public void geraTudo() {
try {
fw = new FileWriter(arquivo, false);
bw = new BufferedWriter(fw);
salvar();
funcaoMax();
funcaoMaxSala();
somatorioCeuLab();
gerarVariaveisPorDisciplina();
gerarSomatorioDisciplinaProfessor();
gerarSomatorioDisciplinaFase();
gerarRestricaoDisciplinaHorarioIndisponiveis();
gerarRestricoesDisciplinaIndisponivel();
gerarRestricoesObrigatorias();
geraSolve();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Método responsável por criar as variáveis que serão utilizadas durante a
* execução do GPLK.
*/
public void salvar() {
try {
List<Disciplina> dis = djc.listarDisciplina();
Disciplina disciplina;
String print = "";
for (int i = 0; i < dis.size(); i++) {
disciplina = dis.get(i);
for (int j = 1; j <= 6; j++) {
for (int k = 1; k <= 2; k++) {
if (disciplina.getSala() != null) {
for (int l = 1; l <= 2; l++) {
if (l == 2) {
print += "var _" + dis.get(i).getCodigo() + "_" + j + k + "_" + dis.get(i).getSala().getNumero() + ",binary;\r\n";
if (i == dis.size() - 1 && j == 6 && k == 2) {
solve += "_" + dis.get(i).getCodigo() + "_" + j + k + "_" + dis.get(i).getSala().getNumero() + ";\r\n";
} else {
solve += "_" + dis.get(i).getCodigo() + "_" + j + k + "_" + dis.get(i).getSala().getNumero() + ",";
}
} else {
print += "var _" + dis.get(i).getCodigo() + "_" + j + k + ",binary;\r\n";
if (i == dis.size() - 1 && j == 6 && k == 2) {
solve += "_" + dis.get(i).getCodigo() + "_" + j + k + ",";
} else {
solve += "_" + dis.get(i).getCodigo() + "_" + j + k + ",";
}
}
}
} else {
print += "var _" + dis.get(i).getCodigo() + "_" + j + k + ",binary;\r\n";
if (i == dis.size() - 1 && j == 6 && k == 2) {
solve += "_" + dis.get(i).getCodigo() + "_" + j + k + ";\r\n";
} else {
solve += "_" + dis.get(i).getCodigo() + "_" + j + k + ",";
}
}
}
}
}
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Método responsável por criar a função de maximazação das variáveis.
*/
public void funcaoMax() {
try {
Files.write(Paths.get("./teste.mod"), "\r\nmaximize z: ".getBytes(), StandardOpenOption.APPEND);
String print = "";
ProfessorJpaController pjc = new ProfessorJpaController();
List<Disciplina> dis = djc.listarDisciplinaComProfessor();
if (pjc.getProfessorCount() != 0) {
for (int i = 0; i < dis.size(); i++) {
for (int j = 1; j <= 6; j++) {
for (int k = 1; k <= 2; k++) {
for (int l = 0; l < dis.get(i).getProfessor().getListaHorario().size(); l++) {
String diaSemana = j + "" + k;
int aux = Integer.parseInt(diaSemana);
if (dis.get(i).getProfessor().getListaHorario().get(l).getSequencia() == aux) {
print += "\n" + dis.get(i).getProfessor().getListaHorario().get(l).getValor() + "*_" + dis.get(i).getCodigo() + "_" + diaSemana + "+";
}
}
}
}
}
}
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
} catch (IOException | NumberFormatException e) {
}
}
/**
* Método responsável por maximizar as variáveis com sala.
*/
public void funcaoMaxSala() {
try {
List<Disciplina> dis = djc.listarDisciplinaComProfessorComSala();
String print = "";
for (int i = 0; i < dis.size(); i++) {
for (int j = 1; j <= 6; j++) {
for (int k = 1; k <= 2; k++) {
for (int l = 0; l < dis.get(i).getProfessor().getListaHorario().size(); l++) {
String diaSemana = j + "" + k;
int aux = Integer.parseInt(diaSemana);
if (dis.get(i).getProfessor().getListaHorario().get(l).getSequencia() == aux) {
if (i == dis.size() - 1 && aux == 62) {
print += "\n" + dis.get(i).getProfessor().getListaHorario().get(l).getValor() + "*_" + dis.get(i).getCodigo() + "_" + diaSemana + "_" + dis.get(i).getSala().getNumero() + ";";
} else {
print += "\n" + dis.get(i).getProfessor().getListaHorario().get(l).getValor() + "*_" + dis.get(i).getCodigo() + "_" + diaSemana + "_" + dis.get(i).getSala().getNumero() + "+";
}
}
}
}
}
}
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
} catch (IOException | NumberFormatException e) {
}
}
/**
* Método responsável por gerar as variáveis por Disciplina.
*/
public void gerarVariaveisPorDisciplina() {
long inicio = System.currentTimeMillis();
try {
Files.write(Paths.get("./teste.mod"), ("\r\n\r\n" + "# somatorio de todas as variaveis da disciplina = carga horaria" + "\r\n\r\n" + "s.t. carga_horaria: ").getBytes(), StandardOpenOption.APPEND);
Disciplina disc = new Disciplina();
List<Disciplina> disComSala = djc.listarDisciplinaComSala();
List<Disciplina> listaDisciplina = djc.listarDisciplina();
int contador = 1;
for (int i = 0; i < listaDisciplina.size(); i++) {
String print = "";
disc = listaDisciplina.get(i);
for (int j = 1; j <= 6; j++) {
for (int k = 1; k <= 2; k++) {
int a = (int) Math.ceil(disc.getCreditos() / 2);
String aux = String.valueOf(a);
if (disc.getSala() != null) {
for (int l = 1; l <= 2; l++) {
if (l == 2) {
if (j == 6 && k == 2) {
if (i != listaDisciplina.size() - 1) {
print += "_" + disc.getCodigo() + "_" + j + k + "_" + disc.getSala().getNumero() + " = " + aux + ";\r\n s.t. carga_horaria" + contador + ":";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
} else {
print += "_" + disc.getCodigo() + "_" + j + k + "_" + disc.getSala().getNumero() + " = " + aux + ";\r\n";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
}
} else {
print += "_" + disc.getCodigo() + "_" + j + k + "_" + disc.getSala().getNumero() + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
}
} else {
if (j == 6 && k == 2) {
print += "_" + disc.getCodigo() + "_" + j + k + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
} else {
print += "_" + disc.getCodigo() + "_" + j + k + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
}
}
}
} else {
if (j == 6 && k == 2) {
if (i != listaDisciplina.size() - 1) {
print += "_" + disc.getCodigo() + "_" + j + k + " = " + aux + ";\r\n s.t. carga_horaria" + contador + ":";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
} else {
print += "_" + disc.getCodigo() + "_" + j + k + " = " + aux + ";\r\n";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
}
} else {
print += "_" + disc.getCodigo() + "_" + j + k + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Método responsável por gerar somatório disciplinas por professor.
*/
public void gerarSomatorioDisciplinaProfessor() {
try {
Files.write(Paths.get("./teste.mod"), "\r\n# somatorio_de_todas as disciplinas de um professor por horario <=1 \r\n s.t. conflito_horario_professor0:".getBytes(), StandardOpenOption.APPEND);
List<Professor> lista = pjc.listarProfessor();
List<Professor> listaProfessor = new ArrayList<>();
List<Professor> listaSala = new ArrayList<>();
Professor professor;
for (int i = 0; i < lista.size(); i++) {
if (lista.get(i).getListaDisciplinaProfessor().size() != 0) {
listaSala.add(lista.get(i));
}
}
listaProfessor = lista;
int contador = 1;
int contadorProfessor = 0;
for (int i = 0; i < listaProfessor.size(); i++) {
String print = "";
professor = lista.get(i);
Disciplina disciplina = new Disciplina();
for (int j = 1; j <= 6; j++) {
for (int k = 1; k <= 2; k++) {
for (int l = 0; l < professor.getListaDisciplinaProfessor().size(); l++) {
disciplina = professor.getListaDisciplinaProfessor().get(l);
if (disciplina.getSala() != null) {
for (int m = 1; m <= 2; m++) {
if (m == 2) {
if (l == professor.getListaDisciplinaProfessor().size() - 1) {
if (contador / 12 == listaSala.size() && j == 6 && k == 2) {
print += "_" + disciplina.getCodigo() + "_" + j + k + "_" + disciplina.getSala().getNumero() + "<= 1; \r\n";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
contadorProfessor++;
} else {
print += "_" + disciplina.getCodigo() + "_" + j + k + "_" + disciplina.getSala().getNumero() + "<= 1; \r\n" + "s.t. conflito_horario_professor" + contador + ":";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
contadorProfessor++;
}
} else {
print += "_" + disciplina.getCodigo() + "_" + j + k + "_" + disciplina.getSala().getNumero() + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
}
} else {
if (l == professor.getListaDisciplinaProfessor().size() - 1) {
print += "_" + disciplina.getCodigo() + "_" + j + k + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
} else {
print += "_" + disciplina.getCodigo() + "_" + j + k + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
}
}
}
} else {
if (l == professor.getListaDisciplinaProfessor().size() - 1) {
if (contador / 12 == listaSala.size() && j == 6 && k == 2) {
print += "_" + disciplina.getCodigo() + "_" + j + k + "<= 1; \r\n";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
contadorProfessor++;
} else {
print += "_" + disciplina.getCodigo() + "_" + j + k + "<= 1; \r\n" + "s.t. conflito_horario_professor" + contador + ":";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
contadorProfessor++;
}
} else {
print += "_" + disciplina.getCodigo() + "_" + j + k + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
}
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Método responsável por gerar somatório disciplinas por fase.
*/
public void gerarSomatorioDisciplinaFase() {
long inicio = System.currentTimeMillis();
try {
Files.write(Paths.get("./teste.mod"), ("\r\n\r\n" + "# somatorio de todas as disciplinas de uma turma por horario <= 1" + "\r\n" + "s.t. conflito_horario_turma0:").getBytes(), StandardOpenOption.APPEND);
Disciplina disc = new Disciplina();
String print = "";
List<Disciplina> listaDisciplina;
int fase = cjc.listarCurso().get(0).getDuracao();
int contador = 1;
for (int i = 1; i < 7; i++) {
for (int j = 1; j < 3; j++) {
for (int k = 1; k <= fase; k++) {
String a = String.valueOf(k);
listaDisciplina = djc.listarDisciplinaPorFase(a);
for (int l = 0; l < listaDisciplina.size(); l++) {
disc = listaDisciplina.get(l);
if (disc.getSala() != null) {
for (int m = 1; m <= 2; m++) {
if (m == 2) {
if (l == listaDisciplina.size() - 1) {
if (k == fase && i == 6 && j == 2) {
print += "_" + disc.getCodigo() + "_" + i + j + "_" + disc.getSala().getNumero() + "<= 1; \r\n";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
} else {
print += "_" + disc.getCodigo() + "_" + i + j + "_" + disc.getSala().getNumero() + "<= 1; \r\n" + "s.t. conflito_horario_turma" + contador + ":";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
}
} else {
print += "_" + disc.getCodigo() + "_" + i + j + "_" + disc.getSala().getNumero() + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
}
} else {
if (l == listaDisciplina.size() - 1) {
print += "_" + disc.getCodigo() + "_" + i + j + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
} else {
print += "_" + disc.getCodigo() + "_" + i + j + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
}
}
}
} else {
if (l == listaDisciplina.size() - 1) {
if (k == fase && j == 2 && i == 6) {
print += "_" + disc.getCodigo() + "_" + i + j + "<= 1; \r\n";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
} else {
print += "_" + disc.getCodigo() + "_" + i + j + "<= 1; \r\n" + "s.t. conflito_horario_turma" + contador + ":";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
}
} else {
print += "_" + disc.getCodigo() + "_" + i + j + "+";
Files.write(Paths.get("./teste.mod"), print.getBytes(), StandardOpenOption.APPEND);
print = "";
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Método responsável por gerar restrições obrigatórias.
*
* @throws IOException Não encontrado(a).
*/
public void gerarRestricoesObrigatorias() throws IOException {
String ini = "\r\n# horario arbitrario de disciplina\r\n";
String inb = "s.t. horario_arbitrario_disciplina";
int contador = 0;
Files.write(Paths.get("./teste.mod"), (ini).getBytes(), StandardOpenOption.APPEND);
List<RestricaoDisciplina> res = new RestricaoDisciplinaJpaController().listarRestricoesObrigatorias();
try {
String[] aRestricoes;
aRestricoes = this.montaStringRestricoes(res);
for (int i = 0; i < 12; i++) {
if (!aRestricoes[i].equals("")) {
inb = "s.t. horario_arbitrario_disciplina" + contador + ":";
Files.write(Paths.get("./teste.mod"), (inb + aRestricoes[i] + " = 1;").getBytes(), StandardOpenOption.APPEND);
contador++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Método responsável por montar String para arquivo.
*/
private String[] montaStringRestricoes(List<RestricaoDisciplina> res) {
String restricao11 = "";
String restricao12 = "";
String restricao21 = "";
String restricao22 = "";
String restricao31 = "";
String restricao32 = "";
String restricao41 = "";
String restricao42 = "";
String restricao51 = "";
String restricao52 = "";
String restricao61 = "";
String restricao62 = "";
for (int i = 0; i < res.size(); i++) {
switch (res.get(i).getHorario()) {
case 11:
restricao11 += this.getStringVariavelRestricao(res.get(i), (!restricao11.equals("")));
break;
case 12:
restricao12 += this.getStringVariavelRestricao(res.get(i), (!restricao12.equals("")));
break;
case 21:
restricao21 += this.getStringVariavelRestricao(res.get(i), (!restricao21.equals("")));
break;
case 22:
restricao22 += this.getStringVariavelRestricao(res.get(i), (!restricao22.equals("")));
break;
case 31:
restricao31 += this.getStringVariavelRestricao(res.get(i), (!restricao31.equals("")));
break;
case 32:
restricao32 += this.getStringVariavelRestricao(res.get(i), (!restricao32.equals("")));
break;
case 41:
restricao41 += this.getStringVariavelRestricao(res.get(i), (!restricao41.equals("")));
break;
case 42:
restricao42 += this.getStringVariavelRestricao(res.get(i), (!restricao42.equals("")));
break;
case 51:
restricao51 += this.getStringVariavelRestricao(res.get(i), (!restricao51.equals("")));
break;
case 52:
restricao52 += this.getStringVariavelRestricao(res.get(i), (!restricao52.equals("")));
break;
case 61:
restricao61 += this.getStringVariavelRestricao(res.get(i), (!restricao61.equals("")));
break;
case 62:
restricao62 += this.getStringVariavelRestricao(res.get(i), (!restricao62.equals("")));
break;
}
}
String[] aRestricoes = new String[12];
aRestricoes[0] = restricao11;
aRestricoes[1] = restricao12;
aRestricoes[2] = restricao21;
aRestricoes[3] = restricao22;
aRestricoes[4] = restricao31;
aRestricoes[5] = restricao32;
aRestricoes[6] = restricao41;
aRestricoes[7] = restricao42;
aRestricoes[8] = restricao51;
aRestricoes[9] = restricao52;
aRestricoes[10] = restricao61;
aRestricoes[11] = restricao62;
return aRestricoes;
}
/**
* Método responsável por adquirir String de variaveis por restrição.
*
* @param oResDis Restrição Disciplina
* @param bAdicionaMais booleano
* @return String
*/
private String getStringVariavelRestricao(RestricaoDisciplina oResDis, boolean bAdicionaMais) {
String print = "";
if (bAdicionaMais) {
print = " + ";
}
print += "_" + oResDis.getDisciplina().getCodigo() + "_" + oResDis.getHorario();
if (oResDis.getDisciplina().getSala() != null) {
print += " + _" + oResDis.getDisciplina().getCodigo() + "_" + oResDis.getHorario() + "_" + oResDis.getDisciplina().getSala().getNumero();
}
return print;
}
/**
* Método responsável por gerar Restrições Disciplina indisponíveis.
*/
public void gerarRestricoesDisciplinaIndisponivel() {
long inicio = System.currentTimeMillis();
try {
String print = "";
String ini = "\r\n# somatorio de todas as disciplinas e horarios indisponiveis delas = 0 \r\n";
RestricaoDisciplinaJpaController rrr = new RestricaoDisciplinaJpaController();
rrr.listarRestricoesProibidas();
String variavel = "";
if (rrr.listarRestricoesProibidas().size() != 0) {
variavel = "s.t. conflito_horario_proibido:";
}
Files.write(Paths.get("./teste.mod"), (ini + variavel).getBytes(), StandardOpenOption.APPEND);
DisciplinaJpaController djc = new DisciplinaJpaController();
int contador = 0;
Disciplina d = new Disciplina();
List<Disciplina> listaDisciplinas = djc.listarDisciplina();
for (int i = 0; i < listaDisciplinas.size(); i++) {
d = listaDisciplinas.get(i);
for (int j = 0; j < d.getListaRestricaoDisciplina().size(); j++) {
if (d.getSala() != null) {
for (int k = 1; k <= 2; k++) {
if (k == 2) {
if (j == d.getListaRestricaoDisciplina().size() - 1) {
if (i == listaDisciplinas.size() - 1) {
print = "_" + d.getCodigo() + "_" + d.getListaRestricaoDisciplina().get(j).getHorario() + "_" + d.getSala().getNumero() + "= 0;\r\n";
variavel = "s.t. conflito_horario_proibido" + contador + ":";
Files.write(Paths.get("./teste.mod"), (print).getBytes(), StandardOpenOption.APPEND);
contador++;
print = "";
variavel = "";
} else {
print = "_" + d.getCodigo() + "_" + d.getListaRestricaoDisciplina().get(j).getHorario() + "_" + d.getSala().getNumero() + "= 0;\r\n";
variavel = "s.t. conflito_horario_proibido" + contador + ":";
Files.write(Paths.get("./teste.mod"), (print + variavel).getBytes(), StandardOpenOption.APPEND);
contador++;
print = "";
variavel = "";
}
} else {
print = "_" + d.getCodigo() + "_" + d.getListaRestricaoDisciplina().get(j).getHorario() + "_" + d.getSala().getNumero() + "+";
Files.write(Paths.get("./teste.mod"), (print).getBytes(), StandardOpenOption.APPEND);
contador++;
print = "";
}
} else {
if (j == d.getListaRestricaoDisciplina().size() - 1) {
print = "_" + d.getCodigo() + "_" + d.getListaRestricaoDisciplina().get(j).getHorario() + "+";
Files.write(Paths.get("./teste.mod"), (print).getBytes(), StandardOpenOption.APPEND);
contador++;
print = "";
} else {
print = "_" + d.getCodigo() + "_" + d.getListaRestricaoDisciplina().get(j).getHorario() + "+";
Files.write(Paths.get("./teste.mod"), (print).getBytes(), StandardOpenOption.APPEND);
contador++;
print = "";
}
}
}
} else {
if (j == d.getListaRestricaoDisciplina().size() - 1) {
if (i == listaDisciplinas.size() - 1) {
print = "_" + d.getCodigo() + "_" + d.getListaRestricaoDisciplina().get(j).getHorario() + "= 0;\r\n";
variavel = "s.t. conflito_horario_proibido" + contador + ":";
Files.write(Paths.get("./teste.mod"), (print).getBytes(), StandardOpenOption.APPEND);
contador++;
print = "";
} else {
print = "_" + d.getCodigo() + "_" + d.getListaRestricaoDisciplina().get(j).getHorario() + "= 0;\r\n";
variavel = "s.t. conflito_horario_proibido" + contador + ":";
Files.write(Paths.get("./teste.mod"), (print + variavel).getBytes(), StandardOpenOption.APPEND);
contador++;
print = "";
}
} else {
print = "_" + d.getCodigo() + "_" + d.getListaRestricaoDisciplina().get(j).getHorario() + "+";
Files.write(Paths.get("./teste.mod"), (print).getBytes(), StandardOpenOption.APPEND);
print = "";
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Método responsável por gerar Restrições Disciplina indisponíveis.
*/
public void gerarRestricaoDisciplinaHorarioIndisponiveis() {
long inicio = System.currentTimeMillis();
try {
String print = "";
String ini = "\r\n# somatorio de todas as disciplinas e horarios indisponiveis de um professor = 0 \r\n";
String inb = "";
Files.write(Paths.get("./teste.mod"), (ini).getBytes(), StandardOpenOption.APPEND);
PessoaHorarioPreferenciaJpaController oPesHorJpa = new PessoaHorarioPreferenciaJpaController();
DisciplinaJpaController oDisciplinaJpa = new DisciplinaJpaController();
RestricaoDisciplinaJpaController rdjc = new RestricaoDisciplinaJpaController();
List<Professor> listaProfessor = oPesHorJpa.listarProfessorComRestricoesProibitivas();
Professor professor;
Disciplina disciplina;
int dia = 0;
int contador = 1;
for (int i = 0; i < listaProfessor.size(); i++) {
professor = listaProfessor.get(i);
for (int k = 0; k < professor.getListaHorario().size(); k++) {
if (professor.getListaHorario().get(k).getValor() == 12) {
dia = professor.getListaHorario().get(k).getSequencia();
for (int j = 0; j < professor.getListaDisciplinaProfessor().size(); j++) {
disciplina = professor.getListaDisciplinaProfessor().get(j);
if (disciplina.getSala() != null) {
for (int l = 1; l <= 2; l++) {
if (l == 2) {
if (j == professor.getListaDisciplinaProfessor().size() - 1) {
inb = "s.t. conflito_horario_professor_indisponivel" + contador + ":";
print += "_" + disciplina.getCodigo() + "_" + dia + "_" + disciplina.getSala().getNumero() + "= 0;\r\n";
Files.write(Paths.get("./teste.mod"), (inb + print).getBytes(), StandardOpenOption.APPEND);
print = "";
contador++;
} else {
print += "_" + disciplina.getCodigo() + "_" + dia + "_" + disciplina.getSala().getNumero() + "+";
}
} else {
if (j == professor.getListaDisciplinaProfessor().size() - 1) {
print += "_" + disciplina.getCodigo() + "_" + dia + "+";
} else {
print += "_" + disciplina.getCodigo() + "_" + dia + "+";
}
}
}
} else {
if (j == professor.getListaDisciplinaProfessor().size() - 1) {
inb = "s.t. conflito_horario_professor_indisponivel" + contador + ":";
print += "_" + disciplina.getCodigo() + "_" + dia + "= 0;\r\n";
Files.write(Paths.get("./teste.mod"), (inb + print).getBytes(), StandardOpenOption.APPEND);
contador++;
print = "";
} else {
print += "_" + disciplina.getCodigo() + "_" + dia + "+";
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Método responsável por gerar restrições de horários proibidos.
*
* @throws IOException
*/
private void gerarRestricoesHorarioProibido() throws IOException {
long inicio = System.currentTimeMillis();
String print = "";
String ini = "\r\n# somatorio de todas as disciplinas e horarios indisponiveis de um professor \n";
String inb = "s.t. conflito_horario_professor: ";
Files.write(Paths.get("./teste.mod"), (ini + inb).getBytes(), StandardOpenOption.APPEND);
PessoaHorarioPreferenciaJpaController oPesHorJpa = new PessoaHorarioPreferenciaJpaController();
DisciplinaJpaController oDisciplinaJpa = new DisciplinaJpaController();
List<Professor> res = oPesHorJpa.listarProfessorComRestricoesProibitivas();
List<Object> aHorarios;
List<Disciplina> aDisciplinas;
// List<PessoaHorarioPreferencia> res = new PessoaHorarioPreferenciaJpaController().listarRestricoesProibitivas();
for (Professor oProf : res) {
aHorarios = oPesHorJpa.getAllHorarioProibidosProfessor((int) (long) oProf.getId());
aDisciplinas = oDisciplinaJpa.listaDisciplinaProfessor((int) (long) oProf.getId());
for (int i = 0; i < aHorarios.size(); i++) {
for (Disciplina oDis : aDisciplinas) {
if (!print.equals("")) {
print += " + ";
}
print += "_" + oDis.getCodigo() + "_" + aHorarios.get(i);
if (oDis.getSala() != null) {
print += " + _" + oDis.getCodigo() + "_" + aHorarios.get(i) + "_" + oDis.getSala().getNumero();
}
}
}
}
Files.write(Paths.get("./teste.mod"), (print + " = 0\n").getBytes(), StandardOpenOption.APPEND);
}
/**
* Método responsável por gerar somatório de horas por Laboratório.
*
* @throws IOException Não encontrado.
*/
private void somatorioHorasLaboratorio() throws IOException {
DisciplinaJpaController djp = new DisciplinaJpaController();
List<Disciplina> dis = djp.listarDisciplinaComSala();
Files.write(Paths.get("./teste.mod"), ("\r\n\r\n# somatorio de todas as disciplinas e horarios de laboratorio = ao céu de 50% da carga horária\r\n").getBytes(), StandardOpenOption.APPEND);
String variavel = "s.t. somatorio_ceu";
int contador = 0;
for (Disciplina d : dis) {
String print = "";
for (int j = 1; j <= 6; j++) {
for (int k = 1; k <= 2; k++) {
if (j == 6 && k == 2) {
int a = (int) Math.ceil(d.getCreditos() / 4.0);
String aux = String.valueOf(a);
print += "_" + d.getCodigo() + "_" + j + k + "_" + d.getSala().getNumero();
print += "= " + aux + ";\r\n";
variavel = "s.t. horario_em_laboratorio" + contador + ":";
Files.write(Paths.get("./teste.mod"), (variavel + print).getBytes(), StandardOpenOption.APPEND);
contador++;
} else {
print += "_" + d.getCodigo() + "_" + j + k + "_" + d.getSala().getNumero() + "+";
}
}
}
}
}
/**
* Método responsável definir se a matéria necessitar de laboratório, no
* mínimo a metade do somatório das aulas precisa ser em laboratório.
*/
public void somatorioCeuLab() {
DisciplinaJpaController djp = new DisciplinaJpaController();
List<Disciplina> dis = djp.listarDisciplinaComSala();
Disciplina d;
String print = "";
String st = "";
int contador = 0;
try {
Files.write(Paths.get("./teste.mod"), ("# somatorio de todas as disciplinas e horarios de laboratorio = ao céu de 50porcento da carga horária\r\n").getBytes(), StandardOpenOption.APPEND);
for (int i = 0; i < dis.size(); i++) {
d = dis.get(i);
for (int j = 1; j < 7; j++) {
for (int k = 1; k < 3; k++) {
if (j == 6 && k == 2) {
int dia = (int) Math.ceil(d.getCreditos() / 4.0);
print += "_" + d.getCodigo() + "_" + j + k + "_" + d.getSala().getNumero() + ">=" + dia + ";\r\n";
st = "s.t. somatorio_ceu" + contador + ":";
Files.write(Paths.get("./teste.mod"), (st + print).getBytes(), StandardOpenOption.APPEND);
contador++;
print = "";
} else {
print += "_" + d.getCodigo() + "_" + j + k + "_" + d.getSala().getNumero() + "+";
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Método responsável por gerar "solve" (GLPK).
*/
public void geraSolve() {
long inicio = System.currentTimeMillis();
try {
Files.write(Paths.get("./teste.mod"), "\r\nsolve;\r\ndisplay ".getBytes(), StandardOpenOption.APPEND);
// List<Disciplina> dis = djc.listarDisciplinaComSala();
// String print = "";
//
// for (int i = 0; i < dis.size(); i++) {
// for (int j = 1; j <= 6; j++) {
// for (int k = 1; k <= 2; k++) {
// print += " _" + dis.get(i).getCodigo() + "_" + j + k;
//
// if (dis.get(i).getSala() != null) {
// print += ", _" + dis.get(i).getCodigo() + "_" + j + k + "_" + dis.get(i).getSala().getNumero();
// }
// if (i + 1 == dis.size()) {
// print += ";";
// } else {
// print += ",";
// }
// }
// }
// }
Files.write(Paths.get("./teste.mod"), solve.getBytes(), StandardOpenOption.APPEND);
Files.write(Paths.get("./teste.mod"), "\r\n\nend;".getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.portmods.SC;
import com.portmods.SC.block.ModBlocks;
import com.portmods.SC.item.ModItems;
import com.portmods.SC.lib.Reference;
import com.portmods.SC.network.PacketHandler;
import com.portmods.SC.proxy.CommonProxy;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
/**
* Created by David on 8/13/2014.
*/
@Mod(name = Reference.MOD_NAME, modid = Reference.MOD_ID, version = Reference.VERSION)
public class SecureCraft {
@Mod.Instance(Reference.MOD_ID)
public static SecureCraft instance;
@SidedProxy(serverSide = Reference.COMMON_PROXY_LOC, clientSide = Reference.CLIENT_PROXY_LOC)
public static CommonProxy proxy;
@Mod.EventHandler
void preInit(FMLPreInitializationEvent event) {}
@Mod.EventHandler
void Init(FMLInitializationEvent event) {
ModBlocks.init();
ModItems.init();
PacketHandler.init();
proxy.intiTileEntitys();
proxy.initRenderingAndTextures();
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent event) {}
}
|
/*
*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.genie.agent.cli;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utilities for interacting with the user terminal/console.
*
* @author mprimi
* @since 4.0.0
*/
public final class UserConsole {
/**
* The name of this logger must match the one explicitly whitelisted in the underlying logger configuration
* consumed by Spring.
*/
private static final String CONSOLE_LOGGER_NAME = "genie-agent";
/**
* This string path must match the one present in the log appender configuration consumed by Spring.
*/
private static final String LOG_FILE_PATH = "/tmp/genie-agent-%s.log";
/**
* This system property is set by Spring.
*/
private static final String PID_SYSTEM_PROPERTY_NAME = "PID";
private static final Logger LOGGER = LoggerFactory.getLogger(CONSOLE_LOGGER_NAME);
private UserConsole() {
}
/**
* Get the LOGGER visible to user on the console.
* All other LOGGER messages are logged on file only to avoid interfering with the job console output.
*
* @return a special Logger whose messages are visible on the user terminal.
*/
public static Logger getLogger() {
return LOGGER;
}
static String getLogFilePath() {
return String.format(
LOG_FILE_PATH,
System.getProperty(PID_SYSTEM_PROPERTY_NAME, "???")
);
}
}
|
public class emp1 {
int eno;
String ename;
address addr;
public emp1(int eno, String ename, address addr) {
this.eno = eno;
this.ename = ename;
this.addr = addr;
}
public int getEno() {
return eno;
}
public void setEno(int eno) {
this.eno = eno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public address getAddr() {
return addr;
}
public void setAddr(address addr) {
this.addr = addr;
}
}
|
package com.ice2systems.voice;
import java.util.LinkedList;
import java.util.List;
public class TextLog {
private int id = -1;
private TimeSlot startTime;
private TimeSlot endTime;
private List<Monolog> monologs = new LinkedList<Monolog>();
public static class Builder {
private int id;
private TimeSlot startTime;
private TimeSlot endTime;
private List<Monolog> monologs = new LinkedList<Monolog>();
public Builder id(int id) {
this.id = id;
return this;
}
public Builder startTime(TimeSlot startTime) {
this.startTime = startTime;
return this;
}
public Builder endTime(TimeSlot endTime) {
this.endTime = endTime;
return this;
}
public Builder monolog(Monolog monolog) {
if(monolog != null) {
this.monologs.add(monolog);
}
return this;
}
public TextLog build() {
return new TextLog(this);
}
}
private TextLog(Builder b) {
this.id = b.id;
this.startTime = b.startTime;
this.endTime = b.endTime;
this.monologs = b.monologs;
}
public int getId() {
return id;
}
public TimeSlot getStartTime() {
return startTime;
}
public TimeSlot getEndTime() {
return endTime;
}
public List<Monolog> getMonologs() {
return monologs;
}
//used to adjust monologs
public void setMonologs(List<Monolog> newMonologs) {
monologs = newMonologs;
}
public boolean isComplete() {
return id > 0 && startTime != null && endTime != null && monologs != null && !monologs.isEmpty();
}
}
|
package com.handsome.qhb.bean;
import java.io.Serializable;
/**
* Created by zhang on 2016/3/16.
*/
public class Address implements Serializable{
private int aid;
private String recePhone;
private String receName;
private String receAddr;
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getRecePhone() {
return recePhone;
}
public void setRecePhone(String recePhone) {
this.recePhone = recePhone;
}
public String getReceName() {
return receName;
}
public void setReceName(String receName) {
this.receName = receName;
}
public String getReceAddr() {
return receAddr;
}
public void setReceAddr(String receAddr) {
this.receAddr = receAddr;
}
public Address(){
}
public Address(String recePhone,String receName,String receAddr){
this.recePhone = recePhone;
this.receName = receName;
this.receAddr = receAddr;
}
public Address(int aid,String recePhone, String receName, String receAddr) {
this.aid = aid;
this.recePhone = recePhone;
this.receName = receName;
this.receAddr = receAddr;
}
@Override
public String toString() {
return "Address{" +
"aid='"+aid+'\''+
"recePhone='" + recePhone + '\'' +
", receName='" + receName + '\'' +
", receAddr='" + receAddr + '\'' +
'}';
}
}
|
package com.witt.datatype;
public class DataType {
public static void main(String[] args) {
// 1
byte b1 = 'a', b2 = 127, b3 = '$';
// 2
short s1 = 32767, s2 = 'a', s3 = '$';
// 4
int i1 = -2147483647, i2 = 'a';
// 8
long l1 = 9223372036854775807L;
// 4
float f1 = 3.4028235E38f;
// 8
double d1 = 1.7976931348623157E308d, d2 = 1.7976931348623157E308D;
// 2
char c1 = 'a', c2 = '我';
// JVM 规范中,boolean 变量作为 int 处理,也就是4字节;boolean 数组当做 byte 数组处理
boolean flag = true;
System.out.println(b1);
System.out.println(d1);
System.out.println(c1);
System.out.println(Double.MAX_VALUE);
System.out.println((1.1-0.1)/0.1);
System.out.println('\u000b');
}
}
|
package com.it.userportrait.reduce;
import com.it.userportrait.analy.BrushEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.flink.api.common.functions.ReduceFunction;
public class HighFrequencyAnlayReduce implements ReduceFunction<BrushEntity> {
@Override
public BrushEntity reduce(BrushEntity brushEntity, BrushEntity t1) throws Exception {
long numbers1 = brushEntity.getNumbers();
long nubmers2 = t1.getNumbers();
String timeinfo = brushEntity.getTimeinfo();
long userid = brushEntity.getUserid();
String groupFiled = brushEntity.getGroupField();
BrushEntity brushEntityResult = new BrushEntity();
brushEntityResult.setTimeinfo(timeinfo);
brushEntityResult.setUserid(userid);
brushEntityResult.setGroupField(groupFiled);
brushEntityResult.setNumbers(numbers1+nubmers2);
return brushEntityResult;
}
}
|
package com.tencent.mm.plugin.appbrand.ui.recents;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.tencent.mm.bp.a;
import com.tencent.mm.modelappbrand.b.b$f;
import com.tencent.mm.plugin.appbrand.appusage.i;
import com.tencent.mm.plugin.appbrand.appusage.i.b;
import com.tencent.mm.plugin.appbrand.appusage.j.d;
import com.tencent.mm.plugin.appbrand.s$d;
import com.tencent.mm.plugin.appbrand.s.g;
import com.tencent.mm.plugin.appbrand.s.h;
import com.tencent.mm.plugin.appbrand.ui.AppBrandLauncherUI;
import com.tencent.mm.plugin.appbrand.ui.AppBrandNearbyEmptyUI;
import com.tencent.mm.plugin.appbrand.widget.AppBrandNearbyShowcaseView;
import com.tencent.mm.protocal.c.ako;
import com.tencent.mm.protocal.c.avr;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.widget.ThreeDotsLoadingView;
final class e extends h implements OnClickListener, b {
View SU;
private Activity bOb;
private TextView gAa;
private AppBrandNearbyShowcaseView gAb;
private View gAc;
private ImageView gAd;
private boolean gAe = false;
private final int gzI;
private final int gzJ;
private final int gzK;
private final int gzL = -1;
private View gzT;
private int gzX = a.gAi;
private b$f gzY;
private final int gzZ;
private ThreeDotsLoadingView gzp;
e(Activity activity, ViewGroup viewGroup) {
this.bOb = activity;
this.gzI = a.fromDPToPix(activity, 25);
this.gzJ = a.fromDPToPix(activity, 19);
this.gzK = a.fromDPToPix(activity, 2);
this.SU = LayoutInflater.from(activity).inflate(h.app_brand_recents_list_header_v2, viewGroup, false);
View findViewById = this.SU.findViewById(g.content_root);
this.gAc = findViewById;
findViewById.setOnClickListener(this);
this.gzT = this.SU.findViewById(g.nearby_showcase_container);
this.gAa = (TextView) this.SU.findViewById(g.notice_text);
this.gAb = (AppBrandNearbyShowcaseView) this.SU.findViewById(g.nearby_icon_showcase);
this.gAb.setIconLayerCount(4);
this.gAb.setIconSize(this.gzI + (this.gzK * 2));
this.gAb.setIconGap(this.gzJ);
this.gzp = (ThreeDotsLoadingView) this.SU.findViewById(g.nearby_loading_view);
this.gAd = (ImageView) this.SU.findViewById(g.nearby_refresh_view);
this.gzZ = a.g(activity, s$d.grey_text_color);
if (!com.tencent.mm.pluginsdk.permission.a.bj(activity, "android.permission.ACCESS_COARSE_LOCATION")) {
this.gzX = a.gAk;
}
}
final View aoh() {
return this.SU;
}
final void onResume() {
if (a.gAk == this.gzX && com.tencent.mm.pluginsdk.permission.a.bj(this.bOb, "android.permission.ACCESS_COARSE_LOCATION")) {
this.gzX = a.gAi;
aog();
}
}
final void aog() {
df(i.acP());
if (a.gAk == this.gzX) {
aoj();
return;
}
i.a(this);
if (!i.acU()) {
this.SU.post(new 1(this));
} else if (i.refresh()) {
aoi();
} else {
df(false);
}
}
final void onDetached() {
i.b(this);
this.bOb = null;
this.SU = null;
this.gAb = null;
this.gzT = null;
}
private void aoi() {
this.gzX = a.gAj;
bN(this.gzT);
bN(this.gAd);
bO(this.gzp);
this.gzp.cAG();
}
private void aoj() {
boolean z = true;
int i = 0;
if (this.SU != null) {
d dVar;
if (i.acP()) {
df(true);
dVar = ((AppBrandLauncherUI) this.bOb).guF;
if (dVar != null) {
dVar.flZ[5] = "1";
}
} else {
df(false);
}
this.gzp.cAH();
bN(this.gzp);
if (a.gAk == this.gzX) {
bN(this.gzT);
bN(this.gAd);
return;
}
ako acT = i.acT();
if (acT == null) {
this.gzX = a.gAg;
bN(this.gzT);
bO(this.gAd);
} else if (acT.gTo <= 0 || bi.cX(acT.rNk)) {
this.gzX = a.gAi;
bN(this.gzT);
} else {
this.gzX = a.gAh;
dVar = ((AppBrandLauncherUI) this.bOb).guF;
if (dVar != null) {
dVar.flZ[3] = "1";
}
if (this.gAa != null) {
this.gAa.setText(acT.rNq);
this.gAa.setTextColor(aO(acT.rNr, this.gzZ));
}
this.gAb.setIconLayerCount(Math.min(acT.rNk.size(), 4));
if (this.gzT.getVisibility() == 0) {
z = false;
}
if (z) {
this.gAb.aoT();
}
if (this.gzY == null) {
this.gzY = new com.tencent.mm.plugin.appbrand.ui.widget.a(this.gzI, this.gzK);
}
while (i < this.gAb.getChildCount()) {
com.tencent.mm.modelappbrand.b.b.Ka().a(this.gAb.lT(i), ((avr) acT.rNk.get(i)).rYG, com.tencent.mm.modelappbrand.b.a.JZ(), this.gzY);
i++;
}
bO(this.gzT);
if (z) {
if (this.gAb != null) {
this.gAb.aoU();
}
if (this.gAa != null) {
this.gAa.setAlpha(0.0f);
this.gAa.animate().alpha(1.0f).setDuration(500).start();
}
}
}
}
}
private static int aO(String str, int i) {
try {
return Color.parseColor(str);
} catch (Exception e) {
return i;
}
}
private void bN(View view) {
if (view.getVisibility() == 0) {
view.animate().setDuration(200).alpha(0.0f).withEndAction(new 2(this, view)).start();
}
}
private static void bO(View view) {
if (view.getVisibility() != 0) {
view.setAlpha(0.0f);
view.setVisibility(0);
}
view.animate().setDuration(200).alpha(1.0f).withEndAction(null).start();
}
public final void acW() {
if (this.SU != null) {
this.SU.post(new 3(this));
}
}
public final void onClick(View view) {
int i = 0;
if (view.getId() == g.content_root && this.bOb != null && a.gAj != this.gzX) {
if (a.gAi == this.gzX) {
aok();
this.bOb.startActivityForResult(new Intent(this.bOb, AppBrandNearbyEmptyUI.class).putExtra("extra_enter_reason", 0), 3);
} else if (a.gAk == this.gzX) {
aok();
this.bOb.startActivityForResult(new Intent(this.bOb, AppBrandNearbyEmptyUI.class).putExtra("extra_enter_reason", 1), 3);
} else {
boolean z = i.acT() != null && i.acU();
this.gAe = z;
if (a.gAg == this.gzX || this.gAe) {
i = 1;
}
4 4 = new 4(this);
if (i != 0) {
aoi();
i.refresh();
return;
}
4.run();
if (i.acT() != null && i.acT().rNs == 1 && this.gAa != null) {
this.gAa.animate().alpha(0.0f).setDuration(200);
}
}
}
}
private void aok() {
if (this.bOb != null) {
d dVar = ((AppBrandLauncherUI) this.bOb).guF;
if (dVar != null) {
dVar.flZ[8] = "1";
}
}
}
}
|
package demo.kanban.contract.moscow.resource.column;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resource;
/**
* Created by xchou on 4/18/16.
*/
public class ColumnResource extends Resource<Column> {
public ColumnResource(Column content, Link... links) {
super(content, links);
}
}
|
package com.tencent.mm.g.a;
public final class hu$a {
public String bKW;
}
|
package com.app.artclass.fragments;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.app.artclass.Logger;
import com.app.artclass.R;
import com.app.artclass.UserSettings;
import com.app.artclass.database.StudentsRepository;
import com.app.artclass.database.entity.GroupType;
import com.app.artclass.fragments.dialog.AddNewStudentDialog;
import com.app.artclass.fragments.dialog.AddToGroupDialog;
import com.app.artclass.fragments.dialog.AlertDialogFragment;
import com.app.artclass.fragments.dialog.DialogCreationHandler;
import com.app.artclass.recycler_adapters.GroupsListRecyclerAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
@RequiresApi(api = Build.VERSION_CODES.O)
public class GroupListFragment extends Fragment {
public GroupListFragment() {
Logger.getInstance().appendLog(getClass(),"init fragment");
}
@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.fragment_group_list, container, false);
//add adapter to update if groups are deleted
final GroupsListRecyclerAdapter groupsRecyclerAdapter = new GroupsListRecyclerAdapter(this, new ArrayList<>());
StudentsRepository.getInstance().getAllGroupTypes().observe(getViewLifecycleOwner(),groupTypeList -> {
UserSettings.getInstance().setAllGroupTypes(groupTypeList);
for (GroupType groupType : UserSettings.getInstance().getAllGroupTypes()) {
final GroupType finGroupType = groupType;
StudentsRepository.getInstance().getStudentsList(groupType).observe(getViewLifecycleOwner(), groupTypeWithStudents ->{
if(groupTypeWithStudents!=null)
groupsRecyclerAdapter.addGroup(finGroupType, groupTypeWithStudents.studentList);
});
}
});
RecyclerView groupsList = mainView.findViewById(R.id.groups_list);
groupsList.setLayoutManager(new LinearLayoutManager(getContext()));
groupsList.setAdapter(groupsRecyclerAdapter);
// set add and delete buttons
FloatingActionButton btn_floating_addnewgroup = mainView.findViewById(R.id.fab_add_new_group);
btn_floating_addnewgroup.setTag(R.id.adapter,groupsRecyclerAdapter);
btn_floating_addnewgroup.setOnClickListener(view ->{
AddToGroupDialog addNewStudentDialog = new AddToGroupDialog(groupsRecyclerAdapter, null, null);
addNewStudentDialog.show(getFragmentManager(), "AddToGroup");
});
FloatingActionButton btn_floating_helpbutton = mainView.findViewById(R.id.fab_secondary);
btn_floating_helpbutton.setOnClickListener(v ->{
AlertDialogFragment alertDialogFragment = new AlertDialogFragment(getString(R.string.title_help),getString(R.string.message_group_delete_help), null);
alertDialogFragment.show(getFragmentManager(), "AlertDialog");
});
return mainView;
}
}
|
package com.one.sugarcane.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="SELLERLOGINLOG")
public class SellerLoginLog {
private Integer ID;
private String time;
private String IP;
private SellerLogin sellerLogin;
@Id
@GeneratedValue(generator="a")
@GenericGenerator(name="a",strategy="identity")
public Integer getID() {
return ID;
}
public void setID(Integer iD) {
ID = iD;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getIP() {
return IP;
}
public void setIP(String iP) {
IP = iP;
}
@ManyToOne
@JoinColumn(name="sellerID")
public SellerLogin getSellerLogin() {
return sellerLogin;
}
public void setSellerLogin(SellerLogin sellerLogin) {
this.sellerLogin = sellerLogin;
}
public SellerLoginLog() {}
public SellerLoginLog(String time, String iP, SellerLogin sellerLogin) {
super();
this.time = time;
IP = iP;
this.sellerLogin = sellerLogin;
}
}
|
package com.tencent.mm.plugin.freewifi.ui;
import android.view.View;
import com.tencent.mm.g.a.bh;
import com.tencent.mm.plugin.freewifi.ui.a.2;
import com.tencent.mm.sdk.b.a;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.x;
class a$2$1 implements Runnable {
final /* synthetic */ View jmm;
final /* synthetic */ 2 jmn;
a$2$1(2 2, View view) {
this.jmn = 2;
this.jmm = view;
}
public final void run() {
bh bhVar = new bh();
long currentTimeMillis = System.currentTimeMillis();
a.sFg.m(bhVar);
x.i("MicroMsg.FreeWifi.FreeWifiBanner", "summeranrt CheckWechatFreeWifiEvent take[%d]ms", new Object[]{Long.valueOf(System.currentTimeMillis() - currentTimeMillis)});
ah.A(new 1(this, bhVar));
}
}
|
package sample;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Main extends Application {
TextField txtNum1, txtNum2;
Button btnAdd, btnSub, btnDiv, btnMult, btnEquals, btnClear;
Label ansLabel;
@Override
public void start(Stage primaryStage) throws Exception{
txtNum1 = new TextField();
txtNum2 = new TextField();
btnAdd = new Button("+");
btnSub = new Button("-");
btnDiv = new Button("/");
btnMult = new Button("*");
btnClear = new Button("Clear");
btnEquals = new Button("=");
ansLabel = new Label("?");
ansLabel.setAlignment(Pos.CENTER);
ansLabel.setStyle("-fx-border-color: #000, -fx-padding: 5px;");
GridPane root = new GridPane();
root.setAlignment(Pos.CENTER);
root.setHgap(10);
root.setVgap(10);
root.add(btnAdd, 0, 0);
root.add(btnSub, 1, 0);
root.add(btnDiv, 0, 1);
root.add(btnMult, 1, 1);
root.add(txtNum1, 0, 2);
root.add(txtNum2, 1, 2);
root.add(ansLabel, 0, 3, 2, 1);
root.add(btnClear, 0, 4, 2, 1);
setWidths();
attachCode();
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.setTitle("Calculator");
primaryStage.show();
// root.add(btnAdd, 2, 0)0;
// Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
// primaryStage.setTitle("Hello World");
// primaryStage.setScene(new Scene(root, 300, 275));
// primaryStage.show();
}
private void attachCode() {
btnAdd.setOnAction(e -> btnCode(e));
btnSub.setOnAction(e -> btnCode(e));
btnDiv.setOnAction(e -> btnCode(e));
btnMult.setOnAction(e -> btnCode(e));
// btnEquals.setOnAction(e -> btnCode(e));
txtNum1.setOnAction(e -> btnCode(e));
txtNum2.setOnAction(e -> btnCode(e));
btnClear.setOnAction(e -> btnCode(e));
}
private void btnCode(ActionEvent e) {
int num1, num2, answer;
char symbol;
if (e.getSource() == btnClear) {
txtNum1.setText("");
txtNum2.setText("");
ansLabel.setText("?");
txtNum1.requestFocus();
return;
}
num1 = Integer.parseInt(txtNum1.getText());
num2 = Integer.parseInt(txtNum2.getText());
if (e.getSource() == btnAdd) {
symbol = '+';
answer = num1 + num2;
} else if (e.getSource() == btnSub) {
symbol = '-';
answer = num1 - num2;
} else if (e.getSource() == btnDiv) {
symbol = '/';
answer = num1 / num2;
} else {
symbol = '*';
answer = num1 * num2;
}
ansLabel.setText(num1 + " " + symbol + " " +num2 + " = " + answer);
}
private void setWidths() {
btnAdd.setPrefWidth(70);
btnSub.setPrefWidth(70);
btnDiv.setPrefWidth(70);
btnMult.setPrefWidth(70);
// btnEquals.setPrefWidth(70);
txtNum1.setPrefWidth(70);
txtNum2.setPrefWidth(70);
btnClear.setPrefWidth(150);
ansLabel.setPrefWidth(150);
}
public static void main(String[] args) {
launch(args);
}
}
|
package com.android.mycourse.notepad;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import com.android.mycourse.MainActivity;
import com.android.mycourse.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import top.wefor.circularanim.CircularAnim;
public class NotepadFragment extends Fragment {
private SearchView svNote;
private ListView lvNote;
private FloatingActionButton fabNewNote;
private NoteHelper mNoteHelper;
private ArrayList<NoteBean> mNotes;
private NoteAdapter mNoteAdapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_notepad, container, false);
setHasOptionsMenu(true);
initView(view); // 初始化控件
initEvent(); // 初始化事件
return view;
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.menu_notepad, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// 清空备忘
if (item.getItemId() == R.id.action_notepad_clear) {
new AlertDialog.Builder(MainActivity.INSTANCE)
.setTitle(getString(R.string.dialog_title))
.setMessage(getString(R.string.notepad_clear_ask))
.setPositiveButton(getString(R.string.btn_yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(),
getString(R.string.notepad_clear_finish),
Toast.LENGTH_SHORT).show();
mNoteHelper.deleteAllNotes();
mNotes.clear();
mNoteAdapter.notifyDataSetChanged();
}
})
.setNegativeButton(getString(R.string.btn_no), null)
.show();
return true;
} // if end
return super.onOptionsItemSelected(item);
} // onOptionsItemSelected end
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
svNote.setQuery(null, true); // 清空搜索框内容,显示全部备忘
svNote.clearFocus(); // 清除搜索框焦点,避免弹出软键盘
// 获取数据
int index =
data != null ? data.getIntExtra(NotepadConstants.EXTRA_INDEX, -1) : -1;
NoteBean note =
data != null ? (NoteBean) data.getParcelableExtra(NotepadConstants.EXTRA_NOTE) : null;
if (requestCode == NotepadConstants.REQUEST_NEW) { // 新建备忘
if (resultCode == NotepadConstants.RESULT_INSERT) { // 添加备忘数据
if (note != null) {
mNotes.add(0, note); // 添加备忘到列表顶端
}
}
} else if (requestCode == NotepadConstants.REQUEST_VIEW) { // 查看备忘
if (resultCode == NotepadConstants.RESULT_UPDATE) { // 更新备忘数据
if (index >= 0 && index < mNotes.size() && note != null) {
mNotes.set(index, note);
}
} else if (resultCode == NotepadConstants.RESULT_DELETE) { // 删除备忘数据
if (index >= 0 && index < mNotes.size()) {
mNotes.remove(index);
}
}
}
mNoteAdapter.notifyDataSetChanged(); // 刷新备忘列表
} // onActivityResult end
/**
* 初始化控件
*
* @param view 布局
*/
private void initView(View view) {
svNote = view.findViewById(R.id.sv_notepad);
lvNote = view.findViewById(R.id.lv_notepad);
fabNewNote = view.findViewById(R.id.fab_notepad_new);
// 读取备忘数据
mNoteHelper = new NoteHelper(getContext());
mNotes = mNoteHelper.getAllNotes();
mNoteAdapter = new NoteAdapter(getContext(), mNotes);
lvNote.setAdapter(mNoteAdapter);
}
/**
* 初始化事件
*/
private void initEvent() {
// 监听搜索框内容变化
svNote.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
mNoteAdapter.getFilter().filter(newText); // 显示搜索结果
return true;
}
});
// 点击备忘列表查看备忘
lvNote.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
Intent intent = new Intent(getContext(), NoteViewActivity.class);
intent.putExtra(NotepadConstants.EXTRA_INDEX, i);
intent.putExtra(NotepadConstants.EXTRA_NOTE, mNotes.get(i));
startActivityForResult(intent, NotepadConstants.REQUEST_VIEW); // 进入查看备忘界面
}
});
// 长按备忘列表删除备忘
lvNote.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
final int index = i;
// 询问是否删除备忘
new AlertDialog.Builder(MainActivity.INSTANCE)
.setTitle(getString(R.string.dialog_title))
.setMessage(String.format(
getString(R.string.notepad_delete_ask), mNotes.get(index).getTitle()))
.setPositiveButton(getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(), String.format(
getString(R.string.notepad_delete_finish),
mNotes.get(index).getTitle()), Toast.LENGTH_SHORT).show();
mNoteHelper.deleteNote(mNotes.get(index));
mNotes.remove(index);
mNoteAdapter.notifyDataSetChanged();
}
})
.setNegativeButton(getString(R.string.btn_no), null)
.show();
return true;
}
});
// 点击圆形按钮新建备忘
fabNewNote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CircularAnim.fullActivity(getActivity(), view)
.go(new CircularAnim.OnAnimationEndListener() {
@Override
public void onAnimationEnd() {
Intent intent = new Intent(getContext(), NoteEditActivity.class);
intent.putExtra(NoteEditActivity.ARG_MODE, NoteEditActivity.VAL_MODE_NEW);
startActivityForResult(intent, NotepadConstants.REQUEST_NEW); // 进入新建备忘界面
}
});
}
});
} // initEvent end
}
|
package calculadora.operadoresmatrizes;
import calculadora.colecoes.Elemento;
import calculadora.colecoes.Matriz;
import calculadora.excecoes.MatrizInvalidaException;
public class DeterminantePorSarrus<T> implements OperadorUnario<T> {
@Override
public Matriz<T> calcula(Matriz<T> m) {
if (m.getTamanhoLinhas() != 3 && m.getTamanhoColunas() != 3)
throw new MatrizInvalidaException("O método de Sarrus so pode ser aplicado em matrizes de ordem 3..");
Elemento<T> el1 = m.getElemento(0, 0);
el1 = el1.multiplica(m.getElemento(1, 1));
el1 = el1.multiplica(m.getElemento(2, 2));
Elemento<T> el2 = m.getElemento(0, 1);
el2 = el2.multiplica(m.getElemento(1, 2));
el2 = el2.multiplica(m.getElemento(2, 0));
Elemento<T> el3 = m.getElemento(0, 2);
el3 = el3.multiplica(m.getElemento(1, 0));
el3 = el3.multiplica(m.getElemento(2, 1));
Elemento<T> d1 = el1.soma(el2).soma(el3);
el1 = m.getElemento(0, 2);
el1 = el1.multiplica(m.getElemento(1, 1));
el1 = el1.multiplica(m.getElemento(2, 0));
el2 = m.getElemento(0, 0);
el2 = el2.multiplica(m.getElemento(1, 2));
el2 = el2.multiplica(m.getElemento(2, 1));
el3 = m.getElemento(0, 1);
el3 = el3.multiplica(m.getElemento(1, 0));
el3 = el3.multiplica(m.getElemento(2, 2));
Elemento<T> d2 = el1.soma(el2).soma(el3);
Elemento<T> elResultado = d1.subtrai(d2);
Matriz<T> mResultado = m.getNovaInstancia(1, 1);
mResultado.setElemento(0, 0, elResultado);
return mResultado;
}
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.common.infinispan.service;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.infinispan.Cache;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.manager.CacheContainer;
import org.overlord.rtgov.common.service.CacheManager;
/**
* This class represents the Infinispan implementation of the CacheManager
* interface.
*
*/
public class InfinispanCacheManager extends CacheManager {
private static final Logger LOG=Logger.getLogger(InfinispanCacheManager.class.getName());
private String _container=null;
private CacheContainer _cacheContainer=null;
/**
* The default constructor.
*/
public InfinispanCacheManager() {
}
/**
* This method sets the JNDI name for the container resource.
*
* @param jndiName The JNDI name for the container resource
*/
public void setContainer(String jndiName) {
_container = jndiName;
}
/**
* This method returns the JNDI name used to obtain
* the container resource.
*
* @return The JNDI name for the container resource
*/
public String getContainer() {
return (_container);
}
/**
* This method returns the cache container for the current thread.
*
* @return The cache container
*/
protected CacheContainer getCacheContainer() {
if (_cacheContainer == null) {
_cacheContainer = org.overlord.rtgov.common.infinispan.InfinispanManager.getCacheContainer(_container);
}
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Returning cache container [container="+_container+"] = "+_cacheContainer);
}
return (_cacheContainer);
}
/**
* {@inheritDoc}
*/
public <K,V> Map<K,V> getCache(String name) {
CacheContainer container=getCacheContainer();
if (container == null) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Requested cache '"+name
+"', but no cache container ("+_container+")");
}
return (null);
}
Map<K,V> ret=container.<K,V>getCache(name);
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Returning cache '"+name
+"' = "+ret);
}
return (ret);
}
/**
* {@inheritDoc}
*/
public boolean lock(String cacheName, Object key) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("About to lock: "+cacheName+" key="+key);
}
CacheContainer container=getCacheContainer();
if (container != null) {
Cache<Object,Object> cache=container.getCache(cacheName);
if (cache != null) {
// Check if cache is transactional
if (cache.getAdvancedCache().getCacheConfiguration().
transaction().transactionMode() != TransactionMode.TRANSACTIONAL) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Not transactional, so returning true");
}
return true;
}
boolean ret=cache.getAdvancedCache().lock(key);
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Lock '"+cacheName
+"' key '"+key+"' = "+ret);
}
return (ret);
} else if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Cannot lock cache '"+cacheName
+"' key '"+key+"' as cache does not exist");
}
} else if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Cannot lock cache '"+cacheName
+"' key '"+key+"' as no container");
}
return false;
}
}
|
package com.store.dao;
import java.util.List;
import com.store.pojo.Building;
/**
* 区域类的 dao层
* @author Administrator
*
*/
public interface BuildingDao {
/**
* 添加区域的方法
* @param building
* @return 是否添加成功
*/
public boolean addBuilding(Building building);
/**
* 更新区域的方法
* @param building
* @return 是否更新成功
*/
public boolean updateBuilding(Building building);
/**
* 删除区域的方法
* @param id
* @return 是否删除成功
*/
public boolean delBuilding(int id);
/**
* 分页查询的方法
* @param pageSize
* @param page
* @return 分页查询到的内容
*/
public List<Building> queryAll(int pageSize,int page);
/**
* 根据id查询指定的区域对象
* @param id
* @return 唯一的区域对象
*/
public Building queryBuildingById(int id);
/**
* 查询所有的区域信息
* @return 包含所有区域信息的集合
*/
public List<Building> queryAll();
/**
* 查询一共有多少条记录
* @return 总条数
*/
public int getAllCount();
}
|
package at.fhj.swd.selenium;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import at.fhj.swd.selenium.pageobjects.LoginPage;
import at.fhj.swd.selenium.pageobjects.IndexPage;
public class AbstractTestSetup {
WebDriver driver;
LoginPage loginPage;
IndexPage indexPage;
@Before
public void setup(){
driver = new FirefoxDriver(createProfileForAutoTextFileToTempDirDownload());
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
protected void loginAdmin() {
driver.get("http://127.0.0.1:8080/fhj-ws2014-sd12-pse/login.jsf");
loginPage = new LoginPage(driver);
indexPage = loginPage.loginAdmin();
}
protected void loginAdminPa() {
driver.get("http://127.0.0.1:8080/fhj-ws2014-sd12-pse/login.jsf");
loginPage = new LoginPage(driver);
indexPage = loginPage.loginAdminPa();
}
protected void loginUser() {
driver.get("http://127.0.0.1:8080/fhj-ws2014-sd12-pse/login.jsf");
loginPage = new LoginPage(driver);
indexPage = loginPage.loginUser();
}
protected FirefoxProfile createProfileForAutoTextFileToTempDirDownload() {
String tmpDir = System.getProperty("java.io.tmpdir");
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.download.dir", tmpDir);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain");
return profile;
}
@After
public void teardown(){
driver.quit();
}
}
|
package br.com.codenation.model;
import br.com.codenation.repository.ProductRepository;
import br.com.codenation.repository.ProductRepositoryImpl;
import javax.swing.text.html.Option;
import java.util.Optional;
public class OrderItem {
private Long productId;
private Long quantity;
private ProductRepository repository = new ProductRepositoryImpl();
public OrderItem(Long productId, Long quantity) {
super();
this.productId = productId;
this.quantity = quantity;
}
public Long getProductId() {
return productId;
}
public Long getQuantity() {
return quantity;
}
public Double total() {
return this.productValue() * this.quantity;
}
private Double productValue() {
// E calcular o valor de um Product é responsabilidade do próprio;
// Aqui só estamos trabalhando com o Optional
return this.product().map(Product::saleValue).orElse(0.0);
}
private Optional<Product> product() {
return this.repository.findById(this.productId);
}
}
|
package com.tencent.mm.wallet_core.ui;
public interface MMScrollView$a {
}
|
package LeetCode.Trees;
import java.util.HashMap;
public class DisjointSets {
class NodeD{
long data;
NodeD parent;
int rank;
NodeD(){}
}
public HashMap<Long, NodeD> map = new HashMap<>();
public void makeSet(long val){
NodeD node = new NodeD();
node.data = val;
node.parent = node;
node.rank = 0;
map.put(val, node);
}
public void union(long data1, long data2){
NodeD node1 = map.get(data1);
NodeD node2 = map.get(data2);
NodeD parent1 = findParent(node1);
NodeD parent2 = findParent(node2);
if(parent1.data == parent2.data)
return;
if(parent1.rank >= parent2.rank){
parent2.parent = parent1;
// increment rank if rank of both the parents are same.
parent1.rank = parent1.rank == parent2.rank ? parent1.rank+1 : parent1.rank;
} else
parent1.parent = parent2;
}
public long findSet(long data){
return findParent(map.get(data)).data;
}
public NodeD findParent(NodeD node){
if(node.parent != node)
node.parent = findParent(node.parent);
return node.parent;
}
public static void main(String[] args){
DisjointSets s = new DisjointSets();
s.makeSet(1);
s.makeSet(2);
s.makeSet(3);
s.makeSet(4);
s.makeSet(5);
s.makeSet(6);
s.makeSet(7);
s.union(1,2);
s.union(2,3);
s.union(4,5);
s.union(6,7);
s.union(5,6);
s.union(3,7);
System.out.print(s.findSet(1));
System.out.print(s.findSet(2));
System.out.print(s.findSet(3));
System.out.print(s.findSet(4));
System.out.print(s.findSet(5));
System.out.print(s.findSet(6));
System.out.print(s.findSet(7));
}
}
|
package design;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
// 295 https://leetcode.com/problems/find-median-from-data-stream/
public class MedianFinder {
private static Map<Integer, Integer> map = new TreeMap<>();
private int count = 0;
// Adds a number into the data structure.
public void addNum(int num) {
if(map.containsKey(num)) {
int value = map.get(num);
map.put(num, value + 1);
} else map.put(num, 1);
count++;
}
// Returns the median of current data stream
public double findMedian() {
if(map.size() == 0) return 0;
int expected = (count+1) / 2;
int sum = 0;
int median1 = 0;
boolean get1 = false;
for(Entry<Integer, Integer> e : map.entrySet()) {
sum += e.getValue();
if(sum < expected);
else if(sum==expected) {
if(count % 2 != 0)
return e.getKey();
else {
median1 = e.getKey();
get1 = true;
}
} else {
if(get1 == true) {
return (e.getKey() + median1) / 2.0;
}
return e.getKey();
}
}
return 0;
}
public static void main(String[] args) {
MedianFinder mf = new MedianFinder();
mf.addNum(2);
mf.addNum(3);
mf.addNum(2);
double d = mf.findMedian();
System.out.println(d);
}
}
|
/* M86Asm
*
* A rudimentary assembler for Micro86 instructions.
*
* Author: Humam Rashid
*
* Assignment: 03-M86Asm
*
* Class: CISC-3160, Programming Languages
*/
import java.io.*;
import java.util.*;
import java.text.*;
public class M86Asm {
private boolean showData = false;
private Micro86DataSet dataSet = new Micro86DataSet();
private boolean m86Instruct = false, cppCode = false;
private final String m86Comment = ";", labelDelim = ":";
/* Class for objects representing intermediate code. */
private class IntermediateCode {
private int opcode;
private String operand;
/* Initialize intermediate code object. */
public IntermediateCode(int opcode, String operand) {
this.opcode = opcode;
this.operand = operand;
return;
}
/* Return opcode. */
public int getOpcode() {
return opcode;
}
/* Return operand. */
public String getOperand() {
return operand;
}
/* Set opcode. */
public void setOpcode(int opcode) {
this.opcode = opcode;
return;
}
/* Set operand. */
public void setOperand(String operand) {
this.operand = operand;
return;
}
/* Return String representation of intermediate code. */
public String toString() {
return ("Opcode: " + opcode + " "
+ "Operand: " + operand);
}
}
/* Class for representing a translation into Micro86 instructions.
* */
private class Micro86Translation {
private int position = 1;
private Map<String, Integer> labels = null,
variables = null, varPositions = null;
private List<IntermediateCode> instructions = null;
/* Initialize maps/tables and lists. */
public Micro86Translation() {
labels = new TreeMap<String, Integer>();
variables = new TreeMap<String, Integer>();
varPositions = new TreeMap<String, Integer>();
instructions = new ArrayList<IntermediateCode>();
return;
}
/* Initialize maps/tables and lists and add one set of
* translation elements. */
public Micro86Translation(String name,
int value, IntermediateCode instruction) {
this();
addVariable(name, value);
addInstruction(instruction);
return;
}
/* Return label name to label position table. */
public Map<String, Integer> getLabels() {
return labels;
}
/* Return variable name to variable value table. */
public Map<String, Integer> getVariables() {
return variables;
}
/* Return variable name to variable position table. */
public Map<String, Integer> getVarPositions() {
return varPositions;
}
/* Add a label with specified name and position. */
public void addLabel(String name, int value) {
labels.put(name, value);
return;
}
/* Add a variable with specified name and value. */
public void addVariable(String name, int value) {
variables.put(name, value);
varPositions.put(name, position++);
return;
}
/* Return list of instructions. */
public List<IntermediateCode> getInstructions() {
return instructions;
}
/* Add an instruction. */
public void addInstruction(IntermediateCode instruction) {
instructions.add(instruction);
return;
}
/* Return number of instructions in translation. */
public int numInstructions() {
return instructions.size();
}
/* Return number of variables in translation. */
public int numVariables() {
return variables.size();
}
/* Return number of labels in translation. */
public int numLabels() {
return labels.size();
}
@Override
/* Return String representation of translation. */
public String toString() {
String values = "";
if (instructions.size() > 0) {
values += "Instructions:\n";
for (IntermediateCode ic : instructions) {
values += "\n"
+ ic.getOpcode() + " " + ic.getOperand();
}
values += "\n";
}
if (variables.size() > 0) {
values += "\nVariable values:\n";
for (Map.Entry<String,
Integer> e : variables.entrySet()) {
values += "\n" + e.getKey() + " " + e.getValue();
}
}
if (varPositions.size() > 0) {
values += "\nVariable positions:\n";
for (Map.Entry<String,
Integer> e : varPositions.entrySet()) {
values += "\n" + e.getKey() + " " + e.getValue();
}
}
if (labels.size() > 0) {
values += "\nLabel positions:\n";
for (Map.Entry<String,
Integer> e : labels.entrySet()) {
values += "\n" + e.getKey() + " " + e.getValue();
}
}
return values;
}
}
/* Class for representing a translation to C++ code. */
private class CPPTranslation {
private List<String[]> operations = null;
private Map<Integer, String> labels = null;
private Map<String, Integer> variables = null;
/* Initialize maps/tables and lists. */
public CPPTranslation() {
operations = new ArrayList<String[]>();
labels = new TreeMap<Integer, String>();
variables = new TreeMap<String, Integer>();
return;
}
/* Initialize maps/tables and lists and add one set of
* translation elements. */
public CPPTranslation(String name,
int value, String[] operation) {
this();
addVariable(name, value);
addOperation(operation);
return;
}
/* Return label position to label name table. */
public Map<Integer, String> getLabels() {
return labels;
}
/* Return variable name to variable position table. */
public Map<String, Integer> getVariables() {
return variables;
}
/* Add a label with specified position and name. */
public void addLabel(int value, String name) {
labels.put(value, name);
return;
}
/* Add a variable with specified name and value. */
public void addVariable(String name, int value) {
variables.put(name, value);
return;
}
/* Return list of operations. */
public List<String[]> getOperations() {
return operations;
}
/* Add an operation. */
public void addOperation(String[] operation) {
operations.add(operation);
return;
}
/* Return number of operations in translation. */
public int numOperations() {
return operations.size();
}
/* Return number of variables in translation. */
public int numVariables() {
return variables.size();
}
/* Return number of labels in translation. */
public int numLabels() {
return labels.size();
}
@Override
/* Return String representation of translation. */
public String toString() {
String values = "";
if (operations.size() > 0) {
values += "Operations:\n";
for (String[] op: operations) {
if (op.length == 1) values += "\n" + op[0];
else values += "\n" + op[0] + " " + op[1];
}
values += "\n";
}
if (variables.size() > 0) {
values += "\nVariable values:\n";
for (Map.Entry<String,
Integer> e : variables.entrySet()) {
values += "\n" + e.getKey() + " " + e.getValue();
}
}
if (labels.size() > 0) {
values += "\nLabel positions:\n";
for (Map.Entry<Integer,
String> e : labels.entrySet()) {
values += "\n" + e.getKey() + " " + e.getValue();
}
}
return values;
}
}
/* Write Micro86 instructions to specified destination. */
private void writeM86Code(
Micro86Translation translation,
PrintStream dest, String[] fileNames, long started) {
String metaData = "", output = "";
List<IntermediateCode> instructList =
translation.getInstructions();
Map<String, Integer>
labelTable = translation.getLabels(),
varTable = translation.getVariables(),
varPositionsTable = translation.getVarPositions();
final int
varCount = translation.numVariables(),
labelCount = translation.numLabels(),
instructCount = translation.numInstructions();
Micro86DataSet.DecodedInstructionFormat dif =
dataSet.new DecodedInstructionFormat(0, 0);
metaData += "# Micro86 instructions.%n"
+ "# Assembled using M86Asm.%n"
+ "# Dated: "
+ new SimpleDateFormat("HH:mm:ss, MM/dd/yyyy").format(
Calendar.getInstance().getTime())
+ ".%n# Approx. assembling time: "
+ (System.currentTimeMillis() - started)
+ " ms.%n# Number of instructions: "
+ instructCount
+ ".%n# Number of memory units allocated: "
+ varCount
+ ".%n%n# === CODE === #%n%n";
for (IntermediateCode ic: instructList) {
dif.setOpcode(ic.getOpcode());
String operand = ic.getOperand();
if (operand != null) {
if (dataSet.isImmediateOpcode(dif.getOpcode())) {
try {
dif.setOperand(Integer.parseInt(operand));
} catch(NumberFormatException nfe) {
if (!labelTable.containsKey(operand))
syntaxError(fileNames[0]);
dif.setOperand(labelTable.get(operand));
}
} else {
if (!varTable.containsKey(operand))
syntaxError(fileNames[0]);
dif.setOperand((instructCount
+ varPositionsTable.get(
operand)) - 1);
}
}
output += dif.encoded() + "%n";
}
if (varCount > 0) {
for (Map.Entry<String, Integer> e: varTable.entrySet()) {
output +=
dataSet.stdInstructFormat(e.getValue()) + "%n";
}
}
if (!showData) dest.printf(output);
else dest.printf(metaData + output + "%n# === EOF === #%n");
if (fileNames[1] != null) {
System.out.printf("Micro86 instructions written to: %s%n",
fileNames[1]);
}
return;
}
/* Write C++ code to specified destination. */
private void writeCPPCode(CPPTranslation translation,
PrintStream dest, String[] fileNames, long started) {
String output = "", metaData= "";
Map<Integer, String> labelTable = translation.getLabels();
Map<String, Integer> varTable = translation.getVariables();
List<String[]> operationList = translation.getOperations();
final int
varCount = translation.numVariables(),
labelCount = translation.numLabels(),
operationCount = translation.numOperations();
metaData += "// C++ code.%n"
+ "// Translated using M86Asm.%n"
+ "// Dated: "
+ new SimpleDateFormat("HH:mm:ss, MM/dd/yyyy").format(
Calendar.getInstance().getTime())
+ ".%n// Approx. translating time: "
+ (System.currentTimeMillis() - started)
+ " ms.%n// Number of operations: "
+ operationCount
+ ".%n// Number of memory units allocated: "
+ varCount
+ ".%n%n// === CODE === //%n%n";
output += "#include <iostream>%n#include <cstdlib>%n"
+ "using namespace std;%n%nint main() {%n"
+ "int _acc = 0, _cmp;%n"
+ "char _byte;%n"
+ "cin >> noskipws;%n";
output += "%n"
+ "// === Declarations === %n%n";
if (varCount > 0) {
for (Map.Entry<String, Integer> e: varTable.entrySet()) {
output += "int "
+ e.getKey() + " = " + e.getValue() + ";%n";
}
}
output += "%n"
+ "// === Operations === %n%n";
int iPos;
for (String[] op: operationList) {
iPos = Integer.parseInt(op[2]);
if (labelTable.containsKey(iPos))
output += labelTable.get(iPos) + ": ";
switch (dataSet.getOpcode(op[0])) {
case 0x0100:
output += "exit(0);%n";
break;
case 0x0201:
case 0x0202:
output += "_acc = " + op[1] + ";%n";
break;
case 0x0302:
output += "" + op[1] + " = " + "_acc;%n";
break;
case 0x401:
case 0x402:
output += "_acc += " + op[1] + ";%n";
break;
case 0x0501:
case 0x0502:
output += "_acc -= " + op[1] + ";%n";
break;
case 0x0601:
case 0x0602:
output += "_acc *= " + op[1] + ";%n";
break;
case 0x0701:
case 0x0702:
output += "_acc /= " + op[1] + ";%n";
break;
case 0x0801:
case 0x0802:
output += "_acc %%= " + op[1] + ";%n";
break;
case 0x0901:
case 0x0902:
output += "_cmp = _acc - " + op[1] + ";%n";
break;
case 0x0A01:
output += "goto " + op[1] + ";%n";
break;
case 0x0B01:
output += "if (_cmp == 0) goto " + op[1] + ";%n";
break;
case 0x0C01:
output += "if (_cmp != 0) goto " + op[1] + ";%n";
break;
case 0x0D01:
output += "if (_cmp < 0) goto " + op[1] + ";%n";
break;
case 0x0E01:
output += "if (_cmp <= 0) goto " + op[1] + ";%n";
break;
case 0x0F01:
output += "if (_cmp > 0) goto " + op[1] + ";%n";
break;
case 0x1001:
output += "if (_cmp >= 0) goto " + op[1] + ";%n";
break;
case 0x1100:
output += "cin >> _byte;%n_acc = (int) _byte;%n";
case 0x1200:
output += "cout << (char) _acc;%n";
break;
}
}
output += "%n// === HALT Bypassed === %n%nexit(1);%n}%n";
if (!showData) dest.printf(output);
else dest.printf(metaData + output + "%n// === EOF === //%n");
if (fileNames[1] != null) {
System.out.printf("C++ code written to: %s%n",
fileNames[1]);
}
return;
}
/* Return a parse to micro86 instructions. */
private Micro86Translation parseM86(String code) {
int iPos = 0;
String label = null;
String[] tokens = code.split("\\s+");
Micro86Translation translation = new Micro86Translation();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].endsWith(labelDelim)) {
label = tokens[i].substring(
0, tokens[i].length() - 1);
if (!validIdentifier(label)) return null;
translation.addLabel(label, iPos);
i++;
}
if (dataSet.isValidMnemonic(tokens[i])) {
if (dataSet.mnemonicHasOperand(tokens[i])) {
translation.addInstruction(new IntermediateCode(
dataSet.getOpcode(tokens[i]),
tokens[i + 1]));
i++;
} else {
translation.addInstruction(new IntermediateCode(
dataSet.getOpcode(tokens[i]), null));
}
iPos++;
} else {
if (tokens[i].equals(dataSet.getDeclrLookahead())) {
if (validIdentifier(tokens[i + 1])) {
translation.addVariable(tokens[i + 1],
Integer.parseInt(tokens[i + 2]));
} else {
return null;
}
i += 2;
} else {
return null;
}
}
}
return translation;
}
/* Return a parse to C++ code. */
private CPPTranslation parseCPP(String code) {
int iPos = 0;
String label = null;
String[] tokens = code.split("\\s+");
CPPTranslation translation = new CPPTranslation();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].endsWith(labelDelim)) {
label = tokens[i].substring(
0, tokens[i].length() - 1);
if (!validIdentifier(label)) return null;
translation.addLabel(iPos, label);
i++;
}
if (dataSet.isValidMnemonic(tokens[i])) {
if (dataSet.mnemonicHasOperand(tokens[i])) {
translation.addOperation(
new String[]{tokens[i], tokens[i + 1],
String.valueOf(iPos)});
i++;
} else {
translation.addOperation(
new String[]{tokens[i], null,
String.valueOf(iPos)});
}
iPos++;
} else {
if (tokens[i].equals(dataSet.getDeclrLookahead())) {
if (validIdentifier(tokens[i + 1])) {
translation.addVariable(tokens[i + 1],
Integer.parseInt(tokens[i + 2]));
} else {
return null;
}
i += 2;
} else {
return null;
}
}
}
return translation;
}
/* Read assembly source and write out translation in Micro86
* instructions and/or C++ code. */
public void readSource(String[] fileNames) {
Scanner input = null;
PrintStream dest = null;
try {
input = new Scanner(new BufferedReader(
new FileReader(fileNames[0])));
if (fileNames[1] != null)
dest = new PrintStream(fileNames[1]);
else dest = System.out;
String text = "", code = "";
while (input.hasNext()) {
text = input.next();
if (text.startsWith(m86Comment))
text = input.nextLine();
else code += text + " ";
}
if (code.isEmpty()) return;
long started;
if (m86Instruct) {
Micro86Translation m86Translation;
started = System.currentTimeMillis();
if ((m86Translation = parseM86(code)) == null)
syntaxError(fileNames[0]);
writeM86Code(m86Translation,
dest, fileNames, started);
}
if (cppCode) {
CPPTranslation cppTranslation;
started = System.currentTimeMillis();
if ((cppTranslation = parseCPP(code)) == null)
syntaxError(fileNames[0]);
writeCPPCode(cppTranslation,
dest, fileNames, started);
}
} catch(IOException ioe) {
System.out.println(ioe.getMessage());
System.exit(2);
} finally {
if (input != null) input.close();
if (fileNames[1] != null && dest != null)
dest.close();
}
return;
}
/* Process commandline arguments. */
public String[] processCMDLine(String[] args) {
boolean error = false;
String inFileName = null, outFileName = null;
for (String arg : args) {
if (arg.startsWith("-")) {
if (arg.substring(1).startsWith("in=")) {
inFileName = arg.substring(4);
} else if (arg.substring(1).startsWith("out=")) {
outFileName = arg.substring(5);
} else if (arg.substring(1).equals("M86")) {
m86Instruct = true;
} else if (arg.substring(1).equals("C++")) {
cppCode = true;
} else if (arg.substring(1).equals("data")) {
showData = true;
} else {
error = true;
}
} else {
error = true;
}
}
if (inFileName == null
|| !(m86Instruct || cppCode) || error) {
System.err.printf("Usage: M86Asm <-M86 | -C++>"
+ " <-in=in_file> [-out=out_file | -data]%n");
System.exit(1);
}
return (new String[]{inFileName, outFileName});
}
/* Verify validity of identifier.
* Same rules as Java with reserved words for Micro86. */
private boolean validIdentifier(String name) {
if (dataSet.isReservedWord(name) ||
!Character.isJavaIdentifierStart(name.charAt(0)))
return false;
for (int i = 1; i < name.length(); i++) {
if (!Character.isJavaIdentifierPart(name.charAt(i)))
return false;
}
return true;
}
/* Indicate syntax error by file name. */
private void syntaxError(String fileName) {
System.err.printf("Invalid syntax in %s!%n", fileName);
System.exit(3);
return;
}
public static void main(String[] args) {
M86Asm asm = new M86Asm();
asm.readSource(asm.processCMDLine(args));
return;
}
}
// EOF.
|
package br.com.labbs.workout.httpclientbattle;
import br.com.labbs.workout.httpclientbattle.shared.HttpClient;
import skinny.http.HTTP;
import skinny.http.Request;
import skinny.http.Response;
public class Skinny implements HttpClient<Request, Response> {
private static final String SKINNY = "Skinny";
private final HTTP http = new HTTP();
@Override
public String getClientName() {
return SKINNY;
}
@Override
public Request newRequest(String url) {
return Request.apply(url);
}
@Override
public void addHeaderToRequest(Request request, String key, String value) {
request = request.header(key, value);
}
@Override
public Response execRequest(Request request, int i) throws Exception {
return http.get(request);
}
@Override
public int getResponseStatusCode(Response response) {
return response.status();
}
}
|
package io.flexio.services.api.documentation.handlers;
import io.flexio.services.api.documentation.Exceptions.ResourceNotFoundException;
import io.flexio.services.api.documentation.ResourcesManager.ResourcesManager;
import io.flexio.services.api.documentation.ResourcesManager.TestResourcesManager;
import io.flexio.services.api.documentation.api.ModulesGetRequest;
import io.flexio.services.api.documentation.api.ModulesGetResponse;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class GetModulesTest {
@Test
public void givenNoParameter__thenResponse400() {
ResourcesManager fs = new TestResourcesManager();
ModulesGetRequest mgr = ModulesGetRequest.builder().build();
ModulesGetResponse response = new GetModules(fs).apply(mgr);
assertTrue(response.opt().status400().isPresent());
}
@Test
public void givenNoParameter__whenNoFile__thenResponse200() {
ResourcesManager fs = new TestResourcesManager() {
@Override
public List<String> getModules(String group) throws ResourceNotFoundException {
return new ArrayList<String>();
}
};
ModulesGetRequest mgr = ModulesGetRequest.builder().group("g").build();
ModulesGetResponse response = new GetModules(fs).apply(mgr);
assertTrue(response.opt().status200().isPresent());
assertThat(response.opt().status200().payload().get().size(), is(0));
}
@Test
public void givenNoParameter__when1File__thenResponse200() {
ResourcesManager fs = new TestResourcesManager() {
@Override
public List<String> getModules(String group) throws ResourceNotFoundException {
List<String> list = new ArrayList<String>();
list.add("plok");
return list;
}
};
ModulesGetRequest mgr = ModulesGetRequest.builder().group("g").build();
ModulesGetResponse response = new GetModules(fs).apply(mgr);
assertTrue(response.opt().status200().isPresent());
assertThat(response.opt().status200().payload().get().size(), is(1));
}
@Test
public void givenOkParameters__whenNoDir__thenResponse404() {
ResourcesManager fs = new TestResourcesManager() {
@Override
public List<String> getModules(String group) throws ResourceNotFoundException {
throw new ResourceNotFoundException();
}
};
ModulesGetRequest mgr = ModulesGetRequest.builder().group("g").build();
ModulesGetResponse response = new GetModules(fs).apply(mgr);
assertTrue(response.opt().status404().isPresent());
}
}
|
package br.ita.sem2dia1.AprofundandoClassesJava.escola;
//passo 1 programamos de forma estruturada para comparar
//passo 2 programamos de forma O.O para comparar
public class Principal {
public static void main(String[] args) {
Aluno samuel = new Aluno();
samuel.bim1=60;
samuel.bim2=80;
samuel.bim3=70;
samuel.bim4=70;
//fica mais intuitivo perguntar ao aluno "o que ele sabe fazer?"
//Quais seus metodos
//vc passou de ano?
System.out.println(samuel.media());
System.out.println(samuel.passouDeAno());
//Estruturado:
/*
System.out.println(samuel.mediaAluno(VerificadoraDeNotas));
System.out.println(VerificadoraDeNotas.passouDeAno(samuel));
*/
}
}
|
package com.company.util;
import java.io.*;
/**
* Created by daisongsong on 2017/5/16.
*/
public class FileUtil {
public static String readFile(String path) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File f = new File(path);
InputStream inputStream = null;
try {
inputStream = new FileInputStream(f);
byte[] buffer = new byte[1024];
int count = inputStream.read(buffer);
while (count > 0) {
byteArrayOutputStream.write(buffer, 0, count);
count = inputStream.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return byteArrayOutputStream.toString();
}
public static void writeFile(String path, String content) {
File file = new File(path);
OutputStream outputStream = null;
try {
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
outputStream = new FileOutputStream(file);
outputStream.write(content.getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
package com.monitora.monitoralog.domain.model;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.groups.ConvertGroup;
import javax.validation.groups.Default;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
import com.monitora.monitoralog.domain.ValidationGroups;
import com.monitora.monitoralog.domain.exception.DomainException;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Getter
@Setter
@Entity
public class Entrega {
@EqualsAndHashCode.Include
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Valid
@ConvertGroup(from = Default.class, to = ValidationGroups.ClientId.class)
@NotNull
@ManyToOne
private Cliente cliente;
@OneToMany(mappedBy = "entrega", cascade = CascadeType.ALL)
private List<Ocorrencia> ocorrencias = new ArrayList<>();
@NotNull
@Valid
@Embedded
private Destinatario destinatario;
@NotNull
private BigDecimal taxa;
@Enumerated(EnumType.STRING)
@JsonProperty(access = Access.READ_ONLY)
private StatusEntrega status;
@JsonProperty(access = Access.READ_ONLY)
private OffsetDateTime DataPedido;
@JsonProperty(access = Access.READ_ONLY)
private OffsetDateTime dataFinalizacao;
public Ocorrencia adicionarOcorrencia(String descricao) {
Ocorrencia ocorrencia = new Ocorrencia();
ocorrencia.setDescricao(descricao);
ocorrencia.setDataRegistro(OffsetDateTime.now());
ocorrencia.setEntrega(this);
ocorrencias.add(ocorrencia);
return ocorrencia;
}
public void finalizar() {
if(!podeSerFinalizada()) {
throw new DomainException("Entrega não pode ser finalizada, pois seu status não está pendente");
}
setStatus(StatusEntrega.FINALIZADA);
setDataFinalizacao(OffsetDateTime.now());
}
public boolean podeSerFinalizada() {
return StatusEntrega.PENDENTE.equals(this.getStatus());
}
}
|
package me.solidev.library.ui.widget.subscribeview;
/**
* Created by _SOLID
* Date:2016/10/17
* Time:16:54
* Desc:
*/
public interface SubscribeItem {
//频道所属类别
String getCategory();
void setCategory(String category);
//频道标题
void setTitle(String title);
String getTitle();
//是否固定
void setIsFix(int isFix);
int getIsFix();
//是否订阅
void setIsSubscribe(int isSubscribe);
int getIsSubscribe();
//频道排序
void setSort(int sort);
int getSort();
}
|
package com.xuecheng;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.xuecheng.test.freemarker.FreemarkerTestApplication;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = FreemarkerTestApplication.class)
public class TestCreateTemplate {
@Autowired
private GridFsTemplate gridFsTemplate;
@Autowired
private GridFSBucket gridFSBucket;
@Test
public void testGenerateHtml() throws IOException, TemplateException {
//创建配置类
Configuration configuration = new Configuration(Configuration.getVersion());
//设置模板路径
String classPath = this.getClass().getResource("/").getPath();
configuration.setDirectoryForTemplateLoading(new File(classPath + "/templates/"));
//设置字符集
configuration.setDefaultEncoding("utf-8");
//加载模板
Template template = configuration.getTemplate("test1.ftlh");
//数据模型
Map<String, Object> map = new HashMap<>();
map.put("name", "黑马程序员");
//静态化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
System.out.println(content);
//输出文件
//InputStream in = new ByteArrayInputStream(content.getBytes(), 0, content.getBytes().length);
InputStream inputStream = IOUtils.toInputStream(content, "utf-8");
FileOutputStream fileOutputStream = new FileOutputStream(new File("e:/test1.html"));
IOUtils.copy(inputStream, fileOutputStream);
}
@Test
public void testGenerateHtmlByString() throws IOException, TemplateException {
//创建配置类
Configuration configuration = new Configuration(Configuration.getVersion());
//设置模板
String templateString = "" +
"<html>\n" +
" <head></head>\n" +
" <body>\n" +
" 名称:${name}\n" +
" </body>\n" +
"</html>";
StringTemplateLoader templateLoader = new StringTemplateLoader();
templateLoader.putTemplate("template", templateString);
configuration.setTemplateLoader(templateLoader);
//设置字符集
configuration.setDefaultEncoding("utf-8");
//加载模板
Template template = configuration.getTemplate("template");
//数据模型
Map<String, Object> map = new HashMap<>();
map.put("name", "黑马程序员");
//静态化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
System.out.println(content);
//输出文件
InputStream inputStream = IOUtils.toInputStream(content, "utf-8");
FileOutputStream fileOutputStream = new FileOutputStream(new File("e:/test1.html"));
IOUtils.copy(inputStream, fileOutputStream);
}
@Test
public void testGridFs() throws FileNotFoundException {
//要存储的文件
File file = new File("e:/course.ftlh");
//定义输入流
FileInputStream inputStram = new FileInputStream(file);
//向GridFS存储文件
ObjectId objectId = gridFsTemplate.store(inputStram, "课程详情模板文件测试1", "utf-8");
//得到文件ID
String fileId = objectId.toString();
System.out.println(fileId);
}
@Test
public void queryFile() throws IOException {
}
//删除文件
@Test
public void testDelFile() throws IOException {
//根据文件id删除fs.files和fs.chunks中的记录
gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5f1bb08c467c6a7b0d675804")));
}
}
|
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import org.junit.FixMethodOrder;
import org.junit.Test;
/**
* This BigNumArithmetic class tests the a “BigNumArithmetic” class or infinite
* precision arithmetic package for non-negative integers.
* @author maneeshavenigalla maneesha24@vt.edu
* @version 1.0
*
*/
@FixMethodOrder()
public class BigNumArithmeticTest {
private BigNumArithmetic bigNum = new BigNumArithmetic();
/**
* @throws IOException
* returns true if the condition passes
* checks for test file
*/
@Test
public void testFileTest() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
bigNum.main(new String[]{"SampleInput.txt"});
assertNotNull(outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for invalid rpn equation
*/
@Test
public void invalidRPNTest() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("2 8 + 2");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("2 8 + 2 =",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for simple addition
*/
@Test
public void simpleTwoAdditionTest() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("2 8 +");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("2 8 + = 10",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for complex three number addition
*/
@Test
public void complexThreeAdditionTest() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("1999999999 29999999999 + 39999999999 +");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("1999999999 29999999999 + 39999999999 + = 71999999997",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for simple mul of two numbers
*/
@Test
public void simpleTwoMultiplicationTest() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("3 4 *");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("3 4 * = 12",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for complex three number mul
*/
@Test
public void complexThreeMultiplicationTest() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("3 4 * 12 *");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("3 4 * 12 * = 144",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for simple exponentiation
*/
@Test
public void simpleExponentTest() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("2 8 ^");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("2 8 ^ = 256",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for series of complex exponentiation
*/
@Test
public void complexExponentTest() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("1000000 3 ^");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("1000000 3 ^ = 1000000000000000000",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for three number complex exponentiation
*/
@Test
public void complexThreeNumExponentTest() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("1000000 3 ^ 2 * 1 ^");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("1000000 3 ^ 2 * 1 ^ = "
+ "2000000000000000000",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for rpn equation
*/
@Test
public void complexThreeNumExponentTest2() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("5 10 ^ 2 * 1 ^");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("5 10 ^ 2 * 1 ^ = "
+ "19531250",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for unparsed rpn equation
*/
@Test
public void parsedMultipplication() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("9 1 + 5 * 00000000 +");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("9 1 + 5 * 00000000 + = 50",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for rpn equation 1
*/
@Test
public void rpnEquationTest1() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("000000056669777 99999911111 + "
+ "352324012 + 03 ^ 555557778 *");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("000000056669777 99999911111 + "
+ "352324012 + 03 ^ 555557778 * = "
+ "562400792227677956625810678708149922000000",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for rpn equation 2
*/
@Test
public void rpnEquationTest2() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("99999999 990001 * 01119111 55565 33333 "
+ "+ * + 88888888 +");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("99999999 990001 * 01119111 55565 33333 "
+ "+ * + 88888888 + = "
+ "99099674628565",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for rpn equation 3
*/
@Test
public void rpnEquationTest3() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("9 1 + 5 * 00000000 +");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("9 1 + 5 * 00000000 + = "
+ "50",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for rpn equation 4
*/
@Test
public void rpnEquationTest4() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("999999999 0 *");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("999999999 0 * = "
+ "0",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for rpn equation 5
*/
@Test
public void rpnEquationTest5() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("9 0 ^");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("9 0 ^ = "
+ "1",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for rpn equation 6
*/
@Test
public void rpnEquationTest6() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("5555555 333333 5454353 999999 666666 01 ^ * * +");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("5555555 333333 5454353 999999 666666 01 ^ * * + =",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for rpn equation 7
*/
@Test
public void rpnEquationTest7() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("3432 3333 9999 + * ^ * * 6666 +");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("3432 3333 9999 + * ^ * * 6666 + =",
outputStreamCaptor.toString().trim());
}
/**
* @throws IOException
* returns true if the condition passes
* checks for large exponent power
*/
@Test
public void rpnEquationTest8() throws IOException {
final ByteArrayOutputStream outputStreamCaptor =
new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStreamCaptor));
FileWriter myWriter = new FileWriter("test-file.txt");
myWriter.write("123456 123 ^");
myWriter.close();
bigNum.main(new String[]{"test-file.txt"});
assertEquals("123456 123 ^ = 18030210630404480750814092"
+ "7865938572807342688638559680488440159857958502360"
+ "81373250219782696986322573087163043641979475893207"
+ "43503803676976498146265429266026647072758742692017"
+ "777439123131975163236902212747138458954577487353094"
+ "843371913732555279282717852063829679989843304821053"
+ "509422299706770549408382109369523039394016567561276"
+ "077785996672437028140727462194319422930054164116350"
+ "7602129604549330513364561556659073596565258793429042"
+ "5473827719935012870093575987789431818047013404691795"
+ "7731704057646146460549492988461846782968136255953333"
+ "1161138525173524450544844305005054716177922974913448"
+ "9643622579100908331839817426366854332416",
outputStreamCaptor.toString().trim());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.