text
stringlengths 10
2.72M
|
|---|
/**
*
*/
package com.controlelancamento.domain;
import java.math.BigDecimal;
import javax.persistence.Embeddable;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
@Embeddable
public class TotalControleLancamento {
private Integer quantidadeLancamentos;
private Integer quantidadeRemessas;
private BigDecimal valorLancamentos;
private Integer totalElements;
private Integer tamanhoPagina;
private Integer indice;
public TotalControleLancamento(){
}
}
|
package com.logzc.webzic.reflection.type;
/**
* Created by lishuang on 2016/7/25.
*/
public class TypeTestBean {
private TypeTestBean(String good) {
System.out.println(good);
}
public TypeTestBean(int a) {
System.out.println(a);
}
public <T> void hello(String a, T num,int a1,boolean b,char c,Integer d, @TypeAnnotation boolean e) {
System.out.println(a);
}
}
|
@Override
public void setSheetName(int sheetIndex, String sheetname) {
//R: Here throwing NullPointerException would be clearer than throwing IllegalArgumentException.
//R: because setSheetName have to check null parameters (null bug) not that if the parameter does not satisy its condion
//R: it is better to use try-catch
if (sheetname == null) {
throw new IllegalArgumentException( "sheetName must not be null" );
}
validateSheetIndex(sheetIndex);
String oldSheetName = getSheetName(sheetIndex);
// YK: Mimic Excel and silently truncate sheet names longer than 31 characters
//R: I think if there are desision can be made with out impacting on user,
//the programmer have to make them and forcing user to enter no longer than 31 characters
//so, there is no need to ask user for cutting,the user does not know what is the better for effective software
if(sheetname.length() > 31) {
sheetname = sheetname.substring(0, 31);
}
WorkbookUtil.validateSheetName(sheetname);
// Do nothing if no change
//R:it must be at the begin of the method and must have throwing exception
if (sheetname.equals(oldSheetName)) {
return;
}
//R: Check it isn't already taken
//R: All previous checks are same as this one line 28-30
if (containsSheet(sheetname, sheetIndex )) {
throw new IllegalArgumentException( "The workbook already contains a sheet of this name" );
}
// Update references to the name
XSSFFormulaUtils utils = new XSSFFormulaUtils(this);
utils.updateSheetName(sheetIndex, oldSheetName, sheetname);
workbook.getSheets().getSheetArray(sheetIndex).setName(sheetname);
}
|
package com.bestseller.common.session;
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class HttpSessionProvider implements SessionProvider {
@Override
public void setAttribute(HttpServletResponse response,HttpServletRequest request, String name, Serializable value) {
HttpSession session = request.getSession();
session.setAttribute(name, value);
}
@Override
public Serializable getAttribute(HttpServletResponse response,HttpServletRequest request, String name) {
HttpSession session = request.getSession(false);
if(null!=session){
return (Serializable) session.getAttribute(name);
}
return null;
}
@Override
public String getSessionId(HttpServletResponse response,HttpServletRequest request) {
return request.getSession().getId();
}
@Override
public void logout(HttpServletResponse response,HttpServletRequest request) {
HttpSession session = request.getSession(false);
if(session!=null){
session.invalidate();
}
}
}
|
package com.syscxp.biz.service.activiti.businessApprove;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.stereotype.Component;
/**
* @Author: sunxuelong.
* @Cretion Date: 2018-09-12.
* @Description: .
*/
@Component(value = "completeTaskListener")
public class CompleteTaskListener implements TaskListener {
@Override
public void notify(DelegateTask delegateTask) {
System.out.println("this is a task listener:" + delegateTask.getEventName());
}
}
|
package general.store;
public class CashierSpeedCalculator {
UniformRandomStream random;
public CashierSpeedCalculator(float min, float max, int seed) {
random = new UniformRandomStream(min, max, seed);
}
public double getTime() {
return random.next();
}
}
|
package com.emg.projectsmanage.common;
/**
* 属性错误
*
* @author zsen
*
*/
public enum ProptyErrorType {
/**
* 无
*/
NONE(21100010000L, "无"),
/**
* 错别字
*/
TYPOS(21100010001L, "错别字"),
/**
* 未按规则制作
*/
ILLEGAL(21100010002L, "未按规则制作"),
/**
* 多制作
*/
EXTRA(21100010003L, "多制作"),
/**
* 漏制作
*/
MISS(21100010004L, "漏制作"),
/**
* 未对保密信息处理
*/
SECRECY(21100010005L, "未对保密信息处理");
private Long value;
private String des;
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
private ProptyErrorType(Long value, String des) {
this.setValue(value);
this.des = des;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
}
|
package be.openclinic.system;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.ScreenHelper;
import java.sql.Connection;
import java.sql.Timestamp;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* Created by IntelliJ IDEA.
* User: mxs-rudy
* Date: 19-mrt-2007
* Time: 18:03:19
* To change this template use File | Settings | File Templates.
*/
public class Document {
private int id;
private String type;
private String format;
private String name;
private String filename;
private int userid;
private String folder;
private Timestamp updatetime;
private int personid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getFolder() {
return folder;
}
public void setFolder(String folder) {
this.folder = folder;
}
public Timestamp getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Timestamp updatetime) {
this.updatetime = updatetime;
}
public int getPersonid() {
return personid;
}
public void setPersonid(int personid) {
this.personid = personid;
}
public static Document getDocumentByID(String sID){
PreparedStatement ps = null;
ResultSet rs = null;
String sSelect = "select * from Documents where id=?";
Document document = null;
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
ps = oc_conn.prepareStatement(sSelect);
ps.setInt(1,Integer.parseInt(sID));
rs = ps.executeQuery();
if(rs.next()){
document = new Document();
document.setId(Integer.parseInt(sID));
document.setType(ScreenHelper.checkString(rs.getString("type")));
document.setFormat(ScreenHelper.checkString(rs.getString("format")));
document.setName(ScreenHelper.checkString(rs.getString("name")));
document.setFilename(ScreenHelper.checkString(rs.getString("filename")));
document.setUserid(rs.getInt("userid"));
document.setFolder(ScreenHelper.checkString(rs.getString("folder")));
document.setUpdatetime(rs.getTimestamp("updatetime"));
document.setPersonid(rs.getInt("personid"));
}
rs.close();
ps.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs!=null)rs.close();
if(ps!=null)ps.close();
oc_conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
return document;
}
}
|
package LLambdaTop.ChallengeLambda;
import java.util.function.Supplier;
public class Lambda3 {
public static void main(String[] args) {
//Supplier<String> iLoveJava = () -> "I love Java";
Supplier<String> iLoveJava = () -> {return "I love Java"; };
String supplierResult = iLoveJava.get(); //with get takes the Supplier values
System.out.println(supplierResult);
}
}
|
package ejerciciojunitparejas;
import com.sun.jmx.snmp.BerException;
public class Metodos extends BRException{
private float salarioBase;
private float totalHorasExtra;
private float retencion;
public float calculaSalarioBruto(String tipo, float ventasMes, float horasExtra) throws BRException {
if (tipo.isEmpty() | (ventasMes < 0) | (horasExtra < 0)) {
throw new BRException();
}
if (tipo.equals("empleado")) {
salarioBase = 1000;
if (ventasMes >= 1000) {
salarioBase = salarioBase + 100;
if (ventasMes == 1500) {
salarioBase = salarioBase + 200;
}
horasExtra = horasExtra * 20;
salarioBase = horasExtra + salarioBase;
}
}
if (tipo.equals("encargado")) {
salarioBase = 1500;
if (ventasMes >= 1000) {
salarioBase = salarioBase + 100;
if (ventasMes == 1500) {
salarioBase = salarioBase + 200;
}
horasExtra = horasExtra * 20;
salarioBase = horasExtra + salarioBase;
}
}
return salarioBase;
}
public float calculaSalarioNeto(float salarioBruto){
float retencion16 = (salarioBruto*16)/100;
if (salarioBruto>1000 && salarioBruto<1500) {
retencion = (salarioBruto*16)/100;
}
if (salarioBruto>1500) {
retencion = (salarioBruto*18)/100;
}
return salarioBruto*(1-retencion);
}
}
|
package com.qumla.service.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import com.qumla.domain.location.Country;
import com.qumla.domain.location.LocationData;
import com.qumla.service.impl.LocationDataDaoMapper;
public class LocationDataDaoTest extends AbstractTest {
@Before
public void before() {
super.before(LocationDataDaoMapper.class);
}
@Test
public void locationTest(){
LocationDataDaoMapper mapper=(LocationDataDaoMapper)getMapper(LocationDataDaoMapper.class);
LocationData location=mapper.findByName("HU","Budapest");
assertTrue(location.getName().equals("Budapest"));
}
@Test
public void insertLocationTest(){
LocationData l=new LocationData();
l.setCity(11L);
l.setCountry("HU");
l.setLat(new Float(47.7));
l.setLon(new Float(35.2));
LocationDataDaoMapper mapper=(LocationDataDaoMapper)getMapper(LocationDataDaoMapper.class);
mapper.insertLocation(l);
LocationData l2=mapper.findOne(l.getId());
assertTrue(l2.getCity().equals(11L));
assertEquals("HU", l2.getCountry());
assertEquals(new Float(47.7), l2.getLat());
assertEquals(new Float(35.2), l2.getLon());
}
@Test
public void findCountry(){
LocationDataDaoMapper mapper=(LocationDataDaoMapper)getMapper(LocationDataDaoMapper.class);
Country c=mapper.findCountry("HU");
assertTrue(c.getCountryName().equals("Hungary"));
}
}
|
import java.io.*;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Scanner;
public class KeyGen {
public static void main (String[] args) throws NoSuchAlgorithmException,
InvalidKeySpecException, IOException {
SecureRandom random = new SecureRandom();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024, random); //1024: key size in bits
// Create RSA KeyPair for X
KeyPair pairX = generator.generateKeyPair();
Key pubKeyX = pairX.getPublic();
Key privKeyX = pairX.getPrivate();
saveKeyFiles("X", pubKeyX, privKeyX);
// Create RSA KeyPair for Y
KeyPair pairY = generator.generateKeyPair();
Key pubKeyY = pairY.getPublic();
Key privKeyY = pairY.getPrivate();
saveKeyFiles("Y", pubKeyY, privKeyY);
// Symmetric key
Scanner stdIn = new Scanner(System.in);
System.out.print("Enter 16 character symmetric key: ");
String keyString = stdIn.nextLine();
while (keyString.length() != 16) {
System.out.println("That was not 16 characters long. Try again");
System.out.print("Enter 16 character symmetric key: ");
keyString = stdIn.nextLine();
}
FileWriter fileWriter = new FileWriter(new File("symmetric.key"));
fileWriter.write(keyString);
fileWriter.close();
}
private static void saveKeyFiles (String keyName, Key pubKey, Key
privKey) throws NoSuchAlgorithmException, InvalidKeySpecException,
IOException {
KeyFactory factory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pubKSpec = factory.getKeySpec(pubKey,
RSAPublicKeySpec.class);
RSAPrivateKeySpec privKSpec = factory.getKeySpec(privKey,
RSAPrivateKeySpec.class);
String fileNamePub = keyName + "Public.key";
String fileNamePriv = keyName + "Private.key";
try (ObjectOutputStream oout = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(fileNamePub)))) {
oout.writeObject(pubKSpec.getModulus());
oout.writeObject(pubKSpec.getPublicExponent());
oout.close();
} catch (Exception e) {
throw new IOException("Unexpected error", e);
}
try (ObjectOutputStream oout = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(fileNamePriv)))) {
oout.writeObject(privKSpec.getModulus());
oout.writeObject(privKSpec.getPrivateExponent());
oout.close();
} catch (Exception e) {
throw new IOException("Unexpected error", e);
}
}
}
|
package com.capgemini.repository;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.capgemini.entity.Donation;
@Repository("donationRepository")
public interface DonationRepository extends JpaRepository<Donation, Integer> {
@Transactional
@Query(value = "SELECT SUM(d.amount) FROM DONATION_TABLE d", nativeQuery = true)
public Double sumDonations();
}
|
package org.usfirst.frc.team178.robot.subsystems;
import org.usfirst.frc.team178.robot.RobotMap;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
*/
public class TapeMeasureScalar extends Subsystem {
public static Relay Rick;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public TapeMeasureScalar() {
Rick = new Relay(RobotMap.scalarMotor, Relay.Direction.kForward);
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand())
}
public void Up() {
Rick.set(Relay.Value.kOn);
}
public void Down() {
Rick.set(Relay.Value.kOff);
}
}
|
package Problem_17471;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N;
static int[] pop;
static boolean[] isSelected;
static boolean[][] isClosed;
static boolean[] isvisited;
static int min_value = Integer.MAX_VALUE;
static void dfs(int idx, boolean flag) {
isvisited[idx] = true;
for(int i = 0; i<N; i++) {
if(!isClosed[idx][i]) continue;
if(isvisited[i]) continue;
if(isSelected[i] != flag) continue;
dfs(i, flag);
}
}
static void getAnswer(int idx, int c) {
if (idx == N && c > 0) {
int a = 0, b = 0;
for (int i = 0; i < N; i++) {
if (isSelected[i])
a = i;
else
b = i;
}
for (int i = 0; i < N; i++)
isvisited[i] = false;
dfs(a, true);
int group_true = 0;
int true_value = 0;
for (int i = 0; i < N; i++)
if (isvisited[i]) {
group_true++;
true_value += pop[i];
}
for (int i = 0; i < N; i++)
isvisited[i] = false;
dfs(b, false);
int group_false = 0;
int false_value = 0;
for (int i = 0; i < N; i++)
if (isvisited[i]) {
group_false++;
false_value += pop[i];
}
if (c != group_true || (N - c) != group_false) return;
if(min_value > Math.abs(false_value - true_value)) min_value = Math.abs(false_value - true_value);
} else if (idx == N)
return;
else {
getAnswer(idx + 1, c);
isSelected[idx] = true;
getAnswer(idx + 1, c + 1);
isSelected[idx] = false;
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
pop = new int[N];
isClosed = new boolean[N][N];
isSelected = new boolean[N];
isvisited = new boolean[N];
String str = br.readLine();
for (int i = 0; i < N; i++)
pop[i] = Integer.parseInt(str.split(" ")[i]);
for (int i = 0; i < N; i++) {
str = br.readLine();
int cnt = Integer.parseInt(str.split(" ")[0]);
for (int j = 1; j <= cnt; j++) {
isClosed[i][Integer.parseInt(str.split(" ")[j]) - 1] = true;
}
}
getAnswer(0, 0);
if(min_value != Integer.MAX_VALUE) {
System.out.println(min_value);
return;
}
System.out.println("-1");
}
}
|
import java.util.Arrays;
// An immutable type representing a location on Earth.
public class Location implements Comparable<Location> {
private final String loc; // location name
private final double lat; // latitude
private final double lon; // longitude
// Construct a new location given its name, latitude, and longitude.
public Location(String loc, double lat, double lon) {
this.loc = loc;
this.lat = lat;
this.lon = lon;
}
// The great-circle distance between this location and that.
public double distanceTo(Location that) {
double x1 = that.lat;
x1 = Math.toRadians(x1);
double y1 = that.lon;
double x2 = lat;
x2 = Math.toRadians(x2);
double y2 = lon;
double c = Math.toRadians(y1-y2);
double e = Math.sin(x1)*Math.sin(x2)+Math.cos(x1)*Math.cos(x2)*Math.cos(c);
double s = Math.acos(e);
double d = 111* s;
d = Math.toDegrees(d);
return d;
}
// Is this location the same as that?
public boolean equals(Location that) {
return that.lat == lat && that.lon == lon;
}
// -1, 0, or 1 depending on whether the distance of this
// location to the origin (Parthenon, Athens, Greece @
// 37.971525, 23.726726) is less than, equal to, or greater
// than the distance of that location to the origin.
public int compareTo(Location that) {
Location l = new Location("", 37.971525, 23.72672);
if (distanceTo(l) < that.distanceTo(l)) return -1;
else if (distanceTo(l) < that.distanceTo(l)) return 0;
else return 1;
}
// A string representation of the location, in "loc (lat, lon)" format.
public String toString() {
return loc + " " + "(" + lat + ", " + lon + ")";
}
// Test client. [DO NOT EDIT]
public static void main(String[] args) {
int rank = Integer.parseInt(args[0]);
double lat = Double.parseDouble(args[1]);
double lon = Double.parseDouble(args[2]);
Location[] wonders = new Location[7];
wonders[0] = new Location("The Great Wall of China (China)",
40.6769, 117.2319);
wonders[1] = new Location("Petra (Jordan)", 30.3286, 35.4419);
wonders[2] = new Location("The Colosseum (Italy)", 41.8902, 12.4923);
wonders[3] = new Location("Chichen Itza (Mexico)", 20.6829, -88.5686);
wonders[4] = new Location("Machu Picchu (Peru)", -13.1633, -72.5456);
wonders[5] = new Location("Taj Mahal (India)", 27.1750, 78.0419);
wonders[6] = new Location("Christ the Redeemer (Brazil)",
22.9519, -43.2106);
Arrays.sort(wonders);
for (Location wonder : wonders) {
StdOut.println(wonder);
}
StdOut.println(wonders[rank].equals(new Location("", lat, lon)));
}
}
|
package ru.spbau.bocharov.FunctionalJava;
import org.junit.Test;
import java.util.Objects;
import static org.junit.Assert.*;
public class PredicateTest {
@Test
public void testConstants() {
assertTrue(Predicate.ALWAYS_TRUE.apply(new Object()));
assertFalse(Predicate.ALWAYS_FALSE.apply(new Object()));
assertFalse(Predicate.ALWAYS_TRUE.not().apply(true));
assertTrue(Predicate.ALWAYS_FALSE.not().apply(false));
}
@Test
public void testCompose() {
String log = "";
Function1<Boolean, String> writer = arg -> arg ? log.concat("true") : log.concat("false");
assertNotEquals("", Predicate.ALWAYS_TRUE.compose(writer).apply(new Object()));
assertEquals("false", Predicate.ALWAYS_FALSE.compose(writer).apply(new Object()));
}
@Test
public void testOr() {
assertTrue(IS_EVEN.or(IS_ODD).apply(4));
assertTrue(IS_ODD.or(IS_EVEN).apply(5));
assertFalse(IS_ODD.or(IS_ODD).apply(4));
assertTrue(IS_EVEN.or(IS_EVEN.not()).apply(4));
assertTrue(IS_EVEN.or(IS_EVEN.not()).apply(5));
assertTrue(IS_EVEN.or(Predicate.ALWAYS_TRUE).apply(4));
assertTrue(IS_ODD.or(Predicate.ALWAYS_FALSE).apply(5));
}
@Test
public void testLaziness() {
Predicate<Object> eq = arg -> arg.equals("");
assertTrue(Predicate.ALWAYS_TRUE.or(eq).apply(null));
assertFalse(Predicate.ALWAYS_FALSE.and(eq).apply(null));
}
@Test
public void testAnd() {
assertFalse(IS_ODD.and(IS_EVEN).apply(4));
assertFalse(IS_EVEN.and(IS_ODD).apply(5));
assertTrue(IS_EVEN.and(IS_EVEN).apply(4));
assertFalse(IS_ODD.and(IS_ODD.not()).apply(4));
assertTrue(IS_ODD.and(IS_EVEN.not()).apply(5));
assertTrue(IS_ODD.and(Predicate.ALWAYS_TRUE).apply(5));
assertFalse(IS_EVEN.and(Predicate.ALWAYS_FALSE).apply(4));
}
private static final Predicate<Integer> IS_EVEN = arg -> arg % 2 == 0;
private static final Predicate<Integer> IS_ODD = arg -> arg % 2 == 1;
}
|
package org.formation.graphql;
import org.formation.model.Account;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.graphql.boot.test.tester.AutoConfigureGraphQlTester;
import org.springframework.graphql.test.tester.GraphQlTester;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
@SpringBootTest
@AutoConfigureGraphQlTester
public class SubscriptionTest {
@Autowired
GraphQlTester graphQlTester;
@Test
void subscriptionWithEntityPath() {
Flux<Account> result = this.graphQlTester.query("subscription { accountSubscription {\n"
+ " id\n"
+ " value\n"
+ " } }")
.executeSubscription()
.toFlux("accountSubscription", Account.class);
StepVerifier.create(result)
.expectNextCount(3)
.verifyComplete();
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Executors;
public class server {
public static void main(String [] args) throws IOException{
System.out.println("Server has started...");
ServerSocket server = new ServerSocket(4999);
ExecutorService executor = Executors.newFixedThreadPool(4);
while(true){
Socket s = server.accept();
System.out.println("New client connected");
System.out.println(s);
executor.execute(new CurrencyConversion(s));
}
}
}
class CurrencyConversion implements Runnable{
private Socket socket;
private BigDecimal amount;
public CurrencyConversion(Socket s) throws IOException{
this.socket = s;
}
public void run(){
try {
InputStreamReader in = new InputStreamReader(this.socket.getInputStream());
BufferedReader bf = new BufferedReader(in);
this.amount = new BigDecimal(bf.readLine());
System.out.println("Input recieved");
calculate_results(this.socket,this.amount);
}catch (IOException e) {
e.printStackTrace();
}
}
static void calculate_results(Socket s, BigDecimal n) throws IOException{
PrintWriter pr = new PrintWriter(s.getOutputStream());
pr.println("USD: " + convert_to_usd(n));
pr.println("GBP: " + convert_to_gbp(n));
pr.println("YEN: " + convert_to_yen(n));
System.out.println("Sent Response");
pr.flush();
}
static BigDecimal convert_to_usd(BigDecimal n){
BigDecimal rate = new BigDecimal("1.09");
return n.multiply(rate);
}
static BigDecimal convert_to_gbp(BigDecimal n){
BigDecimal rate = new BigDecimal("0.88");
return n.multiply(rate);
}
static BigDecimal convert_to_yen(BigDecimal n){
BigDecimal rate = new BigDecimal("116.78");
return n.multiply(rate);
}
}
|
package view;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import controller.DBConnection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;
import java.awt.Dimension;
import java.awt.FlowLayout;
public class MyArea extends JPanel {
/**
*
*/
private static final long serialVersionUID = 2907038343333847170L;
private static Connection conn;
private static Statement statement;
private static ResultSet rs;
private int soBan = 0;
/**
* Create the panel.
*/
public MyArea(int MaVT) {
setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 1025, 767);
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 12, 12));
add(panel);
setVisible(true);
// Đếm số bàn của từng khu
try {
// String sql = "SELECT COUNT(*) FROM BAN WHERE TrangThai = 1 AND
// MaVT =" + MaVT;
String sql = "SELECT COUNT(*) FROM BAN WHERE MaVT =" + MaVT;
conn = DBConnection.getConnection();
statement = conn.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
soBan = rs.getInt(1);
}
rs.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (soBan > 0) {
// Lấy thông tin các bàn trong khu
int[] tableID = new int[soBan];
String[] tableName = new String[soBan];
boolean[] status = new boolean[soBan];
try {
// String sql = "SELECT * FROM BAN WHERE TrangThai = 1 AND MaVT
// = " + MaVT;
String sql = "SELECT * FROM BAN WHERE MaVT = " + MaVT;
conn = DBConnection.getConnection();
statement = conn.createStatement();
rs = statement.executeQuery(sql);
int i = 0;
while (rs.next()) {
tableID[i] = rs.getInt(1);
tableName[i] = rs.getString(2);
status[i++] = rs.getBoolean(4);
}
rs.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Tạo danh sách các bàn
JPanel[] table = (JPanel[]) createMyTable(soBan);
int i = 0;
while (i < soBan) {
table[i] = new MyTable();
table[i].setBorder(null);
((MyTable) table[i]).setId(tableID[i]);
((MyTable) table[i]).setTableName("BÀN " + tableName[i]);
// Set cứng kích thước của bàn
table[i].setPreferredSize(new Dimension(150, 150));
table[i].setBorder(new EtchedBorder());
// Load thông tin bàn (trống, có khách, đang hỏng
try {
String sql = "SELECT NgayGioTra From CHONBAN WHERE MaBan =" + tableID[i];
conn = DBConnection.getConnection();
statement = conn.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
if (rs.getDate(1) == null) {
((MyTable) table[i]).setImage("/resources/bancokhach.png");
break;
}
}
rs.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Set trạng thái bàn
((MyTable) table[i]).setStatus(status[i]);
if (((MyTable) table[i]).isStatus() == false) {
((MyTable) table[i]).setImage("/resources/banhong.png");
// Disable bàn hỏng
((MyTable) table[i]).setEnabledTable(table[i], false);
}
panel.add(table[i]);
i++;
}
} else {
Message.messageBox("Khu " + MaVT + " trống!!!!", "THÔNG BÁO");
}
setVisible(true);
}
// Tạo ra n bàn với kích thước ngẫu nhiên
public static MyTable[] createMyTable(int n) {
Random r = new Random(0);
MyTable[] c = new MyTable[n];
int m = n;
while (m > 0) {
int i = r.nextInt(n);
if (c[i] == null) {
c[i] = new MyTable();
int w = 5 * (2 + r.nextInt(20));
int h = 5 * (2 + r.nextInt(20));
c[i].setPreferredSize(new Dimension(w, h));
c[i].setBorder(new EtchedBorder());
m--;
}
}
return c;
}
}
|
//package com.bnrc.multipallist;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//
//import android.app.Activity;
//import android.content.Intent;
//import android.os.Bundle;
//import android.os.UserManager;
//import android.view.Gravity;
//import android.view.View;
//import android.view.View.OnClickListener;
//import android.view.ViewGroup;
//import android.widget.AdapterView;
//import android.widget.AdapterView.OnItemClickListener;
//import android.widget.Button;
//import android.widget.ListView;
//import android.widget.TextView;
//
//import com.baidu.platform.comapi.map.G;
//import com.bnrc.busapp.R;
//import com.bnrc.multipallist.DemoAdapter.ViewHolder;
//import com.bnrc.ui.rtBus.Child;
//import com.bnrc.ui.rtBus.Group;
//import com.bnrc.util.UserDataDBHelper;
//import com.bnrc.util.collectwifi.BaseActivity;
//
//public class MultiActivity extends BaseActivity implements OnClickListener, OnItemClickListener {
//
// private Button mCancleBtn = null;
//
// private ViewGroup mSelectAll = null;
//
// private Button mSureBtn = null;
//
// private ListView mListView = null;
//
// private TextView mSelectAllText;
// private DemoAdapter adpAdapter = null;
// private List<Group> mGroups;
// private List<Child> mChildren;
// private UserDataDBHelper mUserDB = null;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setAbContentView(R.layout.activity_multi_list);
// this.setTitleTextMargin(20, 0, 0, 0);
// this.setLogo(R.drawable.button_selector_back);
// this.setTitleLayoutBackground(R.drawable.top_bg);
// this.setTitleLayoutGravity(Gravity.CENTER, Gravity.CENTER);
// this.setTitleText("选择提醒线路");
// Intent intent = getIntent();
// Bundle bundle = intent.getExtras();
// mGroups = (List<Group>) bundle.getSerializable("DATA");
// mChildren = new ArrayList<Child>();
// initView();
// initData();
// mUserDB = UserDataDBHelper.getInstance(MultiActivity.this);
// }
//
// private void initView() {
//
// mCancleBtn = (Button) findViewById(R.id.btnCancle);
// mCancleBtn.setOnClickListener(this);
//
// mSureBtn = (Button) findViewById(R.id.btnSure);
// mSureBtn.setOnClickListener(this);
//
// mSelectAll = (ViewGroup) findViewById(R.id.rLayout_SelectAll);
// mSelectAll.setOnClickListener(this);
//
// mListView = (ListView) findViewById(R.id.lvListView);
// mListView.setOnItemClickListener(this);
// mSelectAllText = (TextView) findViewById(R.id.tv_SelectAll);
// }
//
// /**
// * ��ʼ����ͼ
// */
// private void initData() {
// generateChildren();
// adpAdapter = new DemoAdapter(this, mChildren);
// mListView.setAdapter(adpAdapter);
//
// }
//
// private void generateChildren() {
// if (mGroups != null) {
// for (Group group : mGroups) {
// mChildren.addAll(group.getChildren());
// }
// }
// }
//
// @Override
// public void onClick(View v) {
//
// switch (v.getId()) {
// case R.id.btnCancle:
// finish();
// break;
// case R.id.btnSure:
// //
// // if (isAlert) {
// // mUserDB.deleteAlertStation(stationName);
// // appBtn.setBackgroundResource(R.drawable.icon_notalert);
// // isAlert = false;
// // } else {
// // ArrayList<String> station = new ArrayList<String>();
// // station.add(stationName);
// // station.add(1 + "");
// // station.add(mLatitude);
// // station.add(mLongitude);
// // station.add(AZ);
// // mUserDB.addAlertRecord(station);
// // appBtn.setBackgroundResource(R.drawable.icon_isalert);
// // isAlert = true;
// //
// // }
//
// Map<Integer, Boolean> map = adpAdapter.getCheckMap();
// int count = adpAdapter.getCount();
// ArrayList<String> station = new ArrayList<String>();
// for (int i = 0; i < count; i++) {
// int position = i - (count - adpAdapter.getCount());
// Child child = (Child) adpAdapter.getItem(position);
// if (map.get(i) != null && map.get(i)) {
// String stationName = child.getStationName();
// double latitude = child.getLatitude();
// double longitude = child.getLongitude();
// // String AZ = child.getAZ();
// // String SN = child.getBuslineSN();
// station.clear();
// station.add(stationName);
// // station.add(SN);
// station.add(1 + "");
// station.add(latitude + "");
// station.add(longitude + "");
// // station.add(AZ);
// mUserDB.addAlertRecord(station);
// }
// // else
// // mUserDB.deleteAlertStation(child.getBuslineSN());
//
// // if (bean.isCanRemove()) {
// // adpAdapter.getCheckMap().remove(i);
// // adpAdapter.remove(position);
// // } else {
// // map.put(position, false);
// // }
//
// }
// finish();
// break;
// case R.id.rLayout_SelectAll:
// if (mSelectAllText.getText().toString().trim().equals("全选")) {
// adpAdapter.configCheckMap(true);
//
// adpAdapter.notifyDataSetChanged();
//
// mSelectAllText.setText("全不选");
// } else {
// adpAdapter.configCheckMap(false);
//
// adpAdapter.notifyDataSetChanged();
//
// mSelectAllText.setText("全选");
// }
// break;
// default:
// break;
// }
//
// // if (v == mSureBtn) {
// // Map<Integer, Boolean> map = adpAdapter.getCheckMap();
// // int count = adpAdapter.getCount();
// // for (int i = 0; i < count; i++) {
// // int position = i - (count - adpAdapter.getCount());
// // if (map.get(i) != null && map.get(i)) {
// //
// // Child bean = (Child) adpAdapter.getItem(position);
// //
// // if (bean.isCanRemove()) {
// // adpAdapter.getCheckMap().remove(i);
// // adpAdapter.remove(position);
// // } else {
// // map.put(position, false);
// // }
// //
// // }
// // }
// // adpAdapter.notifyDataSetChanged();
// // }
//
// }
//
// @Override
// public void onItemClick(AdapterView<?> listView, View itemLayout, int position, long id) {
//
// if (itemLayout.getTag() instanceof ViewHolder) {
// ViewHolder holder = (ViewHolder) itemLayout.getTag();
// holder.cbCheck.toggle();
//
// }
//
// }
//}
|
package edu.mit.cci.simulation.client.model.transitional;
import edu.mit.cci.simulation.client.comm.RepositoryManager;
/**
* User: jintrone
* Date: 3/17/11
* Time: 4:34 PM
*/
public abstract class AdaptedObject<T> {
T model;
private RepositoryManager manager;
public AdaptedObject(T obj, RepositoryManager manager) {
this.model = obj;
this.manager = manager;
}
public T model() {
return model;
}
public RepositoryManager manager() {
return manager;
}
}
|
/**
* Created by Kuba on 09.11.2017.
*/
public class Map {
private int size = 8;
private String[][] board;
Map() {
this.board = new String[this.size][this.size];
for(int i = 0; i < this.size; ++i) {
for(int j = 0; j < this.size; ++j) {
if((j + i) % 2 == 1 && i < 3) {
this.board[i][j] = "white";
} else if((j + i) % 2 == 1 && i > 4) {
this.board[i][j] = "black";
} else {
this.board[i][j] = ".";
}
}
}
}
public void printBoard() {
for(int i = 0; i < this.size; ++i) {
for(int j = 0; j < this.size; ++j) {
System.out.print(this.board[i][j] + " ");
}
System.out.println();
}
}
public String getSymbolFromMap(int x, int y) {
return this.board[x][y];
}
public void setPoint(int x, int y, String symbol) {
this.board[x][y] = symbol;
}
}
|
package com.example.chordnote.data.prefs;
import android.content.Context;
import android.content.SharedPreferences;
public class PreferencesHelperImpl implements PreferencesHelper {
private SharedPreferences preferences;
public PreferencesHelperImpl(Context context, String name) {
preferences = context.getSharedPreferences(name, Context.MODE_PRIVATE);
}
@Override
public boolean getCurrentLoginState() {
return preferences.getBoolean("loginState",false);
}
@Override
public void setCurrentLoginState(boolean state) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("loginState",state);
editor.apply();
}
@Override
public String getCurrentUserEmail() {
return preferences.getString("currentEmail", " ");
}
@Override
public void setCurrentUserEmail(String email) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString("currentEmail", email);
editor.apply();
}
@Override
public String getCurrentUserPass() {
return preferences.getString("currentPass", " ");
}
@Override
public void setCurrentUserPass(String password) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString("currentPass", password);
editor.apply();
}
@Override
public void setEmailToIdMap(String email, long id) {
if (getIdUsingEmail(email) != 0) {
SharedPreferences.Editor editor = preferences.edit();
editor.putLong(email, id);
editor.apply();
}
}
@Override
public Long getIdUsingEmail(String email) {
return (Long)preferences.getLong(email, 0);
}
@Override
public void deleteEmailToIdMap(String email) {
SharedPreferences.Editor editor = preferences.edit();
editor.remove(email);
editor.apply();
}
@Override
public void resetCurrentLoginInfo() {
setCurrentLoginState(false);
setCurrentUserEmail(" ");
setCurrentUserPass(" ");
setCurrentUserNickName(" ");
}
@Override
public String getCurrentUserNickName() {
return preferences.getString("nickname", " ");
}
@Override
public void setCurrentUserNickName(String name) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString("nickname", name);
editor.apply();
}
}
|
package view;
import app.Principal;
import dao.ConsultaProduto;
import entidades.ItensPedido;
import entidades.Produto;
import entidades.ProntaEntrega;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class FrmInserirProduto extends javax.swing.JDialog {
public ItensPedido entidade;
public Produto produto;
public void entidadeTela() {
tfProduto.setText(entidade.getProduto().getNome());
tfValor.setText(entidade.getValor().toString());
tfQuantidade.setText(entidade.getQuantidade().toString());
if (entidade.isEntregue()) {
cbEntregar.setSelectedItem("Sim");
} else {
cbEntregar.setSelectedItem("Não");
}
}
public void telaEntidade() {
entidade.setProduto(produto);
entidade.setValor(produto.getValor());
entidade.setQuantidade(Long.parseLong(tfQuantidade.getText()));
if (cbEntregar.getSelectedItem() == "Sim") {
entidade.setEntregue(true);
} else {
entidade.setEntregue(false);
}
}
public ItensPedido getEntidade() {
return entidade;
}
public void setEntidade(ItensPedido entidade) {
this.entidade = entidade;
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public boolean validaProntaEntrega() {
boolean retorno = true;
List quantidadeEstoque = new ArrayList();
if (cbEntregar.getSelectedItem().equals("Sim")) {
quantidadeEstoque = Principal.emf.createEntityManager().createNativeQuery(
"select quantidade from "
+ ProntaEntrega.class.getSimpleName() + " where produto_id = "
+ produto.getId()).getResultList();
if (quantidadeEstoque.isEmpty()) {
retorno = false;
} else if (Long.parseLong(quantidadeEstoque.get(0).toString()) < Long.parseLong(tfQuantidade.getText().toString())) {
retorno = false;
}
} else if (Long.parseLong(tfQuantidade.getText()) < 1) {
retorno = false;
}
if (!retorno)
JOptionPane.showMessageDialog(null, "Produto indisponível para entrega imediata!");
return retorno;
}
public FrmInserirProduto(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
tfProduto = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
tfValor = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
cbEntregar = new javax.swing.JComboBox();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
tfQuantidade = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Produto:");
tfProduto.setEnabled(false);
jButton1.setText("Buscar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel2.setText("Valor:");
tfValor.setEnabled(false);
jLabel3.setText("Quantidade:");
jLabel4.setText("Entregar produto agora:");
cbEntregar.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Não", "Sim" }));
jButton2.setText("Ok");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Cancelar");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(100, 100, 100)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfProduto, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(tfValor, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(tfQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(cbEntregar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(tfProduto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(tfValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(tfQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(cbEntregar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton3))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
ConsultaProduto con = new ConsultaProduto();
con.setVisible(true);
produto = (Produto) con.selecionar();
tfProduto.setText(produto.getNome());
tfValor.setText(produto.getValor().toString());
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
if (validaProntaEntrega()) {
telaEntidade();
setVisible(false);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
entidade = null;
produto = null;
setVisible(false);
}//GEN-LAST:event_jButton3ActionPerformed
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FrmInserirProduto dialog = new FrmInserirProduto(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox cbEntregar;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField tfProduto;
private javax.swing.JTextField tfQuantidade;
private javax.swing.JTextField tfValor;
// End of variables declaration//GEN-END:variables
}
|
package com.syscxp.biz.config;
/**
*/
@GlobalPropertyDefinition
public class CoreGlobalProperty {
@GlobalProperty(name = "openTSDBServerUrl", defaultValue = "http://192.168.211.6:4242")
public static String OPENTSDB_SERVER_URL;
}
|
package Problem_10451;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N;
static int[] arr = new int[1001];
static boolean[] isvisited = new boolean[1001];
static int answer;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
StringTokenizer st;
StringBuilder sb = new StringBuilder();
for(int t = 1; t<=T; t++) {
answer = 0;
N = Integer.parseInt(br.readLine());
for(int i = 1; i<=N; i++) {
isvisited[i] = false;
arr[i] = 0;
}
st = new StringTokenizer(br.readLine());
for(int i = 1 ;i<=N; i++) arr[i] = Integer.parseInt(st.nextToken());
for(int i = 1; i<=N; i++) {
if(!isvisited[i]) {
answer++;
dfs(i);
}
}
sb.append(answer).append("\n");
}
System.out.println(sb.toString());
}
static void dfs(int i) {
isvisited[i] = true;
if(!isvisited[arr[i]]) dfs(arr[i]);
}
}
|
package sg.edu.iss.ad.model;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@NotBlank
private String username;
@NotBlank
private String password;
@Email
private String email;
private RoleType role;
// @OneToMany(fetch=FetchType.LAZY,mappedBy="User")
// private List<UserStockComment> UserStockComment;
//
// //@OneToOne(mappedBy="User")
// @OneToMany(fetch=FetchType.LAZY,mappedBy="User")
// private List<UserStockWatchList> UserStockWatchList;
//
// @OneToMany(fetch=FetchType.LAZY,mappedBy="User")
// private List<CandleHistory> CandleHistory;
public User() {}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public RoleType getRole() {
return role;
}
public void setRole(RoleType role) {
this.role = role;
}
// public List<UserStockComment> getUserStockComment() {
// return UserStockComment;
// }
//
// public void setUserStockComment(List<UserStockComment> userStockComment) {
// UserStockComment = userStockComment;
// }
//
// public List<UserStockWatchList> getUserStockWatchList() {
// return UserStockWatchList;
// }
//
// public void setUserStockWatchList(List<UserStockWatchList> userStockWatchList) {
// UserStockWatchList = userStockWatchList;
// }
//
// public List<CandleHistory> getCandleHistory() {
// return CandleHistory;
// }
//
// public void setCandleHistory(List<CandleHistory> candleHistory) {
// CandleHistory = candleHistory;
// };
}
|
package Repository;
import Domain.Rental;
/**
* Created by Emma on 8/11/2018.
*/
public interface RentalRepository extends CrudRepository<Rental, Long>
{
Iterable<Rental> findAllById(long id);//finds all Rentals
}
|
package com.example.karen.lop_android;
import android.app.DialogFragment;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hebi5 on 10/17/2015.
*/
public class MyDialog extends DialogFragment {
View rootView;
TextView textFolder;
Button buttonUp;
Button createFolder;
EditText folderName;
File root;
File curFolder;
ListView dialog_ListView;
private List<String> fileList = new ArrayList<>();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.dialog_layout, container, false);
dialog_ListView = (ListView)rootView.findViewById(R.id.dialogList);
textFolder = (TextView)rootView.findViewById(R.id.folder);
buttonUp = (Button)rootView.findViewById(R.id.paluyo);
buttonUp.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
ListDir(curFolder.getParentFile());
}
});
folderName =(EditText)rootView.findViewById(R.id.folder_name);
createFolder=(Button)rootView.findViewById(R.id.create_folder);
createFolder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File rootDirectory = new File(Environment.getExternalStorageDirectory(), folderName.getText().toString());
if(!rootDirectory.exists()){
Toast.makeText(getActivity(),(rootDirectory.mkdir())?"successful":"failed",Toast.LENGTH_LONG).show();
}
}
});
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File selected = new File(fileList.get(position));
if(selected.isDirectory()) {
ListDir(selected);
} else {
Toast.makeText(getActivity(),selected.toString() + " mao ni siya",
Toast.LENGTH_LONG).show();
getDialog().dismiss();
}
}
});
root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
curFolder = root;
return rootView;
}
void ListDir(File f) {
if(f.equals(root)) {
buttonUp.setEnabled(false);
}
else {
buttonUp.setEnabled(true);
}
curFolder = f;
textFolder.setText(f.getPath());
File[] files = f.listFiles();
fileList.clear();
for(File file: files) {
fileList.add((file.getPath()));
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(getActivity(), R.layout.folder_list,R.id.folder_dir_txt,fileList);
dialog_ListView.setAdapter(directoryList);
}
}
|
package exemplos.aula10.lsp.incorreto;
public interface Car {
void turnOnEngine();
void accelerate();
}
|
package com.javatunes.data;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.springframework.beans.factory.annotation.Qualifier;
import com.javatunes.domain.Cart;
import com.javatunes.persist.XMLDBLocation;
@Qualifier("cart")
public class InMemoryCartDAO implements CartDAO {
// catalog of MusicItem objects
private List<Cart> cart;
private final Comparator<Cart> cartComparator = new Comparator<Cart>() {
@Override
public int compare(final Cart o1, final Cart o2) {
return o1.getUserName().compareTo(o2.getUserName());
}
};
// Constructor - JavaTunesSearch must be created with a catalog passed in
public InMemoryCartDAO(final List<Cart> catalogIn) {
XMLDecoder decoder;
try {
final File f = new File(XMLDBLocation.root + "\\cart.xml");
decoder = new XMLDecoder(new FileInputStream(f));
final Object o = decoder.readObject();
if (o instanceof List) {
this.cart = (List<Cart>) o;
} else {
this.cart = catalogIn;
}
decoder.close();
} catch (final FileNotFoundException e) {
this.cart = catalogIn;
}
Collections.sort(this.cart, this.cartComparator);
}
@Override
public Cart create(final Cart newItem) {
this.cart.add(newItem);
Collections.sort(this.cart, this.cartComparator);
persist();
return this.cart.get(this.cart.size() - 1);
}
@Override
public List<Cart> getAll() {
return Collections.unmodifiableList(this.cart);
}
@Override
public Cart getByID(final String id) {
if (id == null) {
return null;
}
final int index = Collections.binarySearch(this.cart, new Cart(id), this.cartComparator);
return (index <= -1) ? null : this.cart.get(index);
}
public void persist() {
XMLEncoder encoder;
try {
final File f = new File(XMLDBLocation.root + "\\cart.xml");
encoder = new XMLEncoder(new FileOutputStream(f));
encoder.writeObject(this.cart);
encoder.flush();
encoder.close();
} catch (final FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void remove(final String id) {
Cart cartToRemove = null;
for (final Cart c : this.cart) {
if (c.getUserName().equals(id)) {
cartToRemove = c;
break;
}
}
final int index = Collections.binarySearch(this.cart, new Cart(id), this.cartComparator);
if (cartToRemove == null) {
System.out.println("Couldn't find cart");
} else {
this.cart.remove(cartToRemove);
}
persist();
}
@Override
public void removeItem(final String user, final int index) {
final Cart c = getByID(user);
c.remove(index);
}
}
|
package com.github.tobby48.java.scene1;
/**
* <pre>
* com.github.tobby48.java.scene1
* OperatorCasting.java
*
* 설명 : 캐스팅연산자 테스트
* </pre>
*
* @since : 2017. 6. 28.
* @author : tobby48
* @version : v1.0
*/
public class OperatorCasting {
public static void main(String args[]) {
double d1 = 2 + 3.5; // 암시적 형변환
double d2 = (double)2 + 3.5; // 명시적 형변환
System.out.println("d1 : " + d1);
System.out.println("d2 : " + d2);
int d3 = (int) (2 + 3.14); // 큰 타입에서 작은타입으로 변환시 값 유실
System.out.println("d3 : " + d3);
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.testfixture.http.server.reactive.bootstrap.AbstractHttpHandlerIntegrationTests;
import org.springframework.web.testfixture.http.server.reactive.bootstrap.HttpServer;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for server response flushing behavior.
*
* @author Sebastien Deleuze
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 5.0
*/
class FlushingIntegrationTests extends AbstractHttpHandlerIntegrationTests {
private WebClient webClient;
@Override
protected void startServer(HttpServer httpServer) throws Exception {
super.startServer(httpServer);
this.webClient = WebClient.create("http://localhost:" + this.port);
}
@ParameterizedHttpServerTest
void writeAndFlushWith(HttpServer httpServer) throws Exception {
startServer(httpServer);
Mono<String> result = this.webClient.get()
.uri("/write-and-flush")
.retrieve()
.bodyToFlux(String.class)
.takeUntil(s -> s.endsWith("data1"))
.reduce((s1, s2) -> s1 + s2);
StepVerifier.create(result)
.expectNext("data0data1")
.expectComplete()
.verify(Duration.ofSeconds(10L));
}
@ParameterizedHttpServerTest // SPR-14991
void writeAndAutoFlushOnComplete(HttpServer httpServer) throws Exception {
startServer(httpServer);
Mono<String> result = this.webClient.get()
.uri("/write-and-complete")
.retrieve()
.bodyToMono(String.class);
try {
StepVerifier.create(result)
.consumeNextWith(value -> assertThat(value.length()).isEqualTo((64 * 1024)))
.expectComplete()
.verify(Duration.ofSeconds(10L));
}
catch (AssertionError err) {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("windows") && err.getMessage() != null &&
err.getMessage().startsWith("VerifySubscriber timed out")) {
// TODO: Reactor usually times out on Windows ...
err.printStackTrace();
return;
}
throw err;
}
}
@ParameterizedHttpServerTest // SPR-14992
void writeAndAutoFlushBeforeComplete(HttpServer httpServer) throws Exception {
startServer(httpServer);
Mono<String> result = this.webClient.get()
.uri("/write-and-never-complete")
.retrieve()
.bodyToFlux(String.class)
.next();
StepVerifier.create(result)
.expectNextMatches(s -> s.startsWith("0123456789"))
.expectComplete()
.verify(Duration.ofSeconds(10L));
}
@Override
protected HttpHandler createHttpHandler() {
return new FlushingHandler();
}
private static class FlushingHandler implements HttpHandler {
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
String path = request.getURI().getPath();
return switch (path) {
case "/write-and-flush" -> response.writeAndFlushWith(
testInterval(Duration.ofMillis(50), 2)
.map(longValue -> wrap("data" + longValue + "\n", response))
.map(Flux::just)
.mergeWith(Flux.never()));
case "/write-and-complete" -> response.writeWith(
chunks1K().take(64).map(s -> wrap(s, response)));
case "/write-and-never-complete" ->
// Reactor requires at least 50 to flush, Tomcat/Undertow 8, Jetty 1
response.writeWith(
chunks1K().take(64).map(s -> wrap(s, response)).mergeWith(Flux.never()));
default -> response.writeWith(Flux.empty());
};
}
private Flux<String> chunks1K() {
return Flux.generate(sink -> {
StringBuilder sb = new StringBuilder();
do {
for (char c : "0123456789".toCharArray()) {
sb.append(c);
if (sb.length() + 1 == 1024) {
sink.next(sb.append('\n').toString());
return;
}
}
} while (true);
});
}
private DataBuffer wrap(String value, ServerHttpResponse response) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
return response.bufferFactory().wrap(bytes);
}
}
}
|
package objects;
import java.awt.Color;
import java.awt.color.*;
import java.util.Random;
public class Token {
int _number;
boolean _collected;
boolean _visible;
boolean _facedown;
int[] _location; // Tile.getLocation()
public Token(int[] location, Integer integer) {
this._collected = false;
this._location = location;
}
public void flipToken() { // flip it to opposite boolean value
if (this._facedown == true) {
this._facedown = false;
} else {
this._facedown = true;
}
}
public void setNumber() {
// set the number label on the token -Kang
// set as random number ( 1 - 20, 25)
// Random r = new Random(20);
// int a = 25;
// // and array of numbers kang
// Random a = new Random();
// _number = aa[a.nextInt(aa.length)];//picks a random number from the
// array and set it as the token number.
// Jerry
}
public void setColor() {
// set the color of the token
// _visible = Color.WHITE;
// _collected = Color.GRAY;
// -Kevin
}
public int setLocation(int l) {
int location = l;
// get a location from Tile object.
// location is each tile except for edges and initial player
// locations-Keng
return location;
}
public void setNumber(Integer number) {
this._number = number;
}
public Integer getNumber() {
return this._number;
}
}
|
package com.himanshu.springboot2.foundation.context;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
//This annotation added to ensure encrypted properties can be decrypted.
@EnableEncryptableProperties
public class PropertiesPostProcessor implements BeanFactoryPostProcessor, PriorityOrdered {
private static Logger logger = LoggerFactory.getLogger(PropertiesPostProcessor.class);
private ResourceLoader resourceLoader;
private final String applicationName;
public PropertiesPostProcessor(String applicationName) {
this.resourceLoader = new DefaultResourceLoader();
this.applicationName = applicationName;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
String envProperty = System.getProperty("env");
if (envProperty == null || "".equalsIgnoreCase(envProperty.trim())) {
envProperty = "local";
logger.warn("[DEFAULT] Loading file paths for env:[{}]", envProperty);
}
logger.info("Loading file paths for env:[{}]", envProperty);
StandardEnvironment env = (StandardEnvironment) configurableListableBeanFactory.getBean("environment");
MutablePropertySources propertySources = env.getPropertySources();
for (String filePath : filePaths(envProperty)) {
Resource res = resourceLoader.getResource(filePath);
logger.info("res {}", res);
if (res.exists() && res != null) {
try {
Properties props = PropertiesLoaderUtils.loadProperties(res);
PropertiesPropertySource source = new PropertiesPropertySource(res.getFilename(), props);
propertySources.addFirst(source);
postProcessProperties(source);
} catch (IOException e) {
logger.error("Error loading file path : {}", res.getDescription(), e);
}
}
}
}
/**
* File paths.
*
* @param envProperty
* the env property
* @return the list
*/
private List<String> filePaths(String envProperty) {
List<String> filePaths = new ArrayList<String>();
filePaths.add("config/global.default.properties");
filePaths.add(String.format("config/%s.%s.properties", applicationName, envProperty));
filePaths.add("config/personal.properties");
return filePaths;
}
/**
* Post process properties.
*
* @param source
* the source
*/
private void postProcessProperties(PropertiesPropertySource source) {
for (String propertyName : source.getPropertyNames())
logger.debug("Loaded Property: {} with value: {}", propertyName, source.getProperty(propertyName));
}
/**
* Setting priority of this Spring Bean processor
* @return
*/
@Override
public int getOrder() {
return PriorityOrdered.HIGHEST_PRECEDENCE;
}
}
|
package com.pisen.ott.launcher.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.izy.widget.FocusScroller;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.DecelerateInterpolator;
import android.widget.BaseAdapter;
import android.widget.GridView;
import com.pisen.ott.common.view.focus.DefaultKeyFocus;
import com.pisen.ott.launcher.R;
/**
* 详情页面自定义GridView
*
* @author Liuhc
* @version 1.0 2015年2月3日 上午10:50:05
*/
public class GridScaleView extends GridView implements IDetailContent {
private float mScale = 1.1f;
private View lastSelectedView;
private FocusScroller mScroller;
private Rect mCurrRect;
private Drawable mDrawable;
private int FocusBorder;
public DefaultKeyFocus mKeyFocus;
private int lastSelectedItemPos = -1;
private IMasterTitle menuLayout;
private boolean itemLock = false;
private View upFocusView;
public GridScaleView(Context context, AttributeSet attrs) {
super(context, attrs);
setClipChildren(false);
setClipToPadding(false);
setVerticalFadingEdgeEnabled(false);
setChildrenDrawingOrderEnabled(true);
mScroller = new FocusScroller(context, new DecelerateInterpolator());
mCurrRect = new Rect();
mDrawable = getResources().getDrawable(R.drawable.home_focus);
FocusBorder = getResources().getDimensionPixelSize(R.dimen.banner_focus_border);
}
@Override
public void setMasterTitle(IMasterTitle menuLayout) {
menuLayout.setDetailContent(this);
this.menuLayout = menuLayout;
}
@Override
public boolean hasData() {
return getCount() > 0;
}
@Override
public void requestChildFocus() {
if (hasData()) {
setFocusable(true);
requestFocus();
setSelection(lastSelectedItemPos);
((BaseAdapter) getAdapter()).notifyDataSetChanged();
View selectedView = getSelectedView();
if (selectedView != null) {
Rect outRect = getDrawRect(selectedView);
mCurrRect.set(outRect);
}
}
}
public void setUpFocusView(View upFocusView) {
this.upFocusView = upFocusView;
}
/**
* 设置选中项获得光标
* @param pos
*/
public void setSelectionFocused(View v){
if (v != null) {
Rect outRect = getDrawRect(v);
if (mCurrRect.isEmpty()) {
v.getHitRect(mCurrRect);
}
if (!mCurrRect.equals(outRect)) {
mScroller.startScroll(mCurrRect, outRect);
}
}
// if (pos < (getCount()-1)) {
// if (lastSelectedItemPos != pos) {
// View v = getChildAt(pos);
// if (v != null) {
// Rect outRect = getDrawRect(v);
// if (mCurrRect.isEmpty()) {
// v.getHitRect(mCurrRect);
// }
// if (!mCurrRect.equals(outRect)) {
// mScroller.startScroll(mCurrRect, outRect);
// }
// }
// }
// }
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (getChildCount() > 0) {
View selectedView = getSelectedView();
if (selectedView != null) {
if (isFocused()) {
itemZoomIn(selectedView);
lastSelectedView = selectedView;
}
Rect outRect = getDrawRect(selectedView);
if (mCurrRect.isEmpty()) {
mCurrRect.set(outRect);
}
}
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (hasFocus()) {
if (mScroller.computeScrollOffset()) {
Rect currRect = mScroller.getCurrRect();
mCurrRect.set(currRect);
invalidate();
}
mDrawable.setBounds(mCurrRect.left - FocusBorder, mCurrRect.top - FocusBorder, mCurrRect.right + FocusBorder, mCurrRect.bottom + FocusBorder);
mDrawable.draw(canvas);
}
}
@Override
public void setSelection(int position) {
lastSelectedItemPos = position;
super.setSelection(position);
}
public void lockItem() {
itemLock = true;
}
public void unlockItem() {
itemLock = false;
}
public boolean isLockItem() {
return itemLock;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (itemLock) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
return super.dispatchKeyEvent(event);
default:
return true;
}
}
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) {
int numCol = getNumColumns();
int selectedItemPos = getSelectedItemPosition() + 1;
int rowNum = selectedItemPos / numCol + (selectedItemPos % numCol > 0 ? 1 : 0); // 当前所在行数
if (rowNum <= 1) {
if(upFocusView!=null){
lastSelectedItemPos = getSelectedItemPosition();
upFocusView.requestFocus();
View selectedView = getSelectedView();
if (selectedView != null) {
itemZoomOut(selectedView);
}
}
return true;
}
}
if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
int itemCount = getCount();
int numCol = getNumColumns();
int selectedItemPos = getSelectedItemPosition() + 1;
int rowNum = selectedItemPos / numCol + (selectedItemPos % numCol > 0 ? 1 : 0); // 当前所在行数
int rowCount = itemCount / numCol + (itemCount % numCol > 0 ? 1 : 0); // 总行数
if (rowNum >= rowCount) {
return true;
}
}
if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
int numCol = getNumColumns();
int selectedItemPos = getSelectedItemPosition() + 1;
// 判断当前是否是左边第一列
if (selectedItemPos % numCol == 1) {
lastSelectedItemPos = getSelectedItemPosition();
if (menuLayout != null) {
menuLayout.requestChildFocus();
}
setFocusable(false);
View selectedView = getSelectedView();
if (selectedView != null) {
itemZoomOut(selectedView);
}
return true;
}
}
}
return super.dispatchKeyEvent(event);
}
/**
* 放大
*
* @param selectedView
*/
private void itemZoomIn(View selectedView) {
ViewPropertyAnimator animator = selectedView.animate();
animator.scaleX(mScale);
animator.scaleY(mScale);
animator.setDuration(250);
animator.start();
}
/**
* 选中项缩小
*
* @param selectedView
*/
private void itemZoomOut(View selectedView) {
ViewPropertyAnimator animator = selectedView.animate();
animator.scaleX(1f);
animator.scaleY(1f);
animator.setDuration(50);
animator.start();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean result = super.onKeyDown(keyCode, event);
View selectedView = getSelectedView();
if (lastSelectedView == selectedView) {
return result;
}
if (lastSelectedView != null) {
itemZoomOut(lastSelectedView);
}
if (selectedView != null) {
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
itemZoomIn(selectedView);
lastSelectedView = selectedView;
Rect outRect = getDrawRect(selectedView);
if (mCurrRect.isEmpty()) {
selectedView.getHitRect(mCurrRect);
}
if (!mCurrRect.equals(outRect)) {
mScroller.startScroll(mCurrRect, outRect);
}
invalidate();
}
return result;
}
/**
* 获取绘画的区域
*
* @param v
* @return
*/
private Rect getDrawRect(View v) {
Rect outRect = new Rect();
v.getDrawingRect(outRect);
int wMargin = Math.round(outRect.width() * (mScale - 1) / 2);
int hMargin = Math.round(outRect.height() * (mScale - 1) / 2);
v.getHitRect(outRect);
outRect.left -= wMargin;
outRect.top -= hMargin;
outRect.right += wMargin;
outRect.bottom += hMargin;
return outRect;
}
}
|
package com.kingdov.goldwallpapers.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.kingdov.goldwallpapers.activity.MainActivity;
import com.kingdov.goldwallpapers.SplashActivity;
import com.kingdov.goldwallpapers.config.admob;
import comm.kingdov.goldwallpapers.R;
import com.kingdov.goldwallpapers.adapter.WallpaperAdapter;
/**
* Created by kingdov on 17/01/2017.
*/
public class MainFragment extends Fragment {
public static RecyclerView recyclerView;
public static WallpaperAdapter recyclerAdapter;
public static android.support.v7.widget.AppCompatTextView noWallpaper;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_main, container, false);
recyclerView = v.findViewById(R.id.wallpaperList);
noWallpaper = v.findViewById(R.id.no_wallpaper);
LinearLayout linearlayout = v.findViewById(R.id.unitads);
admob.admobBannerCall(getActivity(), linearlayout);
FloatingActionButton fab = v.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), MainActivity.class));
}
});
setRecyclerView(getActivity());
return v;
}
public static void setRecyclerView(Context activity) {
if(SplashActivity.data.size()>0) noWallpaper.setVisibility(View.GONE);
else noWallpaper.setVisibility(View.VISIBLE);
recyclerAdapter = new WallpaperAdapter(activity, SplashActivity.data);
recyclerView.setAdapter(recyclerAdapter);
recyclerView.setLayoutManager(new GridLayoutManager(activity,2));
}
}
|
package com.kalinowskim.recipeproject.services;
import com.kalinowskim.recipeproject.converters.RecipeCommandToRecipe;
import com.kalinowskim.recipeproject.converters.RecipeToRecipeCommand;
import com.kalinowskim.recipeproject.domain.Recipe;
import com.kalinowskim.recipeproject.exceptions.NotFoundException;
import com.kalinowskim.recipeproject.repositories.RecipeRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import static org.springframework.test.util.AssertionErrors.assertNotNull;
public class RecipeServiceImplTest {
private RecipeServiceImpl recipeService;
@Mock
RecipeRepository recipeRepository;
@Mock
RecipeCommandToRecipe recipeCommandToRecipe;
@Mock
RecipeToRecipeCommand recipeToRecipeCommand;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
recipeService = new RecipeServiceImpl(recipeRepository, recipeCommandToRecipe, recipeToRecipeCommand);
}
@Test
public void getAllRecipesTest() {
Recipe recipe = new Recipe();
HashSet<Recipe> recipesData = new HashSet<>();
recipesData.add(recipe);
when(recipeRepository.findAll()).thenReturn(recipesData);
Set<Recipe> recipes = recipeService.getAllRecipes();
assertEquals(recipes.size(), 1);
verify(recipeRepository, times(1)).findAll();
}
@Test
public void findByIdTest() throws Exception {
Recipe recipe = new Recipe();
recipe.setId(1L);
Optional<Recipe> recipeOptional = Optional.of(recipe);
when(recipeRepository.findById(anyLong())).thenReturn(recipeOptional);
Recipe recipeReturned = recipeService.findById(1L);
assertNotNull("Null recipe returned", recipeReturned);
verify(recipeRepository, times(1)).findById(anyLong());
verify(recipeRepository, never()).findAll();
}
@Test
public void deleteByIdTest() {
Long idToDelete = 2L;
recipeService.deleteById(idToDelete);
verify(recipeRepository, times(1)).deleteById(anyLong());
}
@Test(expected = NotFoundException.class)
public void getRecipeByIdTestNotFound() throws Exception {
Optional<Recipe> recipeOptional = Optional.empty();
when(recipeRepository.findById(anyLong())).thenReturn(recipeOptional);
Recipe recipeReturned = recipeService.findById(1L);
//should go boom
}
}
|
package com.loveqrc.web.servlet;
import com.loveqrc.domain.Category;
import com.loveqrc.domain.Product;
import com.loveqrc.domain.User;
import com.loveqrc.service.CategoryService;
import com.loveqrc.service.ProductService;
import com.loveqrc.service.impl.CategoryServiceImpl;
import com.loveqrc.service.impl.ProductServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet(
urlPatterns = "/index"
)
public class IndexServlet extends BaseServlet {
public String index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ProductService productService = new ProductServiceImpl();
List<Product> hotList = null;
List<Product> newList = null;
try {
hotList = productService.findHot();
newList = productService.findNew();
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("nList", newList);
request.setAttribute("hList", hotList);
return "/jsp/index.jsp";
}
}
|
package com.codingchili.router.configuration;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.*;
import com.codingchili.core.configuration.ServiceConfigurable;
import com.codingchili.core.listener.ListenerSettings;
import com.codingchili.core.listener.WireType;
import static com.codingchili.core.configuration.CoreStrings.getService;
/**
* @author Robin Duda
* <p>
* Settings for the router identity.
*/
public class RouterSettings extends ServiceConfigurable {
public static final String PATH_ROUTING = getService("routing");
private List<ListenerSettings> transport = new ArrayList<>();
private Map<String, String> external = new HashMap<>();
public RouterSettings() {
}
public RouterSettings(String address) {
super.setNode(address);
}
/**
* @return a list of configured transports.
*/
public List<ListenerSettings> getTransport() {
return transport;
}
/**
* @param transport sets a list of configured transports.
*/
public void setTransport(List<ListenerSettings> transport) {
this.transport = transport;
}
/**
* Adds a new transport configuration to the list of existing.
*
* @param listener the listener to add
* @return fluent
*/
public RouterSettings addTransport(ListenerSettings listener) {
transport.add(listener);
return this;
}
/**
* @return returns a set of hidden nodes, the router must not route
* messages to these nodes.
*/
public Map<String, String> getExternal() {
return external;
}
public void setHidden(Map<String, String> external) {
this.external = external;
}
/**
* Get configuration for the specified listener.
*
* @param type the type of transport to get configuration for.
* @return the listener setting.
*/
public ListenerSettings getListener(WireType type) {
for (ListenerSettings listener : transport) {
if (listener.getType().equals(type)) {
return listener;
}
}
throw new RuntimeException("No listener configured for " + type.name());
}
/**
* Sets a route to hidden in the router. Any requests for this route will return
* with an error and the unauthorized code.
*
* @param target the route to 'hide' requests for
* @param routeRegex the regex to match routes against.
* @return fluent
*/
public RouterSettings addExternal(String target, String routeRegex) {
if (external.containsKey(target)) {
throw new IllegalArgumentException(String.format("External target '%s' is already added.", target));
}
external.put(target, routeRegex);
return this;
}
@JsonIgnore
public boolean isExternal(String target, String route) {
target = target.toLowerCase();
route = route.toLowerCase();
return external.containsKey(target) && route.matches(external.get(target));
}
}
|
package webuters.com.geet_uttarakhand20aprilpro.activity;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.List;
import webuters.com.geet_uttarakhand20aprilpro.R;
//import com.google.analytics.tracking.android.EasyTracker;
//import com.google.analytics.tracking.android.MapBuilder;
//import com.google.analytics.tracking.android.StandardExceptionParser;
/**
* Created by Tushar on 2/25/2016.
*/
public class MAP extends Activity implements OnMapReadyCallback {
GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
mMap=map;
Log.d("sun",EventDetailesMainClass.Location);
getLocationFromAddress(MAP.this, EventDetailesMainClass.Location);
// map.addMarker(new MarkerOptions()
// .position(new LatLng(28.630407, 77.275868))
// .title("Marker"));
}
public LatLng getLocationFromAddress(Context context,String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
double latitude= location.getLatitude();
double longitude=location.getLongitude();
Log.d("sun",latitude+" "+longitude);
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Event"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(p1));
} catch (Exception ex) {
ex.printStackTrace();
}
return p1;
}
}
//
// extends FragmentActivity implements OnMapReadyCallback {
//
// Button mBtnFind;
// GoogleMap mMap;
// EditText etPlace;
// String Location_finder;
//
//// private EasyTracker easyTracker = null;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.map);
//
//
//// easyTracker = EasyTracker.getInstance(this);
//// easyTracker.send(MapBuilder.createEvent("your_action", "envet_name", "button_name/id", null).build());
////
//// try {
//// int a[] = new int[2];
//// int num = a[4];
//// } catch (ArrayIndexOutOfBoundsException e) {
//// easyTracker.send(MapBuilder.createException(
//// new StandardExceptionParser(this, null)
//// .getDescription(Thread.currentThread().getName(), e), false).build());
//// }
//
// Location_finder=EventDetailesMainClass.Location;
////
//// Intent intent = getIntent();
//// if (null != intent) {
//// Location_finder = intent.getStringExtra("Location_ADDRESS");
//// // Location_finder = String.valueOf(intent.getExtras().getInt("Location_ADDRESS"));
////
////// Log.e("Location_finder Location recived ====>>", Location_finder);
////
//// }
//
//
//
//
//
// // Getting reference to the find button
//// mBtnFind = (Button) findViewById(R.id.btn_show);
//
// // Getting reference to the SupportMapFragment
//
// SupportMapFragment supportMapFragment =
// (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
// mMap = supportMapFragment.getMap();
//
//
//// SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
////
//// // Getting reference to the Google Map
//// mapFragment.getMapAsync(this);
////
////
////
//// MarkerOptions markerOptions = new MarkerOptions();
////
//// LatLng latLng = new LatLng(28.630407, 77.275868);
////
//// // Setting the position for the marker
//// markerOptions.position(latLng);
////
//// // Setting the title for the marker
//// markerOptions.title("location");
////
//// // Placing a marker on the touched position
//// mMap.addMarker(markerOptions);
// // Getting reference to EditText
// // etPlace = (EditText) findViewById(R.id.et_place);
//
// // Setting click event listener for the find button
//// mBtnFind.setOnClickListener(new View.OnClickListener() {
////
//// @Override
//// public void onClick(View v) {
// // Getting the place entered
//// String location = Location_finder;
//// Log.d("sun",location);
////
////// if(location==null || location.equals("")){
////// Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
////// return;
////// }
////
//// String url = "https://maps.googleapis.com/maps/api/geocode/json?";
////
//// try {
//// // encoding special characters like space in the user input place
//// location = URLEncoder.encode(location, "utf-8");
//// } catch (UnsupportedEncodingException e) {
//// e.printStackTrace();
//// }
////
//// String address = "address=" + location;
////
//// String sensor = "sensor=false";
////
////
//// // url , from where the geocoding data is fetched
//// url = url + address + "&" + sensor;
////
//// // Instantiating DownloadTask to get places from Google Geocoding service
//// // in a non-ui thread
//// DownloadTask downloadTask = new DownloadTask();
////
//// // Start downloading the geocoding places
//// downloadTask.execute(url);
//
//
////
//// }
//// });
//
// }
//
// private String downloadUrl(final String strUrl) throws IOException {
// final String[] data1 = {""};
// new AsyncTask<Void,Void,Void>(){
// String data = "";
// @Override
// protected Void doInBackground(Void... params) {
// InputStream iStream = null;
// HttpURLConnection urlConnection = null;
// try{
// URL url = new URL(strUrl);
//
//
// // Creating an http connection to communicate with url
// urlConnection = (HttpURLConnection) url.openConnection();
//
// // Connecting to url
// urlConnection.connect();
//
// // Reading data from url
// iStream = urlConnection.getInputStream();
//
// BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
//
// StringBuffer sb = new StringBuffer();
//
// String line = "";
// while( ( line = br.readLine()) != null){
// sb.append(line);
// }
//
// data = sb.toString();
//
// br.close();
//
// }catch(Exception e){
// Log.d("Excpon whle downing url", e.toString());
// }finally{
// try {
// iStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// urlConnection.disconnect();
// }
// return null;
// }
//
// @Override
// protected void onPostExecute(Void aVoid) {
// super.onPostExecute(aVoid);
// data1[0] =data;
// Log.d("sun","data:-"+data);
// }
// }.execute();
// return data1[0];
// }
//
// @Override
// public void onMapReady(GoogleMap googleMap) {
//
// }
//
//
// /** A class, to download Places from Geocoding webservice */
// private class DownloadTask extends AsyncTask<String, Integer, String>{
//
// String data = null;
//
// // Invoked by execute() method of this object
// @Override
// protected String doInBackground(String... url) {
// try{
// data = downloadUrl(url[0]);
// }catch(Exception e){
// Log.d("Background Task", e.toString());
// }
// return data;
// }
//
// // Executed after the complete execution of doInBackground() method
// @Override
// protected void onPostExecute(String result){
// Log.d("sun","result:-"+result);
// // Instantiating ParserTask which parses the json data from Geocoding webservice
// // in a non-ui thread
// ParserTask parserTask = new ParserTask();
//
// // Start parsing the places in JSON format
// // Invokes the "doInBackground()" method of the class ParseTask
// parserTask.execute(result);
// }
//
// }
//
// /** A class to parse the Geocoding Places in non-ui thread */
// class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>> {
//
// JSONObject jObject;
//
// // Invoked by execute() method of this object
// @Override
// protected List<HashMap<String,String>> doInBackground(String... jsonData) {
//
// List<HashMap<String, String>> places = null;
// GeocodeJSONParser parser = new GeocodeJSONParser();
//
// try{
// jObject = new JSONObject(jsonData[0]);
//
// /** Getting the parsed data as a an ArrayList */
// places = parser.parse(jObject);
//
// }catch(Exception e){
// Log.d("Exception",e.toString());
// }
// return places;
// }
//
// // Executed after the complete execution of doInBackground() method
// @Override
// protected void onPostExecute(List<HashMap<String,String>> list){
//
// // Clears all the existing markers
// if(mMap!=null) {
// mMap.clear();
// }
//
// for(int i=0;i<list.size();i++){
//
// // Creating a marker
// MarkerOptions markerOptions = new MarkerOptions();
//
// // Getting a place from the places list
// HashMap<String, String> hmPlace = list.get(i);
//
// // Getting latitude of the place
// double lat = Double.parseDouble(hmPlace.get("lat"));
// Log.d("maps","lat = "+lat);
//
// // Getting longitude of the place
// double lng = Double.parseDouble(hmPlace.get("lng"));
// Log.d("maps","lng = "+lng);
// // Getting name
// String name = hmPlace.get("formatted_address");
//
// LatLng latLng = new LatLng(lat, lng);
//
// // Setting the position for the marker
// markerOptions.position(latLng);
//
// // Setting the title for the marker
// markerOptions.title(name);
//
// // Placing a marker on the touched position
// mMap.addMarker(markerOptions);
//
// // Locate the first location
// if(i==0)
// mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// }
// }
// }
//
//
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
// return true;
// }
//
//// @Override
//// public void onStart() {
//// super.onStart();
//// EasyTracker.getInstance(this).activityStart(this);
//// }
////
//// @Override
//// public void onStop() {
//// super.onStop();
//// EasyTracker.getInstance(this).activityStop(this);
//// }
//}
//
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.explorer.client.binding;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.data.client.editor.ListStoreEditor;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.PropertyAccess;
import com.sencha.gxt.examples.resources.client.model.Kid;
import com.sencha.gxt.examples.resources.client.model.Person;
import com.sencha.gxt.widget.core.client.form.FieldLabel;
import com.sencha.gxt.widget.core.client.form.FormPanel.LabelAlign;
import com.sencha.gxt.widget.core.client.form.NumberField;
import com.sencha.gxt.widget.core.client.form.NumberPropertyEditor.DoublePropertyEditor;
import com.sencha.gxt.widget.core.client.form.NumberPropertyEditor.IntegerPropertyEditor;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.editing.GridInlineEditing;
public class PersonEditor implements IsWidget, Editor<Person> {
interface KidProperties extends PropertyAccess<Kid> {
@Path("name")
ModelKeyProvider<Kid> key();
ValueProvider<Kid, String> name();
ValueProvider<Kid, Integer> age();
}
private static final KidProperties props = GWT.create(KidProperties.class);
TextField name = new TextField();
TextField company = new TextField();
TextField location = new TextField();
NumberField<Double> income = new NumberField<Double>(new DoublePropertyEditor());
ListStore<Kid> kidStore = new ListStore<Kid>(props.key());
ListStoreEditor<Kid> kids = new ListStoreEditor<Kid>(kidStore);
@Override
public Widget asWidget() {
FlowPanel container = new FlowPanel();
// should be layout based
int w = 275;
name.setWidth(w);
company.setWidth(w);
location.setWidth(w);
income.setWidth(w);
container.add(new FieldLabel(name, "Name"));
container.add(new FieldLabel(company, "Company"));
container.add(new FieldLabel(location, "Location"));
container.add(new FieldLabel(income, "Income"));
List<ColumnConfig<Kid, ?>> columns = new ArrayList<ColumnConfig<Kid,?>>();
ColumnConfig<Kid, String> name = new ColumnConfig<Kid, String>(props.name(), 200, "Name");
columns.add(name);
ColumnConfig<Kid, Integer> age = new ColumnConfig<Kid, Integer>(props.age(), 100, "Age");
columns.add(age);
Grid<Kid> grid = new Grid<Kid>(kidStore, new ColumnModel<Kid>(columns));
grid.setBorders(true);
grid.getView().setForceFit(true);
GridInlineEditing<Kid> inlineEditor = new GridInlineEditing<Kid>(grid);
inlineEditor.addEditor(name, new TextField());
inlineEditor.addEditor(age, new NumberField<Integer>(new IntegerPropertyEditor()));
grid.setWidth(382);
grid.setHeight(200);
FieldLabel kidsContainer = new FieldLabel();
kidsContainer.setText("Kids");
kidsContainer.setLabelAlign(LabelAlign.TOP);
kidsContainer.setWidget(grid);
container.add(kidsContainer);
return container;
}
}
|
package org.giddap.dreamfactory.geeksforgeeks.dynamicprogramming;
/**
* http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/
* <p/>
* Given a sequence, find the length of the longest palindromic subsequence in it. For example, if the given
* sequence is “BBABCBCAB”, then the output should be 7 as “BABCBAB” is the longest palindromic subseuqnce in it.
* “BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones.
* <p/>
*/
public class Set12LongestPalindromicSubsequence {
}
|
package com.hbk.test;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import com.bbg.test.ArrStr;
public class Matrix {
private static int [] [] grid;
public static void main(String[] args) {
/*
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> path = new ArrayList<ArrayList<Integer>>();
grid = new int[][]{ {0, 0, 1, 0, 0, 1, 0},
{1, 0, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 1},
{1, 0, 1, 0, 0, 0, 0},
{1, 0, 1, 1, 0, 1, 0},
{1, 0, 0, 0, 0, 1, 0},
{1, 1, 1, 1, 0, 0, 0}};
int count =traverse(0,0,0, list,path);
System.out.println(count);
*/
//int ret = backPackVal(10, new int[]{2,3,5,7}, new int[]{1, 5, 2, 4});
//int ret = numDecodings("1234");
//int ret = minEditDistance("mart","karma");
int[] arr = {0,1, 4, 7, 9,15, 17,18,20};
int max = maxProfit(arr);
System.out.println(max);
return;
}
//no need way list path if just count
//similar find min cost, each grid element store cost{up,down,left,right} to neighbors, MAX_VALUE for border
//int traverse (int row, int col, int cost)
//if out of boundary or visited (grid[i][j]==null), return MAX_VALUE; if reach dest, return cost
//result = min(traverse(row+|-,col+|-1,cost+grid[row][col].up|down|left|right)
//similar sliding puzzle, init grid one empty slot at most rightdown can swap with up|right|left slot, result grid to find path
//traverse from result back to init 3 ways, use way to swap empty slot with target it moving to till reach rightdown,
//compare grid with given init, if same return path otherwise continue to find next path
public static int traverse (int row, int col, int way, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> path) {
if ((row < 0) || (row >= grid.length) || (col < 0) || (col >= grid[0].length)){
return 0;
} else {
int pos = grid[row][col];
if (pos == 1 || pos == -1 ) {
// block or visited
return 0;
} else if (row == grid.length-1 && col == grid[0].length-1) {
//reach the dest, count it as a one
ArrayList<Integer> temp = new ArrayList<Integer>(list);
temp.add(way);//last step
path.add(temp);
return 1;
} else {
grid[row][col] = -1; // record this position so don't revisit.
list.add(way);
// Count all possible path with one less digit starting
int result=0;
result = traverse(row,col+1,1,list,path)//right
+ traverse(row+1,col,2,list,path)//down
+ traverse(row,col-1,3,list,path)//left
+ traverse(row-1,col,4,list,path);//up
grid[row][col] = pos; // Remove record from position.
list.remove(list.size()-1);
return result;
}
}
}
//m x n grid filled with non-negative numbers, path (down or right) from top left to bottom right which minimizes the sum of all numbers along its path
//similar find number of possible unique paths
//similar probability of passing given (x,y) if corner 1 side 2 mid 4 /total, because 1|2|4 way to pass it
static int minPathSum(int[][] grid) {//O(MN)time
if(grid == null || grid.length==0)
return 0;
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m][n];
dp[0][0] = grid[0][0];
// initialize top row with sum of path
for(int i=1; i<n; i++){
dp[0][i] = dp[0][i-1] + grid[0][i];
//if(grid[0][i]!=1) 1 as block
//dp[0][i] = 1;//find number of possible unique paths: only move right without direction change as one path
}
// initialize left column with sum of path
for(int j=1; j<m; j++){
dp[j][0] = dp[j-1][0] + grid[j][0];
//if(grid[j][0]!=1) 1 as block
//dp[j][0] = 1;//only move down without direction change as one path
}
//dp min path value to each pos : dp(1,1)=min(dp(0,1),dp(1,0)) + grid(1,1)
for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
dp[i][j] = Math.min(dp[i][j-1],dp[i-1][j]) + grid[i][j];
//if(grid[i][j]!=1) 1 as block dp[i][j] stay 0
//dp[i][j] = dp[i-1][j] + dp[i][j-1]; dp[j] += dp[j - 1];//1D
}
}
return dp[m-1][n-1]; //return dp[n-1];
}
//depth-first search: reiterate of same subpath can be avoided by Dynamic Programming O(mn)
//[if grid[i][j] is char, given a dictionary (hashset), find longest valid word by path down or right]
//[?load dict words into trie, start from from [m,n] go thru every [i,j] to [0,0], move up or left because dfs reverse
static int dfs(int i, int j){//[string dfs(int i, int j)]
//if(grid[i][j]==1) return 0; 1 as block
if(i==grid.length-1 && j==grid[0].length-1){
return grid[i][j];
//return 1; //find possible unique paths
}
if(i<grid.length-1 && j<grid[0].length-1){
int r1 = grid[i][j] + dfs(i+1, j);//[string r1 = dfs(i-1, j)+grid[i][j];
int r2 = grid[i][j] + dfs(i, j+1);//[string r2 = dfs(i, j-1)+grid[i][j];
return Math.min(r1,r2);//if trie.prefix(r1|r2) return string r=longer(r1,r2)
//return dfs(i+1,j) + dfs(i,j+1);
}
//j=grid[0].length-1 right col
if(i<grid.length-1){
return grid[i][j] + dfs(i+1, j);
//return dfs(i+1,j);
}
//i=grid.length-1 bottom row
if(j<grid[0].length-1){
return grid[i][j] + dfs(i, j+1);
//return dfs(i,j+1);
}
return 0;//out of boundary
}
//determine the knight's minimum initial health to reach the princess with at least 1 health point
//-2 (K)-3 3
//-5 -10 1
//10 30 -5 (P)
static int calculateMinimumHP(int[][] dungeon) {
int m = dungeon.length;
int n = dungeon[0].length;
int[][] h = new int[m][n];
//dungeon[m - 1][n - 1]<0 ? 1 - dungeon[m - 1][n - 1] : 1, min HP required at P
//dungeon -5 then need hp 6 to get 1 left, 5 then only need 1 to continue
h[m - 1][n - 1] = Math.max(1 - dungeon[m - 1][n - 1], 1);
//init last row, can only move right
for (int i = m - 2; i >= 0; i--) {//reverse set based on h[m - 1][n - 1]
h[i][n - 1] = Math.max(h[i + 1][n - 1] - dungeon[i][n - 1], 1);
}
//init last column, can only move down
for (int j = n - 2; j >= 0; j--) {
h[m - 1][j] = Math.max(h[m - 1][j + 1] - dungeon[m - 1][j], 1);
}
//h[i][j] is the minimum health value before he enters (i,j)
for (int i = m - 2; i >= 0; i--) {
for (int j = n - 2; j >= 0; j--) {
int down = Math.max(h[i + 1][j] - dungeon[i][j], 1);
int right = Math.max(h[i][j + 1] - dungeon[i][j], 1);
h[i][j] = Math.min(right, down);
}
}
return h[0][0];
}
//'1's (land) and '0's (water), count the number of islands
//0 empty seat,1 healthy kid, 2 sick kid, healthy kid sit next to sick kid will be affected, find num of final healthy kids
static int numIslands() {//O(m*n)
if (grid==null || grid.length==0 || grid[0].length==0) return 0;
int count = 0;
for (int i=0; i<grid.length; i++) {
for (int j=0; j<grid[0].length; j++) {
if(grid[i][j] == '1'){//if(grid[i][j] != '0') diff land 1, 2, 3...
count++;
merge(i, j);//set all adjacent land to water so each land only count 1, merge(i, j, grid[i][j]);
}
}
}
return count;
}
//each side expose to water or other land count as 1 for perimeter, 1 perimeter 4, 11 perimeter 6
static void merge(int i, int j){//[int] merge(int i, int j, land[, perimeter])
//boundary check can be spared by adding 0 around the matrix
if(i<0 || j<0 || i>grid.length-1 || j>grid[0].length-1)
return; //[return 1; increment perimeter by 1 if reach the end]
//if current cell is water or visited
if(grid[i][j] == '0')// || grid[i][j]!=land) only merge if same kind land
return; //[return 1;]
//set visited cell to '0'
grid[i][j] = '0'; //[return 0; if same land or revisit need not increment perimeter]
merge(i-1, j);//merge(i-1, j,land);
merge(i+1, j);
merge(i, j-1);
merge(i, j+1);
//[return merge(i-1, j)+merge(i+1, j)+merge(i, j-1)+merge(i, j+1);]
}
//000
//010
//001
//merge all 1 at border and its adjacent 1 to #, only isolated 1 will remain, convert them to 0
//000
//000
//001
public void solve() {
int m = grid.length;
int n = grid[0].length;
for(int i=0;i<m;i++){//merge 1 to # on left & right boarder
if(grid[i][0] == '1')
bfs(i, 0);
if(grid[i][n-1] == '1')
bfs(i,n-1);
}
for(int j=0; j<n; j++){//merge 1 to # on top & bottom boarder
if(grid[0][j] == '1')
bfs(0,j);
if(grid[m-1][j] == '1')
bfs(m-1,j);
}
for(int i=0;i<m;i++){//process the board, 1 to 0 and revert #
for(int j=0; j<n; j++){
if(grid[i][j] == '1'){
grid[i][j] = '0';
}else if(grid[i][j] == '#'){
grid[i][j] = '1';
}
}
}
}
private Queue<Integer> queue = new LinkedList<Integer>();
private void bfs(int i, int j) {//BFS avoid overflow caused by DFS merge
int n = grid[0].length;
fillCell(i, j);
while (!queue.isEmpty()) {
int cur = queue.poll();
int x = cur / n;
int y = cur % n;
fillCell(x - 1, y);
fillCell(x + 1, y);
fillCell(x, y - 1);
fillCell(x, y + 1);
}
}
private void fillCell(int i, int j) {
int m = grid.length;
int n = grid[0].length;
if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != '1')
return;
// add current cell is queue & then process its neighbors in bfs
queue.offer(i * n + j);
grid[i][j] = '#';
}
//find the largest square containing all 1's
public int maxSquare(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int n = matrix.length;
int m = matrix[0].length;
int[][] dp = new int[n][m];
int maxLen = 0;
//Init right and bottom
for (int i = 0; i < m; i++) {
dp[n - 1][i] = matrix[n - 1][i];
maxLen = Math.max(maxLen, dp[n - 1][i]);
}
for (int i = 0; i < n; i++) {
dp[i][m - 1] = matrix[i][m - 1];
maxLen = Math.max(maxLen, dp[i][m - 1]);
}
//if start from rigt-bottom: right and bottom dont have prev to increment on, but left and top can be incremented above prev
for (int i = n - 2; i >= 0; i--) {
for (int j = m - 2; j >= 0; j--) {
if (matrix[i][j] == 1) {
//if min=1, all adjacent 3 point in current 2X2 square are 1s, then new length dp[i][j]=2
//if min=2, all adjacent 3 2X2 squares are 1s, then new length dp[i][j]=3
dp[i][j] = Math.min(Math.min(dp[i][j + 1], dp[i + 1][j]), dp[i + 1][j + 1]) + 1;
maxLen = Math.max(maxLen, dp[i][j]);
}
}
}
return maxLen * maxLen;
}
static int maximalRectangle(char[][] matrix) {
int m = matrix.length;
int n = m == 0 ? 0 : matrix[0].length;
int[][] dp = new int[m][n + 1];
//dp[i][j] represents the number of consecutive 1's (without 0 in between) in column j which end in row i (including).
int maxArea = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '0') {
dp[i][j] = 0;
} else {
dp[i][j] = i == 0 ? 1 : dp[i - 1][j] + 1;
}
}
}
//call "Largest Rectangle in Histogram" on each row level
for (int i = 0; i < m; i++) {
int area = ArrStr.largestRectangle(dp[i]);
if (area > maxArea) {
maxArea = area;
}
}
return maxArea;
}
//Given n items with size A[i], return the max size a backpack of size m can be filled
//time/space complexity O(mn)
static int backPack2D(int m, int[] A) {
if (A == null || A.length == 0 || m <= 0) {
return 0;
}
//dp[i][j] means if some of items A[0-i] can fulfill size j
boolean[][] dp = new boolean[A.length + 1][m + 1];
//for simplicity, add A[0]=0 so j-A[i] instead of j-A[i-1]
dp[0][0] = true;//dp[2][0]=dp[1][0]=dp[0][0] (A[2|1]>j=0)
//dp[i][j] = either dp[i-1][j-A[i]] (add item i) or dp[i-1][j] (not add item i) is true
//j=0<i dp[i][0]=true=dp[i][2-2]=dp[i][4-2]=dp[i][3-3]
// 0 1 2 3 4
//0[T, F, F, F, F]2
//1[T, F, T, F, F]3(2)
//2[T, F, T, T, F] (3)
//dp[1][2]=dp[0][2]||dp[0][2-2]=T
//dp[1][3]=dp[0][3]||dp[0][3-2]=F
//dp[2][2]=dp[1][2] j=2<A[2]=3
//dp[2][3]=dp[1][3]||dp[1][3-3]=T
for (int i = 1; i <= A.length; i++) {
for (int j = 0; j <= m; j++) {
if (j - A[i - 1] >= 0) {
//A[i - 1] represent A[i] due to an extra help row, calculate row i-1 value save in row i
dp[i][j] = dp[i - 1][j] || dp[i - 1][j - A[i - 1]];
} else {// j is smaller than A[i-1], not adding A[i-1]
dp[i][j] = dp[i - 1][j];
}
}
}
for (int j = m; j >= 0; j--) {
if (dp[A.length][j]) {
return j;//Return max j with dp[A.length][j] true.
}
}
return 0;
}
//time complexity O(mn),space complexity O(m)
static int backPack1D(int m, int[] A) {
if (A == null || m == 0) {
return 0;
}
boolean[] DP = new boolean[m + 1];
DP[0] = true;//other init false
//DP[i][j]= DP[i-1][j-A[i]] | DP[i-1][j], result of row i only depend on previous row i-1
//and only last DP row[i=A.length] matters, can reuse one DP row so i recalc and override DP result from previous row i-1
//1[T, F, T, F, F]2
//2[T, F, T, T, F]3 DP[3]=DP[3-3]=DP[0] which still has result from previous i
for (int i = 1; i <= A.length; i++) {//DP row i only depend on row i-1, so i still from 1 up
for (int j = m; j >= 0; j--) {//from m to 0 to use lower DP[j] result from previous row
if (j - A[i - 1] >= 0 && DP[j - A[i - 1]]) {
//DP[0]=DP[2]=DP[3]=true
DP[j] = true;
}
//else: dp[i][j] = dp[i - 1][j]; no need to recalc for i, keep result from i-1
}
}
for (int j = m; j >= 0; j--) {
if (DP[j]) {
return j;
}
}
return 0;
}
//Given n items with size Ai and value Vi, and a backpack with size m. What's the maximum value can you put into the backpack
//A[2, 3, 5, 7] V[1, 5, 2, 4] m=10 return 9
static int backPackVal(int m, int[] A, int V[]) {
if (A == null || m == 0) {
return 0;
}
int[] DP = new int[m + 1];
DP[0] = 0;//save max value instead of T/F
for (int i = 1; i <= A.length; i++) {
for (int j = m; j >= 0; j--) {
if (j - A[i - 1] >= 0 ) {
DP[j] = Math.max(DP[j], DP[j-A[i-1]] + V[i-1]);//DP[j] from previous i (not add) or DP[j-A[i-1]]+V[i-1] (add)
}
}
}
int max=0;
for (int j = m; j >= 0; j--) {
max=Math.max(DP[j], max);
}
return max;
}
//similar sell stock qty(index) 1, 2, 3, 4, 5, 6, 7, 8 profit 1, 4, 7, 9,15, 17,18,20, max profit sell 8 by any way 3:7+5:15=22
static int maxProfit(int[] arr){
if(arr == null || arr.length == 0)
return 0;
int[] dp = new int[arr.length];
for(int i = 1; i < arr.length; i++){
for(int j = 0; j <= i; j++)
dp[i] = Math.max(dp[i], dp[i - j] + arr[j]); //btw use arr[j]: [i - j]+[j] or keep existing [i]
}
return dp[arr.length-1];
}
//Min times of char operation (replace, delete, insert) required to transform one string to another
//given a word, find closest word from a list
static int minEditDistance(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
// len1+1, len2+1, because finally return dp[len1][len2]
int[][] dp = new int[len1 + 1][len2 + 1];
//each right or down as a insert or delete, rightdown as a replace
for (int i = 0; i <= len1; i++) {
dp[i][0] = i;//dp[1,0]=1 as insert word1[0], till dp[len,0]=word[len-1]
}
for (int j = 0; j <= len2; j++) {
dp[0][j] = j;
}
for (int i = 0; i < len1; i++) {
char c1 = word1.charAt(i);
for (int j = 0; j < len2; j++) {
char c2 = word2.charAt(j);
//update dp[i + 1][j + 1] value for char at word1[i],word2[j]
//Replace:dp[i + 1][j + 1] = word1[i] == word2[j] ? DP[i][j] : DP[i][j] + 1;
//Insert: dp[i + 1][j + 1] = dp[i][j+1] + 1; // missing 1 char in word1
//Delete: dp[i + 1][j + 1] = dp[i+1][j] + 1; // extra char in word1
if (c1 == c2) {
//no additional op required above previous
dp[i + 1][j + 1] = dp[i][j];
} else {
int replace = dp[i][j] + 1;
//dp[i][j + 1] already has 1 as delete|insert from dp[i][j], +1 as insert|delete as second step, delete and insert equivalent to replace
int insert = dp[i][j + 1] + 1;
int delete = dp[i + 1][j] + 1;
//min(replace,insert,delete)
int min = replace > insert ? insert : replace;
min = delete > min ? min : delete;
dp[i + 1][j + 1] = min;
}
}
}
return dp[len1][len2];
}
//number of distinct subsequences of T= "rabbit" in S = "rabbbit", 3:bb_,b_b,_bb
public int numSubsequences(String S, String T) {
int[][] dp = new int[S.length() + 1][T.length() + 1];
for (int i = 0; i < S.length(); i++)
dp[i][0] = 1;//when T=="", whatever S will have 1 subsequence: ""
for (int j = 1; j < T.length(); j++)
dp[0][j] = 0;//when S=="", whatever T will not be subsequence of S == "", but keep dp[0][0]=1
for (int i = 1; i <= S.length(); i++) {
for (int j = 1; j <= T.length(); j++) {
dp[i][j] = dp[i - 1][j];//when T exist in S[a~b], it will surely exist in S[a~b+1], so DP[i][j] = DP[i-1][j] + something
if (S.charAt(i - 1) == T.charAt(j - 1))
//if S[i] and S[i - 1] both equals to T[j - 1], count dp[i - 1][j - 1]'s previous records in
dp[i][j] += dp[i - 1][j - 1];//T(ap) S(app) count of 2nd p also need add count of 1st p, otherwise last result as 1 not 2
}
}
return dp[S.length()][T.length()];
}
//longest common substring
// b a b
//c 0 0 0
//a 0 1 0
//b 1 0 2
//a 0 2 0
//if a[i]=b[j] then dp[i,j]=dp[i-1,j-1]+1, return max(dp[i,j])
//use 1D c[] to keep only last dp row and override it
static void getLCString(char[] a, char[] b) {
int i, j;
int len1, len2;
len1 = a.length;
len2 = b.length;
int maxLen = len1 > len2 ? len1 : len2;
int max = 0;
int[] maxIndex = new int[maxLen];
int[] c = new int[maxLen];
for (i = 0; i < len2; i++) {
for (j = len1 - 1; j >= 0; j--) {//from len to 0 to use lower c[j] result from previous row
if (b[i] == a[j]) {//i and j no need to be in same ascend order based on previous dp
if ((i == 0) || (j == 0))
c[j] = 1;//initial c[0], no previous c
else
c[j] = c[j - 1] + 1;
} else {
c[j] = 0;
}
if (c[j] > max) {
max = c[j];
maxIndex[0] = j;
//if a bigger new max, save it at index 0 and clean the rest that equal to previous max
for (int k = 1; k < maxLen; k++) {
maxIndex[k] = 0;
}
} else if (c[j] == max) { //multiple substrings at the same length as current max
for (int k = 1; k < maxLen; k++) {
if (maxIndex[k] == 0) {
maxIndex[k] = j;//end index of multiple substrings at the same length = c[j] = max[0]
break; //append to the last element of maxIndex[]
}
}
}
}
}
for (j = 0; j < maxLen; j++) {
if (maxIndex[j] > 0) {
for (i = maxIndex[j] - max + 1; i <= maxIndex[j]; i++)
System.out.print(a[i]);
}
}
}
//divide b[m] books among k scribes, each book has page b[i] and can be assign to one scriber
//scriber start at the same time at same writing speed 1page per minute, min time to finish (k<m, other wise max(b[i]) is the answer)
//f[i][j] min time for first i books are given to j scribes to finish
//f[i][j] = min{max(f[x][j-1], sum(b[x+1 ~ i])), j<x<i} jth scribe start from xth book
static int minCopyTime(int[] b,int k) {
int[][] dp = new int[b.length+1][k+1];
for(int j=0;j <k;j++)
dp[0][j]=b[0];//1st book given to one of j scribes always take same pages time
for(int i=1;i<b.length;i++){
dp[i][0]=dp[i-1][0]+b[i];//first i books are given to 1 scribe to finish
}
for(int i=1;i<=b.length;i++){
for(int j=1;j<=k;j++){
int min=Integer.MAX_VALUE;
int max = 0;
int sumPgs = 0;
for (int l = j; l <= i; l++)//j-1 =< l < i because each scribe has at lease 1 book
sumPgs = sumPgs + b[l];
for(int m=j-1;m<i;m++){
//dp[m][j-1] sum[m+1 ~ i] : loop thru all m that book[j-1~m] assign to j-1 and book[m+1~i] assign to jth scribes
max = Math.max(dp[m][j-1],sumPgs);
if (min>max)
min=max;
sumPgs -= b[m+1];//keep sum [m+1 ~ i] for the next loop
}
dp[i][j]=min;
}
}
return dp[b.length][k];
}
//Given n balloons, Each painted with a number[i],
//burst balloon i will get nums[left] * nums[i] * nums[right] coins, and the left and right then becomes adjacent
//dp[i][j]: max coins for burst all balloons between i and j
static int maxBalloonCoins(int[] iNums) {
int n = iNums.length;//iNums[0,n-1]
int[] nums = new int[n + 2];
for (int i = 0; i < n; i++) nums[i + 1] = iNums[i];//shift 1 index to handle iNums[-1] as nums[0]
//burst last balloon get iNums[-1]*iNums[i]*iNums[n] coins, add nums[0](iNums[-1]) and nums[n+1](iNums[n]) =1
nums[0] = nums[n + 1] = 1;
int[][] dp = new int[n + 2][n + 2];
return DP(1, n, nums, dp);//start from 1
}
static int DP(int i, int j, int[] nums, int[][] dp) {
if (dp[i][j] > 0) return dp[i][j];//memo previous result
for (int x = i; x <= j; x++) {
// nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
// coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
dp[i][j] = Math.max(dp[i][j], DP(i, x - 1, nums, dp) + nums[i - 1] * nums[x] * nums[j + 1] + DP(x + 1, j, nums, dp));
}
return dp[i][j];
}
//each step can merge two adjacent stone piles to a new pile, the sum of stone in the new pile is accumulated as cost
//if can merge any two piles instead of adjacent, then push all into heap, each time pull 2 min merge and push back
//similar: minimum cost of concat adjacent strings a+b=ab c+d=cd ab+cd=abcd 2+2+4=8 vs a+b=ab ab+c=abc abc+d=abcd 2+3+4=9
//dp[i][j]=min(dp[i][k]+dp[k+1][j]+sum[i,j]) for all k from i to j, dp[i][j] = 0; (i=j)
//min cost for merge stone between i and j = merge stone between i and k + merge stone between k+1 and j ,
public int minCostMergeStone(int[] S) {
int n = S.length;
int[][] dp = new int[n][n];
int[] sum = new int[n]; //no need for concat string all length=1, j-i+1 is sum[i,j]
for(int i=0; i<n; i++) {
sum[i] = (i>0?sum[i-1]:0) + S[i]; //sum up S[0-i]
}
for(int i=0; i<n; i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE); //init all dp[i][j] as max value for later min
dp[i][i] = 0;
}
for(int w=1; w<n; w++) {//window=1 merge every adjacent piles, then =2 merge every adjacent piles from prev merge
for(int i=0; i<n-w; i++) {
int j = i+w; //end=start+window(sliding)
int sumij = sum[j] - (i>0?sum[i-1]:0); // S[0-j]-S[0-i], can only merge adjacent
for(int k=i; k<j; k++) {//find min dp among all possible k between i,j
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k+1][j] + sumij);//compare with dp[i][j] from prev k
}
}
}
return dp[0][n-1];
}
//total number of ways to decode a digits message based on map 'A'=1 'B'=2 ... 'Z'=26
static int numDecodings(String s) {
if(s==null||s.length()==0||s.equals("0"))
return 0;
int[] t = new int[s.length()+1];
t[0] = 1; //to work with t[1] as below
if(isValid(s.substring(0,1)))
t[1]=1;//1st digit in (1,9) can surely be decoded to a char 1 0 X : 1 1 2
else
t[1]=0;//1st digit =0 0 1 X : 1 0 1
for(int i=2; i<=s.length(); i++){
if(isValid(s.substring(i-1,i))){
t[i]+=t[i-1];
}
//either previous 1 or previous 2 digits are in (1,26) will increment t[i]
//1234 t[2]+=t[1] also t[2]+=t[0] 1<23<26, t[2]=2
if(isValid(s.substring(i-2,i))){
t[i]+=t[i-2];
}
}
return t[s.length()];
}
//verify if char 1-26
static boolean isValid(String s){
if(s.charAt(0)=='0')
return false;//if 0 does not count or 0X already count as X
int value = Integer.parseInt(s);
return value>=1&&value<=26;
}
//searches for a value in an m x n sorted matrix:end = m * n - 1; while(start<end){ mid = (end + start)/2;
//int num = matrix[mid/n][mid%n];//[row][col] if (num < target) { start = mid;}...O(logN+M)
public boolean searchMatrix(int[][] matrix, int target) { //O(m + n)
int m=matrix.length-1;
int n=matrix[0].length-1;
int i=m; //sort on row
int j=0;
while(i>=0 && j<=n){
if(target < matrix[i][j]){
i--;//[m][0] at 1st col of row, if smaller must in the prev row
}else if(target > matrix[i][j]){
j++;//[m][0] at last row, if bigger must in the same row
}else{
return true;
}
}
return false;
}
//find largest submatrix (nxn) DP solution based on Kadane's algorithm - O(n^3) time and O(n^2) space
//Kandane's algorithm is a way to find a contiguous subsequence with maximum sum
public static void kadane2D(int[][] a, int n) {
int[][] s = new int[n + 1][n]; // [ending row][sum from row zero to ending row] (rows 1-indexed!)
for (int r = 0; r < n + 1; r++) {
for (int c = 0; c < n; c++) {
s[r][c] = 0;
}
}
for (int r = 1; r < n + 1; r++) {
for (int c = 0; c < n; c++) {
s[r][c] = s[r - 1][c] + a[r - 1][c];
}
}
int maxSum = Integer.MIN_VALUE;
int maxRowStart = -1;
int maxColStart = -1;
int maxRowEnd = -1;
int maxColEnd = -1;
for (int r1 = 1; r1 < n + 1; r1++) { // rows 1-indexed!
for (int r2 = r1; r2 < n + 1; r2++) { // rows 1-indexed!
int[] s1 = new int[n];
for (int c = 0; c < n; c++) {
s1[c] = s[r2][c] - s[r1 - 1][c];
}
int max = 0;
int c1 = 0;
for (int c = 0; c < n; c++) {
max = s1[c] + max;
if (max <= 0) {
max = 0;
c1 = c + 1;
}
if (max > maxSum) {
maxSum = max;
maxRowStart = r1 - 1;
maxColStart = c1;
maxRowEnd = r2 - 1;
maxColEnd = c;
}
}
}
}
}
//maximum number of points that lie on the same straight line: slopes are equal from the same base points
public int maxPointsOnLine(Point[] points) {
if(points == null || points.length == 0) return 0;
HashMap<Double, Integer> result = new HashMap<Double, Integer>();
int max=0;
for(int i=0; i<points.length; i++){
int duplicate = 1;
int vertical = 0;
for(int j=i+1; j<points.length; j++){
//go thru rest point off the current base point
if(points[i].x == points[j].x){
if(points[i].y == points[j].y){
duplicate++;
}else{
vertical++;//case divided by 0
}
}else{//1.0 * cast int to double
double slope = points[j].y == points[i].y ? 0.0 : (1.0 * (points[j].y - points[i].y))/ (points[j].x - points[i].x);
//0 is horizontal
if(result.get(slope) != null){
result.put(slope, result.get(slope) + 1);
}else{
result.put(slope, 2);//at least 2 points each line
}
}
}
for(Integer count: result.values()){
if(count+duplicate > max){//duplicates always included
max = count+duplicate;
}
}
max = Math.max(vertical + duplicate, max);
result.clear();//clear before go next i base point
}
return max;
}
}
|
// Ayman: I found this code online at https://stackoverflow.com/questions/32260445/
// implementing-binary-search-on-an-array-of-strings to help use binary searching.
public class BinaryStringSearch
{
public static int binarySearch(String[] a, String x)
{
int low = 0;
int high = a.length - 1;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
if (a[mid].compareTo(x) < 0)
{
low = mid + 1;
}
else if (a[mid].compareTo(x) > 0)
{
high = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
}
|
/*
* 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 utils;
import java.util.HashMap;
/**
*
* @author jrobledo
*/
public class CommandLineArgsParser {
public static HashMap processCommandLineArgs(String[] args){
HashMap commands = new HashMap();
for(int i = 0; i < args.length; i++){
if(args[i].charAt(0) == '-'){
commands.put(args[i].substring(1), args[i+1]);
}
}
return commands;
}
}
|
package com.paragon.utils.dialogs;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import com.paragon.utils.logger.Logger;
/**
* Created by Rupesh Saxena
*/
public class DVDialog {
private static AlertDialog alertDialog;
private static final String TAG = "DVDialog -> ";
/**
* general image_picker_dialog.
*/
public static void showGeneralDialog(Context context, String title, String message, String buttonTxt, OnDialogButtonsClick listener) {
try {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setCancelable(false);
alertDialog.setMessage(message);
alertDialog.setButton(buttonTxt, (dialog, which) -> {
if (listener != null) {
listener.onPositiveButtonClick();
dialog.cancel();
}
});
alertDialog.show();
} catch (Exception e) {
Logger.e(TAG, e.toString());
}
}
/**
* general image_picker_dialog with negative positive button
*/
public static void showNPButtonDialog(Context context, String title, String message, String pButtonTxt, String nButtonTxt, OnDialogButtonsClick listener) {
try {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton(pButtonTxt, (dialog, id) -> {
if (listener != null)
listener.onPositiveButtonClick();
})
.setNegativeButton(nButtonTxt, (dialog, id) -> {
if (listener != null) {
listener.onNegativeButtonClick();
dialog.cancel();
}
});
alertDialog = builder.create();
alertDialog.show();
} catch (Exception e) {
Logger.e(TAG, e.toString());
}
}
/**
* Showing Alert Dialog with Settings option
* Navigates user to app settings
* NOTE: Keep proper title and message depending on your app
*/
public static void showSettingsDialog(Context context) {
androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(context);
builder.setTitle("Need Permissions");
builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", context.getPackageName(), null);
intent.setData(uri);
((Activity)context).startActivityForResult(intent,121);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
|
/*
* ID: kevin63857
* LANG: JAVA
* TASK: records
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class JON_wormholeDraft
{
static int holes;
static int loops;
static boolean keepGoing = true;
public static void main(String[] args) throws IOException
{
long startTime = System.currentTimeMillis();
// Use BufferedReader rather than RandomAccessFile; it's much faster
/*
* holes=2;
* int[][] pairings2={
* {0,1},};
* //for(int i=0;i<3;i++)fillWithHighest(pairings2,2);
* double[
* System.out.println(Arrays.toString(curSpot));
* System.exit(0);
*/
BufferedReader f = new BufferedReader(new FileReader("wormhole.txt"));
// input file name goes above
// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("wormhole.out")));
// Use StringTokenizer vs. readLine/split -- lots faster
StringTokenizer st = new StringTokenizer(f.readLine());
holes = Integer.parseInt(st.nextToken());
int[][] pairings = new int[holes / 2][2];
int[][] coordinates = new int[holes][2];
for (int i = 0; i < holes; i++)
{
st = new StringTokenizer(f.readLine());
coordinates[i][0] = Integer.parseInt(st.nextToken()) + 1;
coordinates[i][1] = Integer.parseInt(st.nextToken());
}
for (int i = 0; i < holes / 2; i++)
{
pairings[i][0] = 2 * i;
pairings[i][1] = 2 * i + 1;
}
while (keepGoing)
{
check(pairings, coordinates);
repair(pairings);
/*
* for(int i=0;i<holes/2;i++){
* System.out.println(pairings[i][0]+" "+pairings[i][1]);
* }
* System.out.println();
*/
// if(i2==4)
// keepGoing=false;
}
// st = new StringTokenizer(f.readLine());
// st.nextToken();
System.out.println("Time (ms): " + (System.currentTimeMillis() - startTime));
System.out.println(loops);
// out.close();
f.close();
System.exit(0);
}
private static void check(int[][] pairings, int[][] coordinates)
{
double[][] starts = findStarts(coordinates);
for (int i = 0; i < holes; i++)
{
double[] curSpot = Arrays.copyOf(starts[i], 2);
teleport(curSpot, coordinates, pairings);
double[] secondSpot = Arrays.copyOf(curSpot, 2);
while (!noneToRight(curSpot, coordinates))
{
// System.out.println(Arrays.toString(curSpot)+" "+Arrays.toString(secondSpot));
curSpot = teleport(curSpot, coordinates, pairings);
if (curSpot[0] == secondSpot[0] && curSpot[1] == secondSpot[1])
{
loops++;
/*
* for(int i12=0;i12<holes/2;i12++){
* System.out.println((pairings[i12][0]+1)+" "+(pairings[i12][1]+1));
* }
* System.out.println();
*/
return;
}
}
}
}
private static double[] teleport(double[] curSpot, int[][] coordinates, int[][] pairings)
{
int[] lookingFor =
{ (int) (curSpot[0] + .5), (int) curSpot[1] };
int closestX = 2000000000;
int closestIndex = -1;
for (int i = 0; i < holes; i++)
{
if (coordinates[i][1] == lookingFor[1] && coordinates[i][0] - lookingFor[0] >= 0
&& coordinates[i][0] - lookingFor[0] < closestX - lookingFor[0])
{
closestX = coordinates[i][0];
closestIndex = i;
}
}
int other = -1;
for (int i = 0; i < holes / 2; i++)
{
if (pairings[i][0] == closestIndex)
{
other = pairings[i][1];
}
else if (pairings[i][1] == closestIndex)
{
other = pairings[i][0];
}
}
/*
* if(other==-1){
* //System.out.println(Arrays.toString(curSpot));
* for(int i=0;i<holes/2;i++){
* System.out.println(coordinates[i][0]+" "+coordinates[i][1]);
* }
* }
*/
curSpot[0] = coordinates[other][0] + .5;
curSpot[1] = coordinates[other][1];
return curSpot;
}
private static boolean noneToRight(double[] curSpot, int[][] coordinates)
{
for (int[] i : coordinates)
if ((int) curSpot[1] == i[1] && curSpot[0] < i[0])
return false;
return true;
}
private static double[][] findStarts(int[][] coordinates)
{
double[][] starts = new double[holes][2];
for (int i = 0; i < holes; i++)
{
starts[i][0] = coordinates[i][0] - .5;
starts[i][1] = coordinates[i][1];
}
return starts;
}
private static void repair(int[][] pairings)
{
int rowChecking = holes / 2 - 2;
boolean notDone = true;
while (rowChecking >= 0 && notDone)
{
int[] happy = getHappy(pairings, holes / 2 - rowChecking);
if (pairings[rowChecking][1] != happy[happy.length - 1])
{
notDone = false;
}
else
{
rowChecking--;
}
}
if (rowChecking < 0)
{
keepGoing = false;
return;
}
fillWithHighest(pairings, holes / 2 - rowChecking);
}
private static int[] getHappy(int[][] pairings, int levels)
{
int[] happy = new int[2 * levels - 1];
int next = -1;
int bottom = (holes / 2) - levels;
// System.out.println(bottom);
for (int i = bottom + 1; i < holes / 2; i++)
{
// System.out.println(Arrays.toString(happy));
next++;
happy[next++] = pairings[i][0];
happy[next] = pairings[i][1];
}
happy[2 * levels - 2] = pairings[bottom][1];
Arrays.sort(happy);
return happy;
}
private static void fillWithHighest(int[][] pairings, int levels)
{
int[] happy = getHappy(pairings, levels);
int bottom = (holes / 2) - levels;
// System.out.println(Arrays.toString(happy));
ArrayList<Integer> happy2 = new ArrayList<Integer>(0);
for (int i = 0; i < happy.length; i++)
{
happy2.add(happy[i]);
}
pairings[bottom][1] = happy2.remove(find(pairings[bottom][1] + 1, happy2));
for (int i = bottom + 1; i < holes / 2; i++)
{
pairings[i][0] = happy2.remove(0);
pairings[i][1] = happy2.remove(0);
}
}
private static int find(int i2, ArrayList<Integer> happy2)
{
for (int i = 0; i < happy2.size(); i++)
{
if (i2 == happy2.get(i))
return i;
}
// System.out.println(Arrays.toString(happy2.toArray()));
return find(++i2, happy2);
}
private static int fact(int holes)
{
int total = 1;
for (int i = 1; i <= holes; i++)
{
total *= holes;
}
return total;
}
}
|
package io.chark.food.util.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadInputException extends RuntimeException {
public BadInputException(String message, Object... args) {
super(String.format(message, args));
}
}
|
package com.jit.stream09;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> l1 = new ArrayList<Integer>();
l1.add(0);
l1.add(15);
l1.add(10);
l1.add(5);
l1.add(30);
l1.add(25);
l1.add(20);
Integer[] ir = l1.stream().toArray(Integer[]::new);
for (Integer i : ir) {
System.out.println(i);
}
}
}
|
package com.zhicai.byteera.activity.myhome.interfaceview;
import android.app.Activity;
import com.zhicai.byteera.activity.community.dynamic.entity.DynamicEntity;
import java.util.List;
/** Created by bing on 2015/6/29. */
public interface MyDynamicActivityIV {
Activity getContext();
void setData(List<DynamicEntity> dynamicItemList);
}
|
import java.util.Scanner;
public class MethodTest {
public static void main(String[] args){
//创建键盘录入对象
Scanner sc = new Scanner(System.in);
//获取键盘录入数据
System.out.println("请输入第一个数据:");
int a = sc.nextInt();
System.out.println("请输入第二个数据:");
int b = sc.nextInt();
//调用方法
int max = getMax(a, b);
System.out.println("大的值是:"+max);
int c = sc.nextInt();
printMultiplicationTable(c);
}
static int getMax(int a, int b){
return a>b?a:b;
}
static void printMultiplicationTable(int n){
int x = 0;
int y = 0;
for(x=1; x<=n; x++){
for(y=1; y<=x; y++){
System.out.print(x+"*"+y+"="+x*y+"\t");
}
System.out.println();
}
}
}
|
package io.github.yanhu32.xpathkit.converter;
import io.github.yanhu32.xpathkit.utils.Strings;
/**
* @author yh
* @since 2021/4/22
*/
public class BooleanTextConverter implements TextConverter<Boolean> {
@Override
public Boolean apply(String text) {
if (Strings.isEmpty(text)) {
return null;
}
return Boolean.valueOf(text);
}
}
|
package com.qfc.yft.vo;
import com.qfc.yft.utils.JackUtils;
import com.qfc.yft.utils.XMLUtil;
import net.n3.nanoxml.IXMLElement;
public class CimWSReturn {
private int code = 0;
private String message = "";
private String sessionId = "";
private long id = 0L;
private String time = "";
private String version = "";
private String userName = "";
private IXMLElement root = null;
private String faceIndex = "";
private String loginId = "";
private String password = "";
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getLoginId() {
return loginId;
}
public void setLoginId(String loginId) {
this.loginId = loginId;
}
public String getFaceIndex() {
return faceIndex;
}
public void setFaceIndex(String faceIndex) {
this.faceIndex = faceIndex;
}
public CimWSReturn(String xmlStr) throws Exception {
if (xmlStr == null || xmlStr.indexOf("<cim>") < 0) {
code = 9;
message = "登录信息有问题" + xmlStr;
} else {
root = XMLUtil.loadFromStr(xmlStr);
IXMLElement node = XMLUtil.getChildByName(getRoot(), "result");
IXMLElement node2 = XMLUtil.getChildByName(getRoot(), "user");
if (node != null) {
code = Integer.parseInt(node.getAttribute("code", "0"));
message = node.getAttribute("msg", "");
if (code == 0) {
time = node.getAttribute("serverTime", "");
sessionId = node.getAttribute("sessionid", "");
version = node.getAttribute("softVersion", "");
}
if (node2 != null) {
id = Long.parseLong(node2.getAttribute("id", "0"));
userName = node2.getAttribute("nickname", "");
faceIndex = node2.getAttribute("faceIndex", "");
loginId = node2.getAttribute("loginId", "");
}
} else {
code = 99;
}
}
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public String getSessionId() {
return sessionId;
}
public long getId() {
return id;
}
public String getTime() {
return time;
}
public String getVersion() {
return version;
}
public IXMLElement getRoot() {
return root;
}
public boolean isSuccess() {
return (code == 0 || code == 1);
}
public String getUserName() {
if (JackUtils.isBlank(userName)) {
int index = loginId.indexOf("@");
if (index > 0) {
loginId = loginId.substring(0, index);
}
return loginId;
}
else {
return userName;
}
}
}
|
package com.trump.auction.trade.api;
import com.cf.common.util.page.Paging;
import com.cf.common.utils.JsonResult;
import com.trump.auction.trade.model.*;
import java.util.List;
/**
* @author: zhangqingqiang.
* @date: 2018/1/6 0006.
* @Description: 拍品 .
*/
public interface AuctionInfoStubService {
/**
* 按分类查询拍品信息
* @param auctionQuery 根据分类条件查询
* @param pageNum 页码
* @param pageSize 每页条数
* @return Paging<OrderInfoModel> 分页后的拍品信息列表信息
*/
Paging<AuctionInfoModel> queryAuctionInfoByClassify (AuctionInfoQuery auctionQuery, int pageNum, int pageSize);
/**
* 最新成交拍品
* @param auctionQuery 条件查询{status:2}
* @param pageNum 页码
* @param pageSize 每页条数
* @return Paging<OrderInfoModel> 分页后的拍品信息列表信息
*/
Paging<AuctionInfoModel> queryNewestAuctionInfo (AuctionInfoQuery auctionQuery, int pageNum, int pageSize);
/**
* 热拍中
* @param auctionQuery 条件查询 redis中查出的主键id集合
* @return 拍品信息列表信息
*/
List<AuctionInfoModel> queryHotAuctionInfo (AuctionInfoQuery auctionQuery);
/**
*保存拍品信息
* @param auctionInfoModel
* @return {code:xx,msg:xx,data:xx}
*/
JsonResult saveAuctionInfo(AuctionInfoModel auctionInfoModel);
/**
* 根据拍品id和期数查拍卖信息
* @param auctionQuery 拍品id和期数
* @return 拍品名称 当前售价 拍品图片 是否成交
*/
AuctionInfoModel queryAuctionByProductIdAndNo(AuctionInfoQuery auctionQuery);
/**
* 获取拍品信息通过拍品期数ID
* @param auctionId
* @return
*/
AuctionInfoModel getAuctionInfoById(Integer auctionId);
/**
* 通过拍品id获取拍品期数id
* @param auctionProdId
* @return
*/
Integer findAuctionById(Integer auctionProdId);
/**
* 定时生成下一期拍卖信息
*/
JsonResult doAuctionTask(AuctionProductInfoModel prod, AuctionRuleModel rule, AuctionInfoModel auctionInfo,
AuctionProductRecordModel lastRecord);
}
|
package main.java;
import sx.blah.discord.Discord4J;
import sx.blah.discord.api.IListener;
import sx.blah.discord.handle.impl.events.MessageReceivedEvent;
import sx.blah.discord.util.DiscordException;
import sx.blah.discord.util.HTTP429Exception;
import sx.blah.discord.util.MessageBuilder;
import sx.blah.discord.util.MissingPermissionsException;
class CommandListener implements IListener<MessageReceivedEvent> {
/**
* When an event is thrown, if it is a MessageReceivedEvent, it will trigger this method
* @param event the thrown event
*/
@Override
public void handle(MessageReceivedEvent event) {
String commandDiscriminator = "-";
if (event.getMessage().getContent().startsWith(commandDiscriminator)) {// If the content of the message starts with the command discriminator
String commandName = event.getMessage().getContent().substring(1); // Remove the first character
if (commandName.contains(" ")) { // If there are spaces in the command
commandName = commandName.substring(0, commandName.indexOf(" ")); // Strip the arguments
}
ICommand command = CommandRegistry.getCommandFromAlias(commandName); // Create a new command instance from the inputted value
if (command != null) { // If the command exists
String[] arguments = new String[]{};
if (event.getMessage().getContent().contains(" ")) { // If the content of the messages contains spaces
arguments = event.getMessage().getContent().substring(event.getMessage().getContent().indexOf(" ") + 1).split("\\s+"); // Get the arguments from the command
}
if (command.deletesMessage()) { // If the command called's deletesMessage bool is true
try {
event.getMessage().delete(); // Delete the message that triggered the command
} catch (HTTP429Exception | DiscordException | MissingPermissionsException e) {
e.printStackTrace();
}
}
System.out.println("Command executed: " + command.getName()); // Print to the console the name of the deleted message
command.handle(event.getMessage(), arguments); // Call the command, and pass the message that called it, and the stripped arguments
} else { // If the command doesn't exist
try {
new MessageBuilder(GeneralCommands.client).withChannel(event.getMessage().getChannel()).withContent("Command " + commandName + " not found.").build(); // Send a message to the channel to inform the user that it doesn't exist
} catch (HTTP429Exception | MissingPermissionsException | DiscordException e) {
Discord4J.LOGGER.error("Command Not Found message error: ", e);
}
}
}
}
}
|
/*
* 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 phatnh.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import phatnh.filter.DispatcherFilter;
import phatnh.user.UserDAO;
import phatnh.user.UserDTO;
/**
*
* @author nguyenhongphat0
*/
@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url = DispatcherFilter.loginPage;
try {
String username = request.getParameter("userId");
String passwordText = request.getParameter("password");
int password = Integer.parseInt(passwordText);
UserDAO dao = new UserDAO();
UserDTO dto = dao.login(username, password);
if (dto == null) {
request.setAttribute("message", "Incorrect username or password");
} else {
HttpSession session = request.getSession(true);
session.setAttribute("USER", dto);
switch (dto.getRole()) {
case 0:
url = DispatcherFilter.userPage;
break;
case 1:
url = DispatcherFilter.managerPage;
break;
case 2:
url = DispatcherFilter.staffPage;
}
response.sendRedirect(url);
return;
}
} catch (NamingException ex) {
log("LoginServlet - NamingException: " + ex.getMessage());
} catch (SQLException ex) {
log("LoginServlet - SQLException: " + ex.getMessage());
} catch (NumberFormatException ex) {
request.setAttribute("message", "Password is a number");
}
request.getRequestDispatcher(url).forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.aipiao.bkpkold.adapter.newsadapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.aipiao.bkpkold.R;
/**
* Created by Administrator on 2018/3/11.
*/
public class NHomeAdapter extends BaseAdapter {
// private int [] icons={R.mipmap.lot_logo_ssq,
// R.mipmap.lot_logo_11choose5,
// R.mipmap.lot_logo_dlt,
// R.mipmap.lot_logo_3d,R.mipmap.lot_logo_qlc,R.mipmap.lot_logo_qxc,R.mipmap.lot_logo_sfc9,R.mipmap.lot_logo_k3};
// private String [] titles={"双色球","11选5","大乐透","福彩3D","七乐彩","七星彩","任选9","快三"};
//
private int[] icons = {R.mipmap.lot_logo_ssq, R.mipmap.lot_logo_dlt, R.mipmap.lot_logo_3d,
R.mipmap.lot_logo_pl3,
R.mipmap.lot_logo_pl5, R.mipmap.lot_logo_qxc, R.mipmap.lot_logo_qlc,R.mipmap.lot_logo_11choose5};
private String[] titles = {"双色球", "大乐透", "福彩3D", "排列3", "排列5", "七乐彩", "七星彩","11选5"};
// @Override
public int getCount() {
return icons.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = View.inflate(parent.getContext(), R.layout.new_item_home_adapter, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.homeIconImageView.setBackgroundResource(icons[position]);
holder.homeTitleTextView.setText(titles[position]);
return convertView;
}
class ViewHolder {
private ImageView homeIconImageView;
private TextView homeTitleTextView;
ViewHolder(View v) {
homeIconImageView = (ImageView) v.findViewById(R.id.homeIconImageView);
homeTitleTextView = (TextView) v.findViewById(R.id.homeTitleTextView);
}
}
}
|
/*
* Copyright 2016 Grzegorz Skorupa <g.skorupa at gmail.com>.
*
* 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.cricketmsf;
import com.cedarsoftware.util.io.JsonReader;
import com.cedarsoftware.util.io.JsonWriter;
import org.cricketmsf.config.ConfigSet;
import org.cricketmsf.config.Configuration;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
/**
* Runner class is used when running JAR distribution. The class parses the
* command line arguments, reads config from cricket.json, then creates and runs
* the service instance according to the configuration.
*
* @author greg
*/
public class Runner {
public static Kernel getService(String[] args){
long runAt = System.currentTimeMillis();
final Kernel service;
final ConfigSet configSet;
Runner runner = new Runner();
ArgumentParser arguments = new ArgumentParser(args);
if (arguments.isProblem()) {
if (arguments.containsKey("error")) {
System.out.println(arguments.get("error"));
}
System.out.println(runner.getHelp());
System.exit(-1);
}
configSet = runner.readConfig(arguments);
Class serviceClass = null;
String serviceId;
String serviceName = null;
Configuration configuration = null;
if (arguments.containsKey("service")) {
// if service name provided as command line option
serviceId = (String) arguments.get("service");
} else {
// otherwise get first configured service
serviceId = configSet.getDefault().getId();
}
configuration = configSet.getConfigurationById(serviceId);
// if serviceName isn't configured print error and exit
if (configuration == null) {
System.out.println("Configuration not found for id=" + serviceId);
System.exit(-1);
} else if (arguments.containsKey("lift")) {
serviceName = (String) arguments.get("lift");
System.out.println("LIFT service " + serviceName);
} else {
serviceName = configuration.getService();
}
if (arguments.containsKey("help")) {
System.out.println(runner.getHelp(serviceName));
System.exit(0);
}
if (arguments.containsKey("print")) {
System.out.println(runner.getConfigAsString(configSet));
System.exit(0);
}
try {
serviceClass = Class.forName(serviceName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("CRICKET RUNNER");
try {
service = (Kernel) Kernel.getInstanceWithProperties(serviceClass, configuration);
service.configSet = configSet;
service.liftMode = arguments.containsKey("lift");
if (arguments.containsKey("run")) {
service.setStartedAt(runAt);
service.start();
return service;
} else {
//service.setScheduler(new Scheduler());
//System.out.println("Executing runOnce method");
service.runOnce();
service.shutdown();
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
getService(args);
/*
long runAt = System.currentTimeMillis();
final Kernel service;
final ConfigSet configSet;
Runner runner = new Runner();
ArgumentParser arguments = new ArgumentParser(args);
if (arguments.isProblem()) {
if (arguments.containsKey("error")) {
System.out.println(arguments.get("error"));
}
System.out.println(runner.getHelp());
System.exit(-1);
}
configSet = runner.readConfig(arguments);
Class serviceClass = null;
String serviceId;
String serviceName = null;
Configuration configuration = null;
if (arguments.containsKey("service")) {
// if service name provided as command line option
serviceId = (String) arguments.get("service");
} else {
// otherwise get first configured service
serviceId = configSet.getDefault().getId();
}
configuration = configSet.getConfigurationById(serviceId);
// if serviceName isn't configured print error and exit
if (configuration == null) {
System.out.println("Configuration not found for id=" + serviceId);
System.exit(-1);
} else if (arguments.containsKey("lift")) {
serviceName = (String) arguments.get("lift");
System.out.println("LIFT service " + serviceName);
} else {
serviceName = configuration.getService();
}
if (arguments.containsKey("help")) {
System.out.println(runner.getHelp(serviceName));
System.exit(0);
}
if (arguments.containsKey("print")) {
System.out.println(runner.getConfigAsString(configSet));
System.exit(0);
}
try {
serviceClass = Class.forName(serviceName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("CRICKET RUNNER");
try {
service = (Kernel) Kernel.getInstanceWithProperties(serviceClass, configuration);
service.configSet = configSet;
service.liftMode = arguments.containsKey("lift");
if (arguments.containsKey("run")) {
service.setStartedAt(runAt);
service.start();
} else {
//service.setScheduler(new Scheduler());
//System.out.println("Executing runOnce method");
service.runOnce();
service.shutdown();
}
} catch (Exception e) {
e.printStackTrace();
}
*/
}
/**
* Returns content of the default help file ("help.txt")
*
* @return help content
*/
public String getHelp() {
return getHelp(null);
}
/**
* Returns content of the custom service help file (serviceName+"-help.txt")
* Example: if your service class name is
* org.cricketmsf.services.EchoService then help file is
* EchoService-help.txt
*
* @param serviceName the service class simple name
* @return
*/
public String getHelp(String serviceName) {
String content = "Help file not found";
String helpFileName = "/help.txt";
if (null != serviceName) {
helpFileName = "/" + serviceName.substring(serviceName.lastIndexOf(".") + 1) + "-help.txt";
}
try {
content = readHelpFile(helpFileName);
} catch (Exception e) {
try {
content = readHelpFile("/help.txt");
} catch (Exception x) {
e.printStackTrace();
}
}
return content;
}
private String readHelpFile(String fileName) throws Exception {
String content = null;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(fileName)))) {
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append("\r\n");
}
content = out.toString();
}
return content;
}
public ConfigSet readConfig(ArgumentParser arguments) {
ConfigSet configSet = null;
if (arguments.containsKey("config")) {
//Properties props;
Map args = new HashMap();
args.put(JsonReader.USE_MAPS, false);
Map types = new HashMap();
types.put("java.utils.HashMap", "adapters");
types.put("java.utils.HashMap", "properties");
args.put(JsonReader.TYPE_NAME_MAP, types);
try {
InputStream propertyFile = new FileInputStream(new File((String) arguments.get("config")));
String inputStreamString = new Scanner(propertyFile, "UTF-8").useDelimiter("\\A").next();
configSet = (ConfigSet) JsonReader.jsonToJava(inputStreamString, args);
} catch (Exception e) {
e.printStackTrace();
//LOGGER.log(Level.SEVERE, "Adapters initialization error. Configuration: {0}", path);
}
} else {
String propsName = "cricket.json";
InputStream propertyFile = getClass().getClassLoader().getResourceAsStream(propsName);
String inputStreamString = new Scanner(propertyFile, "UTF-8").useDelimiter("\\A").next();
Map args = new HashMap();
args.put(JsonReader.USE_MAPS, false);
Map types = new HashMap();
types.put("java.utils.HashMap", "adapters");
types.put("java.utils.HashMap", "properties");
args.put(JsonReader.TYPE_NAME_MAP, types);
configSet = (ConfigSet) JsonReader.jsonToJava(inputStreamString, args);
}
// read Kernel version
Properties prop = new Properties();
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("cricket.properties")) {
if (inputStream != null) {
prop.load(inputStream);
}
} catch (IOException e) {
}
configSet.setKernelVersion(prop.getProperty("version", "unknown"));
// force property changes based on command line --force param
if (arguments.containsKey("force")) {
ArrayList<String> forcedProps = (ArrayList) arguments.get("force");
for (int i = 0; i < forcedProps.size(); i++) {
configSet.forceProperty(forcedProps.get(i));
}
}
return configSet;
}
public String getConfigAsString(ConfigSet c) {
Map nameBlackList = new HashMap();
ArrayList blackList = new ArrayList();
blackList.add("host");
blackList.add("port");
blackList.add("threads");
blackList.add("filter");
blackList.add("cors");
nameBlackList.put(Configuration.class, blackList);
Map args = new HashMap();
args.put(JsonWriter.PRETTY_PRINT, true);
//args.put(JsonWriter., args)
return JsonWriter.objectToJson(c, args);
}
}
|
/*
* Copyright 2014 Melusyn SAS
*
* Melusyn 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 com.melusyn.sendgrid;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sendgrid.SendGrid;
import com.sendgrid.SendGrid.Email;
import com.sendgrid.SendGrid.Response;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.core.logging.impl.LoggerFactory;
import org.vertx.java.platform.Verticle;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@SuppressWarnings("unused")
public class SendGridMod extends Verticle {
private SendGrid sendgrid;
private static ObjectMapper jsonMapper = new ObjectMapper();
static private final String MELUSYN_MAIL_ID = "mailuuid";
private Logger logger = LoggerFactory.getLogger(getClass());
private Map<String, Integer> templateSuppressionGroup = new HashMap<>();
private String hostname = "unknown";
@Override
public void start() {
super.start();
EventBus eb = vertx.eventBus();
String address = getOptionalStringConfig("address", "melusyn.sendgrid");
String sendgridUsername = getMandatoryStringConfig("sendgrid_username");
String sendgridPassword = getMandatoryStringConfig("sendgrid_password");
JsonObject suppressionJson = container.config().getObject("suppressions", new JsonObject());
for (String templateId : suppressionJson.getFieldNames()) {
templateSuppressionGroup.put(templateId, suppressionJson.getInteger(templateId));
}
try {
InetAddress ip = InetAddress.getLocalHost();
hostname = ip.getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
sendgrid = new SendGrid(sendgridUsername, sendgridPassword);
eb.registerHandler(address + ".send", this::sendEmail);
eb.registerHandler(address + ".sendv2", this::sendEmailV2);
}
public void sendEmail(Message<JsonObject> message) {
logger.debug("Unmarshalling SendGridMod request : " + message.body().encodePrettily());
SendGridRequest sendGridRequest;
try {
sendGridRequest = jsonMapper.readValue(message.body().encode(), SendGridRequest.class);
} catch (Exception e) {
logger.error(e, e);
message.fail(500, e.getMessage());
return;
}
Email email = new Email();
if (sendGridRequest.getTemplateId() != null) {
email.addFilter("templates", "template_id", sendGridRequest.getTemplateId());
}
email.addTo(sendGridRequest.getTos().toArray(new String[sendGridRequest.getTos().size()]));
email.addToName(sendGridRequest.getToNames().toArray(new String[sendGridRequest.getToNames().size()]));
email.setFrom(sendGridRequest.getFrom());
email.setFromName(sendGridRequest.getFromName());
//This will replace <%subject%> tag in your template (if using a template)
email.setSubject(sendGridRequest.getSubject());
if (sendGridRequest.getBodyAsHtml()) {
email.setHtml(sendGridRequest.getBody());
}
email.setText(sendGridRequest.getBody());
sendGridRequest.getSubstitutions().forEach((key, value) ->
email.addSubstitution(key, value.toArray(new String[value.size()]))
);
int suppressionGroupId = templateSuppressionGroup.getOrDefault(sendGridRequest.getTemplateId(), 0);
if (suppressionGroupId != 0) {
email.setASMGroupId(suppressionGroupId);
}
sendGridRequest.getContext().forEach(email::addUniqueArg);
String uuid = UUID.randomUUID().toString();
email.addUniqueArg(MELUSYN_MAIL_ID, uuid);
try {
Response response = sendgrid.send(email);
if (response.getCode() != 200) {
logger.debug("SendGrid failed and responded with : " + response.getCode() + " - " + response.getMessage());
message.fail(response.getCode(), response.getMessage());
return;
}
JsonObject jResponse = SendGridResponse.instance()
.code(response.getCode())
.message(response.getMessage())
.status(response.getStatus())
.toJson();
logger.debug("SendGrid successfully responded with : " + jResponse.encode());
message.reply(jResponse);
} catch (Exception e) {
logger.error(e, e);
message.fail(500, e.getMessage());
}
}
public void sendEmailV2(Message<JsonObject> message) {
SendGridRequestV2 request;
try {
request = jsonMapper.readValue(message.body().encode(), SendGridRequestV2.class);
} catch (IOException e) {
logger.error(e);
message.fail(400, e.getMessage());
return;
}
if (request.getRecipients() == null || request.getRecipients().isEmpty()) {
String errorMessage = "Your request has no recipient. It must at least have one recipient";
logger.error(errorMessage);
message.fail(400, errorMessage);
return;
}
Email email = new Email();
if (request.getTemplateId() != null) {
email.addFilter("templates", "template_id", request.getTemplateId());
}
email.setFrom(request.getFrom());
email.setFromName(request.getFromName());
email.setSubject(request.getSubject());
if (request.getCcs() != null) {
request.getCcs().forEach(recipient -> email.addCc(recipient.getEmail()));
}
if (request.getBccs() != null) {
request.getBccs().forEach(recipient -> email.addBcc(recipient.getEmail()));
}
if (request.getReplyTo() != null) {
email.setReplyTo(request.getReplyTo());
}
if (request.getSections() != null) {
request.getSections().forEach(email::addSection);
}
if (request.getBodyAsHtml()) {
email.setHtml(request.getBody());
}
email.setText(request.getBody());
Map<String, List<String>> substitutions = new HashMap<>();
request.getRecipients().forEach(recipient -> {
email.addTo(recipient.getEmail(), recipient.getFullName());
if (recipient.getSubstitutions() != null) {
recipient.getSubstitutions().forEach((name, value) -> {
List<String> substitution = substitutions.get(name);
if (substitution == null) {
substitution = new ArrayList<>();
substitutions.put(name, substitution);
}
substitution.add(value);
});
}
});
if (request.getAttachments() != null) {
request.getAttachments().forEach((name, attachment) -> {
try {
email.addAttachment(name, new ByteArrayInputStream(attachment));
} catch (IOException ignored) {
logger.error("Michel owes a beer to Hugo.", ignored);
}
});
}
substitutions.forEach((key, list) ->
email.addSubstitution(key, list.toArray(new String[list.size()]))
);
int suppressionGroupId = templateSuppressionGroup.getOrDefault(request.getTemplateId(), 0);
if (suppressionGroupId != 0) {
email.setASMGroupId(suppressionGroupId);
}
request.getContext().forEach(email::addUniqueArg);
String uuid = UUID.randomUUID().toString();
email.addUniqueArg(MELUSYN_MAIL_ID, uuid);
email.addUniqueArg("HOSTNAME", hostname);
try {
Response response = sendgrid.send(email);
if (response.getCode() != 200) {
JsonObject emailJson = new JsonObject(jsonMapper.writeValueAsString(request));
logger.error("SendGrid failed and responded with : " + response.getCode() + " - " + response.getMessage() + " with email:" + emailJson.encodePrettily());
message.fail(500, response.getMessage());
logger.warn(message.body().encodePrettily());
return;
}
JsonObject jResponse = SendGridResponse.instance()
.code(response.getCode())
.message(response.getMessage())
.status(response.getStatus())
.toJson();
logger.debug("SendGrid successfully responded with : " + jResponse.encode());
message.reply(jResponse);
} catch (Exception e) {
logger.error(e, e);
message.fail(500, e.getMessage());
}
}
protected String getMandatoryStringConfig(String fieldName) {
String s = container.config().getString(fieldName);
if (s == null) {
throw new IllegalArgumentException(fieldName + " must be specified in config.");
}
return s;
}
protected String getOptionalStringConfig(String fieldName, String defaultValue) {
String s = container.config().getString(fieldName);
if (s == null) {
return defaultValue;
}
return s;
}
@Override
public void stop() {
super.stop();
}
}
|
package Beans;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class ErrorBean implements Serializable {
public ErrorBean() {
}
private Set<String> errors = new HashSet<>();
public Set<String> getErrors() {
return errors;
}
public void setErrors(Set<String> errors) {
this.errors = errors;
}
public void addError(String error){
errors.add(error);
}
public void cleanErrors(){
errors.clear();
}
}
|
package control;
import java.nio.file.Path;
import java.util.List;
import database.DatabaseConnection;
import database.Establish;
import schemaComparison.loadFile;
public class Main {
public static String filePath = "H:\\Opon edX\\hkustx-2014-09-28\\User";
public static String fieldPath = "H:\\Opon edX\\hkustx-2014-09-28\\User\\schema_list\\auth_user.txt";
public static String tableName = "auth_userprofile";
// public static String className = "AuthUserprofile";
public static String fieldName = "AUTH_USERPROFILE";
public static String dbuser = "testroot";
public static String dbpw = "testroot";
public static String dbpath = "jdbc:mysql://localhost:3306/bitnami_edx";
//Also need to change connection
public static void main(String[] args) {
// TODO Auto-generated method stub
// Establish.go();
// DatabaseConnection.connect(dbpath, dbuser, dbpw);
// List<Path> paths = loadFile.loadFileList(filePath, tableName);
// loadFile.getAllValuesAndAdd(paths);
loadFile.divideLargeFile("F:\\Opon edX\\hkustx-2014-09-28\\Studentmodule\\HKUSTx-COMP102x-2T2014-courseware_studentmodule-prod-analytics.sql", "F:\\Opon edX\\hkustx-2014-09-28\\Studentmodule\\temp");
System.out.println("=======================Finished=====================");
}
}
|
package labrom.litlbro.browser;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import labrom.litlbro.L;
import android.util.Log;
import android.webkit.WebSettings;
public class BrowserSettings {
static class Signature {
final String methodName;
Method method;
final Object[] args;
Signature(String methodName, Object... args) {
this.methodName = methodName;
this.args = args;
}
void bind() {
try {
method = WebSettings.class.getMethod(methodName, boolean.class);
} catch(Exception e) {
Log.w(L.TAG, "Method WebSettings." + methodName + " not available");
}
if(args != null)
for(int i = 0; i < args.length; i ++) {
Object arg = args[i];
if(arg instanceof ReflectLateArg) {
((ReflectLateArg)arg).bind();
args[i] = ((ReflectLateArg)arg).getValue();
}
}
}
void invoke(WebSettings target) {
if(method == null)
return;
try {
method.invoke(target, args);
} catch(Exception e) {
Log.w(L.TAG, "Unable to set " + method.getName() + " - " + e.getClass().getSimpleName() + " : " + e.getMessage());
}
}
}
private static boolean reflectDone;
private static final Collection<Signature> availableReflectMethods = new ArrayList<Signature>();
private static final Signature[] methods = {
new Signature("setDomStorageEnabled", Boolean.TRUE),
new Signature("setAppCacheEnabled", Boolean.TRUE),
new Signature("setDatabaseEnabled", Boolean.TRUE),
new Signature("setAllowFileAccess", Boolean.TRUE),
new Signature("setLoadWithOverviewMode", Boolean.TRUE),
new Signature("setDisplayZoomControls", Boolean.FALSE),
new Signature("setPluginState", new PluginStateOnArg())
};
public static final void configure(WebSettings settings) {
settings.setBuiltInZoomControls(true);
settings.setUseWideViewPort(true);
settings.setSupportZoom(true);
settings.setLightTouchEnabled(true);
settings.setLoadsImagesAutomatically(true);
settings.setPluginsEnabled(true); // Deprecated but using reflection to set setPluginState(PluginState) is a pain
settings.setSupportMultipleWindows(false);
settings.setJavaScriptCanOpenWindowsAutomatically(false);
initReflect();
for(Signature s : availableReflectMethods) {
s.invoke(settings);
}
}
private static final void initReflect() {
if(reflectDone)
return;
availableReflectMethods.clear();
for(Signature s : methods) {
s.bind();
}
reflectDone = true;
}
}
|
package com.qa.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.swing.text.html.parser.Entity;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import com.qa.Data.Headers;
public class RestClient {
Headers headerobj = new Headers();
// 1. GET Method without Headers:
public CloseableHttpResponse get(String url)
throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url); // http get request
CloseableHttpResponse closebaleHttpResponse = httpClient
.execute(httpget); // hit the GET URL
return closebaleHttpResponse;
// 1. GET Method with Headers:
}
public CloseableHttpResponse get(String Url, HashMap<String, String> header)
throws ClientProtocolException, IOException {
CloseableHttpClient closableHttp = HttpClients.createDefault();// Create//
// the//
// client
HttpGet httpget = new HttpGet(Url);// Get the URL
httpget.addHeader(headerobj.getKey(), headerobj.getValue());
CloseableHttpResponse closebaleHttpResponse = closableHttp
.execute(httpget);
return closebaleHttpResponse;
}
// Post Method
public CloseableHttpResponse post(String uri, String entityString,
HashMap<String, String> headermap) throws ClientProtocolException,
IOException {
CloseableHttpClient httpClosable = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);// For URL
httpPost.setEntity(new StringEntity(entityString));
httpPost.addHeader(headerobj.getKey(), headerobj.getValue());
CloseableHttpResponse closeableHttpResponse = httpClosable
.execute(httpPost);
return closeableHttpResponse;
}
// Put Method
public CloseableHttpResponse put(String url, String entityString,
HashMap<String, String> headerMap) throws ClientProtocolException,
IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut putobj = new HttpPut(url);
putobj.addHeader(headerobj.getKey(), headerobj.getValue());
putobj.setEntity(new StringEntity(entityString));
CloseableHttpResponse closeableHttpResponse = httpClient
.execute(putobj);
return closeableHttpResponse;
}
}
|
package me.leaver.bloger.app.mvp.presenter;
import me.leaver.bloger.app.mvp.model.fundamental.Post;
/**
* Created by zhiyuan.lzy on 2016/3/20.
*/
//Model ->Presenter
public interface RequiredPresenterOps {
public void onFetchPostCompleted(Post post);
public void onLoadAllCompleted(String content);
}
|
package com.jit.predicate06;
/*Remove null values and Empty String from the given list*/
import java.util.ArrayList;
import java.util.function.Predicate;
public class Test{
public static void main(String[] args) {
String[] names = {"Durga","null",null,"Katrina","Kareena"};
Predicate<String> p = s -> s != null && s.length() != 0;
ArrayList<String> list = new ArrayList<>();
for(String s : names) {
if(p.test(s))
list.add(s);
}
System.out.println("The List of valid Names : ");
System.out.println(list);
}
}
|
package com.example.submissionempat.ui.main;
import android.content.Intent;
import android.provider.Settings;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.example.submissionempat.R;
import com.example.submissionempat.ui.main.fragment.all.ListAllFragment;
import com.example.submissionempat.ui.main.fragment.favorite.ListFavoriteFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener{
private BottomNavigationView bottomNavigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new ListAllFragment());
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_main);
bottomNavigationView.setOnNavigationItemSelectedListener(this);
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fl_container, fragment)
.commit();
return true;
}
return false;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()){
case R.id.home_menu:
fragment = new ListAllFragment();
break;
case R.id.favorite_menu:
fragment = new ListFavoriteFragment();
break;
}
return loadFragment(fragment);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_change_settings){
Intent setting = new Intent(Settings.ACTION_LOCALE_SETTINGS);
startActivity(setting);
}
return super.onOptionsItemSelected(item);
}
}
|
/**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.view;
import java.util.Comparator;
import java.util.List;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.cell.core.client.SimpleSafeHtmlCell;
import com.sencha.gxt.cell.core.client.form.ComboBoxCell.TriggerAction;
import com.sencha.gxt.core.client.IdentityValueProvider;
import com.sencha.gxt.core.client.Style.SelectionMode;
import com.sencha.gxt.core.client.XTemplates;
import com.sencha.gxt.core.client.XTemplates.Formatter;
import com.sencha.gxt.core.client.XTemplates.FormatterFactories;
import com.sencha.gxt.core.client.XTemplates.FormatterFactory;
import com.sencha.gxt.core.client.resources.CommonStyles;
import com.sencha.gxt.core.client.util.Format;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.core.client.util.Rectangle;
import com.sencha.gxt.data.client.loader.RpcProxy;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.SortDir;
import com.sencha.gxt.data.shared.Store;
import com.sencha.gxt.data.shared.Store.StoreSortInfo;
import com.sencha.gxt.data.shared.StringLabelProvider;
import com.sencha.gxt.data.shared.loader.ListStoreBinding;
import com.sencha.gxt.data.shared.loader.Loader;
import com.sencha.gxt.examples.resources.client.ExampleService;
import com.sencha.gxt.examples.resources.client.ExampleServiceAsync;
import com.sencha.gxt.examples.resources.client.model.Photo;
import com.sencha.gxt.explorer.client.app.ui.ExampleContainer;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.theme.base.client.listview.ListViewCustomAppearance;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.Dialog;
import com.sencha.gxt.widget.core.client.Dialog.PredefinedButton;
import com.sencha.gxt.widget.core.client.ListView;
import com.sencha.gxt.widget.core.client.button.ButtonBar;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer.BorderLayoutData;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.event.DialogHideEvent;
import com.sencha.gxt.widget.core.client.event.DialogHideEvent.DialogHideHandler;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.form.SimpleComboBox;
import com.sencha.gxt.widget.core.client.form.StoreFilterField;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent;
import com.sencha.gxt.widget.core.client.selection.SelectionChangedEvent.SelectionChangedHandler;
import com.sencha.gxt.widget.core.client.toolbar.LabelToolItem;
import com.sencha.gxt.widget.core.client.toolbar.SeparatorToolItem;
import com.sencha.gxt.widget.core.client.toolbar.ToolBar;
@Detail(
name = "Advanced List View",
category = "Templates & Lists",
icon = "advancedlistview",
classes = Photo.class,
files = {"ListViewExample.gss"},
minHeight = AdvancedListViewExample.MIN_HEIGHT,
minWidth = AdvancedListViewExample.MIN_WIDTH
)
public class AdvancedListViewExample implements IsWidget, EntryPoint {
interface DetailRenderer extends XTemplates {
@XTemplate(source = "AdvancedListViewDetail.html")
SafeHtml render(Photo photo, Style style);
}
@FormatterFactories(@FormatterFactory(factory = ShortenFactory.class, name = "shorten"))
interface Renderer extends XTemplates {
@XTemplate(source = "ListViewExample.html")
SafeHtml renderItem(Photo photo, Style style);
}
interface Resources extends ClientBundle {
@Source("ListViewExample.gss")
Style css();
}
static class Shorten implements Formatter<String> {
private int length;
public Shorten(int length) {
this.length = length;
}
@Override
public String format(String data) {
return Format.ellipse(data, length);
}
}
static class ShortenFactory {
public static Shorten getFormat(int length) {
return new Shorten(length);
}
}
interface Style extends CssResource {
String courtesy();
String detail();
String detailInfo();
String over();
String select();
String thumb();
String thumbWrap();
}
protected static final int MIN_HEIGHT = 200;
protected static final int MIN_WIDTH = 200;
private Dialog chooser;
private ContentPanel details;
private Image image;
private DetailRenderer renderer;
private Style style;
private SimpleComboBox<String> comboSort;
private ListStore<Photo> store;
private ListView<Photo, Photo> view;
private VerticalLayoutContainer panel;
@Override
public Widget asWidget() {
if (panel == null) {
final Resources resources = GWT.create(Resources.class);
resources.css().ensureInjected();
style = resources.css();
renderer = GWT.create(DetailRenderer.class);
final ExampleServiceAsync rpcService = GWT.create(ExampleService.class);
RpcProxy<Object, List<Photo>> proxy = new RpcProxy<Object, List<Photo>>() {
@Override
public void load(Object loadConfig, AsyncCallback<List<Photo>> callback) {
rpcService.getPhotos(callback);
}
};
ModelKeyProvider<Photo> keyProvider = new ModelKeyProvider<Photo>() {
@Override
public String getKey(Photo item) {
return item.getName();
}
};
store = new ListStore<Photo>(keyProvider);
store.addSortInfo(new StoreSortInfo<Photo>(new Comparator<Photo>() {
@Override
public int compare(Photo o1, Photo o2) {
String v = comboSort.getCurrentValue();
if (v.equals("Name")) {
return o1.getName().compareToIgnoreCase(o2.getName());
} else if (v.equals("File Size")) {
return o1.getSize() < o2.getSize() ? -1 : 1;
} else {
return o1.getDate().compareTo(o2.getDate());
}
}
}, SortDir.ASC));
Loader<Object, List<Photo>> loader = new Loader<Object, List<Photo>>(proxy);
loader.addLoadHandler(new ListStoreBinding<Object, Photo, List<Photo>>(store));
loader.load();
StoreFilterField<Photo> filterField = new StoreFilterField<Photo>() {
@Override
protected boolean doSelect(Store<Photo> store, Photo parent, Photo item, String filter) {
String name = item.getName().toLowerCase();
if (name.indexOf(filter.toLowerCase()) != -1) {
return true;
}
return false;
}
@Override
protected void onFilter() {
super.onFilter();
view.getSelectionModel().select(0, false);
}
};
filterField.setWidth(100);
filterField.bind(store);
ToolBar toolbar = new ToolBar();
toolbar.setEnableOverflow(false);
toolbar.add(new LabelToolItem("Filter:"));
toolbar.add(filterField);
toolbar.add(new SeparatorToolItem());
toolbar.add(new LabelToolItem("Sort By:"));
comboSort = new SimpleComboBox<String>(new StringLabelProvider<String>());
comboSort.setTriggerAction(TriggerAction.ALL);
comboSort.setEditable(false);
comboSort.setForceSelection(true);
comboSort.setWidth(120);
comboSort.add("Name");
comboSort.add("File Size");
comboSort.add("Last Modified");
comboSort.setValue("Name");
comboSort.addSelectionHandler(new SelectionHandler<String>() {
@Override
public void onSelection(SelectionEvent<String> event) {
store.applySort(false);
}
});
toolbar.add(comboSort);
final Renderer renderer = GWT.create(Renderer.class);
ListViewCustomAppearance<Photo> appearance = new ListViewCustomAppearance<Photo>("." + style.thumbWrap(),
style.over(), style.select()) {
@Override
public void renderEnd(SafeHtmlBuilder builder) {
String markup = new StringBuilder("<div class=\"").append(CommonStyles.get().clear()).append("\"></div>").toString();
builder.appendHtmlConstant(markup);
}
@Override
public void renderItem(SafeHtmlBuilder builder, SafeHtml content) {
builder.appendHtmlConstant("<div class='" + style.thumbWrap() + "' style='border: 1px solid white'>");
builder.append(content);
builder.appendHtmlConstant("</div>");
}
};
view = new ListView<Photo, Photo>(store, new IdentityValueProvider<Photo>() {
@Override
public void setValue(Photo object, Photo value) {
}
}, appearance);
view.setCell(new SimpleSafeHtmlCell<Photo>(new AbstractSafeHtmlRenderer<Photo>() {
@Override
public SafeHtml render(Photo object) {
return renderer.renderItem(object, style);
}
}));
view.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
view.getSelectionModel().addSelectionChangedHandler(new SelectionChangedHandler<Photo>() {
@Override
public void onSelectionChanged(SelectionChangedEvent<Photo> event) {
AdvancedListViewExample.this.onSelectionChange(event);
}
});
view.setBorders(false);
VerticalLayoutContainer main = new VerticalLayoutContainer();
main.setBorders(true);
main.add(toolbar, new VerticalLayoutData(1, -1));
main.add(view, new VerticalLayoutData(1, 1));
details = new ContentPanel();
details.setHeaderVisible(false);
details.setBodyBorder(true);
details.getElement().getStyle().setBackgroundColor("white");
BorderLayoutData eastData = new BorderLayoutData(250);
eastData.setSplit(true);
BorderLayoutData centerData = new BorderLayoutData();
centerData.setMargins(new Margins(0, 5, 0, 0));
BorderLayoutContainer con = new BorderLayoutContainer();
con.setCenterWidget(main, centerData);
con.setEastWidget(details, eastData);
chooser = new Dialog();
chooser.setPixelSize(640, 480);
chooser.setResizable(false);
chooser.setId("img-chooser-dlg");
chooser.setHeading("Advanced List View");
chooser.setModal(true);
chooser.setBodyBorder(false);
chooser.setPredefinedButtons(PredefinedButton.OK, PredefinedButton.CANCEL);
chooser.setHideOnButtonClick(true);
chooser.addDialogHideHandler(new DialogHideHandler() {
@Override
public void onDialogHide(DialogHideEvent event) {
Photo photo = view.getSelectionModel().getSelectedItem();
if (photo != null) {
if (event.getHideButton() == PredefinedButton.OK) {
image.setUrl(photo.getPath());
image.setVisible(true);
panel.forceLayout();
}
}
}
});
chooser.add(con);
TextButton buttonChoose = new TextButton("Choose");
buttonChoose.addSelectHandler(new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
// show the chooser
chooser.show();
// select the first item
view.getSelectionModel().select(0, false);
// constrain the chooser to the viewport (for small mobile screen sizes)
Rectangle bounds = chooser.getElement().getBounds();
Rectangle adjusted = chooser.getElement().adjustForConstraints(bounds);
if (adjusted.getWidth() != bounds.getWidth() || adjusted.getHeight() != bounds.getHeight()) {
chooser.setPixelSize(adjusted.getWidth(), adjusted.getHeight());
}
}
});
ButtonBar buttonBar = new ButtonBar();
buttonBar.add(buttonChoose);
image = new Image();
image.setVisible(false);
panel = new VerticalLayoutContainer();
panel.add(buttonBar, new VerticalLayoutData(1, -1, new Margins(0, 0, 20, 0)));
panel.add(image, new VerticalLayoutData(1, -1));
}
return panel;
}
private void onSelectionChange(SelectionChangedEvent<Photo> se) {
if (se.getSelection().size() > 0) {
details.getBody().setInnerSafeHtml(renderer.render(se.getSelection().get(0), style));
chooser.getButton(PredefinedButton.OK).enable();
} else {
chooser.getButton(PredefinedButton.OK).disable();
details.getBody().setInnerSafeHtml(SafeHtmlUtils.EMPTY_SAFE_HTML);
}
}
@Override
public void onModuleLoad() {
new ExampleContainer(this)
.setMinHeight(MIN_HEIGHT)
.setMinWidth(MIN_WIDTH)
.doStandalone();
}
}
|
package lyrth.makanism.api.react;
import discord4j.core.object.reaction.ReactionEmoji;
import java.util.LinkedHashSet;
import java.util.Set;
public class CustomReactionSet implements ReactionSet {
private final LinkedHashSet<ReactionEmoji> reactions = new LinkedHashSet<>();
public CustomReactionSet(String... buttons){
for (String b : buttons) {
ReactionEmoji emoji = ReactionSet.getReactionEmoji(b);
if (emoji != null) reactions.add(emoji);
}
}
public CustomReactionSet(ReactionEmoji... buttons){
for (ReactionEmoji b : buttons) {
if (b != null) reactions.add(b);
}
}
public CustomReactionSet(ReactionSet from){
reactions.addAll(from.getReactions());
}
public CustomReactionSet append(String... buttons){
for (String b : buttons) {
ReactionEmoji emoji = ReactionSet.getReactionEmoji(b);
if (emoji != null) reactions.add(emoji);
}
return this;
}
public Set<ReactionEmoji> getReactions(){
return reactions;
}
}
|
package com.jelenleti.foodadviser;
import android.os.Bundle;
import android.app.Activity;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
/**
* Created by Jenni on 2017. 12. 12..
*/
public class Pop extends Activity{
Button btnAdd,but;
EditText editNev, editRecept,editHozzavalok;
@Override
protected void onCreate(Bundle saveInstance)
{
setContentView(R.layout.popup1);
super.onCreate(saveInstance);
but = (Button) findViewById(R.id.button);
btnAdd = (Button) findViewById(R.id.button_add);
editNev = (EditText) findViewById(R.id.editText_nev);
editRecept = (EditText) findViewById(R.id.editText_recept);
editHozzavalok = (EditText) findViewById(R.id.editText_hozzavalo);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*.8),(int)(height*.6));
AddData();
but();
}
public void AddData() {
btnAdd.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted = MainActivity.myDb.insertData(editNev.getText().toString(), editRecept.getText().toString(), editHozzavalok.getText().toString());
if (isInserted == true)
Toast.makeText(Pop.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(Pop.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
}
);
}
public void but() {
but.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isUpdate = MainActivity.myDb.updateData(editNev.getText().toString(), editNev.getText().toString(), editRecept.getText().toString(), editHozzavalok.getText().toString());
if (isUpdate == true)
Toast.makeText(Pop.this, "Data Update", Toast.LENGTH_LONG).show();
else
Toast.makeText(Pop.this, "Data not Updated", Toast.LENGTH_LONG).show();
}
}
);
}
}
|
package common;
/**
* Entry point of the program. Launches the GUI and spins off threads as needed.
*
* @author Dilshad Khatri, Alvis Koshy, Drew Noel, Jonathan Tung
* @version 1.0
* @since 2017-01-22
*/
public class EntryPoint {
/**
* Main method, standard entry point to a program
*
* @param args
* Command-line parameters (ignored)
*/
public static void main(String[] args) { // main entry app to run the code
// Create a new thread to do things
Thread t = new Thread(new MainThread());
t.start();
}
}
|
package com.nandi.randomjoke.network;
import com.nandi.randomjoke.model.JokeModel;
import com.octo.android.robospice.request.retrofit.RetrofitSpiceRequest;
/**
* Created by nandi_000 on 25-11-2015.
* API request which fetches the random joke
*/
public class RandomJokeApiRequest extends RetrofitSpiceRequest<JokeModel,RandomJokeApi> {
public RandomJokeApiRequest(){
super(JokeModel.class, RandomJokeApi.class);
}
@Override
public JokeModel loadDataFromNetwork() throws Exception {
return getService().getRandomJoke();
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations;
import org.giddap.dreamfactory.leetcode.onlinejudge.BestTimeToBuyAndSellStockIII;
/**
* 弼馬溫注解:
* <ul>
* <li>Time: O(n); Space: O(n) with extra storage for intermediate results
* .</li>
* <li>Thought Process
* <ul>
* <li>From the most basic case, only one transaction is allowed,
* we can either scan forward OR backward to figure out the max profit.</li>
* <li>Forward: on the iTH day:
* <pre>
* maxProfits[i] = Math.max(maxProfits[i - 1], prices[i] - currentLowest);
* currentLowest = Math.min(currentLowest, prices[i]);
* </pre>
* </li>
* <li>For the case of 'at most two transactions', we could then divide
* the range into 2 sections: before (forward) and after (backward) and run
* forware and backward scans, respectively to achieve overall O(n) time
* complexity. </li>
* </ul>
* </li>
* <li>
* Solution summary:
* <ol>
* <li>Calculate and store the max profit before the iTH day via
* forward scan.</li>
* <li>Calculate and store the max profit after the iTH day via backwards
* scan.</li>
* <li>Figure out the max profit by max (sums of the elements from the two
* arrays, respectively).</li>
* </ol>
* </li>
* <li>We could combine step 2 and step 3 to calculate the result and be
* more efficient on space complexity. However, the code will be a bit
* messier that way. It is a personal preference, I guess</li>
* </ul>
*/
public class BestTimeToBuyAndSellStockIIITwoPassOofNImpl implements
BestTimeToBuyAndSellStockIII {
public int maxProfit(int[] prices) {
final int n = prices.length;
if (n < 2) {
return 0;
}
// buy & sell before i-th day
int[] sell = new int[n];
int min = prices[0];
int mp = 0;
for (int i = 1; i < n; i++) {
min = Math.min(prices[i - 1], min);
mp = Math.max(prices[i] - min, mp);
sell[i] = mp;
}
// buy & sell after i-th day
int[] buy = new int[n];
int max = prices[n - 1];
mp = 0;
for (int i = n - 2; i >= 0; i--) {
max = Math.max(prices[i + 1], max);
mp = Math.max(max - prices[i], mp);
buy[i] = mp;
}
// calculate the max profit for each day
// and pick the max
mp = 0;
for (int i = 0; i < n; i++) {
// note: need to filter out negative profits
mp = Math.max(sell[i] + buy[i], mp);
}
return mp;
}
}
|
package com.citibank.ods.entity.pl;
import com.citibank.ods.common.entity.BaseODSEntity;
import com.citibank.ods.entity.pl.valueobject.BaseTplProdQlfyPrvtEntityVO;
/**
* @author fernando.salgado
*
*
* Window - Preferences - Java - Code Style - Code Templates
*/
public class BaseTplProdQlfyPrvtEntity extends BaseODSEntity
{
/**
* Constante do tamanho do Qualificador
*/
public static final int C_PROD_QLFY_CODE_SIZE = 4;
/**
* Constante do tamanho da descrição do Qualificador
*/
public static final int C_PROD_QLFY_TEXT_SIZE = 40;
/**
* Entity VO Qualificação de Produto
*/
protected BaseTplProdQlfyPrvtEntityVO m_data;
/**
* Retorna o entity VO do agregador de produtos
* @return
*/
public BaseTplProdQlfyPrvtEntityVO getData()
{
return m_data;
}
}
|
package controllers;
import views.ViewMayor3Num;
import models.ModelMayor3Num;
/**
*
* @author lupita
*/
public class ControllerMayor3Nun {
ModelMayor3Num model_mayor3num;
ViewMayor3Num view_mayor3num;
public ControllerMayor3Nun (ModelMayor3Num model_mayor3num, ViewMayor3Num view_mayor3num){
this.model_mayor3num = model_mayor3num;
this.view_mayor3num =view_mayor3num;
view_mayor3num.jbtn_mayor.addActionListener(e -> jbtn_mayor_click());
initview();
}
public void initview(){
view_mayor3num.jtf_n1.setText(String.valueOf(model_mayor3num.getN1()));
view_mayor3num.jtf_n2.setText(String.valueOf(model_mayor3num.getN2()));
view_mayor3num.jtf_n3.setText(String.valueOf(model_mayor3num.getN3()));
view_mayor3num.jtf_n3.setText(String.valueOf(model_mayor3num.getM()));
view_mayor3num.jbtn_mayor.addActionListener(e -> jbtn_mayor_click());
view_mayor3num.setVisible(true);
}
public void jbtn_mayor_click(){
model_mayor3num.setN1(Integer.parseInt(view_mayor3num.jtf_n1.getText()));
model_mayor3num.setN2(Integer.parseInt(view_mayor3num.jtf_n2.getText()));
model_mayor3num.setN3(Integer.parseInt(view_mayor3num.jtf_n3.getText()));
model_mayor3num.mayor();
view_mayor3num.jtf_m.setText(String.valueOf(model_mayor3num .getM()));
}
}
|
package com.jay.mvp_dagger2_sample.data;
import com.jay.mvp_dagger2_sample.data.remote.Api;
import com.jay.mvp_dagger2_sample.data.interfaces.ISecurityDataSource;
import com.jay.mvp_dagger2_sample.data.remote.mapper.DefaultHttpResponse;
import com.jay.mvp_dagger2_sample.helper.event.AppEvent;
import org.greenrobot.eventbus.EventBus;
import javax.inject.Inject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by JINISYS on 26/03/2018.
*/
public class SecurityRepository implements ISecurityDataSource {
private Api api;
@Inject
public SecurityRepository(Api api){
this.api = api;
}
@Override
public void testConnection() {
Call<DefaultHttpResponse> connection = api.testConnection();
connection.enqueue(new Callback<DefaultHttpResponse>() {
@Override
public void onResponse(Call<DefaultHttpResponse> call, Response<DefaultHttpResponse> response) {
if(response.isSuccessful()){
EventBus.getDefault().post(new AppEvent(true, response.message(), response.code()));
}else{
EventBus.getDefault().post(new AppEvent(false, response.message(), response.code()));
}
}
@Override
public void onFailure(Call<DefaultHttpResponse> call, Throwable t) {
EventBus.getDefault().post(new AppEvent(false, t.getMessage(), 500));
}
});
}
}
|
package com.peihua.mapper;
public class UserMapperImpl implements UserMapper{
@Override
public void save() {
System.out.println("user mapper running ...");
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.davivienda.sara.bean.page.administracion;
import com.davivienda.sara.base.ComponenteAjaxObjectContextWeb;
import com.davivienda.sara.base.exception.EntityServicioExcepcion;
import com.davivienda.sara.bean.BaseBean;
import com.davivienda.sara.bean.InitBean;
import com.davivienda.sara.constantes.CodigoError;
import com.davivienda.sara.dto.OficinaMultiDTO;
import com.davivienda.sara.entitys.Oficinamulti;
import com.davivienda.sara.entitys.Zona;
import com.davivienda.sara.tablas.ofimulti.session.OfimultiSessionLocal;
import com.davivienda.utilidades.Constantes;
import com.davivienda.utilidades.conversion.JSon;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.ServletException;
/**
*
* @author jmcastel
*/
@ManagedBean(name = "oficinaMulti")
@ViewScoped
public class OficinaMultifuncional extends BaseBean implements Serializable {
@EJB
OfimultiSessionLocal ofimultiSession;
private String codigo;
private String nombre;
private String codigoCentroEfectivo;
private boolean primeraVez;
private int cantidadZona;
private boolean mostrarBtnGrabar;
private String usuarioSeleccionado;
private boolean mostrarBtnCancelar;
private List<SelectItem> listaOficina;
private List<OficinaMultiDTO> oficinasMulfs;
public ComponenteAjaxObjectContextWeb objectContext;
@PostConstruct
public void OficinaMultifuncional() {
String error = "";
try {
objectContext = cargarComponenteAjaxObjectContext();
setListaOficina(new ArrayList<SelectItem>());
if (objectContext != null) {
Collection<Oficinamulti> items = ofimultiSession.getTodos();
List<OficinaMultiDTO> respuesta = objectContext.getOfimultiCB(items);
setListaOficina(cargarListaOficinaMulti(respuesta));
setOficinasMulfs(respuesta);
this.setUsuarioSeleccionado("");
this.setPrimeraVez(true);
usuarioInicial();
this.setCantidadZona(getListaOficina().size());
}
} catch (Exception ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", Constantes.MSJ_ERROR_INTERNO, null);
}
}
public void usuarioInicial() {
System.err.println("ZonaBean-usuarioInicial: Inicio");
if (!this.oficinasMulfs.isEmpty()) {
this.codigo = String.valueOf(this.oficinasMulfs.get(0).getCodigooficinamulti());
this.nombre = this.oficinasMulfs.get(0).getNombre();
this.codigoCentroEfectivo = String.valueOf(this.oficinasMulfs.get(0).getCodigocentroefectivo());
}
this.mostrarBtnGrabar = false;
this.mostrarBtnCancelar = false;
System.err.println("ZonaBean-usuarioInicial: Final");
}
public void nuevoUsuario() {
this.codigo = "";
this.nombre = "";
this.codigoCentroEfectivo = "";
this.mostrarBtnCancelar = true;
this.mostrarBtnGrabar = true;
}
public void modificarUsuario() {
this.mostrarBtnCancelar = true;
this.mostrarBtnGrabar = true;
}
public void grabarUsuario() {
String resp = "";
try {
Oficinamulti registroEntity = cargarOficinaAplicacion();
if (registroEntity == null) {
abrirModal("SARA", "Los campos Código, Nombre , Código Centro Efectivo son campos Obligatorios ", null);
} else {
ofimultiSession.actualizar(registroEntity);
Collection<Oficinamulti> items = ofimultiSession.getTodos();
List<OficinaMultiDTO> respuesta = objectContext.getOfimultiCB(items);
setListaOficina(cargarListaOficinaMulti(respuesta));
abrirModal("SARA", "Se ha guardado exitosamente el registro", null);
}
} catch (java.lang.ArrayIndexOutOfBoundsException ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", "Ha llegado al último registro", null);
} catch (EJBException | EntityServicioExcepcion ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null);
} catch (Exception ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", Constantes.MSJ_ERROR_INTERNO, null);
}
}
public void buscarRegistro() {
String error = "";
String user = "";
try {
if (!this.usuarioSeleccionado.equals("")) {
user = obtenerUsuario("BUSCAR");
Oficinamulti registroEntity = new Oficinamulti(Integer.parseInt(user.split("-")[0].trim()));
registroEntity = ofimultiSession.buscar(registroEntity.getCodigooficinamulti());
usuarioConvert(objectContext.getOfincinaMultiDTO(registroEntity));
this.usuarioSeleccionado = String.valueOf(buscarCodUsuario(user));
}
if (this.primeraVez) {
this.usuarioSeleccionado = "0";
this.primeraVez = false;
}
} catch (java.lang.ArrayIndexOutOfBoundsException ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", "Ha llegado al último registro", null);
} catch (EJBException | EntityServicioExcepcion ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null);
} catch (Exception ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", Constantes.MSJ_ERROR_INTERNO, null);
}
}
public void usuarioConvert(OficinaMultiDTO registroEntity) {
this.codigo = String.valueOf(registroEntity.getCodigooficinamulti());
this.nombre = registroEntity.getNombre();
this.codigoCentroEfectivo = String.valueOf(registroEntity.getCodigocentroefectivo());
this.setMostrarBtnGrabar(false);
this.setMostrarBtnCancelar(false);
}
public void borrarUsuario() {
String resp = "";
try {
Oficinamulti registroEntity = cargarOficinaAplicacion();
if (registroEntity == null) {
abrirModal("SARA", "Los campos Código, Nombre , Código Centro Efectivo ", null);
} else {
ofimultiSession.borrar(registroEntity);
Collection<Oficinamulti> items = ofimultiSession.getTodos();
List<OficinaMultiDTO> respuesta = objectContext.getOfimultiCB(items);
setListaOficina(cargarListaOficinaMulti(respuesta));
usuarioInicial();
abrirModal("SARA", "Se ha borrado exitosamente el registro", null);
}
} catch (java.lang.ArrayIndexOutOfBoundsException ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", "Ha llegado al último registro", null);
} catch (EJBException | EntityServicioExcepcion ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null);
} catch (Exception ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", Constantes.MSJ_ERROR_INTERNO, null);
}
}
public void anteriorUsuario() {
String error = "";
String user = "";
try {
user = obtenerUsuario("ANTERIOR");
if (!user.isEmpty()) {
Oficinamulti registroEntity = new Oficinamulti(Integer.parseInt(user.split("-")[0].trim()));
registroEntity = ofimultiSession.buscar(registroEntity.getCodigooficinamulti());
usuarioConvert(objectContext.getOfincinaMultiDTO(registroEntity));
this.usuarioSeleccionado = String.valueOf(buscarCodUsuario(user));
}
} catch (java.lang.ArrayIndexOutOfBoundsException ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", "Ha llegado al último registro", null);
} catch (EJBException | EntityServicioExcepcion ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null);
} catch (Exception ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", Constantes.MSJ_ERROR_INTERNO, null);
}
}
public void siguienteUsuario() {
String error = "";
String user = "";
try {
user = obtenerUsuario("SIGUIENTE");
if (!user.isEmpty()) {
Oficinamulti registroEntity = new Oficinamulti(Integer.parseInt(user.split("-")[0].trim()));
registroEntity = ofimultiSession.buscar(registroEntity.getCodigooficinamulti());
usuarioConvert(objectContext.getOfincinaMultiDTO(registroEntity));
this.usuarioSeleccionado = String.valueOf(buscarCodUsuario(user));
}
} catch (java.lang.ArrayIndexOutOfBoundsException ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", "Ha llegado al último registro", null);
} catch (EJBException | EntityServicioExcepcion ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null);
} catch (Exception ex) {
objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
abrirModal("SARA", Constantes.MSJ_ERROR_INTERNO, null);
}
}
public int buscarCodUsuario(String nombreUsuario) {
int codUsuario = 0;
for (SelectItem regional : this.listaOficina) {
if (nombreUsuario.equalsIgnoreCase(regional.getLabel())) {
codUsuario = Integer.parseInt(String.valueOf(regional.getValue()));
}
}
return codUsuario;
}
public String obtenerUsuario(String operUsuario) {
String idUsuario = "1";
String user = "";
switch (operUsuario) {
case "BUSCAR":
idUsuario = this.getUsuarioSeleccionado();
for (SelectItem lista : getListaOficina()) {
if (String.valueOf(lista.getValue()).equals(idUsuario)) {
user = lista.getLabel();
this.setUsuarioSeleccionado(idUsuario);
break;
}
}
break;
case "ANTERIOR": {
int cUser = Integer.parseInt(this.getUsuarioSeleccionado());
cUser = (cUser - 1);
if (cUser >= 1) {
idUsuario = String.valueOf(cUser);
for (SelectItem lista : getListaOficina()) {
if (String.valueOf(lista.getValue()).equals(idUsuario)) {
user = lista.getLabel();
this.setUsuarioSeleccionado(idUsuario);
break;
}
}
}
break;
}
case "SIGUIENTE": {
int cUser = Integer.parseInt(this.getUsuarioSeleccionado());
cUser = (cUser + 1);
if (cUser <= this.getCantidadZona()) {
idUsuario = String.valueOf(cUser);
for (SelectItem lista : getListaOficina()) {
if (String.valueOf(lista.getValue()).equals(idUsuario)) {
user = lista.getLabel();
this.setUsuarioSeleccionado(idUsuario);
break;
}
}
}
break;
}
default:
break;
}
return user;
}
private List<SelectItem> cargarListaOficinaMulti(List<OficinaMultiDTO> ofiMultiCB) {
List<SelectItem> lista = new ArrayList<SelectItem>();
SelectItem item = new SelectItem(0, "");
lista.add(item);
int cont = 1;
for (OficinaMultiDTO dto : ofiMultiCB) {
item = new SelectItem(cont, dto.getCodigooficinamulti() + " - " + dto.getNombre());
lista.add(item);
cont++;
}
return lista;
}
private Oficinamulti cargarOficinaAplicacion() {
Oficinamulti tc = new Oficinamulti();
Integer intTmp = null;
String strTmp = "";
if (this.codigo != null) {
intTmp = Integer.parseInt(this.codigo);
} else {
return null;
}
tc.setCodigooficinamulti(intTmp);
strTmp = this.nombre;
if (strTmp.length() == 0) {
return null;
}
tc.setNombre(strTmp);
intTmp = Integer.parseInt(this.codigoCentroEfectivo);
if (strTmp.length() == 0) {
return null;
}
tc.setCodigocentroefectivo(intTmp);
return tc;
}
/**
* @return the codigo
*/
public String getCodigo() {
return codigo;
}
/**
* @param codigo the codigo to set
*/
public void setCodigo(String codigo) {
this.codigo = codigo;
}
/**
* @return the nombre
*/
public String getNombre() {
return nombre;
}
/**
* @param nombre the nombre to set
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* @return the primeraVez
*/
public boolean isPrimeraVez() {
return primeraVez;
}
/**
* @param primeraVez the primeraVez to set
*/
public void setPrimeraVez(boolean primeraVez) {
this.primeraVez = primeraVez;
}
/**
* @return the cantidadZona
*/
public int getCantidadZona() {
return cantidadZona;
}
/**
* @param cantidadZona the cantidadZona to set
*/
public void setCantidadZona(int cantidadZona) {
this.cantidadZona = cantidadZona;
}
/**
* @return the mostrarBtnGrabar
*/
public boolean isMostrarBtnGrabar() {
return mostrarBtnGrabar;
}
/**
* @param mostrarBtnGrabar the mostrarBtnGrabar to set
*/
public void setMostrarBtnGrabar(boolean mostrarBtnGrabar) {
this.mostrarBtnGrabar = mostrarBtnGrabar;
}
/**
* @return the usuarioSeleccionado
*/
public String getUsuarioSeleccionado() {
return usuarioSeleccionado;
}
/**
* @param usuarioSeleccionado the usuarioSeleccionado to set
*/
public void setUsuarioSeleccionado(String usuarioSeleccionado) {
this.usuarioSeleccionado = usuarioSeleccionado;
}
/**
* @return the mostrarBtnCancelar
*/
public boolean isMostrarBtnCancelar() {
return mostrarBtnCancelar;
}
/**
* @param mostrarBtnCancelar the mostrarBtnCancelar to set
*/
public void setMostrarBtnCancelar(boolean mostrarBtnCancelar) {
this.mostrarBtnCancelar = mostrarBtnCancelar;
}
/**
* @return the listaOcca
*/
public List<SelectItem> getListaOficina() {
return listaOficina;
}
/**
* @param listaOcca the listaOcca to set
*/
public void setListaOficina(List<SelectItem> listaOficina) {
this.listaOficina = listaOficina;
}
/**
* @return the codigoCentroEfectivo
*/
public String getCodigoCentroEfectivo() {
return codigoCentroEfectivo;
}
/**
* @param codigoCentroEfectivo the codigoCentroEfectivo to set
*/
public void setCodigoCentroEfectivo(String codigoCentroEfectivo) {
this.codigoCentroEfectivo = codigoCentroEfectivo;
}
/**
* @return the oficinasMulfs
*/
public List<OficinaMultiDTO> getOficinasMulfs() {
return oficinasMulfs;
}
/**
* @param oficinasMulfs the oficinasMulfs to set
*/
public void setOficinasMulfs(List<OficinaMultiDTO> oficinasMulfs) {
this.oficinasMulfs = oficinasMulfs;
}
}
|
package mx.com.mentoringit.entities;
// Generated 20-jun-2016 21:40:30 by Hibernate Tools 4.3.1.Final
import java.util.HashSet;
import java.util.Set;
/**
* Cuenta generated by hbm2java
*/
public class Cuenta implements java.io.Serializable {
private Integer idCuenta;
private Cliente cliente;
private Tipocuenta tipocuenta;
private int numeroCuenta;
private Set<Movimiento> movimientos = new HashSet<Movimiento>(0);
public Cuenta() {
}
public Cuenta(Cliente cliente, Tipocuenta tipocuenta, int numeroCuenta) {
this.cliente = cliente;
this.tipocuenta = tipocuenta;
this.numeroCuenta = numeroCuenta;
}
public Cuenta(Cliente cliente, Tipocuenta tipocuenta, int numeroCuenta, Set<Movimiento> movimientos) {
this.cliente = cliente;
this.tipocuenta = tipocuenta;
this.numeroCuenta = numeroCuenta;
this.movimientos = movimientos;
}
public Integer getIdCuenta() {
return this.idCuenta;
}
public void setIdCuenta(Integer idCuenta) {
this.idCuenta = idCuenta;
}
public Cliente getCliente() {
return this.cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public Tipocuenta getTipocuenta() {
return this.tipocuenta;
}
public void setTipocuenta(Tipocuenta tipocuenta) {
this.tipocuenta = tipocuenta;
}
public int getNumeroCuenta() {
return this.numeroCuenta;
}
public void setNumeroCuenta(int numeroCuenta) {
this.numeroCuenta = numeroCuenta;
}
public Set<Movimiento> getMovimientos() {
return this.movimientos;
}
public void setMovimientos(Set<Movimiento> movimientos) {
this.movimientos = movimientos;
}
}
|
public class insertionThread extends Thread {
private int array[];
private int split;
public insertionThread(int array[], int split) {
this.array = array;
this.split = split;
}
public void run(){
if (array.length > split){
int array1[] = new int[array.length /2];
int array2[] = new int[array.length - array1.length];
for(int i = 0 ; i < array1.length ; i++){
array1[i] = array[i];
}
for(int i = 0 ; i < array2.length ; i++){
array2[i] = array[i+array1.length];
}
insertionThread temp1 = new insertionThread(array1, split);
insertionThread temp2 = new insertionThread(array2, split);
temp1.start();
temp2.start();
try{
temp1.join(); temp2.join();
}catch(InterruptedException e){};
array = merge(temp1.getSorted(),temp2.getSorted());
}else{
for (int j = 1; j < array.length; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}
}
public int[] getSorted() {
return array;
}
public static int[] merge(int[] a, int[] b) {
int[] answer = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
{
if (a[i] < b[j])
answer[k++] = a[i++];
else
answer[k++] = b[j++];
}
while (i < a.length)
answer[k++] = a[i++];
while (j < b.length)
answer[k++] = b[j++];
return answer;
}
}
|
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
* Diseño de una calculadora
* @author Garcia Garcia Jose Ángel
* */
public class Ventana extends JFrame{
private Container numeros; // Contiene botones del 1-9
private Container operaciones; // Contiene los botones de las operaciones
private Container acciones;
private JTextField num;
private JButton[] btnNumeros;
private JButton suma;
private JButton resta;
private JButton div;
private JButton borrar;
private JButton igual;
private JTextField resultado;
public Ventana() {
numeros = new Container();
num = new JTextField(10);
btnNumeros = rellenarNumeros();
operaciones = botonesOperaciones();
acciones = botonesAcciones();
setLayout(new BorderLayout());
add(numeros,BorderLayout.CENTER);
add(num,BorderLayout.NORTH);
add(operaciones,BorderLayout.EAST);
add(acciones,BorderLayout.SOUTH);
arrancar();
}
public void actualizarResultado(String r){
resultado.setText("Resultado : " + r);
}
private Container botonesAcciones() {
Container principal = new Container();
principal.setLayout(new BoxLayout(principal, BoxLayout.X_AXIS));
Container c = new Container();
c.setLayout(new FlowLayout(FlowLayout.RIGHT));
borrar = new JButton("Borrar Datos");
igual = new JButton("=");
c.add(borrar);
c.add(igual);
resultado = new JTextField(20);
resultado.setEditable(false);
principal.add(resultado);
principal.add(c);
return principal;
}
private Container botonesOperaciones() {
Container c = new Container();
c.setLayout(new GridLayout(3, 1));
suma = new JButton("+");
resta = new JButton("-");
div = new JButton("/");
c.add(suma);
c.add(resta);
c.add(div);
return c;
}
private JButton[] rellenarNumeros(){
numeros.setLayout(new GridLayout(3,3)); // Panel para hacer la calculadora
JButton[] btnNumeros = new JButton[9];
for (int i = 0; i < btnNumeros.length; i++) {
btnNumeros[i] = new JButton("" + (i+1));
btnNumeros[i].setBackground(Color.GRAY);
numeros.add(btnNumeros[i]);
}
return btnNumeros;
}
public void arrancar(){
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
pack();
setVisible(true);
setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
|
package com.proxiad.games.extranet.model;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Set;
import org.springframework.lang.NonNull;
import com.proxiad.games.extranet.enums.LanguageEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Entity
@Table(name="people")
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class People {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@NonNull
private String name;
@NonNull
private String surname;
private Integer sex;
private LocalDateTime birthDate;
private LocalDateTime arrivalDate;
private String email;
private String phone;
private String city;
private Integer pictureIndex;
private String workPlace;
private String job;
@Column(name = "languages")
@ElementCollection
@Enumerated(EnumType.STRING)
private Set<LanguageEnum> languages;
@ElementCollection
private Set<String> interets;
@ElementCollection // this is a collection of primitives
@MapKeyColumn(name="domain") // column name for map "key"
@Column(name="skill") // column name for map "value"
private Map<String, String> skills;
}
|
package gameClient;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import api.DWGraph_Algo;
import api.directed_weighted_graph;
import api.edge_data;
import api.game_service;
import api.node_data;
/**
* This class is used for calculate algorithms for agents movements, and picking the next good pokemon.
*
*/
public class AgentMovementAlgo {
private DWGraph_Algo algo;
private HashMap<CL_Agent, HashMap<CL_Pokemon, Double>> dists;
/**
* constructor for init graph algorithms and game info for algorithms.
* @param game
* @param g
*/
public AgentMovementAlgo(directed_weighted_graph g) {
this.algo = new DWGraph_Algo();
algo.init(g);
}
/**
* The method initializes the routes of all the agents later to the location of the Pokemon
* so that when calling nextNode the next corresponding node is returned.
* The method produces for each agent the series of Pokemon that he needs to catch in order from near to far
* and then commands him to the nearest Pokemon that has not been taken by a closer agent.
* @param agents
* @param pokemons
*/
public void initNextNode(List<CL_Agent> agents, List<CL_Pokemon> pokemons) {
dists = new HashMap<CL_Agent, HashMap<CL_Pokemon,Double>>();
for (int i = 0; i < agents.size(); i++) {
buildPathForallPokemons(agents.get(i), pokemons);
}
for (int i = 0; i < agents.size(); i++) {
setNextPokemon(agents.get(i), agents, pokemons);
}
}
private void setNextPokemon(CL_Agent a, List<CL_Agent> agents, List<CL_Pokemon> pokemons) {
a.set_curr_fruit(null);
double min = Double.POSITIVE_INFINITY;
CL_Pokemon chosen = null;
for(CL_Pokemon p : pokemons) {
double d = dists.get(a).get(p);
if(notTaken(agents, p) && bestAgent(agents, a, p,d) && d < min) {
min = d;
chosen = p;
}
}
if(chosen == null) {
min = Double.POSITIVE_INFINITY;
for(CL_Pokemon p : pokemons) {
double d = dists.get(a).get(p);
if(notTaken(agents, p) && d < min) {
min = d;
chosen = p;
}
}
}
a.set_curr_fruit(chosen);
}
private boolean bestAgent(List<CL_Agent> agents, CL_Agent me, CL_Pokemon p, double d) {
for(CL_Agent a : agents) {
if(a != me && dists.get(a).get(p)*1.2 < d) return false;
}
return true;
}
private boolean notTaken(List<CL_Agent> agents, CL_Pokemon p) {
for(CL_Agent a : agents) {
if(a.get_curr_fruit() == p) return false;
}
return true;
}
private void buildPathForallPokemons(CL_Agent a, List<CL_Pokemon> pokemons) {
List<CL_Pokemon> pok = new LinkedList<CL_Pokemon>();
HashMap<CL_Pokemon, Double> pdists = new HashMap<CL_Pokemon, Double>();
for(CL_Pokemon p : pokemons) pok.add(p);
int src = a.getSrcNode();
double totalDist = 0;
while(!pok.isEmpty()) {
double min_dist = Double.POSITIVE_INFINITY;
int min_index = -1;
for (int i = 0; i < pok.size(); i++) {
double d = algo.shortestPathDist(src, pok.get(i).get_edge().getSrc()) + pok.get(i).get_edge().getWeight();
if(d < min_dist) {
min_dist = d;
min_index = i;
}
}
src = pok.get(min_index).get_edge().getDest();
totalDist += min_dist;
pdists.put(pok.remove(min_index), totalDist);
}
dists.put(a, pdists);
}
/**
* Return the first node on shortest path between the given agent and his closets pokemon.
* @param i
* @return thee next node to go to
*/
public int nextNode(CL_Agent a) {
if(a == null || a.get_curr_fruit() == null) return -1;
edge_data e = a.get_curr_fruit().get_edge();
if(e.getSrc() == a.getSrcNode()) return e.getDest();
List<node_data> p = algo.shortestPath(a.getSrcNode(), e.getSrc());
if(p == null) return -1;
return p.get(1).getKey();
}
}
|
/**
* Copyright (c) 2004-2021 All Rights Reserved.
*/
package com.adomy.mirpc.core.remoting.provider.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 服务提供者注解
*
* @author adomyzhao
* @version $Id: MiRpcService.java, v 0.1 2021年03月23日 8:15 PM adomyzhao Exp $
*/
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MiRpcService {
/**
* 接口类型
*
* @return
*/
Class<?> interfaceType() default void.class;
/**
* 版本
*
* @return 版本号
*/
String version() default "DEFAULT";
}
|
/*
* 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 Model;
import Interfaces.RegIF;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static javax.servlet.SessionTrackingMode.URL;
/**
*
* @author RolfMoikjær
*/
public class RegistratedUsers implements RegIF{
private final String userName = "cphrh110";
private final String passWord = "cphrh110";
private final String driver = "oracle.jdbc.driver.OracleDriver";
private final String URL = "jdbc:oracle:thin:@datdb.cphbusiness.dk:1521:dat";
private ResultSet rs;
private Statement statement;
private Connection connection;
Map<String, User> users = new HashMap();
public RegistratedUsers(){
}
@Override
public boolean authCheck(String name, String id, String pwd, String gender, String age, String country){
//users.put(id, new User(name, id, pwd, gender, age, country));
return true;
}
@Override
public boolean addUser(String name, String id, String pwd, String gender, String age, String country) {
try {
Class.forName(driver);
connection = java.sql.DriverManager.getConnection(URL, userName, passWord);
statement = connection.createStatement();
String sql = "INSERT INTO users VALUES ('"+name+"', '"+id+"', '"+pwd+"', '"+gender+"', '"+age+"', '"+country+"')";
statement.executeUpdate(sql);
} catch (SQLException sqlE) {
System.out.println(Arrays.toString(sqlE.getStackTrace()));
connection = null;
} catch(ClassNotFoundException ex){
System.out.println(ex.getMessage());
}
return true;
}
}
|
package com.nixsolutions.micrometr.service.external.alphavintage.enums;
import com.nixsolutions.micrometr.utils.EnumWithValue;
public enum Endpoints implements EnumWithValue<Endpoints, String>
{
TIME_SERIES_INTRADAY("TIME_SERIES_INTRADAY"),
TIME_SERIES_DAILY("TIME_SERIES_DAILY"),
TIME_SERIES_DAILY_ADJUSTED("TIME_SERIES_DAILY_ADJUSTED"),
TIME_SERIES_WEEKLY("TIME_SERIES_WEEKLY"),
TIME_SERIES_MONTHLY("TIME_SERIES_MONTHLY");
private String value;
Endpoints(String value)
{
this.value = value;
}
public String getValue()
{
return value;
}
@Override
public Endpoints getByValue(String value)
{
return iterateThroughValuesForMatch(value, values());
}
}
|
package com.lzy.movie;
import com.lzy.filter.Filter;
import java.util.ArrayList;
import java.util.HashMap;
public class MovieDatabase {
static HashMap<String,Movie> movieInfo;
public static void initialize(){
FirstRatings fr = new FirstRatings();
if(movieInfo == null){
movieInfo = new HashMap<>();
loadMovies();
}else{
movieInfo = new HashMap<>();
loadMovies("ratemoviesfull");
}
}
private static void loadMovies(String filename){
FirstRatings fr = new FirstRatings();
ArrayList<Movie> list = fr.loadMovies(filename);
for(Movie mv : list){
movieInfo.put(mv.getId(),mv);
}
}
private static void loadMovies(){
FirstRatings fr = new FirstRatings();
ArrayList<Movie> list = fr.loadMovies();
for(Movie mv : list){
movieInfo.put(mv.getId(),mv);
}
}
public boolean containsID(String id){
if(movieInfo.containsKey(id)){
return true;
}
return false;
}
public static int getYear(String id){
return movieInfo.get(id).getYear();
}
public static String getTitle(String id){
return movieInfo.get(id).getTitle();
}
public static String getMovie(String id){
return movieInfo.get(id).getId();
}
public static String getPoster(String id){
return movieInfo.get(id).getPoster();
}
public static int getMinutes(String id){
return movieInfo.get(id).getMinutes();
}
public static String getCountry(String id){
return movieInfo.get(id).getCountry();
}
public static String getGenres(String id){
return movieInfo.get(id).getGenres();
}
public static String getDirector(String id){
return movieInfo.get(id).getDirector();
}
public static int numOfMovies(){
return movieInfo.size();
}
public static ArrayList<String> filterBy(Filter f){
ArrayList<String> list = new ArrayList<>();
for(String movieID : movieInfo.keySet()){
if(f.satisfies(movieID)){
list.add(movieID);
}
}
return list;
}
public static int getNumOfMovies(){
return movieInfo.keySet().size();
}
public static int size(){
return movieInfo.size();
}
}
|
package com.function;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Common {
/**
* 获取现在时间的字符串形式
* @return
*/
public static String time(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(new Date());
}
/**
* 获取现在日期的字符串形式
* @return
*/
public static String time2(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd ");
return format.format(new Date());
}
/**
* 时间格式是否合法
* @param time
* @param format
* @return
*/
public static boolean isValidTimeFormat(String time,String format){
DateFormat formatter = new SimpleDateFormat(format);
try{
Date date = (Date)formatter.parse(time);
return time.equals(formatter.format(date));
}catch(Exception e){
return false;
}
}
/**
* 转化 类型整形和字符串
* @param s
* @return
*/
public static int getType(String s){
int t = -1;
switch (s) {
case "库存管理员":
t = 1;
break;
case "进销人员":
t = 2;
break;
case "财务人员":
t = 3;
break;
case "总经理":
t = 4;
break;
case "系统管理员":
t = 0;
break;
default:
break;
}
return t;
}
public static String getType(int t){
String s = "";
switch (t) {
case 0:
s = "系统管理员";
break;
case 1:
s = "库存管理员";
break;
case 2:
s = "进销人员";
break;
case 3:
s = "财务人员";
break;
case 4:
s = "总经理";
break;
default:
break;
}
return s;
}
}
|
package com.example.miwokapp2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
public class ColorsActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colors);
String maintitle [] = new String[] {
"red", "green", "brown", "gray", "black", "white", "dusty yellow", "mustard yellow"
} ;
String subtitle[] = new String[] {
"weṭeṭṭi", "chokokki", "ṭakaakki", "ṭopoppi", "kululli", "kelelli", "ṭopiisә", "chiwiiṭә"
} ;
WordAdapter adapter=new WordAdapter(this,maintitle,subtitle);
listView=(ListView) findViewById(R.id.listNumbers);
listView.setAdapter(adapter);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Ibrhaim
*/
public class RunnerLab7Pizza {
public static void main(String[] args){
Pizza pizza1 = new Pizza("small", 4, 3, 10);
Pizza pizza2 = new Pizza("medium", 5, 3, 2);
Pizza pizza3 = new Pizza("large", 4, 4, 6);
System.out.println(pizza1.getDescription());
System.out.println(pizza2.getDescription());
System.out.println(pizza3.getDescription());
PizzaOrder pizzaorder = new PizzaOrder(pizza1,pizza2,pizza3);
System.out.println("Cost of the three ordered pizza:$"+pizzaorder.calcTotal());
}
}
|
package resultMerge;
import java.util.LinkedList;
public class LegRace implements RaceType {
private static LegInfo legInfo;
private class Leg {
LinkedList<Time> start = new LinkedList<>();
LinkedList<Time> finish = new LinkedList<>();
int leg;
public Leg(int i) {
leg = i;
}
public void addStart(Time t) {
start.add(t);
}
public void addFinish(Time t) {
finish.add(t);
}
public String getStart() {
return start.isEmpty() ? "Start?" : start.getFirst().toString();
}
public String getStartWithErrors(StringBuilder errors, int i) {
if (start.size() > 1) {
errors.append("Flera starttider Etapp" + i);
for (int j = 1; j < start.size(); j++) {
errors.append(" " + start.get(j));
}
errors.append("; ");
}
return getStart();
}
public String getFinishWithErrors(StringBuilder errors, int i) {
if (finish.size() > 1) {
errors.append("Flera måltider Etapp" + i);
for (int j = 1; j < finish.size(); j++) {
errors.append(" " + finish.get(j));
}
errors.append("; ");
}
return getFinish();
}
public String getFinish() {
return finish.isEmpty() ? "Slut?" : finish.getFirst().toString();
}
public Time getLegTime() {
if (!(start.isEmpty() || finish.isEmpty())) {
try {
Time t = Time.diff(finish.getFirst(), start.getFirst());
t = t.multiply(legInfo.getMultiplier(leg));
return t;
} catch (Exception e) {
}
}
return null;
}
}
private Leg[] legs;
public LegRace(int nbrLegs) {
legs = new Leg[nbrLegs];
for (int i = 0; i < nbrLegs; i++)
legs[i] = new Leg(i);
}
@Override
public String genResult() {
StringBuilder sb = new StringBuilder();
sb.append(getLaps()).append("; ");
Time totalTime = totalTime();
String totTimeStr = totalTime.getTimeAsInt() == 0 ? "--.--.--" : totalTime.toString();
sb.append(totTimeStr.toString()).append("; ");
for (int i = 0; i < legs.length; i++) {
Time legTime = legs[i].getLegTime();
if (legTime != null) {
sb.append(legTime.toString());
}
sb.append("; ");
}
String out = sb.toString();
return out.substring(0, out.length() - 2);
}
@Override
public String genResultWithErrors(Database db) {
StringBuilder sb = new StringBuilder();
StringBuilder errors = new StringBuilder();
sb.append(genResult()).append("; ");
int i = 1;
for (Leg l : legs) { // adds start and finish for each leg
sb.append(l.getStartWithErrors(errors, i)).append("; ");
sb.append(l.getFinishWithErrors(errors, i)).append("; ");
if (db != null) {
try {
Time minimumTime = db.getLegInfo().getMinimumTime(i - 1);
Time diff = l.getLegTime();
if (diff.getTimeAsInt() < minimumTime.getTimeAsInt()) {
errors.append("Omöjlig tid Etapp" + i).append("; ");
}
} catch (Exception ee) {
}
}
i++;
}
sb.append(errors);
String out = sb.toString();
return out.substring(0, out.length() - 2);
}
@Override
public int getLaps() {
int counter = 0;
for (int i = 0; i < legs.length; i++) {
Time legTime = legs[i].getLegTime();
if (legTime != null) {
counter++;
}
}
return counter;
}
private Time totalTime() {
Time totaltime = new Time(0);
for (int i = 0; i < legs.length; i++) {
Time legTime = legs[i].getLegTime();
if (legTime != null) {
totaltime = totaltime.add(legTime);
}
}
return totaltime;
}
public Time getTotalTime() {
Time time = totalTime();
if(time.getTimeAsInt() == 0) return null;
return time;
}
@Override
public String getStart() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getFinish() {
// TODO Auto-generated method stub
return null;
}
@Override
public void addTime(Time t) throws ArrayIndexOutOfBoundsException {
int legNbr = t.getLegNbr() - 1;
if (t.isStart())
legs[legNbr].addStart(t);
else
legs[legNbr].addFinish(t);
}
@Override
public int compareTo(RaceType o) {
LegRace lr = (LegRace) o;
int legDiff = lr.getLaps() - getLaps();
if (legDiff != 0)
return legDiff;
int timediff = totalTime().getTimeAsInt() - lr.totalTime().getTimeAsInt();
return timediff;
}
public static void setLegInfo(LegInfo info) {
legInfo = info;
}
}
|
package mine.config;
import mine.entity.UserEntity;
import org.springframework.context.annotation.*;
/**
* @author 蚂蚁课堂创始人-余胜军QQ644064779
* @title: MySpringConfig
* @description: 每特教育独创第五期互联网架构课程
* @date 2019/6/2221:10
*/
@Configuration
@ComponentScan(value = "mine")
// { , excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Service.class)}, useDefaultFilters = true
public class MySpringConfig {
// includeFilters 包含的扫包范围 必须有这些 排除这些没有
//@Configuration 等于 spring xml
// <bean class="UserEntity" id="方法名称" >
// 将该包下 的 只要有类上加上@service 注解的 注入到spring容器
@Bean
public UserEntity userEntity() {
return new UserEntity("mayikt", 21);
}
/**
* 记住一点 如果需要将外部的jar包注入spring容器中 @Bean
*/
}
|
/*
* Copyright (c) 2008-2022 Haulmont.
*
* 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.haulmont.reports.web.chart_conversion;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.haulmont.reports.entity.charts.ChartSeries;
import com.haulmont.reports.entity.charts.ChartToJsonConverter;
import com.haulmont.reports.entity.charts.SerialChartDescription;
import com.haulmont.reports.entity.charts.SeriesType;
import org.apache.groovy.util.Maps;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
public class ChartToJsonConverterTest {
@Test
public void testLocalDateCategoryValue() throws IOException, URISyntaxException {
ChartToJsonConverter converter = new ChartToJsonConverter();
List<Map<String, Object>> data = new ArrayList<>();
data.add(Maps.of("value", 1, "date", LocalDate.of(2022, 1, 11)));
data.add(Maps.of("value", 2, "date", LocalDate.of(2022, 1, 12)));
data.add(Maps.of("value", 3, "date", LocalDate.of(2022, 1, 13)));
String json = converter.convertSerialChart(generateSerialChartDescription(), data);
String expectedJson = readFile("localdate-serialchart.json");
Assert.assertEquals(prettyJson(expectedJson), prettyJson(json));
}
@Test
public void testLocalDateTimeCategoryValue() throws IOException, URISyntaxException {
ChartToJsonConverter converter = new ChartToJsonConverter();
List<Map<String, Object>> data = new ArrayList<>();
data.add(Maps.of("value", 1, "date", LocalDateTime.of(2022, 1, 11, 1, 12, 33)));
data.add(Maps.of("value", 2, "date", LocalDateTime.of(2022, 1, 12, 2, 13, 34)));
data.add(Maps.of("value", 3, "date", LocalDateTime.of(2022, 1, 13, 3, 14, 35)));
String json = converter.convertSerialChart(generateSerialChartDescription(), data);
String expectedJson = readFile("localdatetime-serialchart.json");
Assert.assertEquals(prettyJson(expectedJson), prettyJson(json));
}
protected SerialChartDescription generateSerialChartDescription() {
SerialChartDescription serialChartDescription = new SerialChartDescription();
serialChartDescription.setId(UUID.randomUUID());
serialChartDescription.setBandName("testBand");
serialChartDescription.setCategoryField("date");
serialChartDescription.setSeries(Collections.singletonList(generateChartSeries()));
return serialChartDescription;
}
protected ChartSeries generateChartSeries() {
ChartSeries chartSeries = new ChartSeries();
chartSeries.setId(UUID.randomUUID());
chartSeries.setType(SeriesType.COLUMN);
chartSeries.setValueField("value");
chartSeries.setOrder(1);
return chartSeries;
}
public static String readFile(String fileName) throws IOException, URISyntaxException {
URL resource = ChartToJsonConverterTest.class
.getResource("/com/haulmont/reports/web/chart_conversion/" + fileName);
byte[] encoded = Files.readAllBytes(Paths.get(resource.toURI()));
return new String(encoded, StandardCharsets.UTF_8);
}
public static String prettyJson(String json) {
JsonElement parsedJson = JsonParser.parseString(json);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(parsedJson);
}
}
|
package com.GestiondesClub.entities;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
@Table(name="materiel_externe")
@NamedQuery(name="MaterielExterne.findAll", query="SELECT me FROM MaterielExterne me")
@PrimaryKeyJoinColumn(name = "id")
public class MaterielExterne extends Materiel{
@Column(name="coutMateriel")
private int coutMateriel ;
@JsonBackReference(value="materiel-Externe")
@OneToMany(mappedBy="materielExterne")
private List<SponsarisationMateriel> lesEvenementSponsoriser;
@JsonBackReference(value="les-demandes-finance")
@OneToMany(mappedBy = "matExterne")
private List<LigneDevi> lesDemandFinance;
public int getCoutMateriel() {
return coutMateriel;
}
public MaterielExterne() {
super();
}
public void setCoutMateriel(int coutMateriel) {
this.coutMateriel = coutMateriel;
}
public List<SponsarisationMateriel> getLesEvenementSponsoriser() {
return lesEvenementSponsoriser;
}
public void setLesEvenementSponsoriser(List<SponsarisationMateriel> lesEvenementSponsoriser) {
this.lesEvenementSponsoriser = lesEvenementSponsoriser;
}
public List<LigneDevi> getLesDemandFinance() {
return lesDemandFinance;
}
public void setLesDemandFinance(List<LigneDevi> lesDemandFinance) {
this.lesDemandFinance = lesDemandFinance;
}
}
|
package analytics.analysis.algorithms.apriori;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import weka.associations.Apriori;
import weka.core.Instances;
import analytics.database.DBBasicOperations;
public class WekaAssociations {
private Apriori algorithm;
private Instances data;
private double deltaValue;
private double lowerBoundMinSupportValue;
private double minMetricValue;
private int numRulesValue;
private double upperBoundMinSupportValue;
private final String arffFileName = "input.ARFF";
public WekaAssociations() {
this.algorithm = new Apriori();
this.data = this.getData();
this.chooseAllVariables();
this.setAllVariables();
}
private void chooseAllVariables() {
//TODO - REFACTOR THIS
this.deltaValue = 0.05;
this.lowerBoundMinSupportValue = 0.1;
this.minMetricValue = 0.5;
this.numRulesValue = 20;
this.upperBoundMinSupportValue = 1.0;
}
private void setAllVariables() {
this.algorithm.setDelta(this.deltaValue);
this.algorithm.setLowerBoundMinSupport(this.lowerBoundMinSupportValue);
this.algorithm.setNumRules(this.numRulesValue);
this.algorithm.setUpperBoundMinSupport(this.upperBoundMinSupportValue);
this.algorithm.setMinMetric(this.minMetricValue);
}
public String runAlgorithm() {
try {
this.algorithm.buildAssociations(this.data);
} catch(Exception e) {
e.printStackTrace();
}
return algorithm.toString();
}
private Instances getData() {
FileReader reader;
Instances result = null;
this.createData();
try {
reader = new FileReader(new File(this.arffFileName));
result = new Instances(reader);
result.setClassIndex(result.numAttributes() - 1);
reader.close();
} catch(Exception e){
e.printStackTrace();
}
return result;
}
private void createData() {
StringBuilder sb = new StringBuilder();
String newLine = System.lineSeparator();
sb.append("@RELATION products");
sb.append(newLine + newLine);
DBBasicOperations db = DBBasicOperations.getInstance();
db.openConnection();
HashMap<Integer, List<Integer>> transactions = db.getTransactions();
HashMap<Integer, String> products = db.getProducts();
db.closeConnection();
for(String product : products.values()) {
sb.append("@ATTRIBUTE '" + product + "' {0,1}" + newLine);
}
sb.append(newLine + "@DATA" + newLine);
Object[] productsCodes = products.keySet().toArray();
Arrays.sort(productsCodes);
Set<Integer> codes = products.keySet();
for(int transactionCode : transactions.keySet()) {
String row = this.getARFFDataRow(transactions.get(transactionCode), codes) + newLine;
sb.append(row);
}
String output = sb.append(newLine).toString();
this.writeARFFFile(output);
}
private String getARFFDataRow(List<Integer> products, Set<Integer> codes) {
StringBuilder row = new StringBuilder();
Object[] sortedProducts = products.toArray();
int currentProductIndex = 0,
maxProductIndex = sortedProducts.length - 1;
Arrays.sort(sortedProducts);
for(int code : codes) {
if(currentProductIndex > maxProductIndex) {
row.append("0,");
continue;
}
if(code != (Integer)sortedProducts[currentProductIndex]) {
row.append("0,");
} else {
row.append("1,");
currentProductIndex++;
}
}
row.deleteCharAt(row.length() - 1);
return row.toString();
}
private void writeARFFFile(String outputText) {
try {
File file = new File(this.arffFileName);
if(file.exists()) {
file.delete();
}
file.createNewFile();
PrintWriter pw = new PrintWriter(new FileOutputStream(file));
pw.write(outputText);
pw.close();
} catch(Exception e) {
}
}
/*
public static void main(String[] args) {
WekaAssociations x = new WekaAssociations();
x.runAlgorithm();
}
*/
}
|
package com.meizu.scriptkeeper.broadcast;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Build;
import android.widget.Toast;
import com.meizu.scriptkeeper.constant.Constants;
import com.meizu.scriptkeeper.preferences.Preferences;
import com.meizu.scriptkeeper.preferences.SchedulePreference;
import com.meizu.scriptkeeper.utils.Downloader;
import com.meizu.scriptkeeper.utils.Log;
import com.meizu.scriptkeeper.utils.UpdateUtil;
/**
* Author: jinghao
* Date: 2015-03-31
* Package: com.meizu.anonymous.broadcast
*/
public class DownloadReceiver extends BroadcastReceiver {
SharedPreferences pref_schedule;
DownloadManager downloadManager;
@Override
public void onReceive(Context context, Intent intent) {
this.downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
this.pref_schedule = context.getSharedPreferences(Preferences.SCHEDULE_PREF, Context.MODE_MULTI_PROCESS);
long expectId = this.pref_schedule.getLong(SchedulePreference.DOWNLOAD_ID, 0);
long downloadId = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID);
Log.e("expect id : " + expectId);
Log.e("download id : " + downloadId);
if (expectId == downloadId) {
//download complete.
Log.e("");
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(expectId);
Cursor cursor = downloadManager.query(query);
this.pref_schedule.edit().putBoolean(SchedulePreference.DOWNLOADING, false).apply();
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(columnIndex);
Log.e("download id status : " + status);
switch (status) {
case DownloadManager.STATUS_SUCCESSFUL:
Log.e("Download successful");
Toast.makeText(context, "download done ", Toast.LENGTH_SHORT).show();
if (this.pref_schedule.getBoolean(SchedulePreference.UPDATE_AFTER_DOWNLOAD, false)) {
this.pref_schedule.edit().putBoolean(SchedulePreference.UPDATE_AFTER_DOWNLOAD, false).apply();
try {
Process p = Runtime.getRuntime().exec((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? Constants.SYSTEM_RUN_MONKEY_A5 : Constants.SYSTEM_RUN_UIAUTOMATOR_A4) + "runtest /data/data/com.meizu.scriptkeeper/files/uitest/scripts/sk_pre_auto.jar#test001SKAuthority");
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
UpdateUtil.update(context, Constants.SD_PATH + "update.zip", false);
}
break;
default:
Toast.makeText(context, "download failed, download again ", Toast.LENGTH_SHORT).show();
long newDownLoadId;
if (this.pref_schedule.getBoolean(SchedulePreference.UPDATE_AFTER_DOWNLOAD, false)) {
this.pref_schedule.edit().putBoolean(SchedulePreference.UPDATE_AFTER_DOWNLOAD, false).apply();
newDownLoadId = Downloader.downLoadUpdate(context, pref_schedule.getString(SchedulePreference.DOWNLOAD_PATH, ""));
} else {
newDownLoadId = Downloader.downloadJar(context, pref_schedule.getString(SchedulePreference.DOWNLOAD_PATH, ""), pref_schedule.getString(SchedulePreference.SRC_FILE_NAME, ""));
}
this.pref_schedule.edit().putBoolean(SchedulePreference.DOWNLOADING, true).apply();
this.pref_schedule.edit().putLong(SchedulePreference.DOWNLOAD_ID, newDownLoadId).apply();
break;
}
}
}
}
}
|
package com.itheima.bos.web.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.itheima.bos.domain.Region;
import com.itheima.bos.domain.Subarea;
import com.itheima.bos.utils.FileUtils;
import com.itheima.bos.web.action.base.BaseAction;
/**
* 分区管理Action
*/
@Controller
@Scope("prototype")
public class SubareaAction extends BaseAction<Subarea> {
/**
* 添加分区
*/
public String add() {
subareaService.save(model);
return "list";
}
/**
* 分页查询
*/
public String pageQuery() {
DetachedCriteria subareaDC = pageBean.getDetachedCriteria();
// 从模型对象中获取提交的查询参数
String addresskey = model.getAddresskey();// 关键字
// 单表查询
if (StringUtils.isNotBlank(addresskey)) {
// 添加查询条件,根据关键字进行模糊查询
subareaDC.add(Restrictions.like("addresskey",
"%" + addresskey.trim() + "%"));
}
Region region = model.getRegion();
// 多表查询
if (region != null) {
String province = region.getProvince();
String city = region.getCity();
String district = region.getDistrict();
DetachedCriteria regionDC = subareaDC.createCriteria("region");
if (StringUtils.isNotBlank(province)) {
// 添加查询条件,根据省进行模糊查询
regionDC.add(Restrictions
.like("province", "%" + province + "%"));
}
if (StringUtils.isNotBlank(city)) {
// 添加查询条件,根据省进行模糊查询
regionDC.add(Restrictions.like("city", "%" + city + "%"));
}
if (StringUtils.isNotBlank(district)) {
// 添加查询条件,根据省进行模糊查询
regionDC.add(Restrictions
.like("district", "%" + district + "%"));
}
}
subareaService.pageQuery(pageBean);
String[] excludes = new String[] { "decidedzone", "subareas" };
this.writePageBean2Json(pageBean, excludes);
return NONE;
}
/**
* 导出分区数据到Excel文件并提供下载
*
* @throws IOException
*/
public String exportXls() throws IOException {
List<Subarea> list = subareaService.findAll();
// 使用POI将查询的数据写入Excel文件中
HSSFWorkbook workbook = new HSSFWorkbook();
// 在工作表中创建一个sheet页
HSSFSheet sheet = workbook.createSheet("分区数据");
// 创建标题行
HSSFRow headRow = sheet.createRow(0);
// 创建单元格
headRow.createCell(0).setCellValue("分区编号");
headRow.createCell(1).setCellValue("关键字");
headRow.createCell(2).setCellValue("地址");
headRow.createCell(3).setCellValue("省市区");
for (Subarea subarea : list) {
// 创建数据行
HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
String id = subarea.getId();
String addresskey = subarea.getAddresskey();
String position = subarea.getPosition();
Region region = subarea.getRegion();
dataRow.createCell(0).setCellValue(id);
dataRow.createCell(1).setCellValue(addresskey);
dataRow.createCell(2).setCellValue(position);
if (region != null) {
String province = region.getProvince();
String city = region.getCity();
String district = region.getDistrict();
String info = province + city + district;
dataRow.createCell(3).setCellValue(info);
}
}
String filename = "分区数据.xls";
String agent = ServletActionContext.getRequest().getHeader("user-agent");//浏览器类型
filename = FileUtils.encodeDownloadFilename(filename, agent );
//根据文件名称动态获得类型
String contentType = ServletActionContext.getServletContext()
.getMimeType(filename);
// 通知客户端下载文件的类型
ServletActionContext.getResponse().setContentType(contentType);
//指定以附件形式下载,指定文件名称
ServletActionContext.getResponse().setHeader("content-disposition", "attachment;filename=" + filename);
// 通过输出流向客户端浏览器写Excel文件
ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();
workbook.write(out);
return NONE;
}
/**
* 查询未分配到定区的分区,返回json
*/
public String listajax(){
List<Subarea> list = subareaService.findListNotAssociation();
String[] excludes = new String[]{"decidedzone","region"};
this.writeListBean2Json(list, excludes );
return NONE;
}
}
|
/*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.jmeter.functions;
public class FlightsContext {
private String numOfToFlights;
public String getNumOfToFlights() {
return numOfToFlights;
}
public void setNumOfToFlights(String numOfToFlights) {
this.numOfToFlights = numOfToFlights;
}
public String getNumOfRetFlights() {
return numOfRetFlights;
}
public void setNumOfRetFlights(String numOfRetFlights) {
this.numOfRetFlights = numOfRetFlights;
}
public String getTOFLIGHT() {
return TOFLIGHT;
}
public void setTOFLIGHT(String tOFLIGHT) {
TOFLIGHT = tOFLIGHT;
}
public String getTOSEGMENTID() {
return TOSEGMENTID;
}
public void setTOSEGMENTID(String tOSEGMENTID) {
TOSEGMENTID = tOSEGMENTID;
}
public String getRETFLIGHT() {
return RETFLIGHT;
}
public void setRETFLIGHT(String rETFLIGHT) {
RETFLIGHT = rETFLIGHT;
}
public String getRESEGMENTID() {
return RESEGMENTID;
}
public void setRESEGMENTID(String rESEGMENTID) {
RESEGMENTID = rESEGMENTID;
}
public String getONEWAY() {
return ONEWAY;
}
public void setONEWAY(String oNEWAY) {
ONEWAY = oNEWAY;
}
public String getIsFlightAvailable() {
return isFlightAvailable;
}
public void setIsFlightAvailable(String isFlightAvailable) {
this.isFlightAvailable = isFlightAvailable;
}
private String numOfRetFlights;
private String TOFLIGHT;
private String TOSEGMENTID;
private String RETFLIGHT;
private String RESEGMENTID;
private String ONEWAY;
private String isFlightAvailable;
@Override
public String toString() {
return "FlightsContext [numOfToFlights=" + numOfToFlights
+ ", numOfRetFlights=" + numOfRetFlights + ", TOFLIGHT="
+ TOFLIGHT + ", TOSEGMENTID=" + TOSEGMENTID + ", RETFLIGHT="
+ RETFLIGHT + ", RESEGMENTID=" + RESEGMENTID + ", ONEWAY="
+ ONEWAY + ", isFlightAvailable=" + isFlightAvailable + "]";
}
}
|
package com.example.netflix_project.src.main.models;
import androidx.annotation.NonNull;
import com.example.netflix_project.src.main.MovieInfoActivity;
import com.example.netflix_project.src.main.home.GenrePageActivity;
import com.example.netflix_project.src.main.home.MovieInterface.ActionMovieView;
import com.example.netflix_project.src.main.home.MovieInterface.ComedieMovieView;
import com.example.netflix_project.src.main.home.MovieInterface.HorrorMovieView;
import com.example.netflix_project.src.main.home.MovieInterface.InternationalMovieView;
import com.example.netflix_project.src.main.home.MovieInterface.MovieSimilarView;
import com.example.netflix_project.src.main.home.MovieInterface.RomanceMovieView;
import com.example.netflix_project.src.main.home.MovieInterface.SFMovieView;
import com.example.netflix_project.src.main.home.MovieInterface.ThrillerMovieView;
import com.example.netflix_project.src.main.interfaces.MovieGenreView;
import com.example.netflix_project.src.main.interfaces.NewGenreView;
import com.example.netflix_project.src.main.interfaces.PopularMovieView;
import com.example.netflix_project.src.main.interfaces.MovieView;
import com.example.netflix_project.src.main.interfaces.MovieInfoView;
import com.example.netflix_project.src.main.interfaces.NewMovieView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.example.netflix_project.src.ApplicationClass.getMovieService;
public class MovieService {
//
private MovieView movieView;
private NewMovieView newMovieView;
private MovieInfoView movieInfoView;
private MovieGenreView movieGenreView;
private PopularMovieView popularMovieView;
private NewGenreView newGenreView;
private HorrorMovieView horrorMovieView;
private ActionMovieView actionMovieView;
private InternationalMovieView internationalMovieView;
private ThrillerMovieView thrillerMovieView;
private RomanceMovieView romanceMovieView;
private SFMovieView sfMovieView;
private ComedieMovieView comedieMovieView;
private MovieSimilarView movieSimilarView;
MovieInfoActivity movieInfoActivity;
int mGenreNo=GenrePageActivity.num;
public static int mLastNo;
int lastNo;
public MovieService(final MovieView movieView, NewMovieView newMovieView){
this.movieView = movieView;
this.newMovieView = newMovieView;
}
public MovieService(final MovieInfoView movieInfoView){
this.movieInfoView = movieInfoView;
}
public MovieService(final MovieGenreView movieGenreView){ this.movieGenreView = movieGenreView; }
public MovieService(final NewGenreView newGenreView){
this.newGenreView = newGenreView;
}
public MovieService(final PopularMovieView popularMovieView){ this.popularMovieView = popularMovieView; }
public MovieService(final HorrorMovieView horrorMovieView){ this.horrorMovieView=horrorMovieView; }
public MovieService(final ComedieMovieView comedieMovieView){this.comedieMovieView=comedieMovieView;}
public MovieService(final RomanceMovieView romanceMovieView){this.romanceMovieView=romanceMovieView;}
public MovieService(final ActionMovieView actionMovieView){this.actionMovieView=actionMovieView;}
public MovieService(final SFMovieView sfMovieView){this.sfMovieView=sfMovieView;}
public MovieService(final ThrillerMovieView thrillerMovieView){this.thrillerMovieView=thrillerMovieView;}
public MovieService(final InternationalMovieView internationalMovieView){this.internationalMovieView = internationalMovieView;}
public MovieService(final MovieSimilarView movieSimilarView){this.movieSimilarView=movieSimilarView;}
//인기있는 영화
public void getPopularMovies(int lastNo) {
getMovieService().getPopularMovie(lastNo)
.enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(@NonNull Call<MoviesResponse> call, @NonNull Response<MoviesResponse> response) {
if (response.isSuccessful()) {
MoviesResponse moviesResponse = response.body();
if (moviesResponse != null && moviesResponse.getMovies() != null) {
int n=moviesResponse.getMovies().size();
mLastNo=moviesResponse.getMovies().get(n-1).getNo();
movieView.onPopularMovieSuccess(moviesResponse.getMovies());
} else {
movieView.onError();
}
} else {
movieView.onError();
}
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
movieView.onError();
}
});
}
//신규 영화
public void getNewMovies() {
getMovieService().getNewMovie()
.enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(@NonNull Call<MoviesResponse> call, @NonNull Response<MoviesResponse> response) {
if (response.isSuccessful()) {
MoviesResponse moviesResponse = response.body();
if (moviesResponse != null && moviesResponse.getMovies() != null) {
newMovieView.onNewMovieSuccess(moviesResponse.getMovies());
} else {
newMovieView.onError();
}
} else {
newMovieView.onError();
}
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
newMovieView.onError();
}
});
}
//영화 디테일
public void getMovieDetail() {
int n= movieInfoActivity.movie_no;
getMovieService().getMovieInfo(n)
.enqueue(new Callback<MovieInfoResponse>() {
@Override
public void onResponse(@NonNull Call<MovieInfoResponse> call, @NonNull Response<MovieInfoResponse> response) {
if (response.isSuccessful()) {
MovieInfoResponse moviesDetailResponse = response.body();
if (moviesDetailResponse != null && moviesDetailResponse.getMovies() != null) {
movieInfoView.onMovieDetailSuccess(moviesDetailResponse.getMovies());
} else {
movieInfoView.onError();
}
} else {
movieInfoView.onError();
}
}
@Override
public void onFailure(Call<MovieInfoResponse> call, Throwable t) {
movieInfoView.onError();
}
});
}
//장르별 영화
public void getMovieGenre(int mGenreNo) {
getMovieService().getGenresMvList(mGenreNo)
.enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(@NonNull Call<MoviesResponse> call, @NonNull Response<MoviesResponse> response) {
if (response.isSuccessful()) {
MoviesResponse moviesResponse = response.body();
if (moviesResponse != null && moviesResponse.getMovies() != null) {
movieGenreView.onGenreMovieSuccess(moviesResponse.getMovies());
} else {
movieGenreView.onError();
}
} else {
movieGenreView.onError();
}
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
movieGenreView.onError();
}
});
}
//개별 장르 영화
public void getGenreMovie(final int mGenreNo) {
getMovieService().getGenresMvList(mGenreNo)
.enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(@NonNull Call<MoviesResponse> call, @NonNull Response<MoviesResponse> response) {
if (response.isSuccessful()) {
MoviesResponse moviesResponse = response.body();
if (moviesResponse != null && moviesResponse.getMovies() != null) {
if(mGenreNo==2)
comedieMovieView.onComedieSuccess(moviesResponse.getMovies());
if(mGenreNo==3)
internationalMovieView.onInternationalSuccess(moviesResponse.getMovies());
if(mGenreNo==4)
sfMovieView.onSFSuccess(moviesResponse.getMovies());
if(mGenreNo==5)
thrillerMovieView.onThriSuccess(moviesResponse.getMovies());
if(mGenreNo==6)
actionMovieView.onActionSuccess(moviesResponse.getMovies());
if(mGenreNo==9)
horrorMovieView.onHorrorSuccess(moviesResponse.getMovies());
if(mGenreNo==13)
romanceMovieView.onRomaceSuccess(moviesResponse.getMovies());
}
else {
movieGenreView.onError();
}
} else {
movieGenreView.onError();
}
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
movieGenreView.onError();
}
});
}
//장르별 인기영화
public void getPopularGenreMovie() {
getMovieService().getGenreSelectPopularMvList(mGenreNo)
.enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(@NonNull Call<MoviesResponse> call, @NonNull Response<MoviesResponse> response) {
if (response.isSuccessful()) {
MoviesResponse moviesResponse = response.body();
if (moviesResponse != null && moviesResponse.getMovies() != null) {
popularMovieView.onGenrePopularMovieSuccess(moviesResponse.getMovies());
} else {
popularMovieView.onError();
}
} else {
popularMovieView.onError();
}
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
popularMovieView.onError();
}
});
}
//장르별 신규영화
public void getNewGenreMovie() {
getMovieService().getGenreSelectMvNewList(mGenreNo)
.enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(@NonNull Call<MoviesResponse> call, @NonNull Response<MoviesResponse> response) {
if (response.isSuccessful()) {
MoviesResponse moviesResponse = response.body();
if (moviesResponse != null && moviesResponse.getMovies() != null) {
newGenreView.onGenreNewMovieSuccess(moviesResponse.getMovies());
} else {
newGenreView.onError();
}
} else {
newGenreView.onError();
}
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
newGenreView.onError();
}
});
}
//비슷한 영화 추천
public void getSimilarMovie(int contentNo) {
getMovieService().getMovieSimilarContentsList(contentNo)
.enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(@NonNull Call<MoviesResponse> call, @NonNull Response<MoviesResponse> response) {
if (response.isSuccessful()) {
MoviesResponse moviesResponse = response.body();
if (moviesResponse != null && moviesResponse.getMovies() != null) {
movieSimilarView.onMovieSimilarSuccess(moviesResponse.getMovies());
} else {
movieSimilarView.onError();
}
} else {
movieSimilarView.onError();
}
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
newGenreView.onError();
}
});
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.