text
stringlengths 10
2.72M
|
|---|
package pers.mine.scratchpad.base.classload;
/**
* 类代码块初始化顺序
*/
public class ClassLoadInitOrderTest {
static {
System.out.println("ClassLoadInitOrderTest静态代码块");
}
public static void main(String[] args) {
new SubClass();
}
static class SuperClass {
static {
System.out.println("父类静态代码块");
}
public SuperClass() {
System.out.println("父类构造方法.");
}
{
System.out.println("父类代码块");
}
}
static class SubClass extends SuperClass {
static {
System.out.println("子类静态代码块");
}
public SubClass() {
System.out.println("子类构造方法.");
}
{
System.out.println("子类代码块");
}
}
}
|
package shoplistgener.domain;
/**
* Enum Types associated with an ingredient
*/
public enum Unit {
DL, ML, G, PCS, CL, KG
}
|
package org.softRoad.models;
import org.softRoad.models.query.QueryUtils;
import javax.persistence.Table;
@Table(name = "procedure_city")
public class ProcedureCity {
public final static String PROCEDURE_ID = "procedure_id";
public final static String CITY_ID = "city_id";
public static String fields(String fieldName, String ... fieldNames) {
return QueryUtils.fields(ProcedureCity.class, fieldName, fieldNames);
}
}
|
package bspq21_e4.ParkingManagment.Classes;
import static org.junit.Assert.*;
import org.databene.contiperf.junit.ContiPerfRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bspq21_e4.ParkingManagement.server.data.Parking;
import bspq21_e4.ParkingManagement.server.data.Slot;
import bspq21_e4.ParkingManagement.server.data.SlotAvailability;
import junit.framework.JUnit4TestAdapter;
public class ParkingTest {
private Parking P1, P2;
final Logger logger = LoggerFactory.getLogger(SlotTest.class);
static int iteration = 0;
@Rule public ContiPerfRule rule = new ContiPerfRule();
public static junit.framework.Test suite() {
return new JUnit4TestAdapter(SlotTest.class);
}
@Before
public void setUp() {
P1 = new Parking(1, "Getxo", 100, 50, 40, 2);
P2 = new Parking(2, "Leioa", 240, 175, 35, 2);
}
@Test
public void parkingClassTest() {
assertEquals(P1.getClass(), Parking.class);
assertEquals(P2.getClass(), Parking.class);
}
@Test
public void getParkingAvailableSlotsTest() {
assertEquals(50, P1.getAvailableSlots());
assertEquals(175, P2.getAvailableSlots());
}
@Test
public void getParkingnSlotsTest() {
assertEquals(100, P1.getnSlots());
assertEquals(245, P2.getnSlots());
}
@Test
public void getParkingFloorsTest() {
assertEquals(2, P1.getFloors());
assertEquals(2, P2.getFloors());
}
@Test
public void getParkingIdTest() {
assertEquals(1, P1.getId());
assertEquals(2, P2.getId());
}
@Test
public void getParkingNameTest() {
assertEquals("Getxo", P1.getNombre());
assertEquals("Leioa", P2.getNombre());
}
@Test
public void getParkingOccupiedSlotsTest() {
assertEquals(40, P1.getOccupiedSlots());
assertEquals(35, P2.getOccupiedSlots());
}
@Test
public void setParkingAvailableSlotsTest() {
P1.setAvailableSlots(70);
P2.setAvailableSlots(150);
assertEquals(70, P1.getAvailableSlots());
assertEquals(150, P2.getAvailableSlots());
}
@Test
public void setParkingnSlotsTest() {
P1.setnSlots(130);
P2.setnSlots(270);
assertEquals(130, P1.getnSlots());
assertEquals(270, P2.getnSlots());
}
@Test
public void setParkingFloorsTest() {
P1.setFloors(1);
P2.setFloors(3);
assertEquals(1, P1.getFloors());
assertEquals(3, P2.getFloors());
}
@Test
public void setParkingIdTest() {
P1.setId(3);
P2.setId(4);
assertEquals(3, P1.getId());
assertEquals(4, P2.getId());
}
@Test
public void setParkingNameTest() {
P1.setNombre("Las Arenas");
P2.setNombre("Santurtzi");
assertEquals("Las Arenas", P1.getNombre());
assertEquals("Santurtzi", P2.getNombre());
}
@Test
public void setParkingOccupiedSlotsTest() {
P1.setOccupiedSlots(30);
P2.setOccupiedSlots(50);
assertEquals(30, P1.getOccupiedSlots());
assertEquals(50, P2.getOccupiedSlots());
}
}
|
package com.hamrahvas.webservice;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.hamrahvas.webservice package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _String_QNAME = new QName("http://tempuri.org/", "string");
private final static QName _ArrayOfString_QNAME = new QName("http://tempuri.org/", "ArrayOfString");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.hamrahvas.webservice
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link MessageUploadResponse }
*
*/
public MessageUploadResponse createMessageUploadResponse() {
return new MessageUploadResponse();
}
/**
* Create an instance of {@link MessageListUploadWithServiceId }
*
*/
public MessageListUploadWithServiceId createMessageListUploadWithServiceId() {
return new MessageListUploadWithServiceId();
}
/**
* Create an instance of {@link ArrayOfString }
*
*/
public ArrayOfString createArrayOfString() {
return new ArrayOfString();
}
/**
* Create an instance of {@link ArrayOfInt }
*
*/
public ArrayOfInt createArrayOfInt() {
return new ArrayOfInt();
}
/**
* Create an instance of {@link MessageUploadWithServiceIdResponse }
*
*/
public MessageUploadWithServiceIdResponse createMessageUploadWithServiceIdResponse() {
return new MessageUploadWithServiceIdResponse();
}
/**
* Create an instance of {@link MessageUpload }
*
*/
public MessageUpload createMessageUpload() {
return new MessageUpload();
}
/**
* Create an instance of {@link MessageListUpload }
*
*/
public MessageListUpload createMessageListUpload() {
return new MessageListUpload();
}
/**
* Create an instance of {@link MessageUploadWithServiceId }
*
*/
public MessageUploadWithServiceId createMessageUploadWithServiceId() {
return new MessageUploadWithServiceId();
}
/**
* Create an instance of {@link MessageListUploadWithServiceIdResponse }
*
*/
public MessageListUploadWithServiceIdResponse createMessageListUploadWithServiceIdResponse() {
return new MessageListUploadWithServiceIdResponse();
}
/**
* Create an instance of {@link MessageListUploadResponse }
*
*/
public MessageListUploadResponse createMessageListUploadResponse() {
return new MessageListUploadResponse();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://tempuri.org/", name = "string")
public JAXBElement<String> createString(String value) {
return new JAXBElement<String>(_String_QNAME, String.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link ArrayOfString }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://tempuri.org/", name = "ArrayOfString")
public JAXBElement<ArrayOfString> createArrayOfString(ArrayOfString value) {
return new JAXBElement<ArrayOfString>(_ArrayOfString_QNAME, ArrayOfString.class, null, value);
}
}
|
package com.emed.shopping.service.admin.goods.impl;
import com.emed.shopping.base.BaseServiceImpl;
import com.emed.shopping.dao.model.admin.goods.ShopGoodsSpecProperty;
import com.emed.shopping.service.admin.goods.GoodsSpecPropertyService;
import org.springframework.stereotype.Service;
/**
* @Author: 周润斌
* @Date: create in 上午 17:35 2018/1/16 0016
* @Description:
*/
@Service
public class GoodsSpecPropertyServiceImpl extends BaseServiceImpl<ShopGoodsSpecProperty> implements GoodsSpecPropertyService{
}
|
package cn.auto.core.annotation;
/**
* Created by chenmeng on 2016/4/26.
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR})
public @interface Task {
String[] taskName() default {};
String[] paras() default {};
}
|
/*
* 4.5.2 Omikuji
* 乱数と条件分岐を使って、「大吉」「中吉」「小吉」「凶」を表示するプログラムを作りましょう。
* 大吉のときだけ、タートルの絵(星など)を描くようにしましょう。
*/
public class Omikuji extends Turtle{
public static void main(String[] args){
Turtle.startTurtle(new Omikuji());
}
public void start(){
int x=random(4);
if(x==1){
System.out.println("大吉です");
rt(144);
fd(100);
rt(144);
fd(100);
rt(144);
fd(100);
rt(144);
fd(100);
rt(144);
fd(100);
}else if(x == 2){
System.out.println("中吉です");
}else if(x==3){
System.out.println("小吉です");
}else if(x==4){
System.out.println("凶です");
}
}
}
|
package contacts;
import suffixtree.SuffixIndex;
import suffixtree.SuffixTrie;
import suffixtree.SuffixTrieNode;
import javax.swing.*;
import java.sql.*;
import java.util.ArrayList;
/*
ContactDB is responsible for the communication between the GUI and the database. Other 'DB' classes have static
implementations of their methods as opposed to this one. The way to use ContactDB is to create an instance of it,
and then you can start communicating with the database via the contained methods. As can be seen instance variables are
present inside here, so anything received from the database needs to be stored here and in a location for the GUI to
access it. This implementation is flawed and a better option was later chosen, and is observable in UploadDB, TemplateDB and
LogDB. As it stands, the class works despite some of the flaws this approach has, so it will be staying this way.
*/
public class ContactDB {
SuffixTrie sf; // stores names of contacts exclusively for searching purposes, does not contain contacts data
DefaultListModel<Contact> listModel;
public ContactDB() {
extractContactsFromDB();
}
public DefaultListModel getListModel() {
return listModel;
}
/**
* Will Query the database to get all the contacts. The contacts are then added to the suffixTrie and saved to listModel
*/
public void extractContactsFromDB() {
String sql = "SELECT * FROM contacts WHERE isDeleted = false ORDER BY givenName";
try (Connection conn = this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
sf = new SuffixTrie();
listModel = new DefaultListModel();
while (rs.next()) {
Contact c = new Contact(rs.getInt("contact_ID"), rs.getString("givenName"),
rs.getString("surname"), rs.getString("email"),
rs.getString("phone"));
sf.insert(rs.getString("givenName") + " " + rs.getString("surname"), c);
listModel.addElement(c);
}
} catch (SQLException e) {
System.out.println(e);
}
}
/**
* Validates and connects to the local database located in url.
*/
private Connection connect() {
// SQLite connection string
String url = "jdbc:sqlite:data/database.db";
Connection conn = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
//may still need, up in the air so will keep for prosperity sake
public static void createNewDatabase(String fileName) {
String url = "jdbc:sqlite:C:/sqlite/db/" + fileName;
try (Connection conn = DriverManager.getConnection(url)) {
if (conn != null) {
DatabaseMetaData meta = conn.getMetaData();
System.out.println("The driver name is " + meta.getDriverName());
System.out.println("A new database has been created.");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
/**
* Will search the SuffixTrie for names that could associate with the search term and add the results to the ContactPanel
*
* @param search The search term to find in the Suffix Trie
*/
public void searchForContact(String search) {
// searchField defaults to Search... when focus is lost, to ensure the SuffixTrie does not search for this term
// and display no results a catch is here to prevent this error
if (search.length() == 0 || search.equals("Search...")) {
extractContactsFromDB();
} else {
ArrayList<SuffixIndex> startIndexes;
listModel = new DefaultListModel<>();
SuffixTrieNode sn = sf.get(search);
if (sn != null) {
startIndexes = sn.getData().getStartIndexes();
for (SuffixIndex s : startIndexes) {
//Prevents duplicate contacts being displayed as a node may contain many subStrings of itself
if (!listModel.contains(s.getObj())) {
listModel.addElement((Contact) s.getObj());
}
}
} else {
//When no contacts are found, display a dummy contact. In the panel this is not selectable.
listModel = new DefaultListModel<>();
listModel.addElement(new Contact(-1, "No Related Contacts Found", "", "", ""));
}
}
}
/**
* When a contact is edited and a save is requested, this will update the database, regenerate the
* contact lists and display all contacts
*
* @param givenName Edited givenName of the contact
* @param surname Edited surname of the contact
* @param email Edited email of the contact
* @param phone Edited phone of the contact
*/
public void updateContact(String givenName, String surname, String email, String phone, int contact_ID) {
String sql = "UPDATE contacts SET givenName = ? , "
+ "surname = ?, "
+ "email = ?, "
+ "phone = ? "
+ "WHERE contact_ID = ?";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
// set the corresponding param
pstmt.setString(1, givenName);
pstmt.setString(2, surname);
pstmt.setString(3, email);
pstmt.setString(4, phone);
pstmt.setInt(5, contact_ID);
// update
pstmt.executeUpdate();
extractContactsFromDB();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
/**
* When a new contact is saved, this will update the database, regenerate the contact lists and display all contacts
*
* @param givenName New contact given name
* @param surname New contact surname
* @param email New contact email
* @param phone New contact phone
*/
public int addContact(String givenName, String surname, String email, String phone) {
String sql = "INSERT INTO contacts(givenName,surname, email, phone) VALUES(?,?,?,?)";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
pstmt.setString(1, givenName);
pstmt.setString(2, surname);
pstmt.setString(3, email);
pstmt.setString(4, phone);
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
extractContactsFromDB();
return rs.getInt(1);
} catch (SQLException e) {
System.out.println(e.getMessage());
return -1;
}
}
/**
* This will delete the contact currently selected. The currently selected contact is determined by
* the last contact that was pressed. If no contact has ever been pressed, then the option should
* never be presented to the user
*/
public void deleteContact(int contact_ID) {
String sql = "UPDATE contacts SET isDeleted = ? WHERE contact_ID = ?";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
// set the corresponding param
pstmt.setBoolean(1, true);
pstmt.setInt(2, contact_ID);
// execute the delete statement
pstmt.executeUpdate();
extractContactsFromDB();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
/**
* This will query the database for the details of an individual contact
*
* @param contactID The Contact ID of the contact to search for
* @return an instance of the contact
*/
public Contact getContactDetails(int contactID) {
String sql = "SELECT * FROM contacts WHERE contact_ID = ?";
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, contactID);
ResultSet rs = pstmt.executeQuery();
return new Contact(rs.getInt("contact_ID"), rs.getString("givenName"),
rs.getString("surname"), rs.getString("email"),
rs.getString("phone"));
} catch (SQLException e) {
return null;
}
}
}
|
//
// Decompiled by Procyon v0.5.36
//
package com.davivienda.sara.tablas.provisionhost.servicio;
import javax.persistence.Query;
import java.util.Collection;
import java.util.Calendar;
import javax.persistence.TransactionRequiredException;
import com.davivienda.sara.base.exception.EntityServicioExcepcion;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.davivienda.sara.entitys.Cajero;
import javax.persistence.EntityManager;
import com.davivienda.sara.base.AdministracionTablasInterface;
import com.davivienda.sara.entitys.ProvisionHost;
import com.davivienda.sara.base.BaseEntityServicio;
public class ProvisionHostServicio extends BaseEntityServicio<ProvisionHost> implements AdministracionTablasInterface<ProvisionHost>
{
public ProvisionHostServicio(final EntityManager em) {
super(em, ProvisionHost.class);
}
public void grabarProvisionHost(final ProvisionHost provisionHost) throws EntityServicioExcepcion {
try {
if (provisionHost.getCajero().getActivo() == 1) {
provisionHost.setCajero((Cajero)this.em.merge((Object)provisionHost.getCajero()));
this.em.persist((Object)provisionHost);
}
}
catch (IllegalStateException ex) {
Logger.getLogger("globalApp").log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (IllegalArgumentException ex2) {
Logger.getLogger("globalApp").log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2);
throw new EntityServicioExcepcion(ex2);
}
catch (TransactionRequiredException ex3) {
Logger.getLogger("globalApp").log(Level.SEVERE, "Se requiere un entorno de transacci\u00f3n ", (Throwable)ex3);
throw new EntityServicioExcepcion((Throwable)ex3);
}
}
public Collection<ProvisionHost> getProvisionHostRangoFecha(final Calendar fechaInicial, final Calendar fechaFinal) throws EntityServicioExcepcion {
Collection<ProvisionHost> regs = null;
try {
Query query = null;
query = this.em.createNamedQuery("ProvisionHost.RangoFecha");
query.setParameter("fechaInicial", (Object)fechaInicial.getTime());
query.setParameter("fechaFinal", (Object)fechaFinal.getTime());
query.setHint("javax.persistence.cache.storeMode", (Object)"REFRESH");
regs = (Collection<ProvisionHost>)query.getResultList();
}
catch (IllegalStateException ex) {
Logger.getLogger("globalApp").log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (IllegalArgumentException ex2) {
Logger.getLogger("globalApp").log(Level.WARNING, "El par\u00e1metro no es v\u00e1lido ", ex2);
throw new EntityServicioExcepcion(ex2);
}
return regs;
}
}
|
package com.pan.Concurrent.t5;
/**
* 当一个线程执行synchronized(非this对象X)时,另一个线程执行x对象中的同步方法或者同步代码块时,成同步效果
*
*/
public class Runt5 {
public static void main(String[] args) throws Exception{
Servicet5 servicet5=new Servicet5();
MyObjectt5 myObjectt5=new MyObjectt5();
ThreadAt5 a=new ThreadAt5(myObjectt5,servicet5);
a.setName("a");
a.start();
Thread.sleep(100);
ThreadBt5 B=new ThreadBt5(myObjectt5);
B.setName("B");
B.start();
}
}
|
package gameView;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import gameController.Card;
public class CardImages
{
//array de arrays, para conter as imagens de jogares/armas/quartos respectivamente
//porque não podem ser final?
private final static BufferedImage playerImages[] = new BufferedImage[6];
private final static BufferedImage weaponImages[] = new BufferedImage[6];
private final static BufferedImage roomImages[] = new BufferedImage[9];
private static BufferedImage NaN;
//private static final BufferedImage NaN;
public static BufferedImage getImage(Card c)
{
if(c == null)
{
return NaN;
}
try
{
switch(c.type)
{
case SUSPECT:
System.out.println(playerImages[c.id].toString());
return playerImages[c.id];
case WEAPON:
System.out.println(weaponImages[c.id].toString());
return weaponImages[c.id];
case ROOM:
System.out.println(roomImages[c.id].toString());
return roomImages[c.id];
}
}catch(IndexOutOfBoundsException e)
{
System.out.println("Não existe imagem para carta procurada:" + e.getMessage());
}
return NaN;
}
//bloco de inicialização static
static{
try
{
//imagem nula, usada em casos de exceção
NaN = ImageIO.read(new File("assets/NaN.jpg"));
//primeiro array contem imagens de jogadores
//"Reverendo Green", "Coronel Mustard", "Senhora Peacock", "Professor Plum", "Senhorita Scarlet","Senhora White"
playerImages[0] = ImageIO.read(new File("assets/Suspeitos/green.jpg"));
playerImages[1] = ImageIO.read(new File("assets/Suspeitos/mustard.jpg"));
playerImages[2] = ImageIO.read(new File("assets/Suspeitos/peacock.jpg"));
playerImages[3] = ImageIO.read(new File("assets/Suspeitos/plum.jpg"));
playerImages[4] = ImageIO.read(new File("assets/Suspeitos/scarlet.jpg"));
playerImages[5] = ImageIO.read(new File("assets/Suspeitos/white.jpg"));
//segundo contem armas
//"Corda", "Cano de Chumbo", "Faca", "Chave Inglesa", "Castiçal", "Revólver"
weaponImages[0] = ImageIO.read(new File("assets/Armas/Corda.jpg"));
weaponImages[1] = ImageIO.read(new File("assets/Armas/Cano.jpg"));
weaponImages[2] = ImageIO.read(new File("assets/Armas/Faca.jpg"));
weaponImages[3] = ImageIO.read(new File("assets/Armas/ChaveInglesa.jpg"));
weaponImages[4] = ImageIO.read(new File("assets/Armas/Castical.jpg"));
weaponImages[5] = ImageIO.read(new File("assets/Armas/Revolver.jpg"));
//"Cozinha", "Sala de Jantar", "Sala de Estar", "Sala de Música", "Entrada", "Jardim de Inverno", "Salão de Jogos", "Biblioteca", "Escritório"
roomImages[0] = ImageIO.read(new File("assets/Comodos/Cozinha.jpg"));
roomImages[1] = ImageIO.read(new File("assets/Comodos/SalaDeJantar.jpg"));
roomImages[2] = ImageIO.read(new File("assets/Comodos/SalaDeEstar.jpg"));
roomImages[3] = ImageIO.read(new File("assets/Comodos/SalaDeMusica.jpg"));
roomImages[4] = ImageIO.read(new File("assets/Comodos/Entrada.jpg"));
roomImages[5] = ImageIO.read(new File("assets/Comodos/JardimInverno.jpg"));
roomImages[6] = ImageIO.read(new File("assets/Comodos/SalaoDeJogos.jpg"));
roomImages[7] = ImageIO.read(new File("assets/Comodos/Biblioteca.jpg"));
roomImages[8] = ImageIO.read(new File("assets/Comodos/Escritorio.jpg"));
}catch (IOException e)
{
System.out.println("Incapaz de abrir imagem. Erro:" + e.getMessage());
System.exit(1);
}
}
}
|
package com.java8.comparator;
import com.java8.behaviourparameterization.Apple;
import com.java8.behaviourparameterization.Color;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ChainingComparatorJava8 {
public static void main(String[] args) {
Apple a1 = new Apple(100, Color.RED);
Apple a2 = new Apple(117, Color.GREEN);
Apple a3 = new Apple(105, Color.RED);
Apple a4 = new Apple(103, Color.BROWN);
Apple a5 = new Apple(108, Color.RED);
Apple a6 = new Apple(140, Color.RED);
Apple a7 = new Apple(116, Color.GREEN);
Apple a8 = new Apple(106, Color.GREEN);
Apple a9 = new Apple(137, Color.RED);
Apple a10 = new Apple(134, Color.GREEN);
List<Apple> listOfApples = new ArrayList<>();
listOfApples.add(a1);
listOfApples.add(a2);
listOfApples.add(a3);
listOfApples.add(a4);
listOfApples.add(a5);
listOfApples.add(a6);
listOfApples.add(a7);
listOfApples.add(a8);
listOfApples.add(a9);
listOfApples.add(a10);
System.out.println("List of apples before any sorting applied");
printApplesList(listOfApples);
// First filter by color if color is same
listOfApples.sort(Comparator.comparing(Apple::getColor));
System.out.println("\nList of apples with color sorting");
printApplesList(listOfApples);
System.out.println("\nList of apples with color sorting and if color is same sorting by weight");
listOfApples.sort(Comparator.comparing(Apple::getColor).thenComparing(Apple::getWeight));
printApplesList(listOfApples);
}
private static void printApplesList(List<Apple> listOfApples) {
listOfApples.forEach(apple -> {
System.out.print(apple.getColor() + " " + apple.getWeight() + ", ");
});
}
}
|
package com.example.gamedb.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import com.example.gamedb.R;
import com.example.gamedb.ui.fragment.GameDetailFragment;
import com.example.gamedb.ui.fragment.GameListFragment;
import static com.example.gamedb.ui.fragment.GameListFragment.GAME_ID;
public class GameDetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_detail);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
Intent intent = getIntent();
if (intent.hasExtra(GAME_ID)) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_game_detail_container, GameDetailFragment.newInstance(
intent.getIntExtra(GAME_ID, -1)))
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.menu_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
/*
* CZY_jd_updatecourseexperimentalenvironment.java
*
* Created on __DATE__, __TIME__
*/
package czy.view;
import global.dao.Databaseconnection;
import java.sql.Connection;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import czy.dao.Courseexperimentalenvironmentaccess;
import czy.model.Courseexperimentalenvironment;
/**
*
* @author __USER__
*/
public class CZY_jd_updatecourseexperimentalenvironment extends
javax.swing.JDialog {
private Courseexperimentalenvironment ce;
/** Creates new form CZY_jd_updatecourseexperimentalenvironment */
public CZY_jd_updatecourseexperimentalenvironment(java.awt.Frame parent,
boolean modal) {
super(parent, modal);
initComponents();
}
public CZY_jd_updatecourseexperimentalenvironment(java.awt.Frame parent,
boolean modal, Courseexperimentalenvironment ce) {
super(parent, modal);
initComponents();
this.ce = ce;
//取得实验环境内容
String experimentalenvironment = ce.getExperimentalenvironment();
//如果实验环境不为空,设置文本框的内容为实验环境
if (experimentalenvironment != null)
jTextField1.setText(experimentalenvironment);
// 设置界面居中显示
this.setLocationRelativeTo(null);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// GEN-BEGIN:initComponents
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("\u5b9e\u9a8c\u73af\u5883\u8bbe\u7f6e");
jLabel1.setText("\u5b9e\u9a8c\u73af\u5883\uff1a");
jButton1.setText("\u786e\u5b9a");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("\u53d6\u6d88");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(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()
.addContainerGap()
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addComponent(
jLabel1)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(
jTextField1,
javax.swing.GroupLayout.DEFAULT_SIZE,
276,
Short.MAX_VALUE)
.addContainerGap())
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(
jButton1)
.addGap(72, 72,
72)
.addComponent(
jButton2)
.addGap(90, 90,
90)))));
layout.setVerticalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(
jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(33, 33, 33)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1))
.addContainerGap()));
pack();
}// </editor-fold>
// GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String experimentalenvironment = jTextField1.getText();
ce.setExperimentalenvironment(experimentalenvironment);
Connection con = null;
try {
con = Databaseconnection.getconnection();
Courseexperimentalenvironmentaccess.updateexperimentalenvironment(
con, ce);
this.dispose();
} catch (Exception e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(this, "实验环境设置失败,请联系系统管理员!");
e.printStackTrace();
} finally {
try {
if (!con.isClosed())
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
}
/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
CZY_jd_updatecourseexperimentalenvironment dialog = new CZY_jd_updatecourseexperimentalenvironment(
new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// GEN-BEGIN:variables
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
|
/***
* @file SitiosDB.java
* @author Francsico Javier Feria Coca
* Descripcion: Aplicacion final del curso Android impartido por @exitae
* Alumno: Francsico Javier Feria Coca
* Notas: En comentarios de codigo quedan excluido acentos y caracteres especiales
* para evitar errores con diferentes codificaciones de caracteres
*/
package info.javierferia.app.misSitios.db;
import android.provider.BaseColumns;
/**
* Clase estructura de la Base de datos
*
*/
public class SitiosDB {
/* Nombre de la Base de Datos */
public static final String DB_NAME = "mis_sitios.db";
/* Version de la Base de Datos */
public static final int DB_VERSION = 1;
/* Constructor, Esta clase no debe ser instanciada */
private SitiosDB () {}
/* Definicion de la tabla posts */
public static final class TSitios implements BaseColumns {
/* Constructor, Esta clase no debe ser instanciada */
private TSitios () {}
/* Orden por defecto */
public static final String DEFAULT_SORT_ORDER = "_ID ASC";
/* Abstraccion de los nombres de campos y tablas */
public static final String NOMBRE_TABLA = "lugar";
public static final String _ID = "_id";
public static final String NOMBRE = "nombre";
public static final String DESCRIPCION = "descripcion";
public static final String LATITUD = "latitud";
public static final String LONGITUD = "longitud";
public static final String FOTO = "foto";
public static final String _COUNT = "6";
} // private static final class Posts
} // Class
|
package com.davivienda.sara.administracion.session;
import com.davivienda.sara.jobs.JobInformeDiferenciasRemote;
import com.davivienda.sara.jobs.JobDaliAutoRemote;
import com.davivienda.sara.jobs.JobCargueDiariosRemote;
import com.davivienda.sara.jobs.JobInformeDiferenciasHome;
import com.davivienda.sara.jobs.JobDaliAutoHome;
import java.util.Date;
import com.davivienda.utilidades.SchedulerInfo;
import com.davivienda.sara.jobs.JobCargueDiariosHome;
import org.quartz.CronExpression;
import com.davivienda.sara.entitys.config.ConfModulosAplicacionPK;
import com.davivienda.sara.entitys.config.ConfModulosAplicacion;
import javax.naming.InitialContext;
import java.security.SecureRandom;
import javax.annotation.PreDestroy;
import javax.management.MBeanServer;
import javax.management.JMException;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.util.Enumeration;
import java.util.Arrays;
import java.io.IOException;
import java.util.logging.Handler;
import java.util.logging.Formatter;
import java.util.logging.SimpleFormatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import com.davivienda.sara.base.BaseServicio;
import com.davivienda.sara.config.SaraConfig;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.ejb.Stateless;
@Stateless
public class SaraConfiguracionSessionBean implements SaraConfiguracionSession
{
@PersistenceContext
private EntityManager em;
private static SaraConfig configApp;
private BaseServicio servicio;
private static FileHandler fh;
private static FileHandler fhAcceso;
private static ConsoleHandler ch;
private static MemoryHandler mh;
private static MemoryHandler mhAcceso;
@Override
public void iniciarConfiguracion(final String archivoPropiedadesConfiguracion) {
if (SaraConfiguracionSessionBean.configApp == null) {
try {
SaraConfiguracionSessionBean.configApp = SaraConfig.obtenerInstancia(archivoPropiedadesConfiguracion, this.em);
this.servicio = new BaseServicio();
this.crearLoggerAplicacion();
this.imprimirConfiguracion();
}
catch (IllegalAccessException ex) {
Logger.getLogger(SaraConfiguracionSessionBean.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
}
catch (Exception ex2) {
Logger.getLogger(SaraConfiguracionSessionBean.class.getName()).log(Level.SEVERE, ex2.getMessage(), ex2);
}
}
else {
SaraConfiguracionSessionBean.configApp.cargarParametrosDB();
this.imprimirConfiguracion();
}
this.cargarTareasProgramadas();
}
@Override
public SaraConfig getAppConfig() {
return SaraConfiguracionSessionBean.configApp;
}
private void crearLoggerAplicacion() {
Level nivelLog = Level.ALL;
try {
SaraConfiguracionSessionBean.configApp.loggerApp.setLevel(Level.ALL);
SaraConfiguracionSessionBean.configApp.loggerAcceso.setLevel(Level.ALL);
if (SaraConfiguracionSessionBean.ch == null && SaraConfiguracionSessionBean.configApp.CONFIGURACION_LOG_MOSTRAR_LOG_CONSOLA > 0) {
(SaraConfiguracionSessionBean.ch = new ConsoleHandler()).setFormatter(new SimpleFormatter());
SaraConfiguracionSessionBean.ch.setLevel(nivelLog);
SaraConfiguracionSessionBean.configApp.loggerApp.addHandler(SaraConfiguracionSessionBean.ch);
}
if (SaraConfiguracionSessionBean.fh == null) {
(SaraConfiguracionSessionBean.fh = new FileHandler(SaraConfiguracionSessionBean.configApp.CONFIGURACION_LOG_DIRECTORIO_LOGS.trim() + "sara.log", SaraConfiguracionSessionBean.configApp.TAMANO_ARCHIVO_LOG, 5, true)).setFormatter(new SimpleFormatter());
SaraConfiguracionSessionBean.fh.setLevel(nivelLog);
SaraConfiguracionSessionBean.configApp.loggerApp.addHandler(SaraConfiguracionSessionBean.fh);
}
if (SaraConfiguracionSessionBean.fhAcceso == null) {
(SaraConfiguracionSessionBean.fhAcceso = new FileHandler(SaraConfiguracionSessionBean.configApp.CONFIGURACION_LOG_DIRECTORIO_LOGS.trim() + "sara_acceso.log", SaraConfiguracionSessionBean.configApp.TAMANO_ARCHIVO_LOG, 5, true)).setFormatter(new SimpleFormatter());
SaraConfiguracionSessionBean.fhAcceso.setLevel(nivelLog);
SaraConfiguracionSessionBean.configApp.loggerAcceso.addHandler(SaraConfiguracionSessionBean.fhAcceso);
}
}
catch (IOException ex) {
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.SEVERE, ex.getMessage(), ex);
System.err.println("No se puede cargar la configuraci\u00f3n de logs : " + ex.getMessage());
ex.printStackTrace();
}
catch (SecurityException ex2) {
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.SEVERE, ex2.getMessage(), ex2);
System.err.println("No se puede cargar la configuraci\u00f3n de logs : " + ex2.getMessage());
ex2.printStackTrace();
}
finally {
if (SaraConfiguracionSessionBean.fh != null) {
if (SaraConfiguracionSessionBean.mh == null) {
(SaraConfiguracionSessionBean.mh = new MemoryHandler(SaraConfiguracionSessionBean.fh, 2000, Level.ALL)).setLevel(nivelLog);
}
SaraConfiguracionSessionBean.configApp.loggerApp.info("<<< SARA 12.2.8.0 >>>");
}
if (SaraConfiguracionSessionBean.fhAcceso != null && SaraConfiguracionSessionBean.mhAcceso == null) {
(SaraConfiguracionSessionBean.mhAcceso = new MemoryHandler(SaraConfiguracionSessionBean.fhAcceso, 2000, Level.ALL)).setLevel(nivelLog);
}
try {
nivelLog = Level.parse(SaraConfiguracionSessionBean.configApp.CONFIGURACION_LOG_NIVEL_LOG);
}
catch (Exception ex3) {
nivelLog = Level.ALL;
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.SEVERE, "No se puede asignar el nivel del log , se asigno por defecto en ALL", ex3);
}
this.cambiarPropiedadLevel("ALL");
SaraConfiguracionSessionBean.configApp.loggerApp.info("Se inici\u00f3 el Log en " + SaraConfiguracionSessionBean.configApp.CONFIGURACION_LOG_DIRECTORIO_LOGS + "sara.log con Nivel " + SaraConfiguracionSessionBean.configApp.loggerApp.getLevel().toString());
SaraConfiguracionSessionBean.configApp.loggerApp.info("Se inici\u00f3 Parametro TIEMPO_SESION " + SaraConfiguracionSessionBean.configApp.TIEMPO_SESION);
SaraConfiguracionSessionBean.configApp.loggerApp.info("Se inici\u00f3 Parametro TIEMPO_LOGIN " + SaraConfiguracionSessionBean.configApp.TIEMPO_LOGIN);
SaraConfiguracionSessionBean.configApp.loggerApp.info("Se inici\u00f3 el Log de Acceso en " + SaraConfiguracionSessionBean.configApp.CONFIGURACION_LOG_DIRECTORIO_LOGS + "sara_acceso.log con Nivel " + SaraConfiguracionSessionBean.configApp.loggerAcceso.getLevel().toString());
SaraConfiguracionSessionBean.configApp.loggerAcceso.info("Se inici\u00f3 el Log de Acceso en " + SaraConfiguracionSessionBean.configApp.CONFIGURACION_LOG_DIRECTORIO_LOGS + "sara_acceso.log con Nivel " + SaraConfiguracionSessionBean.configApp.loggerAcceso.getLevel().toString());
}
}
private void imprimirConfiguracion() {
SaraConfiguracionSessionBean.configApp.loggerApp.config("<<<<<< Valores de configuracion >>>>>>");
if (SaraConfiguracionSessionBean.configApp.config != null) {
final Enumeration e = SaraConfiguracionSessionBean.configApp.config.getKeys();
while (e.hasMoreElements()) {
final String atributo = (String) e.nextElement();
SaraConfiguracionSessionBean.configApp.loggerApp.config(atributo + "=[" + SaraConfiguracionSessionBean.configApp.config.getString(atributo) + "]");
}
}
SaraConfiguracionSessionBean.configApp.loggerApp.config("CONFIGURACION_LOG_DIRECTORIO_LOGS = " + SaraConfiguracionSessionBean.configApp.CONFIGURACION_LOG_DIRECTORIO_LOGS);
SaraConfiguracionSessionBean.configApp.loggerApp.config("TAMANO_ARCHIVO_LOG = " + SaraConfiguracionSessionBean.configApp.TAMANO_ARCHIVO_LOG);
SaraConfiguracionSessionBean.configApp.loggerApp.config("CONFIGURACION_LOG_NIVEL_LOG = " + SaraConfiguracionSessionBean.configApp.CONFIGURACION_LOG_NIVEL_LOG);
SaraConfiguracionSessionBean.configApp.loggerApp.config("CONFIGURACION_LOG_MOSTRAR_LOG_CONSOLA = " + ((SaraConfiguracionSessionBean.configApp.CONFIGURACION_LOG_MOSTRAR_LOG_CONSOLA > 0) ? "SI" : "N0"));
SaraConfiguracionSessionBean.configApp.loggerApp.config("DIRECTORIO_UPLOAD = " + SaraConfiguracionSessionBean.configApp.DIRECTORIO_UPLOAD);
SaraConfiguracionSessionBean.configApp.loggerApp.config("DIRECTORIO_CUADRE = " + SaraConfiguracionSessionBean.configApp.DIRECTORIO_CUADRE);
SaraConfiguracionSessionBean.configApp.loggerApp.config("HORA_INICIO_TRANSMISION_ARCHIVOS = " + SaraConfiguracionSessionBean.configApp.HORA_INICIO_TRANSMISION_DIARIOS_ELECTRONICOS);
SaraConfiguracionSessionBean.configApp.loggerApp.config("URL_ACCESO_APP = " + SaraConfiguracionSessionBean.configApp.URL_ACCESO_APP);
SaraConfiguracionSessionBean.configApp.loggerApp.config("DOMINIOS_VALIDOS = " + Arrays.toString(SaraConfiguracionSessionBean.configApp.DOMINIOS_VALIDOS));
SaraConfiguracionSessionBean.configApp.loggerApp.config("FECHA_HISTORICAS_CONSULTA = " + SaraConfiguracionSessionBean.configApp.FECHA_HISTORICAS_CONSULTA);
SaraConfiguracionSessionBean.configApp.loggerApp.config("TIEMPO_SESION = " + SaraConfiguracionSessionBean.configApp.TIEMPO_SESION);
}
private void iniciarMBeanConfig() throws Exception {
try {
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
final ObjectName idMBean = new ObjectName("com.davivienda.sara.config:type=SaraConfig");
if (!mbs.isRegistered(idMBean)) {
mbs.registerMBean(SaraConfiguracionSessionBean.configApp, idMBean);
}
SaraConfiguracionSessionBean.configApp.loggerApp.config("MBean Iniciado");
}
catch (JMException ex) {
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.WARNING, "No se inicio el MBean => " + ex.getMessage(), ex);
}
}
@PreDestroy
@Override
public void finalizarAplicacion() {
try {
this.destruirMBeanConfig();
this.destruirLoggerAplicacion();
}
catch (Exception ex) {
System.err.println(">>> Se termina la aplicaci\u00f3n SARA 12.2.8.0 con ERROR " + ex.getMessage() + " <<<");
ex.printStackTrace();
}
}
private void destruirLoggerAplicacion() {
try {
SaraConfiguracionSessionBean.configApp.loggerApp.severe("Se da inicio al fin de la aplicaci\u00f3n ... ");
SaraConfiguracionSessionBean.configApp.loggerApp.severe(">>> Se termina la aplicaci\u00f3n SARA 12.2.8.0 <<<");
Handler[] handlers = SaraConfiguracionSessionBean.configApp.loggerAcceso.getHandlers();
for (int i = 0; i < handlers.length; ++i) {
final Handler handler = handlers[i];
handler.flush();
SaraConfiguracionSessionBean.configApp.loggerAcceso.severe("Se finaliza el log de Acceso:" + handler.getClass().getSimpleName() + " con nivel " + handler.getLevel().toString());
SaraConfiguracionSessionBean.configApp.loggerApp.severe("Se finaliza el log de Acceso:" + handler.getClass().getSimpleName() + " con nivel " + handler.getLevel().toString());
handler.close();
SaraConfiguracionSessionBean.configApp.loggerAcceso.removeHandler(handler);
}
handlers = SaraConfiguracionSessionBean.configApp.loggerApp.getHandlers();
for (int i = 0; i < handlers.length; ++i) {
final Handler handler = handlers[i];
handler.flush();
SaraConfiguracionSessionBean.configApp.loggerApp.severe("Se finaliza el log :" + handler.getClass().getSimpleName() + " con nivel " + handler.getLevel().toString());
handler.close();
SaraConfiguracionSessionBean.configApp.loggerApp.removeHandler(handler);
}
}
catch (Exception ex) {
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.SEVERE, "Finalizaci\u00f3n con error de la aplicaci\u00f3n ", ex);
System.err.println(">>> Se termina la aplicaci\u00f3n SARA 12.2.8.0 con ERROR " + ex.getMessage() + " <<<");
}
finally {
System.err.println(">>> Se termina la aplicaci\u00f3n SARA 12.2.8.0 <<<");
}
}
private void destruirMBeanConfig() {
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try {
final ObjectName idMBean = new ObjectName("com.davivienda.sara.config:type=SaraConfig");
if (mbs.isRegistered(idMBean)) {
mbs.unregisterMBean(idMBean);
}
}
catch (Exception ex) {
SaraConfiguracionSessionBean.configApp.loggerApp.severe("No se elimino el MBean " + ex.getMessage());
}
}
@Override
public void cambiarPropiedadLevel(final String nuevoNivel) {
SaraConfiguracionSessionBean.configApp.cambiarNivelLog(nuevoNivel);
}
public void cargarTareasProgramadas() {
SaraConfiguracionSessionBean.configApp.loggerApp.info("Iniciando la creaci\u00f3n de tareas programadas:");
try {
String strCronExpresion = "";
SaraConfiguracionSessionBean.configApp.loggerApp.info("Iniciando la creaci\u00f3n de tareas programadas:");
CronExpression cronExpression = null;
final SecureRandom sr = new SecureRandom();
final int n = sr.nextInt(5);
SaraConfiguracionSessionBean.configApp.loggerApp.info("Procesando tiempo espera la creaci\u00f3n de tareas programadas: " + n + " seg");
Thread.sleep(n * 1000);
final InitialContext ctx = new InitialContext();
try {
strCronExpresion = ((ConfModulosAplicacion)this.em.find((Class)ConfModulosAplicacion.class, (Object)new ConfModulosAplicacionPK("SARA", "QUARTZ.CARGUE_DIARIOS.EXP"))).getValor().trim();
if (!CronExpression.isValidExpression(strCronExpresion)) {
strCronExpresion = "0 30 23 * * ?";
}
}
catch (Exception ex) {
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.SEVERE, "Error al cargar la hora parametrizada para CargueDiarios", ex);
strCronExpresion = "0 30 23 * * ?";
}
final JobCargueDiariosHome homeCargueDiarios = (JobCargueDiariosHome)ctx.lookup("JobCargueDiariosJndi");
final JobCargueDiariosRemote jobCargueDiariosRemote = homeCargueDiarios.create();
final SchedulerInfo schedulerCargueDiarios = new SchedulerInfo();
schedulerCargueDiarios.setTipoProceso("CargueDiarios");
schedulerCargueDiarios.setCronExpresion(strCronExpresion);
schedulerCargueDiarios.setDirectorioUpload(SaraConfiguracionSessionBean.configApp.DIRECTORIO_UPLOAD);
try {
cronExpression = new CronExpression(strCronExpresion);
SaraConfiguracionSessionBean.configApp.loggerApp.info("Cargando datos para CargueDiarios con expresion: " + strCronExpresion);
if (cronExpression != null) {
schedulerCargueDiarios.setProximaEjecucion(cronExpression.getNextValidTimeAfter(new Date()));
jobCargueDiariosRemote.createTimer(schedulerCargueDiarios);
}
}
catch (Exception ex2) {
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.SEVERE, "Finalizaci\u00f3n con error la creaci\u00f3n de tarea programada para CargueDiarios", ex2);
if (cronExpression != null) {
schedulerCargueDiarios.setProximaEjecucion(cronExpression.getNextValidTimeAfter(new Date()));
jobCargueDiariosRemote.createTimer(schedulerCargueDiarios);
}
}
try {
strCronExpresion = ((ConfModulosAplicacion)this.em.find((Class)ConfModulosAplicacion.class, (Object)new ConfModulosAplicacionPK("SARA", "QUARTZ.DALI_AUTO.EXP"))).getValor().trim();
if (!CronExpression.isValidExpression(strCronExpresion)) {
strCronExpresion = "0 30 23 * * ?";
}
}
catch (Exception ex2) {
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.SEVERE, "Error al cargar la hora parametrizada para DaliAuto", ex2);
strCronExpresion = "0 30 23 * * ?";
}
final JobDaliAutoHome homeDaliAuto = (JobDaliAutoHome)ctx.lookup("JobDaliAutoJndi");
final JobDaliAutoRemote jobDaliAutoRemote = homeDaliAuto.create();
final SchedulerInfo schedulerDaliAuto = new SchedulerInfo();
schedulerDaliAuto.setTipoProceso("DaliAuto");
schedulerDaliAuto.setCronExpresion(strCronExpresion);
schedulerDaliAuto.setDirectorioUpload("");
try {
cronExpression = new CronExpression(strCronExpresion);
SaraConfiguracionSessionBean.configApp.loggerApp.info("Cargando datos para DaliAuto con expresion: " + strCronExpresion);
schedulerDaliAuto.setProximaEjecucion(cronExpression.getNextValidTimeAfter(new Date()));
jobDaliAutoRemote.createTimer(schedulerDaliAuto);
}
catch (Exception ex3) {
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.SEVERE, "Finalizaci\u00f3n con error la creaci\u00f3n de tarea programada para DaliAuto", ex3);
schedulerDaliAuto.setProximaEjecucion(cronExpression.getNextValidTimeAfter(new Date()));
jobDaliAutoRemote.createTimer(schedulerDaliAuto);
}
try {
strCronExpresion = ((ConfModulosAplicacion)this.em.find((Class)ConfModulosAplicacion.class, (Object)new ConfModulosAplicacionPK("SARA", "QUARTZ.INFORME_DIFERENCIAS.EXP"))).getValor().trim();
if (!CronExpression.isValidExpression(strCronExpresion)) {
strCronExpresion = "0 30 23 * * ?";
}
}
catch (Exception ex3) {
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.SEVERE, "Error al cargar la hora parametrizada para InformeDiferencias", ex3);
strCronExpresion = "0 30 23 * * ?";
}
final JobInformeDiferenciasHome homeInformeDiferencias = (JobInformeDiferenciasHome)ctx.lookup("JobInformeDiferenciasJndi");
final JobInformeDiferenciasRemote jobInformeDifeRemote = homeInformeDiferencias.create();
final SchedulerInfo schedulerInformeDife = new SchedulerInfo();
schedulerInformeDife.setTipoProceso("InformeDiferencias");
schedulerInformeDife.setCronExpresion(strCronExpresion);
schedulerInformeDife.setDirectorioUpload(SaraConfiguracionSessionBean.configApp.DIRECTORIO_UPLOAD);
try {
cronExpression = new CronExpression(strCronExpresion);
SaraConfiguracionSessionBean.configApp.loggerApp.info("Cargando datos para InformeDiferencias con expresion: " + strCronExpresion);
if (cronExpression != null) {
schedulerInformeDife.setProximaEjecucion(cronExpression.getNextValidTimeAfter(new Date()));
jobInformeDifeRemote.createTimer(schedulerInformeDife);
}
}
catch (Exception ex4) {
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.SEVERE, "Finalizaci\u00f3n con error la creaci\u00f3n de tarea programada para InformeDiferencias", ex4);
if (cronExpression != null) {
schedulerCargueDiarios.setProximaEjecucion(cronExpression.getNextValidTimeAfter(new Date()));
jobCargueDiariosRemote.createTimer(schedulerCargueDiarios);
}
}
}
catch (Exception ex5) {
SaraConfiguracionSessionBean.configApp.loggerApp.log(Level.SEVERE, "", ex5);
}
}
}
|
package v1;
import java.util.Arrays;
import java.util.concurrent.Callable;
public class StatisticsPrinter implements Callable<Void>{
static double[] total_inits, total_balances, total_bandwagons, total_buckpasses, init_myCap_min, init_myCap_med,
init_oppCap_min, init_oppCap_med, init_capRatio_min, init_capRatio_med, init_capMed_min, init_capMed_med,
init_capStd_min, init_capStd_med, init_capMin_min, init_capMin_med, init_capMax_min, init_capMax_med,
init_mySideCap_min, init_mySideCap_med, init_leftCapSum_min, init_leftCapSum_med, init_myEnmity_min,
init_myEnmity_med, init_oppEnmity_min, init_oppEnmity_med, balance_myCap_min, balance_myCap_med,
balance_oppCap_min, balance_oppCap_med, balance_capRatio_min, balance_capRatio_med, balance_capMed_min,
balance_capMed_med, balance_capStd_min, balance_capStd_med, balance_capMin_min, balance_capMin_med,
balance_capMax_min, balance_capMax_med, balance_mySideCap_min, balance_mySideCap_med,
balance_leftCapSum_min, balance_leftCapSum_med, balance_myEnmity_min, balance_myEnmity_med,
balance_oppEnmity_min, balance_oppEnmity_med, bandwagon_myCap_min, bandwagon_myCap_med,
bandwagon_oppCap_min, bandwagon_oppCap_med, bandwagon_capRatio_min, bandwagon_capRatio_med,
bandwagon_capMed_min, bandwagon_capMed_med, bandwagon_capStd_min, bandwagon_capStd_med,
bandwagon_capMin_min, bandwagon_capMin_med, bandwagon_capMax_min, bandwagon_capMax_med,
bandwagon_mySideCap_min, bandwagon_mySideCap_med, bandwagon_leftCapSum_min, bandwagon_leftCapSum_med,
bandwagon_myEnmity_min, bandwagon_myEnmity_med, bandwagon_oppEnmity_min, bandwagon_oppEnmity_med,
buckpass_myCap_min, buckpass_myCap_med, buckpass_oppCap_min, buckpass_oppCap_med, buckpass_capRatio_min,
buckpass_capRatio_med, buckpass_capMed_min, buckpass_capMed_med, buckpass_capStd_min, buckpass_capStd_med,
buckpass_capMin_min, buckpass_capMin_med, buckpass_capMax_min, buckpass_capMax_med, buckpass_mySideCap_min,
buckpass_mySideCap_med, buckpass_leftCapSum_min, buckpass_leftCapSum_med, buckpass_myEnmity_min,
buckpass_myEnmity_med, buckpass_oppEnmity_min, buckpass_oppEnmity_med;
static int currentSimulation, currentGen, PROFILES_PER_CAT, minLevel, maxLevel;
static LevelStrategy[] bestLevelStrategies;
static boolean[][] attackProfiles, balanceProfiles, bandwagonProfiles, buckpassingProfiles;
static World_System_Shell[][] profilingWorlds_Attacks, profilingWorlds_Joins;
static boolean printInProgress;
StatisticsPrinter(LevelStrategy[] bestLevelStrategies, int currentSimulation, int currentGen) {
if (printInProgress){
System.out.println("Error StatisticsPrinter class !!! Print in progress");
System.exit(0);
}
printInProgress=true;
this.bestLevelStrategies = sortBySize(bestLevelStrategies);
this.currentSimulation = currentSimulation;
this.currentGen = currentGen;
minLevel = bestLevelStrategies[0].level;
maxLevel = bestLevelStrategies[bestLevelStrategies.length - 1].level;
PROFILES_PER_CAT = MasterVariables.PROFILES_PER_CAT;
this.profilingWorlds_Attacks = MasterVariables.profilingWorlds_Attacks;
this.profilingWorlds_Joins = MasterVariables.profilingWorlds_Joins;
initializeArrays(bestLevelStrategies.length);
checkErrors();
}
public Void call() {
populateProfiles();
calculateProfileVariables();
printProfileVariablesToFile();
printInProgress=false;
return null;
}
private static void populateProfiles() {
attackProfiles = new boolean[bestLevelStrategies.length][PROFILES_PER_CAT];
for (int i = 0; i < attackProfiles.length; i++) {
int indexWorldSizeAttacks = bestLevelStrategies[i].level - minLevel;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
attackProfiles[i][l] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].willItAttack(
bestLevelStrategies[i].init_strategy, 0);
}
}
if (maxLevel > 2) {
balanceProfiles = new boolean[bestLevelStrategies.length][PROFILES_PER_CAT];
bandwagonProfiles = new boolean[bestLevelStrategies.length][PROFILES_PER_CAT];
buckpassingProfiles = new boolean[bestLevelStrategies.length][PROFILES_PER_CAT];
for (int i = 0; i < attackProfiles.length; i++) {
if (bestLevelStrategies[i].level == 2)
continue;
int indexWorldSizeJoins = bestLevelStrategies[i].level - minLevel - 1;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
balanceProfiles[i][l] = profilingWorlds_Joins[indexWorldSizeJoins][l].willItAttack(
bestLevelStrategies[i].balance_strategy, 1);
bandwagonProfiles[i][l] = profilingWorlds_Joins[indexWorldSizeJoins][l].willItAttack(
bestLevelStrategies[i].bandwagon_strategy, 2);
if (!balanceProfiles[i][l] && !bandwagonProfiles[i][l])
buckpassingProfiles[i][l] = true;
}
}
}
}
private static void calculateProfileVariables() {
for (int index = 0; index < bestLevelStrategies.length; index++) {
boolean even;
int totalAttacks = 0;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
if (attackProfiles[index][l] == true)
totalAttacks++;
}
total_inits[index] = (double) totalAttacks;
if (totalAttacks > 0) {
double[] init_myCap = new double[totalAttacks];
double[] init_oppCap = new double[totalAttacks];
double[] init_capRatio = new double[totalAttacks];
double[] init_capMed = new double[totalAttacks];
double[] init_capStd = new double[totalAttacks];
double[] init_capMin = new double[totalAttacks];
double[] init_capMax = new double[totalAttacks];
double[] init_mySideCap = new double[totalAttacks];
double[] init_leftCapSum = new double[totalAttacks];
double[] init_myEnmity = new double[totalAttacks];
double[] init_oppEnmity = new double[totalAttacks];
int indexWorldSizeAttacks = bestLevelStrategies[index].level - minLevel;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
if (attackProfiles[index][l] == true) {
init_myCap[totalAttacks - 1] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].myCap;
init_oppCap[totalAttacks - 1] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].oppCap;
init_capRatio[totalAttacks - 1] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].capRatio;
init_capMed[totalAttacks - 1] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].capMed;
init_capStd[totalAttacks - 1] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].capStd;
init_capMin[totalAttacks - 1] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].capMin;
init_capMax[totalAttacks - 1] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].capMax;
init_mySideCap[totalAttacks - 1] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].mySideCap;
init_leftCapSum[totalAttacks - 1] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].leftCapSum;
init_myEnmity[totalAttacks - 1] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].myEnmity;
init_oppEnmity[totalAttacks - 1] = profilingWorlds_Attacks[indexWorldSizeAttacks][l].oppEnmity;
totalAttacks--;
}
}
Arrays.sort(init_myCap);
Arrays.sort(init_oppCap);
Arrays.sort(init_capRatio);
Arrays.sort(init_capMed);
Arrays.sort(init_capStd);
Arrays.sort(init_capMin);
Arrays.sort(init_capMax);
Arrays.sort(init_mySideCap);
Arrays.sort(init_leftCapSum);
Arrays.sort(init_myEnmity);
Arrays.sort(init_oppEnmity);
init_myCap_min[index] = init_myCap[0];
init_oppCap_min[index] = init_oppCap[0];
init_capRatio_min[index] = init_capRatio[0];
init_capMed_min[index] = init_capMed[0];
init_capStd_min[index] = init_capStd[0];
init_capMin_min[index] = init_capMin[0];
init_capMax_min[index] = init_capMax[0];
init_mySideCap_min[index] = init_mySideCap[0];
init_leftCapSum_min[index] = init_leftCapSum[0];
init_myEnmity_min[index] = init_myEnmity[0];
init_oppEnmity_min[index] = init_oppEnmity[0];
even = total_inits[index] % 2 == 0 ? true : false;
if (!even) {
init_myCap_med[index] = init_myCap[(int) total_inits[index] / 2];
init_oppCap_med[index] = init_oppCap[(int) total_inits[index] / 2];
init_capRatio_med[index] = init_capRatio[(int) total_inits[index] / 2];
init_capMed_med[index] = init_capMed[(int) total_inits[index] / 2];
init_capStd_med[index] = init_capStd[(int) total_inits[index] / 2];
init_capMin_med[index] = init_capMin[(int) total_inits[index] / 2];
init_capMax_med[index] = init_capMax[(int) total_inits[index] / 2];
init_mySideCap_med[index] = init_mySideCap[(int) total_inits[index] / 2];
init_leftCapSum_med[index] = init_leftCapSum[(int) total_inits[index] / 2];
init_myEnmity_med[index] = init_myEnmity[(int) total_inits[index] / 2];
init_oppEnmity_med[index] = init_oppEnmity[(int) total_inits[index] / 2];
} else {
init_myCap_med[index] = (init_myCap[(int) total_inits[index] / 2] + init_myCap[(int) (total_inits[index] / 2) - 1]) / 2;
init_oppCap_med[index] = (init_oppCap[(int) total_inits[index] / 2] + init_oppCap[(int) (total_inits[index] / 2) - 1]) / 2;
init_capRatio_med[index] = (init_capRatio[(int) total_inits[index] / 2] + init_capRatio[(int) (total_inits[index] / 2) - 1]) / 2;
init_capMed_med[index] = (init_capMed[(int) total_inits[index] / 2] + init_capMed[(int) (total_inits[index] / 2) - 1]) / 2;
init_capStd_med[index] = (init_capStd[(int) total_inits[index] / 2] + init_capStd[(int) (total_inits[index] / 2) - 1]) / 2;
init_capMin_med[index] = (init_capMin[(int) total_inits[index] / 2] + init_capMin[(int) (total_inits[index] / 2) - 1]) / 2;
init_capMax_med[index] = (init_capMax[(int) total_inits[index] / 2] + init_capMax[(int) (total_inits[index] / 2) - 1]) / 2;
init_mySideCap_med[index] = (init_mySideCap[(int) total_inits[index] / 2] + init_mySideCap[(int) (total_inits[index] / 2) - 1]) / 2;
init_leftCapSum_med[index] = (init_leftCapSum[(int) total_inits[index] / 2] + init_leftCapSum[(int) (total_inits[index] / 2) - 1]) / 2;
init_myEnmity_med[index] = (init_myEnmity[(int) total_inits[index] / 2] + init_myEnmity[(int) (total_inits[index] / 2) - 1]) / 2;
init_oppEnmity_med[index] = (init_oppEnmity[(int) total_inits[index] / 2] + init_oppEnmity[(int) (total_inits[index] / 2) - 1]) / 2;
}
}
if (bestLevelStrategies[index].level > 2) {
int totalBalances = 0;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
if (balanceProfiles[index][l] == true)
totalBalances++;
}
total_balances[index] = (double) totalBalances;
if (total_balances[index] > 0) {
double[] balance_myCap = new double[totalBalances];
double[] balance_oppCap = new double[totalBalances];
double[] balance_capRatio = new double[totalBalances];
double[] balance_capMed = new double[totalBalances];
double[] balance_capStd = new double[totalBalances];
double[] balance_capMin = new double[totalBalances];
double[] balance_capMax = new double[totalBalances];
double[] balance_mySideCap = new double[totalBalances];
double[] balance_leftCapSum = new double[totalBalances];
double[] balance_myEnmity = new double[totalBalances];
double[] balance_oppEnmity = new double[totalBalances];
int indexWorldSizeJoins = bestLevelStrategies[index].level - minLevel - 1;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
if (balanceProfiles[index][l] == true) {
balance_myCap[totalBalances - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].myCap;
balance_oppCap[totalBalances - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].largerSideCap;
balance_capRatio[totalBalances - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capRatio;
balance_capMed[totalBalances - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capMed;
balance_capStd[totalBalances - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capStd;
balance_capMin[totalBalances - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capMin;
balance_capMax[totalBalances - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capMax;
balance_mySideCap[totalBalances - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].smallerSideCap;
balance_leftCapSum[totalBalances - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].leftCapSum;
balance_myEnmity[totalBalances - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].myEnmity;
balance_oppEnmity[totalBalances - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].oppEnmity;
totalBalances--;
}
}
Arrays.sort(balance_myCap);
Arrays.sort(balance_oppCap);
Arrays.sort(balance_capRatio);
Arrays.sort(balance_capMed);
Arrays.sort(balance_capStd);
Arrays.sort(balance_capMin);
Arrays.sort(balance_capMax);
Arrays.sort(balance_mySideCap);
Arrays.sort(balance_leftCapSum);
Arrays.sort(balance_myEnmity);
Arrays.sort(balance_oppEnmity);
balance_myCap_min[index] = balance_myCap[0];
balance_oppCap_min[index] = balance_oppCap[0];
balance_capRatio_min[index] = balance_capRatio[0];
balance_capMed_min[index] = balance_capMed[0];
balance_capStd_min[index] = balance_capStd[0];
balance_capMin_min[index] = balance_capMin[0];
balance_capMax_min[index] = balance_capMax[0];
balance_mySideCap_min[index] = balance_mySideCap[0];
balance_leftCapSum_min[index] = balance_leftCapSum[0];
balance_myEnmity_min[index] = balance_myEnmity[0];
balance_oppEnmity_min[index] = balance_oppEnmity[0];
even = total_balances[index] % 2 == 0 ? true : false;
if (!even) {
balance_myCap_med[index] = balance_myCap[(int) total_balances[index] / 2];
balance_oppCap_med[index] = balance_oppCap[(int) total_balances[index] / 2];
balance_capRatio_med[index] = balance_capRatio[(int) total_balances[index] / 2];
balance_capMed_med[index] = balance_capMed[(int) total_balances[index] / 2];
balance_capStd_med[index] = balance_capStd[(int) total_balances[index] / 2];
balance_capMin_med[index] = balance_capMin[(int) total_balances[index] / 2];
balance_capMax_med[index] = balance_capMax[(int) total_balances[index] / 2];
balance_mySideCap_med[index] = balance_mySideCap[(int) total_balances[index] / 2];
balance_leftCapSum_med[index] = balance_leftCapSum[(int) total_balances[index] / 2];
balance_myEnmity_med[index] = balance_myEnmity[(int) total_balances[index] / 2];
balance_oppEnmity_med[index] = balance_oppEnmity[(int) total_balances[index] / 2];
} else {
balance_myCap_med[index] = (balance_myCap[(int) total_balances[index] / 2] + balance_myCap[(int) (total_balances[index] / 2) - 1]) / 2;
balance_oppCap_med[index] = (balance_oppCap[(int) total_balances[index] / 2] + balance_oppCap[(int) (total_balances[index] / 2) - 1]) / 2;
balance_capRatio_med[index] = (balance_capRatio[(int) total_balances[index] / 2] + balance_capRatio[(int) (total_balances[index] / 2) - 1]) / 2;
balance_capMed_med[index] = (balance_capMed[(int) total_balances[index] / 2] + balance_capMed[(int) (total_balances[index] / 2) - 1]) / 2;
balance_capStd_med[index] = (balance_capStd[(int) total_balances[index] / 2] + balance_capStd[(int) (total_balances[index] / 2) - 1]) / 2;
balance_capMin_med[index] = (balance_capMin[(int) total_balances[index] / 2] + balance_capMin[(int) (total_balances[index] / 2) - 1]) / 2;
balance_capMax_med[index] = (balance_capMax[(int) total_balances[index] / 2] + balance_capMax[(int) (total_balances[index] / 2) - 1]) / 2;
balance_mySideCap_med[index] = (balance_mySideCap[(int) total_balances[index] / 2] + balance_mySideCap[(int) (total_balances[index] / 2) - 1]) / 2;
balance_leftCapSum_med[index] = (balance_leftCapSum[(int) total_balances[index] / 2] + balance_leftCapSum[(int) (total_balances[index] / 2) - 1]) / 2;
balance_myEnmity_med[index] = (balance_myEnmity[(int) total_balances[index] / 2] + balance_myEnmity[(int) (total_balances[index] / 2) - 1]) / 2;
balance_oppEnmity_med[index] = (balance_oppEnmity[(int) total_balances[index] / 2] + balance_oppEnmity[(int) (total_balances[index] / 2) - 1]) / 2;
}
}
int totalBandwagons = 0;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
if (bandwagonProfiles[index][l] == true)
totalBandwagons++;
}
total_bandwagons[index] = (double) totalBandwagons;
if (total_bandwagons[index] > 0) {
double[] bandwagon_myCap = new double[totalBandwagons];
double[] bandwagon_oppCap = new double[totalBandwagons];
double[] bandwagon_capRatio = new double[totalBandwagons];
double[] bandwagon_capMed = new double[totalBandwagons];
double[] bandwagon_capStd = new double[totalBandwagons];
double[] bandwagon_capMin = new double[totalBandwagons];
double[] bandwagon_capMax = new double[totalBandwagons];
double[] bandwagon_mySideCap = new double[totalBandwagons];
double[] bandwagon_leftCapSum = new double[totalBandwagons];
double[] bandwagon_myEnmity = new double[totalBandwagons];
double[] bandwagon_oppEnmity = new double[totalBandwagons];
int indexWorldSizeJoins = bestLevelStrategies[index].level - minLevel - 1;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
if (bandwagonProfiles[index][l] == true) {
bandwagon_myCap[totalBandwagons - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].myCap;
bandwagon_oppCap[totalBandwagons - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].smallerSideCap;
bandwagon_capRatio[totalBandwagons - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capRatio;
bandwagon_capMed[totalBandwagons - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capMed;
bandwagon_capStd[totalBandwagons - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capStd;
bandwagon_capMin[totalBandwagons - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capMin;
bandwagon_capMax[totalBandwagons - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capMax;
bandwagon_mySideCap[totalBandwagons - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].largerSideCap;
bandwagon_leftCapSum[totalBandwagons - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].leftCapSum;
bandwagon_myEnmity[totalBandwagons - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].myEnmity;
bandwagon_oppEnmity[totalBandwagons - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].oppEnmity;
totalBandwagons--;
}
}
Arrays.sort(bandwagon_myCap);
Arrays.sort(bandwagon_oppCap);
Arrays.sort(bandwagon_capRatio);
Arrays.sort(bandwagon_capMed);
Arrays.sort(bandwagon_capStd);
Arrays.sort(bandwagon_capMin);
Arrays.sort(bandwagon_capMax);
Arrays.sort(bandwagon_mySideCap);
Arrays.sort(bandwagon_leftCapSum);
Arrays.sort(bandwagon_myEnmity);
Arrays.sort(bandwagon_oppEnmity);
bandwagon_myCap_min[index] = bandwagon_myCap[0];
bandwagon_oppCap_min[index] = bandwagon_oppCap[0];
bandwagon_capRatio_min[index] = bandwagon_capRatio[0];
bandwagon_capMed_min[index] = bandwagon_capMed[0];
bandwagon_capStd_min[index] = bandwagon_capStd[0];
bandwagon_capMin_min[index] = bandwagon_capMin[0];
bandwagon_capMax_min[index] = bandwagon_capMax[0];
bandwagon_mySideCap_min[index] = bandwagon_mySideCap[0];
bandwagon_leftCapSum_min[index] = bandwagon_leftCapSum[0];
bandwagon_myEnmity_min[index] = bandwagon_myEnmity[0];
bandwagon_oppEnmity_min[index] = bandwagon_oppEnmity[0];
even = total_bandwagons[index] % 2 == 0 ? true : false;
if (!even) {
bandwagon_myCap_med[index] = bandwagon_myCap[(int) total_bandwagons[index] / 2];
bandwagon_oppCap_med[index] = bandwagon_oppCap[(int) total_bandwagons[index] / 2];
bandwagon_capRatio_med[index] = bandwagon_capRatio[(int) total_bandwagons[index] / 2];
bandwagon_capMed_med[index] = bandwagon_capMed[(int) total_bandwagons[index] / 2];
bandwagon_capStd_med[index] = bandwagon_capStd[(int) total_bandwagons[index] / 2];
bandwagon_capMin_med[index] = bandwagon_capMin[(int) total_bandwagons[index] / 2];
bandwagon_capMax_med[index] = bandwagon_capMax[(int) total_bandwagons[index] / 2];
bandwagon_mySideCap_med[index] = bandwagon_mySideCap[(int) total_bandwagons[index] / 2];
bandwagon_leftCapSum_med[index] = bandwagon_leftCapSum[(int) total_bandwagons[index] / 2];
bandwagon_myEnmity_med[index] = bandwagon_myEnmity[(int) total_bandwagons[index] / 2];
bandwagon_oppEnmity_med[index] = bandwagon_oppEnmity[(int) total_bandwagons[index] / 2];
} else {
bandwagon_myCap_med[index] = (bandwagon_myCap[(int) total_bandwagons[index] / 2] + bandwagon_myCap[(int) (total_bandwagons[index] / 2) - 1]) / 2;
bandwagon_oppCap_med[index] = (bandwagon_oppCap[(int) total_bandwagons[index] / 2] + bandwagon_oppCap[(int) (total_bandwagons[index] / 2) - 1]) / 2;
bandwagon_capRatio_med[index] = (bandwagon_capRatio[(int) total_bandwagons[index] / 2] + bandwagon_capRatio[(int) (total_bandwagons[index] / 2) - 1]) / 2;
bandwagon_capMed_med[index] = (bandwagon_capMed[(int) total_bandwagons[index] / 2] + bandwagon_capMed[(int) (total_bandwagons[index] / 2) - 1]) / 2;
bandwagon_capStd_med[index] = (bandwagon_capStd[(int) total_bandwagons[index] / 2] + bandwagon_capStd[(int) (total_bandwagons[index] / 2) - 1]) / 2;
bandwagon_capMin_med[index] = (bandwagon_capMin[(int) total_bandwagons[index] / 2] + bandwagon_capMin[(int) (total_bandwagons[index] / 2) - 1]) / 2;
bandwagon_capMax_med[index] = (bandwagon_capMax[(int) total_bandwagons[index] / 2] + bandwagon_capMax[(int) (total_bandwagons[index] / 2) - 1]) / 2;
bandwagon_mySideCap_med[index] = (bandwagon_mySideCap[(int) total_bandwagons[index] / 2] + bandwagon_mySideCap[(int) (total_bandwagons[index] / 2) - 1]) / 2;
bandwagon_leftCapSum_med[index] = (bandwagon_leftCapSum[(int) total_bandwagons[index] / 2] + bandwagon_leftCapSum[(int) (total_bandwagons[index] / 2) - 1]) / 2;
bandwagon_myEnmity_med[index] = (bandwagon_myEnmity[(int) total_bandwagons[index] / 2] + bandwagon_myEnmity[(int) (total_bandwagons[index] / 2) - 1]) / 2;
bandwagon_oppEnmity_med[index] = (bandwagon_oppEnmity[(int) total_bandwagons[index] / 2] + bandwagon_oppEnmity[(int) (total_bandwagons[index] / 2) - 1]) / 2;
}
}
int totalbuckpasses = 0;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
if (buckpassingProfiles[index][l] == true)
totalbuckpasses++;
}
total_buckpasses[index] = (double) totalbuckpasses;
if (total_buckpasses[index] > 0) {
double[] buckpass_myCap = new double[totalbuckpasses];
double[] buckpass_oppCap = new double[totalbuckpasses];
double[] buckpass_capRatio = new double[totalbuckpasses];
double[] buckpass_capMed = new double[totalbuckpasses];
double[] buckpass_capStd = new double[totalbuckpasses];
double[] buckpass_capMin = new double[totalbuckpasses];
double[] buckpass_capMax = new double[totalbuckpasses];
double[] buckpass_mySideCap = new double[totalbuckpasses];
double[] buckpass_leftCapSum = new double[totalbuckpasses];
double[] buckpass_myEnmity = new double[totalbuckpasses];
double[] buckpass_oppEnmity = new double[totalbuckpasses];
int indexWorldSizeJoins = bestLevelStrategies[index].level - minLevel - 1;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
if (buckpassingProfiles[index][l] == true) {
buckpass_myCap[totalbuckpasses - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].myCap;
buckpass_oppCap[totalbuckpasses - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].smallerSideCap;
buckpass_capRatio[totalbuckpasses - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capRatio;
buckpass_capMed[totalbuckpasses - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capMed;
buckpass_capStd[totalbuckpasses - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capStd;
buckpass_capMin[totalbuckpasses - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capMin;
buckpass_capMax[totalbuckpasses - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].capMax;
buckpass_mySideCap[totalbuckpasses - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].largerSideCap;
buckpass_leftCapSum[totalbuckpasses - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].leftCapSum;
buckpass_myEnmity[totalbuckpasses - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].myEnmity;
buckpass_oppEnmity[totalbuckpasses - 1] = profilingWorlds_Joins[indexWorldSizeJoins][l].oppEnmity;
totalbuckpasses--;
}
}
Arrays.sort(buckpass_myCap);
Arrays.sort(buckpass_oppCap);
Arrays.sort(buckpass_capRatio);
Arrays.sort(buckpass_capMed);
Arrays.sort(buckpass_capStd);
Arrays.sort(buckpass_capMin);
Arrays.sort(buckpass_capMax);
Arrays.sort(buckpass_mySideCap);
Arrays.sort(buckpass_leftCapSum);
Arrays.sort(buckpass_myEnmity);
Arrays.sort(buckpass_oppEnmity);
buckpass_myCap_min[index] = buckpass_myCap[0];
buckpass_oppCap_min[index] = buckpass_oppCap[0];
buckpass_capRatio_min[index] = buckpass_capRatio[0];
buckpass_capMed_min[index] = buckpass_capMed[0];
buckpass_capStd_min[index] = buckpass_capStd[0];
buckpass_capMin_min[index] = buckpass_capMin[0];
buckpass_capMax_min[index] = buckpass_capMax[0];
buckpass_mySideCap_min[index] = buckpass_mySideCap[0];
buckpass_leftCapSum_min[index] = buckpass_leftCapSum[0];
buckpass_myEnmity_min[index] = buckpass_myEnmity[0];
buckpass_oppEnmity_min[index] = buckpass_oppEnmity[0];
even = total_buckpasses[index] % 2 == 0 ? true : false;
if (!even) {
buckpass_myCap_med[index] = buckpass_myCap[(int) total_buckpasses[index] / 2];
buckpass_oppCap_med[index] = buckpass_oppCap[(int) total_buckpasses[index] / 2];
buckpass_capRatio_med[index] = buckpass_capRatio[(int) total_buckpasses[index] / 2];
buckpass_capMed_med[index] = buckpass_capMed[(int) total_buckpasses[index] / 2];
buckpass_capStd_med[index] = buckpass_capStd[(int) total_buckpasses[index] / 2];
buckpass_capMin_med[index] = buckpass_capMin[(int) total_buckpasses[index] / 2];
buckpass_capMax_med[index] = buckpass_capMax[(int) total_buckpasses[index] / 2];
buckpass_mySideCap_med[index] = buckpass_mySideCap[(int) total_buckpasses[index] / 2];
buckpass_leftCapSum_med[index] = buckpass_leftCapSum[(int) total_buckpasses[index] / 2];
buckpass_myEnmity_med[index] = buckpass_myEnmity[(int) total_buckpasses[index] / 2];
buckpass_oppEnmity_med[index] = buckpass_oppEnmity[(int) total_buckpasses[index] / 2];
} else {
buckpass_myCap_med[index] = (buckpass_myCap[(int) total_buckpasses[index] / 2] + buckpass_myCap[(int) (total_buckpasses[index] / 2) - 1]) / 2;
buckpass_oppCap_med[index] = (buckpass_oppCap[(int) total_buckpasses[index] / 2] + buckpass_oppCap[(int) (total_buckpasses[index] / 2) - 1]) / 2;
buckpass_capRatio_med[index] = (buckpass_capRatio[(int) total_buckpasses[index] / 2] + buckpass_capRatio[(int) (total_buckpasses[index] / 2) - 1]) / 2;
buckpass_capMed_med[index] = (buckpass_capMed[(int) total_buckpasses[index] / 2] + buckpass_capMed[(int) (total_buckpasses[index] / 2) - 1]) / 2;
buckpass_capStd_med[index] = (buckpass_capStd[(int) total_buckpasses[index] / 2] + buckpass_capStd[(int) (total_buckpasses[index] / 2) - 1]) / 2;
buckpass_capMin_med[index] = (buckpass_capMin[(int) total_buckpasses[index] / 2] + buckpass_capMin[(int) (total_buckpasses[index] / 2) - 1]) / 2;
buckpass_capMax_med[index] = (buckpass_capMax[(int) total_buckpasses[index] / 2] + buckpass_capMax[(int) (total_buckpasses[index] / 2) - 1]) / 2;
buckpass_mySideCap_med[index] = (buckpass_mySideCap[(int) total_buckpasses[index] / 2] + buckpass_mySideCap[(int) (total_buckpasses[index] / 2) - 1]) / 2;
buckpass_leftCapSum_med[index] = (buckpass_leftCapSum[(int) total_buckpasses[index] / 2] + buckpass_leftCapSum[(int) (total_buckpasses[index] / 2) - 1]) / 2;
buckpass_myEnmity_med[index] = (buckpass_myEnmity[(int) total_buckpasses[index] / 2] + buckpass_myEnmity[(int) (total_buckpasses[index] / 2) - 1]) / 2;
buckpass_oppEnmity_med[index] = (buckpass_oppEnmity[(int) total_buckpasses[index] / 2] + buckpass_oppEnmity[(int) (total_buckpasses[index] / 2) - 1]) / 2;
}
}
}
}
}
private static void printProfileVariablesToFile() {
String outputString;
int prevSize = -99, stateNumber = 0;
for (int i = 0; i < bestLevelStrategies.length; i++) {
if (bestLevelStrategies[i].level != prevSize) {
prevSize = bestLevelStrategies[i].level;
stateNumber = 0;
}
stateNumber++;
outputString = (currentSimulation + "," + stateNumber + "," + currentGen + ","
+ bestLevelStrategies[i].level + "," + total_inits[i] + ",");
if (bestLevelStrategies[i].level == 2)
outputString += ("." + "," + "." + "," + ".");
else
outputString += (total_balances[i] + "," + total_bandwagons[i] + "," + total_buckpasses[i]);
for (int j = 0; j < MasterVariables.MAXSYSTEM; j++) {
if (stateNumber - 1 == j || j >= bestLevelStrategies[i].level)
outputString += ("," + ".");
else
outputString += ("," + calcSimilarity(attackProfiles[i], attackProfiles[j]));
}
for (int j = 0; j < MasterVariables.MAXSYSTEM; j++) {
if (stateNumber - 1 == j || j >= bestLevelStrategies[i].level || maxLevel == 2)
outputString += ("," + ".");
else
outputString += ("," + calcSimilarity(balanceProfiles[i], balanceProfiles[j]));
}
for (int j = 0; j < MasterVariables.MAXSYSTEM; j++) {
if (stateNumber - 1 == j || j >= bestLevelStrategies[i].level || maxLevel == 2)
outputString += ("," + ".");
else
outputString += ("," + calcSimilarity(bandwagonProfiles[i], bandwagonProfiles[j]));
}
for (int j = 0; j < MasterVariables.MAXSYSTEM; j++) {
if (stateNumber - 1 == j || j >= bestLevelStrategies[i].level || maxLevel == 2)
outputString += ("," + ".");
else
outputString += ("," + calcSimilarity(buckpassingProfiles[i], buckpassingProfiles[j]));
}
outputString += ("," + init_myCap_min[i] + "," + init_myCap_med[i] + "," + init_oppCap_min[i] + ","
+ init_oppCap_med[i] + "," + init_capRatio_min[i] + "," + init_capRatio_med[i] + ","
+ init_capMed_min[i] + "," + init_capMed_med[i] + "," + init_capStd_min[i] + ","
+ init_capStd_med[i] + "," + init_capMin_min[i] + "," + init_capMin_med[i] + ","
+ init_capMax_min[i] + "," + init_capMax_med[i] + "," + init_mySideCap_min[i] + ","
+ init_mySideCap_med[i] + "," + init_leftCapSum_min[i] + "," + init_leftCapSum_med[i] + ","
+ init_myEnmity_min[i] + "," + init_myEnmity_med[i] + "," + init_oppEnmity_min[i] + "," + init_oppEnmity_med[i]);
if (maxLevel > 2) {
outputString += ("," + balance_myCap_min[i] + "," + balance_myCap_med[i] + "," + balance_oppCap_min[i]
+ "," + balance_oppCap_med[i] + "," + balance_capRatio_min[i] + "," + balance_capRatio_med[i]
+ "," + balance_capMed_min[i] + "," + balance_capMed_med[i] + "," + balance_capStd_min[i] + ","
+ balance_capStd_med[i] + "," + balance_capMin_min[i] + "," + balance_capMin_med[i] + ","
+ balance_capMax_min[i] + "," + balance_capMax_med[i] + "," + balance_mySideCap_min[i] + ","
+ balance_mySideCap_med[i] + "," + balance_leftCapSum_min[i] + "," + balance_leftCapSum_med[i]
+ "," + balance_myEnmity_min[i] + "," + balance_myEnmity_med[i] + ","
+ balance_oppEnmity_min[i] + "," + balance_oppEnmity_med[i] + "," + bandwagon_myCap_min[i]
+ "," + bandwagon_myCap_med[i] + "," + bandwagon_oppCap_min[i] + "," + bandwagon_oppCap_med[i]
+ "," + bandwagon_capRatio_min[i] + "," + bandwagon_capRatio_med[i] + ","
+ bandwagon_capMed_min[i] + "," + bandwagon_capMed_med[i] + "," + bandwagon_capStd_min[i] + ","
+ bandwagon_capStd_med[i] + "," + bandwagon_capMin_min[i] + "," + bandwagon_capMin_med[i] + ","
+ bandwagon_capMax_min[i] + "," + bandwagon_capMax_med[i] + "," + bandwagon_mySideCap_min[i]
+ "," + bandwagon_mySideCap_med[i] + "," + bandwagon_leftCapSum_min[i] + ","
+ bandwagon_leftCapSum_med[i] + "," + bandwagon_myEnmity_min[i] + ","
+ bandwagon_myEnmity_med[i] + "," + bandwagon_oppEnmity_min[i] + ","
+ bandwagon_oppEnmity_med[i] + "," + buckpass_myCap_min[i] + "," + buckpass_myCap_med[i] + ","
+ buckpass_oppCap_min[i] + "," + buckpass_oppCap_med[i] + "," + buckpass_capRatio_min[i] + ","
+ buckpass_capRatio_med[i] + "," + buckpass_capMed_min[i] + "," + buckpass_capMed_med[i] + ","
+ buckpass_capStd_min[i] + "," + buckpass_capStd_med[i] + "," + buckpass_capMin_min[i] + ","
+ buckpass_capMin_med[i] + "," + buckpass_capMax_min[i] + "," + buckpass_capMax_med[i] + ","
+ buckpass_mySideCap_min[i] + "," + buckpass_mySideCap_med[i] + ","
+ buckpass_leftCapSum_min[i] + "," + buckpass_leftCapSum_med[i] + ","
+ buckpass_myEnmity_min[i] + "," + buckpass_myEnmity_med[i] + "," + buckpass_oppEnmity_min[i]
+ "," + buckpass_oppEnmity_med[i]);
}
MasterVariables.state_profiles_writer.writeToFile(outputString + "\n");
}
}
private static double calcSimilarity(boolean[] array1, boolean[] array2) {
double similarity = 0;
if (array1.length != array2.length) {
System.out.println("Statistics printer class ... calcSimilarity method erorr!!");
System.exit(0);
}
for (int i = 0; i < array1.length; i++)
if (array1[i] == array2[i])
similarity++;
similarity = (double) similarity / (double) PROFILES_PER_CAT;
return (similarity);
}
private LevelStrategy[] sortBySize(LevelStrategy[] bestLevelStrategies) {
LevelStrategy[] sortedLevelStrategies = new LevelStrategy[bestLevelStrategies.length];
int[] levels = new int[bestLevelStrategies.length];
boolean[] takenStrategy = new boolean[bestLevelStrategies.length];
for (int i = 0; i < bestLevelStrategies.length; i++) {
levels[i] = bestLevelStrategies[i].level;
takenStrategy[i] = false;
}
Arrays.sort(levels);
for (int i = 0; i < bestLevelStrategies.length; i++) {
for (int k = 0; k < bestLevelStrategies.length; k++) {
if (bestLevelStrategies[k].level == levels[i] && takenStrategy[k] == false) {
sortedLevelStrategies[i] = bestLevelStrategies[k];
takenStrategy[k] = true;
break;
}
}
}
return sortedLevelStrategies;
}
private void initializeArrays(int length) {
total_inits = new double[length];
total_balances = new double[length];
total_bandwagons = new double[length];
total_buckpasses = new double[length];
init_myCap_min = new double[length];
init_myCap_med = new double[length];
init_oppCap_min = new double[length];
init_oppCap_med = new double[length];
init_capRatio_min = new double[length];
init_capRatio_med = new double[length];
init_capMed_min = new double[length];
init_capMed_med = new double[length];
init_capStd_min = new double[length];
init_capStd_med = new double[length];
init_capMin_min = new double[length];
init_capMin_med = new double[length];
init_capMax_min = new double[length];
init_capMax_med = new double[length];
init_mySideCap_min = new double[length];
init_mySideCap_med = new double[length];
init_leftCapSum_min = new double[length];
init_leftCapSum_med = new double[length];
init_myEnmity_min = new double[length];
init_myEnmity_med = new double[length];
init_oppEnmity_min = new double[length];
init_oppEnmity_med = new double[length];
balance_myCap_min = new double[length];
balance_myCap_med = new double[length];
balance_oppCap_min = new double[length];
balance_oppCap_med = new double[length];
balance_capRatio_min = new double[length];
balance_capRatio_med = new double[length];
balance_capMed_min = new double[length];
balance_capMed_med = new double[length];
balance_capStd_min = new double[length];
balance_capStd_med = new double[length];
balance_capMin_min = new double[length];
balance_capMin_med = new double[length];
balance_capMax_min = new double[length];
balance_capMax_med = new double[length];
balance_mySideCap_min = new double[length];
balance_mySideCap_med = new double[length];
balance_leftCapSum_min = new double[length];
balance_leftCapSum_med = new double[length];
balance_myEnmity_min = new double[length];
balance_myEnmity_med = new double[length];
balance_oppEnmity_min = new double[length];
balance_oppEnmity_med = new double[length];
bandwagon_myCap_min = new double[length];
bandwagon_myCap_med = new double[length];
bandwagon_oppCap_min = new double[length];
bandwagon_oppCap_med = new double[length];
bandwagon_capRatio_min = new double[length];
bandwagon_capRatio_med = new double[length];
bandwagon_capMed_min = new double[length];
bandwagon_capMed_med = new double[length];
bandwagon_capStd_min = new double[length];
bandwagon_capStd_med = new double[length];
bandwagon_capMin_min = new double[length];
bandwagon_capMin_med = new double[length];
bandwagon_capMax_min = new double[length];
bandwagon_capMax_med = new double[length];
bandwagon_mySideCap_min = new double[length];
bandwagon_mySideCap_med = new double[length];
bandwagon_leftCapSum_min = new double[length];
bandwagon_leftCapSum_med = new double[length];
bandwagon_myEnmity_min = new double[length];
bandwagon_myEnmity_med = new double[length];
bandwagon_oppEnmity_min = new double[length];
bandwagon_oppEnmity_med = new double[length];
buckpass_myCap_min = new double[length];
buckpass_myCap_med = new double[length];
buckpass_oppCap_min = new double[length];
buckpass_oppCap_med = new double[length];
buckpass_capRatio_min = new double[length];
buckpass_capRatio_med = new double[length];
buckpass_capMed_min = new double[length];
buckpass_capMed_med = new double[length];
buckpass_capStd_min = new double[length];
buckpass_capStd_med = new double[length];
buckpass_capMin_min = new double[length];
buckpass_capMin_med = new double[length];
buckpass_capMax_min = new double[length];
buckpass_capMax_med = new double[length];
buckpass_mySideCap_min = new double[length];
buckpass_mySideCap_med = new double[length];
buckpass_leftCapSum_min = new double[length];
buckpass_leftCapSum_med = new double[length];
buckpass_myEnmity_min = new double[length];
buckpass_myEnmity_med = new double[length];
buckpass_oppEnmity_min = new double[length];
buckpass_oppEnmity_med = new double[length];
}
private void checkErrors() {
if (minLevel != 2) {
System.out.println("StatisticsPrinter class erorr!!!");
System.exit(0);
}
}
}
|
package org.dbdoclet.test.sample;
/**
* @author <a href="mailto:mfuchs@unico-consulting.com">Michael Fuchs</a>
* @version 1.0
*/
public class DreamingException extends Exception {
}
|
package com.mycalc.view;
import com.mycalc.controller.MyCalcController;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DisplayPanel extends JPanel {
private String display;
private int maxDisplayLen;
private boolean toReset;
private JTextField displayTextField;
private JButton btnDisplayClear;
private MyCalcController myCalcController;
public DisplayPanel(MyCalcController myCalcController) {
this.myCalcController = myCalcController;
display = "0";
toReset = true;
maxDisplayLen = 15;
displayTextField = new JTextField(display);
btnDisplayClear = new JButton("C");
setupDisplayPanel();
setupDisplayPanelButtons();
}
private void setupDisplayPanel() {
displayTextField.setHorizontalAlignment(SwingConstants.RIGHT);
displayTextField.setFont(displayTextField.getFont().deriveFont(displayTextField.getFont().getSize() + 10f));
displayTextField.setEditable(false);
displayTextField.setBackground(new Color(255, 255, 255));
displayTextField.setBorder(new EmptyBorder(0, 10, 0, 10));
setLayout(new BorderLayout(10, 0));
setBorder(new EmptyBorder(10, 10, 10, 10));
add(displayTextField, BorderLayout.CENTER);
add(btnDisplayClear, BorderLayout.EAST);
}
private void setupDisplayPanelButtons() {
btnDisplayClear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetDisplay();
myCalcController.getMyCalcModel().setDigitInMemory(false);
}
});
}
public void setDisplay(String newDisplayContent) {
if(toReset) {
displayTextField.setText(newDisplayContent);
toReset = false;
} else {
if (displayTextField.getText().length() <= maxDisplayLen) {
displayTextField.setText(displayTextField.getText() + newDisplayContent);
}
}
}
public String getDisplay() {
return displayTextField.getText();
}
public void resetDisplay() {
displayTextField.setText("0");
toReset = true;
}
public boolean isToReset() {
return toReset;
}
public void setToReset(boolean toReset) {
this.toReset = toReset;
}
}
|
package sop.filegen.generator.impl;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map.Entry;
import fr.opensagres.xdocreport.core.document.SyntaxKind;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;
import sop.filegen.FileGenerationException;
import sop.filegen.FileGeneratorConstant;
import sop.filegen.GenRequest;
import sop.filegen.GenResult;
/**
* @Author: LCF
* @Date: 2020/1/8 17:46
* @Package: sop.filegen.generator.impl
*/
public class DocxFileGenerator extends BaseFileGenerator {
@Override
protected GenResult generateFile(GenRequest request) throws FileGenerationException {
GenResult rs = new GenResult();
try {
final String reportFileName = FileGeneratorUtils.genReportFileName(request);
String outFile = FileGeneratorUtils.getReportOutputFullPath(getOutputFolder(), reportFileName, ".docx");
// 1) Load Docx file by filling Velocity template engine and cache
// it to the registry
InputStream in = new FileInputStream(FileGeneratorUtils.getDocxTemplate(request.getReportId()));
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
// 3) Create context Java model
IContext context = report.createContext();
// Register project
for (Entry<String, Object> entry : request.getParams().entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
FieldsMetadata metadata = new FieldsMetadata();
for (String fn : request.getFieldMeta()) {
metadata.addFieldAsList(fn);
}
for (String fn : request.getHtmlFields()) {
metadata.addFieldAsTextStyling(fn, SyntaxKind.Html);
}
report.setFieldsMetadata(metadata);
// 4) Generate report by merging Java model with the Docx
OutputStream out = new FileOutputStream(outFile);
report.process(context, out);
rs.setReturnCode(FileGeneratorConstant.SUCCESS);
rs.setReportFile(outFile);
} catch (Exception e) {
logger.error("", e);
throw new FileGenerationException(e.getMessage());
}
return rs;
}
}
|
package com.gk.action;
import java.util.List;
import javax.annotation.Resource;
import com.gk.service.CollegeService;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class College extends ActionSupport {
private static final long serialVersionUID = 1L;
private String result;
@Resource(name="collegeService")
private CollegeService collegeService;
public String getAll() {
List<com.gk.entities.College> colleges = collegeService.getAll();
JSONArray array = new JSONArray();
for(com.gk.entities.College college : colleges) {
JSONObject jsonObject = JSONObject.fromObject(college);
System.out.println(jsonObject.toString());
array.add(jsonObject);
}
result = array.toString();
return SUCCESS;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
|
package Models;
import java.sql.Date;
public class Factura {
private int CodigoFactura;
private int TipoDeFactura;
private double MontoTotal;
private double MontoPagado;
private Date Fecha;
private int idCliente;
private int idTipoDePago;
public Factura() {
}
public Factura(int CodigoFactura, int TipoDeFactura, double MontoTotal, double MontoPagado, Date Fecha, int idCliente, int idTipoDePago) {
this.CodigoFactura = CodigoFactura;
this.TipoDeFactura = TipoDeFactura;
this.MontoTotal = MontoTotal;
this.MontoPagado = MontoPagado;
this.Fecha = Fecha;
this.idCliente = idCliente;
this.idTipoDePago = idTipoDePago;
}
public int getCodigoFactura() {
return CodigoFactura;
}
public void setCodigoFactura(int CodigoFactura) {
this.CodigoFactura = CodigoFactura;
}
public int getTipoDeFactura() {
return TipoDeFactura;
}
public void setTipoDeFactura(int TipoDeFactura) {
this.TipoDeFactura = TipoDeFactura;
}
public double getMontoTotal() {
return MontoTotal;
}
public void setMontoTotal(double MontoTotal) {
this.MontoTotal = MontoTotal;
}
public double getMontoPagado() {
return MontoPagado;
}
public void setMontoPagado(double MontoPagado) {
this.MontoPagado = MontoPagado;
}
public Date getFecha() {
return Fecha;
}
public void setFecha(Date Fecha) {
this.Fecha = Fecha;
}
public int getIdCliente() {
return idCliente;
}
public void setIdCliente(int idCliente) {
this.idCliente = idCliente;
}
public int getIdTipoDePago() {
return idTipoDePago;
}
public void setIdTipoDePago(int idTipoDePago) {
this.idTipoDePago = idTipoDePago;
}
}
|
package com.cakeworld.main;
import org.springframework.data.repository.CrudRepository;
import com.cakeworld.model.Bill;
public interface BillRepository extends CrudRepository<Bill, Integer> {
}
|
../../../jvmti-common/Main.java
|
package com.vicutu.batchdownload.engine.io.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import com.vicutu.batchdownload.domain.AccessDetail;
import com.vicutu.batchdownload.engine.io.AbstractFileHandler;
import com.vicutu.batchdownload.engine.io.FileHandler;
import de.schlichtherle.truezip.file.TArchiveDetector;
import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TFileOutputStream;
import de.schlichtherle.truezip.fs.archive.zip.ZipDriver;
import de.schlichtherle.truezip.socket.sl.IOPoolLocator;
public class ArchiveFileHandler extends AbstractFileHandler implements FileHandler {
public ArchiveFileHandler() {
TFile.setDefaultArchiveDetector(new TArchiveDetector("zip", new ZipDriver(IOPoolLocator.SINGLETON)));
}
@Override
public boolean exists(String folder, String name) {
return (new TFile(getZipFileName(folder) + "/" + name)).exists();
}
@Override
public long save(AccessDetail accessDetail, InputStream input, String folder, String name) throws IOException {
OutputStream os = null;
try {
os = new TFileOutputStream(getZipFileName(folder) + "/" + name);
return this.copyLarge(accessDetail, input, os);
} finally {
IOUtils.closeQuietly(os);
}
}
private String getZipFileName(String folder) {
if (StringUtils.endsWith(folder, "/")) {
return StringUtils.substringBeforeLast(folder, "/") + ".zip";
}
return folder + ".zip";
}
}
|
package com.emg.projectsmanage.ctrl;
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/foot.web")
public class FootCtrl extends BaseCtrl {
private static final Logger logger = LoggerFactory.getLogger(FootCtrl.class);
@Value("${version}")
private String version;
@RequestMapping()
public String foot(Model model, HttpSession session, HttpServletRequest request) {
logger.debug("FootCtrl-foot start.");
Calendar date = Calendar.getInstance();
String thisYear = String.valueOf(date.get(Calendar.YEAR));
model.addAttribute("thisYear", thisYear);
model.addAttribute("version", version);
logger.debug("FootCtrl-foot end.");
return "foot";
}
}
|
package com.hashedin.repository;
import java.util.List;
import com.hashedin.model.Task;
public interface TaskRepository {
List<Task> findByProject(long projectId);
List<Task> findAll();
List<Task> findByAssignedTo(long userId);
List<Task> findByStatus(long projectId,String status);
Task save(Task task);
Task update(Task task, Long taskId);
}
|
/*
* 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.pmm.sdgc.ws.model;
import com.pmm.sdgc.model.VariaveisLotacaoSub;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Juliano
*/
public class ModelVariaveisLotacaoSubWs {
private String lotacaoSub;
private String variaveisDesc;
private LocalDate periodoFolha;
private Boolean ativo;
public ModelVariaveisLotacaoSubWs(String lotacaoSub, String variaveisDesc, LocalDate periodoFolha, Boolean ativo) {
this.lotacaoSub = lotacaoSub;
this.variaveisDesc = variaveisDesc;
this.periodoFolha = periodoFolha;
this.ativo = ativo;
}
public static List<ModelVariaveisLotacaoSubWs> toModelLotacaoSubWs(List<VariaveisLotacaoSub> variaveisLotSub) {
List<ModelVariaveisLotacaoSubWs> mlw = new ArrayList();
for (VariaveisLotacaoSub v : variaveisLotSub) {
ModelVariaveisLotacaoSubWs lw = new ModelVariaveisLotacaoSubWs(
v.getLotacaoSub().getNome(),
v.getVariaveisDesc().getNome(),
v.getPeriodoFolha(),
v.getAtivo()
);
mlw.add(lw);
}
return mlw;
}
public String getLotacaoSub() {
return lotacaoSub;
}
public void setLotacaoSub(String lotacaoSub) {
this.lotacaoSub = lotacaoSub;
}
public String getVariaveisDesc() {
return variaveisDesc;
}
public void setVariaveisDesc(String variaveisDesc) {
this.variaveisDesc = variaveisDesc;
}
public LocalDate getPeriodoFolha() {
return periodoFolha;
}
public void setPeriodoFolha(LocalDate periodoFolha) {
this.periodoFolha = periodoFolha;
}
public Boolean getAtivo() {
return ativo;
}
public void setAtivo(Boolean ativo) {
this.ativo = ativo;
}
}
|
package com.gabriel.handyMan.controllers;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gabriel.handyMan.models.dto.ReporteDTO;
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class ReporteRestControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
void testCreate() throws Exception {
ReporteDTO newReporte = new ReporteDTO();
newReporte.setIdTecnico(1209L);
newReporte.setIdServicio(2L);
newReporte.setFechaInicio("2021-02-01T12:45");
newReporte.setFechaFin("2021-02-01T15:45");
ObjectMapper objectMapper = new ObjectMapper();
String jString = objectMapper.writeValueAsString(newReporte);
System.out.println(jString);
mockMvc.perform(post("/api/reportes/").content(jString).contentType("application/json;charset=UTF-8")
.characterEncoding("utf-8")).andExpect(status().isCreated());
}
}
|
package javaOOP;
public class cars {
// attributes and functions
public String vinNumber;
int numberOfdoors;
int numberOfWheels;
String carModel;
boolean blindSpot;
public void start() {
breakCar();
}
public void accelerate() {
}
public void checkMileage() {
}
private void breakCar() {
}
}
|
package maze.logic;
public class Hero extends Piece{
public Hero(int x, int y){
super(x,y,'H');
}
public Hero(){
super(1,1,'H');
}
public void move(char dir){
switch(dir){
case 'N':
case 'n':
posY--;
break;
case 'S':
case 's':
posY++;
break;
case 'E':
case 'e':
posX++;
break;
case 'O':
case 'o':
posX--;
}
}
public void undoMove(char dir){
switch(dir){
case 'S':
case 's':
posY--;
break;
case 'N':
case 'n':
posY++;
break;
case 'O':
case 'o':
posX++;
break;
case 'E':
case 'e':
posX--;
}
}
public void arm(){
symbol = 'A';
}
}
|
package com.javaArray;
import java.util.ArrayList;
public class Customer {
private String name;
private ArrayList<Double> transactions;
public Customer(String name, double amount) {
this.name = name;
this.transactions = new ArrayList<>();
addTransaction(amount);
}
public boolean addTransaction(double amount) {
if (amount >= 0) {
return this.transactions.add(amount);
}
return false;
}
public String getName() {
return name;
}
public ArrayList<Double> getTransactions() {
return transactions;
}
}
|
package com.esum.appetizer;
public interface AppetizerConst {
public static final String LOCALE_KEY = "LOCALE_KEY"; // 언어 키 - request.parameter, session.attribute
public static final String TIMEZONE_KEY = "TIMEZONE_KEY"; // 타임존 키 - request.parameter, session.attribute
public static final String SYSTEM_ADMIN = "admin"; // 시스템 관리자 ID
public static final String AUTH_SYSTEM_ADMIN = "A"; // 사용자 권한 - A: 시스템 관리자
}
|
package Day6LogicalPrograms;
import java.util.Scanner;
public class ReverseOfNumber {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to reverse it");
int N = scanner.nextInt();
int ReversedNo=0;
int remainder=0;
while(N>0)
{
remainder=N%10;
ReversedNo=ReversedNo*10+remainder;
N=N/10;
}
System.out.println("Reversed number: " +ReversedNo);
}
}
|
package com.pickup.pickup.controller;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.pickup.pickup.R;
/**
* Created by zachschlesinger on 4/1/17.
*/
public class JoinActivity extends AppCompatActivity {
private TextView display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_joinevent);
display = (TextView) findViewById(R.id.display);
display.setText(getTime().toString());
}
private String getTime() {
String[] times = {"12,2", "1,3", "2,4"};
Boolean[] person1 = {true, true, true};
Boolean[] person2 = {false, true, true};
Boolean[] person3 = {true, false, false};
Boolean[] person4 = {false, true, true};
Boolean[] person5 = {false, true, false};
Boolean[][] people = new Boolean[5][];
people[0] = person1;
people[1] = person2;
people[2] = person3;
people[3] = person4;
people[4] = person5;
int[] finalPeople = new int[4];
return "meh";
}
}
|
package MVC.controllers;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import MVC.models.inventoryModel;
import MVC.models.productModel;
import MVC.views.inventoryListView;
public class showInventoryController implements ListSelectionListener {
private inventoryListView view;
private inventoryModel model;
private productModel proModel;
private ArrayList<String> partList = new ArrayList<String>();
private ArrayList<String> products = new ArrayList<String>();
private String[] parts;
private JList list;
private MVC.views.invDetailView invDetailView;
private Date date;
private int flag =0;
private int nonproducts =0;
public showInventoryController(inventoryListView view, inventoryModel model, productModel proModel){
this.view = view;
this.model = model;
this.proModel = proModel;
}
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
} else {
//view.dispose();
//view.removeAll();
//view.repaint();
//view.remove(list);
//model.resetInv();
}
partList.clear();
//view.repaint();
view.revalidate();
//view.invalidate();
//System.out.println("outer valueChanged " +e.getValueIsAdjusting());
String command = view.getSelectedValue();
partList = model.getLocationIdPartByName(command);
partList = model.getPartsL();
nonproducts = partList.size();
flag = model.getProductFlag();
if (flag == 1) {
products = model.getProductsArray(command);
//System.out.println("product Arraylist = " +products.toString());
for (String tmp : products) {
//System.out.println("products");
int pid = Integer.parseInt(tmp);
String productDesc = proModel.getProductDescById(pid);
partList.add(productDesc);
}
model.resetSearch();
}
parts = new String[partList.size()];
parts = partList.toArray(parts);
list = new JList(parts);
list.setVisibleRowCount(5);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setFixedCellHeight(44);
list.setFixedCellWidth(100);
view.add(new JScrollPane(list),BorderLayout.CENTER);
view.setVisible(true);
//view.repaint();
//view.invalidate();
//}
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e2) {
if (e2.getValueIsAdjusting()) {
return;
} else {
//System.out.println("changed 2");
}
//model.resetInv();//maybe works
//System.out.println("First index: " + e2.getFirstIndex());
//System.out.println(", Last index: " + e2.getLastIndex());
view.repaint();
//view.revalidate();
view.invalidate();
//JList list = (JList) e2.getSource();
//System.out.println("list getselectedvalue " +list.getSelectedValue());
//System.out.println("inner valueChanged " +e2.getValueIsAdjusting());
int index = list.getSelectedIndex();
if (index >= nonproducts) {
JOptionPane.showMessageDialog(null, "Not able to edit product.");
model.resetInv();
view.repaint();
view.revalidate();
} else {
String str = list.getSelectedValue().toString();
//System.out.println("inner valueChanged " +str);
model.setCurrentInventory(str);
date = model.getCurrentTime();
//System.out.println("DATE ON OPENING INVENTORY DETAIL VIEW = "+ date);
//System.out.println("part9z = "+ date + "x");
invDetailView = new MVC.views.invDetailView(model);
//System.out.println("DetailView created!!");
//invDetailView.closeWindow();
showInvListController controller1 = new showInvListController(model, view, date);
invDetailView.registerListeners(controller1);
invDetailView.setSize(300, 250);
invDetailView.setLocation(800, 0);
invDetailView.setVisible(true);
//model.resetInv();
view.repaint();
//view.revalidate();
}
}
});
partList.clear();
//}
}
}
|
package com.alibaba.druid.bvt.sql.mysql.param;
import com.alibaba.fastjson2.JSON;
import com.alibaba.druid.sql.visitor.ParameterizedOutputVisitorUtils;
import com.alibaba.druid.sql.visitor.VisitorFeature;
import com.alibaba.druid.util.JdbcConstants;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.List;
public class MySqlParameterizedOutputVisitorTest_76 extends TestCase {
public void test_or() throws Exception {
String sql = "select * from select_base_one_one_db_multi_tb where pk>=7 and pk>4 and pk <=49 and pk<18 order by pk limit 1";
List<Object> outParameters = new ArrayList<Object>(0);
String psql = ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.MYSQL, outParameters, VisitorFeature.OutputParameterizedQuesUnMergeOr);
assertEquals("SELECT *\n" +
"FROM select_base_one_one_db_multi_tb\n" +
"WHERE pk >= ?\n" +
"\tAND pk > ?\n" +
"\tAND pk <= ?\n" +
"\tAND pk < ?\n" +
"ORDER BY pk\n" +
"LIMIT ?", psql);
assertEquals("[7,4,49,18,1]", JSON.toJSONString(outParameters));
}
public void test_and() throws Exception {
String sql = "select * from select_base_one_one_db_multi_tb where pk=1 and pk=4 and pk=49 and pk=18 order by pk limit 1";
List<Object> outParameters = new ArrayList<Object>(0);
String psql = ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.MYSQL, outParameters, VisitorFeature.OutputParameterizedQuesUnMergeAnd);
assertEquals("SELECT *\n" +
"FROM select_base_one_one_db_multi_tb\n" +
"WHERE pk = ?\n" +
"\tAND pk = ?\n" +
"\tAND pk = ?\n" +
"\tAND pk = ?\n" +
"ORDER BY pk\n" +
"LIMIT ?", psql);
assertEquals("[1,4,49,18,1]", JSON.toJSONString(outParameters));
}
}
|
package webCrawler;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.io.InputStream;
public class MyCrawler {
private static final String CRAWLED_FILE_DIRECTORY = "D:/workspace/WebCrawler1/repository/";
private static final String CSV_FILENAME = "specification.csv";
private static final long WAIT_TIME = 3000;
private static final String REPORT_FILENAME="report.html";
public static void main(String[] args) throws IOException {
CrawlingSeed cs = new CrawlingSeed();
FileIO fio = new FileIO();
UrlQueue queue = new UrlQueue();
UrlParser parser = new UrlParser();
cs.initCrawler(CSV_FILENAME);
String seedUrl = cs.getSeedUrl();
if (!seedUrl.isEmpty()) {
queue.addUnvisitedURL(seedUrl);
}
while (queue.hasUnvisitedPage() && queue.getVisitedPagesNum() <= cs.getMaxPages()) {
String url = queue.dequeUnvisitedURL();
Boolean hasDownloaded = false;
int statusCode = -1;
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
System.out.println("connecting to " + url);
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println(response.getStatusLine());
statusCode = response.getStatusLine().getStatusCode();
if(statusCode!=200){
System.err.println("Unable to get " + url);
}else {
try {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
String contentType = entity.getContentType().getValue();
if(fio.downloadHTML(url,CRAWLED_FILE_DIRECTORY,content,contentType)){
hasDownloaded = true;
}
} finally {
response.close();
}
}
}catch (IOException e) {
System.out.println("Oops! Unexpected failure!");
}finally {
httpClient.close();
}
parser.parseUrl(url, queue);
if(hasDownloaded){
parser.addRecord(url, parser.getTitle(), fio.getFilePath(), statusCode,
parser.getNumsOfLinks(), parser.getNumsOfImgs());
}
queue.addVisitedURL(url);
try {
Thread.sleep(WAIT_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
fio.writeReportHtml(parser.getRecordList());
}
}
|
package com.example.gitapi;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by sudhanshu on 3/6/16.
*/
public class CustomAdapter extends BaseAdapter {
Context context;
List<Commit> commitList;
public CustomAdapter(Context context, List<Commit> commitList) {
this.context = context;
this.commitList = commitList;
}
@Override
public int getCount() {
return commitList.size();
}
@Override
public Object getItem(int position) {
return commitList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.title1);
holder.sha = (TextView) convertView.findViewById(R.id.title2);
holder.message = (TextView) convertView.findViewById(R.id.title3);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Commit rowItem = (Commit) getItem(position);
holder.name.setText(rowItem.getUsername());
holder.sha.setText(rowItem.getSha());
holder.message.setText(rowItem.getMessage());
return convertView;
}
public class ViewHolder{
TextView name;
TextView sha;
TextView message;
}
}
|
/*
* 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 rpl_03;
/**
*
* @author ASUS ROG
*/
public class Data_Pembelian {
/**
* @return the id_Pembelian
*/
public int getId_Pembelian() {
return id_Pembelian;
}
/**
* @param id_Pembelian the id_Pembelian to set
*/
public void setId_Pembelian(int id_Pembelian) {
this.id_Pembelian = id_Pembelian;
}
/**
* @return the id_Karyawan
*/
public int getId_Karyawan() {
return id_Karyawan;
}
/**
* @param id_Karyawan the id_Karyawan to set
*/
public void setId_Karyawan(int id_Karyawan) {
this.id_Karyawan = id_Karyawan;
}
/**
* @return the id_Supplier
*/
public int getId_Supplier() {
return id_Supplier;
}
/**
* @param id_Supplier the id_Supplier to set
*/
public void setId_Supplier(int id_Supplier) {
this.id_Supplier = id_Supplier;
}
/**
* @return the Tanggal
*/
public char getTanggal() {
return Tanggal;
}
/**
* @param Tanggal the Tanggal to set
*/
public void setTanggal(char Tanggal) {
this.Tanggal = Tanggal;
}
/**
* @return the Total_Pembelian
*/
public int getTotal_Pembelian() {
return Total_Pembelian;
}
/**
* @param Total_Pembelian the Total_Pembelian to set
*/
public void setTotal_Pembelian(int Total_Pembelian) {
this.Total_Pembelian = Total_Pembelian;
}
private int id_Pembelian;
private int id_Karyawan;
private int id_Supplier;
private char Tanggal;
private int Total_Pembelian;
}
|
package org.qa.controllers;
import java.util.List;
import org.qa.automotives.Car;
import org.qa.dao.CarDAO;
import org.qa.utils.UserInput;
public class CarController implements Controller<Car> {
private UserInput input = UserInput.getInstance();
private CarDAO dao = new CarDAO();
@Override
public Car create() {
System.out.println("What is the maker of the car?");
String maker = input.getString();
System.out.println("What is the colour?");
String colour = input.getString();
System.out.println("How many wheels?");
int wheels= input.getInt();
System.out.println("How many doors?");
int doors= input.getInt();
return dao.create(new Car(maker, colour, wheels, doors));
}
@Override
public int delete() {
for(Car car: dao.readAll()) {
System.out.println(car);
}
System.out.println("ID of car to delete?");
int id = input.getInt();
return dao.delete(id);
}
@Override
public List<Car> readAll() {
return dao.readAll();
}
@Override
public Car readByID() {
for(Car car: dao.readAll()) {
System.out.println("ID="+car.getID());
}
System.out.println("Which ID to view?");
int id = input.getInt();
return dao.readByID(id);
}
@Override
public Car update() {
for(Car car: dao.readAll()) {
System.out.println(car);
}
System.out.println("Please select a car to edit");
int id = input.getInt();
Car car = dao.readByID(id);
System.out.println(car);
System.out.println("What is the new maker of the car?");
car.setMaker(input.getString());
System.out.println("What is the new colour?");
car.setColour(input.getString());
System.out.println("How many wheels?");
car.setWheels(input.getInt());
System.out.println("How many doors?");
car.setDoors(input.getInt());
return dao.update(car);
}
}
|
package com.esum.router;
import java.io.File;
import javax.servlet.ServletException;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.framework.common.util.DateUtil;
import com.esum.framework.common.util.SysConstants;
import com.esum.framework.common.util.SysUtil;
import com.esum.framework.core.component.ComponentException;
import com.esum.framework.core.config.Configurator;
import com.esum.framework.core.exception.SystemException;
import com.esum.framework.net.http.proxy.EchoServlet;
import com.esum.framework.net.http.proxy.ProxyServlet;
import com.esum.framework.net.http.server.tomcat.Tomcat70;
import com.esum.framework.product.ProductInfo;
public class ProxyMain extends Thread {
private static Logger log = LoggerFactory.getLogger(ProxyMain.class);
private static String proxyHome;
private String traceId = "[PROXY] ";
public ProxyMain() {
// setDaemon(true);
}
private void startHttpProxyHandler() throws SystemException {
Tomcat70 tomcat = null;
try {
tomcat = Tomcat70.getInstance();
if(tomcat==null || !tomcat.isAlived()) {
tomcat = Tomcat70.newInstance();
}
} catch (Exception e) {
throw new ComponentException("startHttpProxyHandler", " EmbeddedTomcat is not started !! ");
}
/**
use.proxy = true
proxy.context.path = /proxy
proxy.deploy.path = ${xtrus.home}/repository/http/proxy
proxy.http.target.url=http://{target_host}:{target_port}
*/
try {
String proxyContextPath = Configurator.getInstance().getString("proxy.context.path", "/proxy");
String proxyDocBase = SysUtil.replacePropertyToValue(
Configurator.getInstance().getString("proxy.deploy.path", "${xtrus.home}/repository/http/proxy"));
if(!FileUtils.getFile(proxyDocBase).exists()) {
FileUtils.getFile(proxyDocBase).mkdirs();
}
tomcat.createContext(proxyContextPath, proxyDocBase, "proxy","/handler/*", null, new ProxyServlet());
tomcat.addServlet(proxyContextPath, "echo", "/echo/*", new EchoServlet());
} catch (ServletException e) {
throw new RouterException("startHttpProxyHandler", "can not create status servlet handler.", e);
}
}
public void run() {
log.info(traceId+"Starting Http Proxy...");
System.out.println("Starting Http Proxy...");
try {
startHttpProxyHandler();
} catch (SystemException e) {
log.error(e.getMessage(), e);
return;
}
log.info(traceId+"Started Http Proxy...");
System.out.println("Started Http Proxy...");
while(!Thread.interrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
log.warn(traceId+"Proxy Server shutdown called.");
}
public void shutdown() throws SystemException {
log.info(traceId+"Shutdown Proxy Component.");
try {
Tomcat70 tomcat = Tomcat70.getInstance();
if(tomcat!=null)
tomcat.stop();
tomcat = null;
} catch (Exception e) {
}
}
public static void main(String[] args) throws Exception {
proxyHome = System.getProperty("xtrus.home");
if (proxyHome == null || proxyHome.equals("")) {
throw new Exception("xTrus Proxy Home Error!! Please set the system variable which is <xtrus.home>.");
}
ProductInfo productInfo = new ProductInfo(RouterMain.PRODUCT_NAME, RouterMain.VERSION);
System.out.println(productInfo);
PropertyConfigurator.configure(proxyHome + "/conf/log.properties");
log.info(productInfo.toString());
String configPath = proxyHome + File.separator + "conf" + File.separator;
Configurator.init(configPath + "proxy.properties");
SysConstants.DEFAULT_ENCODING = Configurator.getInstance().getString("system.default.encoding", "UTF-8");
Configurator.init(Configurator.DEFAULT_HTTP_CONFIG_ID, configPath + "http.properties");
Configurator.init(Configurator.DEFAULT_SSL_CONFIG_ID, configPath + "ssl.properties");
System.out.println("Starting xTrus Proxy... node.id : "+Configurator.getInstance().getString("node.id"));
boolean useProxy = Configurator.getInstance().getBoolean("use.proxy", false);
if(useProxy) {
System.out.println("Starting Proxy Main Processor...");
ProxyMain proxyMain = new ProxyMain();
Runtime.getRuntime().addShutdownHook(new Thread("proxy-shutdown-thread") {
public void run() {
String date = DateUtil.format("yyyy/MM/dd HH:mm:ss:SSS");
System.out.println("["+date+"] Proxy Main Server shutdowned.");
try {
Tomcat70 t = Tomcat70.getInstance();
if(t!=null && t.isAlived())
t.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
});
proxyMain.start();
} else {
throw new Exception("<use.proxy> property value is false. can not start proxy server.");
}
}
}
|
package com.example.eduardoalejandro.encuesta.encuesta;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.eduardoalejandro.encuesta.R;
public class LoginActivity extends AppCompatActivity {
String text_sucursal,text_sociedad;
/******variables para spinners*********/
Spinner spinner_sucursal, spinner_local;
/*******variable para boton**********/
Button boton_ingresar;
/******* variable para preferencias*****/
private SharedPreferences prs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
/****ejecuta identificadores *****/
Identificadores();
prs = getSharedPreferences("Preferences", Context.MODE_PRIVATE);
/*****adapatador para spinner sociedad*****/
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.sociedades, android.R.layout.simple_spinner_item);
/*****adapatadores por sucursal*****/
final ArrayAdapter<CharSequence> adapter_arandas = ArrayAdapter.createFromResource(this, R.array.sucursales_arandas, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_autlan = ArrayAdapter.createFromResource(this, R.array.sucursales_autlan, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_ayotlan = ArrayAdapter.createFromResource(this, R.array.sucursales_ayotlan, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_bajio = ArrayAdapter.createFromResource(this, R.array.sucursales_bajio, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_dao = ArrayAdapter.createFromResource(this, R.array.sucursales_dao, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_gao = ArrayAdapter.createFromResource(this, R.array.sucursales_gao, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_ixtapa = ArrayAdapter.createFromResource(this, R.array.sucursales_ixtapa, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_la_cienega = ArrayAdapter.createFromResource(this, R.array.sucursales_lacienega, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_laminas = ArrayAdapter.createFromResource(this, R.array.sucursales_laminas_del_norte, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_los_altos = ArrayAdapter.createFromResource(this, R.array.sucursales_los_altos, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_mucha = ArrayAdapter.createFromResource(this, R.array.sucursales_mucha_lamina, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_pega = ArrayAdapter.createFromResource(this, R.array.sucursales_pega, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_SAABSA = ArrayAdapter.createFromResource(this, R.array.sucursales_saabsa, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_tepa = ArrayAdapter.createFromResource(this, R.array.sucursales_tepa, android.R.layout.simple_spinner_item);
final ArrayAdapter<CharSequence> adapter_tijuna = ArrayAdapter.createFromResource(this, R.array.sucursales_tijuana, android.R.layout.simple_spinner_item);
spinner_local.setAdapter(adapter);
spinner_local.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (spinner_local.getSelectedItemPosition()==0){
spinner_sucursal.setAdapter(adapter_arandas);
}
else if(spinner_local.getSelectedItemPosition()==1){
spinner_sucursal.setAdapter(adapter_autlan);
}
else if(spinner_local.getSelectedItemPosition()==2){
spinner_sucursal.setAdapter(adapter_ayotlan);
}
else if(spinner_local.getSelectedItemPosition()==3){
spinner_sucursal.setAdapter(adapter_bajio);
}
else if(spinner_local.getSelectedItemPosition()==4){
spinner_sucursal.setAdapter(adapter_dao);
}
else if(spinner_local.getSelectedItemPosition()==5){
spinner_sucursal.setAdapter(adapter_gao);
}
else if(spinner_local.getSelectedItemPosition()==6){
spinner_sucursal.setAdapter(adapter_ixtapa);
}
else if(spinner_local.getSelectedItemPosition()==7){
spinner_sucursal.setAdapter(adapter_la_cienega);
}
else if(spinner_local.getSelectedItemPosition()==8){
spinner_sucursal.setAdapter(adapter_laminas);
}
else if(spinner_local.getSelectedItemPosition()==9){
spinner_sucursal.setAdapter(adapter_los_altos);
}
else if(spinner_local.getSelectedItemPosition()==10){
spinner_sucursal.setAdapter(adapter_mucha);
}
else if(spinner_local.getSelectedItemPosition()==11){
spinner_sucursal.setAdapter(adapter_pega);
}
else if(spinner_local.getSelectedItemPosition()==12){
spinner_sucursal.setAdapter(adapter_SAABSA);
}
else if(spinner_local.getSelectedItemPosition()==13){
spinner_sucursal.setAdapter(adapter_tepa);
}
else {
spinner_sucursal.setAdapter(adapter_tijuna);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
boton_ingresar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
text_sucursal = spinner_sucursal.getSelectedItem().toString();
text_sociedad = spinner_local.getSelectedItem().toString();
Toast.makeText(LoginActivity.this, text_sucursal +" "+ text_sociedad, Toast.LENGTH_SHORT).show();
NuevaActividad();
GuardarPreferencias(text_sociedad, text_sucursal);
}
});
}
private void GuardarPreferencias(String sociedad, String sucursal){
SharedPreferences.Editor editor = prs.edit();
editor.putString("sociedad", sociedad);
editor.putString("sucursal", sucursal);
editor.apply();
}
/******* metodo identificadores ********/
private void Identificadores(){
spinner_sucursal = (Spinner) findViewById(R.id.spinner_sucursal);
spinner_local = (Spinner) findViewById(R.id.spinner_local);
boton_ingresar= (Button) findViewById(R.id.boton_ingresar);
}
/******* metodo para mostrar actividad ********/
private void NuevaActividad(){
Intent i = new Intent(LoginActivity.this, Inicio.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
/******* metodo para setear sucural y sociedad ********/
private void setPreferencias(){
String sociedad = MetodosSharedPreference.getSociedadPref(prs);
String sucursal = MetodosSharedPreference.getSucursalPref(prs);
}
}
|
package org.foolip.mushup;
import java.io.*;
import java.net.*;
import java.util.regex.*;
import javax.xml.parsers.*;
import org.xml.sax.SAXException;
import org.w3c.dom.*;
import org.htmlparser.*;
import org.htmlparser.filters.*;
import org.htmlparser.tags.*;
import org.htmlparser.util.*;
public class WikipediaBlurb {
private final static int blurbLength = 200;
public static String getBlurb(String url) throws WikipediaException {
Pattern pattern = Pattern.compile("^(http://[^.]+\\.wikipedia.org)/wiki/(.+)$");
Matcher m = pattern.matcher(url);
if (!m.matches())
throw new WikipediaException("Unrecognized Wikipedia URL: " + url);
String baseUrl = m.group(1);
String page = m.group(2);
String apiUrl = baseUrl + "/w/api.php?format=xml&action=parse&prop=text&page=" + page;
Document doc;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
doc = factory.newDocumentBuilder().parse(new URL(apiUrl).openStream());
} catch (ParserConfigurationException e) {
throw new WikipediaException(e);
} catch (SAXException e) {
throw new WikipediaException(e);
} catch (IOException e) {
throw new WikipediaException(e);
}
org.w3c.dom.NodeList nodes = doc.getElementsByTagName("text");
if (nodes.getLength() == 0)
throw new WikipediaException("No parsed text returned");
String html = ((Element)nodes.item(0)).getTextContent();
Parser parser = Parser.createParser(html, "UTF-8");
PrototypicalNodeFactory factory = new PrototypicalNodeFactory();
factory.registerTag (new SupTag());
parser.setNodeFactory (factory);
org.htmlparser.util.NodeList nl;
try {
nl = parser.parse(null);
} catch (ParserException e) {
throw new WikipediaException(e);
}
// only consider top-level paragraphs
nl.keepAllNodesThatMatch(new TagNameFilter("P"));
if (nl.size() == 0)
throw new WikipediaException("No paragraphs in article");
// get rid of references ...
nl.keepAllNodesThatMatch(new NotFilter(new CssClassFilter("reference")), true);
// ... [citation needed] ...
nl.keepAllNodesThatMatch(new NotFilter(new CssClassFilter("noprint")), true);
// ... and [n]
nl.keepAllNodesThatMatch(new NotFilter(new CssClassFilter("autonumber")), true);
StringBuilder blurb = new StringBuilder();
for (SimpleNodeIterator i = nl.elements(); i.hasMoreNodes();) {
String plainText = Translate.decode(i.nextNode().toPlainTextString());
blurb.append(plainText.replaceAll("\\s+", " "));
// FIXME: Chinese doesn't want spaces!
blurb.append(" ");
if (blurb.length() > blurbLength)
break;
}
if (blurb.length() < 20) {
throw new WikipediaException("Rejecting almost empty article");
}
// cut at the appropriate blurb length
if (blurb.length() <= blurbLength) {
return blurb.toString();
}
// remove last word
int lastSpace = blurb.lastIndexOf(" ", blurbLength);
if (blurbLength - lastSpace < 20) {
return blurb.substring(0, lastSpace);
}
return blurb.substring(0, blurbLength);
}
public static final class SupTag extends CompositeTag
{
private static final String[] mIds = new String[] {"SUP"};
public String[] getIds () { return (mIds); }
public String[] getEnders () { return (mIds); }
public String[] getEndTagEnders () { return (new String[0]); }
}
}
|
package com.crmiguez.aixinainventory.apirest;
import com.crmiguez.aixinainventory.entities.ItemImages;
import com.crmiguez.aixinainventory.exception.ResourceNotFoundException;
import com.crmiguez.aixinainventory.service.itemimages.IItemImagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
//@RequestMapping("/api_aixina/v1")
@RequestMapping("/api_aixina/v1/itemimagesmanage")
@CrossOrigin(origins = "*", methods= {RequestMethod.GET,RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
public class ItemImagesController {
@Autowired
@Qualifier("itemImagesService")
private IItemImagesService itemImagesService;
@PreAuthorize("hasAuthority('PERM_READ_ALL_ITEM_IMAGES')")
@GetMapping("/itemimages")
public List<ItemImages> getAllItemImagess() {
return itemImagesService.findAllItemImagess();
}
@PreAuthorize("hasAuthority('PERM_READ_ITEM_IMAGE')")
@GetMapping("/itemimages/{id}")
public ResponseEntity<ItemImages> getItemImagesById(
@PathVariable(value = "id") Long itemImagesId) throws ResourceNotFoundException {
ItemImages ItemImages = itemImagesService.findItemImagesById(itemImagesId)
.orElseThrow(() -> new ResourceNotFoundException("ItemImages not found on :: "+ itemImagesId));
return ResponseEntity.ok().body(ItemImages);
}
@PreAuthorize("hasAuthority('PERM_CREATE_ITEM_IMAGE')")
@PostMapping("/itemimage")
public ItemImages createItemImages(@Valid @RequestBody ItemImages itemImages) { return itemImagesService.addItemImages(itemImages); }
@PreAuthorize("hasAuthority('PERM_UPDATE_ITEM_IMAGE')")
@PutMapping("/itemimages/{id}")
public ResponseEntity<ItemImages> updateItemImages(
@PathVariable(value = "id") Long itemImagesId,
@Valid @RequestBody ItemImages itemImagesDetails) throws ResourceNotFoundException {
ItemImages itemImages = itemImagesService.findItemImagesById(itemImagesId)
.orElseThrow(() -> new ResourceNotFoundException("ItemImages not found on :: "+ itemImagesId));
final ItemImages updatedItemImages = itemImagesService.updateItemImages(itemImagesDetails, itemImages);
if (updatedItemImages == null){
return new ResponseEntity<ItemImages>(HttpStatus.EXPECTATION_FAILED);
} else {
return ResponseEntity.ok(updatedItemImages);
}
}
@PreAuthorize("hasAuthority('PERM_DELETE_ITEM_IMAGE')")
@DeleteMapping("/itemimage/{id}")
public Map<String, Boolean> deleteItemImages(
@PathVariable(value = "id") Long itemImagesId) throws Exception {
ItemImages itemImages = itemImagesService.findItemImagesById(itemImagesId)
.orElseThrow(() -> new ResourceNotFoundException("ItemImages not found on :: "+ itemImagesId));
itemImagesService.deleteItemImages(itemImages);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
|
package com.NewTours_LoginFunctionality;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class NewTours_Loginfunctionality_ExcelOperations {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver","C:\\Users\\new\\eclipse-workspace\\BrowserAutomation\\DriverFiles\\chromedriver.exe");
WebDriver driver =null;
String url="http://www.newtours.demoaut.com/";
driver = new ChromeDriver();
driver.get(url);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
FileInputStream file=new FileInputStream("C:\\Users\\new\\eclipse-workspace\\BrowserAutomation\\src\\com\\ExcelFiles\\NewTours_Multiple Testdata.xlsx");
XSSFWorkbook Workbook=new XSSFWorkbook(file);
XSSFSheet Sheet=Workbook.getSheet("Sheet1");
int rowcount=Sheet.getLastRowNum();
for(int k=1;k<=rowcount;k++) {
Row r=Sheet.getRow(k);
//cell c=r.getCell(k).getStringCellValue();
Cell usernamecell=r.getCell(0);
Cell passwordcell=r.getCell(1);
String Username=usernamecell.getStringCellValue();
String Password=passwordcell.getStringCellValue();
driver.findElement(By.linkText("SIGN-ON")).click();
WebElement UsernameElement=driver.findElement(By.name("userName"));
UsernameElement.sendKeys(Username);
WebElement PasswordElement=driver.findElement(By.name("password"));
PasswordElement.sendKeys(Password);
WebElement Submit=driver.findElement(By.name("login"));
Submit.click();
}
}
}
|
package history.value;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Scanner;
import javax.servlet.http.*;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.google.appengine.labs.repackaged.org.json.JSONTokener;
import com.google.appengine.repackaged.com.google.api.client.util.IOUtils;
import com.opencsv.CSVParser;
import com.opencsv.CSVReader;
import classes.HistoricalValuess;
@SuppressWarnings("serial")
public class HistoricalValueServlet extends HttpServlet {
double lat;
double lng;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html; charset=utf-8");
String var1 = req.getParameter("var1");
String var2 = req.getParameter("var2");
char dol = '$';
char fig = '}';
URL url = new URL("http://localhost:8888/csv/1.csv");
//TODO URL url = new URL("http://examples-web.appspot.com/io/districts.csv");
//обязательно укажите кодировку иначе на сервере AppEngine будут проблемы с кодировкой
CSVReader reader = new CSVReader(
new InputStreamReader(url.openStream()),
dol, CSVParser.DEFAULT_QUOTE_CHARACTER,
1);
String[] nextLine;
// Создание пустого массива bridges с объектами класса BridgeClass
ArrayList<HistoricalValuess> bridges = new ArrayList<HistoricalValuess>();
// Заполнение массива данными из файла
while ((nextLine = reader.readNext()) != null) {
bridges.add(new HistoricalValuess(nextLine));
}
boolean bool = true;
for (int k = 0; k < 367; k++) {
//resp.getWriter().println(bridges.get(k).getWho());
if (bridges.get(k).getWho().contains(var1) && bridges.get(k).getWho().contains(var2)) {
resp.getWriter().println(bridges.get(k).getWho() + " " + bridges.get(k).getWhen());
bool = false;
}
}
if (bool) {
String addres = "Санкт-Петербург, " + var1 + " " + var2;
try {
geocoding(addres);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resp.getWriter().println("Адреса нет в списке объектов культуного наследия: " + var1 + ", " + var2 + "; широта: " + lat +
"; долгота: " + lng);
} else {
String address = "Санкт-Петербург, " + var1 + " " + var2;
try {
geocoding(address);
resp.getWriter().println("широта: " + lat + "; долгота: " + lng);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*resp.getWriter().println("<script>");
resp.getWriter().println("function initialize() {");
resp.getWriter().println("var myLatlng = new google.maps.LatLng(" + lat + ", " + lng + ");");
resp.getWriter().println("var mapOptions = {");
resp.getWriter().println("zoom : 11,");
resp.getWriter().println("center : myLatlng");
resp.getWriter().println("};");
resp.getWriter().println("map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);");
resp.getWriter().println("var contentString = '<div id=\"content\">'");
resp.getWriter().println("+ '<div id=\"siteNotice\">'");
resp.getWriter().println("+ '</div>'");
resp.getWriter().println("+ '<h1 id=\"firstHeading\" class=\"firstHeading\">Сургут</h1>'");
resp.getWriter().println("+ '<div id=\"bodyContent\">'");
resp.getWriter().println("+ '<p><b>Сургут</b>, мой дом.</p>' + '</div>' + '</div>';");
resp.getWriter().println("var contentString2 = 'TEST';");
resp.getWriter().println("var infowindow = new google.maps.InfoWindow({");
resp.getWriter().println("content : contentString");
resp.getWriter().println("});");
resp.getWriter().println("var marker = new google.maps.Marker({");
resp.getWriter().println("position : myLatlng,");
resp.getWriter().println("map : map,");
resp.getWriter().println("title : 'Сургут (мой дом)'");
resp.getWriter().println("});");
resp.getWriter().println("google.maps.event.addListener(marker, 'click', function() {");
resp.getWriter().println("infowindow.open(map, marker);");
resp.getWriter().println("});");
resp.getWriter().println("}");
resp.getWriter().println("function createMarker(myLatlng, contentString, mytitle) {");
resp.getWriter().println("marker = new google.maps.Marker({");
resp.getWriter().println("position : myLatlng,");
resp.getWriter().println("map : map,");
resp.getWriter().println("title : mytitle");
resp.getWriter().println("});");
resp.getWriter().println("infowindow = new google.maps.InfoWindow({");
resp.getWriter().println("content : contentString");
resp.getWriter().println("});");
resp.getWriter().println("google.maps.event.addListener(marker, 'click', function() {");
resp.getWriter().println("infowindow.open(map, marker);");
resp.getWriter().println("});");
resp.getWriter().println("}");
resp.getWriter().println("google.maps.event.addDomListener(window, 'load', initialize);");
resp.getWriter().println("</script>");*/
//resp.getWriter().println("<div id=\"map-canvas\"></div>");
//resp.getWriter().println(bridges.get(0).getWho());
//resp.getWriter().println(bridges.get(2).getWho());
reader.close();
}
public void geocoding(String addr) throws Exception
{
// build a URL
String s = "http://maps.google.com/maps/api/geocode/json?" +
"sensor=false&address=";
s += URLEncoder.encode(addr, "UTF-8");
URL url = new URL(s);
// read from the URL
Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
str += scan.nextLine();
scan.close();
// build a JSON object
JSONObject obj = new JSONObject(str);
//if (! obj.getString("status").equals("OK"))
// return;
// get the first result
JSONObject res = obj.getJSONArray("results").getJSONObject(0);
System.out.println(res.getString("formatted_address"));
JSONObject loc =
res.getJSONObject("geometry").getJSONObject("location");
System.out.println("lat: " + loc.getDouble("lat") +
", lng: " + loc.getDouble("lng"));
lat = loc.getDouble("lat");
lng = loc.getDouble("lng");
}
}
|
/**
*/
package featureModel;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Binary Operation</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link featureModel.BinaryOperation#getRexp <em>Rexp</em>}</li>
* <li>{@link featureModel.BinaryOperation#getLexp <em>Lexp</em>}</li>
* <li>{@link featureModel.BinaryOperation#getOperator <em>Operator</em>}</li>
* </ul>
* </p>
*
* @see featureModel.FeatureModelPackage#getBinaryOperation()
* @model
* @generated
*/
public interface BinaryOperation extends Expression {
/**
* Returns the value of the '<em><b>Rexp</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Rexp</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Rexp</em>' containment reference.
* @see #setRexp(Expression)
* @see featureModel.FeatureModelPackage#getBinaryOperation_Rexp()
* @model containment="true" required="true"
* @generated
*/
Expression getRexp();
/**
* Sets the value of the '{@link featureModel.BinaryOperation#getRexp <em>Rexp</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Rexp</em>' containment reference.
* @see #getRexp()
* @generated
*/
void setRexp(Expression value);
/**
* Returns the value of the '<em><b>Lexp</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Lexp</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Lexp</em>' containment reference.
* @see #setLexp(Expression)
* @see featureModel.FeatureModelPackage#getBinaryOperation_Lexp()
* @model containment="true" required="true"
* @generated
*/
Expression getLexp();
/**
* Sets the value of the '{@link featureModel.BinaryOperation#getLexp <em>Lexp</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Lexp</em>' containment reference.
* @see #getLexp()
* @generated
*/
void setLexp(Expression value);
/**
* Returns the value of the '<em><b>Operator</b></em>' attribute.
* The literals are from the enumeration {@link featureModel.BinaryOperator}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Operator</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Operator</em>' attribute.
* @see featureModel.BinaryOperator
* @see #setOperator(BinaryOperator)
* @see featureModel.FeatureModelPackage#getBinaryOperation_Operator()
* @model required="true"
* @generated
*/
BinaryOperator getOperator();
/**
* Sets the value of the '{@link featureModel.BinaryOperation#getOperator <em>Operator</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Operator</em>' attribute.
* @see featureModel.BinaryOperator
* @see #getOperator()
* @generated
*/
void setOperator(BinaryOperator value);
} // BinaryOperation
|
package com.darwinsys.soundrec;
import java.io.File;
import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
/**
* Sound Recording Service, originally forked from jpstrack.android's VoiceNoteActivity.
* @author Ian Darwin
*/
public class SoundRecService extends Service {
private final String TAG = "SoundRecService";
MediaRecorder recorder = null;
private String soundFile;
@Override
public void onCreate() {
Log.d(TAG, "SoundRecService.onHandleIntent()");
if (!isSdWritable()) {
Toast.makeText(this, "SD Card not writable", Toast.LENGTH_LONG).show();
return;
}
}
private boolean isSdWritable() {
// TODO Auto-generated method stub
return true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int mode = intent.getIntExtra(VoiceNoteActivity.START_STOP_COMMAND, 0);
switch (mode) {
case 1:
startRecording(intent, startId);
return START_STICKY;
case 2:
saveRecording();
return START_STICKY;
case 3:
discardRecording();
return START_STICKY;
default:
throw new IllegalStateException();
}
}
protected void startRecording(Intent intent, int startId) {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
Uri soundUri = intent.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
Log.d(TAG, "SoundUri = " + soundUri);
if (soundUri == null) {
String DIRNAME = "/mnt/sdcard/soundrec";
new File(DIRNAME).mkdirs();
soundFile = DIRNAME + "/sample" + startId + ".mp3";
} else {
soundFile = soundUri.getPath();
}
recorder.setOutputFile(soundFile);
Log.d(TAG, "outputting to " + soundFile);
recorder.prepare();
recorder.start();
Toast.makeText(this, "Started...", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
final String message = "Could not create file:" + e;
Log.e(TAG, message);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
private void discardRecording() {
if (recorder == null) {
return;
}
recorder.stop();
recorder.release();
new File(soundFile).delete();
Toast.makeText(this, "Not saved", Toast.LENGTH_SHORT).show();
}
private void saveRecording() {
if (recorder == null) {
return;
}
recorder.stop();
recorder.release();
Toast.makeText(this, "Saved voice note into " + soundFile, Toast.LENGTH_SHORT).show();
// We don't tell the MediaStore about it as it's not music!
}
@Override
public IBinder onBind(Intent arg0) {
// Not used in this application.
return null;
}
}
|
package owner;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("owner.beans");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationConfig.xml");
context.getBean("person");
}
}
|
/**
* Created by kevin.huang on 2020-09-16.
*/
package foo;
public class User {
private String name;
private int age;
//@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
public Phone phone;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "[User " + "name='" + name + '\'' + ", age=" + age + ", phone=" + phone + ']';
}
}
|
package 수행; ����;
public class Child extends User{
int num,money,age,movenum,moneyh;
public int getMoneyh() {
return moneyh;
}
public void setMoneyh(int moneyh) {
this.moneyh = moneyh;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getMovenum() {
return movenum;
}
public void setMovenum(int movenum) {
this.movenum = movenum;
}
}
|
/**
*
*/
package com.needii.dashboard.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.needii.dashboard.helper.ResponseStatusEnum;
import com.needii.dashboard.model.BaseResponse;
import com.needii.dashboard.model.City;
import com.needii.dashboard.service.CityService;
/**
* @author kelvin
*
*/
@Controller
@RequestMapping(value = "/cities" )
public class CityController extends BaseController {
@Autowired
ServletContext context;
@Autowired
private CityService cityService;
@RequestMapping(value = "", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<BaseResponse> get(@RequestParam(name = "name", required=false, defaultValue = "") String name,
@RequestParam(name = "limit", required=false, defaultValue = "65") String limit) {
BaseResponse response = new BaseResponse();
response.setStatus(ResponseStatusEnum.SUCCESS);
response.setMessage(ResponseStatusEnum.SUCCESS);
response.setData(null);
try {
Pageable pageable = new PageRequest(0, Integer.valueOf(limit));
List<City> cities = cityService.findByName(name, pageable);
List<Object> objects = new ArrayList<Object>();
for (City city : cities) {
Object data = new Object() {
@SuppressWarnings("unused")
public final long id = city.getId();
@SuppressWarnings("unused")
public final String text = city.getName();
};
objects.add(data);
}
response.setResults(objects);
} catch(Exception ex) {
response.setStatus(ResponseStatusEnum.FAIL);
response.setMessageError(ex.getMessage());
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
@RequestMapping(value = "/all", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<BaseResponse> getAll(@RequestParam(name = "name", required=false, defaultValue = "") String name) {
BaseResponse response = new BaseResponse();
response.setStatus(ResponseStatusEnum.SUCCESS);
response.setMessage(ResponseStatusEnum.SUCCESS);
response.setData(null);
try {
List<City> cities = cityService.findAll();
List<Object> objects = new ArrayList<Object>();
for (City city : cities) {
Object data = new Object() {
public final long id = city.getId();
@SuppressWarnings("unused")
public final String text = city.getName();
};
objects.add(data);
}
response.setResults(objects);
} catch(Exception ex) {
response.setStatus(ResponseStatusEnum.FAIL);
response.setMessageError(ex.getMessage());
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
}
|
package com.newbig.im.model.dto;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotEmpty;
@Setter
@Getter
public class LoginDto {
@NotEmpty(message = "手机号不能为空")
private String mobile;
@NotEmpty(message = "密码不能为空")
@Length(min = 6, message = "密码错误")
private String password;
}
|
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
public class NodeTest {
@Test
public void test1() {
String str = "1";
String str2 = "2";
Node node1 = new Node(str, str2, 1);
Node node2 = new Node(str, str2, 1);
Assert.assertEquals(node1, node2);
}
@Test
public void test2() {
Node node1 = new Node("1", "1", 1);
Node node2 = new Node("11", "3", 1);
Assert.assertNotEquals(node1, node2);
}
@Test
public void test3() {
String str = "1";
String str2 = "2";
Node node1 = new Node(str, str2, 1);
Node node2 = new Node(str, str2, 1);
Assert.assertEquals(node1.hashCode(), node2.hashCode());
}
@Test
public void test4() {
Node node1 = new Node("1", "1", 1);
Node node2 = new Node("11", "3", 1);
Assert.assertNotEquals(node1.hashCode(), node2.hashCode());
}
}
|
/**
* Writes data of various types to standard output using StdOut.java
*/
//write to stdout
StdOut.println("Test");
StdOut.println(12);
StdOut.println(true);
StdOut.printf("%.6f\n", 1.0/7.0);
|
// @SOURCE:/Users/zefirini/Documents/Cours/Licence Pro 2013 - 2014/GitHub/Palindrome/conf/routes
// @HASH:406dd2c830d7052fe2d2ae5ceb1d2e93086dd79f
// @DATE:Mon Jan 27 17:49:34 CET 2014
package controllers;
public class routes {
public static final controllers.ReversePalindrome Palindrome = new controllers.ReversePalindrome();
public static final controllers.ReverseAssets Assets = new controllers.ReverseAssets();
public static class javascript {
public static final controllers.javascript.ReversePalindrome Palindrome = new controllers.javascript.ReversePalindrome();
public static final controllers.javascript.ReverseAssets Assets = new controllers.javascript.ReverseAssets();
}
public static class ref {
public static final controllers.ref.ReversePalindrome Palindrome = new controllers.ref.ReversePalindrome();
public static final controllers.ref.ReverseAssets Assets = new controllers.ref.ReverseAssets();
}
}
|
package net.dtkanov.lac.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import net.dtkanov.lac.core.Card;
public class CardPanel extends JPanel {
public CardPanel(Card c) {
super();
isFlipable = true;
setPreferredSize(new Dimension(600, 300));
setLayout(new BorderLayout());
setBorder(BorderFactory.createLineBorder(Color.black));
text = new JLabel();
text.setFont(text.getFont().deriveFont(CARD_TEXT_SIZE));
text.setHorizontalAlignment(SwingConstants.CENTER);
add(text, BorderLayout.CENTER);
setCard(c);
addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
if (isFlipable)
flip();
}
});
}
public void setFlipable(boolean isF) {
isFlipable = isF;
}
public void setCard(Card c) {
card = c;
setSide1();
}
public void setSide1() {
text.setText(card.getSide1());
isSide1 = true;
setBackground(Color.yellow);
repaint();
}
public void setSide2() {
text.setText(card.getSide2());
isSide1 = false;
setBackground(Color.white);
repaint();
}
public void flip() {
if (isSide1)
setSide2();
else
setSide1();
}
private boolean isFlipable;
private boolean isSide1;
private Card card;
private JLabel text;
private static final long serialVersionUID = -5362125150033909667L;
public static final float CARD_TEXT_SIZE = 60.0f;
}
|
package ua.max.sprite;
import application.Game;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.util.Duration;
import ua.max.pane.Player;
public class Timer {
private final Integer startTime = 60;
private Integer seconds = startTime;
private Label label;
protected HBox layout;
protected Pane pane;
protected Timeline time;
private Player player;
public Timer(Player player, Pane pane, Label label, HBox layout) {
this.player=player;
this.pane = pane;
this.label = label;
this.layout = layout;
label.setTextFill(Color.BLACK);
label.setFont(Font.font(20));
layout.getChildren().add(label);
doTime();
pane.getChildren().add(layout);
}
public void doTime() {
time = new Timeline();
time.setCycleCount(Timeline.INDEFINITE);
if (time != null) {
time.stop();
}
KeyFrame frame = new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
seconds--;
label.setText("TIME LEFT: " + seconds.toString());
if (seconds <= 0) {
Game.aTimer.stop();
Game.exist = false;
time.stop();
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("MAX ALERT");
alert.setHeaderText("TIME IS UP");
String s;
if(player.win){
s ="YOU HAVE WIN! YOUR SCORES: " + player.score;
} else {
s ="YOU HAVE LOST!";
}
alert.setContentText(s);
alert.show();
alert.showingProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue) {
System.exit(0);
}
});
/* Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Confirmation Dialog");
alert.setHeaderText("Look, a Confirmation Dialog");
alert.setContentText("Are you ok with this?");
alert.show();
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
System.out.println("OK");
} else {
System.out.println("CANCEL");
}*/
/*
int answer = JOptionPane.showConfirmDialog(null,"Restart Game",null, JOptionPane.YES_NO_CANCEL_OPTION);
if (answer == JOptionPane.YES_OPTION){
System.out.println("YES");
}else if (answer == JOptionPane.NO_OPTION){
System.exit(0);
System.out.println("NO");
} else if (answer == JOptionPane.CANCEL_OPTION){
Game.aTimer.start();
Game.exist = true;
System.out.println("CANCEL");
}*/
}
}
});
time.getKeyFrames().add(frame);
time.playFromStart();
}
}
|
package br.com.fiap.fiapinteliBe21.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import br.com.fiap.fiapinteliBe21.domain.enums.TipoCliente;
import br.com.fiap.fiapinteliBe21.service.validation.ClienteInsert;
@Entity
@Table(name = "T_IB_CLIENTE")
@ClienteInsert
public class Cliente implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "nr_cnpj_cpf")
private Long cnpjOuCpf;
@NotNull(message = "Preenchimento obrigatório")
@Column(name = "tp_cliente")
private Integer tipoCliente;
@NotNull(message = "Preenchimento obrigatório")
@Size(min = 2, max = 60, message = "O tamanho deve ter entre 2 e 60 caracteres")
@Column(name = "nm_cliente")
private String nomeCliente;
@NotNull(message = "Preenchimento obrigatório")
@Size(min = 2, max = 60, message = "O tamanho deve ter entre 2 e 60 caracteres")
@Email
@Column(name = "ds_email")
private String descricaoEmail;
@NotNull(message = "Preenchimento obrigatório")
@Size(min = 2, max = 60, message = "O tamanho deve ter entre 2 e 60 caracteres")
@Column(name = "ds_endereco")
private String descricaoEndereco;
@Size(min = 2, max = 30, message = "O tamanho deve ter entre 2 e 30 caracteres")
@Column(name = "ds_complemento")
private String complementoEndereco;
@NotNull(message = "Preenchimento obrigatório")
@Size(min = 2, max = 30, message = "O tamanho deve ter entre 2 e 30 caracteres")
@Column(name = "ds_bairro")
private String bairro;
@NotNull(message = "Preenchimento obrigatório")
@Size(min = 2, max = 30, message = "O tamanho deve ter entre 2 e 30 caracteres")
@Column(name = "ds_cidade")
private String cidade;
@NotNull(message = "Preenchimento obrigatório")
@Size(min = 2, max = 2, message = "O tamanho deve ter 2 caracteres")
@Column(name = "ds_estado")
private String estado;
@NotNull(message = "Preenchimento obrigatório")
@Size(min = 2, max = 30, message = "O tamanho deve ter entre 2 e 30 caracteres")
@Column(name = "ds_pais")
private String pais;
@NotNull(message = "Preenchimento obrigatório")
@Size(min = 2, max = 20, message = "O tamanho deve ter entre 2 e 60 caracteres")
@Column(name = "ds_cep", nullable = false, length = 20)
private String cep;
@Pattern(regexp = "\\(\\d{3}\\)\\d{4}-\\d{4}", message = "O tamanho deve ter formato (999)9999-9999")
@Column(name = "nr_telefone")
private String telefone;
@OneToMany(mappedBy = "cliente")
private List<Departamento> departamentos = new ArrayList<>();
@OneToMany(mappedBy = "cliente")
private List<Formulario> formulario = new ArrayList<>();
public Cliente(Long cnpjOuCpf, String tipoCliente, String nomeCliente, @Email String descricaoEmail,
String descricaoEndereco, String complementoEndereco, String bairro, String cidade, String estado,
String pais, String cep, String telefone) {
super();
this.cnpjOuCpf = cnpjOuCpf;
this.nomeCliente = nomeCliente;
setTipoCliente(tipoCliente);
this.nomeCliente = nomeCliente;
this.descricaoEmail = descricaoEmail;
this.descricaoEndereco = descricaoEndereco;
this.complementoEndereco = complementoEndereco;
this.bairro = bairro;
this.cidade = cidade;
this.estado = estado;
this.pais = pais;
this.cep = cep;
this.telefone = telefone;
}
public Cliente() {
}
public Long getCnpjOuCpf() {
return cnpjOuCpf;
}
public void setCnpjOuCpf(Long cnpjOuCpf) {
this.cnpjOuCpf = cnpjOuCpf;
}
public TipoCliente getTipoCliente() {
return TipoCliente.toEnum(tipoCliente);
}
public void setTipoCliente(String tipo) {
if (!tipo.equals("PF") && !tipo.equals("PJ")) {
throw new RuntimeException("Tipo dever ser PF ou PJ");
}
TipoCliente tipoCliente = TipoCliente.valueOf(tipo);
this.tipoCliente = tipoCliente.getCod();
}
public String getNomeCliente() {
return nomeCliente;
}
public void setNomeCliente(String nomeCliente) {
this.nomeCliente = nomeCliente;
}
public String getDescricaoEmail() {
return descricaoEmail;
}
public void setDescricaoEmail(String descricaoEmail) {
this.descricaoEmail = descricaoEmail;
}
public String getDescricaoEndereco() {
return descricaoEndereco;
}
public void setDescricaoEndereco(String descricaoEndereco) {
this.descricaoEndereco = descricaoEndereco;
}
public String getComplementoEndereco() {
return complementoEndereco;
}
public void setComplementoEndereco(String complementoEndereco) {
this.complementoEndereco = complementoEndereco;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getPais() {
return pais;
}
public void setPais(String pais) {
this.pais = pais;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public List<Departamento> getDepartamentos() {
return departamentos;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cnpjOuCpf == null) ? 0 : cnpjOuCpf.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cliente other = (Cliente) obj;
if (cnpjOuCpf == null) {
if (other.cnpjOuCpf != null)
return false;
} else if (!cnpjOuCpf.equals(other.cnpjOuCpf))
return false;
return true;
}
@Override
public String toString() {
return "Cliente [cnpjOuCpf=" + cnpjOuCpf + ", tipoCliente=" + tipoCliente + ", nomeCliente=" + nomeCliente
+ ", descricaoEmail=" + descricaoEmail + ", descricaoEndereco=" + descricaoEndereco
+ ", complementoEndereco=" + complementoEndereco + ", bairro=" + bairro + ", cidade=" + cidade
+ ", estado=" + estado + ", pais=" + pais + ", cep=" + cep + ", telefone=" + telefone
+ ", departamentos=" + departamentos + "]";
}
}
|
package fr.pantheonsorbonne.miage;
public class FailedUpdateException extends RuntimeException {
public FailedUpdateException(String message) {
super(message);
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
|
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class Scheduler {
public static AlgorithmResult getAlgorithmResult(List<Service> services, Algorithm algorithm, boolean isMultiThread) {
List<ServiceProcess> availableServiceProcesses = new ArrayList<>();
List<ServiceProcess> serviceProcesses = services.stream()
.map(ServiceProcess::new)
.sorted(algorithm.getComparator())
.collect(Collectors.toList());
final int size = serviceProcesses.size();
final int half = size / 2;
final boolean isEven = size % 2 == 0;
Semaphore lock = new Semaphore(1);
Semaphore full = new Semaphore(0);
Producer producer = new Producer(serviceProcesses, availableServiceProcesses, lock, full);
Consumer consumerA = new Consumer(availableServiceProcesses, lock, full, "John", !isMultiThread ? size : isEven ? half : half + 1);
Consumer consumerB = new Consumer(availableServiceProcesses, lock, full, "Jane", half);
System.out.printf("\n%s\n", algorithm.getValue());
try {
producer.start();
consumerA.start();
if (isMultiThread) consumerB.start();
producer.join();
consumerA.join();
if (isMultiThread) consumerB.join();
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
double returnTime = availableServiceProcesses.stream()
.mapToInt(s -> s.getEndTime() - s.getArrivalTimestamp()).average().orElse(0);
double responseTime = availableServiceProcesses.stream()
.mapToInt(s -> s.getBeginTime() - s.getArrivalTimestamp()).average().orElse(0);
return new AlgorithmResult(availableServiceProcesses.size(), returnTime, responseTime);
}
}
|
package com.icss.bean;
public class OrderFormBean {
private int num;
private int tb_num;
private int desk_num;
private String dateTime;
private double money;
private int user_id;
public OrderFormBean(){
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getTb_num() {
return tb_num;
}
public void setTb_num(int tb_num) {
this.tb_num = tb_num;
}
public int getDesk_num() {
return desk_num;
}
public void setDesk_num(int desk_num) {
this.desk_num = desk_num;
}
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
}
|
package com.gsccs.sme.plat.svg.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.gsccs.sme.plat.Constants;
import com.gsccs.sme.plat.auth.model.DictItemT;
import com.gsccs.sme.plat.auth.model.MsgT;
import com.gsccs.sme.plat.auth.service.DictService;
import com.gsccs.sme.plat.auth.service.MsgService;
import com.gsccs.sme.plat.bass.BaseController;
import com.gsccs.sme.plat.bass.Datagrid;
import com.gsccs.sme.plat.bass.JsonMsg;
import com.gsccs.sme.plat.svg.model.DeclareItemT;
import com.gsccs.sme.plat.svg.model.DeclareTopicT;
import com.gsccs.sme.plat.svg.service.DeclareService;
/**
* 项目申报控制类
*
* @author x.d zhang
*
*/
@Controller
@RequestMapping("/declare")
public class DeclareController extends BaseController {
@Autowired
private DeclareService declareService;
@Autowired
private DictService dictService;
@Autowired
private MsgService msgService;
@RequestMapping(value = "/topic", method = RequestMethod.GET)
protected String topicList(ModelMap map, HttpServletRequest req) {
// 申报类型
List<DictItemT> dectypelist = dictService.getDictItems("DEC_TYPE");
map.put("dectypelist", dectypelist);
return "declare/topic-list";
}
@RequestMapping(value = "/item", method = RequestMethod.GET)
protected String itemList(HttpServletRequest req) {
return "declare/item-list";
}
@RequestMapping(value = "/topic/datagrid", method = RequestMethod.POST)
@ResponseBody
public Datagrid topicList(DeclareTopicT decTopic,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int rows,
@RequestParam(defaultValue = "starttime desc") String orderstr,
HttpServletRequest request, ModelMap map) {
Datagrid grid = new Datagrid();
Subject subject = SecurityUtils.getSubject();
List<DeclareTopicT> list = null;
if (subject.hasRole(Constants.ROLE_SYS_M)
|| subject.hasRole(Constants.ROLE_DECLARE_M)) {
list = declareService.find(decTopic, orderstr, page, rows);
} else {
decTopic.setSvgid(getCurrUser().getOrgid());
list = declareService.find(decTopic, orderstr, page, rows);
}
int count = declareService.count(decTopic);
grid.setRows(list);
grid.setTotal(Long.valueOf(count));
return grid;
}
@RequestMapping(value = "/item/datagrid", method = RequestMethod.POST)
@ResponseBody
public Datagrid itemList(DeclareItemT declareItemT,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int rows,
@RequestParam(defaultValue = "") String orderstr,
HttpServletRequest request, ModelMap map) {
Datagrid grid = new Datagrid();
List<DeclareItemT> list = declareService.findItemBySvg(declareItemT,
orderstr, page, rows);
int count = declareService.count(declareItemT);
grid.setRows(list);
grid.setTotal(Long.valueOf(count));
return grid;
}
// 新增
@RequestMapping(value = "/topic/form", method = RequestMethod.GET)
public String showTopicForm(Long id, Model model) {
if (null != id) {
DeclareTopicT decTopic = declareService.findTopicById(id);
model.addAttribute("decTopic", decTopic);
}
// 申报类型
List<DictItemT> dectypelist = dictService.getDictItems("DEC_TYPE");
model.addAttribute("dectypelist", dectypelist);
return "declare/topic-form";
}
@RequestMapping(value = "/topic/delete", method = RequestMethod.POST)
@ResponseBody
public JsonMsg deleteTopic(Long id) {
JsonMsg msg = new JsonMsg();
try {
if (null != id) {
declareService.delTopics(id);
msg.setSuccess(true);
msg.setMsg("删除成功!");
} else {
msg.setSuccess(false);
msg.setMsg("删除失败!");
}
} catch (Exception e) {
e.printStackTrace();
msg.setSuccess(false);
msg.setMsg("操作失败,未知错误!");
}
return msg;
}
@RequestMapping(value = "/topic/add", method = RequestMethod.POST)
@ResponseBody
public JsonMsg addTopic(@RequestBody DeclareTopicT declareTopicT,
RedirectAttributes redirectAttributes) {
JsonMsg msg = new JsonMsg();
try {
if (null != declareTopicT) {
declareTopicT.setSvgid(getCurrUser().getOrgid());
declareService.insertTopic(declareTopicT);
msg.setSuccess(true);
msg.setMsg("添加成功!");
} else {
msg.setSuccess(false);
msg.setMsg("添加成功!");
}
} catch (Exception e) {
e.printStackTrace();
msg.setSuccess(false);
msg.setMsg("保存失败,未知错误!");
}
return msg;
}
/**
* 修改行政诉求主题
*
* @param declareTopicT
* @return
*/
@RequestMapping(value = "/topic/edit", method = RequestMethod.POST)
@ResponseBody
public JsonMsg update(@RequestBody DeclareTopicT declareTopicT) {
JsonMsg msg = new JsonMsg();
try {
if (null != declareTopicT) {
if (null == declareTopicT.getSvgid()) {
declareTopicT.setSvgid(getCurrUser().getOrgid());
}
declareService.updateTopic(declareTopicT);
msg.setSuccess(true);
msg.setMsg("修改成功!");
} else {
msg.setSuccess(false);
msg.setMsg("修改失败!");
}
} catch (Exception e) {
msg.setSuccess(false);
msg.setMsg("修改失败,未知的错误原因!");
}
return msg;
}
/**
* 查看行政诉求内容
*
* @param id
* @param model
* @return
*/
@RequestMapping(value = "/item/form", method = RequestMethod.GET)
public String showItemForm(Long id, Model model) {
DeclareTopicT declareTopic = null;
DeclareItemT declareItem = null;
if (null != id) {
declareItem = declareService.findItemById(id);
Long topicid = declareItem.getTopicid();
declareTopic = declareService.findTopicById(topicid);
}
model.addAttribute("declareItem", declareItem);
model.addAttribute("declareTopic", declareTopic);
return "declare/item-form";
}
/**
* 行政诉求办理
*
* @param
* @return
*/
@RequestMapping(value = "/item/audit", method = RequestMethod.POST)
@ResponseBody
public JsonMsg itemaudit(@RequestBody DeclareItemT declareItem) {
JsonMsg msg = new JsonMsg();
if (null==declareItem){
msg.setSuccess(false);
msg.setMsg("审核失败,申报内容不存在。");
return msg;
}
declareService.updateItem(declareItem);
//消息通知
MsgT msgT = new MsgT();
msgT.setContent(declareItem.getReply());
msgT.setReceiver(declareItem.getCorpid());
msgT.setSender(getCurrUser().getOrgid());
msgService.createMsg(msgT);
msg.setSuccess(true);
msg.setMsg("审核操作成功!");
return msg;
}
}
|
package com.esum.comp.kftp.table;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.sf.ehcache.Cache;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.framework.cache.CacheUtil;
import com.esum.framework.common.sql.Record;
import com.esum.framework.core.component.ComponentException;
import com.esum.framework.core.component.table.InfoTable;
public class KFtpInfoTable extends InfoTable {
private Logger log = LoggerFactory.getLogger(KFtpInfoTable.class);
public KFtpInfoTable(String traceId, String cacheId) throws ComponentException {
super(traceId, cacheId);
}
public void init() throws ComponentException {
List<Record> result = fullQuery("SELECT * FROM KFTP_INFO");
addInfoRecord(result, KFtpInfoRecord.class, "INTERFACE_ID");
}
public void reloadInfoRecord(String[] ids) throws ComponentException {
Record record = reloadQuery("SELECT * FROM KFTP_INFO WHERE INTERFACE_ID = ?", ids[0]);
KFtpInfoRecord fileInfoRecord = null;
if (record != null) {
fileInfoRecord = new KFtpInfoRecord(ids, record);
}
reloadInfoRecord(ids, fileInfoRecord);
}
public List<KFtpInfoRecord> getFtpGatherInfo() {
Cache map = getInfoRecordList();
Iterator keyIter = map.getKeys().iterator();
List<KFtpInfoRecord> result = new ArrayList<KFtpInfoRecord>();
while (keyIter.hasNext()) {
Object key = keyIter.next();
KFtpInfoRecord record = (KFtpInfoRecord)CacheUtil.get(map, key);
if (record.isInboundUse() && StringUtils.isNotEmpty(record.getInboundHost())) {
result.add(record);
}
}
return result;
}
}
|
package day06.homework.rpcrobin.local;
import day06.homework.rpcrobin.net_common.IdPassException;
import day06.homework.rpcrobin.net_common.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by robin on 2017/8/9.
*/
public class UserDaoImpl implements UserDao {
private UserDaoImpl(){}
private static UserDaoImpl instance=null;
public static UserDaoImpl getInstance(){
if(instance!=null){}
else{
synchronized (UserDaoImpl.class){
if(instance==null)
instance=new UserDaoImpl();
}
}
return instance;
}
// @Override
//这个方法调用自己的,懒得调用底层了
public User logon(int id, String password) throws IdPassException {
List<User> list=getAllUsers();
for(User user:list){
if(id==user.getUid())
if(password.equals(user.getPass()))
return user;
else
throw new IdPassException("error password");
}
throw new IdPassException("no id");
}
// @Override
public List<User> getAllUsers() {
List<User> list=new ArrayList<User>();
Connection connection=null;
PreparedStatement pstmt=null;
ResultSet resultSet=null;
try {
connection=JDBCUtil.getConnection();
pstmt=connection.prepareStatement("select * from user");
resultSet = pstmt.executeQuery();
while(resultSet.next()){
// System.out.println(rs.getInt("uid")+","+rs.getString("name")+","+rs.getString("pass")+","+rs.getString("email"));
User user=new User(resultSet.getInt("uid"),
resultSet.getString("name"),
resultSet.getString("pass"),
resultSet.getString("email"));
list.add(user);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.closeResut(resultSet);
JDBCUtil.closeState(pstmt);
JDBCUtil.closeCon(connection);
}
return null;
}
// @Override
public String getNameById(int id) {
Connection connection=null;
PreparedStatement pstmt=null;
ResultSet resultSet=null;
try {
connection=JDBCUtil.getConnection();
pstmt=connection.prepareStatement("select name from user where uid=?");
pstmt.setInt(1,id);
resultSet = pstmt.executeQuery();
while(resultSet.next()){
//System.out.println(rs.getString("name"));
return resultSet.getString("name");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.closeResut(resultSet);
JDBCUtil.closeState(pstmt);
JDBCUtil.closeCon(connection);
}
return null;
}
// @Override
public int insertUser(User user) {
Connection connection=null;
PreparedStatement pstmt=null;
int n=0;
try {
connection=JDBCUtil.getConnection();
pstmt=connection.prepareStatement("insert into user(uid,name,pass,email)values (?,?,?,?)");
pstmt.setInt(1,user.getUid());
pstmt.setString(2, user.getName());
pstmt.setString(3, user.getPass());
pstmt.setString(4, user.getEmail());
n=pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.closeState(pstmt);
JDBCUtil.closeCon(connection);
}
return n;
}
}
|
package narif.personal.work.fnutils.components;
import narif.personal.work.fnutils.datastructures.Tuple;
import java.util.function.Supplier;
public class Case<T> extends Tuple<Supplier<Boolean>, Supplier<Result<T>>> {
private Case(Supplier<Boolean> booleanSupplier, Supplier<Result<T>> resultSupplier){
super(booleanSupplier,resultSupplier);
}
public static <T> Case<T> mcase(Supplier<Boolean> condition, Supplier<Result<T>> value){
return new Case<>(condition, value);
}
public static <T> DefaultCase<T> mcase(Supplier<Result<T>> value){
return new DefaultCase<>(()->true, value);
}
@SafeVarargs
public static <T> Result<T> match (DefaultCase<T> defaultCase, Case<T>... matchers){
for (Case<T> aCase: matchers)
if(aCase.getFirst().get()) return aCase.getSecond().get();
return defaultCase.getSecond().get();
}
private static class DefaultCase<T> extends Case<T>{
private DefaultCase(Supplier<Boolean> booleanSupplier, Supplier<Result<T>> resultSupplier) {
super(booleanSupplier, resultSupplier);
}
}
}
|
package com.scriptingsystems.tutorialjava.streamsj8;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ProcesandoFicherosStreams {
public static void main (String[] args) {
try {
/* Primera opción
Stream str = Files.lines(Paths.get("urls.txt"));
str.forEach(line -> System.out.println(line));
*/
Files.lines(Paths.get("urls.txt")).forEach(line -> System.out.println(line));
System.out.println("Solo muestra las lineas con mas de 10 caracteres.");
Files.lines(Paths.get("urls.txt")).filter(linea -> linea.length() > 10).forEach( line -> System.out.println(line) );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package edu.mum.cs.cs425.studentmgmt.model;
import javax.persistence.*;
import java.time.LocalDate;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long studentId;
private String studentNumber;
private String firstName;
private String midleName;
private String lastName;
private double gpa;
private LocalDate dateOfEnrollment;
@OneToOne (cascade = CascadeType.ALL)
private Transcript transcript;
@ManyToOne
private Classroom classroom;
public Student() {
}
public Student(String studentNumber, String firstName, String midleName, String lastName, double gpa, LocalDate dateOfEnrollment) {
this.studentNumber = studentNumber;
this.firstName = firstName;
this.midleName = midleName;
this.lastName = lastName;
this.gpa = gpa;
this.dateOfEnrollment = dateOfEnrollment;
}
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMidleName() {
return midleName;
}
public void setMidleName(String midleName) {
this.midleName = midleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public LocalDate getDateOfEnrollment() {
return dateOfEnrollment;
}
public Transcript getTranscript() {
return transcript;
}
public void setTranscript(Transcript transcript) {
this.transcript = transcript;
}
public void setDateOfEnrollment(LocalDate dateOfEnrollment) {
this.dateOfEnrollment = dateOfEnrollment;
}
public Classroom getClassroom() {
return classroom;
}
public void setClassroom(Classroom classroom) {
this.classroom = classroom;
}
}
|
package com.wdl.webapp.filter;
import java.util.List;
import javax.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.wdl.entity.rbac.UserEntity;
import com.wdl.service.rbac.MenuService;
import com.wdl.service.rbac.UserService;
/**
* @author bin 系统安全认证实现类
*
*/
@Service
public class SystemAuthorizingRealm extends AuthorizingRealm {
/**
* 认证回调函数, 登录时调用
*/
@Resource
private UserService userService;
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
// 校验用户名密码
UserEntity user = new UserEntity();
user.setLoginName(token.getUsername());
user.setPassWord(String.copyValueOf(token.getPassword()));
List<UserEntity> userList = userService.findByExample(user);
if (userList.size()>0) {
UserEntity entity=userList.get(0);
SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(entity, token.getPassword(), token.getUsername());
// 注意此处的返回值没有使用加盐方式,如需要加盐,可以在密码参数上加
return authenticationInfo;
}
return null;
}
@RequestMapping(value = "/logout")
public String logout(RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", "已安全登出");
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.removeAttribute("permission");
session.removeAttribute("id");
// session.removeAttribute(SessionKeys.USERID);
// session.removeAttribute(SessionKeys.USERNAME);
// session.removeAttribute(SessionKeys.USERREALNAME);
subject.logout();
return "/admin/login";
}
/**
* 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用 shiro 权限控制有三种 1、通过xml配置资源的权限
* 2、通过shiro标签控制权限 3、通过shiro注解控制权限
*/
@Resource
MenuService menuService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
}
|
package net.acomputerdog.BlazeLoader.util.reflect;
import java.lang.reflect.Method;
/**
* Api functions to simplify reflective tasks.
*/
public class ReflectionUtils {
/**
* Dynamically invokes a method, even if it is inaccessible.
*
* @param method The method instance to invoke.
* @param args Arguments to pass to the method.
* @return Returns whatever is returned by the invoked method, or null if nothing is returned.
*/
public static Object invokeMethod(MethodInstance method, Object... args) {
if (method == null) {
throw new IllegalArgumentException("method cannot be null!");
}
try {
Method m = method.boundMethod;
m.setAccessible(true);
return m.invoke(method.boundObject, args);
} catch (Exception e) {
throw new RuntimeException("Could not invoke method: " + method.boundMethod.getName(), e);
}
}
/**
* Invokes a method named in a string, even if it is inaccessible.
*
* @param method The full name of the method to invoke. Should be in the form of [fully_qualified_class_name].[method_name] OR [method_name] if object is not null.
* Example: "net.acomputerdog.BlazeLoader.util.reflect.ApiReflect.invokeMethod".
* Can NOT be null!
* @param object The object to invoke on, or null if method is static. Can be null if method is static and full name is given.
* @param args Arguments to pass to the method.
* @return Returns whatever is returned by the invoked method, or null if nothing is returned.
*/
public static Object invokeMethod(String method, Object object, Object... args) {
if (method == null) {
throw new IllegalArgumentException("method cannot be null!");
}
if (object != null) {
String[] methodComponents = method.split(".");
String methodName = methodComponents[methodComponents.length - 1];
try {
Method theMethod = object.getClass().getDeclaredMethod(methodName);
theMethod.setAccessible(true);
return theMethod.invoke(object, args);
} catch (Exception e) {
throw new RuntimeException("Could not invoke method: " + methodName, e);
}
} else {
String[] methodComponents = method.split(".");
String methodName = methodComponents[methodComponents.length - 1];
try {
StringBuilder builder = new StringBuilder();
for (int index = 0; index < methodComponents.length - 2; index++) { //must skip last index!
builder.append(methodComponents[index]);
}
Class theClass = Class.forName(builder.toString());
Method theMethod = theClass.getDeclaredMethod(methodName);
theMethod.setAccessible(true);
return theMethod.invoke(null, args);
} catch (Exception e) {
throw new RuntimeException("Could not invoke method: " + methodName, e);
}
}
}
public static <I> FieldInstance<I> getField(Class declaringClass, Object instance, int index) {
return new FieldInstance<I>(declaringClass.getDeclaredFields()[index], instance);
}
}
|
package com.example.zyadzakaria.wev;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
public String message;
private String UUID;
public ListView list;
private ArrayList<Chat> chats;
public MyCustomAdapter customAdapter;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://vast-everglades-73054.herokuapp.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
final WEVService wevService = retrofit.create(WEVService.class);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chats = new ArrayList();
final Button button = (Button) findViewById(R.id.button);
list=(ListView)findViewById(R.id.myList);
customAdapter = new MyCustomAdapter(getApplicationContext(), chats);
list.setAdapter(customAdapter);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
EditText mEdit = (EditText)findViewById(R.id.editText);
message = mEdit.getText().toString();
mEdit.setText("");
chats.add(new Chat(message,false));
customAdapter.notifyDataSetChanged();
Call<ChatObj> chatCall = wevService.chat(UUID, new ChatObj(message));
chatCall.enqueue(new Callback<ChatObj>() {
@Override
public void onResponse(Call<ChatObj> call, Response<ChatObj> response) {
if (response.code() < 200 || response.code() > 299) {
try {
message = response.errorBody().string();
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}else{
message = response.body().message;
}
chats.add(new Chat(message, true));
customAdapter.notifyDataSetChanged();
list.smoothScrollToPosition(chats.size());
}
@Override
public void onFailure(Call<ChatObj> call, Throwable t) {
}
});
}
});
Call<WelcomeResponse> call = wevService.welcome();
call.enqueue(new Callback<WelcomeResponse>() {
@Override
public void onResponse(Call<WelcomeResponse> call, Response<WelcomeResponse> response) {
message = response.body().message;
UUID = response.body().uuid;
chats.add(new Chat(message ,true));
customAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), UUID, Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<WelcomeResponse> call, Throwable t) {
}
});
}
}
|
/*
* 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 LoloModel;
import java.awt.Graphics;
import Auxiliar.Desenho;
import Controler.Tela;
public class Bau extends Elemento{
public Bau(Tela t) {
super("bau.jpg");
this.bTransponivel = true;
}
public void autoDesenho(Graphics g){
Desenho.desenhar(g, this.iImage, pPosicao.getColuna(), pPosicao.getLinha());
}
public void Touch(Tela t){
if(t.getlLolo().pPosicao.igual(this.pPosicao))
t.addElemento(t.getPorta());
}
}
|
package com.thinkdevs.cryptomarket;
import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.provider.Settings;
import androidx.annotation.NonNull;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
/**
* Created by ABC on 8/8/2017.
*/
public class Btc extends Application {
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private static Btc mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
mAuth= FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
}
else{
String uiid= Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
mDatabase = FirebaseDatabase.getInstance().getReference().child("userprofiles").child(mAuth.getCurrentUser().getUid()).child(uiid);
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
mDatabase.child("uds").onDisconnect().setValue(false);
mDatabase.child("uds").setValue(true);
PackageInfo pInfo;
try {
pInfo = getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
mDatabase.child("av").setValue(pInfo.versionCode);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
};
mAuth.addAuthStateListener(mAuthListener);
}
public static synchronized Btc getInstance() {
return mInstance;
}
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
}
|
package com.metoo.foundation.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.metoo.core.constant.Globals;
import com.metoo.core.domain.IdEntity;
/**
*
* <p>
* Title: GroupArea.java
* </p>
*
* <p>
* Description: 团购区域,团购商品申请可以选择允许团购的区域
* </p>
*
* <p>
* Copyright: Copyright (c) 2014
* </p>
*
* <p>
* Company: 沈阳网之商科技有限公司 www.koala.com
* </p>
*
* @author erikzhang
*
* @date 2014-4-25
*
*
* @version koala_b2b2c v2.0 2015版
*/
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Entity
@Table(name = Globals.DEFAULT_TABLE_SUFFIX + "group_area")
public class GroupArea extends IdEntity {
private String ga_name;// 区域名称
private int ga_sequence;// 区域序号,升序排序
@ManyToOne(fetch = FetchType.LAZY)
private GroupArea parent;// 父级区域
@OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
@OrderBy(value = "ga_sequence asc")
private List<GroupArea> childs = new ArrayList<GroupArea>();// 子集区域
private int ga_level;// 区域层级,用在区域显示梯次
public GroupArea() {
super();
// TODO Auto-generated constructor stub
}
public GroupArea(Long id, Date addTime) {
super(id, addTime);
// TODO Auto-generated constructor stub
}
public int getGa_level() {
return ga_level;
}
public void setGa_level(int ga_level) {
this.ga_level = ga_level;
}
public String getGa_name() {
return ga_name;
}
public void setGa_name(String ga_name) {
this.ga_name = ga_name;
}
public int getGa_sequence() {
return ga_sequence;
}
public void setGa_sequence(int ga_sequence) {
this.ga_sequence = ga_sequence;
}
public GroupArea getParent() {
return parent;
}
public void setParent(GroupArea parent) {
this.parent = parent;
}
public List<GroupArea> getChilds() {
return childs;
}
public void setChilds(List<GroupArea> childs) {
this.childs = childs;
}
}
|
package com.atguigu.springcloud.service;
import com.atguigu.springcloud.domain.CommonResult;
import org.apache.ibatis.annotations.Param;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
/**
* @author Yue_
* @create 2020-12-01-17:06
*/
@FeignClient(value = "seata-account-service")
public interface AccountService {
@PostMapping(value = "/account/decrease")
CommonResult decreaseAccount(@Param("productId") Long productId, @Param("count") Integer count);
}
|
package edu.uha.miage.web.controller;
import edu.uha.miage.core.entity.Compte;
import edu.uha.miage.core.entity.Fonction;
import edu.uha.miage.core.entity.Personne;
import edu.uha.miage.core.service.CompteService;
import edu.uha.miage.core.service.DepartementService;
import edu.uha.miage.core.service.FonctionService;
import edu.uha.miage.core.service.PersonneService;
import edu.uha.miage.core.service.RoleService;
import edu.uha.miage.model.Inscription;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
*
* @author victo
*/
@Controller
@RequestMapping("/inscription")
public class InscriptionController {
@Autowired
PersonneService personneService;
@Autowired
DepartementService departementService;
@Autowired
FonctionService fonctiontService;
@Autowired
CompteService compteService;
@Autowired
RoleService roleService;
@RequestMapping(method = RequestMethod.GET)
public String inscription(Model model) {
model.addAttribute("inscription", new Inscription());
model.addAttribute("fonctions", fonctiontService.findAll());
//LOGGER.warn("ATTENTION GET FAIT SUR INSCRIPTION");
return "inscription2";
}
@RequestMapping(method = RequestMethod.POST)
public String inscrit(@Valid Inscription inscription, BindingResult br, Model model) {
//LOGGER.warn("J'ai mis recu un post");
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
//Users user = new Users(inscription.getUsername(), "{noop}"+inscription.getPassword());
if (br.hasErrors()) {
model.addAttribute("fonctions", fonctiontService.findAll());
return "inscription2";
}
//LOGGER.warn("Je suis la!!!");
Personne user = new Personne(inscription.getNom(), inscription.getPrenom(), inscription.getAdresse(), inscription.getEmail());
user.setOccupations(inscription.getFonctions());
for (Fonction f : inscription.getFonctions()) {
f.getOccupationDePersonne().add(user);
}
personneService.save(user);
//LOGGER.warn("BB JAI SAVE LA PERSONNE");
Compte compte = new Compte(inscription.getUsername(), encoder.encode(inscription.getPassword()), user, roleService.findByLibelle("ROLE_COLLABORATEUR"));
compteService.save(compte);
//LOGGER.warn("Super j'ai bien fini l'inscription");
return "redirect:/login";
}
}
|
package Customer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public abstract class ClerkTemplate extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
protected DataSelectPanel dataSelectPanel;
protected JPanel selectBkg;
protected GridBagConstraints gbc;
private String Title = "";
private String ButtonTitle = "";
public ClerkTemplate(String title, String buttonTitle) {
this.setLayout(new FlowLayout(FlowLayout.LEFT));
Title = title;
ButtonTitle = buttonTitle;
setUpPanel();
}
private void addReserveAction(JButton target) {
target.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
buttonAction();
}
});
}
protected abstract void buttonAction();
private void setUpPanel() {
dataSelectPanel = new DataSelectPanel();
JButton reserveButton = new JButton(ButtonTitle);
selectBkg = new JPanel();
JLabel titleLabel = new JLabel(Title);
this.setPreferredSize(new Dimension(600, 400));
selectBkg.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(30,3,3,3);
gbc.gridy = 1;
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.CENTER;
titleLabel.setFont(new Font("TimesRoman", Font.BOLD, 22));
titleLabel.setForeground(Color.orange);
selectBkg.add(titleLabel, gbc);
gbc.gridy = 2;
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.WEST;
selectBkg.add(dataSelectPanel,gbc);
gbc.gridy = 3;
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.SOUTH;
reserveButton.setPreferredSize(new Dimension(200, 50));
selectBkg.add(reserveButton, gbc);
selectBkg.setBackground(Color.DARK_GRAY);
addReserveAction(reserveButton);
this.add(selectBkg);
}
}
|
package com._01_stream;
public class EmployeeConvert {
private String convertName;
private int convertAge;
private String convertExtra;
public EmployeeConvert() {
}
public String getConvertName() {
return convertName;
}
public void setConvertName(String convertName) {
this.convertName = convertName;
}
public int getConvertAge() {
return convertAge;
}
public void setConvertAge(int convertAge) {
this.convertAge = convertAge;
}
public String getConvertExtra() {
return convertExtra;
}
public void setConvertExtra(String convertExtra) {
this.convertExtra = convertExtra;
}
@Override
public String toString() {
return "EmployeeConvert{" +
"convertName='" + convertName + '\'' +
", convertAge=" + convertAge +
", convertExtra='" + convertExtra + '\'' +
'}';
}
public EmployeeConvert(String convertName, int convertAge, String convertExtra) {
this.convertName = convertName;
this.convertAge = convertAge;
this.convertExtra = convertExtra;
}
}
|
package br.com.gestor.controller;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import br.com.gestor.database.dao.EquipeDao;
import br.com.gestor.database.dao.EquipeJPADao;
import br.com.gestor.database.modelo.Dev;
import br.com.gestor.database.modelo.Equipe;
@ManagedBean(name = "equipeBean")
public class EquipeBean {
private Equipe equipe;
private List<Equipe> equipes;
private List<Dev> devsSemEquipe;
public EquipeBean(){
this.equipe = new Equipe();
EquipeDao dao = new EquipeJPADao();
equipes = dao.getList();
devsSemEquipe = dao.getdevsSemEquipe();
}
public Equipe getEquipe() {
return equipe;
}
public void setEquipe(Equipe equipe) {
this.equipe = equipe;
}
public List<Equipe> getEquipes() {
return equipes;
}
public void setEquipes(List<Equipe> equipes) {
this.equipes = equipes;
}
public List<Dev> getdevsSemEquipe() {
return devsSemEquipe;
}
public void setdevsSemEquipe(List<Dev> devsSemEquipe) {
this.devsSemEquipe = devsSemEquipe;
}
public String adicionaEquipe(){
EquipeDao dao = new EquipeJPADao();
this.equipe.setAtivo(true);
dao.save(this.equipe);
return "/gerente/equipe?faces-redirect=true";
}
public String prepararParticipantes(){
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
int id = Integer.parseInt(request.getParameter("idEquipe"));
this.equipe.setId(id);
this.equipe.setNome(request.getParameter("nomeEquipe"));
this.equipe.setAtivo(true);
return "/gerente/adicionar-participantes";
}
public String adicionaParticipante(){
for (Dev dev : equipe.getdevs()) {
dev.setEquipe(this.equipe);
}
EquipeDao dao = new EquipeJPADao();
this.equipe.setAtivo(true);
dao.update(this.equipe);
return "/gerente/equipe?faces-redirect=true";
}
public String removerEquipe(){
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
int id = Integer.parseInt(request.getParameter("idEquipe"));
Equipe equipe = new Equipe();
equipe.setId(id);
EquipeDao dao = new EquipeJPADao();
dao.desativarEquipe(equipe);
return "/gerente/equipe?faces-redirect=true";
}
}
|
package generic;
/**
* Created by max.lu on 2016/2/2.
*/
public class Book<T> {
private T attr;
public T getAttr() {
return attr;
}
public void setAttr(T attr) {
this.attr = attr;
}
}
|
package com.example.repository;
import com.example.entity.Question;
import org.springframework.data.jpa.repository.JpaRepository;
public interface QuestionRepository extends JpaRepository<Question, Integer> {}
|
package com.example.lamelameo.picturepuzzle;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.*;
import com.example.lamelameo.picturepuzzle.ui.main.PuzzleActivity2;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private RecyclerView mRecyclerView;
private final ArrayList<Drawable> savedPhotos = new ArrayList<>();
private final ArrayList<String> photoPaths = new ArrayList<>();
private int mGridRows;
private boolean defaultAdapter;
private final static int REQUEST_PHOTO_CROPPING = 1;
/**
* Setup Buttons and their onClickListeners that allow the user to choose settings, take a photo, and start a puzzle.
* Also setup the recycler view which displays image choices for the puzzle.
*
* @param savedInstanceState get previously saved activity instance
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int[] drawableInts = {
R.drawable.dfdfdefaultgrid, R.drawable.dfdfcarpet, R.drawable.dfdfcat, R.drawable.dfdfclock,
R.drawable.dfdfdarklights, R.drawable.dfdfnendou, R.drawable.dfdfrazer, R.drawable.dfdfsaiki
};
getSavedPhotos();
mRecyclerView = findViewById(R.id.pictureRecyclerView);
// improves performance given that recycler does not change size based on its contents (the images)
mRecyclerView.setHasFixedSize(true);
int orientation = getResources().getConfiguration().orientation;
// use layout manager - horizontal orientation = 0, vertical = 1
RecyclerView.LayoutManager layoutManager;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
layoutManager = new LinearLayoutManager(this, 0, false);
} else {
layoutManager = new LinearLayoutManager(this, 1, false);
}
mRecyclerView.setLayoutManager(layoutManager);
// set adapter to default use default image dataset
final ImageRecyclerAdapter testAdapter = new ImageRecyclerAdapter(drawableInts);
mRecyclerView.setAdapter(testAdapter);
defaultAdapter = true;
// toggle recycler view between default images and photos taken and saved using this app
ToggleButton adapterButton = findViewById(R.id.adapterButton);
final ImageRecyclerAdapter photoAdapter = new ImageRecyclerAdapter(savedPhotos);
//TODO: could use a grid layout manager to allow for a grid in recycler view rather than list (or a choice)
// set button listener to change between datasets (defaults or photos) for the recycler view
adapterButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
defaultAdapter = !defaultAdapter; // update boolean to track which dataset is displayed
if (isChecked) { // recycler displaying default images -> change to app photo gallery
mRecyclerView.swapAdapter(photoAdapter, true);
photoAdapter.notifyDataSetChanged();
photoAdapter.setIsDefaultImages(); // update boolean which tells adapter which dataset is shown
} else { // recycler displaying app gallery -> defaults
mRecyclerView.swapAdapter(testAdapter, true);
testAdapter.notifyDataSetChanged();
testAdapter.setIsDefaultImages();
}
}
});
// move to cropper activity to crop gallery images or take photo with camera
Button cameraGalleryButton = findViewById(R.id.photoCropButton);
final Intent cropperIntent = new Intent(this, PhotoCropping.class);
cameraGalleryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(cropperIntent, REQUEST_PHOTO_CROPPING);
}
});
// set gridsize based on the checked radio button, this value will be used as an intent extra when starting the game
final RadioGroup setGrid = findViewById(R.id.setGrid);
setGrid.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int x = 0; x < 4; x++) {
RadioButton radioButton = (RadioButton) group.getChildAt(x);
if (radioButton.getId() == checkedId) {
mGridRows = x + 3; // update grid size for use in load button listener in this context
break;
}
}
}
});
final Intent gameIntent = new Intent(this, PuzzleActivity2.class);
mGridRows = 4; // default amount of grid rows is 4
final int[] defaultPuzzles = { R.drawable.grid9, R.drawable.grid15, R.drawable.grid25, R.drawable.grid36 };
// on click listener for the load button creates an intent to start the game activity and sets extras to give
// that activity the information of grid size and image to use
Button loadButton = findViewById(R.id.loadButton);
loadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gameIntent.putExtra("numColumns", mGridRows); // set extra for grid size
// remove any previous extra so the game activity does not use it instead of the intended image/photo
gameIntent.removeExtra("photoPath");
gameIntent.removeExtra("drawableId");
// get drawable id or photo path for selected image from recycler view adapter
int selectedImage = testAdapter.getSelection();
// if no selection, check for selected grid size to send the appropriate default image
if (selectedImage == -1) {
gameIntent.putExtra("drawableId", defaultPuzzles[mGridRows - 3]); // 3x3 grid is index 0 in array
} else { // there is a selected item from whichever dataset is displayed
if (defaultAdapter) { // selection is from default images
// if there is a selection, send the id and puzzle number to the game activity
gameIntent.putExtra("drawableId", drawableInts[selectedImage]);
gameIntent.putExtra("puzzleNum", selectedImage);
} else { // selection is from app photos
gameIntent.putExtra("photoPath", photoPaths.get(selectedImage));
gameIntent.putExtra("puzzleNum", -1);
}
}
startActivity(gameIntent); // start game activity
}
});
}
/**
* Scale an image to the size of a view, and rotate 90 degrees to obtain the image in portrait orientation
*
* @param viewSize the size of the view for the image to be scaled to
* @param photopath the file path of the image to be scaled
* @return a Drawable of the given image scaled to a size suitable to fit into the target view
*/
private Drawable scalePhoto(int viewSize, String photopath) {
// scale image previews to fit the allocated View to save app memory
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photopath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = Math.min(photoW / viewSize, photoH / viewSize);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
Bitmap bitmap = BitmapFactory.decodeFile(photopath, bmOptions);
return new BitmapDrawable(getResources(), bitmap);
}
/**
* Search the app picture directory for photos of .jpg or .png type and store them in instance variables as
* drawables (image) and strings (filepath) which can be used to display the photos and send to the Puzzle Activity
*/
private void getSavedPhotos() {
// TODO: should limit amount of storable photos, or have on the fly loading of images as list could be huge
File[] storedImages = Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_PICTURES)).listFiles();
if (storedImages == null) {
return;
}
float density = getResources().getDisplayMetrics().density;
long recyclerViewPx = Math.round(150 * density);
// checks for files in the apps image directory which are not of the jpg or png type
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept(File pathname) {
boolean acceptedType = false;
String pathName = pathname.getName();
if (pathName.endsWith(".jpg") || pathName.endsWith(".png"))
acceptedType = true;
return acceptedType;
}
};
for (File file : storedImages) {
// check for empty or wrong file types and delete them
if (file.length() == 0 || !fileFilter.accept(file)) {
boolean deletedFile = file.delete();
} else {
String imagePath = file.getAbsolutePath();
photoPaths.add(imagePath);
Drawable imageBitmap = scalePhoto((int) recyclerViewPx, imagePath);
savedPhotos.add(imageBitmap);
}
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//TODO: start photocropping with code then when press back set photo data as list of paths then update here
// also consider case where cropper goes to game, then back to here directly from solved UI
if (requestCode == REQUEST_PHOTO_CROPPING && resultCode == RESULT_OK && data != null) {
// must update recycler view adapter for photos, as new photos may have been loaded, notify adapter data changed
ArrayList<String> newPhotos = data.getStringArrayListExtra("savedPhotos");
float density = getResources().getDisplayMetrics().density;
long recyclerViewPx = Math.round(150 * density);
// create bitmap for each new photo and add to adapters data set
for (String photoPath : newPhotos) {
if (photoPath != null) { // just to be sure no null paths sneak in
photoPaths.add(photoPath);
Drawable imageBitmap = scalePhoto((int) recyclerViewPx, photoPath);
savedPhotos.add(imageBitmap);
}
}
if (mRecyclerView.getAdapter() != null) {
mRecyclerView.getAdapter().notifyDataSetChanged();
}
}
}
}
|
package com.lumpofcode.collection.compare;
import java.util.Comparator;
/**
* Created by emurphy on 6/15/15.
*/
public class IntegerComparator implements Comparator<Integer>
{
@Override
public int compare(Integer theValue, Integer theOtherValue)
{
if(null != theValue)
{
if(null != theOtherValue)
{
return theValue.compareTo(theOtherValue);
}
return 1;
}
if(null != theOtherValue)
{
return -1;
}
return 0;
}
}
|
package cn.kgc.controller;
import cn.kgc.domain.Product;
import cn.kgc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class ProductController {
@Autowired
private ProductService productService;
@RequestMapping("getProduct")
@ResponseBody
public List<Product> getProduct(){
List<Product> products = productService.selectAllProduct();
return products;
}
@RequestMapping("checkNum")
@ResponseBody
public Map<String,Object> checkNum(String id){
int i = productService.selectNumById(id);
Map<String,Object> map=new HashMap<>();
map.put("result",i);
return map;
}
}
|
package cn.kitho.web.tools.security;
/**
* Created by lingkitho on 2017/2/17.
*/
public class MixCodeTool {
public static String mixData(String data){
return data;
}
public static String mixData(Integer data){
return data.toString();
}
public static String recoverData(String data){
return data;
}
}
|
package com.eniso.regimi.repository;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.eniso.regimi.models.Specialist;
import com.eniso.regimi.models.Subscriber;
@Repository
public interface SpecialistRepository extends MongoRepository<Specialist, String> {
Optional<Specialist> findById(String Id) ;
List<Specialist> findByEmail(String email);
List<Specialist> findByGender(String gender);
List<Specialist> findBySpeciality(String speciality);
List<Specialist> findByFirstName(String firstName);
List<Specialist> findByLastName(String lastName);
List<Specialist> findByRegion(String Region);
Boolean existsByEmail(String email);
Boolean existsByFirstName(String firstName);
}
|
package com.citibank.ods.persistence.pl.dao;
import java.math.BigInteger;
import java.util.ArrayList;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
*
* @see package com.citibank.ods.persistence.pl.dao;
* @version 1.0
* @author michele.monteiro,05/06/2007
*
*/
public interface BaseTplCurAcctPrmntInstrDAO
{
public ArrayList selectByPK( BigInteger custNbr_, BigInteger prodAcctCode_,
BigInteger prodUnderAcctCode_ );
}
|
package dbAssignment.opti_home_shop.data.model;
import java.util.Objects;
import javax.persistence.*;
import com.sun.istack.NotNull;
import org.hibernate.annotations.CreationTimestamp;
@javax.persistence.Entity
@Table(name = "ordertable")
public class OrderTable {
@Id
@Column(name = "OT_Id")
@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int OT_Id;
public int getOT_Id() {
return this.OT_Id;
}
@Column
@NotNull
@CreationTimestamp
private java.sql.Timestamp O_CreateDate;
public java.sql.Timestamp getO_CreateDate() {
return this.O_CreateDate;
}
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
@JoinColumn(name = "CART_Id")
@NotNull
private Cart cart;
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
@JoinColumn(name = "SHIP_Id")
@NotNull
private Shipping shipping;
public Shipping getShipping() {
return shipping;
}
public void setShipping(Shipping shipping) {
this.shipping = shipping;
}
public OrderTable(Cart cart, Shipping shipping) {
this.shipping = shipping;
this.cart = cart;
}
public OrderTable() {
}
@Override
public String toString() {
return "" + OT_Id;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderTable orderTable = (OrderTable) o;
return Objects.equals(OT_Id, orderTable.OT_Id);
}
@Override
public int hashCode() {
return Objects.hash(OT_Id);
}
}
|
package Models;
public class student {
private String eid;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
}
|
package com.staniul.teamspeak.modules.messengers;
import com.staniul.util.validation.Validator;
public class NotEmptyParamsValidator implements Validator<String> {
@Override
public boolean validate(String element) {
return !"".equals(element);
}
}
|
/*This class is the hash table implementation
* with an array of Linked List to represent the chaining
*
* Methods are as follows:
*
* BinaryTreeNode Constructor defualt
* BinaryTreeNode with parameters
*
*
* @author Julio Corral
* @date 10/29/10
* @professor Dr. Fuentes
* @T.A. Jaime Nava
*/
public class BinaryTreeNode
{
//declare the variables
int element;
int bfactor;
BinaryTreeNode leftChild;
BinaryTreeNode rightChild;
//metohd to initialize the varaibles
public BinaryTreeNode()
{
element=0;
leftChild=null;
rightChild=null;
bfactor=0;
}
//set the variables to another variable
public BinaryTreeNode (int newItem,int bf, BinaryTreeNode L, BinaryTreeNode R)
{
element=newItem;
leftChild=L;
rightChild=R;
bfactor=bf;
}
}
|
package ru.job4j.services;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import ru.job4j.models.Brand;
/**
* Класс BrandRepository реализует репозиторий.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 2019-06-01
* @since 2019-06-01
*/
@Repository
public interface BrandRepository extends CrudRepository<Brand, Long>, JpaSpecificationExecutor<Brand> {
}
|
package com.example.myseekbarlibrary.seekbar;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.example.myseekbarlibrary.progressbar.CircleProgressBar;
/***
* @author ljc
* 实现一个7彩的进度条
*/
public class CircleSeekBar extends CircleProgressBar {
public CircleSeekBar(Context context) {
super(context);
}
public CircleSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CircleSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//初始化高和宽
initWidthAndHeight(w, h);
}
@Override
public void drawCircle(Canvas canvas) {
int centerX = (int) (mCenterX + (mMinRadio + mRadius / 2) * Math.cos(mSweepAngle * Math.PI / 180));
int centerY = (int) (mCenterY + (mMinRadio + mRadius / 2) * Math.sin(mSweepAngle * Math.PI / 180));
mBgPaint.setColor(mCircleColor);
canvas.drawCircle(centerX, centerY, mRadius, mBgPaint);
}
@Override
public boolean performClick() {
return super.performClick();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mProgress = getProgress(event) / 360;
mRadius *= 1.5;
invalidate();
break;
case MotionEvent.ACTION_MOVE:
mProgress = getProgress(event) / 360;
if (progressChange != null) {
progressChange.onProgressChange(mProgress);
}
invalidate();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
getRootView().performClick();
mRadius /= 1.5;
invalidate();
break;
}
return true;
}
/***
* 计算移动角度
*/
private float getProgress(MotionEvent event) {
float x = event.getX() - mCenterX;
float y = event.getY() - mCenterY;
if (x > 0 && y > 0) {
return (float) Math.toDegrees(Math.atan(y / x));
} else if (x < 0 && y > 0) {
return 180 + (float) Math.toDegrees(Math.atan(y / x));
} else if (x < 0 && y < 0) {
return 180 + (float) Math.toDegrees(Math.atan(y / x));
} else {
return 360 + (float) Math.toDegrees(Math.atan(y / x));
}
}
}
|
package com.example.km.genericapp.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.example.km.genericapp.R;
import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;
public class SettingsFragment extends Fragment {
private PublishSubject<Boolean> postsSubject;
private PublishSubject<Boolean> recipesSubject;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_settings, container, false);
Button homeButton = (Button) rootView.findViewById(R.id.btnPosts);
homeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
postsSubject.onNext(true);
}
});
Button settingsButton = (Button) rootView.findViewById(R.id.btnRecipes);
settingsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
recipesSubject.onNext(true);
}
});
return rootView;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_home:
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public Observable<Boolean> launchPosts() {
if (postsSubject == null) {
postsSubject = PublishSubject.create();
}
return postsSubject;
}
public Observable<Boolean> launchRecipes() {
if (recipesSubject == null) {
recipesSubject = PublishSubject.create();
}
return recipesSubject;
}
}
|
package game;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
public static void fightMalfoy(Player player) {
int younumber, malfoy;
System.out.println(
"\n\nYou have entered the slythrien's common room\n here stand your enemy draco malfoy challenge him by press Y and go back by pressing N\n");
String i = in.nextLine();
if (i.charAt(0) == 'y') {
do {
malfoy = (int) (Math.random() * 10);
younumber = (int) (Math.random() * 5);
System.out.println("Malfoy point: " + malfoy);
System.out.println("your point: " + younumber);
if (younumber <= malfoy)
System.out.println("\n\nOooo no malfoy got better than you this time try again\n\n");
} while (younumber <= malfoy);
System.out.println("You have won the challenge lets move forward to dark lord now");
} else {
System.out.println("\n\nYou have decided to move back lets leave malfoy today and kill the dark lord\n\n");
player.move("w");
}
}
public static void view(Player player) {
int choice;
do {
System.out.println("curent room: " + player.getCurrent().getName());
System.out.println("1.move");
System.out.println("2.look");
System.out.println("3.pickup");
System.out.println("4.drop");
System.out.println("5.inventory");
System.out.println("7.exit");
choice = Integer.parseInt(in.nextLine());
if (choice == 1) {
System.out.println("your option: ");
for (int i = 0; i < 4; i++) {
if (player.getCurrent().getNeigbhour()[i] != null) {
if (i == 0)
System.out.println("North(n): " + player.getCurrent().getNeigbhour()[i].getName());
if (i == 1)
System.out.println("West(w): " + player.getCurrent().getNeigbhour()[i].getName());
if (i == 2)
System.out.println("East(e): " + player.getCurrent().getNeigbhour()[i].getName());
if (i == 3)
System.out.println("South(s): " + player.getCurrent().getNeigbhour()[i].getName());
}
}
System.out.println("Enter direction");
String d = in.nextLine();
player.move(d);
if (player.getCurrent().getName() == "Dumboldor's office") {
if (player.getInventory().indexOf("magic wand") > -1) {
System.out.println(
"You used the most deadly magic on dark lord Avada Kedavra. and there falls the dark lord");
break;
} else if (player.getInventory().indexOf("knife") > -1) {
System.out.println("killed dark lord with knife");
break;
} else if (player.getInventory().indexOf("snake poison") > -1) {
System.out.println("killed dark lord with snake poison");
break;
} else if (player.getInventory().indexOf("axe") > -1) {
System.out.println("killed dark lord with axe");
break;
} else {
System.out.println("kicked dark lord in the face and he falls");
break;
}
} else if (player.getCurrent().getName() == "Slytherin's common room") {
fightMalfoy(player);
} else if (player.getCurrent().getName() == "Cliff") {
System.out.println("Malfoy has fooled you u have fallen from the cliff you are dead");
break;
}
} else if (choice == 2) {
player.description();
} else if (choice == 3) {
player.pickup();
} else if (choice == 4) {
player.drop();
} else if (choice == 5) {
player.showInventory();
} else {
if (choice != 7) {
System.out.println("Enter a valid choice");
}
}
} while (choice != 7);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// initiali
Room platform = new Room("platform 9 3/4",
"you are about to enter the first only School of Witchcraft and Wizardry,Hogwarts \n u need to find the correct way to enter the school\n dont forget to pic up your luggage ");
Room forest = new Room("forbidden forest",
"Hurray, you have successfully enter the premises of Hogwarts\n but wait! something doesn't feel right around this time.\nDon't forget to pick up the lantern to explore the area...... \nForbidden Forest is one of the mysterious places in hogwarts please look around for usefull tools.");
Room hut = new Room("hagrid's hut",
"Hargrid the gate keeper of hogwarts place is always a mess \nwelcome says hagrid, \nBe carefull some thing is wrong around hogwards this time ");
Room griffindor = new Room("griffindor's common room",
"Finally here she is ,your firend Ron Weasley,Harry: Where is Hermione Granger? \nlets find her!!! ");
Room slytherin = new Room("Slytherin's common room", "Slytherin is a howgwarts troublemakers house ");
Room library = new Room("The library", "Library is full of books and favourite place of hermione ");
Room cliff = new Room("Cliff", "Oops you are dead by falling off cliff\n");
Room ror = new Room("The room of requirnment",
"room of requirnment one can only discover this place when he/she really needs it.");
Room office = new Room("Dumboldor's office", "the final destination you have to kill the dark lord.");
platform.setNeigbhour(new Room[] { forest, null, null, null });
forest.setNeigbhour(new Room[] { hut, null, null, platform });
hut.setNeigbhour(new Room[] { null, griffindor, slytherin, forest });
griffindor.setNeigbhour(new Room[] { ror, null, hut, null });
slytherin.setNeigbhour(new Room[] { library, hut, null, null });
library.setNeigbhour(new Room[] { null, cliff, null, slytherin });
ror.setNeigbhour(new Room[] { office, null, null, griffindor });
platform.setItems(new ArrayList<String>(Arrays.asList("luggage ", "Hedwig")));
forest.setItems(new ArrayList<String>(Arrays.asList("lantern ", "axe")));
hut.setItems(new ArrayList<String>(Arrays.asList("dragon's egg ")));
griffindor.setItems(new ArrayList<String>(Arrays.asList("Sword of Gryffindor ")));
slytherin.setItems(new ArrayList<String>(Arrays.asList("snake poison ")));
library.setItems(new ArrayList<String>(Arrays.asList("hermine books ")));
ror.setItems(new ArrayList<String>(Arrays.asList("knife ", "magic wand")));
Player me = new Player(platform);
view(me);
}
}
|
package com.adventurpriseme.castme.CommsMgr;
/**
* Enumerates the supported communications channels.
* <p/>
* This provides a list of supported communication channels.
* The final entry, NUM_SUPPORTED_COMM_TYPES, must be the last item in the list,
* and tells us how many communication types we support.
* <p/>
* Created by Timothy on 12/27/2014.
* Copyright 12/27/2014 adventurpriseme.com
*/
public enum ECommChannelTypes
{
CHROMECAST,
CCL,
// Google Chromecast
NUM_SUPPORTED_COMM_TYPES // This must always be last in the list
}
|
package elections;
public class InvalidInputData extends Exception {
}
|
package com.citibank.newcpb.enun;
import java.util.ArrayList;
import com.citibank.newcpb.bean.ResultTableBean;
public enum CustomerTypeEnum {
NATUTAL_PERSON("F", "Fisica"),
LEGAL_PERSON("J","Juridica");
private String value;
private String desc;
private CustomerTypeEnum(String value, String desc) {
this.value = value;
this.desc = desc;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public static CustomerTypeEnum fromValue(String value) throws IllegalArgumentException {
try {
for (CustomerTypeEnum customerTypeEnum : CustomerTypeEnum.values()) {
if (customerTypeEnum.getValue().toUpperCase().equals(value.toUpperCase())) {
return customerTypeEnum;
}
}
return null;
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("Unknown enum value type :" + value);
}
}
public static ArrayList<ResultTableBean> getCustomerTypeList() {
ArrayList<ResultTableBean> constitutionTypeList = new ArrayList<ResultTableBean>() ;
for(CustomerTypeEnum customerTypeEnum : CustomerTypeEnum.values()){
ResultTableBean resultTableBean = new ResultTableBean();
resultTableBean.setResultCode(customerTypeEnum.getValue());
resultTableBean.setResultDescription(customerTypeEnum.getDesc());
constitutionTypeList.add(resultTableBean);
}
return constitutionTypeList;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.