text
stringlengths
10
2.72M
package com.tencent.mm.plugin.ipcall.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.plugin.ipcall.ui.IPCallShareCouponCardUI.6; class IPCallShareCouponCardUI$6$1 implements OnClickListener { final /* synthetic */ 6 kyo; IPCallShareCouponCardUI$6$1(6 6) { this.kyo = 6; } public final void onClick(DialogInterface dialogInterface, int i) { } }
package www.chaayos.com.chaimonkbluetoothapp.management.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import www.chaayos.com.chaimonkbluetoothapp.bluetooth.Constants; import www.chaayos.com.chaimonkbluetoothapp.data.model.OrderItem; import www.chaayos.com.chaimonkbluetoothapp.db.DatabaseAdapter; import www.chaayos.com.chaimonkbluetoothapp.domain.model.ChaiMonk; import www.chaayos.com.chaimonkbluetoothapp.domain.model.new_model.CounterEnum; import www.chaayos.com.chaimonkbluetoothapp.domain.model.new_model.TaskState; /** * Created by shikhar on 18-07-2016. */ public class ChaiMonkManager { private static ChaiMonkManager instance = null; private Map<UUID,ChaiMonk> chaiMonks = new HashMap<>(); private ChaiMonkManager(){} public static ChaiMonkManager getInstance(){ if(instance==null){ instance = new ChaiMonkManager(); } return instance; } public void removeMonk(UUID uuid){ if(instance.chaiMonks.get(uuid)!=null){ instance.chaiMonks.remove(uuid); } } public Map<TaskState,List<ChaiMonk>> findFreeMonks(){ Map<TaskState,List<ChaiMonk>> freeMonks = new HashMap<>(); for(ChaiMonk chaiMonk : instance.chaiMonks.values()){ List<ChaiMonk> monksOfType = freeMonks.get(chaiMonk.getCurrentStatus()); if (monksOfType == null) { monksOfType = new ArrayList<>(); } monksOfType.add(chaiMonk); freeMonks.put(chaiMonk.getCurrentStatus(),monksOfType); } return freeMonks; } public ChaiMonk getChaiMonk(UUID uuid){ return instance.chaiMonks.get(uuid); } public static void setChaiMonks(List<ChaiMonk> chaiMonkList){ for(ChaiMonk chaiMonk : chaiMonkList){ instance.chaiMonks.put(chaiMonk.getUuid(),chaiMonk); } } public ChaiMonk assignToMonk(Map<TaskState, List<ChaiMonk>> monks, OrderItem orderItem, Integer orderId, DatabaseAdapter databaseAdapter) { ChaiMonk assignedMonk = null; if(monks.get(TaskState.WAITING)!=null){ for(ChaiMonk monk : monks.get(TaskState.WAITING)){ int threshold = monk.getQuantity() + orderItem.getQuantity(); if(threshold <= 14 && monk.getProductId().equals(orderItem.getProductId())){ assignedMonk = monk; if(!assignedMonk.getOrderIdList().contains(orderId)){ orderItem.setWorkItemId(monk.getWorkItemId()); monk.getOrderIdList().add(orderId); monk.setQuantity(threshold); } break; } } } if(assignedMonk==null){ assignedMonk = monks.get(TaskState.IDLE)!=null ? monks.get(TaskState.IDLE).get(0):null; if(assignedMonk != null){ Integer workItem = databaseAdapter.getDataFromCounterTable().get(CounterEnum.WORK_ITEM_ID.toString()); orderItem.setWorkItemId(workItem); assignedMonk.setWorkItemId(workItem); assignedMonk.setQuantity(orderItem.getQuantity() >= 14 ? 14 : orderItem.getQuantity()); assignedMonk.setProductId(orderItem.getProductId()); assignedMonk.setProductName(orderItem.getProductName()); assignedMonk.setCurrentStatus(TaskState.WAITING); assignedMonk.setDimension(orderItem.getDimension()!=null ? orderItem.getDimension() : "Regular"); assignedMonk.getOrderIdList().add(orderId); assignedMonk.setCommand(Constants.ChaiMonkCommand.START); databaseAdapter.updateWorkItemId(); // update counter of work item id label in database } } if(assignedMonk!=null){ instance.chaiMonks.put(assignedMonk.getUuid(),assignedMonk); } return assignedMonk; } public List<ChaiMonk> getAllMonks() { return new ArrayList<>(instance.chaiMonks.values()); } public void setChaiMonk(UUID uuid, ChaiMonk chaiMonk) { instance.chaiMonks.put(uuid,chaiMonk); } }
package com.ev.srv.demopai.api; import com.evo.api.springboot.exception.ApiException; import com.ev.srv.demopai.service.PingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; 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.RequestPart; import org.springframework.web.multipart.MultipartFile; import lombok.extern.slf4j.Slf4j; import com.evo.api.springboot.exception.ApiException; import io.swagger.annotations.ApiParam; import io.swagger.annotations.*; import java.util.List; @Slf4j @RestController @RequestMapping("/api") public class PingController { @Autowired private PingService service; @ApiOperation(value = "Returns pong if the server is running.", nickname = "ping", notes = "", response = String.class, tags={ }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = String.class) }) @RequestMapping(value = "/ping", produces = { "application/json" }, method = RequestMethod.GET) public ResponseEntity<String> ping() throws ApiException{ return new ResponseEntity<String>(service.ping(), HttpStatus.NOT_IMPLEMENTED); } }
package com.daheka.nl.social.shadowfish.restserver.rest; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * Exception class that is thrown when a resource is not found */ @ResponseStatus( value = HttpStatus.NOT_FOUND ) class ResourceNotFoundException extends RuntimeException{ // }
package com.bespinglobal.alertnow.models; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Integration { private String eventId; private String Package; private String platform; private String eventTime; private String message; private Level level; private String tag; private Detail detail; }
package com.mega.mvc07.test; public class One1 { public One1() { System.out.println("ssssssssssss"); } }
package bdda; import exception.SGBDException; import java.io.*; import java.util.ArrayList; public class DBDef implements Serializable { private ArrayList<RelDef> listeDeRelDef; private int compteurRel; private static DBDef dbdef = new DBDef(); private DBDef() { listeDeRelDef = new ArrayList<RelDef>(); this.compteurRel = 0; } public static DBDef getInstance() { return dbdef; } /** Pour ajouter une relation * * @param relation (la relation a ajouter) */ public void addRelation(RelDef relation) { listeDeRelDef.add(relation); compteurRel++; } public ArrayList<RelDef> getListeDeRelDef() { return listeDeRelDef; } public void setListeDeRelDef(ArrayList<RelDef> listeDeRelDef) { this.listeDeRelDef = listeDeRelDef; } public int getCompteurRel() { return compteurRel; } public void setCompteurRel(int compteurRel) { this.compteurRel = compteurRel; } /** Initialiser la classe lorsque le programme demarre a partir d'un fichier Catalog.def * */ public void init() throws SGBDException { File fichier = new File(Constantes.pathName + "Catalog.def"); try(FileInputStream fis = new FileInputStream(fichier); ObjectInputStream ois = new ObjectInputStream(fis)){ dbdef = (DBDef) ois.readObject(); System.out.println(dbdef.listeDeRelDef); } catch (FileNotFoundException e) { // si le fichier Catalog.def n'existe pas dbdef = new DBDef(); // on initialise la classe sans rien en plus try { fichier.createNewFile(); // On cree le fichier } catch (IOException ioe) { throw new SGBDException("Impossible de creer un fichier"); } } catch (IOException e) { // S'il y a une autre erreurr d'I/O throw new SGBDException("Erreur lors de la lecture de l'objet DBDef dans le fichier Catalog.def, il se peut qu'il soit corrompu"); } catch (ClassNotFoundException e) { throw new SGBDException("Euh c'est bizarre la, la classe DBDef ne trouve pas la classe DBDef"); } } /** Permet d'enregistrer l'instance de la classe dans le fichier Catalog.def avant d'arreter le programme * * @throws SGBDException */ public void finish() throws SGBDException { File fichier = new File(Constantes.pathName + "Catalog.def"); if(!fichier.exists()) { // Si le fichier n'existe pas //System.out.println("Le fichier n'existe pas"); try { fichier.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try(FileOutputStream fos = new FileOutputStream(fichier); ObjectOutputStream oos = new ObjectOutputStream(fos)){ oos.writeObject(dbdef); } catch (FileNotFoundException e) { throw new SGBDException("Impossible de creer un fichier"); } catch (IOException e) { e.printStackTrace(); throw new SGBDException("Erreur lors de l'ecriture de l'objet DBDef dans le fichier Catalog.def"); } } public void reset(){ listeDeRelDef = new ArrayList<>(); this.compteurRel = 0; } }
package main.model; public class Arc extends CommonField { private String arcType; private String transId; private String placeId; private CommonField annot; public String getArcType() { return arcType; } public void setArcType(String arcType) { this.arcType = arcType; } public String getTransId() { return transId; } public void setTransId(String transId) { this.transId = transId; } public String getPlaceId() { return placeId; } public void setPlaceId(String placeId) { this.placeId = placeId; } public CommonField getAnnot() { return annot; } public void setAnnot(CommonField annot) { this.annot = annot; } }
package negocio.editorial; import java.util.Collection; /** * The Interface SAEditorial. */ public interface SAEditorial { /** * Alta editorial. * * @param tEditorial * the t editorial * @return the integer * @throws Exception * the exception */ public Integer altaEditorial(TransferEditorial tEditorial) throws Exception; /** * Baja editorial. * * @param id * the id * @return the integer * @throws Exception * the exception */ public Integer bajaEditorial(Integer id) throws Exception; /** * Listar editoriales. * * @return the collection * @throws Exception * the exception */ public Collection<TransferEditorial> listarEditoriales() throws Exception; /** * Modificar editorial. * * @param tEditorial * the t editorial * @return the integer * @throws Exception * the exception */ public Integer modificarEditorial(TransferEditorial tEditorial) throws Exception; /** * Mostrar editorial. * * @param id * the id * @return the transfer editorial * @throws Exception * the exception */ public TransferEditorial mostrarEditorial(Integer id) throws Exception; }
/* * StatisticCustomTagService.java * This file was last modified at 2018.12.03 20:05 by Victor N. Skurikhin. * $Id$ * This is free and unencumbered software released into the public domain. * For more information, please refer to <http://unlicense.org> */ package ru.otus.server.services; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import ru.otus.models.StatisticEntities; import ru.otus.models.StatisticEntity; import ru.otus.utils.NullString; import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; import javax.json.bind.JsonbConfig; import javax.servlet.http.HttpServletRequest; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.sql.SQLException; import java.time.LocalDateTime; import java.util.Optional; import static ru.otus.shared.Constants.*; public class StatisticCustomTagService implements DataOrigin, StatisticService { private static final Logger LOGGER = LogManager.getLogger(StatisticCustomTagService.class); private DbService dbService; private boolean collectionEnabled; private List<StatisticEntity> readyResultList = null; public StatisticCustomTagService(DbService dbService, boolean collection) { this.dbService = dbService; this.collectionEnabled = collection; } private String getNameMarker() { return Optional.ofNullable(System.getenv(ENVIRONMENT_MARKER_NAME)).orElse(DEFAULT_MARKER_NAME); } @Override public long saveStatisticFromRequestParams(HttpServletRequest request, DbService dbService) { StatisticEntity result = new StatisticEntity(); result.setId(-1L); result.setNameMarker(getNameMarker()); result.setJspPageName(request.getParameter(PARAMETER_PAGE_NAME)); result.setIpAddress(request.getRemoteAddr()); result.setUserAgent(request.getHeader(HEADER_USER_AGENT)); result.setClientTime(LocalDateTime.parse(request.getParameter(PARAMETER_CLIENT_TIME))); result.setServerTime(LocalDateTime.now()); result.setSessionId(request.getSession().getId()); result.setUser(dbService.getUserEntityByName(request.getRemoteUser())); result.setPreviousId(NullString.returnLong(request.getParameter(PARAMETER_PREVIOS_ID))); return dbService.insertIntoStatistic(result); } @Override public boolean isCollectionEnabled() { return collectionEnabled; } @Override public List<StatisticEntity> getAllVisitsStatElements() { try { return dbService.getAllStatisticElements(); } catch (SQLException e) { LOGGER.error("getAllVisitsStatElements: catch({}): {}", e.getClass(), e); } return null; } @Override public void setCollectionEnabled(boolean collectionEnabled) { this.collectionEnabled = collectionEnabled; } @Override public synchronized boolean isReady() { return readyResultList != null; } private synchronized void setReadyResultList(List<StatisticEntity> readyResultList) { this.readyResultList = readyResultList; } @Override public void fetchData() throws SQLException { setReadyResultList(getAllVisitsStatElements()); } @Override public String getDataXML() { JAXBContext context = null; try { context = JAXBContext.newInstance(StatisticEntities.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); OutputStream os = new ByteArrayOutputStream(); StatisticEntities list = new StatisticEntities(readyResultList); m.marshal(list, os); return os.toString(); } catch (JAXBException e) { LOGGER.error("getDataXML: catch({}): {}", e.getClass(), e); } return null; } @Override public String getDataJSON() { StatisticEntities list = new StatisticEntities(readyResultList); JsonbConfig config = new JsonbConfig().withFormatting(true); Jsonb jsonb = JsonbBuilder.create(config); return jsonb.toJson(list); } } /* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et */ //EOF
package com.chaabane.jasperlog; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class JasperlogApplicationTests { @Test void contextLoads() { } }
package twoLayerNN; import java.util.Arrays; public class NeuralNetwork { /* * activation function: logistic function * f(x) = 1 / (1 + e^(-x)) * * NOTE: WE DO NOT COUNT 'INPUTS' AS A LAYER * * size_list = { num_of_neurons_in_layer_0 (inputs), * num_in_layer_1 (first hidden layer), * ..., * num_in_last_layer (outputs) } * * num_inputs = size_list[0] * num_layers = size_list.length - 1 = sizes.length * sizes = { num_in_layer_1 (first hidden layer), * ..., * num_in_last_layer (outputs) } * * z = net input = weighted input * x = inputs = activations of prev layer = outputs of prev layer * a = outputs = activations of current layer = inputs of next layer * y = target outputs * cost function = loss function = objective = error function * activation function = logistic function = sigmoid function */ final double LEARNING_RATE = 0.5; int num_layers; int num_inputs; int[] sizes; NeuronLayer[] layers; public NeuralNetwork (int[] size_list) { this.num_layers = size_list.length - 1; this.sizes = Arrays.copyOfRange(size_list, 1, size_list.length); this.num_inputs = size_list[0]; // randomize values for weights and biases double[][] weights = new double[this.num_layers][]; for (int i = 0; i < this.num_layers; i++) { int num_weights_for_layer = size_list[i]*size_list[i+1]; weights[i] = randomize_array(num_weights_for_layer); } double[] biases = randomize_array(this.num_layers); create_layers(weights, biases); // this.inspect(); } public NeuralNetwork (int[] size_list, double[][] weights, double[] biases) { this.num_layers = size_list.length - 1; this.sizes = Arrays.copyOfRange(size_list, 1, size_list.length); this.num_inputs = size_list[0]; create_layers(weights, biases); } public void create_layers (double[][] weights, double[] biases) { this.layers = new NeuronLayer[this.num_layers]; for(int i = 0; i < this.num_layers; i++) { this.layers[i] = new NeuronLayer(this.sizes[i], weights[i], biases[i]); } } public double[] randomize_array (int size) { double[] rands = new double[size]; for (int i = 0; i < size; i++) { rands[i] = Math.random(); } return rands; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * public void train (double[] inputs, double[] target_outputs) { // activations' first row = inputs double[][] activations = feedforward(inputs); // print_array("activations from feedforward", activations); double[] outputs = activations[activations.length-1]; // print_array("outputs from feedforward", outputs); double[] errors = total_error(outputs, target_outputs); print_err(errors); double[] output_deltas = get_output_deltas(outputs, target_outputs); // print_array("output deltas", output_deltas); double[][] deltas = new double[this.num_layers][]; deltas[deltas.length-1] = output_deltas; for (int i = deltas.length - 2; i >= 0; i--) { deltas[i] = layers[i+1].get_layer_deltas(deltas[i+1], activations[i+1]); // print_array("activations[" + (i+1) + "]", activations[i+1]); } // print_array("deltas", deltas); double[][][] gradients_w = new double[this.num_layers][][]; for (int i = 0; i < gradients_w.length; i++) { // the reason the inputs here aren't like 'i-1' and 'i', is bc our // delta matrices only have 2 layers, we foregoed the 'input' layer gradients_w[i] = layers[i].get_gradients_w(activations[i], deltas[i]); } // print_array("gradients (WEIGHTS)", gradients_w); double[][] gradients_b = new double[this.num_layers][]; for (int i = 0; i < gradients_b.length; i++) { gradients_b[i] = layers[i].get_gradients_b(deltas[i]); } // print_array("gradients (BIASES)", gradients_b); // this.inspect(); this.update_network(gradients_w, gradients_b); // this.inspect(); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * public double[][] feedforward (double[] inputs) { // activations[i] = outputs of layer i, inputs of layer i+1 double[][] activations = new double[this.num_layers+1][]; activations[0] = inputs; for (int i = 0; i < this.num_layers; i++) { activations[i+1] = this.layers[i].feedforward(activations[i]); } return activations; } public double[] total_error(double[] outputs, double[] target_outputs) { int n = (outputs.length == target_outputs.length) ? outputs.length : -1; if (n < 0) throw new Error("outputs and targets' lengths do not match!!"); double[] errors = new double[n]; for (int i = 0; i < n; i++) { errors[i] = cost_function(outputs[i], target_outputs[i]); } return errors; } public double cost_function (double output, double target) { return 0.5 * Math.pow(target - output, 2); } // EQUATION 1 (BP1) // δ^L_j = (∂C / ∂a^L_j) * σ′(z^L_j) // = [-(target - output)] * [output(1-output)] // = (a - y) * a(1 - a) // from δ = (∂E / ∂z) // = (∂C / ∂a) // = (∂E / ∂a) * (∂a / ∂z) // = (∂C / ∂a^L_j) * σ′(z^L_j) etc public double[] get_output_deltas (double[] outputs, double[] targets) { double[] deltas = new double[outputs.length]; for (int i = 0; i < outputs.length; i++) { deltas[i] = cost_derivative(outputs[i], targets[i]) * activate_derivative(outputs[i]); } return deltas; } public double cost_derivative (double output, double target) { // with respect to output/activation return -(target - output); } public static double activate (double z) { return 1 / (1 + Math.exp(-z)); } public static double activate_derivative (double output) { return output * (1 - output); } public void update_network (double[][][] gradients_w, double[][] gradients_b) { for (int i = 0; i < this.num_layers; i++) { layers[i].update_network_layer(gradients_w[i], gradients_b[i], this.LEARNING_RATE); } } public void try_inputs (double[] inputs, double[] expected) { double[] outputs = feedforward(inputs)[this.num_layers]; System.out.println("inputs: " + Arrays.toString(inputs)); System.out.println("expected: " + Arrays.toString(expected)); System.out.println("outputs: " + Arrays.toString(outputs) + "\n"); } public void inspect() { System.out.println("\t----------------------------------------------------------------------------------"); for (int i = 0; i < layers.length; i++) { layers[i].inspect(); System.out.println("\t----------------------------------------------------------------------------------"); } } public static void print_array(String title, double[] arr) { System.out.println(title + ":"); System.out.println("\t" + Arrays.toString(arr)); System.out.println(); } public static void print_array(String title, double[][] arr) { System.out.println(title + ":"); for (int i = 0; i < arr.length; i++) System.out.println("\t" + Arrays.toString(arr[i])); System.out.println(); } public static void print_array(String title, double[][][] arr) { System.out.println(title + ":"); for (int i = 0; i < arr.length; i++) for (int j = 0; j < arr[i].length; j++) System.out.println("\t" + Arrays.toString(arr[i][j])); System.out.println(); } public static void print_err(double[] err) { // the multiplication is to scale the error so it's easier to compare when we have many iterations // for (int i = 0; i < err.length; i++) err[i] *= 100; System.out.print("errors: " + Arrays.toString(err)); System.out.println(); } public static void main (String[] args) { // given initial values testing example // int[] size_list = {2, 2, 2}; // double[] biases = {0.35, 0.60}; // double[][] weights = { // {0.15, 0.20, 0.25, 0.30}, // {0.40, 0.45, 0.50, 0.55} // }; // double[] inputs = {0.05, 0.10}; // double[] target_outputs = {0.01, 0.99}; // // NeuralNetwork nn = new NeuralNetwork(size_list, weights, biases); // nn.train(inputs, target_outputs); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // random initial values testing example // NeuralNetwork randnn = new NeuralNetwork(size_list); // randnn.train(inputs, target_outputs); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // XOR function testing example: double[][][] training_sets = { {{0, 0}, {0}}, // form: {{inputs}, {expected output}} {{0, 1}, {1}}, {{1, 0}, {1}}, {{1, 1}, {0}}, }; int[] size_list = {training_sets[0][0].length, 5, training_sets[0][1].length}; NeuralNetwork XORnn = new NeuralNetwork(size_list); for (int i = 0; i < 1000000; i++) { int rand_choice = (int) Math.floor(Math.random()*training_sets.length); XORnn.train(training_sets[rand_choice][0], training_sets[rand_choice][1]); } System.out.println("\n------------------------------------------------------\n"); for (int i = 0; i < training_sets.length; i++) XORnn.try_inputs(training_sets[i][0], training_sets[i][1]); System.out.println("------------------------------------------------------"); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // AND function testing example: // double[][][] training_sets = { // {{0, 0}, {0}}, // form: {{inputs}, {expected output}} // {{0, 1}, {0}}, // {{1, 0}, {0}}, // {{1, 1}, {1}}, // }; // int[] size_list = {training_sets[0][0].length, 5, training_sets[0][1].length}; // NeuralNetwork ANDnn = new NeuralNetwork(size_list); // for (int i = 0; i < 1000000; i++) { // int rand_choice = (int) Math.floor(Math.random()*training_sets.length); // ANDnn.train(training_sets[rand_choice][0], training_sets[rand_choice][1]); // } // // System.out.println("\n------------------------------------------------------\n"); // for (int i = 0; i < training_sets.length; i++) // ANDnn.try_inputs(training_sets[i][0], training_sets[i][1]); // System.out.println("------------------------------------------------------"); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // OR function testing example: // double[][][] training_sets = { // {{0, 0}, {0}}, // form: {{inputs}, {expected output}} // {{0, 1}, {1}}, // {{1, 0}, {1}}, // {{1, 1}, {1}}, // }; // int[] size_list = {training_sets[0][0].length, 5, training_sets[0][1].length}; // NeuralNetwork ORnn = new NeuralNetwork(size_list); // for (int i = 0; i < 1000000; i++) { // int rand_choice = (int) Math.floor(Math.random()*training_sets.length); // ORnn.train(training_sets[rand_choice][0], training_sets[rand_choice][1]); // } // // System.out.println("\n------------------------------------------------------\n"); // for (int i = 0; i < training_sets.length; i++) // ORnn.try_inputs(training_sets[i][0], training_sets[i][1]); // System.out.println("------------------------------------------------------"); } }
package com.mygdx.game; import espresso.Matrix; import espresso.Approximation; import espresso.Action; import espresso.Policy; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.Input.Keys; public class MyGdxGame extends ApplicationAdapter { int[] hyperparams; Approximation theta; Approximation.Gradient grad; Action[] actions; GameEnvironment genv; double last100; double totalscore; static final int updateInterval = 100; int count; @Override public void create () { hyperparams = new int[]{8, 7, 8, 5, 1}; theta = new Approximation(hyperparams); grad = Approximation.Gradient.fresh(theta); count = 0; genv = new GameEnvironment(); last100 = 0; totalscore = 0; actions = new Action[]{ new GameEnvironment.DoNothing(), new GameEnvironment.TurnRightAction(), new GameEnvironment.TurnLeftAction(), new GameEnvironment.BoostAction() }; } @Override public void render () { Action.ScoredAction action = Policy.policy(theta, actions, GameEnvironment.observe(genv)); GameEnvironment.GameEnvAction a = (GameEnvironment.GameEnvAction) action.action; genv = a.act(genv); GameEnvironment.draw(genv); Matrix score = GameEnvironment.reward(genv); last100 += score.scalarize(); totalscore += score.scalarize(); Approximation.Gradient dJdW = Approximation.dJdW(theta, action.guess, score); grad = Approximation.accumulate(grad, dJdW); if (count % updateInterval == 0) { theta = Approximation.train(theta, grad); grad = Approximation.Gradient.fresh(theta); System.out.printf("average of last 100 steps %f\n", last100 / updateInterval); System.out.printf("total average %f\n", totalscore / count); last100 = 0; genv = GameEnvironment.helpOut(genv); } count++; } @Override public void dispose () { GameEnvironment.dispose(genv); } }
package com.smxknife.java.ex20.b; /** * @author smxknife * 2018-12-02 */ public class Aa { int a = 1; protected void output() { System.out.println(a); } }
import java.math.BigInteger; import java.net.InetSocketAddress; public class NodeInfo { private BigInteger nodeId; private InetSocketAddress socketAddress; private String ip; private int port; public NodeInfo(BigInteger nodeId, InetSocketAddress socketAddress) { this.nodeId = nodeId; this.socketAddress = socketAddress; this.ip = this.socketAddress.getAddress().getHostAddress(); this.port = this.socketAddress.getPort(); } public BigInteger getNodeId() { return this.nodeId; } public void setNodeId(BigInteger nodeId) { this.nodeId = nodeId; } public InetSocketAddress getSocketAddress() { return this.socketAddress; } public void setSocketAddress(InetSocketAddress socketAddress) { this.socketAddress = socketAddress; } public String getIp() { return this.ip; } public void setIp(String ip) { this.ip = ip; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } @Override public String toString() { return "{" + " nodeId='" + getNodeId() + "'" + ", socketAddress='" + getSocketAddress() + "'" + ", ip='" + getIp() + "'" + ", port='" + getPort() + "'" + "}"; } }
package com.tencent.ugc; import android.graphics.Bitmap; public interface TXRecordCommon$ITXSnapshotListener { void onSnapshot(Bitmap bitmap); }
package org.example.db; import com.sun.tools.javah.Gen; import org.example.model.Actor; import org.example.model.Genre; import org.example.model.Movie; import java.sql.*; import java.util.ArrayList; public class MySQLConnection { private static MySQLConnection instance = null; private Connection connection; private MySQLConnection() { try { connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbmovies", "root", ""); } catch (SQLException throwables) { throwables.printStackTrace(); } } public static synchronized MySQLConnection getInstance() { if (instance == null) { instance = new MySQLConnection(); } return instance; } public void closeDB() { try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } public boolean insertGenero(Genre genero) { boolean add = true; try { Statement statement = connection.createStatement(); String sql = ("INSERT INTO generos (tipo) VALUES ('$TYPE')") .replace("$TYPE", genero.getType()); statement.execute(sql); } catch (SQLException throwables) { throwables.printStackTrace(); add = false; } return add; } public boolean insertActor(Actor actor) { boolean add = true; try { Statement statement = connection.createStatement(); String sql = ("INSERT INTO actores (nombre) VALUES ('$NOMBRE')") .replace("$NOMBRE", actor.getName()); statement.execute(sql); } catch (SQLException throwables) { throwables.printStackTrace(); add = false; } return add; } public boolean insertPelicula(Movie movie, int generoID) { boolean add = true; try { Statement statement = connection.createStatement(); String sql = ("INSERT INTO peliculas (nombre,generoID) VALUES ('$NOMBRE','$GENEROID')") .replace("$NOMBRE", movie.getName()) .replace("$GENEROID", "" + generoID); statement.execute(sql); } catch (SQLException throwables) { throwables.printStackTrace(); add = false; } return add; } public ArrayList<Genre> getAllGenere() { ArrayList<Genre> output = new ArrayList<>(); try { Statement statement = connection.createStatement(); String sql = ("SELECT * FROM generos "); ResultSet result = statement.executeQuery(sql); while (result.next()) { int id = result.getInt(1); String tipo = result.getString(2); Genre genero = new Genre(id, tipo); output.add(genero); } } catch (SQLException throwables) { throwables.printStackTrace(); } return output; } public boolean vincularPA(int idMovie, int idActor) { boolean add = true; try { Statement statement = connection.createStatement(); String sql = ("INSERT INTO peliculas_actores (pelicuaID,actorID) VALUES ('$PELICULAID','$ACTORID')") .replace("$PELICULAID", "" + idMovie) .replace("$ACTORID", "" + idActor); statement.execute(sql); } catch (SQLException throwables) { throwables.printStackTrace(); add = false; } return add; } public ArrayList<Movie> getAllMovies() { ArrayList<Movie> output = new ArrayList<>(); try { Statement statement = connection.createStatement(); String sql = ("SELECT * FROM peliculas "); ResultSet result = statement.executeQuery(sql); while (result.next()) { int id = result.getInt(1); String nombre = result.getString(2); int idGenero = result.getInt(3); Movie genero = new Movie(id, nombre,idGenero); output.add(genero); } } catch (SQLException throwables) { throwables.printStackTrace(); } return output; } public ArrayList<Actor> getAllActors() { ArrayList<Actor> output = new ArrayList<>(); try { Statement statement = connection.createStatement(); String sql = ("SELECT * FROM actores "); ResultSet result = statement.executeQuery(sql); while (result.next()) { int id = result.getInt(1); String nombre = result.getString(2); Actor actor = new Actor(id, nombre); output.add(actor); } } catch (SQLException throwables) { throwables.printStackTrace(); } return output; } public boolean deleteMovie(int idMovie) { boolean removed = true; try { Statement statement = connection.createStatement(); String sql = ("DELETE FROM peliculas_actores WHERE peliculas_actores.pelicuaID=$idMovie") .replace("$idMovie", "" + idMovie); String sql2 = ("DELETE FROM peliculas WHERE peliculas.id=$id ") .replace("$id", "" + idMovie); statement.execute(sql); statement.execute(sql2); } catch (SQLException throwables) { throwables.printStackTrace(); removed = false; } return removed; } public boolean deleteActor(int idActor) { boolean removed = true; try { Statement statement = connection.createStatement(); String sql = ("DELETE FROM peliculas_actores WHERE peliculas_actores.actorID=$idActor") .replace("$idActor", "" + idActor); String sql2 = ("DELETE FROM actores WHERE actores.id=$id ") .replace("$id", "" + idActor); statement.execute(sql); statement.execute(sql2); } catch (SQLException throwables) { throwables.printStackTrace(); removed = false; } return removed; } public boolean deleteGenre(int idGenre) { boolean removed = true; try { Statement statement = connection.createStatement(); String sql = ("SELECT id FROM peliculas WHERE peliculas.generoID = $idGenre") .replace("$idGenre", "" + idGenre); ResultSet result = statement.executeQuery(sql); while (result.next()) { int idMovieGenre = result.getInt(1); deleteMovie(idMovieGenre); } String sql2 = ("DELETE FROM generos WHERE generos.id=$id ") .replace("$id", "" + idGenre); statement.execute(sql2); } catch (SQLException throwables) { throwables.printStackTrace(); removed = false; } return removed; } public ArrayList<Movie> listxGenero(int idGenre) { ArrayList<Movie> output = new ArrayList<>(); try { Statement statement = connection.createStatement(); String sql = ("SELECT id , nombre ,generoID FROM peliculas WHERE peliculas.generoID=$idGenero") .replace("$idGenero", "" + idGenre); ResultSet result = statement.executeQuery(sql); while (result.next()) { int id = result.getInt(1); String nombre = result.getString(2); int idGen = result.getInt(3); Movie movie = new Movie(id, nombre,idGen); output.add(movie); } } catch (SQLException throwables) { throwables.printStackTrace(); } return output; } public ArrayList<Movie> listPxA(int idActor) { ArrayList<Movie> output = new ArrayList<>(); try { Statement statement = connection.createStatement(); String sql = ("SELECT peliculas.id ,peliculas.nombre ,peliculas.generoID FROM (peliculas INNER JOIN peliculas_actores ON peliculas.id = peliculas_actores.pelicuaID) INNER JOIN actores ON peliculas_actores.actorID = actores.id WHERE actores.id = $idAct") .replace("$idAct", "" + idActor); ResultSet result = statement.executeQuery(sql); while (result.next()) { int id = result.getInt(1); String nombre = result.getString(2); int idGen = result.getInt(3); Movie movie = new Movie(id, nombre,idGen); output.add(movie); } } catch (SQLException throwables) { throwables.printStackTrace(); } return output; } //SELECT actores.id , actores.nombre FROM ( actores INNER JOIN peliculas_actores ON actores.id= peliculas_actores.actorID) INNER JOIN peliculas ON peliculas.id= peliculas_actores.pelicuaID WHERE peliculas.id=5 public ArrayList<Actor> listAxP(int idMovie) { ArrayList<Actor> output = new ArrayList<>(); try { Statement statement = connection.createStatement(); String sql = ("SELECT actores.id , actores.nombre FROM ( actores INNER JOIN peliculas_actores ON actores.id= peliculas_actores.actorID) INNER JOIN peliculas ON peliculas.id= peliculas_actores.pelicuaID WHERE peliculas.id=$idM") .replace("$idM", "" + idMovie); ResultSet result = statement.executeQuery(sql); while (result.next()) { int id = result.getInt(1); String nombre = result.getString(2); Actor actor = new Actor(id, nombre); output.add(actor); } } catch (SQLException throwables) { throwables.printStackTrace(); } return output; } public ArrayList<String> infoALl(){ ArrayList<String> ouput = new ArrayList<>(); try { Statement statement = connection.createStatement(); String sql = ("SELECT peliculas.nombre, actores.nombre , generos.tipo FROM (peliculas LEFT JOIN peliculas_actores ON peliculas.id = peliculas_actores.pelicuaID) LEFT JOIN actores ON peliculas_actores.actorID = actores.id INNER JOIN generos ON generos.id=peliculas.generoID"); ResultSet result = statement.executeQuery(sql); while (result.next()) { String nombreMovie ="TITULO: "+result.getString(1); String nombreActor ="ACTOR: "+result.getString(2); String tipo ="GENERO: "+result.getString(3); String obj =nombreMovie+". "+tipo+". "+nombreActor+"."; ouput.add(obj); } } catch (SQLException throwables) { throwables.printStackTrace(); } return ouput; } public String getGenre(int idGenre){ String genero = ""; try { Statement statement = connection.createStatement(); String sql = ("SELECT generos.id, generos.tipo FROM generos WHERE generos.id = $generid") .replace("$generid",""+idGenre); ResultSet result = statement.executeQuery(sql); while (result.next()) { genero = result.getString(2); } } catch (SQLException throwables) { throwables.printStackTrace(); } return genero; } }
package javax.vecmath; import java.io.Serializable; public class GVector implements Serializable, Cloneable { private int length; double[] values; static final long serialVersionUID = 1398850036893875112L; public GVector(int length) { this.length = length; this.values = new double[length]; for (int i = 0; i < length; ) { this.values[i] = 0.0D; i++; } } public GVector(double[] vector) { this.length = vector.length; this.values = new double[vector.length]; for (int i = 0; i < this.length; ) { this.values[i] = vector[i]; i++; } } public GVector(GVector vector) { this.values = new double[vector.length]; this.length = vector.length; for (int i = 0; i < this.length; ) { this.values[i] = vector.values[i]; i++; } } public GVector(Tuple2f tuple) { this.values = new double[2]; this.values[0] = tuple.x; this.values[1] = tuple.y; this.length = 2; } public GVector(Tuple3f tuple) { this.values = new double[3]; this.values[0] = tuple.x; this.values[1] = tuple.y; this.values[2] = tuple.z; this.length = 3; } public GVector(Tuple3d tuple) { this.values = new double[3]; this.values[0] = tuple.x; this.values[1] = tuple.y; this.values[2] = tuple.z; this.length = 3; } public GVector(Tuple4f tuple) { this.values = new double[4]; this.values[0] = tuple.x; this.values[1] = tuple.y; this.values[2] = tuple.z; this.values[3] = tuple.w; this.length = 4; } public GVector(Tuple4d tuple) { this.values = new double[4]; this.values[0] = tuple.x; this.values[1] = tuple.y; this.values[2] = tuple.z; this.values[3] = tuple.w; this.length = 4; } public GVector(double[] vector, int length) { this.length = length; this.values = new double[length]; for (int i = 0; i < length; i++) this.values[i] = vector[i]; } public final double norm() { double sq = 0.0D; for (int i = 0; i < this.length; i++) sq += this.values[i] * this.values[i]; return Math.sqrt(sq); } public final double normSquared() { double sq = 0.0D; for (int i = 0; i < this.length; i++) sq += this.values[i] * this.values[i]; return sq; } public final void normalize(GVector v1) { double sq = 0.0D; if (this.length != v1.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector0")); int i; for (i = 0; i < this.length; i++) sq += v1.values[i] * v1.values[i]; double invMag = 1.0D / Math.sqrt(sq); for (i = 0; i < this.length; i++) this.values[i] = v1.values[i] * invMag; } public final void normalize() { double sq = 0.0D; int i; for (i = 0; i < this.length; i++) sq += this.values[i] * this.values[i]; double invMag = 1.0D / Math.sqrt(sq); for (i = 0; i < this.length; i++) this.values[i] = this.values[i] * invMag; } public final void scale(double s, GVector v1) { if (this.length != v1.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector1")); for (int i = 0; i < this.length; i++) this.values[i] = v1.values[i] * s; } public final void scale(double s) { for (int i = 0; i < this.length; i++) this.values[i] = this.values[i] * s; } public final void scaleAdd(double s, GVector v1, GVector v2) { if (v2.length != v1.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector2")); if (this.length != v1.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector3")); for (int i = 0; i < this.length; i++) this.values[i] = v1.values[i] * s + v2.values[i]; } public final void add(GVector vector) { if (this.length != vector.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector4")); for (int i = 0; i < this.length; i++) this.values[i] = this.values[i] + vector.values[i]; } public final void add(GVector vector1, GVector vector2) { if (vector1.length != vector2.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector5")); if (this.length != vector1.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector6")); for (int i = 0; i < this.length; i++) this.values[i] = vector1.values[i] + vector2.values[i]; } public final void sub(GVector vector) { if (this.length != vector.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector7")); for (int i = 0; i < this.length; i++) this.values[i] = this.values[i] - vector.values[i]; } public final void sub(GVector vector1, GVector vector2) { if (vector1.length != vector2.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector8")); if (this.length != vector1.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector9")); for (int i = 0; i < this.length; i++) this.values[i] = vector1.values[i] - vector2.values[i]; } public final void mul(GMatrix m1, GVector v1) { double[] v; if (m1.getNumCol() != v1.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector10")); if (this.length != m1.getNumRow()) throw new MismatchedSizeException(VecMathI18N.getString("GVector11")); if (v1 != this) { v = v1.values; } else { v = (double[])this.values.clone(); } for (int j = this.length - 1; j >= 0; j--) { this.values[j] = 0.0D; for (int i = v1.length - 1; i >= 0; i--) this.values[j] = this.values[j] + m1.values[j][i] * v[i]; } } public final void mul(GVector v1, GMatrix m1) { double[] v; if (m1.getNumRow() != v1.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector12")); if (this.length != m1.getNumCol()) throw new MismatchedSizeException(VecMathI18N.getString("GVector13")); if (v1 != this) { v = v1.values; } else { v = (double[])this.values.clone(); } for (int j = this.length - 1; j >= 0; j--) { this.values[j] = 0.0D; for (int i = v1.length - 1; i >= 0; i--) this.values[j] = this.values[j] + m1.values[i][j] * v[i]; } } public final void negate() { for (int i = this.length - 1; i >= 0; i--) this.values[i] = this.values[i] * -1.0D; } public final void zero() { for (int i = 0; i < this.length; i++) this.values[i] = 0.0D; } public final void setSize(int length) { int max; double[] tmp = new double[length]; if (this.length < length) { max = this.length; } else { max = length; } for (int i = 0; i < max; i++) tmp[i] = this.values[i]; this.length = length; this.values = tmp; } public final void set(double[] vector) { for (int i = this.length - 1; i >= 0; i--) this.values[i] = vector[i]; } public final void set(GVector vector) { if (this.length < vector.length) { this.length = vector.length; this.values = new double[this.length]; for (int i = 0; i < this.length; i++) this.values[i] = vector.values[i]; } else { int i; for (i = 0; i < vector.length; i++) this.values[i] = vector.values[i]; for (i = vector.length; i < this.length; i++) this.values[i] = 0.0D; } } public final void set(Tuple2f tuple) { if (this.length < 2) { this.length = 2; this.values = new double[2]; } this.values[0] = tuple.x; this.values[1] = tuple.y; for (int i = 2; i < this.length; ) { this.values[i] = 0.0D; i++; } } public final void set(Tuple3f tuple) { if (this.length < 3) { this.length = 3; this.values = new double[3]; } this.values[0] = tuple.x; this.values[1] = tuple.y; this.values[2] = tuple.z; for (int i = 3; i < this.length; ) { this.values[i] = 0.0D; i++; } } public final void set(Tuple3d tuple) { if (this.length < 3) { this.length = 3; this.values = new double[3]; } this.values[0] = tuple.x; this.values[1] = tuple.y; this.values[2] = tuple.z; for (int i = 3; i < this.length; ) { this.values[i] = 0.0D; i++; } } public final void set(Tuple4f tuple) { if (this.length < 4) { this.length = 4; this.values = new double[4]; } this.values[0] = tuple.x; this.values[1] = tuple.y; this.values[2] = tuple.z; this.values[3] = tuple.w; for (int i = 4; i < this.length; ) { this.values[i] = 0.0D; i++; } } public final void set(Tuple4d tuple) { if (this.length < 4) { this.length = 4; this.values = new double[4]; } this.values[0] = tuple.x; this.values[1] = tuple.y; this.values[2] = tuple.z; this.values[3] = tuple.w; for (int i = 4; i < this.length; ) { this.values[i] = 0.0D; i++; } } public final int getSize() { return this.values.length; } public final double getElement(int index) { return this.values[index]; } public final void setElement(int index, double value) { this.values[index] = value; } public String toString() { StringBuffer buffer = new StringBuffer(this.length * 8); for (int i = 0; i < this.length; i++) buffer.append(this.values[i]).append(" "); return buffer.toString(); } public int hashCode() { long bits = 1L; for (int i = 0; i < this.length; i++) bits = VecMathUtil.hashDoubleBits(bits, this.values[i]); return VecMathUtil.hashFinish(bits); } public boolean equals(GVector vector1) { try { if (this.length != vector1.length) return false; for (int i = 0; i < this.length; i++) { if (this.values[i] != vector1.values[i]) return false; } return true; } catch (NullPointerException e2) { return false; } } public boolean equals(Object o1) { try { GVector v2 = (GVector)o1; if (this.length != v2.length) return false; for (int i = 0; i < this.length; i++) { if (this.values[i] != v2.values[i]) return false; } return true; } catch (ClassCastException e1) { return false; } catch (NullPointerException e2) { return false; } } public boolean epsilonEquals(GVector v1, double epsilon) { if (this.length != v1.length) return false; for (int i = 0; i < this.length; i++) { double diff = this.values[i] - v1.values[i]; if (((diff < 0.0D) ? -diff : diff) > epsilon) return false; } return true; } public final double dot(GVector v1) { if (this.length != v1.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector14")); double result = 0.0D; for (int i = 0; i < this.length; i++) result += this.values[i] * v1.values[i]; return result; } public final void SVDBackSolve(GMatrix U, GMatrix W, GMatrix V, GVector b) { if (U.nRow != b.getSize() || U.nRow != U.nCol || U.nRow != W.nRow) throw new MismatchedSizeException(VecMathI18N.getString("GVector15")); if (W.nCol != this.values.length || W.nCol != V.nCol || W.nCol != V.nRow) throw new MismatchedSizeException(VecMathI18N.getString("GVector23")); GMatrix tmp = new GMatrix(U.nRow, W.nCol); tmp.mul(U, V); tmp.mulTransposeRight(U, W); tmp.invert(); mul(tmp, b); } public final void LUDBackSolve(GMatrix LU, GVector b, GVector permutation) { int size = LU.nRow * LU.nCol; double[] temp = new double[size]; double[] result = new double[size]; int[] row_perm = new int[b.getSize()]; if (LU.nRow != b.getSize()) throw new MismatchedSizeException(VecMathI18N.getString("GVector16")); if (LU.nRow != permutation.getSize()) throw new MismatchedSizeException(VecMathI18N.getString("GVector24")); if (LU.nRow != LU.nCol) throw new MismatchedSizeException(VecMathI18N.getString("GVector25")); int i; for (i = 0; i < LU.nRow; i++) { for (int j = 0; j < LU.nCol; j++) temp[i * LU.nCol + j] = LU.values[i][j]; } for (i = 0; i < size; ) { result[i] = 0.0D; i++; } for (i = 0; i < LU.nRow; ) { result[i * LU.nCol] = b.values[i]; i++; } for (i = 0; i < LU.nCol; ) { row_perm[i] = (int)permutation.values[i]; i++; } GMatrix.luBacksubstitution(LU.nRow, temp, row_perm, result); for (i = 0; i < LU.nRow; ) { this.values[i] = result[i * LU.nCol]; i++; } } public final double angle(GVector v1) { return Math.acos(dot(v1) / norm() * v1.norm()); } public final void interpolate(GVector v1, GVector v2, float alpha) { interpolate(v1, v2, alpha); } public final void interpolate(GVector v1, float alpha) { interpolate(v1, alpha); } public final void interpolate(GVector v1, GVector v2, double alpha) { if (v2.length != v1.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector20")); if (this.length != v1.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector21")); for (int i = 0; i < this.length; i++) this.values[i] = (1.0D - alpha) * v1.values[i] + alpha * v2.values[i]; } public final void interpolate(GVector v1, double alpha) { if (v1.length != this.length) throw new MismatchedSizeException(VecMathI18N.getString("GVector22")); for (int i = 0; i < this.length; i++) this.values[i] = (1.0D - alpha) * this.values[i] + alpha * v1.values[i]; } public Object clone() { GVector v1 = null; try { v1 = (GVector)super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } v1.values = new double[this.length]; for (int i = 0; i < this.length; i++) v1.values[i] = this.values[i]; return v1; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\javax\vecmath\GVector.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
class TestTrieTree { public static void main(String[] args) { TrieTree trie = new TrieTree(); String[] dict = new String[]{"hello", "word", "i", "love", "you", "your"}; for (String word : dict) { trie.insert(word); } for (String word : dict) { System.out.println(trie.search(word)); } trie.delete("love"); System.out.println(trie.search("love")); trie.delete("your"); System.out.println(trie.search("your")); System.out.println(trie.search("you")); trie.insert("ysx"); System.out.println(trie.search("ysx")); trie.delete("ysx"); System.out.println(trie.search("ysx")); } }
package ba.bitcamp.LabS11D04.vjezbe; import java.io.InputStream; import java.io.DataInputStream; import java.io.IOException; public class BitBuffer { private static InputStream is; public BitBuffer(InputStream is) { this.is = is; } public String readLine() { byte[] buffer = new byte[10]; StringBuilder sb = new StringBuilder(); DataInputStream dis = new DataInputStream(is); try { while (dis.read(buffer) >= 0) { for (int i = 0; i < buffer.length; i++) { if (buffer[i] != (byte)('\n')) { sb.append((char)(buffer[i])); } else { System.out.println("Usao"); return sb.toString(); } } } dis.close(); } catch (IOException e) { e.printStackTrace(); } return null; } }
package JavaEgzersiz.OOPPresinpleri.TeknoMarket; public class Bilgisayar { private String islemci; private String ekranKarti; private Double ekranBoyutu; private String depolamaTuru; private Integer depoHacmi; private String marka; private Double fiyat; public Double getFiyat() { return fiyat; } public void setFiyat(Double fiyat) { this.fiyat = fiyat; } public String getMarka() { return marka; } public void setMarka(String marka) { this.marka = marka; } public String getIslemci() { return islemci; } public void setIslemci(String islemci) { this.islemci = islemci; } public String getEkranKarti() { return ekranKarti; } public void setEkranKarti(String ekranKarti) { this.ekranKarti = ekranKarti; } public Double getEkranBoyutu() { return ekranBoyutu; } public void setEkranBoyutu(Double ekranBoyutu) { this.ekranBoyutu = ekranBoyutu; } public String getDepolamaTuru() { return depolamaTuru; } public void setDepolamaTuru(String depolamaTuru) { this.depolamaTuru = depolamaTuru; } public Integer getDepoHacmi() { return depoHacmi; } public void setDepoHacmi(Integer depoHacmi) { this.depoHacmi = depoHacmi; } }
/* * 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 dao; /** * * @author SAMUEL */ public class Notas { int[] notas; Asignatura codAsignatura; public Notas() { } public Notas(int[] notas, Asignatura codAsignatura) { this.notas = notas; this.codAsignatura = codAsignatura; } public int[] getNotas() { return notas; } public void setNotas(int[] notas) { this.notas = notas; } public Asignatura getCodAsignatura() { return codAsignatura; } public void setCodAsignatura(Asignatura codAsignatura) { this.codAsignatura = codAsignatura; } }
package com.yida.design.builder.demo; import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.yida.design.builder.demo.car.BMWModel; import com.yida.design.builder.demo.car.BenzModel; /** ********************* * 可能会报错,因为Director类全局变量sequence并非线程安全 * * @author yangke * @version 1.0 * @created 2018年5月10日 下午5:59:27 *********************** */ public class Client { public static void main(String[] args) { int count = 100; CountDownLatch countDownLatch = new CountDownLatch(count); Director director = new Director(); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2), new ThreadPoolExecutor.DiscardPolicy()); for (int i = 0; i < count; i++) { threadPoolExecutor.execute(new Worker(countDownLatch, director)); } try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } } class Worker implements Runnable { private final CountDownLatch countDownLatch; private final Director director; public Worker(CountDownLatch countDownLatch, Director director) { this.countDownLatch = countDownLatch; this.director = director; } @Override public void run() { Random random = new Random(); int nextInt = random.nextInt(2); if (nextInt == 0) { BenzModel benzModel = director.getABenzModel(); benzModel.run(); } else { BMWModel bbmwModel = director.getBBMWModel(); bbmwModel.run(); } countDownLatch.countDown(); } }
package com.fatosajvazi; public class Main { public static void main(String[] args) { // write your code here System.out.println(hasSameLastDigit(12,5,22)); } public static boolean isValid(int number) { if (number < 10 || number > 1000){ return false; } return true; } public static boolean hasSameLastDigit(int firstNumber, int secondNumber, int thirdNumber) { if (!isValid(firstNumber) || !isValid(secondNumber) || !isValid(thirdNumber)){ return false; } int lastDigitOfFirstNumber = firstNumber % 10; int lastDigitOfSecondNumber = secondNumber % 10; int lastDigitOfThirdNumber = thirdNumber % 10; if (lastDigitOfFirstNumber == lastDigitOfSecondNumber || lastDigitOfFirstNumber == lastDigitOfThirdNumber || lastDigitOfSecondNumber == lastDigitOfThirdNumber){ return true; } return false; } }
import java.util.Vector; public class FileTable { private Vector table = new Vector<FileTableEntry>(); // the actual entity of this file table private Directory dir; // the root directory public FileTable(Directory directory) { // constructor dir = directory; // receive a reference to the Director } // from the file system public synchronized FileTableEntry falloc(String filename, String mode) { // Check for incorrect filename input // if (filename == null || filename.isEmpty()) { // return null; // } // Check for incorrect mode input short iNumber = -1; Inode node = null; while (true) { // Set iNumber if (filename.equals("/")) { iNumber = 0; } else { iNumber = dir.namei(filename); } if (iNumber >= 0) { node = new Inode(iNumber); if (mode.equals("r")) { if (node.flag != 0 && node.flag != 1) { try { this.wait(); } catch (InterruptedException e) { } continue; } node.flag = 1; break; } if (node.flag != 0 && node.flag != 3) { if (node.flag == 1 || node.flag == 2) { node.flag = (short)(node.flag + 3); node.toDisk(iNumber); } try { this.wait(); } catch (InterruptedException e) { } continue; } node.flag = 2; break; } if (mode.equals("r")) { return null; } iNumber = this.dir.ialloc(filename); node = new Inode(); node.flag = 2; break; } ++node.count; node.toDisk(iNumber); FileTableEntry tblEntry = new FileTableEntry(node, iNumber, mode); table.addElement(tblEntry); return tblEntry; } public synchronized boolean ffree(FileTableEntry entry) { // Check for null entry being given if (entry == null) { return true; } // Attempt to remove, return false if entry not found if (!table.removeElement(entry)) { return false; } entry.inode.count--; if (entry.inode.flag == 1 || entry.inode.flag == 2) { entry.inode.flag = 0; } if (entry.inode.flag == 4 || entry.inode.flag == 5) { entry.inode.flag = 3; } // Write inode to disk entry.inode.toDisk(entry.iNumber); // Set entry to null entry = null; notify(); return true; } public synchronized boolean fempty() { return table.isEmpty(); // return if table is empty } // should be called before starting a format }
/** * */ package org.rebioma.client.bean.api; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; /** * @author Mikajy * */ @XmlRootElement(name="response") @XmlAccessorType (XmlAccessType.FIELD) public class APIChangePasswordResponse { private boolean success; private String message; private int changePassStatus; public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getChangePassStatus() { return changePassStatus; } public void setChangePassStatus(int changePassStatus) { this.changePassStatus = changePassStatus; } }
package com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.widget; import android.view.View; import android.view.animation.AnimationUtils; import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.widget.a.b; class a$b$5 implements Runnable { final /* synthetic */ b nGF; a$b$5(b bVar) { this.nGF = bVar; } public final void run() { if (a.q(this.nGF.nGD) != null) { View bvP = a.q(this.nGF.nGD).bvP(); if (bvP != null) { if (!(a.C(this.nGF.nGD) != null || a.q(this.nGF.nGD).bvQ() == -1 || a.k(this.nGF.nGD).get() == null)) { a.a(this.nGF.nGD, AnimationUtils.loadAnimation(((View) a.k(this.nGF.nGD).get()).getContext(), a.q(this.nGF.nGD).bvQ())); } if (a.C(this.nGF.nGD) != null) { bvP.startAnimation(a.C(this.nGF.nGD)); } bvP.setVisibility(0); } } } }
package a2lend.app.com.a2lend; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; /** * Created by Igbar on 1/22/2018. */ public class ControlPanelFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_control_panel,null); //super.onCreateView(inflater, container, savedInstanceState); // on create } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // created Toast.makeText(getContext(), "ControlPanelFragment ", Toast.LENGTH_SHORT).show(); } }
package com.maspain.snake.entity; import java.util.Hashtable; import com.maspain.snake.game.Game; import com.maspain.snake.graphics.Screen; import com.maspain.snake.entity.SnakeHead; import com.maspain.snake.entity.Entity; import com.maspain.snake.entity.SnakeFood; import com.maspain.snake.level.PixelCoordinate; public class FoodSpawner extends Entity { private int maxFood; private int minFood; public static int spriteSize = SnakeHead.spriteSize; public static int halfSpriteSize = spriteSize >> 1; private static int[] validXLocations; private static int[] validYLocations; private Hashtable<PixelCoordinate, SnakeFood> food = new Hashtable<PixelCoordinate, SnakeFood>(); public FoodSpawner(int minFood, int maxFood) { this.minFood = minFood; this.maxFood = maxFood; int xMax = Game.width - Game.borderWidth - halfSpriteSize; int xMin = Game.borderWidth + halfSpriteSize; int yMax = Game.height - Game.borderWidth - halfSpriteSize; int yMin = Game.borderWidth + halfSpriteSize; int xSize = (xMax - xMin) / spriteSize; int ySize = (yMax - yMin) / spriteSize; validXLocations = new int[xSize]; validYLocations = new int[ySize]; for (int i = 0; i < xSize; i++) { validXLocations[i] = (i * spriteSize) + spriteSize; } for (int i = 0; i < ySize; i++) { validYLocations[i] = (i * spriteSize) + spriteSize; } } public void init() { for (int i = 0; i < maxFood; i++) spawn(); } public void spawn() { PixelCoordinate p; do p = getValidLocation(); while (food.contains(p)); addFood(new SnakeFood(p)); } public void addFood(SnakeFood s) { food.put(s.location(), s); } public boolean removeFoodAt(PixelCoordinate p) { return (food.remove(p) != null); } private PixelCoordinate getValidLocation() { int xa = random.nextInt(validXLocations.length); int ya = random.nextInt(validYLocations.length); return (new PixelCoordinate(validXLocations[xa], validYLocations[ya])); } public void update() { int foodCount = food.size(); if (foodCount < minFood) { for (int i = foodCount; i < maxFood; i++) { spawn(); } } } public void render(Screen screen) { for (SnakeFood f : food.values()) f.render(screen); } }
package com.example.deviceapi.vo; import javax.validation.constraints.NotBlank; public class GetUserGetRequest { @NotBlank private String userNo; public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo; } }
package micro.usuarios.publicos.services; import java.util.HashSet; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.stereotype.Service; import dao.auth.fingerprint.FingerPrintAuthenticationDao; import dao.auth.fingerprint.FingerPrintFmdIndiceDerechoDao; import dao.auth.fingerprint.FingerPrintFmdIndiceIzquierdoDao; import dao.auth.fingerprint.FingerPrintFmdMedioDerechoDao; import dao.auth.fingerprint.FingerPrintFmdMedioIzquierdoDao; import dao.auth.fingerprint.FingerPrintFmdPulgarDerechoDao; import dao.auth.fingerprint.FingerPrintFmdPulgarIzquierdoDao; import dao.auth.usuarios.publicos.UsuarioPublicoDao; import dto.main.Respuesta; import dto.usuarios.FiltroUsuarioPublicoDTO; import dto.usuarios.PatchUsuarioPublicoDTO; import excepciones.controladas.ErrorInternoControlado; import interfaces.interfaces.MainCrud; import micro.usuarios.publicos.interfaces.IUsuarioService; import model.auth.usuarios.fingerprint.FingerPrintAuthentication; import model.auth.usuarios.fingerprint.FingerPrintFmdIndiceDerecho; import model.auth.usuarios.fingerprint.FingerPrintFmdIndiceIzquierdo; import model.auth.usuarios.fingerprint.FingerPrintFmdMedioDerecho; import model.auth.usuarios.fingerprint.FingerPrintFmdMedioIzquierdo; import model.auth.usuarios.fingerprint.FingerPrintFmdPulgarDerecho; import model.auth.usuarios.fingerprint.FingerPrintFmdPulgarIzquierdo; import model.auth.usuarios.publicos.UsuarioPublico; import utils._config.language.Translator; @Service public class UsuarioService extends MainCrud<UsuarioPublico, Long> implements IUsuarioService { Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired UsuarioPublicoDao usuarioPublicoDao; @Autowired private BCryptPasswordEncoder bcrypt; @Autowired FingerPrintAuthenticationDao fingerPrintAuthenticationDao; @Autowired FingerPrintFmdIndiceDerechoDao fingerPrintFmdIndiceDerechoDao; @Autowired FingerPrintFmdIndiceIzquierdoDao fingerPrintFmdIndiceIzquierdoDao; @Autowired FingerPrintFmdMedioDerechoDao fingerPrintFmdMedioDerechoDao; @Autowired FingerPrintFmdMedioIzquierdoDao fingerPrintFmdMedioIzquierdoDao; @Autowired FingerPrintFmdPulgarDerechoDao fingerPrintFmdPulgarDerechoDao; @Autowired FingerPrintFmdPulgarIzquierdoDao fingerPrintFmdPulgarIzquierdoDao; @Override public Respuesta<Page<UsuarioPublico>> filtrar(Pageable pageable, FiltroUsuarioPublicoDTO filtroUsuarioPublicoDTO) { Page<UsuarioPublico> datos = usuarioPublicoDao.filtro(pageable, filtroUsuarioPublicoDTO); return new Respuesta<Page<UsuarioPublico>>(200, datos, Translator.toLocale("usuarios.publico.usuarioservice.filtrar")); } @Override public Respuesta<UsuarioPublico> obtenerPorToken(OAuth2Authentication auth) { UsuarioPublico usuarioPublico = usuarioPublicoDao.findByUsernameOrEmail(auth.getPrincipal().toString(), auth.getPrincipal().toString()); return new Respuesta<UsuarioPublico>(200, usuarioPublico, Translator.toLocale("usuarios.publico.usuarioservice.obtenerportoken")); } @Override public Respuesta<UsuarioPublico> crear(UsuarioPublico usuarioPublico) { UsuarioPublico usuario = usuarioPublicoDao.findByUsernameOrEmail(usuarioPublico.getUsername(), usuarioPublico.getCorreo()); if (usuario != null) { return ErrorInternoControlado.usuarioOCorreoDuplicado(usuarioPublico.getUsername()); } usuarioPublico.setPassword(bcrypt.encode(usuarioPublico.getPassword())); UsuarioPublico usuarioPublic = usuarioPublicoDao.saveAndFlush(usuarioPublico); return new Respuesta<UsuarioPublico>(200, usuarioPublic, Translator.toLocale("usuarios.publico.usuarioservice.crear")); } // PATCH @Override public Respuesta<UsuarioPublico> actualizar(PatchUsuarioPublicoDTO patchUsuarioPublicoDTO, OAuth2Authentication auth) { UsuarioPublico usuarioActual = usuarioPublicoDao.findByUsernameOrEmail(auth.getPrincipal().toString(), auth.getPrincipal().toString()); if (!patchUsuarioPublicoDTO.getPassword().equals(patchUsuarioPublicoDTO.getRepetirPassword())) { return ErrorInternoControlado.passwordsNoCoinciden(); } if (patchUsuarioPublicoDTO.getPassword().isEmpty()) { patchUsuarioPublicoDTO.setPassword(usuarioActual.getPassword()); } else { patchUsuarioPublicoDTO.setPassword(bcrypt.encode(patchUsuarioPublicoDTO.getPassword())); } BeanUtils.copyProperties(patchUsuarioPublicoDTO, usuarioActual); usuarioActual = usuarioPublicoDao.saveAndFlush(usuarioActual); return new Respuesta<UsuarioPublico>(200, usuarioActual, Translator.toLocale("usuarios.publico.usuarioservice.actualizar")); } @Override public Respuesta<UsuarioPublico> actualizar(Long id, UsuarioPublico usuarioPublico) { UsuarioPublico usuarioActual = usuarioPublicoDao.findById(id).get(); /* PASSWORD */ if (usuarioPublico.getPassword().isEmpty()) { usuarioPublico.setPassword(usuarioActual.getPassword()); } else { usuarioPublico.setPassword(bcrypt.encode(usuarioPublico.getPassword())); } updateFingerPrints(usuarioPublico, usuarioActual); UsuarioPublico usuarioPublic = usuarioPublicoDao.saveAndFlush(usuarioPublico); return new Respuesta<UsuarioPublico>(200, usuarioPublic, Translator.toLocale("usuarios.publico.usuarioservice.actualizar")); } @Override public Respuesta<Boolean> borrar(Long id) { usuarioPublicoDao.deleteById(id); return new Respuesta<Boolean>(200, true, Translator.toLocale("usuarios.publico.usuarioservice.borrar")); } @Override public Respuesta<Boolean> actualizarHuellas(FingerPrintAuthentication fingerPrintAuthentication) { UsuarioPublico usuarioActual = usuarioPublicoDao.findByUsername(fingerPrintAuthentication.getUsuario()); if (usuarioActual == null) { return new Respuesta<Boolean>(500, false, Translator.toLocale("usuarios.publico.usuarioservice.actualizarHuellas.usuarionoexiste")); } enrollFingerPrints(usuarioActual, fingerPrintAuthentication); usuarioPublicoDao.saveAndFlush(usuarioActual); return new Respuesta<Boolean>(200, true, Translator.toLocale("usuarios.publico.usuarioservice.actualizarHuellas")); } private void enrollFingerPrints(UsuarioPublico usuarioActual, FingerPrintAuthentication fingerPrintAuthentication) { if (usuarioActual.getFingerPrintAuthentication() != null) { fingerPrintAuthentication.setId(usuarioActual.getFingerPrintAuthentication().getId()); } for (FingerPrintFmdIndiceDerecho fingerPrintFmdIndiceDerecho : fingerPrintAuthentication .getFingerPrintFmdIndiceDerecho()) { fingerPrintFmdIndiceDerecho.setFingerPrintAuthentication(fingerPrintAuthentication); } for (FingerPrintFmdMedioDerecho fingerPrintFmdMedioDerecho : fingerPrintAuthentication .getFingerPrintFmdMedioDerecho()) { fingerPrintFmdMedioDerecho.setFingerPrintAuthentication(fingerPrintAuthentication); } for (FingerPrintFmdPulgarDerecho fingerPrintFmdPulgarDerecho : fingerPrintAuthentication .getFingerPrintFmdPulgarDerecho()) { fingerPrintFmdPulgarDerecho.setFingerPrintAuthentication(fingerPrintAuthentication); } for (FingerPrintFmdIndiceIzquierdo fingerPrintFmdIndiceIzquierdo : fingerPrintAuthentication .getFingerPrintFmdIndiceIzquierdo()) { fingerPrintFmdIndiceIzquierdo.setFingerPrintAuthentication(fingerPrintAuthentication); } for (FingerPrintFmdMedioIzquierdo fingerPrintFmdMedioIzquierdo : fingerPrintAuthentication .getFingerPrintFmdMedioIzquierdo()) { fingerPrintFmdMedioIzquierdo.setFingerPrintAuthentication(fingerPrintAuthentication); } for (FingerPrintFmdPulgarIzquierdo fingerPrintFmdPulgarIzquierdo : fingerPrintAuthentication .getFingerPrintFmdPulgarIzquierdo()) { fingerPrintFmdPulgarIzquierdo.setFingerPrintAuthentication(fingerPrintAuthentication); } usuarioActual.setFingerPrintAuthentication(fingerPrintAuthentication); } private void updateFingerPrints(UsuarioPublico usuario, UsuarioPublico usuarioActual) { if (usuario.getFingerPrintAuthentication() != null) { if (usuarioActual.getFingerPrintAuthentication() != null) { usuario.getFingerPrintAuthentication().setId(usuarioActual.getFingerPrintAuthentication().getId()); List<FingerPrintFmdIndiceDerecho> fingersPrintFmdIndiceDerecho = fingerPrintFmdIndiceDerechoDao .findByFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication().getId()); List<FingerPrintFmdIndiceIzquierdo> fingersPrintFmdIndiceIzquierdo = fingerPrintFmdIndiceIzquierdoDao .findByFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication().getId()); List<FingerPrintFmdMedioDerecho> fingersPrintFmdMedioDerecho = fingerPrintFmdMedioDerechoDao .findByFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication().getId()); List<FingerPrintFmdMedioIzquierdo> fingersPrintFmdMedioIzquierdo = fingerPrintFmdMedioIzquierdoDao .findByFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication().getId()); List<FingerPrintFmdPulgarDerecho> fingersPrintFmdPulgarDerecho = fingerPrintFmdPulgarDerechoDao .findByFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication().getId()); List<FingerPrintFmdPulgarIzquierdo> fingersPrintFmdPulgarIzquierdo = fingerPrintFmdPulgarIzquierdoDao .findByFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication().getId()); if (usuario.getFingerPrintAuthentication().getFingerPrintFmdIndiceDerecho().size() > 0) { fingerPrintFmdIndiceDerechoDao.deleteAll(fingersPrintFmdIndiceDerecho); } else { usuario.getFingerPrintAuthentication().setFingerPrintFmdIndiceDerecho( new HashSet<FingerPrintFmdIndiceDerecho>(fingersPrintFmdIndiceDerecho)); } if (usuario.getFingerPrintAuthentication().getFingerPrintFmdMedioDerecho().size() > 0) { fingerPrintFmdMedioDerechoDao.deleteAll(fingersPrintFmdMedioDerecho); } else { usuario.getFingerPrintAuthentication().setFingerPrintFmdMedioDerecho( new HashSet<FingerPrintFmdMedioDerecho>(fingersPrintFmdMedioDerecho)); } if (usuario.getFingerPrintAuthentication().getFingerPrintFmdPulgarDerecho().size() > 0) { fingerPrintFmdPulgarDerechoDao.deleteAll(fingersPrintFmdPulgarDerecho); } else { usuario.getFingerPrintAuthentication().setFingerPrintFmdPulgarDerecho( new HashSet<FingerPrintFmdPulgarDerecho>(fingersPrintFmdPulgarDerecho)); } if (usuario.getFingerPrintAuthentication().getFingerPrintFmdIndiceIzquierdo().size() > 0) { fingerPrintFmdIndiceIzquierdoDao.deleteAll(fingersPrintFmdIndiceIzquierdo); } else { usuario.getFingerPrintAuthentication().setFingerPrintFmdIndiceIzquierdo( new HashSet<FingerPrintFmdIndiceIzquierdo>(fingersPrintFmdIndiceIzquierdo)); } if (usuario.getFingerPrintAuthentication().getFingerPrintFmdMedioIzquierdo().size() > 0) { fingerPrintFmdMedioIzquierdoDao.deleteAll(fingersPrintFmdMedioIzquierdo); } else { usuario.getFingerPrintAuthentication().setFingerPrintFmdMedioIzquierdo( new HashSet<FingerPrintFmdMedioIzquierdo>(fingersPrintFmdMedioIzquierdo)); } if (usuario.getFingerPrintAuthentication().getFingerPrintFmdPulgarIzquierdo().size() > 0) { fingerPrintFmdPulgarIzquierdoDao.deleteAll(fingersPrintFmdPulgarIzquierdo); } else { usuario.getFingerPrintAuthentication().setFingerPrintFmdPulgarIzquierdo( new HashSet<FingerPrintFmdPulgarIzquierdo>(fingersPrintFmdPulgarIzquierdo)); } for (FingerPrintFmdIndiceDerecho fingerPrintFmdIndiceDerecho : usuario.getFingerPrintAuthentication() .getFingerPrintFmdIndiceDerecho()) { fingerPrintFmdIndiceDerecho .setFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication()); } for (FingerPrintFmdMedioDerecho fingerPrintFmdMedioDerecho : usuario.getFingerPrintAuthentication() .getFingerPrintFmdMedioDerecho()) { fingerPrintFmdMedioDerecho .setFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication()); } for (FingerPrintFmdPulgarDerecho fingerPrintFmdPulgarDerecho : usuario.getFingerPrintAuthentication() .getFingerPrintFmdPulgarDerecho()) { fingerPrintFmdPulgarDerecho .setFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication()); } for (FingerPrintFmdIndiceIzquierdo fingerPrintFmdIndiceIzquierdo : usuario .getFingerPrintAuthentication().getFingerPrintFmdIndiceIzquierdo()) { fingerPrintFmdIndiceIzquierdo .setFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication()); } for (FingerPrintFmdMedioIzquierdo fingerPrintFmdMedioIzquierdo : usuario.getFingerPrintAuthentication() .getFingerPrintFmdMedioIzquierdo()) { fingerPrintFmdMedioIzquierdo .setFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication()); } for (FingerPrintFmdPulgarIzquierdo fingerPrintFmdPulgarIzquierdo : usuario .getFingerPrintAuthentication().getFingerPrintFmdPulgarIzquierdo()) { fingerPrintFmdPulgarIzquierdo .setFingerPrintAuthentication(usuarioActual.getFingerPrintAuthentication()); } } else { for (FingerPrintFmdIndiceDerecho fingerPrintFmdIndiceDerecho : usuario.getFingerPrintAuthentication() .getFingerPrintFmdIndiceDerecho()) { fingerPrintFmdIndiceDerecho.setFingerPrintAuthentication(usuario.getFingerPrintAuthentication()); } for (FingerPrintFmdMedioDerecho fingerPrintFmdMedioDerecho : usuario.getFingerPrintAuthentication() .getFingerPrintFmdMedioDerecho()) { fingerPrintFmdMedioDerecho.setFingerPrintAuthentication(usuario.getFingerPrintAuthentication()); } for (FingerPrintFmdPulgarDerecho fingerPrintFmdPulgarDerecho : usuario.getFingerPrintAuthentication() .getFingerPrintFmdPulgarDerecho()) { fingerPrintFmdPulgarDerecho.setFingerPrintAuthentication(usuario.getFingerPrintAuthentication()); } for (FingerPrintFmdIndiceIzquierdo fingerPrintFmdIndiceIzquierdo : usuario .getFingerPrintAuthentication().getFingerPrintFmdIndiceIzquierdo()) { fingerPrintFmdIndiceIzquierdo.setFingerPrintAuthentication(usuario.getFingerPrintAuthentication()); } for (FingerPrintFmdMedioIzquierdo fingerPrintFmdMedioIzquierdo : usuario.getFingerPrintAuthentication() .getFingerPrintFmdMedioIzquierdo()) { fingerPrintFmdMedioIzquierdo.setFingerPrintAuthentication(usuario.getFingerPrintAuthentication()); } for (FingerPrintFmdPulgarIzquierdo fingerPrintFmdPulgarIzquierdo : usuario .getFingerPrintAuthentication().getFingerPrintFmdPulgarIzquierdo()) { fingerPrintFmdPulgarIzquierdo.setFingerPrintAuthentication(usuario.getFingerPrintAuthentication()); } } } } }
/* * 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 vasylts.blackjack.game; import java.util.List; import java.util.Set; import vasylts.blackjack.deck.IDeck; import vasylts.blackjack.deck.card.ICard; import vasylts.blackjack.game.end.GameFinishDealerBlackjack; import vasylts.blackjack.game.end.GameFinishDealerBusted; import vasylts.blackjack.game.end.GameFinishWorker; import vasylts.blackjack.game.end.IGameFinishWorker; import vasylts.blackjack.jaxb.EnumGameState; import vasylts.blackjack.logger.EnumLogAction; import vasylts.blackjack.logger.IActionLogger; import vasylts.blackjack.player.hand.DealerHand; import vasylts.blackjack.player.IPlayer; import vasylts.blackjack.user.IUser; /** * This class realize logic for blackjack game with only one user * <p> * @author VasylcTS */ public class SinglePlayerBlackjackGame implements IBlackjackGame { private final GamePlayerManager playerManager; private final IDeck gameDeck; private final boolean resetDeck; private IActionLogger logger; private EnumGameState state; private DealerHand dealerHand; /** * Creates a new instance of {@code SinglePlayerBlackjackGame} class with * specific {@code IDeck} * <p> * @param deck A card deck wich will be used for playing * this game * @param resetDeckAfterEachGame Parameter that stands for reset and shuffle * deck after each game. Should be * {@code true} in most cases. * <p> * @see vasylts.blackjack.deck.IDeck * @see vasylts.blackjack.deck.DeckBuilder */ public SinglePlayerBlackjackGame(IDeck deck, boolean resetDeckAfterEachGame) { gameDeck = deck; resetDeck = resetDeckAfterEachGame; playerManager = new GamePlayerManager(); state = EnumGameState.WAITING_BETS; } /** * We have only one player in this game :( * <p> * @return our single {@code IPlayer} */ private IPlayer getMySinglePlayer() { if (playerManager.getPlayers().iterator().hasNext()) { return playerManager.getPlayers().iterator().next(); } else { return null; } } /** * Starts game with one player */ private void startGame() { EnumLogAction logAction = EnumLogAction.GAME_START; getLogger().logGameAction(true, logAction, "Trying to start game."); try { checkState(EnumGameState.WAITING_BETS); IPlayer player = getMySinglePlayer(); if (player != null && player.getBet() > 0) { // let`s give cards to dealer dealerHand = new DealerHand(); setDealerHiddenCard(gameDeck.getNextCard()); getCardToDealer(gameDeck.getNextCard()); // and now let`s give cards to our player setState(EnumGameState.GAME_IN_PROCESS); getLogger().logGameAction(true, logAction, "Game started."); hitPlayer(0, player.getId()); hitPlayer(0, player.getId()); } } catch (Exception e) { getLogger().logGameAction(false, logAction, e.toString()); throw e; } } /** * 1. Play for a dealer * <p> * 2. Show dealer cards * <p> * 3. Select winner * <p> * 4. Give prize * <p> * p.s. this method does not reset game(so you can not start new one). For * reseting should call resetAll() * <p> * This method is called from: {@code public void standPlayer();} */ private void tryToEndGame() { EnumLogAction logAction = EnumLogAction.GAME_END; getLogger().logGameAction(true, logAction, "Trying to end game."); try { checkState(EnumGameState.GAME_IN_PROCESS); // p.s. we have only one player so we don`t need to check if all players used action "STAND" // Let`s end this game setState(EnumGameState.GAME_FINISHED); playForDealer(); IGameFinishWorker gameEndWorker; if (dealerHand.isBlackjack()) { getLogger().logGameAction(true, logAction, "Dealer has blackjack with hand: " + dealerHand.toString()); gameEndWorker = new GameFinishDealerBlackjack(); } else if (dealerHand.isBusted()) { getLogger().logGameAction(true, logAction, "Dealer busted with hand: " + dealerHand.toString()); gameEndWorker = new GameFinishDealerBusted(); } else { getLogger().logGameAction(true, logAction, "Dealer ended game with hand: " + dealerHand.toString()); gameEndWorker = new GameFinishWorker(); } gameEndWorker.givePrizesToWinners(dealerHand, playerManager.getPlayers(), getLogger()); getLogger().logGameAction(true, logAction, "All winners received prizes."); getLogger().logGameAction(true, logAction, "Game successfully ended."); } catch (Exception e) { getLogger().logGameAction(false, logAction, e.toString()); throw e; } } /** * Set dealers hidden card. This method should be called only once after new * game started * <p> * @param card new card */ private void setDealerHiddenCard(ICard card) { dealerHand.setHiddenCard(card); getLogger().logGameAction(true, EnumLogAction.GAME_DEALER, "Received hidden card: " + card.toString()); } /** * Gives new card to dealer hand. * <p> * @param card */ private void getCardToDealer(ICard card) { getLogger().logGameAction(true, EnumLogAction.GAME_DEALER, "Received card: " + card.toString()); dealerHand.addCard(card); } /** * Dealer will take cards until his score is less than 17 * <p> * This method is called from {@code tryToEndGame()} */ private void playForDealer() { checkState(EnumGameState.GAME_FINISHED); dealerHand.openHiddenCard(); while (dealerHand.getScore() < DealerHand.dealerPlayScore) { getCardToDealer(gameDeck.getNextCard()); } dealerHand.setStand(); } /** * Reset: 1. Dealer hand 2. Our single player hand(card|bet|flags) 3. Reset * Deck if such flag is true */ private void resetAll() { EnumLogAction logAction = EnumLogAction.GAME_RESET; getLogger().logGameAction(true, logAction, "Trying to reset game."); try { checkState(EnumGameState.GAME_FINISHED); if (getMySinglePlayer() != null) { // reset our single player hand(card|bet|flags) getMySinglePlayer().resetGame(); // reset dealer hand dealerHand = null; // reset deck if (resetDeck) { gameDeck.resetDeck(); gameDeck.shuffleDeck(); } setState(EnumGameState.WAITING_BETS); getLogger().logGameAction(true, logAction, "Game successfully reseted!"); } } catch (Exception e) { getLogger().logGameAction(false, logAction, e.toString()); throw e; } } private void checkState(EnumGameState needToBeState) throws IllegalStateException { if (this.getState() != needToBeState) { throw new IllegalStateException("You can not perform this action right now. Game must be in state: " + needToBeState.toString() + ". Now game in state: " + getState().toString()); } } private void checkStateUpperEqualsTo(EnumGameState needToBeStateOrUpper) throws IllegalStateException { if (this.getState().ordinal() < needToBeStateOrUpper.ordinal()) { throw new IllegalStateException("You can not perform this action right now. Game state must be >= " + needToBeStateOrUpper.toString() + ". Now game in state: " + getState().toString()); } } /** * @return the state */ @Override public EnumGameState getState() { return state; } /** * @param state the state to set */ private void setState(EnumGameState state) { if (this.state != state) { getLogger().logGameAction(true, EnumLogAction.GAME_STATE, "Changing game state from " + this.state.toString() + " to " + state.toString()); this.state = state; } } /** * * @param logger */ public void setLogger(IActionLogger logger) { if (logger != null) { this.logger = logger; } } /** * @return the logger */ public IActionLogger getLogger() { if (logger == null) { // Please call setLogger() before calling any other methods! throw new NullPointerException("Logger is not initialized!"); } return logger; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Access to IPlayerManager methods with checking and changing state of game //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- /** * Place a bet for a player. * <p> * @param userId in single player game does not using * @param playerId long playerId * @param bet Value of a bet. * <p> * @return false if it is impossible to place a bet for this player. */ @Override public boolean placeBet(long userId, long playerId, Double bet) { EnumLogAction action = EnumLogAction.PLAYER_BET; getLogger().logPlayerAction(true, playerId, action, "Trying to set a bet for player with value: " + bet); try { checkState(EnumGameState.WAITING_BETS); boolean isSetted = playerManager.placeBetUnauthorized(playerId, bet); if (isSetted) { getLogger().logPlayerAction(true, playerId, action, "Bet successfully setted!"); } else { getLogger().logPlayerAction(false, playerId, action, "Bet did not set! Perhaps there are no money in players wallet."); } return isSetted; } catch (Exception e) { getLogger().logPlayerAction(false, playerId, action, e.toString()); throw e; } } /** * Blackjack action: "Hit: Take another card from the dealer." Gives new * card to player from deck. * <p> * @param userId in single player game does not using * @param playerId Player id who will receive new card * <p> * @return Card from deck. */ @Override public ICard hitPlayer(long userId, long playerId) { EnumLogAction action = EnumLogAction.PLAYER_HIT; getLogger().logPlayerAction(true, playerId, action, "Trying to get a card for player."); try { checkState(EnumGameState.GAME_IN_PROCESS); if (isPlayerCanTakeCard(playerId)) { ICard card = gameDeck.getNextCard(); playerManager.giveCardUnauthorized(playerId, card); getLogger().logPlayerAction(true, playerId, action, "Player received card: " + card.toString()); if (playerManager.isPlayerBusted(playerId)) { standPlayer(userId, playerId); } // card already added to players hand // returning this card just for info return card; } else { getLogger().logPlayerAction(false, playerId, action, "Player can not take card now."); return null; } } catch (Exception e) { getLogger().logPlayerAction(false, playerId, action, e.toString()); throw e; } } /** * Blackjack action: "Stand: Take no more cards, also known as "stand pat", * "stick", or "stay"." Stops game for this player. Doing nothing if player * already used this action. * <p> * @param userId in single player game does not using * @param playerId Player id who wants to stop the game */ @Override public void standPlayer(long userId, long playerId) { EnumLogAction action = EnumLogAction.PLAYER_STAND; getLogger().logPlayerAction(true, playerId, action, "Trying to use 'STAND' to player."); if (state == EnumGameState.GAME_IN_PROCESS) { playerManager.standPlayerUnauthorized(playerId); getLogger().logPlayerAction(true, playerId, action, "Action 'STAND' used to player."); tryToEndGame(); } else { getLogger().logPlayerAction(false, playerId, action, "Can not use 'STAND' to player, game in wrong state."); } } /** * Sends message to game that this player is place his bet and ready to * start game. * <p> * @param playerId Player id in this game */ @Override public void readyPlayerToStart(long playerId) { EnumLogAction action = EnumLogAction.PLAYER_READY_START; try { checkState(EnumGameState.WAITING_BETS); playerManager.getPlayer(playerId).setReadyToStart(); getLogger().logPlayerAction(true, playerId, action, "Player setted as ready to start"); } catch (Exception e) { getLogger().logPlayerAction(false, playerId, action, e.toString()); throw e; } if (playerManager.isAllPlayerReadyToStart()) { startGame(); } } /** * Send message to game that this player received all needed info about last * game and ready to finish this game and start another one. * <p> * @param playerId */ @Override public void readyPlayerToEnd(long playerId) { EnumLogAction action = EnumLogAction.PLAYER_READY_END; try { checkState(EnumGameState.GAME_FINISHED); playerManager.getPlayer(playerId).setReadyToFinish(); getLogger().logPlayerAction(true, playerId, action, "Player setted as ready to end"); } catch (Exception e) { getLogger().logPlayerAction(false, playerId, action, e.toString()); throw e; } if (playerManager.isAllPlayerReadyToEnd()) { resetAll(); } } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Access to IPlayerManager methods //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- /** * Game will create new player and will add him to game. * <p> * @param user User who wants to play this game. * <p> * @return player`s id in game. * <p> * @throws IllegalStateException when game already have player */ @Override public long addUserToGame(IUser user) { if (user == null) { throw new NullPointerException("User can not be null"); } if (getMySinglePlayer() == null) { long playerId = playerManager.addUserToGame(user); logger.logGameAction(true, EnumLogAction.GAME_STATE, "Added player to game with id: " + playerId + ". User id: " + user.getId()); return playerId; } else { throw new IllegalStateException("This game already have player"); } } /** * This method will delete user`s player from this instance of * IBlackjackGame * <p> * @param userId in single player game does not using * <p> * @param playerId Player`s id in this game * <p> * @return {@code true} if player deleted from game */ @Override public boolean deletePlayerByUser(long userId, long playerId) { logger.logGameAction(true, EnumLogAction.GAME_STATE, "Delete player from game with id: " + playerId + ". User id: " + userId); return playerManager.deletePlayerUnauthorized(playerId); } /** * This method returns all players in this instance of IBlackjackGame * <p> * @return players that added to this game */ @Override public Set<Long> getPlayersInGame() { return playerManager.getPlayersInGame(); } /** * Returns players bet * <p> * @param playerId Player id in this game * <p> * @return Bet of selected player */ @Override public double getPlayerBet(long playerId) { return playerManager.getPlayerBet(playerId); } /** * This method returns {@code List} of player cards * <p> * @param playerId Player id in this game * <p> * @return {@code List} of player cards */ @Override public List<ICard> getPlayerCards(long playerId) { return playerManager.getPlayerCards(playerId); } /** * Check if player is busted(score is more than 21) and can not take cards * any more * <p> * @param playerId Player id in this game * <p> * @return {@code true} if player busted */ @Override public boolean isPlayerBusted(long playerId) { return playerManager.isPlayerBusted(playerId); } /** * This action returns dealer cards if all players used action: "Stand" * otherwise it will return only opened(not hidden) dealer cards. * <p> * @return dealer cards if all players used action: "Stand" otherwise it * will return only opened(not hidden) dealer cards. */ @Override public List<ICard> getDealerCards() { checkStateUpperEqualsTo(EnumGameState.GAME_IN_PROCESS); return dealerHand.getCardList(); } /** * This action returns dealer score only if all players used action: "Stand" * otherwise it return {@code null} * <p> * @return dealer score only if all players used action: "Stand" otherwise * it return {@code null} */ @Override public int getDealerScore() { checkStateUpperEqualsTo(EnumGameState.GAME_IN_PROCESS); return dealerHand.getScore(); } /** * This method checks if game started, player placed a bet, he is not busted * and some other conditions * <p> * @param playerId Player id in this game * <p> * @return {@code true} if player can take more cards */ @Override public boolean isPlayerCanTakeCard(long playerId) { if (state == EnumGameState.GAME_IN_PROCESS) { return playerManager.isPlayerCanTakeCard(playerId); } else { return false; } } /** * This method return player score. * <p> * @param playerId Player id * <p> * @return Player score */ @Override public int getPlayerScore(long playerId) { return playerManager.getPlayerScore(playerId); } }
package com.github.agmcc.slate.ast.mapper; import com.github.agmcc.slate.antlr.SlateParser.AssignmentStatementContext; import com.github.agmcc.slate.antlr.SlateParser.BinaryOperationContext; import com.github.agmcc.slate.antlr.SlateParser.BlockStatementContext; import com.github.agmcc.slate.antlr.SlateParser.BooleanLiteralContext; import com.github.agmcc.slate.antlr.SlateParser.CompilationUnitContext; import com.github.agmcc.slate.antlr.SlateParser.ConditionStatementContext; import com.github.agmcc.slate.antlr.SlateParser.DecimalLiteralContext; import com.github.agmcc.slate.antlr.SlateParser.ExpressionContext; import com.github.agmcc.slate.antlr.SlateParser.ExpressionStatementContext; import com.github.agmcc.slate.antlr.SlateParser.ForLoopStatementContext; import com.github.agmcc.slate.antlr.SlateParser.ForTraditionalContext; import com.github.agmcc.slate.antlr.SlateParser.IntLiteralContext; import com.github.agmcc.slate.antlr.SlateParser.MethodDeclarationContext; import com.github.agmcc.slate.antlr.SlateParser.MethodInvocationContext; import com.github.agmcc.slate.antlr.SlateParser.ParameterContext; import com.github.agmcc.slate.antlr.SlateParser.ParenExpressionContext; import com.github.agmcc.slate.antlr.SlateParser.PostDecrementContext; import com.github.agmcc.slate.antlr.SlateParser.PostIncrementContext; import com.github.agmcc.slate.antlr.SlateParser.PreDecrementContext; import com.github.agmcc.slate.antlr.SlateParser.PreIncrementContext; import com.github.agmcc.slate.antlr.SlateParser.PrintStatementContext; import com.github.agmcc.slate.antlr.SlateParser.ReturnStatementContext; import com.github.agmcc.slate.antlr.SlateParser.StatementContext; import com.github.agmcc.slate.antlr.SlateParser.StringLiteralContext; import com.github.agmcc.slate.antlr.SlateParser.TypeContext; import com.github.agmcc.slate.antlr.SlateParser.VarDeclarationStatementContext; import com.github.agmcc.slate.antlr.SlateParser.VarReferenceContext; import com.github.agmcc.slate.antlr.SlateParser.WhileLoopStatementContext; import com.github.agmcc.slate.ast.CompilationUnit; import com.github.agmcc.slate.ast.MethodDeclaration; import com.github.agmcc.slate.ast.Parameter; import com.github.agmcc.slate.ast.Position; import com.github.agmcc.slate.ast.expression.BooleanLit; import com.github.agmcc.slate.ast.expression.DecLit; import com.github.agmcc.slate.ast.expression.Expression; import com.github.agmcc.slate.ast.expression.IntLit; import com.github.agmcc.slate.ast.expression.MethodInvocation; import com.github.agmcc.slate.ast.expression.PostDecrement; import com.github.agmcc.slate.ast.expression.PostIncrement; import com.github.agmcc.slate.ast.expression.PreDecrement; import com.github.agmcc.slate.ast.expression.PreIncrement; import com.github.agmcc.slate.ast.expression.StringLit; import com.github.agmcc.slate.ast.expression.VarReference; import com.github.agmcc.slate.ast.expression.binary.AdditionExpression; import com.github.agmcc.slate.ast.expression.binary.BinaryExpression; import com.github.agmcc.slate.ast.expression.binary.DivisionExpression; import com.github.agmcc.slate.ast.expression.binary.MultiplicationExpression; import com.github.agmcc.slate.ast.expression.binary.SubtractionExpression; import com.github.agmcc.slate.ast.expression.binary.logic.AndExpression; import com.github.agmcc.slate.ast.expression.binary.logic.EqualExpression; import com.github.agmcc.slate.ast.expression.binary.logic.GreaterEqualExpression; import com.github.agmcc.slate.ast.expression.binary.logic.GreaterExpression; import com.github.agmcc.slate.ast.expression.binary.logic.LessEqualExpression; import com.github.agmcc.slate.ast.expression.binary.logic.LessExpression; import com.github.agmcc.slate.ast.expression.binary.logic.NotEqualExpression; import com.github.agmcc.slate.ast.expression.binary.logic.OrExpression; import com.github.agmcc.slate.ast.statement.Assignment; import com.github.agmcc.slate.ast.statement.Block; import com.github.agmcc.slate.ast.statement.Condition; import com.github.agmcc.slate.ast.statement.ExpressionStatement; import com.github.agmcc.slate.ast.statement.For; import com.github.agmcc.slate.ast.statement.ForTraditional; import com.github.agmcc.slate.ast.statement.Print; import com.github.agmcc.slate.ast.statement.Return; import com.github.agmcc.slate.ast.statement.Statement; import com.github.agmcc.slate.ast.statement.VarDeclaration; import com.github.agmcc.slate.ast.statement.While; import java.util.stream.Collectors; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; import org.objectweb.asm.Type; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class ParseTreeMapperImpl implements ParseTreeMapper<CompilationUnitContext, CompilationUnit> { private boolean considerPosition; @Override public CompilationUnit toAst(CompilationUnitContext ctx) { if (ctx == null) { return null; } return new CompilationUnit( ctx.methodDeclaration().stream().map(this::toAst).collect(Collectors.toList()), toPosition(ctx)); } private MethodDeclaration toAst(MethodDeclarationContext ctx) { return new MethodDeclaration( ctx.ID().getText(), ctx.parameter().stream().map(this::toAst).collect(Collectors.toList()), toAst(ctx.returnType), toAst(ctx.statement()), toPosition(ctx)); } private Type toAst(TypeContext ctx) { if (ctx == null) { return Type.VOID_TYPE; } final Type type; if (ctx.INT() != null) { type = Type.INT_TYPE; } else if (ctx.DEC() != null) { type = Type.DOUBLE_TYPE; } else if (ctx.STRING() != null) { type = Type.getObjectType(Type.getInternalName(String.class)); } else if (ctx.BOOL() != null) { type = Type.BOOLEAN_TYPE; } else { throw new UnsupportedOperationException(getErrorMsg(ctx)); } if (ctx.ARRAY() != null) { return Type.getType("[".concat(type.getDescriptor())); } return type; } private Parameter toAst(ParameterContext ctx) { return new Parameter(toAst(ctx.type()), ctx.ID().getText(), toPosition(ctx)); } private Statement toAst(StatementContext ctx) { if (ctx instanceof VarDeclarationStatementContext) { final var varDecAssignment = ((VarDeclarationStatementContext) ctx).varDeclaration().assignment(); return new VarDeclaration( varDecAssignment.ID().getText(), toAst(varDecAssignment.expression()), toPosition(ctx)); } else if (ctx instanceof AssignmentStatementContext) { var assignmentCtx = ((AssignmentStatementContext) ctx).assignment(); return new Assignment( assignmentCtx.ID().getText(), toAst(assignmentCtx.expression()), toPosition(ctx)); } else if (ctx instanceof PrintStatementContext) { return new Print(toAst(((PrintStatementContext) ctx).print().expression()), toPosition(ctx)); } else if (ctx instanceof BlockStatementContext) { final var statements = ((BlockStatementContext) ctx).block().statement(); return new Block( statements.stream().map(this::toAst).collect(Collectors.toList()), toPosition(ctx)); } else if (ctx instanceof ConditionStatementContext) { final var condition = ((ConditionStatementContext) ctx).condition(); return new Condition( toAst(condition.expression()), toAst(condition.trueStatement), condition.falseStatement != null ? toAst(condition.falseStatement) : null, toPosition(ctx)); } else if (ctx instanceof WhileLoopStatementContext) { final var whileLoop = ((WhileLoopStatementContext) ctx).whileLoop(); return new While(toAst(whileLoop.expression()), toAst(whileLoop.body), toPosition(ctx)); } else if (ctx instanceof ForLoopStatementContext) { return toAst((ForLoopStatementContext) ctx); } else if (ctx instanceof ReturnStatementContext) { final ExpressionContext value = ((ReturnStatementContext) ctx).ret().value; return new Return(value != null ? toAst(value) : null, toPosition(ctx)); } else if (ctx instanceof ExpressionStatementContext) { return new ExpressionStatement( toAst(((ExpressionStatementContext) ctx).expression()), toPosition(ctx)); } else { throw new UnsupportedOperationException(getErrorMsg(ctx)); } } private Expression toAst(ExpressionContext ctx) { if (ctx instanceof BinaryOperationContext) { return toAst((BinaryOperationContext) ctx); } else if (ctx instanceof IntLiteralContext) { return new IntLit(ctx.getText(), toPosition(ctx)); } else if (ctx instanceof DecimalLiteralContext) { return new DecLit(ctx.getText(), toPosition(ctx)); } else if (ctx instanceof StringLiteralContext) { final var text = ctx.getText(); return new StringLit(text.substring(1, text.length() - 1), toPosition(ctx)); } else if (ctx instanceof VarReferenceContext) { return new VarReference(ctx.getText(), toPosition(ctx)); } else if (ctx instanceof ParenExpressionContext) { return toAst(((ParenExpressionContext) ctx).expression()); } else if (ctx instanceof MethodInvocationContext) { final var methodInvocation = (MethodInvocationContext) ctx; return new MethodInvocation( methodInvocation.ID().getText(), methodInvocation.expression().stream().map(this::toAst).collect(Collectors.toList()), toPosition(ctx)); } else if (ctx instanceof BooleanLiteralContext) { return new BooleanLit(ctx.getText(), toPosition(ctx)); } else if (ctx instanceof PostIncrementContext) { return new PostIncrement(((PostIncrementContext) ctx).ID().getText(), toPosition(ctx)); } else if (ctx instanceof PreIncrementContext) { return new PreIncrement(((PreIncrementContext) ctx).ID().getText(), toPosition(ctx)); } else if (ctx instanceof PostDecrementContext) { return new PostDecrement(((PostDecrementContext) ctx).ID().getText(), toPosition(ctx)); } else if (ctx instanceof PreDecrementContext) { return new PreDecrement(((PreDecrementContext) ctx).ID().getText(), toPosition(ctx)); } else { throw new UnsupportedOperationException(getErrorMsg(ctx)); } } private BinaryExpression toAst(BinaryOperationContext ctx) { switch (ctx.operator.getText()) { case "+": return new AdditionExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); case "-": return new SubtractionExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); case "*": return new MultiplicationExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); case "/": return new DivisionExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); case ">": return new GreaterExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); case ">=": return new GreaterEqualExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); case "==": return new EqualExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); case "!=": return new NotEqualExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); case "<": return new LessExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); case "<=": return new LessEqualExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); case "&&": return new AndExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); case "||": return new OrExpression(toAst(ctx.left), toAst(ctx.right), toPosition(ctx)); default: throw new UnsupportedOperationException(getErrorMsg(ctx)); } } private For toAst(ForLoopStatementContext ctx) { final var forLoop = ctx.forLoop(); if (forLoop instanceof ForTraditionalContext) { final var forLoopTrad = (ForTraditionalContext) forLoop; return new ForTraditional( (VarDeclaration) toAst(forLoopTrad.declaration), toAst(forLoopTrad.check), toAst(forLoopTrad.after), toAst(forLoopTrad.body), toPosition(ctx)); } else { throw new UnsupportedOperationException(getErrorMsg(ctx)); } } private Position toPosition(ParserRuleContext ctx) { if (!considerPosition) { return null; } final var start = ctx.getStart(); final var stop = ctx.getStop(); final var stopLength = stop.getType() == Token.EOF ? 0 : stop.getText().length(); return Position.of( start.getLine(), start.getCharPositionInLine(), stop.getLine(), stop.getCharPositionInLine() + stopLength); } private String getErrorMsg(ParserRuleContext ctx) { return String.format("%s: %s", ctx.getClass().getCanonicalName(), ctx.getText()); } }
package com.pineapple.mobilecraft.tumcca.data; import com.google.gson.Gson; /** * Created by yihao on 15/5/26. */ public class Account { /** * 手机 */ public String mobile; /** * 权限 */ public String authority; /** * 邮箱 */ public String email; public static Account NULL = new Account(); public static Account createTestAccount(){ return null; } public static Account fromJSON(String str){ Gson gson = new Gson(); return gson.fromJson(str, Account.class); } }
package com.epam.strings.text.factory; import com.epam.strings.text.sorter.WordSorterByLength; import com.epam.strings.text.sorter.ParagraphSorter; import com.epam.strings.text.sorter.Sorter; import com.epam.strings.text.sorter.SorterType; import com.epam.strings.text.sorter.WordSorterByAmountSymbol; import org.testng.Assert; import org.testng.annotations.Test; public class SorterFactoryTest { private final SorterFactory factory = new SorterFactory(); @Test public void testCreateSorterShouldReturnParagraphSorterWhenTypePARAGRAPH() { Sorter actualSorter = factory.createSorter(SorterType.PARAGRAPH); Assert.assertEquals(actualSorter.getClass(), ParagraphSorter.class); } @Test public void testCreateSorterShouldReturnPWordSorterByAmountSymbolWhenTypeWordByAmountSymbolSpace() { Sorter actualSorter = factory.createSorter(SorterType.WORD_BY_AMOUNT_SYMBOL); Assert.assertEquals(actualSorter.getClass(), WordSorterByAmountSymbol.class); } @Test public void testCreateSorterShouldReturnPWordSorterByLengthWhenTypeWordByLength() { Sorter actualSorter = factory.createSorter(SorterType.WORD_BY_LENGTH); Assert.assertEquals(actualSorter.getClass(), WordSorterByLength.class); } @Test public void testCreateSorterBySymbolShouldReturnPWordSorterByAmountSymbolWhenTypeWordByAmountSymbolA() { Sorter actualSorter = factory.createSorter(SorterType.WORD_BY_AMOUNT_SYMBOL); Assert.assertEquals(actualSorter.getClass(), WordSorterByAmountSymbol.class); } }
package com.example.qiaolulu.qiaorecyclerview; /** * @author:qiaolulu * @date:2019/07/02 * @function:音乐类包含的信息 */ public class SongInfo { private String number; private String song; private String time; public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getSong() { return song; } public void setSong(String song) { this.song = song; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public SongInfo(String number,String song,String time){ this.number = number; this.song = song; this.time = time; } }
package com.template.data; import android.arch.lifecycle.LiveData; import com.template.data.model.api.TestEntity; import com.template.data.remote.DataSourceInterface; import com.template.data.remote.Resource; import com.template.di.Remote; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public class DataRepository implements DataSourceInterface { private final DataSourceInterface mRemoteDataSource; @Inject public DataRepository(@Remote DataSourceInterface remoteDataSource) { mRemoteDataSource = remoteDataSource; } @Override public LiveData<Resource<TestEntity>> getHome() { return mRemoteDataSource.getHome(); } }
package pkgGame; import static org.junit.jupiter.api.Assertions.*; import java.util.Arrays; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.lang.reflect.*; public class SudokuTest { @Test public void Sudoku_Test1() { try { Sudoku s1 = new Sudoku(9); } catch (Exception e) { fail("Test failed to build a Sudoku"); } } @Test public void Sudoku_Test2() { Assertions.assertThrows(Exception.class, () -> { Sudoku s1 = new Sudoku(10); }); } @Test public void getRegion_Test1() { int[][] puzzle = { { 1, 2, 3, 4 }, { 3, 4, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; int[] ExpectedRegion = { 3, 4, 1, 2 }; // // 1 2 3 4 // 3 4 1 2 // 2 1 4 3 // 4 3 2 1 // // region 0 = 1 2 3 4 // region 1 = 3 4 1 2 int[] region; try { Sudoku s1 = new Sudoku(puzzle); region = s1.getRegion(1); System.out.println(Arrays.toString(region)); assertTrue(Arrays.equals(ExpectedRegion, region)); } catch (Exception e) { fail("Test failed to build a Sudoku"); } } @Test public void getRegion_Test2() { int[][] puzzle = { { 1, 2, 3, 4 }, { 3, 4, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; int[] ExpectedRegion = { 2, 1, 4, 3 }; // // 1 2 3 4 // 3 4 1 2 // 2 1 4 3 // 4 3 2 1 // // region at 0,2 = 2 1 4 3 int[] region; try { Sudoku s1 = new Sudoku(puzzle); region = s1.getRegion(0,2); System.out.println(Arrays.toString(region)); assertTrue(Arrays.equals(ExpectedRegion, region)); } catch (Exception e) { fail("Test failed to build a Sudoku"); } } @Test public void Sudoku_test1() { int[][] puzzle = { { 5, 3, 4, 6, 7, 8, 9, 1, 2 }, { 6, 7, 2, 1, 9, 5, 3, 4, 8 }, { 1, 9, 8, 3, 4, 2, 5, 6, 7 }, { 8, 5, 9, 7, 6, 1, 4, 2, 3 }, { 4, 2, 6, 8, 5, 3, 7, 9, 1 }, { 7, 1, 3, 9, 2, 4, 8, 5, 6 }, { 9, 6, 1, 5, 3, 7, 2, 8, 4 }, { 2, 8, 7, 4, 1, 9, 6, 3, 5 }, { 3, 4, 5, 2, 8, 6, 1, 7, 9 } }; try { Sudoku s1 = new Sudoku(puzzle); assertTrue(s1.isSudoku()); } catch (Exception e) { fail("Test failed to build a Sudoku"); } } @Test public void Sudoku_test2() { int[][] puzzle = { { 5, 5, 5, 6, 7, 8, 9, 1, 2 }, { 6, 7, 2, 1, 9, 5, 3, 4, 8 }, { 1, 9, 8, 3, 4, 2, 5, 6, 7 }, { 8, 5, 9, 7, 6, 1, 4, 2, 3 }, { 4, 2, 6, 8, 5, 3, 7, 9, 1 }, { 7, 1, 3, 9, 2, 4, 8, 5, 6 }, { 9, 6, 1, 5, 3, 7, 2, 8, 4 }, { 2, 8, 7, 4, 1, 9, 6, 3, 5 }, { 3, 4, 5, 2, 8, 6, 1, 7, 9 } }; try { Sudoku s1 = new Sudoku(puzzle); assertFalse(s1.isSudoku()); } catch (Exception e) { fail("Test failed to build a Sudoku"); } } @Test public void Sudoku_test3() { int[][] puzzle = { { 5, 3, 4, 6, 7, 8, 9, 1, 2 }, { 5, 7, 2, 1, 9, 5, 3, 4, 8 }, { 5, 9, 8, 3, 4, 2, 5, 6, 7 }, { 8, 5, 9, 7, 6, 1, 4, 2, 3 }, { 4, 2, 6, 8, 5, 3, 7, 9, 1 }, { 7, 1, 3, 9, 2, 4, 8, 5, 6 }, { 9, 6, 1, 5, 3, 7, 2, 8, 4 }, { 2, 8, 7, 4, 1, 9, 6, 3, 5 }, { 3, 4, 5, 2, 8, 6, 1, 7, 9 } }; try { Sudoku s1 = new Sudoku(puzzle); assertFalse(s1.isSudoku()); } catch (Exception e) { fail("Test failed to build a Sudoku"); } } @Test public void Sudoku_test4() { int[][] puzzle = { { 55, 3, 4, 6, 7, 8, 9, 1, 2 }, { 6, 7, 2, 1, 9, 5, 3, 4, 8 }, { 1, 9, 8, 3, 4, 2, 5, 6, 7 }, { 8, 5, 9, 7, 6, 1, 4, 2, 3 }, { 4, 2, 6, 8, 5, 3, 7, 9, 1 }, { 7, 1, 3, 9, 2, 4, 8, 5, 6 }, { 9, 6, 1, 5, 3, 7, 2, 8, 4 }, { 2, 8, 7, 4, 1, 9, 6, 3, 5 }, { 3, 4, 5, 2, 8, 6, 1, 7, 9 } }; try { Sudoku s1 = new Sudoku(puzzle); assertFalse(s1.isSudoku()); } catch (Exception e) { fail("Test failed to build a Sudoku"); } } @Test public void PartialSudoku_Test1() { // This test will test a partial sudoku... a zero in [0,0]... everything else works // but the first element in the puzzle is zero int[][] puzzle = { { 0, 3, 4, 6, 7, 8, 9, 1, 2 }, { 6, 7, 2, 1, 9, 5, 3, 4, 8 }, { 1, 9, 8, 3, 4, 2, 5, 6, 7 }, { 8, 5, 9, 7, 6, 1, 4, 2, 3 }, { 4, 2, 6, 8, 5, 3, 7, 9, 1 }, { 7, 1, 3, 9, 2, 4, 8, 5, 6 }, { 9, 6, 1, 5, 3, 7, 2, 8, 4 }, { 2, 8, 7, 4, 1, 9, 6, 3, 5 }, { 3, 4, 5, 2, 8, 6, 1, 7, 9 } }; try { Sudoku s1 = new Sudoku(puzzle); assertTrue(s1.isPartialSudoku()); } catch (Exception e) { fail("Test failed to build a Sudoku"); } } @Test public void PartialSudoku_Test2() { // This test will test a partial sudoku... // Everything zero, but there's a duplciate value in the region (not row/column) int[][] puzzle = { { 1, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; try { Sudoku s1 = new Sudoku(puzzle); assertFalse(s1.isPartialSudoku()); } catch (Exception e) { fail("Test failed to build a Sudoku"); } } @Test public void PartialSudoku_Test3() { // This is a working solution, make sure it fails isPartiaSudoku() int[][] puzzle = { { 5, 3, 4, 6, 7, 8, 9, 1, 2 }, { 6, 7, 2, 1, 9, 5, 3, 4, 8 }, { 1, 9, 8, 3, 4, 2, 5, 6, 7 }, { 8, 5, 9, 7, 6, 1, 4, 2, 3 }, { 4, 2, 6, 8, 5, 3, 7, 9, 1 }, { 7, 1, 3, 9, 2, 4, 8, 5, 6 }, { 9, 6, 1, 5, 3, 7, 2, 8, 4 }, { 2, 8, 7, 4, 1, 9, 6, 3, 5 }, { 3, 4, 5, 2, 8, 6, 1, 7, 9 } }; try { Sudoku s1 = new Sudoku(puzzle); assertFalse(s1.isPartialSudoku()); } catch (Exception e) { fail("Test failed to build a Sudoku"); } } @Test public void TestRegionNbr() { Sudoku s1= null; int[][] puzzle = { { 5, 3, 4, 6, 7, 8, 9, 1, 2 }, { 6, 7, 2, 1, 9, 5, 3, 4, 8 }, { 1, 9, 8, 3, 4, 2, 5, 6, 7 }, { 8, 5, 9, 7, 6, 1, 4, 2, 3 }, { 4, 2, 6, 8, 5, 3, 7, 9, 1 }, { 7, 1, 3, 9, 2, 4, 8, 5, 6 }, { 9, 6, 1, 5, 3, 7, 2, 8, 4 }, { 2, 8, 7, 4, 1, 9, 6, 3, 5 }, { 3, 4, 5, 2, 8, 6, 1, 7, 9 } }; int [] Region5 = {4,2,3,7,9,1,8,5,6}; try { s1 = new Sudoku(puzzle); } catch (Exception e) { fail("Bad Sudoku"); } assertTrue(Arrays.equals(Region5, s1.getRegion(5))); } @Test public void testValidValue() { try { int[][] puzzle = { { 0, 2, 3, 4 }, { 3, 4, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); s1.printPuzzle(puzzle); assertEquals(true,s1.isValidValue(0, 0, 1)); } catch(Exception e) { fail("Bad Sudoku"); } } @Test public void testValidValue2() { try { int[][] puzzle = { { 1, 2, 3, 4 }, { 3, 4, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); assertEquals(false,s1.isValidValue(0, 0, 1)); } catch(Exception e) { fail("Bad Sudoku"); } } @Test public void testValidValue3() { try { int[][] puzzle = { { 1, 2, 3, 4 }, { 0, 4, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); assertEquals(true,s1.isValidValue(0,1,3)); } catch(Exception e) { fail("Bad Sudoku"); } } @Test public void testValidValue4() { try { int[][] puzzle = { { 1, 2, 0, 4 }, { 3, 4, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); assertEquals(false,s1.isValidValue(0,0,3)); } catch(Exception e) { fail("Bad Sudoku"); } } @Test public void testValidValue5() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); assertEquals(false,s1.isValidValue(0,0,2)); } catch(Exception e) { fail("Bad Sudoku"); } } @Test public void testgetRegionNbr() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); assertEquals(0,s1.getRegionNbr(0, 0)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testgetRegionNbr2() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); assertEquals(1,s1.getRegionNbr(0, 2)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testgetRegionNbr3() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); assertEquals(2,s1.getRegionNbr(2, 0)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testgetRegionNbr4() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); assertEquals(3,s1.getRegionNbr(2, 2)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testShuffleArray() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); s1.shuffleArray(s1.getRow(0)); assertNotSame(new int[] {1,0,0,4},s1.getRow(0)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testShuffleArray2() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); s1.shuffleArray(s1.getRow(1)); assertNotSame(new int[] {3,2,1,2},s1.getRow(1)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testShuffleArray3() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); s1.shuffleArray(s1.getRow(2)); assertNotSame(new int[] {2,1,4,3},s1.getRow(2)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testShuffleArray4() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); s1.shuffleArray(s1.getRow(3)); assertNotSame(new int[] {4,3,2,1},s1.getRow(3)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testShuffleRegion() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); Method method = Sudoku.class.getDeclaredMethod("ShuffleRegion", int.class); method.setAccessible(true); method.invoke(s1, 0); assertNotSame(new int[] {1,0,3,2},s1.getRegion(0)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testShuffleRegion2() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); Method method = Sudoku.class.getDeclaredMethod("ShuffleRegion", int.class); method.setAccessible(true); method.invoke(s1, 1); assertNotSame(new int[] {0,4,1,2},s1.getRegion(1)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testShuffleRegion3() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); Method method = Sudoku.class.getDeclaredMethod("ShuffleRegion", int.class); method.setAccessible(true); method.invoke(s1, 2); assertNotSame(new int[] {2,1,4,3},s1.getRegion(2)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testShuffleRegion4() { try { int[][] puzzle = { { 1, 0, 0, 4 }, { 3, 2, 1, 2 }, { 2, 1, 4, 3 }, { 4, 3, 2, 1 } }; Sudoku s1 = new Sudoku(puzzle); Method method = Sudoku.class.getDeclaredMethod("ShuffleRegion", int.class); method.setAccessible(true); method.invoke(s1, 3); assertNotSame(new int[] {4,3,2,1},s1.getRegion(3)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testSetRegion() { try { int[][] puzzle = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; Sudoku s1 = new Sudoku(puzzle); Method method = Sudoku.class.getDeclaredMethod("SetRegion", int.class); method.setAccessible(true); method.invoke(s1, 0); assertNotSame(new int[] {0,0,0,0},s1.getRegion(0)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testSetRegion2() { try { int[][] puzzle = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; Sudoku s1 = new Sudoku(puzzle); Method method = Sudoku.class.getDeclaredMethod("SetRegion", int.class); method.setAccessible(true); method.invoke(s1, 1); assertNotSame(new int[] {0,0,0,0},s1.getRegion(1)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testSetRegion3() { try { int[][] puzzle = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; Sudoku s1 = new Sudoku(puzzle); Method method = Sudoku.class.getDeclaredMethod("SetRegion", int.class); method.setAccessible(true); method.invoke(s1, 2); assertNotSame(new int[] {0,0,0,0},s1.getRegion(2)); } catch(Exception ex) { fail("Bad Sudoku"); } } @Test public void testSetRegion4() { try { int[][] puzzle = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; Sudoku s1 = new Sudoku(puzzle); Method method = Sudoku.class.getDeclaredMethod("SetRegion", int.class); method.setAccessible(true); method.invoke(s1, 3); assertNotSame(new int[] {0,0,0,0},s1.getRegion(3)); } catch(Exception ex) { fail("Bad Sudoku"); } } }
package day15_Scanner_Stringclass; import java.util.Scanner; public class task03 { public static void main(String[] args) { /* write a program that asks to enter first and last name at th end shoul didsplay the full name */ Scanner input = new Scanner(System.in); System.out.println("Enter your first name"); String name= input.next(); System.out.println("Enter your last name"); String lastname = input.next(); System.out.println("Your full name is: " + name + " "+ lastname); input.close();// we closed the scanner here to get rid of the warning, we can not use it later } }
package com.att.api.sms.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONObject; import com.att.api.controller.APIController; import com.att.api.sms.model.SMSReceiveMessage; import com.att.api.sms.model.SMSReceiveStatus; import com.att.api.sms.service.SMSFileUtil; public class LoadNotifications extends APIController { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONArray statuses = new JSONArray(); for (final SMSReceiveStatus status : SMSFileUtil.getStatuses()) { statuses.put(new JSONArray() .put(status.getMessageId()) .put(status.getAddress()) .put(status.getDeliveryStatus())); } JSONArray msgs = new JSONArray(); for (final SMSReceiveMessage msg : SMSFileUtil.getMsgs()) { msgs.put(new JSONArray() .put(msg.getMessageId()) .put(msg.getDateTime()) .put(msg.getSenderAddress()) .put(msg.getSenderAddress()) .put(msg.getDestinationAddress()) .put(msg.getMessage())); } JSONObject jresponse = new JSONObject() .put("messages", msgs) .put("deliveryStatus", statuses); response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.print(jresponse); writer.flush(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Ignore get requests return; } }
package com.infotecsjava.keyvalue.service; import java.io.IOException; import java.util.List; import org.springframework.stereotype.Service; import com.infotecsjava.keyvalue.model.KeyValueModel; /* * Интерфейс, описывающий сервис-хранилище */ @Service public interface KeyValueService { /* * Операция чтения (get) * @param key - ключ для хранилища * @return данные, хранящиеся по ключу или null, если данных с таким ключем не существует */ public String getValue(String key); /* * Два варианта операции записи (set) * Если по переданному ключу уже хранятся данные - заменяет их, а также сбрасывает ttl на значение по умолчанию * Иначе - создает новую запись * @param key - ключ для хранилища * @param value - данные для хранилища * @param ttl - продолжительность жизни записи (если не задано, используется дефолтное значение * ttl = 600000) * @return true, если данные успешно записаны, else - иначе */ public boolean setValue(String key, String value); public boolean setValue(String key, String value, long ttl); /* * Операция удаления (remove) * Стирает данные, хранящиеся по заданному ключу, а также сбрасывает ttl на значение по умолчанию * @param key - ключ для хранилища * @return данные, хранившиеся по заданному ключу, или null, если таких данных не существует */ public String remove(String key); /* * Операция сохранения текущего состояния (dump) * Сохраняет текущее состояние хранилища в файл dump.txt в корневую папку проекта в виде json-строк * При проблемах с обработкой файла или перевода объектов в json выбрасывает IOException * @return текущее состояние проекта в формате json */ public String dump() throws IOException; /* * Операция загрузки состояния хранилища (load) * Загружает текущее состояние хранилища из файла dump.txt, создаваемого * При проблемах с обработкой файла или json-объектов выбрасывает IOException */ public void load() throws IOException; /* * Операция получения состояния хранилища * @return список всех пар ключ-значение, сохраненных на данный момент */ public List<KeyValueModel> getAll(); /* * Метод для проверки времени до удаления записей в хранилище * Если время жизни какой-либо записи истекло - она удаляется из хранилища и выводится сообщение об этом в консоль * @param n - количество милисекунд, через которое записи перепроверяются */ public void checkTtls(int n); }
package quiz; import java.util.Scanner; public class Quiz28 { public static void main(String[] args) { /* *1. 가로, 세로를입력 받습니다 *2. 가로 길이, 세로길이의 사각형을 출력하면 됩니다 *3. 단, 윤곽만 나타나도록 처리합니다 *조건 : 첫행, 마지막 행에 출력, 첫열 마지막 열에 출력 */ Scanner scan = new Scanner(System.in); System.out.print("가로> "); int a = scan.nextInt(); System.out.print("세로> "); int b = scan.nextInt(); for (int i = 0; i < b; i++) { for (int j = 0; j < a; j++) { if (1<=i && i<b-1 && j>0 && j<(a-1)) { System.out.print(" "); }else System.out.print("*"); } System.out.println(); } } }
package sample; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import sample.loadWorkBase.LoadWorksBase; import sample.welcomeWindow.WelcomeController; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ //new LoadWorksBase().load(); FXMLLoader loader = new FXMLLoader(getClass().getResource("/welcomeWindow.fxml")); Parent root = loader.load(); primaryStage.setTitle("Estimates"); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.setMinHeight(480); primaryStage.setMinWidth(570); WelcomeController controller = loader.getController(); primaryStage.show(); controller.load(scene.getWindow()); } public static void main(String[] args) { Application.launch(args); } }
/* * 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 rcpl; import java.sql.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; /** * * @author lenovo */ public class AddCriminalAction extends org.apache.struts.action.Action { /* forward name="success" path="" */ private static String SUCCESS = "success"; /** * This is the action called from the Struts framework. * * @param mapping The ActionMapping used to select this instance. * @param form The optional ActionForm bean for this request. * @param request The HTTP Request we are processing. * @param response The HTTP Response we are processing. * @throws java.lang.Exception * @return */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AddCriminalBean acb=(AddCriminalBean)form; String cid=acb.getCid(); String name=acb.getName(); String gender=acb.getGender(); String height=acb.getHeight(); String weight=acb.getWeight(); String pid=acb.getPid(); String level=acb.getLevel(); String stat=acb.getStat(); Connection con=null; PreparedStatement pst=null; try{ HttpSession session=request.getSession(false); if(session.getAttribute("admin")!=null) { Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://localhost:3306/police","root","password"); pst=con.prepareStatement("insert into criminal values(?,?,?,?,?,?,?,?)"); pst.setString(1,cid); pst.setString(2,name); pst.setString(3,gender); pst.setString(4,height); pst.setString(5,weight); pst.setString(6,pid); pst.setString(7,level); pst.setString(8,stat); int status=0; if(cid.length()!=0 && name.length()!=0 && gender.length()!=0 && height.length()!=0 && weight.length()!=0 && pid.length()!=0 && level.length()!=0 && stat.length()!=0) { status=pst.executeUpdate(); } if(status>0) { request.setAttribute("id",""+cid); SUCCESS="pass"; } else { request.setAttribute("msg","incomplete"); SUCCESS="fail"; } } else { SUCCESS="fail"; } } catch(Exception e) { request.setAttribute("msg","notunique"); SUCCESS="uniquefail"; } return mapping.findForward(SUCCESS); } }
package bnorm.timer; /** * A simple {@link ITimeout} implementation. * * @author Brian Norman */ public class Timeout extends Timer implements ITimeout { /** * The timeout value in seconds. */ private double timeout; /** * Creates a new timer with the specified timeout in seconds. * * @param seconds how long until the timer times out. */ public Timeout(double seconds) { super(); this.timeout = seconds; } @Override public Timeout start() { super.start(); return this; } @Override public Timeout stop() { super.stop(); return this; } @Override public Timeout reset() { super.reset(); return this; } @Override public double getTimeout() { return timeout; } @Override public Timeout setTimeout(double seconds) { this.timeout = seconds; return this; } @Override public double getRemainingTime() { if (TimerState.STOPPED == getTimerState() || getTimeout() <= 0.0) { // If the timer is not running or the timeout is less than or equal to 0, there is no timeout return Double.POSITIVE_INFINITY; } else { return getTimeout() - getElapsedTime(); } } @Override public boolean hasTimedOut() { return getRemainingTime() <= 0; } }
package bm; import java.util.Map; import org.openqa.grid.internal.utils.DefaultCapabilityMatcher; public class browserMatcher extends DefaultCapabilityMatcher{ @Override public boolean matches(Map<String, Object> nodeCapability, Map<String, Object> requestedCapability) { System.out.println("*************************************"); return super.matches(nodeCapability, requestedCapability) && nodeCapability.get("browserName").toString().equalsIgnoreCase(requestedCapability.get("browserName").toString()); } }
package com.espendwise.manta.web.controllers; import com.espendwise.manta.model.data.BusEntityData; import com.espendwise.manta.model.view.ContactView; import com.espendwise.manta.model.view.SiteIdentPropertiesView; import com.espendwise.manta.model.view.SiteIdentView; import com.espendwise.manta.service.DatabaseUpdateException; import com.espendwise.manta.service.SiteService; import com.espendwise.manta.spi.Clean; import com.espendwise.manta.spi.SuccessMessage; import com.espendwise.manta.spi.AutoClean; import com.espendwise.manta.util.PropertyUtil; import com.espendwise.manta.util.alert.ArgumentedMessage; import com.espendwise.manta.util.binder.PropertyBinder; import com.espendwise.manta.util.parser.Parse; import com.espendwise.manta.util.validation.ValidationException; import com.espendwise.manta.web.forms.SiteForm; import com.espendwise.manta.web.resolver.DatabaseWebUpdateExceptionResolver; import com.espendwise.manta.web.resolver.SiteWebUpdateExceptionResolver; import com.espendwise.manta.web.util.*; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.WebRequest; import net.glxn.qrgen.*; import net.glxn.qrgen.image.*; import java.util.List; @Controller @RequestMapping(UrlPathKey.SITE.IDENTIFICATION) @AutoClean(SessionKey.SITE_USER_FILTER_RESULT) public class SiteController extends BaseController { private static final Logger logger = Logger.getLogger(SiteController.class); private SiteService siteService; @Autowired public SiteController(SiteService siteService) { this.siteService = siteService; } public String handleValidationException(ValidationException ex, WebRequest request) { WebErrors webErrors = new WebErrors(request); webErrors.putErrors(ex, new SiteWebUpdateExceptionResolver()); return "site/edit"; } public String handleDatabaseUpdateException(DatabaseUpdateException ex, WebRequest request) { WebErrors webErrors = new WebErrors(request); webErrors.putErrors(ex, new DatabaseWebUpdateExceptionResolver()); return "site/edit"; } @SuccessMessage @Clean(SessionKey.SITE_HEADER) @RequestMapping(value = "", method = RequestMethod.POST) public String save(WebRequest request, @ModelAttribute(SessionKey.SITE) SiteForm siteForm, Model model) throws Exception { logger.info("save()=> BEGIN, siteForm: "+siteForm); WebErrors webErrors = new WebErrors(request); List<? extends ArgumentedMessage> validationErrors = WebAction.validate(siteForm); if (!validationErrors.isEmpty()) { webErrors.putErrors(validationErrors); model.addAttribute(SessionKey.SITE, siteForm); return "site/edit"; } SiteIdentView siteView = new SiteIdentView(); if (!siteForm.getIsNew()) { siteView = siteService.findSiteToEdit(getStoreId(), siteForm.getSiteId() ); } siteView.setAccountId(Parse.parseLong(siteForm.getAccountId())); siteView.setAccountName(siteForm.getAccountName()); siteView.setBusEntityData(WebFormUtil.createBusEntityData(getAppLocale(), siteView.getBusEntityData(), siteForm)); siteView.setProperties(WebFormUtil.createSiteIdentProperties(siteView.getProperties(), siteForm)); siteView.setContact(WebFormUtil.createContact(siteView.getContact(), siteForm)); try { siteView = siteService.saveSiteIdent( getStoreId(), getUserId(), siteView, siteForm.isClonedWithAssoc() ? (Long) parseNumber(siteForm.getCloneId()) : null ); } catch (ValidationException e) { return handleValidationException(e, request); } catch (DatabaseUpdateException e) { return handleDatabaseUpdateException(e, request); } logger.info("redirect(()=> redirect to: " + siteView.getBusEntityData().getBusEntityId()); logger.info("save()=> END."); return redirect(String.valueOf(siteView.getBusEntityData().getBusEntityId())); } @Clean(SessionKey.SITE_HEADER) @RequestMapping(value = SiteForm.ACTION.CLONE, method = RequestMethod.POST) public String clone(@ModelAttribute(SessionKey.SITE) SiteForm form, Model model) throws Exception { logger.info("clone()=> BEGIN"); clone(form, model, SiteForm.ACTION.CLONE); logger.info("clone()=> END."); return "site/edit"; } private void clone(SiteForm form, Model model, String cloneCode) { String title = AppI18nUtil.getMessage("admin.global.text.cloned", new String[]{form.getSiteName()}); form.setCloneId(String.valueOf(form.getSiteId())); form.setSiteId(null); form.setSiteName(title); form.setLocationBudgetRefNum(null); form.setLocationDistrRefNum(null); form.setCloneCode(cloneCode); model.addAttribute(SessionKey.SITE, form); } @Clean(SessionKey.SITE_HEADER) @RequestMapping(value = SiteForm.ACTION.CLONE_WITH_ASSOC, method = RequestMethod.POST) public String cloneWithAssoc(@ModelAttribute(SessionKey.SITE) SiteForm form, Model model) throws Exception { logger.info("cloneWithAssoc()=> BEGIN"); clone(form, model, SiteForm.ACTION.CLONE_WITH_ASSOC); logger.info("cloneWithAssoc()=> END."); return "site/edit"; } @SuccessMessage @Clean(SessionKey.SITE_HEADER) @RequestMapping(value = SiteForm.ACTION.DELETE, method = RequestMethod.POST) public String delete(WebRequest request, @ModelAttribute(SessionKey.SITE) SiteForm siteForm) throws Exception { logger.info("delete()=> BEGIN, siteForm: " + siteForm); if (!siteForm.getIsNew()) { try { siteService.deleteSite(getStoreId(), siteForm.getSiteId()); } catch (DatabaseUpdateException e) { return handleDatabaseUpdateException(e, request); } WebFormUtil.removeObjectFromFilterResult( request, SessionKey.SITE_FILTER_RESULT, siteForm.getSiteId() ); logger.info("delete()=> END. redirect to filter"); return redirect("../"); } logger.info("delete()=> END."); return "emailTemplate/edit"; } @Clean(SessionKey.SITE_HEADER) @RequestMapping(value = SiteForm.ACTION.CREATE) public String create(@ModelAttribute(SessionKey.SITE) SiteForm form, Model model) throws Exception { logger.info("create()=> BEGIN"); form = new SiteForm(); form.initialize(); model.addAttribute(SessionKey.SITE, form); logger.info("create()=> END."); return "site/edit"; } @RequestMapping(value = "", method = RequestMethod.GET) public String show(@ModelAttribute(SessionKey.SITE) SiteForm form, @PathVariable(IdPathKey.LOCATION_ID) Long locationId, Model model) { logger.info("show()=> BEGIN"); SiteIdentView site = siteService.findSiteToEdit(getStoreId(), locationId ); logger.info("show()=> site: "+site); if (site != null) { BusEntityData entity = site.getBusEntityData(); ContactView contact = site.getContact(); SiteIdentPropertiesView properties = PropertyBinder.bindSiteIdentProperties(new SiteIdentPropertiesView(), entity.getBusEntityId(), site.getProperties() ); form.setSiteId(site.getBusEntityData().getBusEntityId()); form.setSiteName(site.getBusEntityData().getShortDesc()); form.setAccountId(String.valueOf(site.getAccountId())); form.setAccountName(site.getAccountName()); form.setStatus(site.getBusEntityData().getBusEntityStatusCd()); form.setEffDate(formatDate(getAppLocale(), site.getBusEntityData().getEffDate())); form.setExpDate(formatDate(getAppLocale(), site.getBusEntityData().getExpDate())); form.setLocationBudgetRefNum(PropertyUtil.toValueNN(properties.getSiteReferenceNumber())); form.setLocationDistrRefNum(PropertyUtil.toValueNN(properties.getDistrSiteRefNumber())); form.setProductBundle(PropertyUtil.toValueNN(properties.getProductBundle())); form.setTargetFicilityRank(PropertyUtil.toValueNN(properties.getTargetFicilityRank())); form.setLocationLineLevelCode(PropertyUtil.toValueNN(properties.getLocationLineLevelCode())); form.setLocationComments(PropertyUtil.toValueNN(properties.getLocationComments())); form.setLocationShipMsg(PropertyUtil.toValueNN(properties.getLocationShipMsg())); form.setContact(WebFormUtil.createContactForm(contact)); form.setOptions(WebFormUtil.createSiteOptions(properties)); form.setCorporateSchedule(WebFormUtil.createDeliveryScheduleForm(getAppLocale(), site.getCorporateScheduleCorporate())); } model.addAttribute(SessionKey.SITE, form); logger.info("show()=> END."); return "site/edit"; } @ModelAttribute(SessionKey.SITE) public SiteForm initModel() { SiteForm form = new SiteForm(); form.initialize(); return form; } @ResponseBody @RequestMapping(value = SiteForm.ACTION.GET_QRCODE) public byte[] getQRCode( @PathVariable(IdPathKey.LOCATION_ID) Long locationId, @RequestParam("desc") String siteName) throws Exception { logger.info("getQRCode()=> BEGIN storeId = " + getStoreId() + ", locationId = " + locationId+ ", siteName=" + siteName); byte[] stream = ((QRCode.from("https://LO/" + getStoreId() +"/"+ locationId + "/" + siteName).to(ImageType.GIF).withSize(175, 175).stream()).toByteArray() ); logger.info("getQRCode()=> END. stream.length = " + (stream!= null ? stream.length : 0)); return stream; } }
package com.outsideintdd.katas.scoreboard; public class ScorePrinter { private static final String DELIMITER = ":"; private Console console; public ScorePrinter(Console console) { this.console = console; } public void print(int teamAScore, int teamBScore) { String aScore = String.format("%03d", teamAScore); String bScore = String.format("%03d", teamBScore); console.printLine(aScore + DELIMITER + bScore); } }
package backjun.silver; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Main_1181_단어정렬 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); String[] dataSet = new String[N]; for (int i = 0; i < N; i++) { dataSet[i] = sc.next(); } Arrays.sort(dataSet); Arrays.sort(dataSet, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.length() - o2.length(); } }); System.out.println(dataSet[0]); for (int i = 1; i < dataSet.length; i++) { if (dataSet[i - 1].equals(dataSet[i])) { continue; } System.out.println(dataSet[i]); } } }
package com.ehootu.flow.service.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ehootu.flow.dao.BlockingEventDao; import com.ehootu.flow.model.BlockingEventEntity; import com.ehootu.flow.service.BlockingEventService; @Service("blockingEventService") public class BlockingEventServiceImpl implements BlockingEventService { @Autowired private BlockingEventDao blockingEventDao; @Override public BlockingEventEntity queryObject(String id){ return blockingEventDao.queryObject(id); } @Override public List<BlockingEventEntity> queryList(Map<String, Object> map){ return blockingEventDao.queryList(map); } @Override public int queryTotal(Map<String, Object> map){ return blockingEventDao.queryTotal(map); } @Override public void save(BlockingEventEntity blockingEvent, String pageName) { blockingEventDao.saveAndGetId(blockingEvent); } @Override public void update(BlockingEventEntity blockingEvent){ blockingEventDao.update(blockingEvent); } @Override public void delete(String id){ blockingEventDao.delete(id); } @Override public void deleteBatch(Integer[] ids){ blockingEventDao.deleteBatch(ids); } }
package com.gtfs.bean; // Generated 30 Aug, 2014 4:24:58 PM by Hibernate Tools 3.4.0.CR1 import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; /** * UserLoginDtls generated by hbm2java */ @Entity @Table(name = "USER_LOGIN_DTLS") public class UserLoginDtls implements java.io.Serializable { private Long id; private Long userid; private Date loginTime; private Long branchId; public UserLoginDtls() { } public UserLoginDtls(Long id, Long userid, Date loginTime) { this.id = id; this.userid = userid; this.loginTime = loginTime; } public UserLoginDtls(Long id, Long userid, Date loginTime, Long branchId) { this.id = id; this.userid = userid; this.loginTime = loginTime; this.branchId = branchId; } @Id @SequenceGenerator(name="USER_LOGIN_DTLS_SEQ",sequenceName="USER_LOGIN_DTLS_SEQ") @GeneratedValue(generator="USER_LOGIN_DTLS_SEQ",strategy=GenerationType.AUTO) @Column(name = "ID", unique = true, nullable = false, precision = 22, scale = 0) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column(name = "USERID", nullable = false, precision = 22, scale = 0) public Long getUserid() { return this.userid; } public void setUserid(Long userid) { this.userid = userid; } @Column(name = "LOGIN_TIME", nullable = false) public Date getLoginTime() { return this.loginTime; } public void setLoginTime(Date loginTime) { this.loginTime = loginTime; } @Column(name = "BRANCH_ID", precision = 22, scale = 0) public Long getBranchId() { return this.branchId; } public void setBranchId(Long branchId) { this.branchId = branchId; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.05.19 at 03:23:59 PM IST // package www.chaayos.com.chaimonkbluetoothapp.domain.model.new_model; import java.io.Serializable; import java.math.BigDecimal; public class IngredientVariantDetail implements Serializable { /** * */ private static final long serialVersionUID = -2198505699784866775L; private String _id; private Long version; /** * Added to avoid a runtime error whereby the detachAll property is checked * for existence but not actually used. */ private String detachAll; protected int productId; protected String alias; protected UnitOfMeasure uom; protected BigDecimal quantity; protected boolean defaultSetting; protected String status = "ACTIVE"; protected boolean captured = true; public String get_id() { return _id; } public void set_id(String _id) { this._id = _id; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public String getDetachAll() { return detachAll; } public void setDetachAll(String detachAll) { this.detachAll = detachAll; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public UnitOfMeasure getUom() { return uom; } public void setUom(UnitOfMeasure uom) { this.uom = uom; } /** * Gets the value of the alias property. * * @return possible object is {@link String } * */ public String getAlias() { return alias; } /** * Sets the value of the alias property. * * @param value * allowed object is {@link String } * */ public void setAlias(String value) { this.alias = value; } /** * Gets the value of the quantity property. * * @return possible object is {@link String } * */ public BigDecimal getQuantity() { return quantity; } /** * Sets the value of the quantity property. * * @param value * allowed object is {@link String } * */ public void setQuantity(BigDecimal value) { this.quantity = value; } /** * Gets the value of the default property. * */ public boolean isDefaultSetting() { return defaultSetting; } /** * Sets the value of the default property. * */ public void setDefaultSetting(boolean value) { this.defaultSetting = value; } /** * Gets the value of the status property. * * @return possible object is {@link String } * */ public String getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is {@link String } * */ public void setStatus(String value) { this.status = value; } /** * @return the captured */ public boolean isCaptured() { return captured; } /** * @param captured * the captured to set */ public void setCaptured(boolean captured) { this.captured = captured; } }
package runner; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features="Featurefile/Expractice.feature", glue="stepDefinition",monochrome=true, format={"html:report/webReport","json:report/jsonwebReport.json"}) public class Expracticrunner { }
package com.zhowin.miyou.recommend.model; /** * 礼物列表 */ public class GiftList { /** * giftId : 1 * giftName : 玫瑰花 * giftPictureKey : http://qfah2px93.hn-bkt.clouddn.com/image.gift.xh.png * price : 66 * bidPrice : 64 * sort : 2 * enable : 1 * createTime : 1600153082000 */ private int giftId; private String giftName; private String giftPictureKey; private int price; private int bidPrice; private int sort; private int enable; private long createTime; public int getGiftId() { return giftId; } public void setGiftId(int giftId) { this.giftId = giftId; } public String getGiftName() { return giftName; } public void setGiftName(String giftName) { this.giftName = giftName; } public String getGiftPictureKey() { return giftPictureKey; } public void setGiftPictureKey(String giftPictureKey) { this.giftPictureKey = giftPictureKey; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getBidPrice() { return bidPrice; } public void setBidPrice(int bidPrice) { this.bidPrice = bidPrice; } public int getSort() { return sort; } public void setSort(int sort) { this.sort = sort; } public int getEnable() { return enable; } public void setEnable(int enable) { this.enable = enable; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } }
package com.mideas.rpg.v2.hud.social.who; import static com.mideas.rpg.v2.hud.social.SocialFrame.X_SOCIAL_FRAME; import static com.mideas.rpg.v2.hud.social.SocialFrame.Y_SOCIAL_FRAME; import java.util.ArrayList; import org.lwjgl.input.Mouse; import com.mideas.rpg.v2.FontManager; import com.mideas.rpg.v2.Mideas; import com.mideas.rpg.v2.chat.ChatFrame; import com.mideas.rpg.v2.command.CommandFriend; import com.mideas.rpg.v2.command.CommandIgnore; import com.mideas.rpg.v2.command.CommandParty; import com.mideas.rpg.v2.command.CommandWho; import com.mideas.rpg.v2.game.race.Race; import com.mideas.rpg.v2.game.social.WhoUnit; import com.mideas.rpg.v2.game.unit.ClassType; import com.mideas.rpg.v2.render.Draw; import com.mideas.rpg.v2.render.Sprites; import com.mideas.rpg.v2.render.TTF; import com.mideas.rpg.v2.utils.Button; import com.mideas.rpg.v2.utils.ButtonMenuSort; import com.mideas.rpg.v2.utils.Color; import com.mideas.rpg.v2.utils.DropDownMenu; import com.mideas.rpg.v2.utils.Input; import com.mideas.rpg.v2.utils.ScrollBar; import com.mideas.rpg.v2.utils.TextMenu; import com.mideas.rpg.v2.utils.TooltipMenu; public class WhoFrame { private static boolean shouldUpdateSize; private final static int MAXIMUM_UNIT_DISPLAYED = 17; private static int hoveredUnit = -1; static int selectedUnit = -1; private static int unitDown = -1; private static String numberPeopleFound = "0 player found"; private static int peopleFoundWidth = FontManager.get("FRIZQT", 12).getWidth(numberPeopleFound); private static boolean updateString = true; static WhoSort sorted = WhoSort.NAME_ASCENDING; static WhoDropDownDisplay dropDownDisplay = WhoDropDownDisplay.AREA; final static ArrayList<WhoUnit> whoList = new ArrayList<WhoUnit>(); final static TooltipMenu tooltipMenu = new TooltipMenu(0, 0, 0) { @Override public void onShow() { dropDownMenu.setActive(false); } }; final static Input input = new Input(FontManager.get("FRIZQT", 13), 255, false, false) { @Override public boolean keyEvent(char c) { if(c == Input.ENTER_CHAR_VALUE) { CommandWho.write(input.getText()); return true; } if(c == Input.ESCAPE_CHAR_VALUE) { this.setIsActive(false); return true; } return false; } }; private final static TextMenu whisperMenu = new TextMenu(0, 0, 0, "Whisper", 12, 1, 0) { @Override public void eventButtonClick() { ChatFrame.setWhisper(whoList.get(selectedUnit).getName()); ChatFrame.setChatActive(true); tooltipMenu.setActive(false); } }; private final static TextMenu inviteMenu = new TextMenu(0, 0, 0, "Invite", 12, 1, 0) { @Override public void eventButtonClick() { CommandParty.invitePlayer(whoList.get(selectedUnit).getName()); tooltipMenu.setActive(false); } }; private final static TextMenu targetMenu = new TextMenu(0, 0, 0, "Target", 12, 1, 0) { @Override public void eventButtonClick() { tooltipMenu.setActive(false); } }; private final static TextMenu ignoreMenu = new TextMenu(0, 0, 0, "Ignore", 12, 1, 0) { @Override public void eventButtonClick() { CommandIgnore.addIgnore(whoList.get(selectedUnit).getName()); tooltipMenu.setActive(false); } }; private final static TextMenu cancelMenu = new TextMenu(0, 0, 0, "Cancel", 12, 1, 0) { @Override public void eventButtonClick() { tooltipMenu.setActive(false); } }; final static DropDownMenu dropDownMenu = new DropDownMenu(X_SOCIAL_FRAME+114*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+74*Mideas.getDisplayYFactor(), 115*Mideas.getDisplayXFactor(), X_SOCIAL_FRAME+105*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+98*Mideas.getDisplayYFactor(), 100*Mideas.getDisplayXFactor(), 13, .6f, 15, true) { @Override public void menuEventButtonClick() { if(this.selectedMenuValue == 0) { dropDownDisplay = WhoDropDownDisplay.AREA; } else if(this.selectedMenuValue == 1) { dropDownDisplay = WhoDropDownDisplay.GUILD; } else if(this.selectedMenuValue == 2) { dropDownDisplay = WhoDropDownDisplay.RACE; } } @Override public void barEventButtonClick() { if(dropDownDisplay == WhoDropDownDisplay.AREA) { if(sorted == WhoSort.AREA_ASCENDING) { sorted = WhoSort.AREA_DESCENDING; } else { sorted = WhoSort.AREA_ASCENDING; } } else if(dropDownDisplay == WhoDropDownDisplay.GUILD) { if(sorted == WhoSort.GUILD_ASCENDING) { sortByGuildDescending(); sorted = WhoSort.GUILD_DESCENDING; } else { sortByGuildAscending(); sorted = WhoSort.GUILD_ASCENDING; } } else if(dropDownDisplay == WhoDropDownDisplay.RACE) { if(sorted == WhoSort.RACE_ASCENDING) { sortByRaceDescending(); sorted = WhoSort.RACE_DESCENDING; } else { sortByRaceAscending(); sorted = WhoSort.RACE_ASCENDING; } } } }; private final static TextMenu sortByGuild = new TextMenu(0, 0, 0, "Guild", 12, 1); private final static TextMenu sortByArea = new TextMenu(0, 0, 0, "Area", 12, 1); private final static TextMenu sortByRace = new TextMenu(0, 0, 0, "Race", 12, 1); private final static Button updateButton = new Button(X_SOCIAL_FRAME+17*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+437*Mideas.getDisplayYFactor(), 100, 25, "Actualise", 12, 1) { @Override public void onLeftClickUp() { CommandWho.write(input.getText()); } }; private final static Button addFriendButton = new Button(X_SOCIAL_FRAME+119*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+437*Mideas.getDisplayYFactor(), 132, 25, "Add Friend", 12, 1) { @Override public void onLeftClickUp() { if(selectedUnit != -1) CommandFriend.addFriend(whoList.get(selectedUnit).getName()); } @Override public boolean activateCondition() { return selectedUnit != -1; } }; private final static Button inviteButton = new Button(X_SOCIAL_FRAME+253*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+437*Mideas.getDisplayYFactor(), 132, 25, "Inv. Party", 12, 1) { @Override public void onLeftClickUp() { if(selectedUnit != -1) CommandParty.invitePlayer(whoList.get(selectedUnit).getName()); } @Override public boolean activateCondition() { return selectedUnit != -1 && Mideas.joueur1().canInvitePlayerInParty(whoList.get(selectedUnit).getId()); } }; private final static ButtonMenuSort sortByName = new ButtonMenuSort(X_SOCIAL_FRAME+19*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+74*Mideas.getDisplayYFactor(), 95*Mideas.getDisplayXFactor(), "Name", 12) { @Override public void eventButtonClick() { if(sorted == WhoSort.NAME_ASCENDING) { sortByNameDescending(); sorted = WhoSort.NAME_DESCENDING; } else { sortByNameAscending(); sorted = WhoSort.NAME_ASCENDING; } } }; private final static ButtonMenuSort dropDownBackground = new ButtonMenuSort(X_SOCIAL_FRAME+112*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+74*Mideas.getDisplayYFactor(), 125*Mideas.getDisplayXFactor(), "", 12); private final static ButtonMenuSort sortByLevel = new ButtonMenuSort(X_SOCIAL_FRAME+234*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+74*Mideas.getDisplayYFactor(), 40*Mideas.getDisplayXFactor(), "Lvl.", 12) { @Override public void eventButtonClick() { if(sorted == WhoSort.LEVEL_ASCENDING) { sortByLevelDescending(); sorted = WhoSort.LEVEL_DESCENDING; } else { sortByLevelAscending(); sorted = WhoSort.LEVEL_ASCENDING; } } }; private final static ButtonMenuSort sortByClasse = new ButtonMenuSort(X_SOCIAL_FRAME+272*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+74*Mideas.getDisplayYFactor(), 80*Mideas.getDisplayXFactor(), "Classe", 12) { @Override public void eventButtonClick() { if(sorted == WhoSort.CLASSE_ASCENDING) { sortByClasseDescending(); sorted = WhoSort.CLASSE_DESCENDING; } else { sortByClasseAscending(); sorted = WhoSort.CLASSE_ASCENDING; } } }; private final static ScrollBar scrollBar = new ScrollBar(X_SOCIAL_FRAME+357*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+100*Mideas.getDisplayYFactor(), 290*Mideas.getDisplayYFactor(), 400*Mideas.getDisplayXFactor(), 290*Mideas.getDisplayYFactor(), false, 20*Mideas.getDisplayYFactor()); private static boolean initDropDownMenu; public static void draw() { updateSize(); if(!initDropDownMenu) { dropDownMenu.addMenu(sortByArea); dropDownMenu.addMenu(sortByGuild); dropDownMenu.addMenu(sortByRace); initDropDownMenu = true; } if(updateString) { if(whoList.size() > 1) numberPeopleFound = whoList.size()+" players found"; else numberPeopleFound = whoList.size()+" player found"; peopleFoundWidth = FontManager.get("FRIZQT", 12).getWidth(numberPeopleFound); updateString = false; } Draw.drawQuad(Sprites.who_frame, X_SOCIAL_FRAME, Y_SOCIAL_FRAME); updateButton.draw(); addFriendButton.draw(); inviteButton.draw(); sortByName.draw(); sortByLevel.draw(); sortByClasse.draw(); FontManager.get("FRIZQT", 12).drawStringShadow(X_SOCIAL_FRAME+200*Mideas.getDisplayXFactor()-peopleFoundWidth/2, Y_SOCIAL_FRAME+392*Mideas.getDisplayYFactor(), numberPeopleFound, Color.YELLOW, Color.BLACK, 1, 0, 0); if(whoList.size() == 0) { dropDownBackground.draw(); dropDownMenu.draw(); return; } int i = 0; int iOffset = 0; if(whoList.size() > MAXIMUM_UNIT_DISPLAYED) { scrollBar.draw(); i = iOffset = (int)((whoList.size()-MAXIMUM_UNIT_DISPLAYED)*scrollBar.getScrollPercentage()); } TTF font = FontManager.get("FRIZQT", 12); font.drawBegin(); float y = Y_SOCIAL_FRAME+103*Mideas.getDisplayYFactor(); float yShift = 17*Mideas.getDisplayYFactor(); float yShiftHeight = 0; while(i < whoList.size()) { WhoUnit unit = whoList.get(i); font.drawStringShadowPart(X_SOCIAL_FRAME+30*Mideas.getDisplayXFactor(), y+yShiftHeight, unit.getName(), Color.YELLOW, Color.BLACK, 1, 0, 0); if(dropDownDisplay == WhoDropDownDisplay.AREA) font.drawStringShadowPart(X_SOCIAL_FRAME+120*Mideas.getDisplayXFactor(), y+yShiftHeight, "Area", Color.WHITE, Color.BLACK, 1, 0, 0); else if(dropDownDisplay == WhoDropDownDisplay.GUILD) font.drawStringShadowPart(X_SOCIAL_FRAME+120*Mideas.getDisplayXFactor(), y+yShiftHeight, unit.getGuildName(), Color.WHITE, Color.BLACK, 1, 0, 0); else if(dropDownDisplay == WhoDropDownDisplay.RACE) font.drawStringShadowPart(X_SOCIAL_FRAME+120*Mideas.getDisplayXFactor(), y+yShiftHeight, unit.getRace(), Color.WHITE, Color.BLACK, 1, 0, 0); font.drawStringShadowPart(X_SOCIAL_FRAME+240*Mideas.getDisplayXFactor(), y+yShiftHeight, unit.getLevelString(), Color.WHITE, Color.BLACK, 1, 0, 0); font.drawStringShadowPart(X_SOCIAL_FRAME+280*Mideas.getDisplayXFactor(), y+yShiftHeight, unit.getClasse(), unit.getColor(), Color.BLACK, 1, 0, 0); yShiftHeight+= yShift; if(yShiftHeight >= 280*Mideas.getDisplayYFactor()) break; i++; } font.drawEnd(); i = iOffset; float width; if(whoList.size() > MAXIMUM_UNIT_DISPLAYED) width = 325*Mideas.getDisplayXFactor(); else width = 345*Mideas.getDisplayXFactor(); if(hoveredUnit != -1 && hoveredUnit >= iOffset && hoveredUnit < iOffset+MAXIMUM_UNIT_DISPLAYED) Draw.drawQuadBlend(Sprites.friend_border, X_SOCIAL_FRAME+25*Mideas.getDisplayXFactor(), y+(hoveredUnit-iOffset)*yShift, width, 17*Mideas.getDisplayYFactor()); if(selectedUnit != -1 && selectedUnit != hoveredUnit && selectedUnit >= iOffset && selectedUnit < iOffset+MAXIMUM_UNIT_DISPLAYED) Draw.drawQuadBlend(Sprites.friend_border, X_SOCIAL_FRAME+25*Mideas.getDisplayXFactor(), y+(selectedUnit-iOffset)*yShift, width, 17*Mideas.getDisplayYFactor()); tooltipMenu.draw(); dropDownBackground.draw(); dropDownMenu.draw(); } public static boolean mouseEvent() { if(updateButton.event()) return true; if(addFriendButton.event()) return true; if(inviteButton.event()) return true; if(sortByName.mouseEvent()) return true; if(sortByLevel.mouseEvent()) return true; if(dropDownMenu.event()) return true; if(sortByClasse.mouseEvent()) return true; if(tooltipMenu.event()) return true; int i = 0; hoveredUnit = -1; if(whoList.size() > MAXIMUM_UNIT_DISPLAYED) { if(scrollBar.event()) return true; i = (int)((whoList.size()-MAXIMUM_UNIT_DISPLAYED)*scrollBar.getScrollPercentage()); } float y = Y_SOCIAL_FRAME+103*Mideas.getDisplayYFactor(); float yShift = 17*Mideas.getDisplayYFactor(); float yShiftHeight = 0; while(i < whoList.size()) { if(Mideas.getHover() && Mideas.mouseX() >= X_SOCIAL_FRAME+30*Mideas.getDisplayXFactor() && Mideas.mouseX() <= X_SOCIAL_FRAME+350*Mideas.getDisplayXFactor() && Mideas.mouseY() >= y+yShiftHeight && Mideas.mouseY() <= y+yShiftHeight+yShift) { hoveredUnit = i; Mideas.setHover(false); break; } i++; yShiftHeight+= yShift; } if(hoveredUnit != -1) { if(Mouse.getEventButtonState()) { if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) unitDown = hoveredUnit; } else if(hoveredUnit == unitDown) { if(Mouse.getEventButton() == 0) { selectedUnit = hoveredUnit; unitDown = -1; return true; } else if(Mouse.getEventButton() == 1) { selectedUnit = hoveredUnit; buildTooltipMenu(); unitDown = -1; return true; } } } return false; } private static void buildTooltipMenu() { tooltipMenu.clearMenu(); tooltipMenu.setName(whoList.get(selectedUnit).getName()); tooltipMenu.addMenu(whisperMenu); tooltipMenu.addMenu(inviteMenu); tooltipMenu.addMenu(targetMenu); tooltipMenu.addMenu(ignoreMenu); tooltipMenu.addMenu(cancelMenu); tooltipMenu.setActive(true); tooltipMenu.updateSize(Mideas.mouseX(), Mideas.mouseY(), true); } public static void sortByNameAscending() { int i = -1; int j = -1; WhoUnit tmp; while(++i < whoList.size()) { j = i; while(++j < whoList.size()) { if(whoList.get(i).getName().compareTo(whoList.get(j).getName()) > 0) { tmp = whoList.get(j); whoList.set(j, whoList.get(i)); whoList.set(i, tmp); } } } } public static void sortByNameDescending() { int i = -1; int j = -1; WhoUnit tmp; while(++i < whoList.size()) { j = i; while(++j < whoList.size()) { if(whoList.get(i).getName().compareTo(whoList.get(j).getName()) < 0) { tmp = whoList.get(j); whoList.set(j, whoList.get(i)); whoList.set(i, tmp); } } } } public static void sortByArea() { } public static void sortByGuildAscending() { int i = -1; int j = -1; WhoUnit tmp; while(++i < whoList.size()) { j = i; while(++j < whoList.size()) { if(whoList.get(i).getGuildName().compareTo(whoList.get(j).getGuildName()) > 0) { tmp = whoList.get(j); whoList.set(j, whoList.get(i)); whoList.set(i, tmp); } } } } public static void sortByGuildDescending() { int i = -1; int j = -1; WhoUnit tmp; while(++i < whoList.size()) { j = i; while(++j < whoList.size()) { if(whoList.get(i).getGuildName().compareTo(whoList.get(j).getGuildName()) < 0) { tmp = whoList.get(j); whoList.set(j, whoList.get(i)); whoList.set(i, tmp); } } } } public static void sortByLevelAscending() { int i = -1; int j = -1; WhoUnit tmp; while(++i < whoList.size()) { j = i; while(++j < whoList.size()) { if(whoList.get(i).getLevel() >= whoList.get(j).getLevel()) { tmp = whoList.get(j); whoList.set(j, whoList.get(i)); whoList.set(i, tmp); } } } } public static void sortByLevelDescending() { int i = -1; int j = -1; WhoUnit tmp; while(++i < whoList.size()) { j = i; while(++j < whoList.size()) { if(whoList.get(i).getLevel() <= whoList.get(j).getLevel()) { tmp = whoList.get(j); whoList.set(j, whoList.get(i)); whoList.set(i, tmp); } } } } public static void sortByRaceAscending() { int i = -1; int j = -1; WhoUnit tmp; while(++i < whoList.size()) { j = i; while(++j < whoList.size()) { if(whoList.get(i).getRace().compareTo(whoList.get(j).getRace()) >= 0) { tmp = whoList.get(j); whoList.set(j, whoList.get(i)); whoList.set(i, tmp); } } } } public static void sortByRaceDescending() { int i = -1; int j = -1; WhoUnit tmp; while(++i < whoList.size()) { j = i; while(++j < whoList.size()) { if(whoList.get(i).getRace().compareTo(whoList.get(j).getRace()) <= 0) { tmp = whoList.get(j); whoList.set(j, whoList.get(i)); whoList.set(i, tmp); } } } } public static void sortByClasseAscending() { int i = -1; int j = -1; WhoUnit tmp; while(++i < whoList.size()) { j = i; while(++j < whoList.size()) { if(whoList.get(i).getClasse().compareTo(whoList.get(j).getClasse()) >= 0) { tmp = whoList.get(j); whoList.set(j, whoList.get(i)); whoList.set(i, tmp); } } } } public static void sortByClasseDescending() { int i = -1; int j = -1; WhoUnit tmp; while(++i < whoList.size()) { j = i; while(++j < whoList.size()) { if(whoList.get(i).getClasse().compareTo(whoList.get(j).getClasse()) <= 0) { tmp = whoList.get(j); whoList.set(j, whoList.get(i)); whoList.set(i, tmp); } } } } public static void clearList() { selectedUnit = -1; whoList.clear(); updateString = true; } public static void updateSize() { if(!shouldUpdateSize) return; dropDownMenu.update(X_SOCIAL_FRAME+114*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+74*Mideas.getDisplayYFactor(), 115*Mideas.getDisplayXFactor(), X_SOCIAL_FRAME+105*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+98*Mideas.getDisplayYFactor(), 100*Mideas.getDisplayXFactor()); dropDownBackground.update(X_SOCIAL_FRAME+112*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+74*Mideas.getDisplayYFactor(), 125*Mideas.getDisplayXFactor()); sortByClasse.update(X_SOCIAL_FRAME+272*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+74*Mideas.getDisplayYFactor(), 80*Mideas.getDisplayXFactor()); sortByLevel.update(X_SOCIAL_FRAME+234*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+74*Mideas.getDisplayYFactor(), 40*Mideas.getDisplayXFactor()); sortByName.update(X_SOCIAL_FRAME+19*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+74*Mideas.getDisplayYFactor(), 95*Mideas.getDisplayXFactor()); scrollBar.update(X_SOCIAL_FRAME+357*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+100*Mideas.getDisplayYFactor(), 290*Mideas.getDisplayYFactor(), 400*Mideas.getDisplayXFactor(), 290*Mideas.getDisplayYFactor(), 20*Mideas.getDisplayYFactor()); updateButton.update(X_SOCIAL_FRAME+17*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+437*Mideas.getDisplayYFactor()); addFriendButton.update(X_SOCIAL_FRAME+119*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+437*Mideas.getDisplayYFactor()); inviteButton.update(X_SOCIAL_FRAME+253*Mideas.getDisplayXFactor(), Y_SOCIAL_FRAME+437*Mideas.getDisplayYFactor()); tooltipMenu.updateSize(); shouldUpdateSize = false; } public static void shouldUpdate() { shouldUpdateSize = true; } public static void addToList(WhoUnit unit) { whoList.add(unit); /*int i = 0; while(i < 70) { whoList.add(new WhoUnit(3, "Test", "GuildTest", (int)(70*Math.random()), ClassType.DRUID, Race.DRAENEI)); i++; }*/ whoList.add(new WhoUnit(3, "END", "EENNDD", 70, ClassType.DRUID, Race.DRAENEI)); } public static ArrayList<WhoUnit> getList() { return (whoList); } }
package com.example.acer.retrofit; import android.annotation.SuppressLint; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; public class TiketAdapter extends RecyclerView.Adapter<TiketAdapter.MyViewHolder> { List<Tiket> mTiketList; public TiketAdapter(List<Tiket> tiketList) { mTiketList = tiketList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); MyViewHolder mViewHolder = new MyViewHolder(mView); return mViewHolder; } @SuppressLint("SetTextI18n") @Override public void onBindViewHolder(@NonNull MyViewHolder holder,final int position) { holder.mTextViewIdTiket.setText("Id Tiket : " + mTiketList.get(position) .getId_tiket()); holder.mTextViewIdfilm.setText("Id film : " + mTiketList.get(position) .getId_film()); holder.mTextViewIdstudio.setText("Id_studio : " + mTiketList.get(position) .getId_studio()); holder.mTextViewharga.setText("Harga : " + mTiketList.get(position) .getHarga()); holder.mTextViewtayang.setText("Total Harga : " + String.valueOf(mTiketList.get (position).getHarga())); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent mIntent = new Intent(view.getContext(), LayarDetail.class); mIntent.putExtra("id_tiket",mTiketList.get(position).getId_tiket()); mIntent.putExtra("id_film",mTiketList.get(position).getId_tiket()); mIntent.putExtra("id_studio",mTiketList.get(position).getId_studio()); mIntent.putExtra("harga",mTiketList.get(position).getHarga()); mIntent.putExtra("tayang",mTiketList.get(position).getTayang()); view.getContext().startActivity(mIntent); } }); } @Override public int getItemCount() { return mTiketList.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { public TextView mTextViewIdTiket, mTextViewIdfilm, mTextViewIdstudio, mTextViewharga, mTextViewtayang; public MyViewHolder(View itemView) { super(itemView); mTextViewIdTiket = (TextView) itemView.findViewById(R.id.tvIdTiket); mTextViewIdfilm = (TextView) itemView.findViewById(R.id.tvIdFilm); mTextViewIdstudio = (TextView) itemView.findViewById(R.id.tvIdStd); mTextViewharga = (TextView) itemView.findViewById(R.id.tvharga); mTextViewtayang = (TextView) itemView.findViewById(R.id.tvtayang); } } }
package Guvi; public class ReverseInt { public int getReverseInt(int value) { int resultNumber = 0; for(int i = value; i !=0; i /= 10) { resultNumber = resultNumber * 10 + i % 10; } return resultNumber; } }
package com.example.todolist.Model.Repositories; import com.example.todolist.Model.Entities.EntryResponse; import com.example.todolist.Model.RemoteDataSource.Api_Interface; import com.google.gson.JsonObject; import io.reactivex.Single; public class EntryRepository { private Api_Interface api_interface; public EntryRepository(Api_Interface api_interface) { this.api_interface = api_interface; } public Single<EntryResponse> entry(JsonObject body){ return api_interface.entry(body); } }
public class Rey extends Jedi implements LightSaber, Pilot{ public Rey(){ super("Rey","Both","Resistance",true); } public String lightSaber(){ return "yellow lightsaber"; } public boolean pilot(){ return true; } }
package com.tt.miniapphost.process.extra; import com.tt.miniapphost.process.helper.AsyncIpcHandler; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; public interface ICrossProcessOperator { void callbackOnOriginProcess(String paramString); boolean isSwitchProcessOperateAsync(); void operateFinishOnGoalProcess(String paramString, AsyncIpcHandler paramAsyncIpcHandler); String operateProcessIdentify(); @Retention(RetentionPolicy.SOURCE) public static @interface OperateProcessIdentify {} } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapphost\process\extra\ICrossProcessOperator.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
/******************************************************************************* * QBiC Project qNavigator enables users to manage their projects. * Copyright (C) "2016” Christopher Mohr, David Wojnar, Andreas Friedrich * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-147 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.06.25 at 04:13:23 PM CEST // package life.qbic.xml.notes; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="comment" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="time" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="username" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "comment", "time", "username" }) @XmlRootElement(name = "note") public class Note { @XmlElement(required = true) protected String comment; @XmlElement(required = true) protected String time; @XmlElement(required = true) protected String username; /** * Gets the value of the comment property. * * @return * possible object is * {@link String } * */ public String getComment() { return comment; } /** * Sets the value of the comment property. * * @param value * allowed object is * {@link String } * */ public void setComment(String value) { this.comment = value; } /** * Gets the value of the time property. * * @return * possible object is * {@link String } * */ public String getTime() { return time; } /** * Sets the value of the time property. * * @param value * allowed object is * {@link String } * */ public void setTime(String value) { this.time = value; } /** * Gets the value of the username property. * * @return * possible object is * {@link String } * */ public String getUsername() { return username; } /** * Sets the value of the username property. * * @param value * allowed object is * {@link String } * */ public void setUsername(String value) { this.username = value; } }
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.replicatedmap.operation; import com.hazelcast.core.Member; import com.hazelcast.instance.MemberImpl; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.DataSerializable; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import com.hazelcast.replicatedmap.ReplicatedMapService; import com.hazelcast.replicatedmap.record.AbstractReplicatedRecordStore; import com.hazelcast.replicatedmap.record.ReplicationPublisher; import com.hazelcast.spi.Operation; import com.hazelcast.spi.OperationService; import java.io.IOException; import java.util.Arrays; /** * The replicated map post join operation to execute on remote nodes */ public class ReplicatedMapPostJoinOperation extends AbstractReplicatedMapOperation implements IdentifiedDataSerializable { /** * Default size for replication chunks */ public static final int DEFAULT_CHUNK_SIZE = 100; private MemberMapPair[] replicatedMaps; private int chunkSize; ReplicatedMapPostJoinOperation() { } public ReplicatedMapPostJoinOperation(MemberMapPair[] replicatedMaps, int chunkSize) { this.replicatedMaps = Arrays.copyOf(replicatedMaps, replicatedMaps.length); this.chunkSize = chunkSize; } @Override public void run() throws Exception { Member localMember = getNodeEngine().getLocalMember(); ReplicatedMapService replicatedMapService = getService(); for (MemberMapPair replicatedMap : replicatedMaps) { String mapName = replicatedMap.getName(); if (localMember.equals(replicatedMap.getMember())) { AbstractReplicatedRecordStore recordStorage = (AbstractReplicatedRecordStore) replicatedMapService .getReplicatedRecordStore(mapName, false); if (recordStorage != null && recordStorage.isLoaded()) { ReplicationPublisher replicationPublisher = recordStorage.getReplicationPublisher(); replicationPublisher.queuePreProvision(getCallerAddress(), chunkSize); } else { OperationService operationService = getNodeEngine().getOperationService(); Operation operation = new ReplicatedMapInitChunkOperation(mapName, localMember); operationService.send(operation, getCallerAddress()); } } } } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { out.writeInt(chunkSize); out.writeInt(replicatedMaps.length); for (int i = 0; i < replicatedMaps.length; i++) { replicatedMaps[i].writeData(out); } } @Override protected void readInternal(ObjectDataInput in) throws IOException { chunkSize = in.readInt(); int length = in.readInt(); replicatedMaps = new MemberMapPair[length]; for (int i = 0; i < length; i++) { replicatedMaps[i] = new MemberMapPair(); replicatedMaps[i].readData(in); } } @Override public int getFactoryId() { return ReplicatedMapDataSerializerHook.F_ID; } @Override public int getId() { return ReplicatedMapDataSerializerHook.OP_POST_JOIN; } /** * A mapping for replicated map names and the assigned provisioning member */ public static class MemberMapPair implements DataSerializable { private Member member; private String name; MemberMapPair() { } public MemberMapPair(Member member, String name) { this.member = member; this.name = name; } public Member getMember() { return member; } public String getName() { return name; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); member.writeData(out); } @Override public void readData(ObjectDataInput in) throws IOException { name = in.readUTF(); member = new MemberImpl(); member.readData(in); } } }
package com.cmpickle.volumize.view.schedule.edit; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.support.v4.app.Fragment; import com.cmpickle.volumize.R; import com.cmpickle.volumize.data.entity.ScheduleEvent; import com.cmpickle.volumize.view.edit.EditActivity; /** * @author Cameron Pickle * Copyright (C) Cameron Pickle (cmpickle) on 4/9/2017. */ public class EditScheduleActivity extends EditActivity implements EditScheduleRouter { public static final String INTENT_EVENT_ID = "eventId"; @Override protected Fragment createFragment() { return EditScheduleFragment.newInstance(getIntentId()); } @Override protected int getToolbarTitleId() { return R.string.edit_schedule_title; } public static void start(Activity activity) { Intent intent = new Intent(activity, EditScheduleActivity.class); activity.startActivity(intent); } public static void startEditEvent(Activity activity, ScheduleEvent event) { Intent intent = new Intent(activity, EditScheduleActivity.class); intent.putExtra(INTENT_EVENT_ID, event.getId()); activity.startActivity(intent); } @Override public void leave() { this.finish(); } public Context getContext() { return this; } public String getIntentId() { return getIntent().getStringExtra(INTENT_EVENT_ID); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.navigations.service.functions; import de.hybris.platform.core.model.ItemModel; import de.hybris.platform.core.model.media.MediaModel; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import java.util.function.Function; /** * Default implementation for conversion of {@link ItemModel} into {@code MediaModel#getCode()} */ public class DefaultNavigationEntryMediaModelIdConversionFunction implements Function<ItemModel, String> { @Override public String apply(final ItemModel itemModel) { if (!(MediaModel.class.isAssignableFrom(itemModel.getClass()))) { throw new ConversionException("Invalid Media Component: " + itemModel); } return ((MediaModel) itemModel).getCode(); } }
package com.fastjavaframework.listener; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import com.fastjavaframework.exception.ThrowException; /** * 读取字典表 */ public class SystemCode extends ContextLoader { private static Logger logger = LoggerFactory.getLogger(SystemCode.class); public static Map<String, CodeBean> CODE = new HashMap<>(); @Override public void runBeforeContext(ApplicationContext context) { } @Override public void runAferContext(ApplicationContext context) { try { logger.info("---------读取字典表---------"); DataSource ds = (DataSource) context.getBean("dataSource"); PreparedStatement ps = ds.getConnection().prepareStatement("select id,parent_id,`group`,name,`code` from sys_code where enable='1' order by id,parent_id,sequence"); ResultSet rs = ps.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); int parentId = rs.getInt("parent_id"); String group = rs.getString("group"); String name = rs.getString("name"); String code = rs.getString("code"); CODE.put(group, new CodeBean(id, parentId, name, code)); logger.info("--->" + id + "," + parentId + "," + group + "," + name + "," + code); } logger.info("---------读取字典表结束---------"); } catch (SQLException e) { logger.info("---------读取字典表失败---------"); throw new ThrowException("读取字典表失败:" + e.getMessage()); } } class CodeBean { private int id; private int parentId; private String name; private String code; public CodeBean(int id,int parentId,String name,String code) { this.id = id; this.parentId = parentId; this.name = name; this.code = code; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getParentId() { return parentId; } public void setParentId(int parentId) { this.parentId = parentId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } } }
package com.crud.tasks.service; import com.crud.tasks.config.AdminConfig; import com.crud.tasks.config.CompanyDetails; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import java.util.ArrayList; import java.util.List; @Service public class MailCreatorService { @Autowired private AdminConfig adminConfig; @Autowired private CompanyDetails companyDetails; @Autowired @Qualifier("templateEngine") private TemplateEngine templateEngine; private Context contextTrello; private List<String> functionality; public String buildTrelloCardEmail(String message) { contextTrello = new Context(); contextTrello.setVariable("message", message); makeListForIteration(); makeDataTrelloContext(); return templateEngine.process("mail/created-trello-card-mail", contextTrello); } public String buildScheduledTrelloInfoMail(String message) { contextTrello = new Context(); contextTrello.setVariable("message", message); makeDataTrelloContext(); return templateEngine.process("mail/scheduled-trello-cards-mail", contextTrello); } private void makeDataTrelloContext() { contextTrello.setVariable("tasks_url", "https://radoslaw-lazur.github.io/"); contextTrello.setVariable("button", "Visit website"); contextTrello.setVariable("goodbye", "Best regards: " + adminConfig.getAdminName()); contextTrello.setVariable("details", "Company Details:"); contextTrello.setVariable("admin_name", adminConfig.getAdminName()); contextTrello.setVariable("app_name", "Company name: " + companyDetails.getAppName()); contextTrello.setVariable("app_description", "Company description: " + companyDetails.getAppDescription()); contextTrello.setVariable("company_mail", "Company e-mail: " + companyDetails.getMail()); contextTrello.setVariable("company_mobile", "Company mobile: " + companyDetails.getMobile()); contextTrello.setVariable("show_button", true); contextTrello.setVariable("show_button_in_scheduled_mail", true); contextTrello.setVariable("is_friend", false); contextTrello.setVariable("is_friend_in_scheduled_mail", false); contextTrello.setVariable("admin_config", adminConfig); contextTrello.setVariable("application_functionality", functionality); } private void makeListForIteration() { functionality = new ArrayList<>(); functionality.add("You can manage your tasks"); functionality.add("Provides connection with Trello Account"); functionality.add("Application allows sending tasks to Trello"); } }
/* * Copyright © 2019 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.dom.builder.shared; /** Builds an option element. */ public interface OptionBuilder extends ElementBuilderBase<OptionBuilder> { /** * Represents the value of the HTML selected attribute. The value of this attribute does not * change if the state of the corresponding form control, in an interactive user agent, changes. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-selected">W3C * HTML Specification</a> */ OptionBuilder defaultSelected(); /** * Prevents the user from selecting this option. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-disabled">W3C * HTML Specification</a> */ OptionBuilder disabled(); /** * Option label for use in menus. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-label-OPTION">W3C * HTML Specification</a> */ OptionBuilder label(String label); /** * Represents the current state of the corresponding form control, in an interactive user agent. * Changing this attribute changes the state of the form control, but does not change the value of * the HTML selected attribute of the element. */ OptionBuilder selected(); /** * The current form control value. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-value-OPTION">W3C * HTML Specification</a> */ OptionBuilder value(String value); }
package com.设计模式.抽象工厂.listfactory; import com.设计模式.抽象工厂.factory.*; public class ListFactory extends Factory { public Link createLink(String caption, String url) { return new ListLink(caption, url); } }
package hhh; public class TestOnGit { public static void main(String[] args) { int i=0; } }
package dograce.models; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.scene.paint.Color; public class Dog { private String dogName; private Color color; private double posX = 0; private int speed = 10; public void setPlayerName(String name) { dogName = name; } public String getPlayerName() { return dogName; } public void setColor(Color color) { this.color = color; } public Color getColor() { return color; } public void setPosX(double posX) { this.posX = posX; } public double getPosX() { return posX; } public void setSpeed(int speed) { this.speed = speed; } public int getSpeed() { return speed; } public Dog(){}; public Dog(String name, Color color) { dogName = name; this.color = color; } }
package br.com.utfpr.dao.impl; import br.com.utfpr.beans.Address; import br.com.utfpr.dao.ConnectionBuilder; import br.com.utfpr.beans.Driver; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.List; import br.com.utfpr.dao.Dao; public class DriverDao implements Dao<Driver> { public DriverDao() { try{ Connection con = new ConnectionBuilder().getConnection(); String sql = "CREATE TABLE IF NOT EXISTS public.motorista\n" + "(\n" + " cod bigint NOT NULL,\n" + " nome character varying(45) COLLATE pg_catalog.\"default\",\n" + " fone character varying(15) COLLATE pg_catalog.\"default\",\n" + " rg bigint,\n" + " cpf bigint,\n" + " email character varying(50) COLLATE pg_catalog.\"default\",\n" + " cnh bigint,\n" + " tipocnh character varying(2) COLLATE pg_catalog.\"default\",\n" + " datavencimento date,\n" + " status boolean,\n" + " CONSTRAINT motorista_pkey PRIMARY KEY (cod)\n" + ")\n" + "WITH (\n" + " OIDS = FALSE\n" + ")\n" + "TABLESPACE pg_default;"; PreparedStatement stmt = con.prepareStatement(sql); stmt.execute(); stmt.close(); con.close(); }catch(SQLException e){ throw new RuntimeException(e); } } @Override public void add(Object obj) { try{ Connection con; con = new ConnectionBuilder().getConnection(); Driver driver = (Driver) obj; String sql = "insert into motorista(cod,nome,fone,rg,cpf,email,cnh,tipocnh,datavencimento,status)" + "values(?,?,?,?,?,?,?,?,?,?)"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setLong(1, driver.getId()); stmt.setString(2,driver.getName()); stmt.setString(3, driver.getPhone()); stmt.setLong(4,driver.getRG()); stmt.setLong(5,driver.getCPF()); stmt.setString(6,driver.getEmail()); stmt.setLong(7, driver.getCNHnum()); stmt.setString(8,driver.getCNHtype()); stmt.setDate(9, new Date(driver.getExpiration() .getTimeInMillis())); stmt.setBoolean(10,driver.isStatus()); AddressDao address = new AddressDao(); address.add(driver.getAddress()); stmt.execute(); stmt.close(); con.close(); }catch(SQLException e){ throw new RuntimeException(e); } } @Override public void remove(Object obj) { try(Connection con = new ConnectionBuilder().getConnection()){ Driver driver = (Driver) obj; Dao<Address> address = new AddressDao(); Address ad = new Address(); ad.setId(driver.getAddress().getId()); try{ address.remove(ad); }catch(RuntimeException e){ throw e; } String sql = "delete from motorista where cod=?"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setLong(1,driver.getId()); stmt.execute(); stmt.close(); con.close(); }catch(SQLException e){ throw new RuntimeException(e); } } @Override public void update(Object obj) { try(Connection con = new ConnectionBuilder().getConnection()){ Driver driver = (Driver) obj; String sql = "update motorista set nome=?,fone=?,rg=?,cpf=?,email=?,cnh=?,tipocnh=?,datavencimento=?,status=?" + "where cod=?"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setString(1,driver.getName()); stmt.setString(2, driver.getPhone()); stmt.setLong(3,driver.getRG()); stmt.setLong(4,driver.getCPF()); stmt.setString(5,driver.getEmail()); stmt.setLong(6, driver.getCNHnum()); stmt.setString(7,driver.getCNHtype()); stmt.setDate(8, new Date(driver.getExpiration() .getTimeInMillis())); stmt.setBoolean(9,driver.isStatus()); AddressDao address= new AddressDao(); address.update(driver.getAddress()); stmt.setLong(10, driver.getId()); stmt.execute(); stmt.close(); con.close(); }catch(SQLException e){ throw new RuntimeException(e); } } @Override public Object read(long id) { try(Connection con = new ConnectionBuilder().getConnection()){ Driver driver = new Driver(); String sql = "select * from motorista where cod=?"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setLong(1, id); ResultSet rs = stmt.executeQuery(); while(rs.next()) { driver.setId(rs.getLong("cod")); driver.setName(rs.getString("nome")); driver.setPhone(rs.getString("fone")); driver.setRG(rs.getLong("rg")); driver.setCPF(rs.getLong("cpf")); driver.setEmail(rs.getString("email")); driver.setCNHnum(rs.getLong("cnh")); driver.setCNHtype(rs.getString("tipocnh")); Calendar date = Calendar.getInstance(); date.setTime(rs.getDate("datavencimento")); driver.setExpiration(date); driver.setStatus(rs.getBoolean("status")); AddressDao address= new AddressDao(); driver.setAddress((Address) address.read(id)); } return driver; }catch(SQLException e){ throw new RuntimeException(e); } } @Override public Collection<Driver> getList() { try(Connection con = new ConnectionBuilder().getConnection()){ List<Driver> driverList = new ArrayList<>(); String sql = "select * from motorista"; PreparedStatement stmt = con.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while(rs.next()){ Driver driver = new Driver(); driver.setId(rs.getLong("cod")); driver.setName(rs.getString("nome")); driver.setPhone(rs.getString("fone")); driver.setRG(rs.getLong("rg")); driver.setCPF(rs.getLong("cpf")); driver.setEmail(rs.getString("email")); driver.setCNHnum(rs.getLong("cnh")); driver.setCNHtype(rs.getString("tipocnh")); Calendar date = Calendar.getInstance(); date.setTime(rs.getDate("datavencimento")); driver.setExpiration(date); driver.setStatus(rs.getBoolean("status")); AddressDao address= new AddressDao(); driver.setAddress((Address) address.read(driver.getId())); driverList.add(driver); } return driverList; }catch(SQLException e){ throw new RuntimeException(e); } } }
package com.Arrays; import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class socks { // Complete the sockMerchant function below. static int sockMerchant(int n, int[] ar) { Arrays.sort(ar); int count = 0; int temp = ar[0]; int glo = 0; for(int i = 0; i < n; i++){ if(temp == ar[i]){ count++; }else{ glo = glo + count/2; count = 1; temp = ar[i]; } } glo = glo + count/2; return glo; } private static Scanner scanner = null; static { try { scanner = new Scanner( new FileInputStream(new File("input/dummy"))); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int[] ar = new int[n]; String[] arItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int arItem = Integer.parseInt(arItems[i]); ar[i] = arItem; } int result = sockMerchant(n, ar); System.out.println(String.valueOf(result)); scanner.close(); } }
package com.travelportal.vm; import java.util.ArrayList; import java.util.List; import com.travelportal.domain.HotelStarRatings; import com.travelportal.domain.rooms.RateMeta; public class SerachedHotelbyDate { public String date; public List<SerachedRoomType> roomType; public String flag; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public List<SerachedRoomType> getRoomType() { return roomType; } public void setRoomType(List<SerachedRoomType> roomType) { this.roomType = roomType; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } }
package pl.edu.pw.mini.gapso.optimizer.move; import com.google.gson.Gson; import pl.edu.pw.mini.gapso.configuration.MoveConfiguration; import pl.edu.pw.mini.gapso.optimizer.Particle; import pl.edu.pw.mini.gapso.optimizer.SamplingOptimizer; import pl.edu.pw.mini.gapso.utils.Generator; import java.util.List; public class DEBest1Bin extends Move { public static final String NAME = "DE/best/1/bin"; private final double _scale; private final double _crossProb; private final boolean _constantScale; private final boolean _constantCrossProb; public static double[] getDESample(double[] current, double[] best, double[] diffVector1, double[] diffVector2, double scale, double crossProb) { final int dim = current.length; double[] tryX = new double[dim]; int alwaysSwitchIdx = Generator.RANDOM.nextInt(dim); for (int dimIdx = 0; dimIdx < dim; ++dimIdx) { tryX[dimIdx] = best[dimIdx] + scale * (diffVector1[dimIdx] - diffVector2[dimIdx]); if (alwaysSwitchIdx != dimIdx) { double testIfSwitch = Generator.RANDOM.nextDouble(); if (testIfSwitch > crossProb) { tryX[dimIdx] = current[dimIdx]; } } } return tryX; } public DEBest1Bin(MoveConfiguration moveConfiguration) { super(moveConfiguration); Gson gson = new Gson(); DEBest1BinConfiguration deConf = gson.fromJson( moveConfiguration.getParameters(), DEBest1BinConfiguration.class); _scale = deConf.getScale(); _crossProb = deConf.getCrossProb(); _constantScale = deConf.isConstantScale(); _constantCrossProb = deConf.isConstantCrossProb(); } @Override public double[] getNext(Particle currentParticle, List<Particle> particleList) { final int particlesCount = particleList.size(); if (particlesCount < 4) { throw new IllegalArgumentException("Not enough particles for " + NAME); } int bestIndex = currentParticle.getGlobalBestIndex(); int currentIndex = currentParticle.getIndex(); int randomIndex1 = currentIndex; while (randomIndex1 == currentIndex || randomIndex1 == bestIndex) { randomIndex1 = Generator.RANDOM.nextInt(particlesCount); } int randomIndex2 = randomIndex1; while (randomIndex2 == randomIndex1 || randomIndex2 == currentIndex || randomIndex2 == bestIndex) { randomIndex2 = Generator.RANDOM.nextInt(particlesCount); } double scale = getValue(_scale, _constantScale); double crossProb = getValue(_crossProb, _constantCrossProb); return getDESample( particleList.get(currentIndex).getBest().getX(), particleList.get(bestIndex).getBest().getX(), particleList.get(randomIndex1).getBest().getX(), particleList.get(randomIndex2).getBest().getX(), scale, crossProb); } @Override public void registerObjectsWithOptimizer(SamplingOptimizer samplingOptimizer) { //DO NOTHING ON PURPOSE } @Override public void resetState(int particleCount) { resetWeight(); } @Override public void registerPersonalImprovement(double deltaY) { //DO NOTHING ON PURPOSE } @Override public void newIteration() { //DO NOTHING ON PURPOSE } @Override public void registerSamplingResult(double y) { //DO NOTHING ON PURPOSE } private double getValue(double parameter, boolean constantParameter) { double scale = parameter; if (!constantParameter) { scale = Generator.RANDOM.nextDouble() * parameter; } return scale; } public static class DEBest1BinConfiguration { private double scale; private double crossProb; private boolean constantScale; private boolean constantCrossProb; public DEBest1BinConfiguration(double scale, double crossProb) { this(scale, crossProb, false, false); } public DEBest1BinConfiguration(double scale, double crossProb, boolean constantScale, boolean constantCrossProb) { this.scale = scale; this.crossProb = crossProb; this.constantScale = constantScale; this.constantCrossProb = constantCrossProb; } public double getScale() { return scale; } public double getCrossProb() { return crossProb; } public boolean isConstantScale() { return constantScale; } public boolean isConstantCrossProb() { return constantCrossProb; } public void setConstantCrossProb(boolean constantCrossProb) { this.constantCrossProb = constantCrossProb; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ package sbe.msg.marketData; import uk.co.real_logic.sbe.codec.java.CodecUtil; import uk.co.real_logic.agrona.MutableDirectBuffer; @SuppressWarnings("all") public class OrderModifiedEncoder { public static final int BLOCK_LENGTH = 26; public static final int TEMPLATE_ID = 21; public static final int SCHEMA_ID = 1; public static final int SCHEMA_VERSION = 0; private final OrderModifiedEncoder parentMessage = this; private MutableDirectBuffer buffer; protected int offset; protected int limit; protected int actingBlockLength; protected int actingVersion; public int sbeBlockLength() { return BLOCK_LENGTH; } public int sbeTemplateId() { return TEMPLATE_ID; } public int sbeSchemaId() { return SCHEMA_ID; } public int sbeSchemaVersion() { return SCHEMA_VERSION; } public String sbeSemanticType() { return ""; } public int offset() { return offset; } public OrderModifiedEncoder wrap(final MutableDirectBuffer buffer, final int offset) { this.buffer = buffer; this.offset = offset; limit(offset + BLOCK_LENGTH); return this; } public int encodedLength() { return limit - offset; } public int limit() { return limit; } public void limit(final int limit) { buffer.checkLimit(limit); this.limit = limit; } public OrderModifiedEncoder messageType(final MessageTypeEnum value) { CodecUtil.charPut(buffer, offset + 0, value.value()); return this; } public static long nanosecondNullValue() { return 4294967294L; } public static long nanosecondMinValue() { return 0L; } public static long nanosecondMaxValue() { return 4294967293L; } public OrderModifiedEncoder nanosecond(final long value) { CodecUtil.uint32Put(buffer, offset + 1, value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } public static long orderIdNullValue() { return 0xffffffffffffffffL; } public static long orderIdMinValue() { return 0x0L; } public static long orderIdMaxValue() { return 0xfffffffffffffffeL; } public OrderModifiedEncoder orderId(final long value) { CodecUtil.uint64Put(buffer, offset + 5, value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } public static long newQuantityNullValue() { return 4294967294L; } public static long newQuantityMinValue() { return 0L; } public static long newQuantityMaxValue() { return 4294967293L; } public OrderModifiedEncoder newQuantity(final long value) { CodecUtil.uint32Put(buffer, offset + 13, value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } private final PriceEncoder newPrice = new PriceEncoder(); public PriceEncoder newPrice() { newPrice.wrap(buffer, offset + 17); return newPrice; } public OrderModifiedEncoder flags(final Flags value) { CodecUtil.uint8Put(buffer, offset + 25, value.value()); return this; } }
package day24_loops; public class WhileLoopReverse { public static void main(String[] args) { int count =5; while(count >=0){ System.out.println("Count = " +count); count--; } System.out.println("Finished counting"); System.out.println("*************************************"); int unreadSMS = 10; System.out.println("I've total " + unreadSMS +"unread SMS"); while(unreadSMS >=1){ //>0 System.out.println("Reading SMS " + unreadSMS); unreadSMS--; } System.out.println("All SMS finished"); } }
package rent.common.repository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import rent.common.entity.RecalculationTypeEntity; import rent.common.projection.RecalculationTypeBasic; import java.util.List; @RepositoryRestResource( collectionResourceRel = "recalculation-types", path = "recalculation-type", itemResourceRel = "recalculation-type", excerptProjection = RecalculationTypeBasic.class) public interface RecalculationTypeRepository extends PagingAndSortingRepository<RecalculationTypeEntity, String> { RecalculationTypeEntity findByCode(@Param("code") String code); List<RecalculationTypeEntity> findByNameContainingOrderByCode(@Param("name") String name); }
package com.example.hereapi_example; import java.util.List; import com.here.android.common.GeoCoordinate; import com.here.android.common.ViewObject; import com.here.android.mapping.FragmentInitListener; import com.here.android.mapping.InitError; import com.here.android.mapping.Map; import com.here.android.mapping.MapCircle; import com.here.android.mapping.MapFactory; import com.here.android.mapping.MapFragment; import com.here.android.mapping.MapGestureListener; import com.here.android.mapping.MapMarker; import android.app.Activity; import android.graphics.Color; import android.graphics.PointF; import android.location.Location; import android.os.Bundle; interface LocationChangedListener{ void onLocationChanged(Location location); } public class LocationSourceDemoActivity extends Activity implements LocationChangedListener{ private static class LongPressLocationSource implements MapGestureListener{ private LocationChangedListener mListener = null; private Map mMap = null; /** * Flag to keep track of the activity's lifecycle. This is not strictly necessary in this * case because onMapLongPress events don't occur while the activity containing the map is * paused but is included to demonstrate best practices (e.g., if a background service were * to be used). */ private boolean mPaused; public LongPressLocationSource(LocationChangedListener listener,Map map) { mListener = listener; mMap = map; } public void onPause() { mPaused = true; } public void onResume() { mPaused = false; } @Override public boolean onLongPressEvent(PointF p) { if (mListener != null && !mPaused) { Location location = new Location("LongPressLocationProvider"); GeoCoordinate point = MapFactory.createGeoCoordinate(mMap.pixelToGeo(p)); location.setLatitude(point.getLatitude()); location.setLongitude(point.getLongitude()); location.setAccuracy(100); mListener.onLocationChanged(location); } return false; } @Override public boolean onDoubleTapEvent(PointF p) { return false; } @Override public void onLongPressRelease() {} @Override public boolean onMapObjectsSelected(List<ViewObject> objects) { return false; } @Override public void onMultiFingerManipulationEnd() {} @Override public void onMultiFingerManipulationStart() {} @Override public void onPanEnd() {} @Override public void onPanStart() {} @Override public void onPinchLocked() {} @Override public boolean onPinchZoomEvent(float scaleFactor, PointF p) { return false; } @Override public boolean onRotateEvent(float rotateAngle) { return false; } @Override public void onRotateLocked() {} @Override public boolean onTapEvent(PointF p) { return false; } @Override public boolean onTiltEvent(float angle) { return false; } @Override public boolean onTwoFingerTapEvent(PointF p) { return false; } } private LongPressLocationSource mLocationSource = null; Map mMap = null; private MapMarker centerMarker = null; private MapCircle circle = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.basic_demo); setUpMapIfNeeded(); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); if(mLocationSource != null){ mLocationSource.onResume(); } } private void setUpMapIfNeeded() { final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map); final LocationSourceDemoActivity that = this; // initialize the Map Fragment to create a map and // attached to the fragment mapFragment.init(new FragmentInitListener() { @Override public void onFragmentInitializationCompleted(InitError error) { if (error == InitError.NONE) { mMap = (Map) mapFragment.getMap(); mLocationSource = new LongPressLocationSource(that,mMap); mapFragment.getMapGesture().addMapGestureListener(mLocationSource); //mMap.setMyLocationEnabled(true); } } }); } @Override protected void onPause() { super.onPause(); if(mLocationSource != null){ mLocationSource.onPause(); } } @Override public void onLocationChanged(Location location) { if(location == null){ }else if(centerMarker != null && circle != null){ circle.setRadius(location.getAccuracy()); circle.setCenter(MapFactory.createGeoCoordinate(location.getLatitude(),location.getLongitude())); centerMarker.setCoordinate(circle.getCenter()); }else{ circle = MapFactory.createMapCircle(location.getAccuracy(),MapFactory.createGeoCoordinate(location.getLatitude(),location.getLongitude())); circle.setLineWidth(2); circle.setLineColor(Color.BLACK); circle.setFillColor(Color.argb(50, 0xFF, 0x00,0x00)); mMap.addMapObject(circle); centerMarker = MapFactory.createMapMarker(); centerMarker.setCoordinate(circle.getCenter()); centerMarker.setTitle("centerMarker"); centerMarker.setDraggable(true); mMap.addMapObject(centerMarker); } } }
package org.buaa.ly.MyCar.exception; import org.buaa.ly.MyCar.http.ResponseStatusMsg; public class OrderIdentityDuplicate extends BaseError { public OrderIdentityDuplicate(String message) { super(ResponseStatusMsg.ERROR.getStatus(), message); } }
package com.xvr.serviceBook.controller.restapi.dtorepresentation; import com.fasterxml.jackson.annotation.JsonProperty; import com.xvr.serviceBook.entity.AppRole; import com.xvr.serviceBook.entity.Worker; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import org.springframework.hateoas.CollectionModel; import org.springframework.hateoas.RepresentationModel; import javax.persistence.FetchType; import javax.persistence.OneToOne; import javax.validation.constraints.NotEmpty; import java.util.HashSet; import java.util.Set; @Getter @Builder @EqualsAndHashCode(callSuper = false) public class AppUserModelRepresentation extends RepresentationModel<AppUserModelRepresentation> { @JsonProperty("App User Id") private Long id; @NotEmpty private String userName; private boolean enabled; @JsonProperty("User Role") private CollectionModel<AppRoleModelRepresentation> appRole; /* TODO @OneToOne(fetch = FetchType.LAZY) private Worker worker;*/ }
public class MinimumFlipToMonotonicIncrement { public static int minFlipsMonoIncr(String S) { int length = S.length(); int[] p = new int[length+1]; for(int i=0;i<length;i++) { p[i+1] = p[i] + (S.charAt(i) == '1'?1:0); } int flip = Integer.MAX_VALUE; for (int i =0;i<=length;i++) { flip = Math.min(flip, p[i] + ((length - i) - (p[length] - p[i]))); } return flip; } public static void main(String[] args) { System.out.println(minFlipsMonoIncr("00011000")); } }
package eu.lsem.bakalarka.dao; import eu.lsem.bakalarka.model.*; import org.springframework.dao.DataAccessException; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import java.util.HashMap; import java.util.List; import java.util.Map; public class ThesesDaoImpl extends SqlMapClientDaoSupport implements ThesesDao { private TransactionTemplate transactionTemplate; public void setTransactionTemplate(TransactionTemplate transactionTemplate) { //injected by spring this.transactionTemplate = transactionTemplate; } @Override public void insertThesis(final MinimalThesis thesis) { getSqlMapClientTemplate().insert("Theses.insertThesis", thesis); } @Override @SuppressWarnings("unchecked") public Thesis getThesis(Integer id, ThesisSearch thesisSearch) { Map m = new HashMap(4); m.put("id", id); if (thesisSearch != null) { PostgresSpecificThesisSearch post = new PostgresSpecificThesisSearch(thesisSearch, getSqlMapClientTemplate()); m.put("databaseMetadataQuery", post.getDatabaseMetadataQuery()); m.put("fulltextQuery", post.getDatabaseQueryWithoutModifiers()); m.put("searchAnnotation", post.isSearchAnnotation()); m.put("searchAuthor", post.isSearchAuthor()); m.put("searchSubject", post.isSearchSubject()); m.put("searchFulltext", post.isSearchFulltext()); m.put("searchResume", post.isSearchResume()); } else { m.put("searchAnnotation", false); m.put("searchAuthor", false); m.put("searchSubject", false); m.put("searchFulltext", false); m.put("searchResume", false); } return (Thesis) getSqlMapClientTemplate().queryForObject("Theses.getThesis", m); } @Override @SuppressWarnings("unchecked") public List<BasicThesis> getTheses(Integer offset, Integer limit, boolean orderByAuthor, ThesesSelector selector, Integer[] args) { if (selector == null) { selector = ThesesSelector.ALL; } Map m = new HashMap(3); m.put("offset", offset); m.put("limit", limit); m.put("thesesSelector", selector); m.put("orderBy", orderByAuthor ? "author" : "date"); if (selector == ThesesSelector.DIRECTORY) { m.put("directoryId", args != null && args.length > 0 ? args[0] : null); } return getSqlMapClientTemplate().queryForList("Theses.getTheses", m); } @Override @SuppressWarnings("unchecked") public List<BasicThesis> searchTheses(ThesisSearch s) { if (s.isLikeSearch()) { LikeThesisSearch likeThesisSearch = new LikeThesisSearch(s); if(likeThesisSearch.getWords().size() == 0) { throw new TooFewTokensException("V dotazu není ani jedno slovo delší, než 2 znaky."); } return (List<BasicThesis>) getSqlMapClientTemplate().queryForList("Theses.likeSearchTheses", likeThesisSearch); } else { PostgresSpecificThesisSearch postgresSpecificThesisSearch = new PostgresSpecificThesisSearch(s, getSqlMapClientTemplate()); return (List<BasicThesis>) getSqlMapClientTemplate().queryForList("Theses.searchTheses", postgresSpecificThesisSearch); } } @Override public Integer deleteThesis(Integer i) { return getSqlMapClientTemplate().delete("Theses.deleteThesis", i); } @Override public void updateThesisMetadata(final Thesis thesis) { final DataAccessException[] exc = new DataAccessException[1]; Integer status = (Integer) transactionTemplate.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { try { getSqlMapClientTemplate().update("Theses.updateThesisMetadata", thesis); getSqlMapClientTemplate().delete("Theses.deleteTagsForThesis", thesis); //smazu tagy if (thesis.getTags() != null) { for (Tag tag : thesis.getTags()) { //znova pridam tagy zmeneny Map<String, Integer> map = new HashMap<String, Integer>(); map.put("tagID", tag.getId()); map.put("thesisID", thesis.getId()); getSqlMapClientTemplate().insert("Theses.insertThesisTag", map); } } } catch (DataAccessException e) { exc[0] = e; return 1; } return 0; } }); if (status != 0) { throw exc[0]; } } @Override @SuppressWarnings("unchecked") public void updateThesisFulltext(Integer id, String fulltext, String docPath) { Map m = new HashMap(); m.put("id", id); m.put("fulltext", fulltext); m.put("docPath", docPath); getSqlMapClientTemplate().update("Theses.updateThesisFulltext", m); } @Override @SuppressWarnings("unchecked") public void updateThesisHasData(Integer id, boolean data) { Map m = new HashMap(); m.put("id", id); m.put("hasData", data); getSqlMapClientTemplate().update("Theses.updateHasData", m); } @Override public int updateParentDirectory(Integer thesisId, Integer parentDirectoryId) { Map<String, Integer> m = new HashMap<String, Integer>(2); m.put("parentId", parentDirectoryId); m.put("id", thesisId); return getSqlMapClientTemplate().update("Theses.udpateThesisDirectory", m); } @Override @SuppressWarnings("unchecked") public List<Integer> getYears() { return getSqlMapClientTemplate().queryForList("Theses.getYears"); } @Override public int countTheses() { return (Integer) getSqlMapClientTemplate().queryForObject("Theses.countTheses"); } @Override public int countThesesWithUncompleteMetadata() { return (Integer) getSqlMapClientTemplate().queryForObject("Theses.countThesesWithUncompleteMetadata"); } @Override public int countThesesWithMissingData() { return (Integer) getSqlMapClientTemplate().queryForObject("Theses.countThesesWithMissingData"); } @Override public int countThesesWithoutSelectedDocumentation() { return (Integer) getSqlMapClientTemplate().queryForObject("Theses.countThesesWithoutSelectedDocumentation"); } @Override public int countThesesWithThesisCategory(Integer id) { return (Integer) getSqlMapClientTemplate().queryForObject("Theses.countThesesWithThesisCategory", id); } @Override public int countThesesWithFieldOfStudy(Integer id) { return (Integer) getSqlMapClientTemplate().queryForObject("Theses.countThesesWithFieldOfStudy", id); } @Override public int countThesesWithFormOfStudy(Integer id) { return (Integer) getSqlMapClientTemplate().queryForObject("Theses.countThesesWithFormOfStudy", id); } @Override public int countThesesAtYear(Integer year) { return (Integer) getSqlMapClientTemplate().queryForObject("Theses.countThesesWithYear", year); } @Override @SuppressWarnings("unchecked") public int countThesesAtYearAndCategory(Integer year, Integer categoryId) { Map<String, Integer> m = new HashMap<String, Integer>(2); m.put("year", year); m.put("categoryId", categoryId); return (Integer) getSqlMapClientTemplate().queryForObject("Theses.countThesesWithYearAndCategory", m); } @Override public int countThesesAtYearAndFieldOfStudy(Integer year, Integer fieldOfStudyId) { Map<String, Integer> m = new HashMap<String, Integer>(2); m.put("year", year); m.put("fieldOfStudyId", fieldOfStudyId); return (Integer) getSqlMapClientTemplate().queryForObject("Theses.countThesesWithYearAndFieldOfStudy", m); } @Override public int countThesesWithThesisCategoryAndFieldOfStudy(Integer thesisCategory, Integer fieldOfStudyId) { Map<String, Integer> m = new HashMap<String, Integer>(2); m.put("categoryId", thesisCategory); m.put("fieldOfStudyId", fieldOfStudyId); return (Integer) getSqlMapClientTemplate().queryForObject("Theses.countThesesWithThesisCategoryAndFieldOfStudy", m); } }
package com.trey.fitnesstools; import android.app.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; public class ActivityDeloadCalculator extends AppCompatActivity { private EditText editTextEnterDeloadWeight; private SeekBar seekBarDeloadPercent; private TextView textViewDeloadPercent; private TextView textViewOutput; private Button btnShowDeloadedPlates; private double weightInput; private int deloadedWeight; private int deloadPercent; public static final String KEY_INTENT_WEIGHT = "key_intent_weight"; public static final String KEY_INTENT_Percent = "key_intent_percent"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_deload_calculator); editTextEnterDeloadWeight = (EditText)findViewById(R.id.editTextEnterDeloadWeight); seekBarDeloadPercent = (SeekBar)findViewById(R.id.seekBarDeloadPercent); textViewDeloadPercent = (TextView)findViewById(R.id.textViewDeloadPercent) ; textViewOutput = (TextView)findViewById(R.id.txtDeloadedOutput); btnShowDeloadedPlates = (Button)findViewById(R.id.btnShowDeloadPlates); seekBarDeloadPercent.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { //get the deload percent and perform the deload calculation. deloadPercent = seekBar.getProgress(); updatePercentLabel(); deload(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); editTextEnterDeloadWeight.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable textBox) { deload(); if(editTextEnterDeloadWeight.getText().toString().isEmpty()) textViewOutput.setText(null); } }); //when the button is pressed, start the plate calculator activity. btnShowDeloadedPlates.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ActivityPlateCalculator.startActivityPlateCalculator(ActivityDeloadCalculator.this,deloadedWeight); } }); textViewDeloadPercent.setText(Integer.toString(seekBarDeloadPercent.getProgress())); deloadedWeight = 0; weightInput = getIntent().getDoubleExtra(KEY_INTENT_WEIGHT,0); if(weightInput > 0) editTextEnterDeloadWeight.setText(LiftingCalculations.desiredFormat(weightInput)); //If deload percent has been passed from another activity, it will be stored in the intent. //if not found, the percent will be 0 (second arg in getIntExtra(...) //SUBTRACT BY 100 BECAUSE IT IS BEING PASSED THE PERCENT OF THE WEIGHT, NOT THE PERCENT TO DELOAD BY. deloadPercent = 100 - getIntent().getIntExtra(KEY_INTENT_Percent,100); seekBarDeloadPercent.setProgress(deloadPercent); updatePercentLabel(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_question_mark,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.question_item) { String message = getString(R.string.long_message_deload_calculator); DialogFragmentQuestionMark dialog = DialogFragmentQuestionMark.newInstance(message); dialog.show(getSupportFragmentManager(),"question_tag"); } return false; } private void updatePercentLabel() { textViewDeloadPercent.setText(Integer.toString(deloadPercent) + " %"); } //gets user's weight input and outputs the deloaded amount private void deload() { try { //make sure the string isn't empty if (!editTextEnterDeloadWeight.getText().toString().isEmpty()) { weightInput = Double.parseDouble(editTextEnterDeloadWeight.getText().toString()); deloadedWeight = LiftingCalculations.deloadWeight(weightInput, deloadPercent); textViewOutput.setText(Integer.toString(deloadedWeight) + " is the weight after deloading"); } } catch(Exception e) { Toast.makeText(ActivityDeloadCalculator.this,"Enter valid input", Toast.LENGTH_SHORT); } } //use this method to start ActivityDeloadCalculator from another activity and pass it an initial weight value. public static void startActivityDeloadCalculator(Activity context,double weight,int percent) { Intent intent = new Intent(context,ActivityDeloadCalculator.class); intent.putExtra(KEY_INTENT_WEIGHT,weight); intent.putExtra(KEY_INTENT_Percent,percent); context.startActivity(intent); } }
package cs455.nfs.shared.structure; import cs455.nfs.shared.structure.node.CurrentDirNode; import cs455.nfs.shared.structure.node.DirectoryNode; import cs455.nfs.shared.structure.node.FileNode; import cs455.nfs.shared.structure.node.Node; import cs455.nfs.shared.structure.node.ParentDirNode; public interface IVisitor { void visitNode(Node node); void visitFile(FileNode node); void visitDirectory(DirectoryNode node); void visitParent(ParentDirNode node); void visitCur(CurrentDirNode node); }
package com.rofour.baseball.service.manager.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.rofour.baseball.controller.model.manager.KeywordInfo; import com.rofour.baseball.dao.manager.bean.KeywordBean; import com.rofour.baseball.dao.manager.mapper.KeywordMapper; import com.rofour.baseball.service.manager.KeywordService; @Service("keywordService") public class KeywordServiceImpl implements KeywordService { @Autowired @Qualifier("keywordMapper") private KeywordMapper dao; @Override public int insertKeyword(KeywordBean bean) { return dao.insertKeyword(bean); } @Override public int deleteByPrimaryKey(KeywordBean bean) { return dao.deleteByPrimaryKey(bean); } @Override public List<KeywordInfo> getList(KeywordInfo info) { return dao.getList(info); } @Override public int getListCount(KeywordInfo info) { return dao.getListCount(info); } @Override public boolean validateKeyword(KeywordBean bean) { List<KeywordBean> list = dao.validateKeyword(bean); if(list != null) { if(list.size() > 0) { return true; } } return false; } }
package data; import java.io.*; import java.util.ArrayList; import data.Recipe; public class FilterParseRecipeList { private String recipeFileLoc; private Recipe recipe; private ArrayList<Recipe> recipesList; private ArrayList<String> searchIngredientsList; private ArrayList<String> searchNegativeIngredientsList; private boolean goodRecipe = false; BufferedReader br = null; public FilterParseRecipeList(String recipeFileLocation, ArrayList<String> searchIngredients, ArrayList<String> searchNegIngredients){ recipeFileLoc = recipeFileLocation; searchIngredientsList = searchIngredients; searchNegativeIngredientsList = searchNegIngredients; recipe = new Recipe(); recipesList = new ArrayList<Recipe>(); try { String sCurrentLine; br = new BufferedReader(new FileReader(recipeFileLoc)); while ((sCurrentLine = br.readLine()) != null) { if (recipesList.size() > 50){ break; } parseLine(sCurrentLine); } // System.out.println(recipesList); } catch (IOException e) { System.out.println("RECIPE TXT FILE NOT FOUND, Please Try Again"); e.printStackTrace(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public void parseLine(String curLine) { String lineID = curLine.split(":")[0]; String lineVAL = curLine.split(": ")[1]; //System.out.println("lineID: " + lineID); //System.out.println("lineVAL: " + lineVAL); switch (lineID) { case "name": String theName = lineVAL; recipe.setName(theName); break; case "img_url": String url = lineVAL; recipe.setImageURL(url); break; case "recipe_url": String url1 = lineVAL; recipe.setRecipeURL(url1); break; case "ingredient": String ingred = lineVAL; recipe.addIngredient(lineVAL); break; case "calories": String cals = lineVAL; recipe.setCalories(Integer.parseInt(lineVAL)); break; case "nutrition": String[] vals = lineVAL.split(" "); Nutrient nutrient = new Nutrient(); if (vals[0].equals("Vitamin")) { nutrient.setName(vals[0] + " " + vals[1]); nutrient.setAmount(vals[2]); nutrient.setPercent(Integer.parseInt(vals[3].substring(0, vals[3].length() - 1))); } else { nutrient.setName(vals[0]); nutrient.setAmount(vals[1]); nutrient.setPercent(Integer.parseInt(vals[2].substring(0, vals[2].length() - 1))); } recipe.addNutrient(nutrient); break; case "nutritionF": String fat = lineVAL; String[] valsFats = lineVAL.split(" "); Fats fatC = new Fats(); fatC.setFat(valsFats[0]); fatC.setAmount(valsFats[1]); fatC.setPercent(Integer.parseInt(valsFats[2].substring(0, valsFats[2].length() - 1))); recipe.addFat(fatC); break; case "nutritionC": String carb = lineVAL; recipe.addCarb(carb); break; case "header": recipe = new Recipe(); break; case "footer": //System.out.println(recipe.containsIngredients(searchIngredientsList)); if (recipe.containsIngredients(searchIngredientsList)) { if (searchNegativeIngredientsList != null && !searchNegativeIngredientsList.isEmpty()) { if (!recipe.containsIngredients(searchNegativeIngredientsList)) { recipesList.add(recipe); } } else { recipesList.add(recipe); } } recipe = new Recipe(); //accelerateToNextRecipe(); break; } } /*private void accelerateToNextRecipe() { // TODO Auto-generated method stub String sCurrentLine; try{ sCurrentLine = br.readLine(); while(!sCurrentLine.equals("header: RECIPE")){ } }catch(IOException e){ e.printStackTrace(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } }*/ public ArrayList<Recipe> getRecipes(){ return recipesList; } }
package LogReader; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.filechooser.FileSystemView; public class LogExtractorViewer extends JFrame implements ActionListener { static JTextField t,t1,t2; static Frame f; static JButton b,b1,b2; static JLabel l; static JTextArea tArea; static JCheckBox c; LogExtractorViewer() { } public static void viewer() { f = new Frame("Unique Log Extractor"); f.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent windowEvent){System.exit(0);}}); //f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); f.setLocation((dim.width/2-f.getSize().width/2)-250, (dim.height/2-f.getSize().height/2)-100); l = new JLabel(" Input field Name "); l.setFont(new Font("Serif", Font.BOLD,13)); LogExtractorViewer te = new LogExtractorViewer(); b = new JButton("Extract"); b.setPreferredSize(new Dimension(90,20)); b.addActionListener(te); b1 = new JButton("Input File Path"); b1.setPreferredSize(new Dimension(125, 20)); b1.addActionListener(te); b2 = new JButton("Output File Path"); b2.setPreferredSize(new Dimension(125, 20)); b2.addActionListener(te); t = new JTextField(28); t1 = new JTextField(28); t2 = new JTextField(28); //JPanel p = new JPanel(new GridLayout(7, 2, 20, 4)); JPanel p = new JPanel(new FlowLayout()); p.setBorder(BorderFactory.createTitledBorder("Hello Arcsight V1.0: ")); c= new JCheckBox(); c.setText("Key-vale pair"); c.setSelected(true); c.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JCheckBox cb = (JCheckBox) event.getSource(); if (cb.isSelected()) { l.setText(" Input field Name "); } else { l.setText(" Input UniqueId "); } } }); //checkbox.setIcon(icon); p.add(t); p.add(b1); p.add(t1); p.add(b2); p.add(t2); p.add(l); p.add(b); p.add(c); f.add(p); f.setSize(500,250); f.show(); } public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("Extract")) { if(t.getText().equals("")|t1.getText().equals("")|t2.getText().equals("")) { JOptionPane.showMessageDialog(this,"Please Input", "Warning",JOptionPane.WARNING_MESSAGE); } else { MyFileReader.myReader(t.getText(),t1.getText(),t2.getText()); if(MyFileReader.flags==1) { JOptionPane.showMessageDialog(this,"Done!!!!!!","Successful",JOptionPane.PLAIN_MESSAGE); } else { JOptionPane.showMessageDialog(this,"Invalid Input!!!","Error",JOptionPane.ERROR_MESSAGE); } } } else if(s.equals("Output File Path")) { JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); int returnValue = jfc.showOpenDialog(null); //int returnValue = jfc.showSaveDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); t1.setText( selectedFile.getAbsolutePath()); } } else { JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); int returnValue = jfc.showOpenDialog(null); //int returnValue = jfc.showSaveDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); t.setText( selectedFile.getAbsolutePath()); } } } }
package com.tencent.mm.protocal; import com.tencent.mm.protocal.c.g; final class c$gc extends g { public c$gc() { super("preloadMiniProgramContacts", "preloadMiniProgramContacts", 303, false); } }
package model; import java.util.List; import java.util.Vector; import model.impl.GridPointImpl; public interface AccessPointNetwork { public Vector<AccessPoint> getAccessPoints(int levelnumber); public Vector<Vector<AccessPoint>> getAccessPoints(); public void addAccessPoint(AccessPoint ap); public SensorNode getApWithID(int ID); public boolean farEnough4E(double x,double y,int dist); public boolean refineGridLocationsAroundAPs(int grid_size, List<GridPoint[]>gridPointstemp); public int getTotalSize(); public void removeAllAccessPoints(); }
package am.itspace.newfeaturesinjava8.util; import am.itspace.newfeaturesinjava8.model.User; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; @Component public class UsersUtil { public static List<User> users(){ return Arrays.asList( new User(39,"valod"), new User(15,"poxos"), new User(24,"aram"), new User(15,"petros"), new User(15,"martiros"), new User(24,"poxos"), new User(39,"aram") ); } }
package com.epam.restaurant.controller.command.impl; import com.epam.restaurant.controller.command.Command; import com.epam.restaurant.controller.command.exception.CommandException; import com.epam.restaurant.controller.name.JspPageName; import com.epam.restaurant.entity.Dish; import com.epam.restaurant.entity.Order; import com.epam.restaurant.entity.OrderDish; import com.epam.restaurant.entity.User; import com.epam.restaurant.service.DishService; import com.epam.restaurant.service.OrderDishService; import com.epam.restaurant.service.OrderService; import com.epam.restaurant.service.exception.ServiceException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import static com.epam.restaurant.util.SessionUtil.*; import static com.epam.restaurant.controller.name.RequestParameterName.*; /** * Add dish to users order whose role USER. */ public class AddToOrderCommand implements Command { /** * Service provides work with database (order table) */ private static final OrderService orderService = OrderService.getInstance(); /** * Service provides work with database (dish table) */ private static final DishService dishService = DishService.getInstance(); /** * Service provides work with database (order_dish table) */ private static final OrderDishService orderDishService = OrderDishService.getInstance(); /** * At first, check session expiration. If it's expired, return login page. * If not, get from request user and his order. Create order if it still doesn't exist. * Get dish id from request and add corresponding dish to order. * If everything is fine, return concrete order page value. * * @return page to forward to * @throws CommandException if can't add to order */ @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws CommandException { String result = JspPageName.ORDER_JSP; if (sessionExpired(request)) { result = JspPageName.LOGIN_JSP; return result; } User currentUser = (User) request.getSession().getAttribute(USER); Order currentOrder = (Order) request.getSession().getAttribute(ORDER); try { long dishId = Long.parseLong(request.getParameter(DISH_ID)); if (currentOrder == null) { currentOrder = orderService.create(currentUser.getId(), new Date()); } OrderDish orderDish = orderDishService.create(dishId, currentOrder.getId(), 1); Dish dish = dishService.getById(dishId); orderDish.setDish(dish); currentOrder.getOrderDishes().add(orderDish); request.getSession().setAttribute(ORDER, currentOrder); } catch (ServiceException e) { e.printStackTrace(); throw new CommandException("Cant't execute AddToOrderCommand", e); } return result; } }
/* * Copyright © 2016, 2018 IBM Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.ibm.cloudant.kafka.connect; import com.ibm.cloudant.kafka.common.InterfaceConst; import com.ibm.cloudant.kafka.common.MessageKey; import com.ibm.cloudant.kafka.common.utils.ResourceBundleUtil; import org.apache.kafka.common.config.AbstractConfig; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigDef.Importance; import org.apache.kafka.common.config.ConfigDef.Type; import org.apache.kafka.common.config.ConfigDef.Width; import org.apache.log4j.Logger; import java.util.Map; public class CloudantSourceConnectorConfig extends AbstractConfig { private static Logger LOG = Logger.getLogger(CloudantSourceConnectorConfig.class); public static final String DATABASE_GROUP = "Database"; public static final String CLOUDANT_LAST_SEQ_NUM_DEFAULT = null; public static final ConfigDef CONFIG_DEF = baseConfigDef(); public static ConfigDef baseConfigDef() { return new ConfigDef() // Cloudant URL .define(InterfaceConst.URL, Type.STRING, Importance.HIGH, ResourceBundleUtil.get(MessageKey.CLOUDANT_CONNECTION_URL_DOC), DATABASE_GROUP, 1, Width.LONG, ResourceBundleUtil.get(MessageKey.CLOUDANT_CONNECTION_URL_DISP)) // Cloudant Username .define(InterfaceConst.USER_NAME, Type.STRING, Importance.HIGH, ResourceBundleUtil.get(MessageKey.CLOUDANT_CONNECTION_USR_DOC), DATABASE_GROUP, 1, Width.LONG, ResourceBundleUtil.get(MessageKey.CLOUDANT_CONNECTION_USR_DISP)) // Cloudant Password .define(InterfaceConst.PASSWORD, Type.PASSWORD, Importance.HIGH, ResourceBundleUtil.get(MessageKey.CLOUDANT_CONNECTION_PWD_DOC), DATABASE_GROUP, 1, Width.LONG, ResourceBundleUtil.get(MessageKey.CLOUDANT_CONNECTION_PWD_DISP)) // Cloudant last change sequence .define(InterfaceConst.LAST_CHANGE_SEQ, Type.STRING, CLOUDANT_LAST_SEQ_NUM_DEFAULT, Importance.LOW, ResourceBundleUtil.get(MessageKey.CLOUDANT_LAST_SEQ_NUM_DOC), DATABASE_GROUP, 1, Width.LONG, ResourceBundleUtil.get(MessageKey.CLOUDANT_LAST_SEQ_NUM_DOC)) // Kafka topic .define(InterfaceConst.TOPIC, Type.LIST, Importance.HIGH, ResourceBundleUtil.get(MessageKey.KAFKA_TOPIC_LIST_DOC), DATABASE_GROUP, 1, Width.LONG, ResourceBundleUtil.get(MessageKey.KAFKA_TOPIC_LIST_DISP)) // Whether to omit design documents .define(InterfaceConst.OMIT_DESIGN_DOCS, Type.BOOLEAN, false, Importance.LOW, ResourceBundleUtil.get(MessageKey.CLOUDANT_OMIT_DDOC_DOC), DATABASE_GROUP, 1, Width.NONE, ResourceBundleUtil.get(MessageKey.CLOUDANT_OMIT_DDOC_DISP)) // Whether to generate a struct Schema .define(InterfaceConst.USE_VALUE_SCHEMA_STRUCT, Type.BOOLEAN, false, Importance.MEDIUM, ResourceBundleUtil.get(MessageKey.CLOUDANT_STRUCT_SCHEMA_DOC), DATABASE_GROUP, 1, Width.NONE, ResourceBundleUtil.get(MessageKey.CLOUDANT_STRUCT_SCHEMA_DISP)) // Whether to flatten nested objects in the generated struct .define(InterfaceConst.FLATTEN_VALUE_SCHEMA_STRUCT, Type.BOOLEAN, false, Importance.MEDIUM, ResourceBundleUtil.get(MessageKey.CLOUDANT_STRUCT_SCHEMA_FLATTEN_DOC), DATABASE_GROUP, 1, Width.NONE, ResourceBundleUtil.get(MessageKey.CLOUDANT_STRUCT_SCHEMA_FLATTEN_DISP)); } public CloudantSourceConnectorConfig(Map<String, String> originals) { super(CONFIG_DEF, originals, false); } protected CloudantSourceConnectorConfig(ConfigDef subclassConfigDef, Map<String, String> originals) { super(subclassConfigDef, originals); } public static void main(String[] args) { System.out.println(CONFIG_DEF.toRst()); } }
package com.lin.paper.service.impl; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.lin.paper.bean.ScoreTable; import com.lin.paper.bean.UserInfo; import com.lin.paper.mapper.PSelectMapper; import com.lin.paper.pojo.PPaper; import com.lin.paper.pojo.PPaperExample; import com.lin.paper.pojo.PProgress; import com.lin.paper.pojo.PSelect; import com.lin.paper.pojo.PSelectExample; import com.lin.paper.pojo.PSelectExample.Criteria; import com.lin.paper.pojo.PSubject; import com.lin.paper.service.InfoService; import com.lin.paper.service.ProgressService; import com.lin.paper.service.SelectService; import com.lin.paper.service.SubjectService; import com.lin.paper.service.TaskService; import com.lin.paper.utils.IDUtils; /** * 选题的业务逻辑实现类 * @ * @date 2018年3月9日下午4:30:44 * @version 1.0 */ @Service public class SelectServiceImpl implements SelectService { @Value("${SUBJECT_SHOW_ROWS}") private Integer SUBJECT_SHOW_ROWS; //后台每页显示课题数据 @Resource private PSelectMapper selectMapper; @Resource private SubjectService subjectService; @Resource private ProgressService progressService; @Resource private TaskService taskService; @Resource private InfoService infoService; @Override public void saveSelect(PSelect select) { //插入数据 selectMapper.insertSelective(select); } @Override public List<PSubject> getSelectStatesByStu(List<PSubject> subjectList, String userid) { for (PSubject pSubject : subjectList) { PSelect select = getFirstSelectBySubjectid(pSubject.getSubjectid(), userid); if (select == null) { //没有选择 PSelect first = getFirstSelectBySubjectid(pSubject.getSubjectid(), ""); if (first != null) { //有没选的 pSubject.setSubjectstate(0); } else { //都选完了 pSubject.setSubjectstate(2); } } else { //已经选择 pSubject.setSubjectstate(1); if (select.getSelectstate()==1) { //通过 pSubject.setSubjectstate(3); } else if (select.getSelectstate()==2){ //未通过 pSubject.setSubjectstate(4); } /*else if (select.getSelectstate()==3){ //开始写作中 pSubject.setSubjectstate(8); }*/ } } return subjectList; } @Override public PSelect getFirstSelectBySubjectid(String Subjectid, String Stuid) { //查询选题列表 PSelectExample example = new PSelectExample(); //创建查询条件 Criteria criteria = example.createCriteria(); criteria.andSubjectidEqualTo(Subjectid); //课题 criteria.andStuidEqualTo(Stuid); //用户 //查询数据 List<PSelect> list = selectMapper.selectByExample(example); if (list != null && list.size()>0) { //有没选的 return list.get(0); } else { //都选完了 return null; } } @Override public void updateSelect(PSelect select) { //更新数据 selectMapper.updateByPrimaryKey(select); } @Override public PageInfo<PSelect> getSelectList(Integer page, String teachid) { List<PSubject> list2 = subjectService.getSubjectListByTeachid(teachid); List<String> subjectids = new ArrayList<>(); if (list2 != null) { for (PSubject subject : list2) { subjectids.add(subject.getSubjectid()); } } //查询选题列表 PSelectExample example = new PSelectExample(); //排序显示 example.setOrderByClause("subjectid DESC"); //分页处理:page第几页,rows多少行 PageHelper.startPage(page, SUBJECT_SHOW_ROWS); //查询条件 Criteria criteria = example.createCriteria(); criteria.andSubjectidIn(subjectids); criteria.andStuidNotEqualTo(""); //不为空 //查询数据 List<PSelect> list = selectMapper.selectByExample(example); //补全题目与学生的姓名 for (PSelect select : list) { //题目 select.setSubjectid(subjectService.getSubjectById(select.getSubjectid()).getSubjectname()); //学生 select.setStuid(infoService.getUserInfoById(select.getStuid()).getName()); } //创建一个返回值对象,设置数据 PageInfo<PSelect> pageInfo = new PageInfo<>(list); return pageInfo; } @Override public PSelect getSelectById(String selectid) { return selectMapper.selectByPrimaryKey(selectid); } @Override public String getTeachByStuid(String stuid) { //查询选题列表 PSelectExample example = new PSelectExample(); //查询条件 Criteria criteria = example.createCriteria(); criteria.andStuidEqualTo(stuid); //学号 ArrayList<Integer> list2 = new ArrayList<>(); list2.add(1); list2.add(3); criteria.andSelectstateIn(list2); //状态 //查询数据 List<PSelect> list = selectMapper.selectByExample(example); if (list != null && list.size()>0) { PSubject subject = subjectService.getSubjectById(list.get(0).getSubjectid()); if (subject != null) { return subject.getTeachid(); } } return null; } @Override public PSelect getSelectByStuAndState(String userid, int i) { //查询选题列表 PSelectExample example = new PSelectExample(); //查询条件 Criteria criteria = example.createCriteria(); criteria.andStuidEqualTo(userid); //学号 criteria.andSelectstateEqualTo(i); //状态 //查询数据 List<PSelect> list = selectMapper.selectByExample(example); if (list != null && list.size()>0) { return list.get(0); }else{ return null; } } @Override public PSelect startSelect(String subjectid, String teachid, String userid) { PSelect selectById = getFirstSelectBySubjectid(subjectid, userid); if (selectById == null) { PSelect select = new PSelect(); select.setCreatetime(new Date()); select.setUpdatetime(new Date()); select.setSelectid(IDUtils.getSelectId()); select.setSelectstate(1); select.setStuid(userid); select.setSubjectid(subjectid); select.setTaskid(taskService.getTaskByState(1).get(0).getTaskid()); //插入数据 saveSelect(select); } //1、删除选题表中该用户其他选题信息,2、修改选题的状态为写作中(3),3、修改课题的状态为8(写作中) //删除选题表中该用户其他选题信息 deleteOtherSelects(subjectid, userid); //修改选题的状态为写作中 selectById = getFirstSelectBySubjectid(subjectid, userid); if (selectById != null) { //开始进度内容:开题报告、一稿、二稿、三稿、定稿内容 //创建开题报告进度 String progressid = progressService.addProgress("开题报告", userid); selectById.setProgressid(progressid); selectById.setSelectstate(3); //写作中3 updateSelect(selectById); //更新数据 //修改课题的状态为8(写作中) PSubject subject = subjectService.getSubjectById(selectById.getSubjectid()); subject.setSubjectstate(8); //写作中 subjectService.updateSubject(subject); } return selectById; } /** * 删除选题表中该用户其他选题信息 * @param selectid * @param userid */ private void deleteOtherSelects(String subjectid, String userid) { //查询选题列表 PSelectExample example = new PSelectExample(); //查询条件 Criteria criteria = example.createCriteria(); criteria.andStuidEqualTo(userid); //学号 criteria.andSubjectidNotEqualTo(subjectid); //课题不为开始subjectid //删除数据 selectMapper.deleteByExample(example); } @Override public PageInfo<PSelect> getSelectListByLeader(Integer page) { //查询选题列表 PSelectExample example = new PSelectExample(); //排序显示 example.setOrderByClause("subjectid DESC"); //分页处理:page第几页,rows多少行 PageHelper.startPage(page, SUBJECT_SHOW_ROWS); //查询条件 Criteria criteria = example.createCriteria(); criteria.andSelectstateEqualTo(3); //写作中 criteria.andStuidNotEqualTo(""); //不为空 //查询数据 List<PSelect> list = selectMapper.selectByExample(example); //补全题目与学生的姓名 for (PSelect select : list) { PSubject subject = subjectService.getSubjectById(select.getSubjectid()); if (subject != null) { //指导老师:题目 select.setSubjectid(infoService.getUserInfoById(subject.getTeachid()).getName()+":"+subject.getSubjectname()); } //班级:学生 UserInfo info = infoService.getUserInfoById(select.getStuid()); select.setStuid(info.getClazz()+":"+info.getName()); //任务 select.setTaskid(taskService.getTaskById(select.getTaskid()).getTaskname()); } //创建一个返回值对象,设置数据 PageInfo<PSelect> pageInfo = new PageInfo<>(list); return pageInfo; } @Override public List<UserInfo> getUserListByTeach(String userid) { //查询选题集合 List<PSubject> subjects = subjectService.getSubjectListByTeachid(userid); List<String> subjectids = new ArrayList<>(); List<UserInfo> userInfos = null; if (subjects != null) { for (PSubject pSubject : subjects) { subjectids.add(pSubject.getSubjectid()); } } //查询选题列表 PSelectExample example = new PSelectExample(); //排序显示 example.setOrderByClause("subjectid DESC"); //查询条件 Criteria criteria = example.createCriteria(); criteria.andStuidNotEqualTo(""); //学生不为空 criteria.andSubjectidIn(subjectids); //课题ID //查询数据 List<PSelect> list = selectMapper.selectByExample(example); if (list != null && list.size()>0){ userInfos = new ArrayList<>(); for (PSelect pSelect : list) { UserInfo userInfo = infoService.getUserInfoById(pSelect.getStuid()); PSubject subject = subjectService.getSubjectById(pSelect.getSubjectid()); userInfo.setTitle(subject==null?"":subject.getSubjectname()); //设置选题信息 userInfos.add(userInfo); } } return userInfos; } @Override public List<ScoreTable> getScoreListByLeader() { List<ScoreTable> scoreTables = null; //查询选题列表 PSelectExample example = new PSelectExample(); //排序显示 example.setOrderByClause("updatetime"); Criteria criteria = example.createCriteria(); criteria.andScoreIsNotNull(); //成绩不为空 criteria.andSelectstateEqualTo(3); //状态为3 //查询数据 List<PSelect> list = selectMapper.selectByExample(example); if (list != null && list.size()>0) { scoreTables = new ArrayList<>(); //补全显示的数据 for (PSelect select : list) { ScoreTable scoreTable = new ScoreTable(); //学生信息 UserInfo student = infoService.getUserInfoById(select.getStuid()); //学生的课题信息 PSubject subject = subjectService.getSubjectById(select.getSubjectid()); //教师信息 UserInfo teacher = infoService.getUserInfoById(subject.getTeachid()); //保留两位小数 DecimalFormat dFormat=new DecimalFormat("#.00"); String score = dFormat.format(select.getScore()); String[] scores = score.split("\\."); String baseScore = scores[0]; String showScore = scores[1]; //设置数据 scoreTable.setStudent(student); scoreTable.setTeacher(teacher); scoreTable.setBaseScore(baseScore); scoreTable.setShowScore(showScore); scoreTable.setSubjectname(subject.getSubjectname()); scoreTables.add(scoreTable); } } return scoreTables; } }
package com.example.userportal.security; import com.example.userportal.domain.Customer; import com.example.userportal.repository.CustomerRepository; import com.example.userportal.security.jwt.UserPrincipal; import lombok.RequiredArgsConstructor; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @RequiredArgsConstructor public class CustomUserDetailsService implements UserDetailsService { final CustomerRepository customerRepository; @Transactional public UserDetails loadUserById(Integer id) { Customer customer = customerRepository.findOneWithAuthoritiesById(id).orElseThrow( () -> new UsernameNotFoundException("Not found user by id: " + id) ); return UserPrincipal.create(customer); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Customer customer = customerRepository.findOneByEmailIgnoreCase(username) .orElseThrow(() -> new UsernameNotFoundException("Not found user by username: " + username) ); return UserPrincipal.create(customer); } }
package controllers; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.validation.BindingResult; 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.servlet.ModelAndView; import services.AdvertisementService; import services.ArticleService; import services.FollowUpService; import services.NewspaperService; import services.UserService; import domain.Advertisement; import domain.Article; import domain.Newspaper; @Controller @RequestMapping("/article/user") public class ArticleUserController extends AbstractController { @Autowired ArticleService articleService; @Autowired UserService userService; @Autowired NewspaperService newspaperService; @Autowired FollowUpService followUpService; @Autowired AdvertisementService advertisementService; // Displaying @RequestMapping(value = "/display", method = RequestMethod.GET) public ModelAndView display(@RequestParam final int articleId) { ModelAndView res; final Article article = this.articleService.findOne(articleId); Assert.isTrue(article.getNewspaper().isFree() || article.getCreator().getId() == this.userService.findByPrincipal().getId()|| article.getNewspaper().getCreator().getId()== this.userService.findByPrincipal().getId()); Assert.isTrue(article.getMoment()!=null|| article.getCreator().getId() == this.userService.findByPrincipal().getId()|| article.getNewspaper().getCreator().getId()== this.userService.findByPrincipal().getId()); final String requestURI = "article/user/display.do"; final List<String> pictures = new ArrayList<String>(article.getPictureUrls()); final boolean hasPictures = !pictures.isEmpty(); final boolean hasFollowUps = !this.followUpService.findFollowUpsByArticle(articleId).isEmpty(); String bannerUrl=this.advertisementService.getRandomAdvertisementImage(article.getNewspaper().getId()); List<Advertisement> advs=new ArrayList<Advertisement>(this.advertisementService.findAdvertisementByNewspaperId(article.getNewspaper().getId())); int advertisementSize=advs.size(); res = new ModelAndView("article/display"); res.addObject("bannerUrl", bannerUrl); res.addObject("advertisementSize", advertisementSize); res.addObject("article", article); res.addObject("pictures", pictures); res.addObject("hasPictures", hasPictures); res.addObject("hasFollowUps", hasFollowUps); res.addObject("requestURI", requestURI); return res; } @RequestMapping(value = "/list-editable", method = RequestMethod.GET) public ModelAndView listMarked() { ModelAndView res; final Collection<Article> articles = this.articleService.findEditableArticlesByUser(); final String requestURI = "article/user/list-editable.do"; res = new ModelAndView("article/list"); res.addObject("articles", articles); res.addObject("requestURI", requestURI); return res; } //Creating @RequestMapping(value = "/create", method = RequestMethod.GET) public ModelAndView create() { final ModelAndView res; final Article a = this.articleService.createArticle(); res = this.createEditModelAndView(a); return res; } // //Editing @RequestMapping(value = "/edit", method = RequestMethod.GET) public ModelAndView edit(@RequestParam final int articleId) { ModelAndView res; Article a; a = this.articleService.findOne(articleId); Assert.isTrue(a.getCreator().getId() == this.userService.findByPrincipal().getId()); Assert.isTrue(a.isFinalMode() == false); res = this.createEditModelAndView(a); return res; } @RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save") public ModelAndView save(final Article a, final BindingResult binding) { ModelAndView res; final Article article = this.articleService.reconstruct(a, binding); if (binding.hasErrors()) res = this.createEditModelAndView(article); else try { this.articleService.save(article); res = new ModelAndView("redirect:list-editable.do"); } catch (final Throwable oops) { res = this.createEditModelAndView(article, "article.commit.error"); } return res; } @RequestMapping(value = "/list-published", method = RequestMethod.GET) public ModelAndView listPublished() { ModelAndView res; final Collection<Article> articles = this.articleService.findPublishedArticlesByUser(this.userService.findByPrincipal().getId()); final String requestURI = "article/user/list-published.do"; res = new ModelAndView("article/list"); res.addObject("articles", articles); res.addObject("requestURI", requestURI); return res; } //Ancillary methods protected ModelAndView createEditModelAndView(final Article a) { return this.createEditModelAndView(a, null); } protected ModelAndView createEditModelAndView(final Article a, final String messageCode) { ModelAndView res; res = new ModelAndView("article/edit"); final Collection<Newspaper> newspapers = this.newspaperService.findNotPublicatedNewspaper(); res.addObject("article", a); res.addObject("newspapers", newspapers); return res; } }
package com.example.todo.service; import com.example.todo.model.User; import com.example.todo.repository.UserRepository; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Collections; @Service @RequiredArgsConstructor(onConstructor = @__({@Autowired,@NonNull})) public class AppUserDetailsService implements UserDetailsService { private final UserRepository userRepository; @Override public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) throw new UsernameNotFoundException(username); return new org.springframework.security.core.userdetails.User( user.getUsername() , user.getPassword(), Collections.emptyList() ); } }
package com.shakeboy.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.shakeboy.mapper.UArticleMapper; import com.shakeboy.pojo.UArticle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UArticleService { @Autowired private UArticleMapper uArticleMapper; // 根据用户id查询所有文章 public List<UArticle> getAllArticleById(int user_id){ QueryWrapper<UArticle> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("user_id",user_id); return uArticleMapper.selectList(queryWrapper); } // 用户写文章 public Boolean writeArticle(int user_id,String uarticle_name,String uarticle_content){ UArticle article = new UArticle(); article.setUserId(user_id); article.setUarticleName(uarticle_name); article.setUarticleContent(uarticle_content); int i = uArticleMapper.insert(article); return i!=0; } }
package com.pineapple.mobilecraft.utils; /** * Created by yihao on 15/3/10. */ public abstract class SyncCallback<T> { private Object mLock = new Object(); T mResult = null; public T executeBegin() { // Thread t = new Thread(new Runnable() { // @Override // public void run() { // // } // }); // t.start(); // // try { // Thread.currentThread().sleep(500); // } catch (InterruptedException e) { // e.printStackTrace(); // } executeImpl(); synchronized (mLock) { try { mLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } return mResult; } public abstract void executeImpl(); /** * 记得在executeImpl的回调中调用onResult方法,否则会卡住 * @param result */ protected void onResult(T result) { mResult = result; synchronized (mLock) { mLock.notify(); } } }
package ccnMultiChat.UI; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JTextField; public class FormLogin extends JDialog { private static final long serialVersionUID = 1L; private JTextField _typedText; private String _username = ""; public String getUsername() { return _username; } public boolean isUsernameValid() { return !_username.equals(""); } public FormLogin() { super((Window)null); setModal(true); // User interface _typedText = new JTextField(32); initForm(); setTitle("Login"); setSize(400, 90); setResizable(false); setLocationRelativeTo(null); setVisible(true); } private void initForm() { JPanel panelY = new JPanel(); panelY.setLayout(new BoxLayout(panelY, BoxLayout.Y_AXIS)); panelY.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); _typedText.setMinimumSize(new Dimension(360, 25)); _typedText.setMaximumSize(new Dimension(360, 25)); _typedText.setPreferredSize(new Dimension(360, 25)); _typedText.requestFocusInWindow(); panelY.add(_typedText, BorderLayout.NORTH); JPanel panelX = new JPanel(); panelX.setLayout(new BoxLayout(panelX, BoxLayout.X_AXIS)); JButton btnCheck = new JButton("Validar"); btnCheck.setMinimumSize(new Dimension(180, 25)); btnCheck.setMaximumSize(new Dimension(180, 25)); btnCheck.setPreferredSize(new Dimension(180, 25)); btnCheck.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { checkUsername(); } }); panelX.add(btnCheck); JButton btnCancel = new JButton("Cancelar"); btnCancel.setMinimumSize(new Dimension(180, 25)); btnCancel.setMaximumSize(new Dimension(180, 25)); btnCancel.setPreferredSize(new Dimension(180, 25)); btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { dispose(); } }); panelX.add(btnCancel); panelY.add(panelX, BorderLayout.SOUTH); setContentPane(panelY); } private void checkUsername() { boolean valid = true; String error = ""; if (_typedText.getText().trim().equals("")) { valid = false; error = "Debe contener al menos 1 caracter"; } else if (_typedText.getText().trim().contains(" ")) { valid = false; error = "No puede contener espacios en blanco"; } if(valid) { _username = _typedText.getText().trim(); dispose(); } else { String text = "Introduzca un nombre válido"; if (!error.equals("")) text += ": " + error; Utils.showMessage(text); } } }
package com.example.shashankshekhar.application3s1.Map; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.example.shashankshekhar.application3s1.R; import com.example.shashankshekhar.smartcampuslib.HelperClass.CommonUtils; public class MoteProperties extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mote_properties); Motes mote = (Motes)getIntent().getSerializableExtra("moteObj"); CommonUtils.printLog("mote id: " + mote.getSensorId()); TextView source = (TextView)findViewById(R.id.text_view8); String sourceString = "<b>Source:</b> " + mote.getSource(); source.setText(Html.fromHtml(sourceString)); TextView type = (TextView)findViewById(R.id.text_view9); sourceString = "<b>Type:</b> " + mote.getType(); type.setText(Html.fromHtml(sourceString)); TextView sensorId = (TextView)findViewById(R.id.text_view1); sourceString = "<b>Mote Id:</b> " + Integer.toString(mote.getSensorId()); sensorId.setText(Html.fromHtml(sourceString)); TextView geoLocation = (TextView)findViewById(R.id.text_view2); sourceString = "<b>Location:</b> "+ mote.getLocation().toDoubleString(); geoLocation.setText(Html.fromHtml(sourceString)); TextView platform = (TextView)findViewById(R.id.text_view3); sourceString = "<b>Platform:</b> "+ mote.getPlatform(); platform.setText(Html.fromHtml(sourceString)); TextView frequency = (TextView)findViewById(R.id.text_view4); sourceString = "<b>Frequency:</b> "+mote.getFrequency(); frequency.setText(Html.fromHtml(sourceString)); TextView channel = (TextView)findViewById(R.id.text_view5); sourceString = "<b>Channel:</b> "+Integer.toString(mote.getChannel()); channel.setText(Html.fromHtml(sourceString)); TextView topic = (TextView)findViewById(R.id.text_view6); sourceString = "<b>Telemetry Topic:</b> "+mote.getTelemetryTopic(); topic.setText(Html.fromHtml(sourceString)); TextView url= (TextView)findViewById(R.id.text_view7); sourceString = "<b>Url:</b> "+mote.getWebPageUrlString(); url.setText(Html.fromHtml(sourceString)); } public void showGraph (View view){ return; } }