text stringlengths 10 2.72M |
|---|
package com.rankytank.client.gui;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.jg.core.client.ui.SuggestionBoxUi;
import com.jg.core.client.ui.TextBoxUi;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
public class TeamUI extends FlowPanel implements Navigator {
private String[] suggestionStartTexts;
private List<ChosenPlayer> chosenPlayerUIs = new ArrayList<ChosenPlayer>();
private FlowPanel chosenPlayersPanel = new FlowPanel();
private AddResultPopUp parent;
private MultiWordSuggestOracle oracle;
private PlayerSuggetsBox suggestBox;
private String teamColor;
private boolean homeTeam;
private SuggestionBoxUi suggester;
public TeamUI(AddResultPopUp parent, MultiWordSuggestOracle or, String[] defaultTexts, boolean homeTeam) {
this.setWidth("310px");
this.teamColor = homeTeam ? Colors.GREEN : Colors.BLUE;
this.homeTeam = homeTeam;
this.parent = parent;
this.oracle = or;
this.suggestionStartTexts = defaultTexts;
setStyleName("teamUI");
add(chosenPlayersPanel);
add(getSuggester());
//getSuggestBox().getElement().getStyle().setMarginBottom(10, Style.Unit.PX);
chosenPlayersPanel.setStyleName("chosenPlayerPanel");
}
public SuggestionBoxUi getSuggester() {
if (suggester == null) {
suggester = new SuggestionBoxUi(getSuggestBox(), suggestionStartTexts[0]);
suggester.getElement().getStyle().setPaddingBottom(20, Style.Unit.PX);
}
return suggester;
}
public PlayerSuggetsBox getSuggestBox() {
if (suggestBox == null) {
suggestBox = new PlayerSuggetsBox(oracle, suggestionStartTexts, homeTeam);
suggestBox.addKeyDownHandler(new KeyDownHandler() {
public void onKeyDown(KeyDownEvent event) {
keyDownInSuggestBox(event);
}
});
suggestBox.addKeyUpHandler(new KeyUpHandler() {
public void onKeyUp(KeyUpEvent event) {
keyUpInSuggestBox(event);
}
});
suggestBox.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
public void onSelection(SelectionEvent<SuggestOracle.Suggestion> event) {
playerSelected(event.getSelectedItem().getReplacementString());
}
});
suggestBox.getValueBox().addFocusHandler(new FocusHandler() {
public void onFocus(FocusEvent event) {
handleFocus();
}
});
suggestBox.getValueBox().addBlurHandler(new BlurHandler() {
public void onBlur(BlurEvent event) {
handleBlur();
}
});
}
return suggestBox;
}
private void keyUpInSuggestBox(KeyUpEvent event) {
styleSuggestionBox();
}
private void handleBlur() {
styleSuggestionBox();
}
private void keyDownInSuggestBox(KeyDownEvent event) {
int keycode = event.getNativeEvent().getKeyCode();
if (getSuggestBox().isSuggestionListShowing()) {
if (keycode == KeyCodes.KEY_ESCAPE) {//ESC
getSuggestBox().hideSuggestionList();
}
else if (keycode == KeyCodes.KEY_UP) {//arrow up
final String s = getSuggestBox().getText();
if (s == null || s.equals("")) {
//ignore
}
else {
Timer t = new Timer() {
@Override
public void run() {
getSuggestBox().getValueBox().setCursorPos(s.length());
}
};
t.schedule(50);
}
}
}
}
public void handleFocus() {
styleSuggestionBox();
}
public void styleSuggestionBox(){
String text = getSuggestBox().getText();
if(text == null || text.equals("")){
styleEmptySuggestionBox();
getSuggestBox().hideSuggestionList();
}
}
private void styleEmptySuggestionBox() {
if(chosenPlayerUIs.isEmpty()){
getSuggester().setEmptyText(suggestionStartTexts[0]);
}
else if(chosenPlayerUIs.size() == 1){
getSuggester().setEmptyText(suggestionStartTexts[1]);
}
else{
getSuggester().setEmptyText(suggestionStartTexts[2]);
}
}
public void playerSelected(String playerName) {
ChosenPlayer playerUI = new ChosenPlayer(playerName, this);
chosenPlayersPanel.add(playerUI);
chosenPlayerUIs.add(playerUI);
getSuggestBox().getValueBox().setText("");
styleSuggestionBox();
parent.style();
}
public void delete(ChosenPlayer w) {
getSuggestBox().getValueBox().setFocus(false);
chosenPlayerUIs.remove(w);
w.removeFromParent();
getSuggestBox().getValueBox().setFocus(true);
parent.style();
}
public String getTeamColor() {
return teamColor;
}
public void styleWon(){
for (ChosenPlayer p : chosenPlayerUIs) {
styleWon(p);
}
}
public void styleLost(){
for (ChosenPlayer p : chosenPlayerUIs) {
styleLost(p);
}
}
public void styleNormal(){
for (ChosenPlayer p : chosenPlayerUIs) {
styleNormal(p);
}
}
public void styleNormal(ChosenPlayer p){
Style style = p.getLabel().getElement().getStyle();
style.setColor(getTeamColor());
chosenPlayersPanel.getElement().getStyle().setBackgroundColor("white");
}
public void styleWon(ChosenPlayer p){
Style style = p.getLabel().getElement().getStyle();
style.setColor(getTeamColor());
chosenPlayersPanel.getElement().getStyle().setBackgroundColor("#ffb200");
}
public void styleLost(ChosenPlayer p){
Style style = p.getLabel().getElement().getStyle();
style.setColor("grey");
chosenPlayersPanel.getElement().getStyle().setBackgroundColor("white");
}
}
|
package com.devpmts.dropaline.ui;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import com.devpmts.DevsLogger;
import com.devpmts.dropaline.api.AuthenticationException;
import com.devpmts.dropaline.api.PimApi;
import com.devpmts.dropaline.textLine.PimItem;
import com.devpmts.util.StringUtil;
public class JavaConsoleUserInterface implements UserInterface {
@Override
public void requestCredentialsFromUser(PimApi pimApi) {
if (!pimApi.authenticator().isAuthenticated()) {
presentMessageToUser("Enter credentials", "Please type your task providers username and password");
String username = readLine();
String password = readLine();
try {
pimApi.authenticator().setCredentials(username, password);
} catch (AuthenticationException e) {
handleAuthenticationFailed(pimApi, e);
}
}
pimApi.authenticator().attemptAuthentication();
}
@Override
public void handleSuccessfulDelivery(List<PimItem> items) {
consoleOut("The following items were sent successfully:");
items.forEach(pimItem -> consoleOut(pimItem.getHumanReadableIdentifier()));
consoleOut();
}
@Override
public void handleAuthenticationFailed(PimApi api, AuthenticationException ae) {
consoleOut("Authentication error. Do you want to try again? (y/n)");
if (readLine().equalsIgnoreCase("y")) {
requestCredentialsFromUser(api);
}
}
private String readLine() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
return reader.readLine();
} catch (IOException e) {
DevsLogger.log("no console input");
return "";
}
}
@Override
public void presentMessageToUser(String title, String message) {
if (!StringUtil.isEmpty(title)) {
consoleOut(title);
underline(title);
}
consoleOut(message);
}
@Override
public void preparePimItemTransfer(PimItem item) {
}
private void underline(String line) {
char[] titleUnderLine = new char[line.length()];
Arrays.fill(titleUnderLine, '#');
consoleOut(new String(titleUnderLine));
}
private void consoleOut(String... lines) {
Arrays.stream(lines).forEach(line -> System.out.println(line));
}
@Override
public String getTextLine() {
assert false;
return null;
}
}
|
package org.tum.project.dashboard_controller.simulationPane;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jfoenix.controls.*;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.tum.project.bean.ProjectInfo;
import org.tum.project.dashboard_controller.DashBoardController;
import org.tum.project.dashboard_controller.SimulationController;
import org.tum.project.dataservice.FifoSizeService;
import org.tum.project.dataservice.FlitTraceService;
import org.tum.project.dataservice.FlowLatencyService;
import org.tum.project.dataservice.FlowPacketLatencyService;
import org.tum.project.login_controller.MenusHolderController;
import org.tum.project.thread.TaskExecutorPool;
import org.tum.project.utils.CefModifyUtils;
import org.tum.project.utils.SimulationUtils;
import org.tum.project.utils.Utils;
import org.tum.project.utils.xmlUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;
/**
* project setting class
* Created by heylbly on 17-6-4.
*/
public class SimulationProjectSettingController implements Initializable {
@FXML
private JFXButton btnSimulation;
@FXML
private JFXRadioButton rb_new;
@FXML
private JFXRadioButton rb_load;
@FXML
private JFXComboBox<String> cb_file;
@FXML
private JFXTextField et_loadFactor;
@FXML
private JFXTextField et_frequency;
@FXML
private JFXTextField et_dbName;
@FXML
private JFXTextField et_ftName;
@FXML
private JFXTextField et_fileName;
@FXML
private JFXTextField et_mtName;
@FXML
private JFXTextField et_fftName;
@FXML
private JFXTextField et_cefFile;
@FXML
private JFXTextField et_testBench;
@FXML
private JFXButton btn_analysis;
private File xmlFile;
private HashMap<String, ProjectInfo> infosMap;
/**
* select default test bench path
*
* @param actionEvent
*/
public void loadDefaultTestBenchPathAction(ActionEvent actionEvent) {
et_cefFile.setEditable(false);
et_testBench.setEditable(false);
String cefPath = Utils.readPropValue("CefFilePath");
String saveCppPath = Utils.readPropValue("SaveCppPath");
et_cefFile.setText(cefPath);
et_testBench.setText(saveCppPath);
}
class SimulationTask implements Runnable {
@Override
public void run() {
try {
System.out.println("start simulation");
btnSimulation.setDisable(true);
SimulationProgressController simulationProgressController = (SimulationProgressController) SimulationController.getControllerInstance(SimulationProgressController.class.getName());
simulationProgressController.clear();
simulationProgressController.startAnimation1("Checking for Start");
//Collect the necessary path information
SimulationPathSettingController simulationPathSettingController = (SimulationPathSettingController) SimulationController.getControllerInstance(SimulationPathSettingController.class.getName());
String[] simulationPath = simulationPathSettingController.getSimulationPath();
//Collect the necessary simulation dank bank information
String db_name = et_dbName.getText().toLowerCase();
String mt_name = et_mtName.getText().toLowerCase();
String ft_name = et_ftName.getText().toLowerCase();
String fft_name = et_fftName.getText().toLowerCase();
if (xmlUtils.hasExecute(db_name)) {
// directAnalysis();
// System.out.println("analysis has executed, direct read database");
Platform.runLater(() -> {
CefModifyUtils.alertDialog("this simulation has been executed, pls use direct analysis button");
simulationProgressController.clear();
btnSimulation.setDisable(false);
});
return;
}
if (et_loadFactor.getText() == null || et_frequency.getText() == null || et_dbName.getText() == null || et_mtName.getText() == null || et_ftName.getText() == null || et_fftName.getText() == null) {
Platform.runLater(() -> {
CefModifyUtils.alertDialog("Edit Text cant be null");
btnSimulation.setDisable(false);
simulationProgressController.clear();
});
return;
}
String loadFactor = et_loadFactor.getText();
String sampleFrequency = et_frequency.getText();
//Collect the necessary cef model and save test bench test c++ file path
String cefFilePath = et_cefFile.getText();
String testBenchSavePath = et_testBench.getText();
System.out.println("start collect information");
simulationProgressController.startAnimation2("Collecting\n" + "Info\n");
ProjectInfo info = new ProjectInfo();
info.setSimulationFile(et_fileName.getText().toLowerCase());
info.setDataBankName(db_name);
info.setModuleTableName(mt_name);
info.setFifoTableName(ft_name);
info.setFastfifoTabelName(fft_name);
info.setLoadFactor(loadFactor);
info.setSampleFrequency(sampleFrequency);
//only when the new project is active, then write the project info to the app intern
if (rb_new.isSelected() && (!rb_load.isSelected())) {
xmlUtils.writeToDocument(info);
}
//write the relative information to the json file in the simulation path.
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
String parametersPath = simulationPath[0] + "/params.txt";
try {
FileWriter writer = new FileWriter(parametersPath);
writer.write(info.getSimulationFile() + "\n");
writer.write(info.getDataBankName() + "\n");
writer.write("module_simulation_" + info.getModuleTableName().toLowerCase() + "\n");
writer.write("fifo_simulation_" + info.getFifoTableName().toLowerCase() + "\n");
writer.write("fastfiforw_simulation_" + info.getFastfifoTabelName().toLowerCase() + "\n");
writer.write(info.getLoadFactor() + "\n");
writer.write(info.getSampleFrequency() + "\n");
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
//generate the test bench c++ file
System.out.println("Start generate c++ file");
simulationProgressController.startAnimation3("Generate\n" + "file\n");
SimulationUtils.generateTestFile(cefFilePath, testBenchSavePath);
//compile the module
System.out.println("start compile");
simulationProgressController.startAnimation4("Start\n" + "to\n" + "compile\n");
SimulationUtils.compile(simulationPath[0]);
//execute the simulation
System.out.println("start simulation");
simulationProgressController.startAnimation5("Start\n" + "to\n" + "simulate\n");
String cmd = "./nocSim " + et_loadFactor.getText();
// String cmd = "./nocSim ";
SimulationUtils.execute(cmd, simulationPath[0], simulationPath[1]);
Utils.updatePropValue("CefFilePath", cefFilePath);
Utils.updatePropValue("SaveCppPath", testBenchSavePath);
//start to analyze
System.out.println("start to analyze");
simulationProgressController.startAnimation6("Start\n" + "to\n" + "analyze\n");
//execute the analysis for flow latency
//module table name list is needed for the execution
FlowLatencyService flowLatencyInstance = (FlowLatencyService) DashBoardController.getDataServiceInstance(FlowLatencyService.class.getName());
List<String> moduleTableList = new ArrayList<>();
moduleTableList.add("module_simulation_" + mt_name);
//flowLatencyInstance.startAnalyze(moduleTableList, db_name);
//moduleTableList.add("module_simulation_2017_6_10_14_21_58");
flowLatencyInstance.startAnalyze(moduleTableList, db_name);
//execute the analysis for flow packet details
//module table name list is needed for the execution
FlowPacketLatencyService flowPacketLatencyService = (FlowPacketLatencyService) DashBoardController.getDataServiceInstance(FlowPacketLatencyService.class.getName());
flowPacketLatencyService.startAnalyze(moduleTableList, db_name);
//execute the analysis for fifo size analyse details
//fifo size table name list is needed for the execution
FifoSizeService fifoSizeService = (FifoSizeService) DashBoardController.getDataServiceInstance(FifoSizeService.class.getName());
List<String> fifoTabelList = new ArrayList<>();
fifoTabelList.add("fifo_simulation_" + ft_name);
//fifoTabelList.add("fifo_simulation_2017_6_10_14_21_58");
fifoSizeService.startAnalyze(fifoTabelList, db_name);
//execute the analysis for trace flits details
FlitTraceService flitTraceService = (FlitTraceService) DashBoardController.getDataServiceInstance(FlitTraceService.class.getName());
List<String> fastfifoTabelList = new ArrayList<>();
fastfifoTabelList.add("fastfiforw_simulation_" + fft_name);
//fastfifoTabelList.add("fastfiforw_simulation_2017_6_10_14_21_58");
flitTraceService.startAnalyze(fastfifoTabelList, db_name);
btnSimulation.setDisable(false);
//load the simulation to the default
Utils.updatePropValue("ModelsNocPath", simulationPath[0]);
Utils.updatePropValue("SystemCLibPath", simulationPath[1]);
//finish
System.out.println("finish");
simulationProgressController.stopAnimation6();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception simulation aborting");
SimulationProgressController simulationProgressController = (SimulationProgressController) DashBoardController.getDataServiceInstance(SimulationProgressController.class.getName());
simulationProgressController.stopALL();
simulationProgressController.setError("An exception occurs \n" +
"Emulation is terminated");
btnSimulation.setDisable(false);
}
}
}
@FXML
public void startSimulationAction(ActionEvent actionEvent) {
//simulationThread = new Thread(new SimulationTask());
//simulationThread.start();
TaskExecutorPool.getExecutor().execute(new SimulationTask());
}
@FXML
public void startDirectlyAnalysis(ActionEvent actionEvent) {
directAnalysis();
}
/**
* direct execute the analysis
* avoid repeat to compile and execute the simulation and avoid to write data always to the database
*/
private void directAnalysis() {
SimulationProgressController simulationProgressController = (SimulationProgressController) SimulationController.getControllerInstance(SimulationProgressController.class.getName());
try {
//Collect the necessary simulation dank bank information
String db_name = et_dbName.getText().toLowerCase();
String mt_name = et_mtName.getText().toLowerCase();
String ft_name = et_ftName.getText().toLowerCase();
String fft_name = et_fftName.getText().toLowerCase();
//execute the analysis for flow latency
//module table name list is needed for the execution
FlowLatencyService flowLatencyInstance = (FlowLatencyService) DashBoardController.getDataServiceInstance(FlowLatencyService.class.getName());
List<String> moduleTableList = new ArrayList<>();
moduleTableList.add("module_simulation_" + mt_name);
//flowLatencyInstance.startAnalyze(moduleTableList, db_name);
//moduleTableList.add("module_simulation_2017_6_10_14_21_58");
flowLatencyInstance.startAnalyze(moduleTableList, db_name);
//execute the analysis for flow packet details
//module table name list is needed for the execution
FlowPacketLatencyService flowPacketLatencyService = (FlowPacketLatencyService) DashBoardController.getDataServiceInstance(FlowPacketLatencyService.class.getName());
flowPacketLatencyService.startAnalyze(moduleTableList, db_name);
//execute the analysis for fifo size analyse details
//fifo size table name list is needed for the execution
FifoSizeService fifoSizeService = (FifoSizeService) DashBoardController.getDataServiceInstance(FifoSizeService.class.getName());
List<String> fifoTabelList = new ArrayList<>();
fifoTabelList.add("fifo_simulation_" + ft_name);
//fifoTabelList.add("fifo_simulation_2017_6_10_14_21_58");
fifoSizeService.startAnalyze(fifoTabelList, db_name);
//execute the analysis for trace flits details
FlitTraceService flitTraceService = (FlitTraceService) DashBoardController.getDataServiceInstance(FlitTraceService.class.getName());
List<String> fastfifoTabelList = new ArrayList<>();
fastfifoTabelList.add("fastfiforw_simulation_" + fft_name);
//fastfifoTabelList.add("fastfiforw_simulation_2017_6_10_14_21_58");
flitTraceService.startAnalyze(fastfifoTabelList, db_name);
//finish
System.out.println("finish");
Platform.runLater(() -> simulationProgressController.directlyAnalysisSuccess());
} catch (Exception e) {
e.printStackTrace();
Platform.runLater(() -> simulationProgressController.setError("analysis failed"));
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
System.out.println("SimulationProjectSettingController initialize");
btn_analysis.setDisable(true);
btnSimulation.setDisable(true);
SimulationController.registerSelfToController(this, getClass().getName());
//find the xml file, from this file, we can find the project information
//if file does't exist, then create it.
//if file already exist, then do nothing.
xmlFile = xmlUtils.createAndGetProjectXmlFile();
//add the click item listener to the item of combo box
cb_file.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
//item click, set content to the UI
ProjectInfo info = infosMap.get(newValue);
if (info == null) {
return;
}
et_fileName.setText(info.getSimulationFile());
et_dbName.setText(info.getDataBankName());
et_mtName.setText(info.getModuleTableName());
et_ftName.setText(info.getFifoTableName());
et_fftName.setText(info.getFastfifoTabelName());
et_loadFactor.setText(info.getLoadFactor());
et_frequency.setText(info.getSampleFrequency());
});
et_cefFile.setOnMouseClicked(event -> {
File file = Utils.openFileChooser("open", MenusHolderController.getDashBoardStage());
if (file != null) {
et_cefFile.setText(file.getAbsolutePath());
System.out.println(file.getAbsolutePath());
}
});
et_testBench.setOnMouseClicked(event -> {
File file = Utils.openDirectorChooser("open", MenusHolderController.getDashBoardStage());
if (file != null) {
et_testBench.setText(file.getAbsolutePath());
System.out.println(file.getAbsolutePath());
}
});
}
/**
* loading project information from existing xml file into the combo box
*/
private void loadingIntoComboBox() {
try {
cb_file.getItems().clear();
Document document = xmlUtils.readDocument(xmlFile.getAbsolutePath());
ArrayList<ProjectInfo> infos = xmlUtils.getAllProjectFromDocument(document);
infosMap = new HashMap<>();
for (ProjectInfo info : infos) {
cb_file.getItems().add(info.getSimulationFile() + ": " + info.getDataBankName());
infosMap.put(info.getSimulationFile(), info);
}
cb_file.show();
} catch (MalformedURLException | DocumentException e) {
e.printStackTrace();
}
}
@FXML
void rb_loadAction(ActionEvent event) {
btn_analysis.setDisable(false);
btnSimulation.setDisable(true);
setEditTextEnable(false);
loadingIntoComboBox();
}
@FXML
void rb_newAction(ActionEvent event) {
btn_analysis.setDisable(true);
btnSimulation.setDisable(false);
setEditTextEnable(true);
clearEditTextContent();
}
/**
* enable or not enable all edit text that Project Setting include
*
* @param editTextEnable whether enable or not enable
*/
public void setEditTextEnable(boolean editTextEnable) {
et_fileName.setEditable(editTextEnable);
et_dbName.setEditable(editTextEnable);
et_mtName.setEditable(editTextEnable);
et_fftName.setEditable(editTextEnable);
et_ftName.setEditable(editTextEnable);
et_loadFactor.setEditable(editTextEnable);
et_frequency.setEditable(editTextEnable);
}
/**
* clear the content of all the edit text field
*/
public void clearEditTextContent() {
et_fileName.setText(null);
et_dbName.setText(null);
et_mtName.setText(null);
et_fftName.setText(null);
et_ftName.setText(null);
et_loadFactor.setText(null);
et_frequency.setText(null);
}
}
|
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.RectHV;
import edu.princeton.cs.algs4.StdDraw;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class PointSET {
private final Set<Point2D> points = new TreeSet<>();
/**
* is the set empty?
*
* @return true iff empty
*/
public boolean isEmpty() {
return points.isEmpty();
}
/**
* Number of points in the set
*
* @return number of points in set
*/
public int size() {
return points.size();
}
/**
* Add the point to the set (if it is not already in the set)
*
* @param p point to add
*/
public void insert(Point2D p) {
points.add(p);
}
/**
* Does the set contain point p?
*/
public boolean contains(Point2D p) {
if (p == null)
throw new NullPointerException();
return points.contains(p);
}
/**
* Draw all points to standard draw
*/
public void draw() {
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.setPenRadius(0.01);
StdDraw.enableDoubleBuffering();
for (final Point2D p : points)
p.draw();
StdDraw.pause(50);
}
/**
* All points that are inside the rectangle
*
* @param rect query rectangle
* @return points inside
*/
public Iterable<Point2D> range(final RectHV rect) {
if (rect == null)
throw new NullPointerException();
final List<Point2D> inside = new ArrayList<>();
for (final Point2D point : points)
if (rect.contains(point))
inside.add(point);
return inside;
}
/**
* A nearest neighbor in the set to point p; null if the set is empty
*
* @param p the point
* @return neighbor
*/
public Point2D nearest(final Point2D p) {
if (p == null)
throw new NullPointerException();
Point2D nearest = null;
double dist = Double.MAX_VALUE;
for (final Point2D point : points)
if (nearest == null || Double.compare(p.distanceTo(point), dist) < 0) {
nearest = point;
dist = p.distanceTo(point);
}
return nearest;
}
}
|
package ca.mcgill.ecse223.kingdomino.controller;
import java.util.ArrayList;
import java.util.List;
import ca.mcgill.ecse223.kingdomino.KingdominoApplication;
import ca.mcgill.ecse223.kingdomino.model.Game;
import ca.mcgill.ecse223.kingdomino.model.Player;
public class QueryMethodController {
public static String getWinner() {
Game game=KingdominoApplication.getKingdomino().getCurrentGame();
Player winner=null;
int score =0;
for(Player p:game.getPlayers()) {
if(p.getTotalScore()>score) {
score=p.getTotalScore();
winner=p;
}
}
return winner.getColor().toString();
}
public static List<TOPlayer> getPlayers() {
ArrayList<TOPlayer> list = new ArrayList<TOPlayer>();
Game game=KingdominoApplication.getKingdomino().getCurrentGame();
for(Player p:game.getPlayers()) {
list.add(new TOPlayer(p.getColor().toString(),p.getCurrentRanking(),p.getBonusScore(),p.getPropertyScore()));
}
return list;
}
}
|
package de.domistiller.vp.android;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.widget.TextView;
import de.domistiller.vpapi.model.Entry;
public class DetailActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Bundle extras = getIntent().getExtras();
Entry entry = (Entry) extras.getSerializable("entry");
((TextView) findViewById(R.id.detail_class_content)).setText(entry.getClassName());
((TextView) findViewById(R.id.detail_lesson_content)).setText(String.valueOf(entry.getLesson()));
((TextView) findViewById(R.id.detail_teacherSubject_content)).setText(entry.getOriginalTeacher() + " / " + entry.getOriginalSubject());
((TextView) findViewById(R.id.detail_replacedBy_content)).setText(entry.getSubstitutionTeacher());
((TextView) findViewById(R.id.detail_subject_content)).setText(entry.getSubstitutionSubject());
((TextView) findViewById(R.id.detail_room_content)).setText(entry.getSubstitutionRoom());
((TextView) findViewById(R.id.detail_comments_content)).setText(entry.getComments());
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.trump.auction.reactor.util.lock;
/**
* Distributed lock support
*
* @author Owen
* @since 2018/1/18
*/
public interface DistributedLock {
/**
* 占用锁
*/
void acquire();
/**
* 释放锁
*/
void release();
}
|
package com.trump.auction.reactor.api;
import com.trump.auction.reactor.api.model.Bidder;
/**
* 出价人服务
*
* @author Owen
* @since 2017/12/29
*/
public interface BidderService {
Bidder nextBidder(Bidder lastBidder, String auctionNo);
Bidder nextBidder(Bidder lastBidder);
Bidder nextBidder();
}
|
/**
* <copyright>
* </copyright>
*
*
*/
package ssl.resource.ssl.mopp;
/**
* A basic implementation of the ssl.resource.ssl.ISslURIMapping interface that
* can map identifiers to URIs.
*
* @param <ReferenceType> unused type parameter which is needed to implement
* ssl.resource.ssl.ISslURIMapping.
*/
public class SslURIMapping<ReferenceType> implements ssl.resource.ssl.ISslURIMapping<ReferenceType> {
private org.eclipse.emf.common.util.URI uri;
private String identifier;
private String warning;
public SslURIMapping(String identifier, org.eclipse.emf.common.util.URI newIdentifier, String warning) {
super();
this.uri = newIdentifier;
this.identifier = identifier;
this.warning = warning;
}
public org.eclipse.emf.common.util.URI getTargetIdentifier() {
return uri;
}
public String getIdentifier() {
return identifier;
}
public String getWarning() {
return warning;
}
}
|
package com.wuyou.springboot_stumanager;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.wuyou")
@MapperScan("com.wuyou.dao")
public class SpringbootStumanagerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootStumanagerApplication.class, args);
}
}
|
package br.com.fitNet.model.percistence.Interfaces;
import java.sql.SQLException;
import java.util.Set;
import br.com.fitNet.model.Cliente;
import br.com.fitNet.model.Contrato;
import br.com.fitNet.model.Endereco;
import br.com.fitNet.model.Matricula;
public interface IRepositorioCliente {
void incluir(Cliente cliente) throws SQLException;
void alterar(Cliente cliente) throws SQLException;
void remover(Cliente cliente) throws SQLException;
Set<Cliente> consultar() throws SQLException;
Set<Cliente> consultarMatriculados() throws SQLException;
Set<Cliente> consultarClienteParaPagamento() throws SQLException;
Set<Cliente> consultarNaoMatriculados() throws SQLException;
void incluirEnderecoCliente(Endereco endereco) throws SQLException;
Endereco consultarEndereco(String cep) throws SQLException;
int consultarAutoIncremento() throws SQLException;
int consultarAutoIncrementoMatricula() throws SQLException;
int consultarAutoIncrementoContrato() throws SQLException;
Cliente consultarClientePorId(int idCliente) throws SQLException;
Set<Cliente> consultarClientePorNome(String nome) throws SQLException;
Cliente consultarClientePorMatricula(int matricula) throws SQLException;
String gerarNumeroMatricula() throws SQLException;
void incluirContrato(Contrato contrato) throws SQLException;
void incluirMatricula(Matricula matricula) throws SQLException;
Set<String> consultarListaModalidadeCliente(int idContrato) throws SQLException;
}
|
package com.safepayu.wallet.activity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import com.safepayu.wallet.BaseActivity;
import com.safepayu.wallet.BaseApp;
import com.safepayu.wallet.R;
import com.safepayu.wallet.api.ApiClient;
import com.safepayu.wallet.api.ApiService;
import com.safepayu.wallet.dialogs.LoadingDialog;
import com.safepayu.wallet.enums.ButtonActions;
import com.safepayu.wallet.halper.Config;
import com.safepayu.wallet.listener.MobileEditTextWatcher;
import com.safepayu.wallet.listener.SnackBarActionClickListener;
import com.safepayu.wallet.models.request.Login;
import com.safepayu.wallet.models.response.LoginResponse;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.schedulers.Schedulers;
public class LoginActivity extends BaseActivity implements View.OnClickListener, SnackBarActionClickListener {
private static String TAG = LoginActivity.class.getName();
private EditText mobileNo, password;
private ApiService apiService;
private LoadingDialog loadingDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setToolbar(false, null, true);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
loadingDialog = new LoadingDialog(this);
apiService = ApiClient.getClient(getApplicationContext()).create(ApiService.class);
mobileNo = findViewById(R.id.et_mobileNo);
password = findViewById(R.id.et_password);
mobileNo.addTextChangedListener(new MobileEditTextWatcher(mobileNo));
mobileNo.setText("+91 8750110867");
password.setText("qwerty123");
mobileNo.setSelection(mobileNo.getText().length());
findViewById(R.id.btn_login).setOnClickListener(this);
findViewById(R.id.btn_forgetPass).setOnClickListener(this);
findViewById(R.id.btn_newAccount).setOnClickListener(this);
// checkPermission();
}
@Override
protected int getLayoutResourceId() {
return R.layout.activity_login;
}
@Override
protected void connectivityStatusChanged(Boolean isConnected, String message) {
if (isConnected) {
findViewById(R.id.btn_login).setEnabled(true);
} else {
findViewById(R.id.btn_login).setEnabled(false);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_login:
BaseApp.getInstance().commonUtils().hideKeyboard(this);
if (checkPermission() && validate()) {
loginUser();
}
break;
case R.id.btn_forgetPass:
break;
case R.id.btn_newAccount:
startActivity(new Intent(this, NewAccount.class));
break;
}
}
public Boolean checkPermission() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermission();
return false;
}
return true;
}
private void requestPermission() {
// BEGIN_INCLUDE(read_phone_state_permission_request)
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
BaseApp.getInstance().toastHelper().showSnackBar(mobileNo, getResources().getString(R.string.permission_read_phone_state), false, getResources().getString(R.string.ok), ButtonActions.SHOW_SETTING, this);
} else {
// Read phone state permission has not been granted yet. Request it directly.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
BaseApp.getInstance().commonUtils().REQUEST_RED_PONE_STATE);
}
// END_INCLUDE(read_phone_state_permission_request)
}
@Override
public void onPositiveClick(View view, ButtonActions action) {
switch (action) {
case SHOW_SETTING:
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", this.getPackageName(), null);
intent.setData(uri);
startActivity(intent);
break;
case VERIFY_MOBILE:
startActivity(new Intent(LoginActivity.this, OtpVerification.class).putExtra(Config.MOBILE_NO, mobileNo.getText().toString().split(" ")[1]));
break;
default:
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{Manifest.permission.READ_PHONE_STATE}, BaseApp.getInstance().commonUtils().REQUEST_RED_PONE_STATE);
break;
}
}
private Boolean validate() {
if (mobileNo.getText().toString().trim().length() == 0) {
mobileNo.requestFocus();
BaseApp.getInstance().toastHelper().showSnackBar(findViewById(R.id.layout_mainLayout), "Please enter valid phone number", true);
return false;
} else if (PhoneNumberUtils.isGlobalPhoneNumber(mobileNo.getText().toString().trim())) {
mobileNo.requestFocus();
BaseApp.getInstance().toastHelper().showSnackBar(findViewById(R.id.layout_mainLayout), "Please enter valid phone number", true);
return false;
} else if (mobileNo.getText().toString().trim().length() < 10 || mobileNo.getText().toString().trim().length() > 14 || mobileNo.getText().toString().trim().matches(BaseApp.getInstance().commonUtils().phoneNumberRegex) == false) {
mobileNo.requestFocus();
BaseApp.getInstance().toastHelper().showSnackBar(findViewById(R.id.layout_mainLayout), "Please enter valid phone number", true);
return false;
} else if (password.getText().toString().trim().length() == 0) {
mobileNo.requestFocus();
BaseApp.getInstance().toastHelper().showSnackBar(findViewById(R.id.layout_mainLayout), "Please enter password", true);
return false;
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == BaseApp.getInstance().commonUtils().REQUEST_RED_PONE_STATE) {
// BEGIN_INCLUDE(permission_result)
// Received permission result.
// Check if the only required permission has been granted
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission has been granted, preview can be displayed
BaseApp.getInstance().toastHelper().showSnackBar(mobileNo, getResources().getString(R.string.permission_granted), true);
} else {
BaseApp.getInstance().toastHelper().showSnackBar(mobileNo, getResources().getString(R.string.permission_not_granted), false, getResources().getString(R.string.setting), ButtonActions.SHOW_SETTING, this);
}
// END_INCLUDE(permission_result)
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void loginUser() {
loadingDialog.showDialog(getResources().getString(R.string.loading_message), false);
Login login = new Login(mobileNo.getText().toString().split(" ")[1], password.getText().toString());
BaseApp.getInstance().getDisposable().add(apiService.login(login)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableSingleObserver<LoginResponse>() {
@Override
public void onSuccess(LoginResponse response) {
loadingDialog.hideDialog();
if (response.getStatus()) {
BaseApp.getInstance().sharedPref().setString(BaseApp.getInstance().sharedPref().ACCESS_TOKEN, response.getAccessToken());
BaseApp.getInstance().sharedPref().setString(BaseApp.getInstance().sharedPref().ACCESS_TOKEN_EXPIRE_IN, response.getTokenExpiresIn());
BaseApp.getInstance().sharedPref().setString(BaseApp.getInstance().sharedPref().USER_ID, response.getUserId());
switch (response.getStatusCode()) {
case 1:
BaseApp.getInstance().toastHelper().showSnackBar(mobileNo, response.getMessage(), false);
break;
case 2:
BaseApp.getInstance().toastHelper().showSnackBar(mobileNo, response.getMessage(), false, getResources().getString(R.string.verify), ButtonActions.VERIFY_MOBILE, LoginActivity.this);
break;
case 3:
// BaseApp.getInstance().toastHelper().showSnackBar(mobileNo, response.getMessage(), false, getResources().getString(R.string.verify), ButtonActions.VERIFY_MOBILE, LoginActivity.this);
startActivity(new Intent(LoginActivity.this, CreatePassCodeActivity.class));
break;
case 4:
startActivity(new Intent(LoginActivity.this,HomeActivity.class));
finish();
break;
}
}
}
@Override
public void onError(Throwable e) {
Log.e(BaseApp.getInstance().toastHelper().getTag(LoginActivity.class), "onError: " + e.getMessage());
loadingDialog.hideDialog();
BaseApp.getInstance().toastHelper().showApiExpectation(findViewById(R.id.layout_mainLayout), true, e);
}
}));
}
}
|
package org.usfirst.frc.team3164.lib.robot.FRC2015;
import java.util.Arrays;
import java.util.List;
import org.usfirst.frc.team3164.lib.baseComponents.LightController;
import org.usfirst.frc.team3164.lib.baseComponents.LightController.Color;
import org.usfirst.frc.team3164.lib.baseComponents.Watchcat;
import org.usfirst.frc.team3164.lib.baseComponents.mechDrive.MechDriveManager;
import org.usfirst.frc.team3164.lib.baseComponents.motors.JagMotor;
import org.usfirst.frc.team3164.lib.baseComponents.motors.VicMotor;
import org.usfirst.frc.team3164.lib.baseComponents.sensors.LimitSwitch;
import org.usfirst.frc.team3164.lib.baseComponents.sensors.MotorEncoder;
import org.usfirst.frc.team3164.lib.baseComponents.sensors.NXTRangefinder;
import org.usfirst.frc.team3164.lib.util.ColorFader;
import org.usfirst.frc.team3164.lib.util.Timer;
import org.usfirst.frc.team3164.lib.vision.ToteParser;
import org.usfirst.frc.team3164.lib.vision.ToteParser.ToteParseResult;
import org.usfirst.frc.team3164.robot.Robot;
import com.ni.vision.NIVision;
import com.ni.vision.NIVision.FlipAxis;
import com.ni.vision.NIVision.Image;
import edu.wpi.first.wpilibj.CameraServer;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public abstract class JSRobot extends IterativeRobot {
//Drive train
public static int DRIVETRAIN_MOTOR_FRONTLEFT = 0;
public static int DRIVETRAIN_MOTOR_FRONTRIGHT = 1;
public static int DRIVETRAIN_MOTOR_REARLEFT = 2;
public static int DRIVETRAIN_MOTOR_REARRIGHT = 3;
//Lift Mech
public static int LIFTMECH_MOTOR_1 = 4;
public static int LIFTMECH_LIMIT_TOP = 0;
public static int LIFTMECH_LIMIT_MIDDLE = 1;//TODO PORT
public static int LIFTMECH_LIMIT_BOTTOM = 2;
public static int LIFTMECH_ENCODER_AC = 8;
public static int LIFTMECH_ENCODER_BC = 9;
//Pinch Mech
public static int PINCHMECH_MOTOR = 5;
public static int PINCHMECH_LIMIT_SWITCH_OPEN = 3;
public static int PINCHMECH_LIMIT_SWITCH_CLOSE = 4;
public static int RANGEFINDER = -1;
public static int CAMERAUPDATEDELAY = 50;
public DriveTrain driveTrain;
public LiftMech liftMech;
public PinchMech pincer;
public MechDriveManager mechDrive;
public NXTRangefinder ultra;
public int camses;
public static Image frame;
public static Image toStatImg;
public static Image frame2;
public static ToteParseResult latestParseResult;
public LightController lights;
public JSRobot() {
Watchcat.init();
this.lights = new LightController(7,8,9);
this.driveTrain = new DriveTrain(new JagMotor(JSRobot.DRIVETRAIN_MOTOR_FRONTLEFT, true),
new JagMotor(JSRobot.DRIVETRAIN_MOTOR_FRONTRIGHT, false), new JagMotor(JSRobot.DRIVETRAIN_MOTOR_REARLEFT, true),
new JagMotor(JSRobot.DRIVETRAIN_MOTOR_REARRIGHT), false);
this.liftMech = new LiftMech(new LimitSwitch(JSRobot.LIFTMECH_LIMIT_TOP), new LimitSwitch(JSRobot.LIFTMECH_LIMIT_BOTTOM),
new LimitSwitch(JSRobot.LIFTMECH_LIMIT_MIDDLE)
,new MotorEncoder(JSRobot.LIFTMECH_ENCODER_AC, JSRobot.LIFTMECH_ENCODER_BC, false), new VicMotor(JSRobot.LIFTMECH_MOTOR_1));
this.pincer = new PinchMech(new VicMotor(JSRobot.PINCHMECH_MOTOR), new LimitSwitch(JSRobot.PINCHMECH_LIMIT_SWITCH_CLOSE),
new LimitSwitch(JSRobot.PINCHMECH_LIMIT_SWITCH_OPEN));
camses = NIVision.IMAQdxOpenCamera("cam0",
NIVision.IMAQdxCameraControlMode.CameraControlModeController);
NIVision.IMAQdxConfigureGrab(camses);
frame = NIVision.imaqCreateImage(NIVision.ImageType.IMAGE_RGB, 0);
toStatImg = NIVision.imaqCreateImage(NIVision.ImageType.IMAGE_RGB, 0);
frame2 = NIVision.imaqCreateImage(NIVision.ImageType.IMAGE_RGB, 0);
new Thread() {
@Override
public void run() {
SmartDashboard.putBoolean("ShowToteParsedImage", false);
SmartDashboard.putInt("CameraUpdateSpeed", JSRobot.CAMERAUPDATEDELAY);
while(true) {
NIVision.IMAQdxGrab(camses, frame, 1);
//NIVision.imaqFlip(frame2, frame, FlipAxis.HORIZONTAL_AXIS);
//NIVision.imaqFlip(toStatImg, frame2, FlipAxis.VERTICAL_AXIS);
if(SmartDashboard.getBoolean("ShowToteParsedImage")) {
ToteParseResult result = ToteParser.parseImg(toStatImg);
latestParseResult = result;
SmartDashboard.putBoolean("IsTote", result.isTote);
CameraServer.getInstance().setImage(result.parsedImage);
} else {
CameraServer.getInstance().setImage(frame/*toStatImg <-- Was*/);
}
CAMERAUPDATEDELAY = SmartDashboard.getInt("CameraUpdateSpeed");
Timer.waitMillis(SmartDashboard.getInt("CameraUpdateSpeed"));
}
}
}.start();
new Thread() {
@Override
public void run() {
while(true) {
try {SmartDashboard.putDouble("FL Mtr Pwr", Robot.rbt.driveTrain.leftFront.getPower());} catch(Exception ex) {}
try {SmartDashboard.putDouble("FR Mtr Pwr", Robot.rbt.driveTrain.rightFront.getPower());} catch(Exception ex) {}
try {SmartDashboard.putDouble("BL Mtr Pwr", Robot.rbt.driveTrain.leftBack.getPower());} catch(Exception ex) {}
try {SmartDashboard.putDouble("BR Mtr Pwr", Robot.rbt.driveTrain.rightBack.getPower());} catch(Exception ex) {}
try {SmartDashboard.putDouble("Lift Mtr Pwr", Robot.rbt.liftMech.motors.getPower());} catch(Exception ex) {}
try {SmartDashboard.putDouble("Pincer Mtr Pwr", Robot.rbt.pincer.motor.getPower());} catch(Exception ex) {}
try {SmartDashboard.putBoolean("Lift Lowlim", Robot.rbt.liftMech.lowLim.isPressed());} catch(Exception ex) {}
try {SmartDashboard.putBoolean("Lift Midlim", Robot.rbt.liftMech.midLim.isPressed());} catch(Exception ex) {}
try {SmartDashboard.putBoolean("Lift Toplim", Robot.rbt.liftMech.topLim.isPressed());} catch(Exception ex) {}
try {SmartDashboard.putDouble("Lift Enc", Robot.rbt.liftMech.enc.getValue());} catch(Exception ex) {}
try {SmartDashboard.putDouble("Lift Setpoint", Robot.rbt.liftMech.eval);} catch(Exception ex) {}
try {SmartDashboard.putBoolean("Pincer Open", Robot.rbt.pincer.openLim.isPressed());} catch(Exception ex) {}
try {SmartDashboard.putBoolean("Pincer Close", !Robot.rbt.pincer.closeLim.isPressed());} catch(Exception ex) {}
Timer.waitMillis(100);
}
}
}.start();
new Thread() {
@Override
public void run() {
List<Color> cols = Arrays.asList(Color.AQUA, Color.RED, Color.MAGENTA, Color.BLUE, Color.WHITE);
int loc = -1;
ColorFader fad = new ColorFader(new Color(0, 0, 0), Color.WHITE);
while(true) {
if(fad.disp()) {
Timer.waitSec(4);
loc++;
if(loc>=cols.size()) {
loc = 0;
}
Color c = cols.get(loc);
fad = new ColorFader(lights.getColor(), c);
} else {
Timer.waitMillis(20);
}
}
}
}.start();
}
}
|
package portal.utils;
import io.qameta.allure.Step;
import org.openqa.selenium.Keys;
import portal.data.enumdata.ButtonName;
import portal.data.enumdata.component.PopUpComponent;
import static com.codeborne.selenide.Selenide.*;
public class PopUpFull {
@Step("Кликаем на кнопку {buttonName}")
public void clickButtonByName(ButtonName buttonName) {
var button = buttonName.getValue();
$x("//*[contains(@class,'bs-modal_container')]//*[text()='" + button + "']").click();
}
@Step("Меняем статус")
public PopUpFull changeItem(PopUpComponent popUpComponent, String item) {
var component = popUpComponent.toString();
$("[name='" + component + "'] div").click();
$x("//*[text()='" + item + "']").click();
return this;
}
@Step("Меняем статус заявки на ")
public PopUpFull changeRequestStatus(String status) {
$("[name='state'] div").click();
$x("//p[text()='" + status + "']").click();
return this;
}
@Step("Оставляем комментарий")
public PopUpFull setComment(String comment) {
$x("//*[@placeholder='Введите ваше сообщение...']").setValue(comment);
return this;
}
@Step("Кликаем и вводим дату {date}")
public PopUpFull setDate(String date) {
$("[data-date-format='dd.MM.yyyy']").clear();
$("[data-date-format='dd.MM.yyyy']").setValue(date).pressEnter();
return this;
}
@Step("Кликаем и вводим время {time}")
public PopUpFull setTime(String time) {
$("[data-time-format='HH:mm']").sendKeys(Keys.chord(Keys.CONTROL, "a", Keys.DELETE));
$("[data-time-format='HH:mm']").setValue(time).pressEnter();
return this;
}
@Step("Получаем текущую дату тестирования")
public String getCurrentTestingDate() {
return $$x("//*[contains(@class,'bs-unit_transclude--no-edit')]").get(1).text();
}
}
|
package com.koma.gank;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.koma.component_base.base.SwipeActivity;
import com.koma.gank.R;
@Route(path = "/gank/main")
public class MainActivity extends SwipeActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gank_activity_main);
}
}
|
/**
*
*/
package com.fixit.core.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fixit.core.dao.mongo.MapAreaDao;
import com.fixit.core.data.ImmutableLatLng;
import com.fixit.core.data.mongo.MapArea;
/**
* @author Kostyantin
* @createdAt 2017/04/30 14:45:55 GMT+3
*/
@Component
public class MapAreaService {
@Autowired
private MapAreaDao mapAreaDao;
public static class MapAreaRepresentation {
public final String id;
public final String name;
public final ImmutableLatLng[][] polygons;
public MapAreaRepresentation(MapArea mapArea) {
this.id = mapArea.get_id().toHexString();
this.name = mapArea.getName();
double[][][] coords = mapArea.getGeometry().getCoordinates();
this.polygons = new ImmutableLatLng[coords.length][];
for(int polygonIndex = 0; polygonIndex < coords.length; polygonIndex++) {
double[][] polygonCoords = coords[polygonIndex];
this.polygons[polygonIndex] = new ImmutableLatLng[polygonCoords.length];
for(int coordsIndex = 0; coordsIndex < polygonCoords.length; coordsIndex++) {
this.polygons[polygonIndex][coordsIndex] = new ImmutableLatLng(polygonCoords[coordsIndex][1], polygonCoords[coordsIndex][0]);
}
}
}
}
}
|
package ee.ttu.usermanagement.security;
import java.util.HashSet;
import java.util.Set;
import javax.inject.Inject;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
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 ee.ttu.usermanagement.entity.Role;
import ee.ttu.usermanagement.entity.UserProfile;
import ee.ttu.usermanagement.service.UserManagementService;
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
@Inject
private UserManagementService userService;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
UserProfile userProfile = userService.findUserByEmail(email, true);
if (userProfile == null) {
throw new UsernameNotFoundException("User with the email " + email + " not found");
}
// Using email as username
String username = userProfile.getEmail();
String password = userProfile.getPassword();
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for (Role role : userProfile.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
// org.springframework.security.core.userdetails.User implements UserDetails
User user = new User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
return user;
}
}
|
package com.example.factory.abstractfactory;
/**
* @author: 曹文
* @create: 2020/3/19
* @update: 11:12
* @version: V1.0
* @detail:
**/
public class AbstractFactoryTest {
public static void main(String[] args) {
AppleFactory factory = new AppleFactory();
factory.createCPU().developCPU();
factory.createParts().importParts();
}
}
|
/*
* #%L
* Diana UI Core
* %%
* Copyright (C) 2014 Diana UI
* %%
* 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.
* #L%
*/
package com.dianaui.universal.core.client.ui;
import com.dianaui.universal.core.client.ui.base.HasSize;
import com.dianaui.universal.core.client.ui.gwt.RichTextArea;
import com.dianaui.universal.core.client.ui.constants.ButtonGroupSize;
import com.dianaui.universal.core.client.ui.html.Div;
import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.TakesValue;
import com.google.gwt.user.client.ui.HasValue;
/**
* @author <a href='mailto:donbeave@gmail.com'>Alexey Zhokhov</a>
*/
public class WYSIWYGEditor extends Div implements HasValueChangeHandlers<String>, HasValue<String>, TakesValue<String>,
LeafValueEditor<String>, HasSize<ButtonGroupSize> {
private RichTextToolbar toolbar;
private RichTextArea textArea;
public WYSIWYGEditor() {
textArea = new RichTextArea();
toolbar = new RichTextToolbar(textArea);
add(toolbar);
add(textArea);
}
public RichTextToolbar getToolbar() {
return toolbar;
}
public RichTextArea getTextArea() {
return textArea;
}
@Override
public String getValue() {
return textArea.getValue();
}
@Override
public void setValue(String value) {
textArea.setValue(value);
}
@Override
public void setValue(String value, boolean fireEvents) {
textArea.setValue(value, fireEvents);
}
@Override
public HandlerRegistration addValueChangeHandler(final ValueChangeHandler<String> handler) {
return textArea.addValueChangeHandler(handler);
}
@Override
public ButtonGroupSize getSize() {
return toolbar.group1.getSize();
}
@Override
public void setSize(ButtonGroupSize size) {
toolbar.group1.setSize(size);
toolbar.group2.setSize(size);
toolbar.group3.setSize(size);
toolbar.group4.setSize(size);
}
}
|
/**
* Copyright (C) Alibaba Cloud Computing, 2012
* All rights reserved.
*
* 版权所有 (C)阿里巴巴云计算,2012
*/
package com.aliyun.oss.internal;
import static com.aliyun.oss.internal.OSSUtils.safeCloseResponse;
import java.net.URI;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.common.auth.RequestSigner;
import com.aliyun.oss.common.auth.ServiceCredentials;
import com.aliyun.oss.common.comm.ExecutionContext;
import com.aliyun.oss.common.comm.RequestMessage;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.common.comm.RetryStrategy;
import com.aliyun.oss.common.comm.ServiceClient;
/**
* Base class for classes doing OSS operations.
*/
public abstract class OSSOperation {
private URI endpoint;
private ServiceCredentials credentials;
private ServiceClient client;
protected OSSOperation(URI endpoint, ServiceClient client, ServiceCredentials cred) {
assert (endpoint != null && client != null && cred != null);
this.endpoint = endpoint;
this.client = client;
this.credentials = cred;
}
public URI getEndpoint() {
return endpoint;
}
protected ServiceClient getInnerClient() {
return this.client;
}
/**
* Invokes a request.
* @param request
* Request message to be sent.
* @param context
* Requset context.
* @return
* Response message.
* @throws OSSException
* On service returns an error.
* @throws ClientException
* On client request fails.
*/
protected ResponseMessage send(RequestMessage request,
ExecutionContext context) throws OSSException, ClientException {
return send(request, context, false);
}
protected ResponseMessage send(RequestMessage request,
ExecutionContext context, boolean keepResponseOpen) throws OSSException, ClientException{
try {
ResponseMessage response = client.sendRequest(request, context);
if (!keepResponseOpen) {
safeCloseResponse(response);
}
return response;
} catch (ServiceException e) {
assert (e instanceof OSSException);
throw (OSSException)e;
}
}
private static RequestSigner createSigner(HttpMethod method, String bucket,
String key, ServiceCredentials credentials){
String resourcePath = "/" +
((bucket != null) ? bucket : "") +
((key != null ? "/" + key : ""));
// Hacked. the sign path is /bucket/key for two-level-domain mode
// but /bucket/key/ for the three-level-domain mode.
if (bucket != null && key == null) {
resourcePath = resourcePath + "/";
}
return new OSSRequestSigner(method.toString(), resourcePath, credentials);
}
protected ExecutionContext createDefaultContext(HttpMethod method, String bucket, String key) {
ExecutionContext context = new ExecutionContext();
context.setCharset(OSSConstants.DEFAULT_CHARSET_NAME);
context.setSigner(createSigner(method, bucket, key, credentials));
context.getResponseHandlers().add(new OSSErrorResponseHandler());
if (method == HttpMethod.POST) {
// Non Idempotent operation
context.setRetryStrategy(new RetryStrategy() {
@Override
public boolean shouldRetry(Exception ex, RequestMessage request,
ResponseMessage response, int retries) {
return false;
}
});
}
return context;
}
protected ExecutionContext createDefaultContext(HttpMethod method, String bucketName) {
return this.createDefaultContext(method, bucketName, null);
}
protected ExecutionContext createDefaultContext(HttpMethod method) {
return this.createDefaultContext(method, null, null);
}
}
|
package symap.closeup.components;
import symap.closeup.alignment.HitAlignment;
public interface CloseUpListener {
public void hitClicked(HitAlignment ha);
}
|
package com.example.hante.newprojectsum.util;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.NotificationCompat;
import com.example.hante.newprojectsum.R;
/**
* 通知栏 样式
* 各标志符介绍
* Notification.FLAG_SHOW_LIGHTS //三色灯提醒,在使用三色灯提醒时候必须加该标志符
* Notification.FLAG_ONGOING_EVENT //发起正在运行事件(活动中)
* Notification.FLAG_INSISTENT //让声音、振动无限循环,直到用户响应 (取消或者打开)
* Notification.FLAG_ONLY_ALERT_ONCE //发起Notification后,铃声和震动均只执行一次
* Notification.FLAG_AUTO_CANCEL //用户单击通知后自动消失
* Notification.FLAG_NO_CLEAR //只有全部清除时,Notification才会清除 ,不清楚该通知(QQ的通知无法清除,就是用的这个)
* Notification.FLAG_FOREGROUND_SERVICE //表示正在运行的服务
*
* .setDefaults(int defaults)
* 方法解释:向通知添加声音、闪灯和振动效果的最简单、使用默认(defaults)属性,可以组合多个属性
* Notification.DEFAULT_VIBRATE //添加默认震动提醒 需要 VIBRATE permission
* Notification.DEFAULT_SOUND // 添加默认声音提醒
* Notification.DEFAULT_LIGHTS// 添加默认三色灯提醒
* Notification.DEFAULT_ALL// 添加默认以上3种全部提醒
*
*
*/
public class NotificationManager {
/**
* 通知栏
* 设置提醒标志符Flags
* 方法解释:提醒标志符,向通知添加声音、闪灯和振动效果等设置达到通知提醒效果,可以组合多个属性
* 创建通知栏之后通过给他添加.flags属性赋值。
* @param context 上下文
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public Notification notificationManager(@NonNull Context context){
NotificationCompat.Builder mBuilder;
Notification mNotification;
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setContentTitle("Title");
mBuilder.setContentText("Content Text");
mBuilder.setNumber(1);
mBuilder.setTicker("通知");//通知首次出现在通知栏,带上升动画效果的
mBuilder.setWhen(System.currentTimeMillis());
mBuilder.setPriority(Notification.PRIORITY_DEFAULT);
mBuilder.setAutoCancel(true);//设置这个标志当用户单击面板就可以让通知将自动取消
mBuilder.setOngoing(false);//TRUE,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,
// 因此占用设备(如一个文件下载,同步操作,主动网络连接)
mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);//向通知添加声音、闪灯和振动效果的最简单
// 、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合
mBuilder.setSmallIcon(R.drawable.leak_canary_icon);
mBuilder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));
mNotification = mBuilder.build();
mNotification.flags = Notification.FLAG_AUTO_CANCEL;
return mNotification;
}
/**
*
* 点击通知栏进行跳转
* @param context 上下文
* @param activity 跳转activity的Intent
* @return 返回值 PendingIntent
*/
public PendingIntent getPendingIntent(@NonNull Context context, int requestCode, @NonNull
Intent activity){
return PendingIntent
.getActivity(context, requestCode, activity, PendingIntent.FLAG_CANCEL_CURRENT);
}
}
|
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
public class FirmwareFile {
private final List<byte[]> frames = new LinkedList();
public FirmwareFile(InputStream stream) throws IOException {
this.parse(stream);
}
public List<byte[]> getFrames() {
return this.frames;
}
private void parse(InputStream stream) throws IOException {
try {
this.readFrames(stream);
} catch (IOException var3) {
}
}
private void readFrames(InputStream stream) throws IOException {
this.frames.clear();
for(byte[] frame = this.readFrame(stream); frame != null; frame = this.readFrame(stream)) {
this.frames.add(frame);
}
}
private byte[] readFrame(InputStream stream) throws IOException {
int length = this.readLength(stream);
return length > 0?this.readFrameData(stream, length):null;
}
private int readLength(InputStream stream) throws IOException {
int high = this.readByte(stream);
int low = this.readByte(stream);
return high << 8 | low;
}
private byte[] readFrameData(InputStream stream, int length) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
for(int result = 0; result < length; ++result) {
int value = this.readByte(stream);
outStream.write(value);
}
byte[] var6 = outStream.toByteArray();
outStream.close();
return var6;
}
private int readByte(InputStream stream) throws IOException {
int high = stream.read();
int low = stream.read();
return this.createByte(high, low);
}
private int createByte(int high, int low) {
return this.fromHex(high) << 4 | this.fromHex(low);
}
private int fromHex(int value) {
return 48 <= value && value <= 57?value - 48:(97 <= value && value <= 102?value - 97 + 10:(65 <= value && value <= 70?value - 65 + 10:0));
}
}
|
package com.myvodafone.android.front.stores;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.myvodafone.android.R;
import com.myvodafone.android.utils.StaticTools;
import java.util.List;
/**
* Created by d.alexandrakis on 30/3/2016.
*/
public class StoreFinderListAdapter extends ArrayAdapter<StoreFinderListItem> {
private List<StoreFinderListItem> items;
private int layoutResourceId;
private Context context;
public StoreFinderListAdapter(Context context, int layoutResourceId, List<StoreFinderListItem> items){
super(context,layoutResourceId,items);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder viewHolder;
if(row == null){
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId,parent,false);
viewHolder = new ViewHolder();
viewHolder.item = items.get(position);
viewHolder.address = (TextView) row.findViewById(R.id.addressTxt);
viewHolder.shop = (TextView) row.findViewById(R.id.shopTxt);
viewHolder.distance = (TextView) row.findViewById(R.id.distanceTxt);
if(!StaticTools.checkLocationServices(context)) {
viewHolder.distance.setVisibility(View.GONE);
} else {
viewHolder.distance.setVisibility(View.VISIBLE);
}
row.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) row.getTag();
viewHolder.item = items.get(position);
}
setupItem(viewHolder,items.get(position));
return row;
}
public static class ViewHolder{
StoreFinderListItem item;
TextView address;
TextView shop;
TextView distance;
}
private void setupItem(ViewHolder holder, StoreFinderListItem item){
holder.address.setText(item.getAddress());
holder.distance.setText(item.getDistance());
holder.shop.setText(item.getShop());
}
}
|
package ru.client.model;
import java.util.List;
public interface DAO<T, K> {
void create(T entity);
T getById(K id);
List<T> getAll();
boolean delete(K id);
boolean update(T entity);
} |
package gameUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import Connection.DatabaseConnect;
import Connection.PlayerTable;
import game.Calculator;
import game.ObjectPool;
import game.Villager;
/**
* OnePlyer UI for 1 player mode.
*
* @author Pimwalun Witchawanitchanun
*
*/
public class OnePlayer extends JPanel implements Observer, Runnable {
private JLabel question, timeLabel, time, distance, distanceLabel, witch, lion, win, showScore, lose, powerup,
combo;
private JTextField textField;
private JButton restartButton, homeButton;
private JScrollPane scroll;
private ImageIcon w, lion_in_cage, power;
private Renderer renderer;
private JTable table;
int num1 = 0;
int num2 = 0;
char op;
int result, score = 0;
int timeup = 0;
int dist = 0;
private long TIME_DELAY = 1000;
private String message;
private boolean guest = true, loser = false;
private Calculator game;
private Thread thread;
private final AtomicBoolean running = new AtomicBoolean(true);
private ObjectPool objectPool;
private PlayerTable player = new PlayerTable();
/**
* Create the application.
*/
public OnePlayer() {
// System.out.println("Run 1 player...");
game = new Calculator();
objectPool = new ObjectPool();
objectPool.addObserver(this);
renderer = new Renderer();
add(renderer);
timeLabel = new JLabel();
timeLabel.setFont(new Font("Andale Mono", Font.PLAIN, 20));
timeLabel.setText("Time: ");
timeLabel.setBounds(44, 35, 80, 25);
add(timeLabel);
time = new JLabel();
time.setFont(new Font("Andale Mono", Font.PLAIN, 20));
time.setText("00.00 sec");
time.setBounds(110, 35, 200, 25);
add(time);
combo = new JLabel();
combo.setFont(new Font("Andale Mono", Font.PLAIN, 20));
combo.setText("Combo: 0");
combo.setBounds(1160, 310, 400, 25);
add(combo);
distanceLabel = new JLabel();
distanceLabel.setFont(new Font("Andale Mono", Font.PLAIN, 20));
distanceLabel.setText("Distance: ");
distanceLabel.setBounds(44, 70, 300, 25);
add(distanceLabel);
distance = new JLabel();
distance.setFont(new Font("Andale Mono", Font.PLAIN, 20));
distance.setBounds(160, 70, 500, 25);
add(distance);
question = new JLabel();
question.setFont(new Font("Arial Rounded Bold", Font.PLAIN, 40));
question.setText("question");
question.setBounds(497, 178, 213, 57);
add(question);
textField = new JTextField();
textField.setFont(new Font("Arial Rounded Bold", Font.PLAIN, 43));
textField.setBounds(710, 168, 105, 75);
add(textField);
power = new ImageIcon(getClass().getResource("/res/power.png"));
powerup = new JLabel(power);
powerup.setBounds(1110, 330, 150, 71);
powerup.setVisible(false);
add(powerup);
w = new ImageIcon(getClass().getResource("/res/witch_r.gif"));
witch = new JLabel(w);
witch.setBounds(980, 250, 299, 212);
witch.setVisible(false);
add(witch);
lion_in_cage = new ImageIcon(getClass().getResource("/res/push_lion_left.png"));
lion = new JLabel(lion_in_cage);
lion.setBounds(750, 375, 424, 253);
add(lion);
ImageIcon img = new ImageIcon(getClass().getResource("/res/save.png"));
win = new JLabel(img);
win.setBounds(400, 70, 517, 373);
add(win);
win.setVisible(false);
ImageIcon youLose = new ImageIcon(getClass().getResource("/res/lose.png"));
lose = new JLabel(youLose);
lose.setBounds(400, 70, 517, 373);
add(lose);
lose.setVisible(false);
ImageIcon b1 = new ImageIcon(getClass().getResource("/res/restart.png"));
restartButton = new JButton(b1);
restartButton.setBounds(440, 470, 204, 87);
restartButton.addActionListener((e) -> {
OnePlayer goTo = new OnePlayer();
if (guest == false) {
goTo.initializePlayer(player);
}
MainFrame.setPanel(goTo);
});
add(restartButton);
restartButton.setVisible(false);
ImageIcon b2 = new ImageIcon(getClass().getResource("/res/home.png"));
homeButton = new JButton(b2);
homeButton.setBounds(680, 470, 204, 87);
homeButton.addActionListener((e) -> {
IndexUI goTo = new IndexUI();
MainFrame.setPanel(goTo.getPanel());
});
add(homeButton);
homeButton.setVisible(false);
table = new JTable();
table.setRowHeight(25);
table.setFont(new Font("Arial Rounded Bold", Font.BOLD, 16));
table.setFont(new Font("Arial Rounded Bold", Font.PLAIN, 12));
table.setForeground(Color.white);
table.setOpaque(true);
table.setBorder(BorderFactory.createLineBorder(new Color(148, 91, 39)));
table.setSelectionForeground(new Color(148, 91, 39));
// table.setSelectionBackground(new Color(247, 219, 0));
scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.getViewport().setOpaque(false);
scroll.setOpaque(false);
scroll.setBounds(500, 190, 320, 200);
scroll.setVisible(false);
add(scroll);
ImageIcon score = new ImageIcon(getClass().getResource("/res/score_board.png"));
showScore = new JLabel(score);
showScore.setBounds(410, 0, 500, 700);
showScore.setVisible(false);
add(showScore);
countdown();
play();
setLayout(new BorderLayout());
add(renderer);
}
/**
* Initialize from PlayerTable to show the score board.
*
* @param player
* is info from database.
*/
public void initializePlayer(PlayerTable newPlayer) {
guest = false;
player.setName(newPlayer.getName());
player.setScore(0);
// System.out.println("gameEnd(): " + player.getName() + ", " + player.getScore());
}
/**
* Playing the game.
*/
public void play() {
game.setX(780); // set first lion's position ; panel center:493
lion.setBounds(game.getX(), 375, 424, 253);
renderer.setVisible(true);
distance.setText(String.format("%d meter", game.getX()));
question();
question.setText(getMessage());
textField.addKeyListener(new Enter());
}
/**
* Count down before the game starts.
*/
public void countdown() {
question.setVisible(false);
textField.setVisible(false);
JLabel count = new JLabel();
count.setFont(new Font("Arial Rounded Bold", Font.PLAIN, 500));
count.setBounds(500, 100, 500, 500);
add(count);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
count.setText("3");
timer.schedule(new TimerTask() {
@Override
public void run() {
count.setText("2");
timer.schedule(new TimerTask() {
@Override
public void run() {
count.setText("1");
timer.schedule(new TimerTask() {
@Override
public void run() {
count.setVisible(false);
question.setVisible(true);
textField.setVisible(true);
remove(count);
start();
}
}, TIME_DELAY);
}
}, TIME_DELAY);
}
}, TIME_DELAY);
}
}, TIME_DELAY);
}
@Override
public void update(Observable o, Object arg) {
repaint();
}
/**
* Input the answer and check that correct or not.
*
* @author pimwalun
*
*/
class Enter implements KeyListener {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
int answer = 9999;
try {
String ans = textField.getText().trim();
answer = Integer.parseInt(ans);
} catch (NumberFormatException e1) {
textField.setText("");
}
if (!game.check(answer, num1, num2, op)) {
score = 0;
textField.setText("");
game.back();
lion.setLocation(game.getX(), 375);
objectPool.setStop(game.getX() + 20);
distance.setText(String.format("%d meter", game.getX()));
combo.setText(String.format("Combo: %d", score));
// System.out.println(game.getX());
} else { // correct answer
objectPool.setStop(game.getX() - game.getDx());
objectPool.burstVillagers(e.getKeyCode());
if (score % 3 == 0 && score > 0) {
witch.setVisible(true);
powerup.setVisible(true);
objectPool.burstVillagers(1);
game.setDx(5);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
witch.setVisible(false);
powerup.setVisible(false);
}
}, TIME_DELAY);
}
game.setDx(10);
score++;
textField.setText("");
game.push();
lion.setLocation(game.getX(), 375);
distance.setText(String.format("%d meter", game.getX()));
combo.setText(String.format("Combo: %d", score));
}
if (game.getX() >= 890) {
stop();
lose.setVisible(true);
loser = true;
gameEnd();
}
else if (isGameEnd()) {
stop();
distance.setText("0 meter");
win.setVisible(true);
loser = false;
gameEnd();
} else {
question();
question.setText(getMessage());
}
}
}
public boolean isGameEnd() {
if (game.getX() <= -10)
return true;
return false;
}
/**
* Waiting before show score board.
*/
public void showScoreBoard() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
timer.schedule(new TimerTask() {
@Override
public void run() {
timer.schedule(new TimerTask() {
@Override
public void run() {
win.setVisible(false);
lose.setVisible(false);
lion.setVisible(false);
showScore.setVisible(true);
scroll.setVisible(true);
restartButton.setBounds(900, 380, 204, 87);
homeButton.setBounds(900, 500, 204, 87);
restartButton.setVisible(true);
homeButton.setVisible(true);
}
}, TIME_DELAY);
}
}, TIME_DELAY);
}
}, TIME_DELAY);
}
/**
* If player select start button the panel it show scoreboard. If player select
* skip button the panel it doesn't show scoreboard.
*/
private void gameEnd() {
double time = timeup * 0.01; // เวลาทีทำได้
// System.out.printf("%.2f sec\n", time);
textField.removeKeyListener(textField.getKeyListeners()[0]);
textField.setVisible(false);
question.setVisible(false);
combo.setVisible(false);
if (guest == false && loser == false) {
showScoreBoard();
// System.out.println("guset");
player.setScore(time);
// System.out.println("gameEnd(): " + player.getName() + ", " + player.getScore());
DatabaseConnect.getInstance().update(player);
showScoreBoard();
List<PlayerTable> playerList = new ArrayList<PlayerTable>(
DatabaseConnect.getInstance().pullAllPlayerdata());
Collections.sort(playerList);
String columnNames[] = { "No", "Name", "Time" };
String[][] data = new String[playerList.size()][3];
for (int i = 0; i < playerList.size(); i++) {
data[i][0] = (i + 1) + "";
data[i][1] = playerList.get(i).getName();
data[i][2] = playerList.get(i).getScore() + "";
if (playerList.get(i).getName().equalsIgnoreCase(player.getName())) {
}
}
TableModel model = new DefaultTableModel(data, columnNames) {
public boolean isCellEditable(int row, int column) {
return false;
}
};
JTableHeader header = table.getTableHeader();
header.setBackground(new Color(148, 91, 39));
header.setForeground(Color.white);
header.setReorderingAllowed(false);
header.setPreferredSize(new Dimension(100, 30));
table.setModel(model);
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(50);
columnModel.getColumn(1).setPreferredWidth(200);
columnModel.getColumn(2).setPreferredWidth(100);
getNewRenderedTable(table);
} else if (guest == true || loser == true) {
lose.setVisible(true);
restartButton.setVisible(true);
homeButton.setVisible(true);
}
}
/**
* Set color of the current user playing.
*
* @param table
* is scoreboard.
* @return every value of scoreboard.
*/
private JTable getNewRenderedTable(JTable table) {
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
String status = (String) table.getModel().getValueAt(row, 1);
if ((player.getName()).equals(status)) {
setBackground(Color.white);
setForeground(Color.black);
} else {
setBackground(new Color(148, 91, 39));
setForeground(Color.white);
}
return this;
}
});
return table;
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
}
/**
* Paint background and villager in the panel.
*
* @author pimwalun
*
*/
class Renderer extends JPanel {
public Renderer() {
setDoubleBuffered(true);
setPreferredSize(new Dimension(1280, 720));
}
@Override
public void paint(Graphics g) {
super.paint(g);
BufferedImage img1 = null;
try {
img1 = ImageIO.read(this.getClass().getResource("/res/single_mode.png"));
} catch (IOException e) {
}
g.drawImage(img1, 0, 0, 1280, 720, null);
BufferedImage img = null;
try {
img = ImageIO.read(this.getClass().getResource("/res/push.png"));
} catch (IOException e) {
}
// Draw space
for (Villager villager : objectPool.getVillager()) {
g.drawImage(img, 1200 + villager.getX(), 510, 111, 120, null);
}
}
}
/**
* Random question to the player.
*/
public void question() {
char operator[] = { '+', '-', 'x', '÷' };
// TODO ค่อยแก้เลข
num1 = (int) (1 + (Math.random() * 10));
num2 = (int) (1 + (Math.random() * 10));
int id = (int) (Math.random() * 4);
op = operator[id];
switch (op) {
case '-':
if (num2 > num1) {
int temp = num1;
num1 = num2;
num2 = temp;
}
result = (int) (num1 - num2);
break;
case '÷':
if (num2 > num1) {
int temp = num1;
num1 = num2;
num2 = temp;
}
if (num1 % num2 != 0) {
num1 -= (num1 % num2);
}
result = (int) (num1 / num2);
break;
case 'x':
if (num2 > 10) {
num2 = num2 % 10;
}
result = num1 * num2;
break;
}
setMessage(num1 + " " + op + " " + num2 + " =");
// System.out.println(num1 + " " + op + " " + num2);
}
/**
* Set a message about the game.
*
* @param message
* a string about the question in the game.
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Return a message about the question in the game.
*
* @return string message related to the recent question.
*/
public String getMessage() {
return message;
}
/**
* Start timer.
*/
public void start() {
thread = new Thread(this);
thread.start();
}
/**
* Stop timer.
*/
public void stop() {
running.set(false);
}
/**
* Time of user to play in 1 game.
*/
@Override
public void run() {
while (running.get()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
timeup++;
time.setText(String.format("%.2f sec", timeup * 0.01));
}
}
/**
* Return panel of OnePlayer.
*
* @return panel of OnePlayer.
*/
public JPanel getPanel() {
return this;
}
}
|
package testutils;
import java.util.Map;
import java.util.TreeMap;
public class DispensedMessage implements LogMessage {
private int canisterNumber;
private int amount;
public DispensedMessage(int canisterNumber, int amount) {
this.canisterNumber = canisterNumber;
this.amount = amount;
}
@Override
public Object getData() {
return this;
}
@Override
public String toString() {
return "Dispensed Amount: " + amount + " from canister " + canisterNumber;
}
public int getCanisterNumber() {
return canisterNumber;
}
public int getAmount() {
return amount;
}
}
|
package cs261_project.config;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import cs261_project.data_structure.Event;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
/**
* Configuration class for web application
* @author Group 12 - Stephen Xu, JuanYan Huo, Ellen Tatum, JiaQi Lv, Alexander Odewale
*/
@Configuration
@ComponentScan
public class AppConfiguration implements WebMvcConfigurer, ApplicationContextAware {
//application
private ApplicationContext context;
public AppConfiguration(){
}
@Override
public void setApplicationContext(final ApplicationContext appContext) throws BeansException {
this.context = appContext;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
WebMvcConfigurer.super.addResourceHandlers(registry);
//in the resources folder
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/image/**").addResourceLocations("classpath:/image/");
}
@Override
public void addFormatters(FormatterRegistry registry) {
WebMvcConfigurer.super.addFormatters(registry);
//format the datetime using the style given in the Event class
registry.addFormatter(new Formatter<LocalDateTime>(){
@Override
public LocalDateTime parse(String text, Locale locale) {
try{
return Event.StringToTempo(text);
}catch(DateTimeParseException dtpe){
throw dtpe;
}
}
@Override
public String print(LocalDateTime datetime, Locale locale) {
try{
return Event.TempoToString(datetime);
}catch(DateTimeParseException dtpe){
throw dtpe;
}
}
});
}
@Bean
public SpringResourceTemplateResolver templateResolver(){
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(this.context);
resolver.setTemplateMode(TemplateMode.HTML);
//in the resources folder
resolver.setPrefix("classpath:/dynamic/");
resolver.setSuffix(".html");
resolver.setCacheable(true);
return resolver;
}
@Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(this.templateResolver());
engine.setEnableSpringELCompiler(true);
return engine;
}
@Bean
public ThymeleafViewResolver viewResolver(){
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(this.templateEngine());
resolver.setOrder(1);
resolver.setContentType("text/html");
resolver.setCharacterEncoding("UTF-8");
resolver.setViewNames(new String[]{"*.html"});
return resolver;
}
@Bean
public SimpleUrlHandlerMapping customFaviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Integer.MIN_VALUE);
mapping.setUrlMap(Collections.singletonMap(
"/favicon.ico", faviconRequestHandler()));
return mapping;
}
@Bean
protected ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler
= new ResourceHttpRequestHandler();
ClassPathResource classPathResource
= new ClassPathResource("../resources/static");
List<Resource> locations = Arrays.asList(classPathResource);
requestHandler.setLocations(locations);
return requestHandler;
}
}
|
package com.netcracker.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@EnableResourceServer
@RestController
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
{
@Override
public void configure(HttpSecurity http) throws Exception {
/*http.authorizeRequests()
.antMatchers("/oauth/token", "/oauth/authorize**", "/helloUser", "/users/sign-up", "/users/", "/group/notifications")
.permitAll().and().authorizeRequests().anyRequest().fullyAuthenticated()
;*/
/*http
/* http.authorizeRequests()
.antMatchers("/oauth/token", "/oauth/authorize**", "/helloUser", "/users/sign-up", "/users/**", "/routes/**")
.permitAll();
http.authorizeRequests().anyRequest().fullyAuthenticated();
*/
/*
http
.authorizeRequests().antMatchers("/oauth/token",
"/oauth/authorize**",
"/helloUser",
"/users/sign-up",
"/users/",
"/routes/**",
"/group/notifications").permitAll()
// .anyRequest().authenticated();
.and().requestMatchers().antMatchers( "/users/User" ,
"/users/user/profile",
"/users/update-user-password",
"/users/update-user-fio",
"/users/update-user-city",
"/users/update-user-phone-number",
"/users/update-user-info",
"/group/",
"/users/update-user-image",
"/users/update-user-email",
"/users/user/image",
"/reports/create-report",
"/users/rate/driver-rating",
"/group",
"/group/",
"/group/entergroup/*",
"/group/useringroup/")
.and().authorizeRequests()
.antMatchers( "/users/User",
"/users/user/profile",
"/users/update-user-password",
"/users/update-user-fio",
"/users/update-user-city",
"/users/update-user-phone-number",
"/users/update-user-info",
"/group/",
"/users/update-user-image",
"/users/update-user-email",
"/users/user/image",
"/reports/create-report",
"/users/rate/driver-rating",
"/group",
"/group/",
"/group/entergroup/*",
"/group/useringroup/",
"/users/groups")
.access("hasAnyRole('USER', 'ADMIN')")
.and().requestMatchers().antMatchers( "/users/Admin")
.and().authorizeRequests()
.antMatchers("/users/Admin").access("hasRole('ADMIN')")
.anyRequest().fullyAuthenticated()
.and()
.formLogin(); */
/* http.authorizeRequests()
.antMatchers("/oauth/token", "/oauth/authorize**", "/helloUser", "/users/sign-up", "/users/", "/routes/**")
.permitAll();
http.authorizeRequests().anyRequest().fullyAuthenticated();*/
/* http
.authorizeRequests()
.antMatchers("/oauth/token", "/oauth/authorize**", "/helloUser", "/users/sign-up")
.permitAll();
// .anyRequest().authenticated();
http.requestMatchers()
.antMatchers( "/users/User", "/group", "/group/", "/group/entergroup/*", "/group/useringroup/")
.and().authorizeRequests()
.antMatchers( "/users/User", "/group", "/group/", "/group/entergroup/*", "/group/useringroup/" )
.access(
"hasAnyRole('USER', 'ADMIN')")
.and().requestMatchers().antMatchers( "/users/Admin")
.and().authorizeRequests()
.antMatchers("/users/Admin").access("hasRole('ADMIN')");*/
http
.authorizeRequests()
.antMatchers("/users/getAllUsersWithComplains").access("hasRole('ADMIN')")
.antMatchers("/oauth/token", "/oauth/authorize**", "/routes/randomRoutes", "/helloUser", "/users/sign-up", "/journeys/{Journey_ID}", "/group", "/yandex/driver", "/yandex/callback")
.permitAll()
.anyRequest().fullyAuthenticated()
;
}
}
|
package com.v1_4.mydiaryapp.com;
import android.graphics.Bitmap;
public class Obj_Screen{
String guid = "";
String appGuid = "";
String screenGuid = "";
String menuText = "";
String screenTitle = "";
String screenType = "";
String menuIcon = "";
String jsonScreenOptions = "";
Bitmap imgMenuIcon;
int showAsSelected = 0;
//constructor
public Obj_Screen(String _appGuid, String _screenGuid){
guid = _screenGuid;
appGuid = _appGuid;
screenGuid = _screenGuid;
}
//getters / setters
public String getAppGuid() {
return appGuid;
}
public void setAppGuid(String appGuid) {
this.appGuid = appGuid;
}
public void setGuid(String guid){
this.guid = guid;
}
public String getGuid(){
return guid;
}
public String getScreenGuid() {
return screenGuid;
}
public void setScreenGuid(String screenGuid) {
this.screenGuid = screenGuid;
}
public String getMenuText() {
return menuText;
}
public void setMenuText(String menuText) {
this.menuText = menuText;
}
public String getScreenTitle() {
return screenTitle;
}
public void setScreenTitle(String screenTitle) {
this.screenTitle = screenTitle;
}
public String getScreenType() {
return screenType;
}
public void setScreenType(String screenType) {
this.screenType = screenType;
}
public String getMenuIcon() {
return menuIcon;
}
public void setMenuIcon(String menuIcon) {
this.menuIcon = menuIcon;
}
public String getJsonScreenOptions() {
return menuIcon;
}
public void setJsonScreenOptions(String jsonScreenOptions) {
this.jsonScreenOptions = jsonScreenOptions;
}
public Bitmap getImgMenuIcon() {
return imgMenuIcon;
}
public void setImgMenuIcon(Bitmap imgMenuIcon) {
this.imgMenuIcon = imgMenuIcon;
}
public int getShowAsSelected() {
return showAsSelected;
}
public void setShowAsSelected(int theInt) {
this.showAsSelected = theInt;
}
}
|
package groupworkNamaste;
public class EmployeeStatistics {
private static double adminPercentage;
private static double managementPercentage;
private static double marketingPercentage;
private static double programmerPercentage;
private static double testerPercentage;
// SUBMENU for statistics
public static void subMenuStatistics() {
boolean x = true; //boolean used to run/break loop
// START CHOICE LOOP
do {// USER MAKES A CHOICE OF FOLLOWING
System.out.println("\n *~^~*~^~*~^~*~^~*~^~*\n SUBMENU STATISTICS\n *~^~*~^~*~^~*~^~*~^~*");
System.out.println("1 - Show total salary");
System.out.println("2 - Show total bonus");
System.out.println("3 - Show total wages (salary + bonus)");
System.out.println("4 - Show average wages in company");
System.out.println("5 - Find minimum salary");
System.out.println("6 - Find maximum salary");
System.out.println("7 - Print number of employees");
System.out.println("8 - Print all data");
System.out.println("9 - Print percentages of personell categories");
System.out.println("10 - Exit the statistics menu");
System.out.println("\nChoose acitivity by number ");
int choice = MainMenu.ourScanner.nextInt();
MainMenu.ourScanner.nextLine(); // EMPTY SCANNER
switch (choice) {
case 1:
calculateTotalSalary();
break;
case 2:
calculateTotalBonus();
break;
case 3:
calculateTotalWages();
break;
case 4:
calculateAverageWage();
break;
case 5:
findMinimumSalary();
break;
case 6:
findMaximumSalary();
break;
case 7:
printAll();
break;
case 8:
EmployeeDataBase.printArrayList();
break;
case 9:
printPercentages();
break;
case 10:
x = false; // SET EXIT LOOP VALUE
break;
default:
System.out.println("Ooops, please enter a number btw 1-3");
break;
} // END OF SWITCH
} // END OF DO LOOP
while (x);
// END OF LOOP
}
//meethods to calculate size of arraylist, total and average salary, bonus, wage, minimum and maximum salary,
public static void sizeOfArrayList() {
System.out.println("Size of list: " + EmployeeManagement.employeeList.size());
}
// total
public static double calculateTotalSalary() {
double totalSalary = 0;
for (SuperClassEmployee sce : EmployeeManagement.employeeList) {
totalSalary += sce.getSalary();
}
System.out.println("Total salary is " + totalSalary);
return totalSalary;
}
public static double calculateTotalBonus() {
double totalBonus = 0;
for (SuperClassEmployee sce : EmployeeManagement.employeeList) {
sce.bonusCalculation();
totalBonus += sce.getBonus();
}
System.out.println("Total bonus is " + totalBonus);
return totalBonus;
}
public static double calculateTotalWages() {
double totalWages = 0;
for (SuperClassEmployee sce : EmployeeManagement.employeeList) {
totalWages += sce.getSalary() + sce.getSalary();
;
}
System.out.println("Total wages is " + totalWages);
return totalWages;
}
public static double calculateAverageWage() {
double totalWages = 0;
for (SuperClassEmployee sce : EmployeeManagement.employeeList) {
totalWages += sce.getSalary() + sce.getSalary();
;
}
System.out.println("Average wage is " + totalWages / EmployeeManagement.employeeList.size());
return totalWages;
}
public static double findMinimumSalary() {
double min = 1000000000;
for (SuperClassEmployee sce : EmployeeManagement.employeeList) {
if (sce.getSalary() < min) {
min = sce.getSalary();
}
}
System.out.println("The lowest salary is: " + min);
return min;
}
public static double findMaximumSalary() {
double max = 0;
for (SuperClassEmployee sce : EmployeeManagement.employeeList) {
if (sce.getSalary() > max) {
max = sce.getSalary();
}
}
System.out.println("The highest salary is: " + max);
return max;
}
//methods used to print the number of employees in different categories
public static void printAll() {
System.out.println("The number of employees is " + SuperClassEmployee.getCounterId());
}
public static void printAdmin() {
System.out.println("The number of employees in this category is " + CategoryAdmin.getCounterAdmin());
}
public static void printMgt() {
System.out.println("The number of employees in this category is " + CategoryManagement.getCounterMgt());
}
public static void printMkt() {
System.out.println("The number of employees in this category is " + CategoryMarketing.getCounterMkt());
}
public static void printPro() {
System.out.println("The number of employees in this category is " + CategoryProgrammer.getCounterPro());
}
public static void printTst() {
System.out.println("The number of employees in this category is " + CategoryTesters.getCounterTst());
}
//methods used to calculate percentages
// TODO: integrate functionality
public static void printPercentages() {
System.out.println("The percentage of personnel that work in administration is " + ((double)CategoryAdmin.getCounterAdmin()/(double)SuperClassEmployee.getCounterId()*100) + "%");
System.out.println("The percentage of personnel that work in management is " + ((double)CategoryManagement.getCounterMgt()/(double)SuperClassEmployee.getCounterId()*100) + "%");
System.out.println("The percentage of personnel that work in marketing is " + ((double)CategoryMarketing.getCounterMkt()/(double)SuperClassEmployee.getCounterId()*100) + "%");
System.out.println("The percentage of programmers in the company is " + ((double)CategoryProgrammer.getCounterPro()/(double)SuperClassEmployee.getCounterId()*100) + "%");
System.out.println("The percentage of testers in the company is " + ((double)CategoryTesters.getCounterTst()/(double)SuperClassEmployee.getCounterId()*100) + "%");
}
public static double percentageAdmin() {
double adminPercentage = ((double)CategoryAdmin.getCounterAdmin()/(double)SuperClassEmployee.getCounterId()*100);
System.out.println("The percentage of personnel in administration is " + adminPercentage + "%");
return adminPercentage;
}
public static double percentageManagement() {
double managementPercentage = ((double)CategoryManagement.getCounterMgt()/(double)SuperClassEmployee.getCounterId()*100);
System.out.println("The percentage of personnel in management is " + managementPercentage + "%");
return managementPercentage;
}
public static double percentageMarketing() {
double marketingPercentage = ((double)CategoryMarketing.getCounterMkt()/(double)SuperClassEmployee.getCounterId()*100);
System.out.println("The percentage of personnel in marketing is " + marketingPercentage + "%");
return marketingPercentage;
}
public static double percentageProgrammer() {
double programmerPercentage = ((double)CategoryProgrammer.getCounterPro()/(double)SuperClassEmployee.getCounterId()*100);
System.out.println("The percentage of programmers in the company is " + programmerPercentage + "%");
return programmerPercentage;
}
public static double percentageTester() {
double testerPercentage = ((double)CategoryTesters.getCounterTst()/(double)SuperClassEmployee.getCounterId()*100);
System.out.println("The percentage of testers in the company is " + testerPercentage + "%");
return testerPercentage;
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.springframework.lang.Nullable;
/**
* Interface to discover parameter names for methods and constructors.
*
* <p>Parameter name discovery is not always possible, but various strategies are
* available to try, such as looking for debug information that may have been
* emitted at compile time, and looking for argname annotation values optionally
* accompanying AspectJ annotated methods.
*
* @author Rod Johnson
* @author Adrian Colyer
* @since 2.0
*/
public interface ParameterNameDiscoverer {
/**
* Return parameter names for a method, or {@code null} if they cannot be determined.
* <p>Individual entries in the array may be {@code null} if parameter names are only
* available for some parameters of the given method but not for others. However,
* it is recommended to use stub parameter names instead wherever feasible.
* @param method the method to find parameter names for
* @return an array of parameter names if the names can be resolved,
* or {@code null} if they cannot
*/
@Nullable
String[] getParameterNames(Method method);
/**
* Return parameter names for a constructor, or {@code null} if they cannot be determined.
* <p>Individual entries in the array may be {@code null} if parameter names are only
* available for some parameters of the given constructor but not for others. However,
* it is recommended to use stub parameter names instead wherever feasible.
* @param ctor the constructor to find parameter names for
* @return an array of parameter names if the names can be resolved,
* or {@code null} if they cannot
*/
@Nullable
String[] getParameterNames(Constructor<?> ctor);
}
|
package ru.vi.diskqueue;
import java.nio.ByteBuffer;
/**
* Implementation should be thread safe!!!
*
* User: arevkov
* Date: 3/18/13
* Time: 4:39 PM
*/
public interface Serializer<V> {
ByteBuffer encode(V v) throws Exception;
V decode(ByteBuffer bb) throws Exception;
}
|
//Figure 2-27 Main Class which uses the ProducerConsumerMonitor with multiple
// producers and consumers
import ProducerConsumerMonitor;
import Item;
class ProducerConsumer3 extends Thread {
private ProducerConsumerMonitor theMonitor;
// Inner classes for the Producers and Consumers
class Producer extends Thread {
public void run() {
while(true) {
Item data = produce_item();
System.out.println("Producer " + myNumber
+ " trying to insert");
theMonitor.insert(data);
try{sleep(1000);}
catch(InterruptedException ex){};
}
}
private Item produce_item(){
Item data;
try{sleep(1000);}
catch(InterruptedException ex){};
data = new Item(myNumber,itemCount++);
System.out.println("Producer " + myNumber
+ " making item " + data);
return data;
}
// Count of Items created
private int itemCount;
// Identification number for the Producer
private int myNumber;
public Producer(int x){
myNumber = x;
itemCount = 0;
}
}
public class Consumer extends Thread {
public void run() {
while(true) {
System.out.println("Consumer " + myNumber
+ " trying to remove");
Item data = theMonitor.remove();
consume_item(data);
}
}
private void consume_item(Item data){
System.out.println("Consumer " + myNumber
+ " used item " + data);
try{sleep(1000);}
catch(InterruptedException ex){};
}
// Identification number for the Consumer
private int myNumber;
public Consumer(int x){
myNumber = x;
}
}
// What the ProducerConsumer Thread does
public void run(){
theMonitor = new ProducerConsumerMonitor();
final int PRODUCERS = 10;
final int CONSUMERS = 10;
Producer p;
Consumer c;
// Make and start the Producer threads
for(int i=0; i<PRODUCERS; i++){
p = new Producer(i);
p.start();
}
// Make and start the Consumer threads
for(int i=0; i<CONSUMERS; i++){
c = new Consumer(i);
c.start();
}
}
// Start the whole thing going
public static void main(String args[]) {
ProducerConsumer3 pc = new ProducerConsumer3();
pc.start();
}
}
|
package hu.fallen.popularmovies.adapters;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import hu.fallen.popularmovies.R;
public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.ViewHolder> {
private static final String TAG = TrailerAdapter.class.getSimpleName();
private static final int VIEW_TYPE_REVIEW = 0;
private static final int VIEW_TYPE_SEPARATOR = 1;
private ArrayList<ReviewInfo> mReviewInfo;
public ReviewAdapter() { }
public void setReviewInfo(ArrayList<ReviewInfo> trailerInfo) {
mReviewInfo = trailerInfo;
}
@Override
public long getItemId(int position) {
return getItemViewType(position) == 0 ? position / 2 : -1;
}
@Override
public int getItemCount() {
return mReviewInfo == null || mReviewInfo.isEmpty() ? 0 : mReviewInfo.size() * 2 - 1;
}
private int count = 0;
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Log.d(TAG, String.format("onCreateViewHolder called: %d", count++));
View view;
if (viewType == VIEW_TYPE_SEPARATOR) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.separator, parent, false);
} else {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_review, parent, false);
}
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
if (getItemViewType(position) == VIEW_TYPE_SEPARATOR) {
Log.d(TAG, String.format("onBindViewHolder called: %d (separator)", position));
return; // no change needed
}
final ReviewInfo reviewInfo = mReviewInfo.get(position / 2);
String trailerTitle = reviewInfo.toString();
Log.d(TAG, String.format("onBindViewHolder called: %d (%s)", position, trailerTitle));
((TextView) holder.itemView.findViewById(R.id.tv_author)).setText(reviewInfo.author);
((TextView) holder.itemView.findViewById(R.id.tv_content)).setText(reviewInfo.content);
}
@Override
public int getItemViewType(int i) {
return i % 2 == 0 ? VIEW_TYPE_REVIEW : VIEW_TYPE_SEPARATOR;
}
public ArrayList<ReviewInfo> getReviewInfo() {
return mReviewInfo;
}
class ViewHolder extends RecyclerView.ViewHolder {
ViewHolder(View itemView) {
super(itemView);
}
}
}
|
package com.willian.Estoque.resources;
import com.willian.Estoque.domain.Cliente;
import com.willian.Estoque.domain.Marca;
import com.willian.Estoque.service.ClienteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = "/clientes")
public class ClienteResource {
@Autowired
private ClienteService service;
@CrossOrigin
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Cliente> findById(@PathVariable Integer id) {
Cliente cliente = service.findById(id);
return ResponseEntity.ok().body(cliente);
}
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<Cliente>> findAll(){
List<Cliente> lista = service.findAll();
return ResponseEntity.ok().body(lista);
}
}
|
package CarModel;
/**
* Created by Mr. Crapfruit on 21.11.2015.
*/
import Highway.Highway;
public class Sensor {
private static final int SPEED_FACTOR = 1;
private Highway Highway;
private Location Location;
private Car car;
public Sensor(Highway highway, Location location) {
this.Highway = highway;
this.Location = location;
}
public void setHighway(Highway highway) {
this.Highway = highway;
}
public void setCar(Car car) {
this.car = car;
}
public SensorData getSensorData() {
Car CarInFront = getCarInFront();
if(CarInFront == null) {
return null;
}
int distance = (CarInFront.getCurrentSpeed() * SPEED_FACTOR) + CarInFront.getPosition() - (getFuturePosition());
return new SensorData(distance, CarInFront.getCurrentSpeed());
}
public boolean checkLeftLane() {
// Integer lowerPos = Highway.leftLane.lowerKey(Location.getPosition());
// Integer higherPos = Highway.leftLane.higherKey(Location.getPosition());
// int lowerFuturePos = getFuturePosition();
// int higherFuturePos = getFuturePosition();
// int myFuturePos = getFuturePosition();
return false;
}
public void updateCar(Integer oldPos) {
if(car != null) {
Integer pos = Location.getPosition();
this.Highway.bufferedLane.put(pos, car);
}
}
private Car getCarInFront() {
Integer key;
if (Location.getLane().equals("right")) {
key = Highway.rightLane.higherKey(Location.getPosition());
if (key == null) return null;
return Highway.rightLane.get(key);
}
key = Highway.leftLane.higherKey(Location.getPosition());
if (key == null) return null;
return Highway.leftLane.get(key);
}
private int getFuturePosition() {
return (car.getCurrentSpeed() * SPEED_FACTOR) + car.getPosition();
}
}
|
package Utilities;
import java.awt.geom.Point2D;
//This should be replaced with java.awt.Point
public class Coordinates extends Point2D{
public double yLoc, xLoc;
public Coordinates(int xLoc, int yLoc){
this.xLoc = xLoc;
this.yLoc = yLoc;
}
public Coordinates(double xLoc, double yLoc){
this.xLoc = xLoc;
this.yLoc = yLoc;
}
public double getYLoc(){
return yLoc;
}
public double getXLoc(){
return xLoc;
}
public String toString(){
return xLoc+", "+yLoc;
}
@Override
public double getX() {
// TODO Auto-generated method stub
return xLoc;
}
@Override
public double getY() {
// TODO Auto-generated method stub
return yLoc;
}
@Override
public void setLocation(double arg0, double arg1) {
xLoc = arg0;
yLoc = arg1;
}
}
|
/**
* @author filipe.pinheiro, 29/09/2018
*/
package mt.com.vodafone.controller;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import mt.com.vodafone.entity.*;
import mt.com.vodafone.service.SubscriberService;
@RestController
@RequestMapping("/api")
@CrossOrigin("*")
public class SubscriberController {
private final Logger LOG = LoggerFactory.getLogger(SubscriberController.class);
@Autowired
private SubscriberService service;
@GetMapping(path = "/subscribers")
public Iterable<Subscriber> getAllMobileSubscribers() throws Throwable {
return service.findAll();
}
@GetMapping(path = "/subscribers/{id}")
public Subscriber getMobileSubscriberById(@PathVariable Integer id) throws Throwable {
LOG.debug("id", id);
return service.findById(id);
}
@PostMapping(path = "/subscribers")
public Subscriber addMobileSubscriber(@Valid @RequestBody Subscriber subscriber) throws Throwable {
LOG.debug("subscriber", subscriber);
return service.save(subscriber);
}
@PutMapping("/subscribers/{id}")
public Subscriber updateMobileSubscriber(@Valid @RequestBody Subscriber newSubscriber, @PathVariable Integer id)
throws Throwable {
LOG.debug("id", id);
LOG.debug("newSubscriber", newSubscriber);
return service.merge(id, newSubscriber);
}
@DeleteMapping("/subscribers/{id}")
public ResponseEntity<Subscriber> deleteMobileSubscriber(@PathVariable Integer id) throws Throwable {
LOG.debug("id", id);
service.delete(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
|
package com.schappet.inv.controller;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.servlet.ModelAndView;
import com.schappet.inv.domain.Message;
import com.schappet.inv.domain.Person;
import edu.uiowa.icts.exception.MappingNotFoundException;
@Controller
@RequestMapping("/*")
public class DefaultController extends AbstractInvController {
private static final Log log = LogFactory.getLog(DefaultController.class);
@RequestMapping("/**")
public void mappingNotFound(HttpServletRequest request, HttpServletResponse response) throws MappingNotFoundException {
throw new MappingNotFoundException(request.getRequestURL().toString());
}
@RequestMapping(value = "indentified.html", method = RequestMethod.GET)
public ModelAndView indentified( HttpServletRequest req,HttpServletResponse res ){
ModelMap model = new ModelMap();
return new ModelAndView("indentified",model);
}
@RequestMapping(value = "de-indentified.html", method = RequestMethod.GET)
public ModelAndView deIndentified( HttpServletRequest req,HttpServletResponse res ){
ModelMap model = new ModelMap();
return new ModelAndView("de-indentified",model);
}
@RequestMapping(value = "{ page }.html", method = RequestMethod.GET)
public ModelAndView displayDefault(@PathVariable String page,HttpServletRequest req,HttpServletResponse res){
ModelMap model = new ModelMap();
return new ModelAndView(page,model);
}
@RequestMapping(value = "access_denied.html", method = RequestMethod.GET)
public ModelAndView accessDenied(@RequestParam(value="requestUri", required=false) String page, HttpServletRequest req,HttpServletResponse res){
ModelMap model = new ModelMap();
model.addAttribute("message", invDaoService.getMessageService().getCurrentMessage("ACCESS_DENIED"));
model.addAttribute("page", page);
return new ModelAndView("access_denied", model);
}
@RequestMapping(value = "alive.html", method = RequestMethod.GET)
public void alive( HttpServletResponse response ) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream("ALIVE".getBytes());
IOUtils.copy(bais, response.getOutputStream());
bais.close();
} catch (IOException e){
log.error("error during keep alive",e);
}
}
@RequestMapping(value = "faq.html", method = RequestMethod.GET)
public ModelAndView faq(HttpServletRequest req,HttpServletResponse res){
ModelMap model = new ModelMap();
model.addAttribute("message", invDaoService.getMessageService().getCurrentMessage("faq"));
return new ModelAndView("faq", model);
}
@RequestMapping(value = "profile.html", method = RequestMethod.GET)
public ModelAndView profile(HttpServletRequest req,HttpServletResponse res){
ModelMap model = new ModelMap();
Person person = invDaoService.getPersonService().findByUsername(getUsername());
model.addAttribute("person",person);
return new ModelAndView("inv/person/edit",model);
}
@RequestMapping(value = "contact.html", method = RequestMethod.GET)
public ModelAndView contact(HttpServletRequest req,HttpServletResponse res){
ModelMap model = new ModelMap();
model.addAttribute("message", invDaoService.getMessageService().getCurrentMessage("contact"));
return new ModelAndView("contact",model);
}
@RequestMapping(value = "message.html", method = RequestMethod.GET)
public ModelAndView message(HttpServletRequest req,HttpServletResponse res,
@RequestParam("message") String message,
@RequestParam(value="error",required=false,defaultValue="false") Boolean error ){
ModelMap model = new ModelMap();
model.addAttribute("message", message);
model.addAttribute("error", error);
return new ModelAndView("message",model);
}
@RequestMapping(value = {"/","index.html"}, method = RequestMethod.GET)
public ModelAndView index( HttpServletRequest request, @RequestParam(value="error", required=false) String error, @RequestParam(value="info", required=false) String info) {
ModelMap model = new ModelMap();
Message message = invDaoService.getMessageService().getCurrentMessage("main.index");
if( message == null ){
message = new Message();
message.setMessageText( "<div class=\"alert alert-error\">main.index message not found</div>" );
}
model.addAttribute("message", message );
if( info != null ){
model.addAttribute("info", info);
}
if( error != null ){
model.addAttribute("error", error);
}
return new ModelAndView("index",model);
}
@RequestMapping(value = "error.html", method = RequestMethod.GET)
public ModelAndView error(HttpServletRequest request) {
ModelMap model = new ModelMap();
log.error("Error URI: " + request.getAttribute("javax.servlet.error.request_uri")) ;
log.error("Error Message: " + request.getAttribute("javax.servlet.error.message"), (Throwable) request.getAttribute("javax.servlet.error.exception"));
return new ModelAndView("error",model);
}
@RequestMapping(value = "switch_user.html", method = RequestMethod.GET)
public ModelAndView switch_user(@RequestParam(value="error", required=false) Boolean error) {
ModelMap model = new ModelMap();
model.addAttribute("error", error);
return new ModelAndView("/admin/switch_user",model);
}
@RequestMapping(value = "charts.html")
public ModelAndView charts(HttpServletRequest req) {
ModelMap model = new ModelMap();
return new ModelAndView("mainTemplate|charts",model);
}
@RequestMapping(value = "get_names.html")
public ModelAndView getNames(@RequestParam("first") String first, @RequestParam("last") String last, @RequestParam("var_name") String var_name){
ModelMap model = new ModelMap();
model.addAttribute("first", first);
model.addAttribute("last", last);
model.addAttribute("var", var_name);
return new ModelAndView("bodyOnlyTemplate|get_names", model);
}
@RequestMapping(value = "login.html", method = RequestMethod.GET)
public ModelAndView login(@RequestParam(value = "error", required=false) String error, HttpServletRequest req) {
ModelMap model = new ModelMap();
model.addAttribute("error", error);
return new ModelAndView("baseTemplateWide|login",model);
}
@RequestMapping(value = "logout.html", method = RequestMethod.GET)
public ModelAndView logout(HttpServletRequest req, HttpServletResponse res) {
ModelMap model = new ModelMap();
req.getSession().invalidate();
return new ModelAndView("redirect:index.html",model);
}
@RequestMapping(value = "roles.html")
public String roles() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if( auth != null ){
Collection<? extends GrantedAuthority> auths = auth.getAuthorities();
for( GrantedAuthority ga : auths ){
log.debug( ga.getAuthority() );
}
} else {
log.debug( "no authentication object" );
}
return "redirect:/index.html";
}
} |
package com.krixon.ecosystem.profiling.web.field;
import com.krixon.ecosystem.profiling.domain.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.ExposesResourceFor;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@ExposesResourceFor(Field.class)
@RequestMapping("/fields")
public class FieldController
{
private final FieldRepository fieldRepository;
private final FieldResourceAssembler assembler;
public FieldController(FieldRepository fieldRepository, FieldResourceAssembler assembler)
{
this.fieldRepository = fieldRepository;
this.assembler = assembler;
}
@GetMapping
public ResponseEntity<? extends ResourceSupport> collection(
@PageableDefault Pageable p,
PagedResourcesAssembler<Field> pageAssembler
) {
Page<Field> page = fieldRepository.findAll(p);
PagedResources resource = pageAssembler.toResource(page, assembler);
return new ResponseEntity<>(resource, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<? extends ResourceSupport> one(@PathVariable("id") String id)
{
Optional<Field> field = fieldRepository.findById(id);
if (!field.isPresent()) {
return ResponseEntity.notFound().build();
}
FieldResource resource = assembler.toResource(field.get());
return new ResponseEntity<>(resource, HttpStatus.OK);
}
@PutMapping("/{id}")
public ResponseEntity<?> define(
@PathVariable("id") String id,
@RequestBody FieldResource resource
) {
Field field = fieldRepository
.findById(id)
.map(f -> {
if (resource.getPanel() == null) {
f.promoteToGlobal();
} else {
f.transferToPanel(resource.getPanel());
}
f.rename(resource.getName());
return f;
})
.orElseGet(() -> Field.define(id, resource.getName(), resource.getPanel()));
Field savedField = fieldRepository.save(field);
FieldResource newResource = assembler.toResource(savedField);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(newResource.getLink("self").getTemplate().expand());
return new ResponseEntity<>(newResource, headers, HttpStatus.CREATED);
}
}
|
package main.java;
import java.util.ArrayList;
import java.util.List;
public class Teach {
public String teacher;
public String classroom;
public String course;
public int capacity;
public List<Time> time;
public Teach(String teacher, String classroom, String course, int capacity, ArrayList<Time> time) {
super();
this.teacher = teacher;
this.classroom = classroom;
this.course = course;
this.capacity = capacity;
this.time = new ArrayList<Time>();
this.time.addAll(time);
}
}
|
package com.nopcommerce.demo.topmenupage;
import com.nopcommerce.demo.pages.TopMenuPage;
import com.nopcommerce.demo.testbase.TestBase;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TopMenuTest extends TestBase {
TopMenuPage topMenuPage = new TopMenuPage();
//e class "TopMenuTest"
// 1.1 create method with name "selectMenu" it has one parameter name "menu" of type string
// 1.2 This method should click on the menu whatever name is passed as parameter.
// 1.3. create the @Test method name verifyPageNavigation.use selectMenu method to select the Menu and click on it and verify the page navigation.
@Test
public void verifyUserShouldNavigateToTopMenuPage() throws InterruptedException {
topMenuPage.selectMenu("Computers");
String expectedMessage = "Computers";
String actualMessage = topMenuPage.verifyComputerPages();
Assert.assertEquals(actualMessage, expectedMessage);
topMenuPage.selectMenu("Electronics");
String expectedMessage1 = "Electronics";
String actualMessage1 = topMenuPage.verifyElectronicspages();
Assert.assertEquals(actualMessage1, expectedMessage1);
topMenuPage.selectMenu("Apparel");
String expectedMessage2 = "Apparel";
String actualMessage2 = topMenuPage.verifyAppearlPages();
Assert.assertEquals(actualMessage2, expectedMessage2);
topMenuPage.selectMenu("Digital downloads");
String expectedMessage3 = "Digital downloads";
String actualMessage3 = topMenuPage.verifydigitalDowanload();
Assert.assertEquals(actualMessage2, expectedMessage2);
topMenuPage.selectMenu("Books");
String expectedMessage4 = "Books";
String actualMessage4 = topMenuPage.verifyBooksPages();
Assert.assertEquals(actualMessage4, expectedMessage4);
topMenuPage.selectMenu("Jewelry");
String expectedMessage5 = "Jewelry";
String actualMessage5 = topMenuPage.verifyJewlrypages();
Assert.assertEquals(actualMessage5, expectedMessage5);
topMenuPage.selectMenu("Gift Cards");
String expectedMessage6 = "Gift Cards";
String actualMessage6 = topMenuPage.verifyGiftcardspages();
Assert.assertEquals(actualMessage6, expectedMessage6);
}
}
|
package com.example.scso.school_social;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.BootstrapEditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
public class FileInformationActivity extends Activity {
private ImageView iv_back;
private TextView tv_back;
private TextView file_name;
private BootstrapButton file_load;
private ImageView file_img;
private TextView file_describe;
private ImageView file_like;
private String file_id;
private String load_url;
private String likes;
private String username;
private String target_user_id;
private String target_user_name;
private ListView pinglun_list;
private JSONObject json;
private BootstrapEditText pinglun_edit;
private BootstrapButton pinglun_button;
private BootstrapButton huifu_button;
private ArrayList<HashMap<String,String>> pinglun_data_list;
private String user_id;
private String type="file";
private Handler handler1;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_information);
username=getIntent().getStringExtra("user_id");
initview();
back();
Intent intent=getIntent();
file_id=intent.getStringExtra("file_id");
post(file_id,posthandler);
pinglun();
like();
load();
}
public void pinglun(){
handler1=new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==3){
Toast.makeText(FileInformationActivity.this,"评论成功",Toast.LENGTH_SHORT).show();
pinglun_edit.setText("");
get_data(handler);
}
else{
Toast.makeText(FileInformationActivity.this,"评论失败,请稍后再试",Toast.LENGTH_SHORT).show();
}
}
};
pinglun_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (TextUtils.isEmpty(pinglun_edit.getText())) {
Toast.makeText(FileInformationActivity.this, "评论不能为空", Toast.LENGTH_SHORT).show();
} else {
json = new JSONObject();
try {
json.put("type", type);
json.put("id", file_id);
json.put("user_id", user_id);
json.put("content", pinglun_edit.getText().toString());
json.put("is_huifu", 0);
} catch (JSONException e) {
e.printStackTrace();
}
HttpPost httpPost = new HttpPost(json, "pinglun.jsp", handler1);
httpPost.doPost();
}
}
});
huifu_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(PinglunActivity.this,"huifu",Toast.LENGTH_SHORT).show();
if (TextUtils.isEmpty(pinglun_edit.getText())) {
Toast.makeText(FileInformationActivity.this, "评论不能为空", Toast.LENGTH_SHORT).show();
} else {
json = new JSONObject();
try {
json.put("type", type);
json.put("id", file_id);
json.put("user_id", user_id);
json.put("is_huifu", 1);
json.put("target_user_id", target_user_id);
json.put("content", "回复 @" + target_user_name + " :" + pinglun_edit.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
HttpPost httpPost = new HttpPost(json, "pinglun.jsp", handler1);
httpPost.doPost();
}
}
});
pinglun_list.setOnItemClickListener(new ListListener());
handler=new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==3){
pinglun_data_list=new ArrayList<>();
JSONArray pinglunJSON=(JSONArray) msg.obj;
Log.e("a",pinglunJSON.toString());
try {
for (int i = 0; i < pinglunJSON.length(); i++) {
HashMap<String, String> data = new HashMap<>();
data.put("user_name", pinglunJSON.getJSONObject(i).getString("user_name"));
data.put("user_id",pinglunJSON.getJSONObject(i).getString("user_id"));
data.put("date_time",pinglunJSON.getJSONObject(i).getString("date_time"));
data.put("content",pinglunJSON.getJSONObject(i).getString("content"));
Log.e("666",data.toString());
pinglun_data_list.add(data);
}
}catch (JSONException e){
e.printStackTrace();
}
SimpleAdapter adapter=new SimpleAdapter(FileInformationActivity.this,pinglun_data_list,R.layout.pinglun_list_layout,
new String[] {"user_name","user_id","date_time","content"},new int[] {R.id.user_name,R.id.user_id,
R.id.date_time,R.id.content});
pinglun_list.setAdapter(adapter);
}
else{
Toast.makeText(FileInformationActivity.this,"获取评论失败",Toast.LENGTH_SHORT);
}
}
};
get_data(handler);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode== KeyEvent.KEYCODE_BACK && huifu_button.getVisibility()==View.VISIBLE){
huifu_button.setVisibility(View.GONE);
pinglun_button.setVisibility(View.VISIBLE);
}
else{
finish();
}
return false;
}
public class ListListener implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int now_position=position-parent.getFirstVisiblePosition();
View v=(View)parent.getChildAt(now_position);
TextView user_id_text=(TextView) v.findViewById(R.id.user_id);
TextView user_name_text=(TextView) v.findViewById(R.id.user_name);
//TextView id_text=(TextView)layout.findViewById(R.id.goods_id);
target_user_id=user_id_text.getText().toString();
target_user_name=user_name_text.getText().toString();
pinglun_edit.clearFocus();
InputMethodManager imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0,InputMethodManager.SHOW_IMPLICIT);
pinglun_button.setVisibility(View.GONE);
huifu_button.setVisibility(View.VISIBLE);
}
}
public void get_data(Handler handler){
Log.d("tag", "get_data: ");
JSONObject json=new JSONObject();
try {
json.put("type",type);
json.put("id",file_id);
} catch (JSONException e) {
e.printStackTrace();
}
HttpPost httpPost=new HttpPost(json,"get_pinglun.jsp",handler);
httpPost.doPost();
}
public void load() {
file_load.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder dialog=new AlertDialog.Builder(FileInformationActivity.this);
dialog.setTitle(file_name.getText().toString());
dialog.setIcon(file_img.getDrawable());
dialog.setMessage("是否确认下载");
dialog.setCancelable(true);
dialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String url = "http://118.89.199.187/school_social/file" + load_url;
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalPublicDir("/school_social/"+username+"/", file_name.getText().toString());
Log.e("aa","http://118.89.199.187/school_social/file" + load_url);
Log.e("aa",file_name.getText().toString());
DownloadManager downloadManager = (DownloadManager) FileInformationActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
long reference = downloadManager.enqueue(request);
////加入下载队列后会给该任务返回一个long型的id,
//通过该id可以取消任务,重启任务等等
//在通知栏中显示,默认就是显示的
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.allowScanningByMediaScanner();//允许被扫描
request.setTitle("文件下载");
initFinishRecicever(reference);
}
});
dialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
});
}
private void initFinishRecicever(final long reference) {
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long references = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (references == reference) {
Toast.makeText(FileInformationActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
}
}
};
registerReceiver(receiver, intentFilter);
}
private Handler postlikehandler=new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.arg1==4){
file_like.setImageResource(R.drawable.like1);
file_like.setTag("1");
}
else file_like.setTag("0");
}
};
private Handler posthandler=new Handler(){
@Override
public void handleMessage(Message msg) {
setview((HashMap<String, String>) msg.obj);
}
};
public void like()
{
file_like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
JSONObject json = new JSONObject();
if (file_like.getTag().equals("1")) {
file_like.setImageResource(R.drawable.like);
file_like.setTag("0");
try {
json.put("do", "quxiao");
json.put("user_id", username);
json.put("file_id", file_id);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
file_like.setImageResource(R.drawable.like1);
file_like.setTag("1");
try {
json.put("do", "dianzan");
json.put("user_id", username);
json.put("file_id", file_id);
} catch (JSONException e) {
e.printStackTrace();
}
}
HttpPost httpPost = new HttpPost(json, "file_dianzan.jsp", new Handler());
httpPost.doPost();
}
});
}
private void back()
{
iv_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
tv_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private void initview()
{
pinglun_list =(ListView) findViewById(R.id.pinglunlist);
pinglun_edit = (BootstrapEditText) findViewById(R.id.pinglun_edit);
pinglun_edit.clearFocus();
pinglun_button= (BootstrapButton) findViewById(R.id.pinglun_button);
huifu_button= (BootstrapButton) findViewById(R.id.huifu_button);
file_describe= (TextView) findViewById(R.id.file_describe);
file_img= (ImageView) findViewById(R.id.file_type);
file_like= (ImageView) findViewById(R.id.like);
file_name= (TextView) findViewById(R.id.file_name);
file_load= (BootstrapButton) findViewById(R.id.file_load);
iv_back=(ImageView) findViewById(R.id.tab_back);
tv_back=(TextView)findViewById(R.id.tab_back1);
}
public void post(final String file_id, final Handler posthandler){
new Thread(new Runnable() {
@Override
public void run() {
HashMap<String,String> service=new HashMap<>();
String uriAPI = null;
try {
uriAPI = "http://118.89.199.187/school_social/jsp/get_fileinformation.jsp?id=" + URLEncoder.encode(file_id,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
URL url=new URL(uriAPI);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String jsonstr = URLDecoder.decode(in.readLine(), "utf-8");
final JSONObject jsonObject = new JSONObject(jsonstr);
JSONArray data = jsonObject.getJSONArray("Data");
for(int i=0;i<data.length();i++){
service.put("name",data.getJSONObject(i).getString("name"));
service.put("type",data.getJSONObject(i).getString("type"));
service.put("size",data.getJSONObject(i).getString("size"));
service.put("url",data.getJSONObject(i).getString("url"));
service.put("describe",data.getJSONObject(i).getString("describe"));
service.put("likes",data.getJSONObject(i).getString("likes"));
}
Message msg=Message.obtain(posthandler,3);
msg.obj=service;
posthandler.sendMessage(msg);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
}
public void setview(HashMap<String,String> service){
file_name.setText(service.get("name"));
file_describe.setText("文件描述:\n"+service.get("describe"));
file_load.setText("下载文件("+service.get("size")+")");
likes=service.get("likes");
load_url=service.get("url");
user_id=username;
String type=service.get("type");
if (type.equals("txt"))file_img.setImageResource(R.drawable.txt);
else if (type.equals("docx")||type.equals("doc")||type.equals("docm")||type.equals("dotx")||type.equals("dotm"))file_img.setImageResource(R.drawable.docx);
else if (type.equals("pptx")||type.equals("pptm")||type.equals("ppt")||type.equals("ppsx")||type.equals("potx")||type.equals("potm"))file_img.setImageResource(R.drawable.ppt);
else if (type.equals("xls")||type.equals("xlt")||type.equals("xlsx")||type.equals("xlsm")||type.equals("xltx")||type.equals("xltm")||type.equals("xlsb"))file_img.setImageResource(R.drawable.excel);
else if (type.equals("rar")||type.equals("zip"))file_img.setImageResource(R.drawable.rar);
else if (type.equals("pdf"))file_img.setImageResource(R.drawable.pdf);
else if (type.equals("bmp")||type.equals("jpg")||type.equals("png")||type.equals("tiff")||type.equals("gif")||type.equals("pcx")
||type.equals("tga")||type.equals("exif")||type.equals("fpx") ||type.equals("svg")||type.equals("psd")||type.equals("cdr")
||type.equals("pcd")||type.equals("dxf")||type.equals("ufo")||type.equals("eps")||type.equals("ai")||type.equals("raw")
||type.equals("WMF"))file_img.setImageResource(R.drawable.picture);
else file_img.setImageResource(R.drawable.file_else);
postlike(file_id,user_id,postlikehandler);
}
public void postlike(final String file_id, final String user_id,final Handler postlikehandler){
new Thread(new Runnable() {
@Override
public void run() {
HashMap<String,String> service=new HashMap<>();
String uriAPI = null;
uriAPI = "http://118.89.199.187/school_social/jsp/get_wholike.jsp?file_id=" + file_id+"&user_id="+user_id;
try {
URL url=new URL(uriAPI);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String jsonstr = URLDecoder.decode(in.readLine(), "utf-8");
final JSONObject jsonObject = new JSONObject(jsonstr);
JSONArray data = jsonObject.getJSONArray("Data");
if(String.valueOf(data).equals("[]")){
Message msg=Message.obtain(postlikehandler,3);
msg.arg1=8;
Log.w("asd", String.valueOf(msg.arg1));
postlikehandler.sendMessage(msg);
}
else {
Message msg=Message.obtain(postlikehandler,3);
msg.arg1=4;
Log.w("asd", String.valueOf(msg.arg1));
postlikehandler.sendMessage(msg);
}
Log.w("qwe", String.valueOf(String.valueOf(data).equals("[]")));
Log.w("asd", String.valueOf(data));
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
}
}
|
package com.codecool.movieorganizer.service.dao.jpa;
import com.codecool.movieorganizer.config.StorageProperties;
import com.codecool.movieorganizer.model.Movie;
import com.codecool.movieorganizer.service.CharacterActorMovieMapService;
import com.codecool.movieorganizer.service.MovieCharacterService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import java.time.LocalDateTime;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
@TestPropertySource(properties = "storage.type=db")
@Import({MovieDaoDb.class, StorageProperties.class, CharacterActorMovieMapService.class, MovieCharacterService.class})
@ActiveProfiles("test")
class MovieDaoDbTest {
@Autowired
private MovieDaoDb movieDao;
@BeforeEach
void setUp() {
Set<String> categories = new HashSet<>(Arrays.asList("dark", "sci-fi"));
Movie alien = Movie.builder()
.title("alien")
.addedTime(LocalDateTime.now())
.lastModified(LocalDateTime.now())
.categories(categories)
.build();
movieDao.add(alien);
}
@Test
void categoriesArePersistedWithMoviesCorrectly() {
Movie joker = Movie.builder()
.title("joker")
.addedTime(LocalDateTime.now())
.lastModified(LocalDateTime.now())
.categories(new HashSet<>(Arrays.asList("Drama", "Crime")))
.build();
Movie jokerFromDb = movieDao.add(joker);
assertSame(joker, jokerFromDb);
assertThat(movieDao.find(joker.getId()).getCategories()).hasSize(2);
}
@Test
void whenMoviesAreUpdated_CategoriesShouldBeMappedToThem() {
Movie alien = movieDao.findByTitle("alien");
Movie newAlien = Movie.builder()
.title("alien")
.categories(new HashSet<>(Arrays.asList("extra", "dark", "sci-fi")))
.build();
movieDao.update(alien.getId(), newAlien);
assertThat(alien.getCategories()).hasSize(3);
}
@Test
void addNewMovieThanDeleteItShouldNotBeIn() {
Movie joker = Movie.builder()
.title("joker")
.addedTime(LocalDateTime.now())
.lastModified(LocalDateTime.now())
.categories(new HashSet<>(Arrays.asList("drama", "crime")))
.build();
movieDao.add(joker);
movieDao.remove(movieDao.findByTitle("alien").getId());
assertThat(movieDao.findByTitle("alien")).isEqualTo(null);
}
@Test
void whenMoviesAreUpdated_AndAnExistingCategoryIsAttachedToThem_ItShouldGoDownTheHappyPath() {
Movie alien = movieDao.findByTitle("alien");
Movie newAlien = Movie.builder()
.title("alien")
.categories(new HashSet<>(Arrays.asList("dark", "sci-fi", "horror")))
.build();
assertDoesNotThrow(() -> movieDao.update(alien.getId(), newAlien));
assertThat(alien.getCategories()).hasSize(3);
}
} |
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations;
import org.giddap.dreamfactory.leetcode.onlinejudge.GasStation;
/**
*
*/
public class GasStationTwoLoopImpl implements GasStation {
public int canCompleteCircuit(int[] gas, int[] cost) {
final int len = gas.length;
int[] deltas = new int[gas.length];
for (int i = 0; i < len; i++) {
deltas[i] = gas[i] - cost[i];
}
int i = 0;
while (i < len && deltas[i] >= 0) {
int j = i;
int r = deltas[i];
while (r >= 0) {
j = (j + 1) % len;
if (j == i) {
return i;
}
r += deltas[j];
}
i++;
}
return -1;
}
}
|
package Problem_14651;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
double k = 1e9+9;
long[] dp = new long[33334];
dp[1] = 0; dp[2] = 2;
for(int i = 3; i<=N;i++) {
dp[i] = (long) ((dp[i-1]*3) % k);
}
System.out.println(dp[N]);
}
}
|
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import java.text.DecimalFormat;
import static javafx.application.Application.launch;
public class Main extends Application {
public void switchUI(String fileName, Label locator){
try {
Parent root = FXMLLoader.load(getClass().getResource(fileName));
Stage stage = (Stage) locator.getScene().getWindow();
Scene scene = new Scene(root, 1600,900);
stage.setScene(scene);
}
catch(Exception e){
e.printStackTrace();
}
}
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/ChoicePane.fxml"));
Scene scene = new Scene(root, 1600, 900);
primaryStage.setScene(scene);
primaryStage.setTitle("Set Up");
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static double totalPE;
public static double SPE;
public double EarthMassx24 = 5.972;
public double MarsMassx23 = 6.39;
public double SunMassx30 = 1.989;
public double ISSMass = 417289;
public double MoonMassx22 = 7.34767309;
public double aBombPowerx9 = 4.184;
DecimalFormat df = new DecimalFormat("#.###");
public double G = .0000000000667;
public static void main(String[] args) {
launch(args);
}
}
|
package gov.nih.mipav.view;
import java.io.*;
import javax.swing.tree.*;
/**
* This class is used to represent a file system in a tree. This is a node of the file system. It has a java.io.File as
* its user object.
*
* <p>Nodes in the tree are expanded by calling this class's explore method. You can set the explore method to return
* only directories by setting the directoriesOnly flag. Additionally you can call explore with a file filter, and only
* nodes that satisfy that file filter will be returned. Directories are verified to contain valid files before they are
* added to the tree.</p>
*
* <p>Basic structure of class taken from Sun's Graphic Java Swing "Trees" section.</p>
*
* @author David Parsons
* @author Neva Cherniavsky
* @see ViewImageDirectory
* @see JDialogAnonymizeDirectory
*/
public class ViewFileTreeNode extends DefaultMutableTreeNode {
//~ Static fields/initializers -------------------------------------------------------------------------------------
/** Use serialVersionUID for interoperability. */
private static final long serialVersionUID = 2761808148905905365L;
//~ Instance fields ------------------------------------------------------------------------------------------------
/** DOCUMENT ME! */
private boolean directoriesOnly = false;
/** DOCUMENT ME! */
private boolean explored = false;
/** DOCUMENT ME! */
private boolean rootfile = false;
//~ Constructors ---------------------------------------------------------------------------------------------------
/**
* Loads a File into the tree-leaf.
*
* @param node File for tree leaf.
*/
public ViewFileTreeNode(File node) {
setUserObject(node);
}
/**
* Loads a File into a tree-leaf. This method permits telling the node that the file is a root for the filesystem.
*
* <p>It can be useful to remember whether or not the given file was a root. (which is not information normally
* stored by the File.)</p>
*
* @param node File for tree leaf.
* @param fsRoot Flag indicating if this is a root.
*/
public ViewFileTreeNode(File node, boolean fsRoot) {
this(node);
rootfile = fsRoot;
}
//~ Methods --------------------------------------------------------------------------------------------------------
/**
* Adds the children of this file to the this FileNode for display in a JTree. adjusts the <code>explored</code>
* variable. Does nothing if the FileNode is not a directory or if the node has already been explored. If
* directories only are to be explored, then the only children to be added will be directories; otherwise, all files
* in the directory will be added to the node.
*
* <p>Implementation of this is different from the Sun Books' code.</p>
*/
public void explore() {
explore(null);
}
/**
* Adds the children of this file to the this FileNode for display in a JTree. adjusts the <code>explored</code>
* variable. Does nothing if the FileNode is not a directory or if the node has already been explored. If
* directories only are to be explored, then the only children to be added will be directories. Otherwise, if the
* file filter is not null, only the files that satisfy the filter will be added. If the filter is null, all files
* will be added.
*
* <p>Implementation of this is different from the Sun Books' code.</p>
*
* @param filter File filter; can be null.
*/
public void explore(ViewImageFileFilter filter) {
if (!isDirectory()) {
return;
}
if (!isExplored()) {
File file = getFile();
File[] children = file.listFiles();
if (children == null) {
explored = true;
return;
}
// else
for (int i = 0; i < children.length; i++) {
if (directoriesOnly) {
if (children[i].isDirectory()) {
ViewFileTreeNode node = new ViewFileTreeNode(children[i]);
if (node.hasValidChildren(filter)) {
node.exploreDirectoriesOnly(true);
add(node);
}
}
} else {
if (filter == null) {
add(new ViewFileTreeNode(children[i]));
} else {
if (children[i].isDirectory()) {
ViewFileTreeNode node = new ViewFileTreeNode(children[i]);
if (node.hasValidChildren(filter)) {
add(node);
}
} else {
if (filter.accept(children[i])) {
add(new ViewFileTreeNode(children[i]));
}
}
}
}
}
explored = true;
}
}
/**
* Accessor to whether or not the FileNode is to only explore Directories.
*
* @return <code>true</code> if FileNode only explores directories.
*/
public boolean exploreDirectoriesOnly() {
return directoriesOnly;
}
/**
* Sets the FileNode to view only directories when it goes exploring.
*
* @param directoryChildren The permission to view only directories.
*/
public void exploreDirectoriesOnly(boolean directoryChildren) {
directoriesOnly = directoryChildren;
}
/**
* The absolute path of the FileNode, as taken from its File.
*
* @return The File's name.
*/
public String getAbsolutePath() {
return getFile().getAbsolutePath();
}
/**
* Only directoies can allow children.
*
* @return <code>true</code> if this is a directory.
*/
public boolean getAllowsChildren() {
return isDirectory();
}
/**
* The directory of the FileNode, as taken from its File.
*
* @return The directory's name.
*/
public String getDirectory() {
return getFile().getParent();
}
/**
* Returns the File that is this node on the tree.
*
* @return the File that is this node on the tree.
*/
public File getFile() {
return (File) getUserObject();
}
/**
* The name of the FileNode, as taken from its File.
*
* @return The File's name.
*/
public String getName() {
return getFile().getName();
}
/**
* Returns <code>true</code> if this fileNode is a directory and not a normal file.
*
* @return <code>true</code> if this fileNode is a directory.
*/
public boolean isDirectory() {
return getFile().isDirectory();
}
/**
* Whether or not this node has been 'explored', and its subdirectories and file-children have been found.
*
* @return whether or not this FileNode knows that is known.
*/
public boolean isExplored() {
return explored;
}
/**
* Leaves are not directories. Directories can extend.
*
* @return <code>true</code> if not directory.
*/
public boolean isLeaf() {
return !isDirectory();
}
/**
* Gets the name of the File. When this FileNode is a FileNode for a root of the filesystem, the String returned is
* the absolute path (that is so on Windows systems,the user sees "C:\"); otherwise, the string returned is the
* filename.
*
* @return Name of the file.
*/
public String toString() {
return (rootfile) ? getAbsolutePath() : getName();
}
/**
* Checks if this directory ought to be added to the list based on whether it has any children that satisfy the
* filter.
*
* @param filter Filter to check files against; if null returns true.
*
* @return Flag indicating if this directory has valid children.
*/
private boolean hasValidChildren(ViewImageFileFilter filter) {
if (filter == null) {
return true;
}
if (!isDirectory()) {
if (filter.accept(getFile())) {
return true;
} else {
return false;
}
}
File file = getFile();
File[] children = file.listFiles();
if (children == null) {
return false;
}
ViewFileTreeNode node;
// else
for (int i = 0; i < children.length; i++) {
node = new ViewFileTreeNode(children[i]);
if (node.hasValidChildren(filter)) {
return true;
}
}
return false;
}
}
|
package scc.storage.Exceptions;
public class MasterKeyNotFound extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public MasterKeyNotFound(){
super("You need to provide your CosmosDb Master Key");
}
public MasterKeyNotFound(String message){
super(message);
}
}
|
package models;
import io.ebean.annotation.NotNull;
import javax.persistence.Entity;
/**
* Created by lamdevops on 7/15/17.
*/
@Entity
public class RoleType extends BaseModel{
@NotNull
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "RoleType{" +
"name='" + name + '\'' +
'}';
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
import schema.BitnamiEdx;
import schema.Keys;
import schema.tables.records.ContentstorePushnotificationconfigRecord;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class ContentstorePushnotificationconfig extends TableImpl<ContentstorePushnotificationconfigRecord> {
private static final long serialVersionUID = -1311561125;
/**
* The reference instance of <code>bitnami_edx.contentstore_pushnotificationconfig</code>
*/
public static final ContentstorePushnotificationconfig CONTENTSTORE_PUSHNOTIFICATIONCONFIG = new ContentstorePushnotificationconfig();
/**
* The class holding records for this type
*/
@Override
public Class<ContentstorePushnotificationconfigRecord> getRecordType() {
return ContentstorePushnotificationconfigRecord.class;
}
/**
* The column <code>bitnami_edx.contentstore_pushnotificationconfig.id</code>.
*/
public final TableField<ContentstorePushnotificationconfigRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.contentstore_pushnotificationconfig.change_date</code>.
*/
public final TableField<ContentstorePushnotificationconfigRecord, Timestamp> CHANGE_DATE = createField("change_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>bitnami_edx.contentstore_pushnotificationconfig.enabled</code>.
*/
public final TableField<ContentstorePushnotificationconfigRecord, Byte> ENABLED = createField("enabled", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, "");
/**
* The column <code>bitnami_edx.contentstore_pushnotificationconfig.changed_by_id</code>.
*/
public final TableField<ContentstorePushnotificationconfigRecord, Integer> CHANGED_BY_ID = createField("changed_by_id", org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* Create a <code>bitnami_edx.contentstore_pushnotificationconfig</code> table reference
*/
public ContentstorePushnotificationconfig() {
this("contentstore_pushnotificationconfig", null);
}
/**
* Create an aliased <code>bitnami_edx.contentstore_pushnotificationconfig</code> table reference
*/
public ContentstorePushnotificationconfig(String alias) {
this(alias, CONTENTSTORE_PUSHNOTIFICATIONCONFIG);
}
private ContentstorePushnotificationconfig(String alias, Table<ContentstorePushnotificationconfigRecord> aliased) {
this(alias, aliased, null);
}
private ContentstorePushnotificationconfig(String alias, Table<ContentstorePushnotificationconfigRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return BitnamiEdx.BITNAMI_EDX;
}
/**
* {@inheritDoc}
*/
@Override
public Identity<ContentstorePushnotificationconfigRecord, Integer> getIdentity() {
return Keys.IDENTITY_CONTENTSTORE_PUSHNOTIFICATIONCONFIG;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<ContentstorePushnotificationconfigRecord> getPrimaryKey() {
return Keys.KEY_CONTENTSTORE_PUSHNOTIFICATIONCONFIG_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<ContentstorePushnotificationconfigRecord>> getKeys() {
return Arrays.<UniqueKey<ContentstorePushnotificationconfigRecord>>asList(Keys.KEY_CONTENTSTORE_PUSHNOTIFICATIONCONFIG_PRIMARY);
}
/**
* {@inheritDoc}
*/
@Override
public List<ForeignKey<ContentstorePushnotificationconfigRecord, ?>> getReferences() {
return Arrays.<ForeignKey<ContentstorePushnotificationconfigRecord, ?>>asList(Keys.CONTENTSTORE_PUSH_CHANGED_BY_ID_72C47AF098F7F8B1_FK_AUTH_USER_ID);
}
/**
* {@inheritDoc}
*/
@Override
public ContentstorePushnotificationconfig as(String alias) {
return new ContentstorePushnotificationconfig(alias, this);
}
/**
* Rename this table
*/
public ContentstorePushnotificationconfig rename(String name) {
return new ContentstorePushnotificationconfig(name, null);
}
}
|
package com.class3601.social.persistence;
import java.util.List;
//import org.apache.struts.action.ActionError;
//import org.apache.struts.action.ActionErrors;
//import org.apache.struts.action.ActionMessage;
//import org.apache.struts.action.ActionMessages;
import org.hibernate.HibernateException;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.JDBCConnectionException;
import com.class3601.social.persistence.HibernateUtil;
import com.class3601.social.common.BookingLogger;
import com.class3601.social.common.Messages;
import com.class3601.social.models.Friend;
public class HibernateFriendManager extends AbstractHibernateDatabaseManager {
private static String FRIEND_TABLE_NAME = "FRIEND";
private static String FRIEND_CLASS_NAME = "Friend";
private static String SELECT_ALL_FRIENDS = "from " + FRIEND_CLASS_NAME + " as friend";
private static String SELECT_FRIEND_WITH_ID = "from " + FRIEND_CLASS_NAME + " as friend where friend.id = ?";
private static String SELECT_FRIEND_WITH_TOKEN = "from " + FRIEND_CLASS_NAME + " as friend where friend.token = ?";
private static final String DROP_TABLE_SQL = "drop table if exists " + FRIEND_TABLE_NAME + ";";
private static String SELECT_NUMBER_FRIENDS = "select count (*) from " + FRIEND_CLASS_NAME;
private static String METHOD_INCREMENT_FRIEND_BY_ID_BY = "incrementFriendByIdBy";
private static final String CREATE_TABLE_SQL = "create table " + FRIEND_TABLE_NAME +
"(FRIEND_ID_PRIMARY_KEY char(36) primary key, " +
"ID tinytext, " +
"FRIENDID tinytext," +
"STATUS tinytext);";
private static final String METHOD_GET_N_FRIENDS = "getNFriendsStartingAtIndex";
private static String METHOD_GET_OBJECT_WITH_NAME = "getObjectWithName";
private static HibernateFriendManager manager;
public HibernateFriendManager() {
super();
}
/**
* Returns default instance.
*
* @return
*/
public static HibernateFriendManager getDefault() {
if (manager == null) {
manager = new HibernateFriendManager();
}
return manager;
}
public String getClassName() {
return FRIEND_CLASS_NAME;
}
@Override
public boolean setupTable() {
HibernateUtil.executeSQLQuery(DROP_TABLE_SQL);
return HibernateUtil.executeSQLQuery(CREATE_TABLE_SQL);
}
/**
* Adds given object (friend) to the database
*/
public synchronized boolean add(Object object) {
return super.add(object);
}
/**
* Updates given object (friend).
*
* @param object
* @return
*/
public synchronized boolean update(Friend friend) {
boolean result = super.update(friend);
return result;
}
/**
* Deletes given friend from the database.
* Returns true if successful, otherwise returns false.
*
* @param object
* @return
*/
public synchronized boolean delete(Friend friend){
Session session = null;
Transaction transaction = null;
boolean errorResult = false;
try {
session = HibernateUtil.getCurrentSession();
transaction = session.beginTransaction();
session.delete(friend);
transaction.commit();
return true;
}
catch (HibernateException exception) {
rollback(transaction);
BookingLogger.getDefault().severe(this, Messages.METHOD_DELETE_FRIEND, Messages.HIBERNATE_FAILED, exception);
return errorResult;
}
catch (RuntimeException exception) {
rollback(transaction);
BookingLogger.getDefault().severe(this, Messages.METHOD_DELETE_FRIEND, Messages.GENERIC_FAILED, exception);
return errorResult;
}
finally {
closeSession();
}
}
/**
* Increments counter found for given name by 1.
*
* @param name
*/
public synchronized void incrementFriendById(String id) {
incrementFriendByIdBy(id, 1);
}
/**
* Increments counter found for given name by given count.
*
* @param name
* @param count
*/
public synchronized void incrementFriendByIdBy(String id, int count) {
Session session = null;
Transaction transaction = null;
try {
session = HibernateUtil.getCurrentSession();
transaction = session.beginTransaction();
Query query = session.createQuery(SELECT_FRIEND_WITH_ID);
query.setParameter(0, id);
Friend friend = (Friend) query.uniqueResult();
if (friend != null) {
//friend.setCounter(friend.getCounter() + count);
session.update(friend);
transaction.commit();
} else {
BookingLogger.getDefault().severe(this,
METHOD_INCREMENT_FRIEND_BY_ID_BY,
Messages.OBJECT_NOT_FOUND_FAILED + ":" + id, null);
}
} catch (ObjectNotFoundException exception) {
BookingLogger.getDefault().severe(this,
METHOD_INCREMENT_FRIEND_BY_ID_BY,
Messages.OBJECT_NOT_FOUND_FAILED, exception);
} catch (HibernateException exception) {
BookingLogger.getDefault().severe(this,
METHOD_INCREMENT_FRIEND_BY_ID_BY,
Messages.HIBERNATE_FAILED, exception);
} catch (RuntimeException exception) {
BookingLogger.getDefault().severe(this,
METHOD_INCREMENT_FRIEND_BY_ID_BY,
Messages.GENERIC_FAILED, exception);
} finally {
closeSession();
}
}
/**
* Returns friend from the database with given id.
* Upon exception returns null.
*
* @param id
* @return
*/
public synchronized Friend getFriendById(String id) {
Session session = null;
Friend errorResult = null;
try {
session = HibernateUtil.getCurrentSession();
Query query = session.createQuery(SELECT_FRIEND_WITH_ID);
query.setParameter(0, id);
Friend aFriend = (Friend) query.uniqueResult();
return aFriend;
} catch (ObjectNotFoundException exception) {
BookingLogger.getDefault().severe(this,
METHOD_GET_OBJECT_WITH_NAME,
Messages.OBJECT_NOT_FOUND_FAILED, exception);
return errorResult;
} catch (HibernateException exception) {
BookingLogger.getDefault().severe(this,
METHOD_GET_OBJECT_WITH_NAME, Messages.HIBERNATE_FAILED,
exception);
return errorResult;
} catch (RuntimeException exception) {
BookingLogger.getDefault().severe(this,
METHOD_GET_OBJECT_WITH_NAME, Messages.GENERIC_FAILED,
exception);
return errorResult;
} finally {
closeSession();
}
}
@SuppressWarnings("unchecked")
public synchronized List<Friend> getFriendsByID(String id) {
List<Friend> errorResult = null;
Session session = null;
try {
session = HibernateUtil.getCurrentSession();
Query query = session.createQuery(SELECT_FRIEND_WITH_ID);
query.setParameter(0, id);
List<Friend> friends = query.list();
return friends;
} catch (ObjectNotFoundException exception) {
BookingLogger.getDefault().severe(this, METHOD_GET_N_FRIENDS,
Messages.OBJECT_NOT_FOUND_FAILED, exception);
return errorResult;
} catch (JDBCConnectionException exception) {
HibernateUtil.clearSessionFactory();
BookingLogger.getDefault().severe(this, METHOD_GET_N_FRIENDS,
Messages.HIBERNATE_CONNECTION_FAILED, exception);
return errorResult;
} catch (HibernateException exception) {
BookingLogger.getDefault().severe(this, METHOD_GET_N_FRIENDS,
Messages.HIBERNATE_FAILED, exception);
return errorResult;
} catch (RuntimeException exception) {
BookingLogger.getDefault().severe(this, METHOD_GET_N_FRIENDS,
Messages.GENERIC_FAILED, exception);
return errorResult;
} finally {
closeSession();
}
}
public synchronized Friend getFriendByToken(String token) {
Session session = null;
Friend errorResult = null;
try {
session = HibernateUtil.getCurrentSession();
Query query = session.createQuery(SELECT_FRIEND_WITH_TOKEN);
query.setParameter(0, token);
Friend aFriend = (Friend) query.uniqueResult();
return aFriend;
} catch (ObjectNotFoundException exception) {
BookingLogger.getDefault().severe(this,
METHOD_GET_OBJECT_WITH_NAME,
Messages.OBJECT_NOT_FOUND_FAILED, exception);
return errorResult;
} catch (HibernateException exception) {
BookingLogger.getDefault().severe(this,
METHOD_GET_OBJECT_WITH_NAME, Messages.HIBERNATE_FAILED,
exception);
return errorResult;
} catch (RuntimeException exception) {
BookingLogger.getDefault().severe(this,
METHOD_GET_OBJECT_WITH_NAME, Messages.GENERIC_FAILED,
exception);
return errorResult;
} finally {
closeSession();
}
}
/**
* Returns friend with given emailAddress and password from the database.
* If not found returns null.
*
* @param emailAddress
* @param password
* @return
*/
public Friend getFriend(String id, String friendid) {
Friend friend = getFriendById(id);
if ((friend != null) && (friend.getId().equals(id)) && (friend.getFriendid().equals(friendid))) {
return friend;
} else {
return null;
}
}
/**
* Returns friends,
* from database.
* If not found returns null.
* Upon error returns null.
*
* @param phonenumber
* @return
*/
@SuppressWarnings("unchecked")
public synchronized List<Friend> getNFriendsStartingAtIndex(int index, int n) {
List<Friend> errorResult = null;
Session session = null;
try {
session = HibernateUtil.getCurrentSession();
Query query = session.createQuery(SELECT_ALL_FRIENDS);
query.setFirstResult(index);
query.setMaxResults(n);
List<Friend> friends = query.list();
return friends;
} catch (ObjectNotFoundException exception) {
BookingLogger.getDefault().severe(this, METHOD_GET_N_FRIENDS,
Messages.OBJECT_NOT_FOUND_FAILED, exception);
return errorResult;
} catch (JDBCConnectionException exception) {
HibernateUtil.clearSessionFactory();
BookingLogger.getDefault().severe(this, METHOD_GET_N_FRIENDS,
Messages.HIBERNATE_CONNECTION_FAILED, exception);
return errorResult;
} catch (HibernateException exception) {
BookingLogger.getDefault().severe(this, METHOD_GET_N_FRIENDS,
Messages.HIBERNATE_FAILED, exception);
return errorResult;
} catch (RuntimeException exception) {
BookingLogger.getDefault().severe(this, METHOD_GET_N_FRIENDS,
Messages.GENERIC_FAILED, exception);
return errorResult;
} finally {
closeSession();
}
}
public String getTableName() {
return FRIEND_TABLE_NAME;
}
/**
* Returns number of friends.
*
* Upon error returns empty list.
*
* @param a charge status
* @return
*/
public synchronized int getNumberOfFriends() {
Session session = null;
Long aLong;
try {
session = HibernateUtil.getCurrentSession();
Query query = session
.createQuery(SELECT_NUMBER_FRIENDS);
aLong = (Long) query.uniqueResult();
return aLong.intValue();
} catch (ObjectNotFoundException exception) {
BookingLogger.getDefault().severe(this,
Messages.METHOD_GET_NUMBER_OF_FRIENDS,
Messages.OBJECT_NOT_FOUND_FAILED, exception);
return 0;
} catch (HibernateException exception) {
BookingLogger.getDefault().severe(this,
Messages.METHOD_GET_NUMBER_OF_FRIENDS,
Messages.HIBERNATE_FAILED, exception);
return 0;
} catch (RuntimeException exception) {
BookingLogger.getDefault().severe(this,
Messages.METHOD_GET_NUMBER_OF_FRIENDS,
Messages.GENERIC_FAILED, exception);
return 0;
} finally {
closeSession();
}
}
} |
package org.nathan.lib.widget;
import org.nathan.lib.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* 长方形图片框,可设置宽高比
* 在布局XML文件中要添加xmlns:rectImage="http://schemas.android.com/apk/res/org.nathan.lib"
* @author Nathan
*/
public class RectImageView extends ImageView {
/**
* 宽/高比例
*/
public float ratio =1;
public RectImageView(Context context) {
super(context);
}
public RectImageView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.RectImageView);
ratio = a.getFloat(R.styleable.RectImageView_ratio, 1f);
a.recycle();
}
public RectImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.RectImageView);
ratio = a.getFloat(R.styleable.RectImageView_ratio, 1f);
a.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), (int)(getMeasuredWidth()* ratio)); //Snap to width
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import javax.lang.model.element.Modifier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.framework.autoproxy.AutoProxyUtils;
import org.springframework.aot.generate.GeneratedMethod;
import org.springframework.aot.generate.GenerationContext;
import org.springframework.aot.hint.ExecutableMode;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.ResourceHints;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.TypeReference;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor;
import org.springframework.beans.factory.aot.BeanFactoryInitializationCode;
import org.springframework.beans.factory.aot.BeanRegistrationAotContribution;
import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor;
import org.springframework.beans.factory.aot.BeanRegistrationCode;
import org.springframework.beans.factory.aot.BeanRegistrationCodeFragments;
import org.springframework.beans.factory.aot.BeanRegistrationCodeFragmentsDecorator;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.config.SingletonBeanRegistry;
import org.springframework.beans.factory.parsing.FailFastProblemReporter;
import org.springframework.beans.factory.parsing.PassThroughSourceExtractor;
import org.springframework.beans.factory.parsing.ProblemReporter;
import org.springframework.beans.factory.parsing.SourceExtractor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationStartupAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ConfigurationClassEnhancer.EnhancedConfiguration;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PropertySourceDescriptor;
import org.springframework.core.io.support.PropertySourceProcessor;
import org.springframework.core.metrics.ApplicationStartup;
import org.springframework.core.metrics.StartupStep;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.MethodMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.javapoet.CodeBlock;
import org.springframework.javapoet.CodeBlock.Builder;
import org.springframework.javapoet.MethodSpec;
import org.springframework.javapoet.ParameterizedTypeName;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
/**
* {@link BeanFactoryPostProcessor} used for bootstrapping processing of
* {@link Configuration @Configuration} classes.
*
* <p>Registered by default when using {@code <context:annotation-config/>} or
* {@code <context:component-scan/>}. Otherwise, may be declared manually as
* with any other {@link BeanFactoryPostProcessor}.
*
* <p>This post processor is priority-ordered as it is important that any
* {@link Bean @Bean} methods declared in {@code @Configuration} classes have
* their corresponding bean definitions registered before any other
* {@code BeanFactoryPostProcessor} executes.
*
* @author Chris Beams
* @author Juergen Hoeller
* @author Phillip Webb
* @author Sam Brannen
* @since 3.0
*/
public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
BeanRegistrationAotProcessor, BeanFactoryInitializationAotProcessor, PriorityOrdered,
ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware {
/**
* A {@code BeanNameGenerator} using fully qualified class names as default bean names.
* <p>This default for configuration-level import purposes may be overridden through
* {@link #setBeanNameGenerator}. Note that the default for component scanning purposes
* is a plain {@link AnnotationBeanNameGenerator#INSTANCE}, unless overridden through
* {@link #setBeanNameGenerator} with a unified user-level bean name generator.
* @since 5.2
* @see #setBeanNameGenerator
*/
public static final AnnotationBeanNameGenerator IMPORT_BEAN_NAME_GENERATOR =
FullyQualifiedAnnotationBeanNameGenerator.INSTANCE;
private static final String IMPORT_REGISTRY_BEAN_NAME =
ConfigurationClassPostProcessor.class.getName() + ".importRegistry";
private final Log logger = LogFactory.getLog(getClass());
private SourceExtractor sourceExtractor = new PassThroughSourceExtractor();
private ProblemReporter problemReporter = new FailFastProblemReporter();
@Nullable
private Environment environment;
private ResourceLoader resourceLoader = new DefaultResourceLoader();
@Nullable
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();
private boolean setMetadataReaderFactoryCalled = false;
private final Set<Integer> registriesPostProcessed = new HashSet<>();
private final Set<Integer> factoriesPostProcessed = new HashSet<>();
@Nullable
private ConfigurationClassBeanDefinitionReader reader;
private boolean localBeanNameGeneratorSet = false;
/* Using short class names as default bean names by default. */
private BeanNameGenerator componentScanBeanNameGenerator = AnnotationBeanNameGenerator.INSTANCE;
/* Using fully qualified class names as default bean names by default. */
private BeanNameGenerator importBeanNameGenerator = IMPORT_BEAN_NAME_GENERATOR;
private ApplicationStartup applicationStartup = ApplicationStartup.DEFAULT;
@Nullable
private List<PropertySourceDescriptor> propertySourceDescriptors;
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE; // within PriorityOrdered
}
/**
* Set the {@link SourceExtractor} to use for generated bean definitions
* that correspond to {@link Bean} factory methods.
*/
public void setSourceExtractor(@Nullable SourceExtractor sourceExtractor) {
this.sourceExtractor = (sourceExtractor != null ? sourceExtractor : new PassThroughSourceExtractor());
}
/**
* Set the {@link ProblemReporter} to use.
* <p>Used to register any problems detected with {@link Configuration} or {@link Bean}
* declarations. For instance, an @Bean method marked as {@code final} is illegal
* and would be reported as a problem. Defaults to {@link FailFastProblemReporter}.
*/
public void setProblemReporter(@Nullable ProblemReporter problemReporter) {
this.problemReporter = (problemReporter != null ? problemReporter : new FailFastProblemReporter());
}
/**
* Set the {@link MetadataReaderFactory} to use.
* <p>Default is a {@link CachingMetadataReaderFactory} for the specified
* {@linkplain #setBeanClassLoader bean class loader}.
*/
public void setMetadataReaderFactory(MetadataReaderFactory metadataReaderFactory) {
Assert.notNull(metadataReaderFactory, "MetadataReaderFactory must not be null");
this.metadataReaderFactory = metadataReaderFactory;
this.setMetadataReaderFactoryCalled = true;
}
/**
* Set the {@link BeanNameGenerator} to be used when triggering component scanning
* from {@link Configuration} classes and when registering {@link Import}'ed
* configuration classes. The default is a standard {@link AnnotationBeanNameGenerator}
* for scanned components (compatible with the default in {@link ClassPathBeanDefinitionScanner})
* and a variant thereof for imported configuration classes (using unique fully-qualified
* class names instead of standard component overriding).
* <p>Note that this strategy does <em>not</em> apply to {@link Bean} methods.
* <p>This setter is typically only appropriate when configuring the post-processor as a
* standalone bean definition in XML, e.g. not using the dedicated {@code AnnotationConfig*}
* application contexts or the {@code <context:annotation-config>} element. Any bean name
* generator specified against the application context will take precedence over any set here.
* @since 3.1.1
* @see AnnotationConfigApplicationContext#setBeanNameGenerator(BeanNameGenerator)
* @see AnnotationConfigUtils#CONFIGURATION_BEAN_NAME_GENERATOR
*/
public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) {
Assert.notNull(beanNameGenerator, "BeanNameGenerator must not be null");
this.localBeanNameGeneratorSet = true;
this.componentScanBeanNameGenerator = beanNameGenerator;
this.importBeanNameGenerator = beanNameGenerator;
}
@Override
public void setEnvironment(Environment environment) {
Assert.notNull(environment, "Environment must not be null");
this.environment = environment;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
Assert.notNull(resourceLoader, "ResourceLoader must not be null");
this.resourceLoader = resourceLoader;
if (!this.setMetadataReaderFactoryCalled) {
this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
}
}
@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = beanClassLoader;
if (!this.setMetadataReaderFactoryCalled) {
this.metadataReaderFactory = new CachingMetadataReaderFactory(beanClassLoader);
}
}
@Override
public void setApplicationStartup(ApplicationStartup applicationStartup) {
this.applicationStartup = applicationStartup;
}
/**
* Derive further bean definitions from the configuration classes in the registry.
*/
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
}
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + registry);
}
this.registriesPostProcessed.add(registryId);
processConfigBeanDefinitions(registry);
}
/**
* Prepare the Configuration classes for servicing bean requests at runtime
* by replacing them with CGLIB-enhanced subclasses.
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
int factoryId = System.identityHashCode(beanFactory);
if (this.factoriesPostProcessed.contains(factoryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + beanFactory);
}
this.factoriesPostProcessed.add(factoryId);
if (!this.registriesPostProcessed.contains(factoryId)) {
// BeanDefinitionRegistryPostProcessor hook apparently not supported...
// Simply call processConfigurationClasses lazily at this point then.
processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
}
enhanceConfigurationClasses(beanFactory);
beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
}
@Nullable
@Override
public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) {
Object configClassAttr = registeredBean.getMergedBeanDefinition()
.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE);
if (ConfigurationClassUtils.CONFIGURATION_CLASS_FULL.equals(configClassAttr)) {
Class<?> proxyClass = registeredBean.getBeanType().toClass();
return BeanRegistrationAotContribution.withCustomCodeFragments(codeFragments ->
new ConfigurationClassProxyBeanRegistrationCodeFragments(codeFragments, proxyClass));
}
return null;
}
@Override
@Nullable
public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
boolean hasPropertySourceDescriptors = !CollectionUtils.isEmpty(this.propertySourceDescriptors);
boolean hasImportRegistry = beanFactory.containsBean(IMPORT_REGISTRY_BEAN_NAME);
if (hasPropertySourceDescriptors || hasImportRegistry) {
return (generationContext, code) -> {
if (hasPropertySourceDescriptors) {
new PropertySourcesAotContribution(this.propertySourceDescriptors, this::resolvePropertySourceLocation)
.applyTo(generationContext, code);
}
if (hasImportRegistry) {
new ImportAwareAotContribution(beanFactory).applyTo(generationContext, code);
}
};
}
return null;
}
@Nullable
private Resource resolvePropertySourceLocation(String location) {
try {
String resolvedLocation = (this.environment != null ?
this.environment.resolveRequiredPlaceholders(location) : location);
return this.resourceLoader.getResource(resolvedLocation);
}
catch (Exception ex) {
return null;
}
}
/**
* Build and validate a configuration model based on the registry of
* {@link Configuration} classes.
*/
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
String[] candidateNames = registry.getBeanDefinitionNames();
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
// Return immediately if no @Configuration classes were found
if (configCandidates.isEmpty()) {
return;
}
// Sort by previously determined @Order value, if applicable
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});
// Detect any custom bean name generation strategy supplied through the enclosing application context
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry _sbr) {
sbr = _sbr;
if (!this.localBeanNameGeneratorSet) {
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
if (generator != null) {
this.componentScanBeanNameGenerator = generator;
this.importBeanNameGenerator = generator;
}
}
}
if (this.environment == null) {
this.environment = new StandardEnvironment();
}
// Parse each @Configuration class
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
do {
StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");
parser.parse(candidates);
parser.validate();
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
// Read the model and create bean definitions based on its content
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);
processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();
candidates.clear();
if (registry.getBeanDefinitionCount() > candidateNames.length) {
String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = Set.of(candidateNames);
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}
// Store the PropertySourceDescriptors to contribute them Ahead-of-time if necessary
this.propertySourceDescriptors = parser.getPropertySourceDescriptors();
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory cachingMetadataReaderFactory) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
cachingMetadataReaderFactory.clearCache();
}
}
/**
* Post-processes a BeanFactory in search of Configuration class BeanDefinitions;
* any candidates are then enhanced by a {@link ConfigurationClassEnhancer}.
* Candidate status is determined by BeanDefinition attribute metadata.
* @see ConfigurationClassEnhancer
*/
public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
StartupStep enhanceConfigClasses = this.applicationStartup.start("spring.context.config-classes.enhance");
Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<>();
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
Object configClassAttr = beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE);
AnnotationMetadata annotationMetadata = null;
MethodMetadata methodMetadata = null;
if (beanDef instanceof AnnotatedBeanDefinition annotatedBeanDefinition) {
annotationMetadata = annotatedBeanDefinition.getMetadata();
methodMetadata = annotatedBeanDefinition.getFactoryMethodMetadata();
}
if ((configClassAttr != null || methodMetadata != null) &&
(beanDef instanceof AbstractBeanDefinition abd) && !abd.hasBeanClass()) {
// Configuration class (full or lite) or a configuration-derived @Bean method
// -> eagerly resolve bean class at this point, unless it's a 'lite' configuration
// or component class without @Bean methods.
boolean liteConfigurationCandidateWithoutBeanMethods =
(ConfigurationClassUtils.CONFIGURATION_CLASS_LITE.equals(configClassAttr) &&
annotationMetadata != null && !ConfigurationClassUtils.hasBeanMethods(annotationMetadata));
if (!liteConfigurationCandidateWithoutBeanMethods) {
try {
abd.resolveBeanClass(this.beanClassLoader);
}
catch (Throwable ex) {
throw new IllegalStateException(
"Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
}
}
}
if (ConfigurationClassUtils.CONFIGURATION_CLASS_FULL.equals(configClassAttr)) {
if (!(beanDef instanceof AbstractBeanDefinition abd)) {
throw new BeanDefinitionStoreException("Cannot enhance @Configuration bean definition '" +
beanName + "' since it is not stored in an AbstractBeanDefinition subclass");
}
else if (logger.isWarnEnabled() && beanFactory.containsSingleton(beanName)) {
logger.warn("Cannot enhance @Configuration bean definition '" + beanName +
"' since its singleton instance has been created too early. The typical cause " +
"is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor " +
"return type: Consider declaring such methods as 'static' and/or mark the " +
"containing configuration class as 'proxyBeanMethods=false'.");
}
configBeanDefs.put(beanName, abd);
}
}
if (configBeanDefs.isEmpty()) {
// nothing to enhance -> return immediately
enhanceConfigClasses.end();
return;
}
ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) {
AbstractBeanDefinition beanDef = entry.getValue();
// If a @Configuration class gets proxied, always proxy the target class
beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
// Set enhanced subclass of the user-specified bean class
Class<?> configClass = beanDef.getBeanClass();
Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
if (configClass != enhancedClass) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("Replacing bean definition '%s' existing class '%s' with " +
"enhanced class '%s'", entry.getKey(), configClass.getName(), enhancedClass.getName()));
}
beanDef.setBeanClass(enhancedClass);
}
}
enhanceConfigClasses.tag("classCount", () -> String.valueOf(configBeanDefs.keySet().size())).end();
}
private static class ImportAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
private final BeanFactory beanFactory;
public ImportAwareBeanPostProcessor(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public PropertyValues postProcessProperties(@Nullable PropertyValues pvs, Object bean, String beanName) {
// Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's
// postProcessProperties method attempts to autowire other configuration beans.
if (bean instanceof EnhancedConfiguration enhancedConfiguration) {
enhancedConfiguration.setBeanFactory(this.beanFactory);
}
return pvs;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if (bean instanceof ImportAware importAware) {
ImportRegistry ir = this.beanFactory.getBean(IMPORT_REGISTRY_BEAN_NAME, ImportRegistry.class);
AnnotationMetadata importingClass = ir.getImportingClassFor(ClassUtils.getUserClass(bean).getName());
if (importingClass != null) {
importAware.setImportMetadata(importingClass);
}
}
return bean;
}
}
private static class ImportAwareAotContribution implements BeanFactoryInitializationAotContribution {
private static final String BEAN_FACTORY_VARIABLE = BeanFactoryInitializationCode.BEAN_FACTORY_VARIABLE;
private static final ParameterizedTypeName STRING_STRING_MAP =
ParameterizedTypeName.get(Map.class, String.class, String.class);
private static final String MAPPINGS_VARIABLE = "mappings";
private static final String BEAN_DEFINITION_VARIABLE = "beanDefinition";
private static final String BEAN_NAME = "org.springframework.context.annotation.internalImportAwareAotProcessor";
private final ConfigurableListableBeanFactory beanFactory;
public ImportAwareAotContribution(ConfigurableListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public void applyTo(GenerationContext generationContext,
BeanFactoryInitializationCode beanFactoryInitializationCode) {
Map<String, String> mappings = buildImportAwareMappings();
if (!mappings.isEmpty()) {
GeneratedMethod generatedMethod = beanFactoryInitializationCode.getMethods().add(
"addImportAwareBeanPostProcessors", method -> generateAddPostProcessorMethod(method, mappings));
beanFactoryInitializationCode.addInitializer(generatedMethod.toMethodReference());
ResourceHints hints = generationContext.getRuntimeHints().resources();
mappings.forEach((target, from) -> hints.registerType(TypeReference.of(from)));
}
}
private void generateAddPostProcessorMethod(MethodSpec.Builder method, Map<String, String> mappings) {
method.addJavadoc("Add ImportAwareBeanPostProcessor to support ImportAware beans.");
method.addModifiers(Modifier.PRIVATE);
method.addParameter(DefaultListableBeanFactory.class, BEAN_FACTORY_VARIABLE);
method.addCode(generateAddPostProcessorCode(mappings));
}
private CodeBlock generateAddPostProcessorCode(Map<String, String> mappings) {
CodeBlock.Builder code = CodeBlock.builder();
code.addStatement("$T $L = new $T<>()", STRING_STRING_MAP,
MAPPINGS_VARIABLE, HashMap.class);
mappings.forEach((type, from) -> code.addStatement("$L.put($S, $S)",
MAPPINGS_VARIABLE, type, from));
code.addStatement("$T $L = new $T($T.class)", RootBeanDefinition.class,
BEAN_DEFINITION_VARIABLE, RootBeanDefinition.class, ImportAwareAotBeanPostProcessor.class);
code.addStatement("$L.setRole($T.ROLE_INFRASTRUCTURE)",
BEAN_DEFINITION_VARIABLE, BeanDefinition.class);
code.addStatement("$L.setInstanceSupplier(() -> new $T($L))",
BEAN_DEFINITION_VARIABLE, ImportAwareAotBeanPostProcessor.class, MAPPINGS_VARIABLE);
code.addStatement("$L.registerBeanDefinition($S, $L)",
BEAN_FACTORY_VARIABLE, BEAN_NAME, BEAN_DEFINITION_VARIABLE);
return code.build();
}
private Map<String, String> buildImportAwareMappings() {
ImportRegistry importRegistry = this.beanFactory.getBean(IMPORT_REGISTRY_BEAN_NAME, ImportRegistry.class);
Map<String, String> mappings = new LinkedHashMap<>();
for (String name : this.beanFactory.getBeanDefinitionNames()) {
Class<?> beanType = this.beanFactory.getType(name);
if (beanType != null && ImportAware.class.isAssignableFrom(beanType)) {
String target = ClassUtils.getUserClass(beanType).getName();
AnnotationMetadata from = importRegistry.getImportingClassFor(target);
if (from != null) {
mappings.put(target, from.getClassName());
}
}
}
return mappings;
}
}
private static class PropertySourcesAotContribution implements BeanFactoryInitializationAotContribution {
private static final String ENVIRONMENT_VARIABLE = "environment";
private static final String RESOURCE_LOADER_VARIABLE = "resourceLoader";
private final List<PropertySourceDescriptor> descriptors;
private final Function<String, Resource> resourceResolver;
PropertySourcesAotContribution(List<PropertySourceDescriptor> descriptors, Function<String, Resource> resourceResolver) {
this.descriptors = descriptors;
this.resourceResolver = resourceResolver;
}
@Override
public void applyTo(GenerationContext generationContext, BeanFactoryInitializationCode beanFactoryInitializationCode) {
registerRuntimeHints(generationContext.getRuntimeHints());
GeneratedMethod generatedMethod = beanFactoryInitializationCode.getMethods()
.add("processPropertySources", this::generateAddPropertySourceProcessorMethod);
beanFactoryInitializationCode.addInitializer(generatedMethod.toMethodReference());
}
private void registerRuntimeHints(RuntimeHints hints) {
for (PropertySourceDescriptor descriptor : this.descriptors) {
Class<?> factory = descriptor.propertySourceFactory();
if (factory != null) {
hints.reflection().registerType(factory, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
for (String location : descriptor.locations()) {
Resource resource = this.resourceResolver.apply(location);
if (resource instanceof ClassPathResource classPathResource && classPathResource.exists()) {
hints.resources().registerPattern(classPathResource.getPath());
}
}
}
}
private void generateAddPropertySourceProcessorMethod(MethodSpec.Builder method) {
method.addJavadoc("Apply known @PropertySources to the environment.");
method.addModifiers(Modifier.PRIVATE);
method.addParameter(ConfigurableEnvironment.class, ENVIRONMENT_VARIABLE);
method.addParameter(ResourceLoader.class, RESOURCE_LOADER_VARIABLE);
method.addCode(generateAddPropertySourceProcessorCode());
}
private CodeBlock generateAddPropertySourceProcessorCode() {
Builder code = CodeBlock.builder();
String processorVariable = "processor";
code.addStatement("$T $L = new $T($L, $L)", PropertySourceProcessor.class,
processorVariable, PropertySourceProcessor.class, ENVIRONMENT_VARIABLE,
RESOURCE_LOADER_VARIABLE);
code.beginControlFlow("try");
for (PropertySourceDescriptor descriptor : this.descriptors) {
code.addStatement("$L.processPropertySource($L)", processorVariable,
generatePropertySourceDescriptorCode(descriptor));
}
code.nextControlFlow("catch ($T ex)", IOException.class);
code.addStatement("throw new $T(ex)", UncheckedIOException.class);
code.endControlFlow();
return code.build();
}
private CodeBlock generatePropertySourceDescriptorCode(PropertySourceDescriptor descriptor) {
CodeBlock.Builder code = CodeBlock.builder();
code.add("new $T(", PropertySourceDescriptor.class);
CodeBlock values = descriptor.locations().stream()
.map(value -> CodeBlock.of("$S", value)).collect(CodeBlock.joining(", "));
if (descriptor.name() == null && descriptor.propertySourceFactory() == null &&
descriptor.encoding() == null && !descriptor.ignoreResourceNotFound()) {
code.add("$L)", values);
}
else {
List<CodeBlock> arguments = new ArrayList<>();
arguments.add(CodeBlock.of("$T.of($L)", List.class, values));
arguments.add(CodeBlock.of("$L", descriptor.ignoreResourceNotFound()));
arguments.add(handleNull(descriptor.name(), () -> CodeBlock.of("$S", descriptor.name())));
arguments.add(handleNull(descriptor.propertySourceFactory(),
() -> CodeBlock.of("$T.class", descriptor.propertySourceFactory())));
arguments.add(handleNull(descriptor.encoding(),
() -> CodeBlock.of("$S", descriptor.encoding())));
code.add(CodeBlock.join(arguments, ", "));
code.add(")");
}
return code.build();
}
private CodeBlock handleNull(@Nullable Object value, Supplier<CodeBlock> nonNull) {
if (value == null) {
return CodeBlock.of("null");
}
else {
return nonNull.get();
}
}
}
private static class ConfigurationClassProxyBeanRegistrationCodeFragments extends BeanRegistrationCodeFragmentsDecorator {
private final Class<?> proxyClass;
public ConfigurationClassProxyBeanRegistrationCodeFragments(BeanRegistrationCodeFragments codeFragments,
Class<?> proxyClass) {
super(codeFragments);
this.proxyClass = proxyClass;
}
@Override
public CodeBlock generateSetBeanDefinitionPropertiesCode(GenerationContext generationContext,
BeanRegistrationCode beanRegistrationCode, RootBeanDefinition beanDefinition, Predicate<String> attributeFilter) {
CodeBlock.Builder code = CodeBlock.builder();
code.add(super.generateSetBeanDefinitionPropertiesCode(generationContext,
beanRegistrationCode, beanDefinition, attributeFilter));
code.addStatement("$T.initializeConfigurationClass($T.class)",
ConfigurationClassUtils.class, ClassUtils.getUserClass(this.proxyClass));
return code.build();
}
@Override
public CodeBlock generateInstanceSupplierCode(GenerationContext generationContext,
BeanRegistrationCode beanRegistrationCode, Executable constructorOrFactoryMethod,
boolean allowDirectSupplierShortcut) {
Executable executableToUse = proxyExecutable(generationContext.getRuntimeHints(), constructorOrFactoryMethod);
return super.generateInstanceSupplierCode(generationContext, beanRegistrationCode,
executableToUse, allowDirectSupplierShortcut);
}
private Executable proxyExecutable(RuntimeHints runtimeHints, Executable userExecutable) {
if (userExecutable instanceof Constructor<?> userConstructor) {
try {
runtimeHints.reflection().registerConstructor(userConstructor, ExecutableMode.INTROSPECT);
return this.proxyClass.getConstructor(userExecutable.getParameterTypes());
}
catch (NoSuchMethodException ex) {
throw new IllegalStateException("No matching constructor found on proxy " + this.proxyClass, ex);
}
}
return userExecutable;
}
}
}
|
/**
* ConfirmationCodeDeserializer
*/
package com.bs.bod.converter;
import java.io.IOException;
import com.bs.bod.ConfirmationCode;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
/**
* @author dbs on Dec 26, 2015 2:19:17 PM
* @version 1.0
* @since V0.0.1
*
*/
public class ConfirmationCodeDeserializer extends JsonDeserializer<ConfirmationCode> {
@Override
public ConfirmationCode deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
try {
return ConfirmationCode.values()[jp.getValueAsInt()];
} catch (Exception e) {
}
return ConfirmationCode.never;
}
}
|
package com.tdd.gameoflife;
public class GameOfLife {
private int[][] grid;
public GameOfLife(int[][] grid) {
this.grid = grid;
}
public int[][] nextGeneration() {
for (int row = 0; row < grid.length; row++) {
for(int column = 0; column < grid[row].length; column++) {
int cellCount = calculateNeighbourCount(row, column);
int result = 0;
grid[row][column] = applySurvivalRule(row, column, cellCount, result);
}
}
return grid;
}
private int applySurvivalRule(int row, int column, int cellCount, int result) {
if(cellCount < 2) {
result = 0;
} else if((2 == cellCount || 3 == cellCount) && grid[row][column] == 1 ) {
result = 1;
} else if(cellCount > 3 && grid[row][column] == 1) {
result = 0;
} else if (cellCount == 3 && grid[row][column] == 0) {
result = 1;
}
return result;
}
protected int calculateNeighbourCount(int row, int column) {
int count = 0;
for(int currentRow = row - 1; currentRow <= row + 1; currentRow++) {
for(int currentColumn = column -1; currentColumn <= column + 1; currentColumn++) {
if(currentRow > -1 && currentRow < grid.length) {
if(currentColumn > -1 && currentColumn < grid[row].length) {
if(!(currentColumn == column && currentRow == row)) {
count += grid[currentRow][currentColumn];
}
}
}
}
}
return count;
}
}
|
package com.kingnode.gou.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.kingnode.xsimple.entity.AuditEntity;
/**
* @author segry ouyang(328361257@qq.com)
*/
@Entity @Table(name="footprint")
public class Footprint extends AuditEntity{
private long customerId;
private long productId;
private Date browsingTime;
public Footprint(long customerId,long productId,Date browsingTime){
this.customerId=customerId;
this.productId=productId;
this.browsingTime=browsingTime;
}
public long getCustomerId(){
return customerId;
}
public void setCustomerId(long customerId){
this.customerId=customerId;
}
public long getProductId(){
return productId;
}
public void setProductId(long productId){
this.productId=productId;
}
public Date getBrowsingTime(){
return browsingTime;
}
public void setBrowsingTime(Date browsingTime){
this.browsingTime=browsingTime;
}
}
|
/*
* Copyright (C) 2015 Adrien Guille <adrien.guille@univ-lyon2.fr>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package main.java.fr.ericlab.sondy.algo.eventdetection.edcow;
import java.util.LinkedList;
////////////////////////////////////////////////////////////////////////////////
// This file is part of SONDY. //
// //
// SONDY 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. //
// //
// SONDY 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 SONDY. If not, see <http://www.gnu.org/licenses/>. //
////////////////////////////////////////////////////////////////////////////////
/**
* @author yue HE, Falitokiniaina RABEARISON, Département Informatique et Statistiques, Université Lumière Lyon 2
* @author Adrien GUILLE, Laboratoire ERIC, Université Lumière Lyon 2
*/
public class EDCoWEvent implements Comparable<EDCoWEvent>{
public LinkedList<String> keywords;
public double epsylon;
public float startSlice;
public float endSlice;
public EDCoWEvent(LinkedList<String> keywords_, float startDay_, float endDay_){
keywords = keywords_;
startSlice = startDay_;
endSlice = endDay_;
}
public EDCoWEvent(){
keywords = new LinkedList<>();
}
public String getKeywordsAsString(){
String str = "";
for(String keyword : keywords){
str += keyword+" ";
}
return str;
}
public String getIntervalAsString(){
return startSlice+";"+endSlice;
}
public double[] getInterval(float intervalDuration){
double array[] = {(startSlice*intervalDuration)/24, (endSlice*intervalDuration)/24};
return array;
}
public void setEpsylon(double epsylon) {
this.epsylon = epsylon;
}
public void setStartSlice(float startDay) {
this.startSlice = startDay;
}
public void setEndSlice(float endDay) {
this.endSlice = endDay;
}
public double getEpsylon() {
return epsylon;
}
@Override
public int compareTo(EDCoWEvent event0) {
if(this.epsylon < event0.epsylon){
return -1;
}else{
if(this.epsylon > event0.epsylon){
return 1;
}else{
return 0;
}
}
}
}
|
/*
* 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 lk.vcnet.storemodule.client;
import lk.vcnet.storemodule.server.Supplier;
/**
*
* @author user
*/
public class CLt {
public static void main(String[] args)
{
try
{
Supplier sup=new Supplier();
sup.setSid("S4");
sup.setSname("Sunil");
sup.setSadr("DEWW Rd");
sup.setCity("Colombo");
sup.setTele("0412235599");
sup.registerSupplier();
//sup.updateSupplier();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
|
package com.raildeliveryservices.burnrubber.adapters;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.raildeliveryservices.burnrubber.R;
import com.raildeliveryservices.burnrubber.data.Order;
public class OrderListCursorAdapter extends SimpleCursorAdapter {
private Context _context;
private int _layout;
private LayoutInflater _layoutInflater;
private boolean _readOnly;
public OrderListCursorAdapter(Context context, int layout, boolean readOnly) {
super(context, layout, null, new String[]{Order.Columns.FILE_NO}, new int[]{R.id.fileNoText}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
_context = context;
_layout = layout;
_layoutInflater = LayoutInflater.from(context);
_readOnly = readOnly;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return _layoutInflater.inflate(_layout, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
final long orderId = cursor.getLong(cursor.getColumnIndex(Order.Columns._ID));
final int fileNo = cursor.getInt(cursor.getColumnIndex(Order.Columns.FILE_NO));
final TextView fileNoText = (TextView) view.findViewById(com.raildeliveryservices.burnrubber.R.id.fileNoText);
final TextView voyageNoText = (TextView) view.findViewById(R.id.voyageNoText);
final TextView hazmatText = (TextView) view.findViewById(R.id.hazmatText);
final TextView apptDateText = (TextView) view.findViewById(R.id.apptDateText);
final TextView apptTimeText = (TextView) view.findViewById(R.id.apptTimeText);
final TextView moveTypeText = (TextView) view.findViewById(R.id.moveTypeText);
final Button confirmButton = (Button) view.findViewById(R.id.confirmButton);
final Button rejectButton = (Button) view.findViewById(R.id.rejectButton);
final boolean confirmedFlag = cursor.getInt(cursor.getColumnIndex(Order.Columns.CONFIRMED_FLAG)) == 1 ? true : false;
final boolean hazmatFlag = cursor.getInt(cursor.getColumnIndex(Order.Columns.HAZMAT_FLAG)) == 1 ? true : false;
fileNoText.setText(String.valueOf(fileNo));
voyageNoText.setText(cursor.getString(cursor.getColumnIndex(Order.Columns.VOYAGE_NO)));
if (hazmatFlag) {
hazmatText.setVisibility(View.VISIBLE);
} else {
hazmatText.setVisibility(View.GONE);
}
apptDateText.setText(cursor.getString(cursor.getColumnIndex(Order.Columns.APPT_DATE_TIME)));
apptTimeText.setText(cursor.getString(cursor.getColumnIndex(Order.Columns.APPT_TIME)));
moveTypeText.setText(cursor.getString(cursor.getColumnIndex(Order.Columns.MOVE_TYPE)));
confirmButton.setTag(orderId);
rejectButton.setTag(orderId);
if (confirmedFlag || _readOnly) {
confirmButton.setVisibility(View.GONE);
rejectButton.setVisibility(View.GONE);
} else {
confirmButton.setVisibility(View.VISIBLE);
rejectButton.setVisibility(View.VISIBLE);
confirmButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put(Order.Columns.CONFIRMED_FLAG, 1);
_context.getContentResolver().update(Uri.withAppendedPath(Order.CONTENT_URI, String.valueOf(v.getTag())), values, null, null);
/*
try {
SharedPreferences settings = _context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate(Constants.WEB_SERVICE_FIELD_FILE_NO, fileNo);
jsonObject.accumulate(Constants.WEB_SERVICE_FIELD_CONFIRMATION_TYPE, "Accepted");
jsonObject.accumulate(Constants.WEB_SERVICE_FIELD_LAST_UPDATE_USER_NAME, settings.getString(Constants.SETTINGS_USER_NAME, ""));
UploadQueueAsyncTask uploadAsyncTask = new UploadQueueAsyncTask(_context);
uploadAsyncTask.execute(new String[] { Constants.WEB_SERVICE_CONFIRM_REJECT_ORDER_URL, jsonObject.toString() });
} catch (JSONException e) {
}
*/
}
});
rejectButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(_context);
dialogBuilder.setTitle(_context.getResources().getString(R.string.reject_order_dialog_title));
dialogBuilder.setMessage(String.format(_context.getResources().getString(R.string.reject_order_dialog_message), fileNoText.getText()));
dialogBuilder.setPositiveButton(_context.getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
_context.getContentResolver().delete(
Uri.withAppendedPath(Order.CONTENT_URI, String.valueOf(v.getTag())),
null,
null);
/*
try {
SharedPreferences settings = _context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate(Constants.WEB_SERVICE_FIELD_FILE_NO, fileNo);
jsonObject.accumulate(Constants.WEB_SERVICE_FIELD_CONFIRMATION_TYPE, "Rejected");
jsonObject.accumulate(Constants.WEB_SERVICE_FIELD_LAST_UPDATE_USER_NAME, settings.getString(Constants.SETTINGS_USER_NAME, ""));
UploadQueueAsyncTask uploadAsyncTask = new UploadQueueAsyncTask(_context);
uploadAsyncTask.execute(new String[] { Constants.WEB_SERVICE_CONFIRM_REJECT_ORDER_URL, jsonObject.toString() });
} catch (JSONException e) {
}
*/
dialog.dismiss();
}
});
dialogBuilder.setNegativeButton(_context.getResources().getString(R.string.no), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialogBuilder.show();
}
});
}
}
}
|
package ariel.manndrops.game.viewmodel;
import android.databinding.ObservableField;
import android.graphics.Point;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import ariel.manndrops.game.view.GameActivity;
import ariel.manndrops.game.view.RainDropView;
import ariel.manndrops.game.viewmodel.events.OnRainDropFell;
import ariel.manndrops.game.viewmodel.exercisesmanagment.generation.model.ExerciseDataLevel;
import ariel.manndrops.profile.SharedPrefManager;
public class GameViewModel implements ViewModel {
private static final String TAG = GameViewModel.class.getName();
public ObservableField<String> userAnswer;
public ObservableField<String> score;
private GameActivity gameActivity;
private Map<String, RainDropView> allRainDropsOnScreen;
public GameViewModel(GameActivity gameActivity) {
// saveScreenSizesToSharedPref();
EventBus.getDefault().register(this);
userAnswer = new ObservableField<>(""); //empty string prevents "null" as string in result field
score = new ObservableField<>("0");
this.gameActivity = gameActivity;
this.allRainDropsOnScreen = new HashMap<>();
scheduleRainDropping(1000, 4000);
}
public void onNumberClicked(View clickedNumberView) {
Button numberButton = (Button) clickedNumberView;
userAnswer.set(userAnswer.get() + numberButton.getText());
}
public void onExerciseAnswered(View enterButton) {
if (!userAnswer.get().isEmpty()) {
onUserAnswered(userAnswer.get());
}
userAnswer.set("");
}
public void onDeleteClicked(View deleteButton) {
if (userAnswer.get().length() > 0) {
String resultWithoutLastDigit = (userAnswer.get().substring(0, userAnswer.get().length() - 1));
userAnswer.set(resultWithoutLastDigit);
}
}
public void onExerciseError() {
}
@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
gameActivity = null;
}
private void scheduleRainDropping(int delayTime, int constantInterval) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
dropRainDrop();
}
});
}
}, delayTime, constantInterval);
}
private void dropRainDrop() { //Raindrop is dropping method is called upon creation
//pass activity authorities, gameLayout and exercise model for exercise generation
String id = UUID.randomUUID().toString();
RelativeLayout gameLayout = gameActivity.getBinding().gameViewLayout;
RainDropView view = new RainDropView(gameActivity, id, gameLayout, ExerciseDataLevel.NORMAL);
allRainDropsOnScreen.put(id, view);
}
private void saveScreenSizesToSharedPref() {
Display display = gameActivity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
SharedPrefManager.getInstance(gameActivity).saveIntInfoToSharedPreferences(gameActivity, "deviceScreenHeight", height);
SharedPrefManager.getInstance(gameActivity).saveIntInfoToSharedPreferences(gameActivity, "deviceScreenWidth", width);
}
private void onUserCorrect(String rainDropId, View rainDropForRemove, String answer) {
removeRainDropFromScreen(rainDropId, rainDropForRemove);
Integer newScore = Integer.parseInt(score.get()) + Integer.parseInt(answer);
score.set(String.valueOf(newScore));
Log.d(TAG, "User was correct and raindrop with id: " + rainDropId + " was removed from screen");
}
private void onUserAnswered(String userAnswer) {
int numbrerOfExercisesBeforeCalculation = allRainDropsOnScreen.keySet().size();
Iterator iter = allRainDropsOnScreen.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry item = (Map.Entry<String, RainDropView>) iter.next();
String rainDropId = (String) item.getKey();
RainDropView rainDropView = (RainDropView) item.getValue();
if (rainDropView.getAnswer().equals(userAnswer)) {
Log.d(TAG, "User was correct with answer: " + rainDropView.getAnswer());
onUserCorrect(rainDropId, rainDropView.getView(), userAnswer);
}
}
if (numbrerOfExercisesBeforeCalculation == allRainDropsOnScreen.keySet().size()) {
onUserWrong();
}
}
@Subscribe
public void onRainDropFell(OnRainDropFell event) {
removeRainDropFromScreen(event.rainDropId, event.rainDropForRemove);
// removeAllRainDropsFromScreen();
Log.d(TAG, "Raindrop with id: " + event.rainDropId + " fell before user has answered it. activate panelty");
}
private void removeAllRainDropsFromScreen() {
for (Map.Entry<String, RainDropView> entry : allRainDropsOnScreen.entrySet()) {
String id = entry.getKey();
View rainDropView = entry.getValue().getView();
removeRainDropFromScreen(id, rainDropView);
}
allRainDropsOnScreen.clear();
}
private void onUserWrong() {
Integer currentScore = Integer.valueOf(score.get());
Integer scorePanelty = currentScore * 5 / 100; //Decrease 5% from total score
score.set(String.valueOf(currentScore - scorePanelty));
Log.d(TAG, "User was wrong, score panelty: " + scorePanelty);
}
private void removeRainDropFromScreen(String id, View rainDrop) {
allRainDropsOnScreen.remove(id);
gameActivity.getBinding().gameViewLayout.removeView(rainDrop);
}
} |
package br.com.vanhackathon.axiomzen.mastermind.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import br.com.vanhackathon.axiomzen.mastermind.MastermindManager;
import br.com.vanhackathon.axiomzen.mastermind.model.Game;
import br.com.vanhackathon.axiomzen.mastermind.model.User;
@Path("/new_game")
public class NewGame {
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response createNewGame(User user) {
if (user.getUser() == null) {
return Response.status(404).entity("No User, No Game!").build();
}
Game game = new Game();
MastermindManager manager = MastermindManager.getManager();
while (!manager.addGame(game)) {
game = new Game();
}
System.out.println("Welcome: " + user.getUser() + " yours Game Key is " + game.getGameKey());
game.setUser(user);
return Response.status(200).entity(game).build();
}
}
|
package designpatterns.factory.abstrac.factory;
import designpatterns.factory.abstrac.product.AbstractProductA;
import designpatterns.factory.abstrac.product.AbstractProductB;
public abstract class AbstractFactory {
public abstract AbstractProductA createAbstractProductA();
public abstract AbstractProductB createAbstractProductB();
}
|
package org.bca.training.spring.core;
import org.bca.training.spring.core.beans.data.Car;
import org.bca.training.spring.core.beans.data.Model;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "org.bca.training.spring.core")
public class Config {
Model modelFactory() {
return new Car();
}
}
|
package com.saasxx.core.module.common.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.saasxx.core.module.common.schema.PArea;
public interface AreaRepository extends JpaRepository<PArea, String> {
PArea findByCode(String regionCode);
}
|
package br.com.sousuperseguro.serviceImpl;
import java.math.BigInteger;
import java.util.ArrayList;
import org.springframework.stereotype.Service;
import br.com.sousuperseguro.service.PropostaService;
@Service
public class PropostServiceImpl implements PropostaService{
// @Override
public String calcularProposta(BigInteger novoIdProposta) {
//Valor setado harded coded de acordo com a conta dada pelo Bradesco.
String sigla = "SSC";
int contaSsc = 66;
String idPropostaString = novoIdProposta.toString();
int tamanhodaString = idPropostaString.length();
int tamanhoDeZeros = 11 - tamanhodaString;
String novaString = "";
for(int i = 0; i < tamanhoDeZeros; i++) {
novaString = 0 + novaString;
}
novaString = novaString + idPropostaString;
int stringNumeroDoisEum = 1;
ArrayList<Integer> arrayParaSoma = new ArrayList<Integer>();
char[] stringChar = novaString.toCharArray();
for( int i = (stringChar.length - 1) ; i >= 0 ; i-- ) {
if(stringNumeroDoisEum == 2) {
stringNumeroDoisEum = 1;
} else if(stringNumeroDoisEum == 1) {
stringNumeroDoisEum = 2;
}
int numeroDaProposta = Integer.parseInt(String.valueOf(stringChar[i]));
arrayParaSoma.add(numeroDaProposta * stringNumeroDoisEum);
}
int numeroFinalNumeros = 0;
for(Integer soma : arrayParaSoma) {
numeroFinalNumeros = numeroFinalNumeros + soma;
}
int numeroFinal = (contaSsc + numeroFinalNumeros);
int resto = numeroFinal % 10;
String digitoVerificador = "";
if(resto == 0) {
digitoVerificador = String.valueOf(0);
} else {
digitoVerificador = String.valueOf(10 - resto);
}
// digito verificador antigo com hifen
return sigla + novaString + "" + digitoVerificador;
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.scheduler.resourcemanager.nodesource.policy;
import java.io.File;
import org.apache.log4j.Logger;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.core.util.wrapper.BooleanWrapper;
import org.objectweb.proactive.extensions.annotation.ActiveObject;
import org.ow2.proactive.authentication.crypto.Credentials;
import org.ow2.proactive.resourcemanager.authentication.Client;
import org.ow2.proactive.resourcemanager.nodesource.common.Configurable;
import org.ow2.proactive.resourcemanager.nodesource.policy.NodeSourcePolicy;
import org.ow2.proactive.resourcemanager.utils.RMLoggers;
import org.ow2.proactive.scheduler.common.NotificationData;
import org.ow2.proactive.scheduler.common.Scheduler;
import org.ow2.proactive.scheduler.common.SchedulerAuthenticationInterface;
import org.ow2.proactive.scheduler.common.SchedulerConnection;
import org.ow2.proactive.scheduler.common.SchedulerEvent;
import org.ow2.proactive.scheduler.common.SchedulerEventListener;
import org.ow2.proactive.scheduler.common.SchedulerState;
import org.ow2.proactive.scheduler.common.job.JobInfo;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.UserIdentification;
import org.ow2.proactive.scheduler.common.task.TaskInfo;
@ActiveObject
public abstract class SchedulerAwarePolicy extends NodeSourcePolicy implements SchedulerEventListener {
/** */
private static final long serialVersionUID = 31L;
protected static Logger logger = ProActiveLogger.getLogger(RMLoggers.POLICY);
@Configurable
protected String schedulerUrl = "";
@Configurable(credential = true)
protected File schedulerCredentialsPath;
protected SchedulerState state;
protected Scheduler scheduler;
@Override
public BooleanWrapper configure(Object... params) {
super.configure(params);
SchedulerAuthenticationInterface authentication;
if (params[3] == null) {
throw new IllegalArgumentException("Credentials must be specified");
}
try {
authentication = SchedulerConnection.join(params[2].toString());
Credentials creds = Credentials.getCredentialsBase64((byte[]) params[3]);
scheduler = authentication.login(creds);
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
return new BooleanWrapper(true);
}
@Override
public BooleanWrapper activate() {
SchedulerAuthenticationInterface authentication;
try {
state = scheduler.addEventListener(getSchedulerListener(), false, true, getEventsList());
} catch (Exception e) {
logger.error("", e);
throw new RuntimeException(e.getMessage(), e);
}
return new BooleanWrapper(true);
}
@Override
public void shutdown(Client initiator) {
try {
scheduler.removeEventListener();
scheduler.disconnect();
} catch (Exception e) {
logger.error("", e);
}
super.shutdown(initiator);
}
public void jobStateUpdatedEvent(NotificationData<JobInfo> notification) {
}
public void jobSubmittedEvent(JobState job) {
}
public void schedulerStateUpdatedEvent(SchedulerEvent eventType) {
}
public void taskStateUpdatedEvent(NotificationData<TaskInfo> notification) {
}
public void usersUpdatedEvent(NotificationData<UserIdentification> notification) {
}
protected abstract SchedulerEvent[] getEventsList();
protected abstract SchedulerEventListener getSchedulerListener();
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge;
/**
* <a href="https://oj.leetcode.com/problems/longest-valid-parentheses/">
* Longest Valid Parentheses</a>
* <p/>
* Copyright 2013 LeetCode
* <p/>
* Given a string containing just the characters '(' and ')',
* find the length of the longest valid (well-formed) parentheses substring.
* <p/>
* For "(()", the longest valid parentheses substring is "()", which has length = 2.
* <p/>
* Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
* <p/>
*
* @see <a href="http://coding-exercise.blogspot.com/2013/03/leetcode-longest-valid-parentheses.html">Coding Exercise</a>
* @see <a href="http://discuss.leetcode.com/questions/212/longest-valid-parentheses">LeetCode discussion</a>
* @see <a href="http://yucoding.blogspot.com/2013/01/leetcode-question-46-longest-valid.html">Yu's Coding</a>
* http://jane4532.blogspot.com/2013/07/longest-valid-parenthesisleetcode.html
* @see <a href="http://www.mitbbs.com/article_t/JobHunting/32066231.html">mitbbs discussion</a>
*/
public interface LongestValidParentheses {
int longestValidParentheses(String s);
}
|
package polymorphismTest;
/**
*
* @file_name : Bank.java
* @author : dingo44kr@gmail.com
* @date : 2015. 9. 25.
* @story :
*/
import java.util.Scanner;
public class HanbitBank {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BankService service = BankService.getService();
Account a = new Account();
while (true) { // 무한루프를 사용할 때는 WhileLoop을 사용한다.
System.out.println("원하는 업무를 선택해주세요\n "
+ "1: 통장개설 2: 잔액조회 3: 입금 4: 출금 5: 정지");
int key = scanner.nextInt();
switch (key) {
case 1: // 통장개설
System.out.println("이름을 입력해주세요");
String accountName = scanner.next();
System.out.println("비밀번호를 입력해주세요");
int password = scanner.nextInt();
System.out.println(service.open(password, accountName));
break;
case 2: // 잔액조회
System.out.println(service.search());
break;
case 3: // 입금
System.out.println("입금할 금액을 입력해 주세요.");
int inMoney = scanner.nextInt();
System.out.println(service.deposit(inMoney));
break;
case 4: // 출금
System.out.println("출금할 금액을 입력해 주세요.");
int outMoney = scanner.nextInt();
System.out.println(service.withdraw(outMoney));
break;
case 5: // 정지
return;
default: break;
}
}
}
} |
package com.zs.bus;
import com.huaiye.sdk.sdpmsgs.meet.CStartMeetingReq;
import java.util.ArrayList;
/**
* author: admin
* date: 2018/05/29
* version: 0
* mail: secret
* desc: CloseView
*/
public class WaitViewAllFinish {
public String from;
public WaitViewAllFinish(String from) {
this.from = from;
}
}
|
package com.stk123.entity;
import javax.persistence.*;
import java.util.Objects;
//@Entity
@Table(name = "STK_SYNC_TABLE")
public class StkSyncTableEntity {
private String name;
private String pk;
@Id
@Column(name = "NAME", nullable = true, length = 200)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "PK", nullable = true, length = 200)
public String getPk() {
return pk;
}
public void setPk(String pk) {
this.pk = pk;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StkSyncTableEntity that = (StkSyncTableEntity) o;
return Objects.equals(name, that.name) &&
Objects.equals(pk, that.pk);
}
@Override
public int hashCode() {
return Objects.hash(name, pk);
}
}
|
package serenitylabs.tutorials;
import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.google.common.collect.TreeRangeMap;
import serenitylabs.tutorials.interfaces.ConversationalTime;
import serenitylabs.tutorials.interfaces.ProvideTime;
public class ConversationalClock {
private final ProvideTime timeProvider;
public ConversationalClock(ProvideTime timeProvider){this.timeProvider=timeProvider;}
private static RangeMap<Integer,ConversationalTime> TIME_FORMAT_STRATEGY= TreeRangeMap.create();
static{
TIME_FORMAT_STRATEGY.put(Range.closed(15,15),TransformToConversationalTime.QUARTER_PAST);
TIME_FORMAT_STRATEGY.put(Range.closed(30,30),TransformToConversationalTime.HALF_PAST);
TIME_FORMAT_STRATEGY.put(Range.closed(45,45),TransformToConversationalTime.QUARTER_TO);
TIME_FORMAT_STRATEGY.put(Range.closed(00,00),TransformToConversationalTime.DEFAULT);
TIME_FORMAT_STRATEGY.put(Range.closed(56,59),TransformToConversationalTime.ALMOST);
TIME_FORMAT_STRATEGY.put(Range.closed(01,04),TransformToConversationalTime.JUST_AFTER);
TIME_FORMAT_STRATEGY.put(Range.closed(05,14),TransformToConversationalTime.PAST);
TIME_FORMAT_STRATEGY.put(Range.closed(16,29),TransformToConversationalTime.PAST);
TIME_FORMAT_STRATEGY.put(Range.closed(31,44),TransformToConversationalTime.TO);
TIME_FORMAT_STRATEGY.put(Range.closed(46,55),TransformToConversationalTime.TO);
}
public String conversationalTime(){
Integer localTimeHour=timeProvider.getLocalTime().getHour();
Integer localTimeMinute=timeProvider.getLocalTime().getMinute();
return conversationalTimeFor(localTimeHour,localTimeMinute);
}
private String conversationalTimeFor(Integer localTimeHour, Integer localTimeMinute){
return TIME_FORMAT_STRATEGY.get(localTimeMinute).conversation(localTimeHour,localTimeMinute);
}
}
|
package conn.smart;
import conn.smart.connection.FacebookConnection;
import conn.smart.connection.Profile;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.json.Json;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
@WebServlet(name = "Smart", urlPatterns = "/Smart")
public class ServletSmartConn extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
//conexão com o fb
String email = request.getParameter("email");
String password = request.getParameter("password");
FacebookConnection fb = new FacebookConnection(email, password);
//string com informações
Profile pf = null;
StringBuilder notificationString = new StringBuilder();
StringBuilder messageString = new StringBuilder();
StringBuilder feedString = new StringBuilder();
//
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// FileWriter writer = new FileWriter("/main/saida.json");
List<JSONObject> jsonObjectList = new ArrayList<>();
try {
pf = fb.connectAndRetrieveProfile();
Profile finalPf = pf;
//monta notificações
pf.getNotifications().forEach(n -> {
JSONObject jsonObject = new JSONObject();
notificationString.append("<br>");
notificationString.append(finalPf.getNotifications().indexOf(n) + 1);
notificationString.append(" : ");
notificationString.append(n.getBody());
notificationString.append("<br>");
notificationString.append("Quando : ");
notificationString.append(n.getWhen());
notificationString.append("<br>");
jsonObject.put("notificacao:", n.getBody());
jsonObject.put("quando:", n.getWhen());
jsonObjectList.add(jsonObject);
});
//monta mensagens
pf.getMessages().forEach(n -> {
JSONObject jsonObjectMessage = new JSONObject();
messageString.append("<br>");
messageString.append("Quem : ");
messageString.append(n.getWho());
messageString.append("<br>");
messageString.append("Mensagem : ");
messageString.append(n.getBody());
messageString.append("<br>");
jsonObjectMessage.put("quem:", n.getWho());
jsonObjectMessage.put("menssagem:", n.getBody());
jsonObjectList.add(jsonObjectMessage);
});
// //monta feed
// pf.getFeed().forEach(n -> {
// feedString.append("<br>");
// feedString.append(finalPf.getFeed().indexOf(n) + 1);
// feedString.append(" : ");
// feedString.append(n.getBody());
// feedString.append("<br>");
// feedString.append("Quando : ");
// feedString.append(n.getWhen());
// feedString.append("<br>");
// });
} catch (IOException ex) {
ex.printStackTrace();
}
// try{
//// bf.write(jsonObjectList.toString());
//// bf.flush();
//// bf.close();
//// writer.write(jsonObjectList.toString());
//// writer.close();
// }
// catch (IOException ex) {
// ex.printStackTrace();
// }
String json = jsonObjectList.toString();
out.println("<!DOCTYPE html>\n" +
"<html lang=\"pt-BR\">\n" +
"<title>Smart Conn</title>\n" +
"<head>\n" +
" <meta charset=\"utf-8\" />\n" +
" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
" <title>Cadastro Usuario</title>\n" +
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" +
" <link rel=\"icon\" href=\"smartFiles/sc.png\" type=\"image/png\" sizes=\"16x16\">\n" +
" <link rel=\"stylesheet\" href=\"https://www.w3schools.com/w3css/4/w3.css\">\n" +
" <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Montserrat\">\n" +
" <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">\n" +
" <link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"main.css\" />\n" +
" <script src=\"main.js\"></script>\n" +
"</head>\n" +
"<style>\n" +
" body, h1,h2,h3,h4,h5,h6 {font-family: \"Montserrat\", sans-serif}\n" +
" .w3-row-padding img {margin-bottom: 12px}\n" +
" /* Set the width of the sidebar to 120px */\n" +
" .w3-sidebar {width: 120px;background: #222;}\n" +
" /* Add a left margin to the \"page content\" that matches the width of the sidebar (120px) */\n" +
" #main {margin-left: 120px}\n" +
" /* Remove margins from \"page content\" on small screens */\n" +
" @media only screen and (max-width: 600px) {#main {margin-left: 0}}\n" +
"</style>\n" +
"<body class=\"w3-black\">\n" +
"\n" +
"<!-- Icon Bar (Sidebar - hidden on small screens) -->\n" +
"<nav class=\"w3-sidebar w3-bar-block w3-small w3-hide-small w3-center\">\n" +
" <!-- Avatar image in top left corner -->\n" +
" <img src=\"smartFiles/smartconnLogo.png\" style=\"width:100%\">\n" +
" <a href=\"#\" class=\"w3-bar-item w3-button w3-padding-large w3-black\" id=\"a\" onclick=\"blackButton('a', 'b', 'c', 'd')\">\n" +
" <i class=\"fa fa-home w3-xxlarge\"></i>\n" +
" <p>HOME</p>\n" +
" </a>\n" +
" <a href=\"#teste\" class=\"w3-bar-item w3-button w3-padding-large w3-hover-black\" id=\"b\" onclick=\"blackButton('b', 'a', 'c', 'd')\">\n" +
" <i class=\"fa fa-user w3-xxlarge\"></i>\n" +
" <p>TESTE</p>\n" +
" </a>\n" +
" <a href=\"#charts\" class=\"w3-bar-item w3-button w3-padding-large w3-hover-black\" id=\"c\" onclick=\"blackButton('c', 'b', 'a', 'd')\">\n" +
" <i class=\"fa fa-area-chart w3-xxlarge\"></i>\n" +
" <p>CHARTS</p>\n" +
" </a>\n" +
" <a href=\"#contact\" class=\"w3-bar-item w3-button w3-padding-large w3-hover-black\" id=\"d\" onclick=\"blackButton('d', 'b', 'c', 'a')\">\n" +
" <i class=\"fa fa-envelope w3-xxlarge\"></i>\n" +
" <p>CONTATO</p>\n" +
" </a>\n" +
"</nav>\n" +
"\n" +
"<!-- Navbar on small screens (Hidden on medium and large screens) -->\n" +
"<div class=\"w3-top w3-hide-large w3-hide-medium\" id=\"myNavbar\">\n" +
" <div class=\"w3-bar w3-black w3-opacity w3-hover-opacity-off w3-center w3-small\">\n" +
" <a href=\"#\" class=\"w3-bar-item w3-button\" style=\"width:25% !important\">HOME</a>\n" +
" <a href=\"#teste\" class=\"w3-bar-item w3-button\" style=\"width:25% !important\">teste</a>\n" +
" <a href=\"#charts\" class=\"w3-bar-item w3-button\" style=\"width:25% !important\">CHARTS</a>\n" +
" <a href=\"#contact\" class=\"w3-bar-item w3-button\" style=\"width:25% !important\">CONTACT</a>\n" +
" </div>\n" +
"</div>\n" +
"\n" +
"<!-- Page Content -->\n" +
"<div class=\"w3-padding-large\" id=\"main\">\n" +
" <!-- Header/Home -->\n" +
" <header class=\"w3-container w3-padding-32 w3-center w3-black\" id=\"home\">\n" +
" <h1 class=\"w3-jumbo\"><span class=\"w3-hide-small\">Smart Conn</span> </h1>\n" +
" <p>Tornando suas conexões mais Smart</p>\n" +
" </header>\n" +
"\n" +
" <!-- teste Section -->\n" +
" <div class=\"w3-row w3-content w3-justify w3-text-grey w3-padding-64\" id=\"teste\">\n" +
" <h2 class=\"w3-text-light-grey\">Gerencie suas Redes Sociais</h2>\n" +
" <hr style=\"width:200px\" class=\"w3-opacity\">\n" +
" <p>Aplicação para quem quer tomar conta de suas Redes Sociais, sem gastar seu tempo com elas.\n" +
" Aqui você pode minerar os dados de qualquer conta de Rede Social, e ver nossa análise gráfica sobre.\n" +
" Também temos uma ferramenta para automação de postagens e menssagens. Faça um teste agora mesmo!\n" +
" </p>\n" +
" <h3 class=\"w3-padding-16 w3-text-light-grey\">Facebook</h3>\n" +
" <form name=\"\" action=\"Smart\" method=\"POST\">\n" +
" <p><input class=\"w3-input w3-padding-16\" type=\"text\" placeholder=\"Email\" required name=\"email\"></p>\n" +
" <p> <input class=\"w3-input w3-padding-16\" type=\"password\" placeholder=\"Password\" required name=\"password\" id=\"password\"> </p>\n" +
"\n" +
" <div class=\"w3-row w3-center w3-text-light-grey\">\n" +
" <div class=\"w3-row w3-quarter\">\n" +
" <p align=\"left\"><input class=\"w3-check\" type=\"checkbox\" onclick=\"showPassword()\"> <label> Mostrar Senha </label></p>\n" +
" </div>\n" +
" <div class=\"w3-row w3-half\"> </div>\n" +
" <div class=\"w3-row w3-quarter\">\n" +
" <p align=\"right\">\n" +
" <button class=\"w3-button w3-light-grey w3-padding-large\" type=\"submit\">\n" +
" <i class=\"fa fa-paper-plane\"></i> CONECTAR\n" +
" </button>\n" +
" </p>\n" +
" </div>\n" +
" </div>\n" +
" </form>\n" +
"\n" +
" <div class=\"w3-row w3-center w3-padding-16 w3-section w3-light-grey\">\n" +
" <div class=\"w3-third w3-section\">\n" +
" <span class=\"w3-xlarge\" > " + pf.getNotificationCount() + "</span><br>\n" +
" Notificações\n" +
" </div>\n" +
" <div class=\"w3-third w3-section\">\n" +
" <span class=\"w3-xlarge\"> "+ pf.getMessagesCount() +"</span><br>\n" +
" Mensagens\n" +
" </div>\n" +
" <div class=\"w3-third w3-section\">\n" +
" <span class=\"w3-xlarge\">" + 0 + "</span><br>\n" +
" Postagens\n" +
" </div>\n" +
" </div>\n" +
"\n" +
" <h3 class=\"w3-padding-16 w3-text-light-grey\"> Perfil de "+ pf.getName() +"</h3>" +
" <p class=\"w3-black\" style=\"margin: 16px \">Notificações:</p>\n" +
" <div class=\"w3-dark-grey\" style=\" max-height: 60ch; overflow: hidden; text-overflow: white-space: nowrap;\">\n" +
" <div class=\"w3-dark-grey\" style=\"margin-left:30px\"> " + notificationString + "</div>\n" +
" </div>\n" +
" <p class=\"w3-black\" style=\"margin: 16px \">Mensagens:</p>\n" +
" <div class=\"w3-dark-grey\" style=\" max-height: 60ch; overflow: hidden; text-overflow: white-space: nowrap;\">\n" +
" <div class=\"w3-dark-grey\" style=\"margin-left:30px\"> " + messageString + "</div>\n" +
" </div>\n" +
" <p class=\"w3-black\" style=\"margin: 16px \">Postagens:</p>\n" +
" <div class=\"w3-dark-grey\" style=\" max-height: 60ch; overflow: hidden; text-overflow: white-space: nowrap;\">\n" +
" <div class=\"w3-dark-grey\" style=\"margin-left:30px\"> <br> Nenhuma Postagem <br><br> </div>\n" +
" </div>\n" +
"\n" +
" <a href=\"/home/henrique/IdeaProjects/Projeto-Servlets/src/main/java/conn/smart/saida.json\" download>\n" +
" <button class=\"w3-button w3-light-grey w3-padding-large w3-section\">\n" +
" <i class=\"fa fa-download\"></i> Baixar Dados\n" +
" </button>\n" +
" </a>" +
"\n" +
" </div>\n" +
"</div>\n" +
"\n" +
"<!-- Portfolio Section -->\n" +
"<div class=\"w3-padding-64 w3-content\" id=\"charts\">\n" +
" <h2 class=\"w3-text-light-grey\">Charts</h2>\n" +
" <hr style=\"width:200px\" class=\"w3-opacity\">\n" +
"\n" +
" <!-- Grid for charts -->\n" +
" <div class=\"w3-row-padding\" style=\"margin:0 -16px\">\n" +
" <div class=\"w3-half\">\n" +
" <div id=\"piechart\"></div>" +
" </div>\n" +
" <h3 class=\" w3-half w3-padding-16 w3-text-light-grey\"><br><br> Tenha acesso à mais gráficos analíticos, faça teste Premium! </h3>"+
" </div>\n" +
" <!-- End Portfolio Section -->\n" +
"</div>\n" +
"\n" +
"<!-- Contact Section -->\n" +
"<div class=\"w3-padding-64 w3-content w3-text-grey\" id=\"contact\">\n" +
" <h2 class=\"w3-text-light-grey\">Contate-nos:</h2>\n" +
" <hr style=\"width:200px\" class=\"w3-opacity\">\n" +
"\n" +
" <div class=\"w3-section\">\n" +
" <p><i class=\"fa fa-map-marker fa-fw w3-text-white w3-xxlarge w3-margin-right\"></i> Rio do Sul - SC</p>\n" +
" <p><i class=\"fa fa-phone fa-fw w3-text-white w3-xxlarge w3-margin-right\"></i> Telefone: (47) 99190-9909</p>\n" +
" <p><i class=\"fa fa-envelope fa-fw w3-text-white w3-xxlarge w3-margin-right\"> </i> brkshen@gmail.com</p>\n" +
" </div><br>\n" +
" <p>Envie uma mensagem:</p>\n" +
"\n" +
" <form action=\"/action_page.php\" target=\"_blank\">\n" +
" <p><input class=\"w3-input w3-padding-16\" type=\"text\" placeholder=\"Nome\" required name=\"Nome\"></p>\n" +
" <p><input class=\"w3-input w3-padding-16\" type=\"text\" placeholder=\"Email\" required name=\"Email\"></p>\n" +
" <p><input class=\"w3-input w3-padding-16\" type=\"text\" placeholder=\"Mensagem\" required name=\"Mensagem\"></p>\n" +
" <p>\n" +
" <button class=\"w3-button w3-light-grey w3-padding-large\" type=\"submit\">\n" +
" <i class=\"fa fa-paper-plane\"></i> ENVIAR\n" +
" </button>\n" +
" </p>\n" +
" </form>\n" +
" <!-- End Contact Section -->\n" +
"</div>\n" +
"\n" +
"<!-- Footer -->\n" +
"<footer class=\"w3-content w3-padding-64 w3-text-grey w3-xlarge\">\n" +
" <a href=\"https://www.facebook.com/henriquegodoy.godofredo\" target=\"_blank\" class=\"fa fa-facebook-official w3-hover-opacity\"></a>\n" +
" <a href=\"https://www.instagram.com/henrick_nasc/\" target=\"_blank\" class=\"fa fa-instagram w3-hover-opacity\"></a>\n" +
" <a href=\"https://www.linkedin.com/in/henrique-nascimento-635a5216b/\" target=\"_blank\" class=\"fa fa-linkedin w3-hover-opacity\"></a>\n" +
" <a href=\"https://github.com/GodoyRick/\" target=\"_blank\" class=\"fa fa-github w3-hover-opacity\"></a>\n" +
" <!-- End footer -->\n" +
"</footer>\n" +
"\n" +
"<!-- END PAGE CONTENT -->\n" +
"</div>\n" +
"\n" +
"</body>\n" +
"<script>\n" +
" function showPassword() {\n" +
" var x = document.getElementById(\"password\");\n" +
" if (x.type === \"password\") {\n" +
" x.type = \"text\";\n" +
" } else {\n" +
" x.type = \"password\";\n" +
" }\n" +
" }\n" +
"\n" +
"\n" +
" function blackButton(a,b,c,d){\n" +
" document.getElementById(a).setAttribute('class', 'w3-bar-item w3-button w3-padding-large w3-black');\n" +
" document.getElementById(b).setAttribute('class', 'w3-bar-item w3-button w3-padding-large w3-hover-black');\n" +
" document.getElementById(c).setAttribute('class', 'w3-bar-item w3-button w3-padding-large w3-hover-black');\n" +
" document.getElementById(d).setAttribute('class', 'w3-bar-item w3-button w3-padding-large w3-hover-black');\n" +
" }\n" +
"\n" +
"</script>\n" +
"<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n" +
"\n" +
"<script type=\"text/javascript\">\n" +
" // Load google charts\n" +
" google.charts.load('current', {'packages':['corechart']});\n" +
" google.charts.setOnLoadCallback(drawChart);\n" +
"\n" +
" // Draw the chart and set the chart values\n" +
" function drawChart() {\n" +
" var data = google.visualization.arrayToDataTable([\n" +
" ['Tipo de Notificação', 'Total'],\n" +
" ['Notificação', " + pf.getNotificationCount() +"],\n" +
" ['Mensagem', " + pf.getMessagesCount() + "],\n" +
" ['Feed', " + 0 + "]\n" +
" ]);\n" +
"\n" +
" // Optional; add a title and set the width and height of the chart\n" +
" var options = {\n" +
" 'title':'Porcentagem das Notificações: ',\n" +
" 'width':550,\n" +
" 'height':400,\n" +
" 'backgroundColor': 'transparent',\n" +
" is3D: true,\n" +
" titleTextStyle: { color: '#FFF', size: '30'},\n" +
" legendTextStyle: { color: '#FFF' }\n" +
"\n" +
" };\n" +
"\n" +
" // Display the chart inside the <div> element with id=\"piechart\"\n" +
" var chart = new google.visualization.PieChart(document.getElementById('piechart'));\n" +
" chart.draw(data, options);\n" +
" }\n" +
"</script>" +
"\n" +
"</html>\n");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
|
package gameData;
import gameData.enums.Difficulty;
/**
* Created by paul.moon on 1/28/16.
*/
public class GameParameters {
private int nbRows;
private int nbColumns;
private int numberOfBattleShips;
private Difficulty difficulty;
public GameParameters() {
this.nbRows = 3;
this.nbColumns = 3;
this.numberOfBattleShips = 2;
this.difficulty = Difficulty.EASY;
}
public GameParameters(int nbRows, int nbColumns, int numberOfBattleShips, Difficulty difficulty) {
this.nbRows = nbRows;
this.nbColumns = nbColumns;
this.numberOfBattleShips = numberOfBattleShips;
this.difficulty = difficulty;
}
/*GETTERS AND SETTERS*/
public int getNbRows() {
return nbRows;
}
public int getNbColumns() {
return nbColumns;
}
public int getNumberOfBattleShips() {
return numberOfBattleShips;
}
public Difficulty getDifficulty() {
return difficulty;
}
}
|
package com.rof.uav.adpater;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.uav.rof.R;
import com.uav.rof.override.UAVTextView;
import com.uav.rof.vo.DataAdapterVO;
import java.util.ArrayList;
public class TextTextAdapter extends BaseAdapter {
private Context context;
ArrayList<DataAdapterVO> dataList;
private int design;
private LayoutInflater layoutInflater;
private int length;
public TextTextAdapter(Context context, ArrayList<DataAdapterVO> dataList, int design){
this.context=context;
this.dataList = dataList;
this.design = design;
layoutInflater=((Activity)context).getLayoutInflater();
this.length = dataList.size();
}
@Override
public int getCount() {
return this.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(context).
inflate(this.design, parent, false);
UAVTextView textViewL=(UAVTextView) convertView.findViewById(R.id.listtext1);
UAVTextView textViewR=(UAVTextView) convertView.findViewById(R.id.listtext2);
DataAdapterVO dataAdapterVO = (DataAdapterVO)dataList.get(position);
if(dataAdapterVO.getText().equals("Address")){
textViewR.setTextColor(Color.parseColor("#12ab55"));
textViewR.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
textViewR.setTextSize(20);
}
textViewL.setText( dataAdapterVO.getText());
textViewR.setText( dataAdapterVO.getText2());
return convertView;
}
}
|
package com.example.mdt;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Speaker extends AppCompatActivity {
private MediaPlayer mMediaPlayer;
private Button mButton;
private boolean isPlayingOnSpeaker = false;
Button btn5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speaker);
btn5 = (Button)findViewById(R.id.btn5);
AudioManager mAudioManager;
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
//mAudioManager.setMode(AudioManager.MODE_IN_CALL);
mAudioManager.setSpeakerphoneOn(true);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.audio);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mp.start();
Intent intent = new Intent(Speaker.this, Testspeaker.class);
startActivity(intent);
}
});
}
} |
/**
* project name:saas
* file name:WeChatUrlController
* package name:com.cdkj.wechat.controller
* date:2018/3/29 下午5:28
* author:bovine
* Copyright (c) CD Technology Co.,Ltd. All rights reserved.
*/
package com.cdkj.manager.wechat.controller;
import com.cdkj.common.base.controller.BaseController;
import com.cdkj.util.JsonUtils;
import com.cdkj.util.StringUtil;
import com.cdkj.constant.SysDictConstants;
import com.cdkj.manager.wechat.service.api.WeChatService;
import com.cdkj.manager.wechat.service.api.WechatFuncInfoService;
import com.cdkj.manager.wechat.util.ApiResult;
import com.cdkj.manager.wechat.util.WeChatUserUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* description: 授权控制器 <br>
* date: 2018/3/29 下午5:28
*
* @author bovine
* @version 1.0
* @since JDK 1.8
*/
@Controller
@RequestMapping("/wechat/url/")
@PropertySource("classpath:config/wechat.properties")
public class WeChatUrlController extends BaseController {
@Resource
private WeChatService weChatService;
@Value("${wechat.appid}")
private String componentAppId;
@Resource
private WechatFuncInfoService wechatFuncInfoService;
/**
* 不通过前端,后台直接获取微信CODE
*
* @param sysAccount 帐套号
* @param redirectUri 回调路径
* @param state 为空或者指定的值
* @param scope true snsapi_base ;false snsapi_userinfo
* @return
*/
@RequestMapping("/open/getWechatCode/{sysAccount}/{scope}")
public String getWechatCode(HttpServletRequest request, @PathVariable("sysAccount") String sysAccount,
@RequestParam(value = "redirectUri", required = false) String redirectUri,
@RequestParam(value = "state", required = false) String state, @PathVariable("scope") String scope) {
logger.debug("WechatUrlController.getWechatCode.sysAccount={},redirectUri={},state={},scope={}", sysAccount, redirectUri, state, scope);
if (!StringUtil.areNotEmpty(sysAccount)) {
return JsonUtils.resFailed("参数异常");
}
logger.debug("重定向地址1:" + redirectUri);
//根据帐套获取APPID
String appId = "wxf7d2ddffc117e8de";
// appId = redisClient.get(RedisKeys.WECHAT_AUTHORIZER_APPID + sysAccount);
// String scope;
//通过REDIS字典服务,提供数据查询
//需要先存前端给的地址redirectUri,然后换成本接口地址。
String code = request.getParameter("code");
//根据帐套获取微信配置信息
if (ObjectUtils.isEmpty(code)) {
request.getSession().setAttribute("WECHAT_CODE_REDIRECT_URI", redirectUri);
String url = "wechat.hubeta.com/wechat/url/open/getWechatCode/" + sysAccount + "/" + scope;
logger.debug("从微信服务端获取code失败,重试获取!");
logger.debug("重定向地址2:" + url);
return "redirect:" + WeChatUserUtil.getWechatCodeUrl(appId, url, scope, state, componentAppId);
}
logger.debug("重定向地址3:" + redirectUri);
redirectUri = (String) request.getSession().getAttribute("WECHAT_CODE_REDIRECT_URI");
try {
//如果有code,则用code 去获取openId,通过openId获取会员信息
//并且跳转到 传入的URL
ApiResult result = null;
if ("snsapi_userinfo".equals(scope)) {
result = WeChatUserUtil.getOpenIdByCodeScopeUserInfo(appId, code, "authorization_code", componentAppId, weChatService.getWeChatApiComponentToken());
}
if ("snsapi_base".equals(scope)) {
result = WeChatUserUtil.getOpenIdByCodeScopeBase(appId, code, "authorization_code", componentAppId, weChatService.getWeChatApiComponentToken());
}
//使用openId获取用户信息
logger.debug("从微信服务端获取信息成功:{}", result);
return "redirect:" + redirectUri;
} catch (Exception e) {
logger.error("WechatUrlController.getWechatCode.error", e);
return JsonUtils.resFailed("服务器异常,请稍后重试!");
}
}
/**
* 获取微信权限url
*
* @param sysAccount 帐套号
* @param redirectUri 回调路径
* @param state 为空或者指定的值
* @param scope snsapi_base, snsapi_userinfo
* @return
*/
@ResponseBody
@RequestMapping("/open/getAuthorizeURL")
public String getAuthorizeURL(String sysAccount, String redirectUri, String scope, String state) {
logger.debug("WechatUrlController.getAuthorizeURL.sysAccount={},redirectUri={},state={},scope={}", sysAccount, redirectUri, state, scope);
if (!StringUtil.areNotEmpty(sysAccount, redirectUri)) {
return JsonUtils.resFailed("参数异常");
}
try {
String appId = redisClient.get(SysDictConstants.PREFIX + "-" + SysDictConstants.GROUP_CODE.WE_CHAT_TYPE + "-" + SysDictConstants.WE_CHAT_TYPE.WX_APP_ID + "-" + sysAccount);
if (ObjectUtils.isEmpty(appId)) {
//调用数据admin 中的服务 获得APP ID信息
}
appId = "wxf7d2ddffc117e8de";
//查库里的授权码
//根据帐套获取对应的信息
String url = WeChatUserUtil.getWechatCodeUrl(appId, redirectUri, scope, state, componentAppId);
return JsonUtils.res(url);
} catch (Exception e) {
logger.error("WechatUrlController.getAuthorizeURL.error", e);
return JsonUtils.resFailed("系统异常");
}
}
@ResponseBody
@RequestMapping("/open/user")
public String userInfo() {
return "true";
}
} |
package com.maxmind.geoip2;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.CountryResponse;
import java.io.IOException;
import java.net.InetAddress;
public interface GeoIp2Provider {
/**
* @param ipAddress IPv4 or IPv6 address to lookup.
* @return A Country model for the requested IP address.
* @throws GeoIp2Exception if there is an error looking up the IP
* @throws IOException if there is an IO error
*/
CountryResponse country(InetAddress ipAddress) throws IOException,
GeoIp2Exception;
/**
* @param ipAddress IPv4 or IPv6 address to lookup.
* @return A City model for the requested IP address.
* @throws GeoIp2Exception if there is an error looking up the IP
* @throws IOException if there is an IO error
*/
CityResponse city(InetAddress ipAddress) throws IOException,
GeoIp2Exception;
}
|
package br.com.pwc.nfe.integracao.mail;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import br.com.pwc.nfe.integracao.mail.config.Account;
import br.com.pwc.nfe.integracao.mail.config.IntegradorEmailMessageFactory;
import br.com.pwc.nfe.integracao.mail.util.FileManager;
import br.com.pwc.nfe.integracao.mail.util.XmlInspector;
/**
* Classe que contém o job para o quartz executar.
*
* @author daniel.santos
*
*/
@Scope(value="singleton")
@Component
public class RunJobTask {
@Autowired
private IntegradorEmailMessageFactory messageFactory;
@Autowired
private XmlInspector xmlInspector;
@Autowired
private Integrador integrador;
@Autowired
private FileManager fileManager;
@Resource(name = "configPrincipal")
private Properties configProperties;
private EmailReader[] arrayOfEmailReader;
private static ExecutorService executorService;
@Autowired
private LoadAccounts loadAccounts;
@PostConstruct
public void init() {
// pega as contas configuradas
Account[] arrayOfAccounts = loadAccounts.getAccounts();
// cria o array de leitores de email e o array de threads
arrayOfEmailReader = new EmailReader[arrayOfAccounts.length];
executorService = Executors.newFixedThreadPool(arrayOfAccounts.length);
for(int i = 0; i < arrayOfEmailReader.length; i++) {
arrayOfEmailReader[i] = new EmailReader(
arrayOfAccounts[i], messageFactory, xmlInspector, integrador, fileManager, configProperties);
}
}
public void execute() {
for(int j = 0; j < arrayOfEmailReader.length; j++) {
executorService.execute(arrayOfEmailReader[j]);
}
}
public static ExecutorService getExecutorService() {
return executorService;
}
}
|
package com.bigbang.myfavoriteplaces.database;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.DatabaseConfiguration;
import androidx.room.InvalidationTracker;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import androidx.sqlite.db.SupportSQLiteOpenHelper;
import com.bigbang.myfavoriteplaces.model.Location;
@Database(entities = {Location.class}, version = 1)
public abstract class LocationDB extends RoomDatabase {
public abstract DAO dao();
private static LocationDB instance;
public static LocationDB getDatabase(Context context) {
if (instance == null) {
synchronized (LocationDB.class) {
instance = Room.databaseBuilder(context, LocationDB.class, "location_database")
.fallbackToDestructiveMigration()
.allowMainThreadQueries()
.addCallback(lRoomDatabaseCallback)
.build();
}
}
return instance;
}
private static RoomDatabase.Callback lRoomDatabaseCallback = new RoomDatabase.Callback() {
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
}
};
@NonNull
@Override
protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration config) {
return null;
}
@NonNull
@Override
protected InvalidationTracker createInvalidationTracker() {
return null;
}
@Override
public void clearAllTables() {
}
}
|
package com.cdkj.util;
import java.util.HashMap;
import java.util.Map;
/**
* Created by sky on 2016/2/25.
*/
public class ValidateCodeUtil {
public static Map<String, Object> getResult(String str) {
Map<String, Object> map = new HashMap<>();
map.put("code", str);
return map;
}
public static Map<String, Object> getCode() {
String code = "";
code += (int) (Math.random() * 9 + 1);
for (int i = 0; i < 5; i++) {
code += (int) (Math.random() * 10);
}
return getResult(code);
}
}
|
package com.ftf.phi.network.service.ip;
import com.ftf.phi.network.Restful;
import com.ftf.phi.network.service.Service;
import java.io.IOException;
//TODO: Encrypt the data to and from this service
public class IPService extends Service {
private static final int PORT = 1507;
private Thread serverThread;
private IPServer server;
private int port;
public IPService(Restful api){
this(api, PORT);
}
IPService(Restful api, int port) {
super(api);
this.port = port;
//Create a thread for the server to run on
try {
this.server = new IPServer(api, port);
this.serverThread = new Thread(this.server);
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop() throws InterruptedException {
this.server.stop();
this.serverThread.join();
}
public void pause(){
this.server.pause();
}
public void resume(){
this.server.resume();
}
}
|
package com.ider.ytb_tv.utils;
import com.ider.ytb_tv.data.AppEntry;
import com.ider.ytb_tv.data.Movie;
import com.ider.ytb_tv.data.PlayList;
import com.ider.ytb_tv.data.ResourceEntry;
import com.ider.ytb_tv.ui.fragment.MySearchFragment;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by ider-eric on 2016/8/12.
*/
public class JsonParser {
public static ArrayList<ResourceEntry> parseForApp(String json) {
if(json == null) {
return null;
}
ArrayList<ResourceEntry> apps = new ArrayList<>();
try {
JSONObject root = new JSONObject(json);
JSONArray array = root.getJSONObject("datalist").getJSONArray("list");
Utils.log(MySearchFragment.TAG, "arrays.length = " + array.length());
for(int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
AppEntry app = new AppEntry();
app.id = item.getInt("id");
app.name = item.getString("name");
app.pkgname = item.getString("package");
app.vername = item.getJSONObject("file").getString("vername");
app.vercode = item.getJSONObject("file").getInt("vercode");
app.iconurl = item.getString("icon");
app.graphics = item.getString("graphic");
apps.add(app);
}
} catch (Exception e) {
e.printStackTrace();
}
Utils.log(MySearchFragment.TAG, "apps.size = " + apps.size());
return apps;
}
public static ArrayList parsePopular(String json) {
if(json == null) {
return null;
}
ArrayList<Movie> list = new ArrayList<>();
try {
JSONObject rootJson = new JSONObject(json);
JSONArray items = rootJson.getJSONArray("items");
for(int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
Movie movie = new Movie();
movie.setId(item.getString("id"));
movie.setTitle(item.getJSONObject("snippet").getString("title"));
try {
movie.setCardImageUrl(item.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url"));
movie.setBgUrl(item.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url"));
} catch (Exception e) {
e.printStackTrace();
}
movie.setDuration(formatTime(item.getJSONObject("contentDetails").getString("duration")));
list.add(movie);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static String getNextPageToken(String json) {
try {
JSONObject rootJson = new JSONObject(json);
return rootJson.getString("nextPageToken");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static int getTotalResult(String json) {
try {
JSONObject rootJson = new JSONObject(json);
return rootJson.getJSONObject("pageInfo").getInt("totalResults");
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public static ArrayList<Movie> parseEditorChoice(String json) {
if(json == null) {
return null;
}
ArrayList<Movie> list = new ArrayList<>();
try{
JSONObject rootJson = new JSONObject(json);
JSONArray items = rootJson.getJSONArray("items");
for(int i = 0; i < items.length(); i++) {
JSONObject itemSnippet = items.getJSONObject(i).getJSONObject("snippet");
Movie movie = new Movie();
movie.setId(itemSnippet.getJSONObject("resourceId").getString("videoId"));
movie.setTitle(itemSnippet.getString("title"));
try {
movie.setCardImageUrl(itemSnippet.getJSONObject("thumbnails").getJSONObject("medium").getString("url"));
movie.setBgUrl(itemSnippet.getJSONObject("thumbnails").getJSONObject("high").getString("url"));
} catch (Exception e) {
e.printStackTrace();
}
list.add(movie);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static ArrayList parseRelateOrSearchVideos(String json) {
ArrayList<ResourceEntry> list = new ArrayList<>();
try {
JSONObject rootJson = new JSONObject(json);
JSONArray items = rootJson.getJSONArray("items");
for(int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
Movie movie = new Movie();
movie.setId(item.getJSONObject("id").getString("videoId"));
movie.setTitle(item.getJSONObject("snippet").getString("title"));
try {
movie.setCardImageUrl(item.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url"));
movie.setBgUrl(item.getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("high").getString("url"));
} catch (Exception e) {
e.printStackTrace();
}
list.add(movie);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static Map parseEditorChoiceId(String json) {
if(json == null) {
return null;
}
try {
JSONObject rootJson = new JSONObject(json);
JSONArray items = rootJson.getJSONArray("items");
for(int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
String title = item.getJSONObject("snippet").getString("title");
if(title.toLowerCase().contains("ider")) {
Map map = new HashMap();
map.put("id", item.getString("id"));
map.put("itemCount", item.getJSONObject("contentDetails").getInt("itemCount"));
return map;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static ArrayList<ResourceEntry> parsePlaylist(String json) {
ArrayList<ResourceEntry> list = new ArrayList<>();
try {
JSONObject rootJson = new JSONObject(json);
JSONArray items = rootJson.getJSONArray("items");
for(int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
PlayList playlist = new PlayList();
playlist.setId(item.getJSONObject("id").getString("playlistId"));
playlist.setTitle(item.getJSONObject("snippet").getString("title"));
list.add(playlist);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static ArrayList acceptVideosDuration(ArrayList list, String json) {
try {
JSONObject rootJson = new JSONObject(json);
JSONArray items = rootJson.getJSONArray("items");
for(int i = 0; i < items.length(); i++) {
((Movie)list.get(i)).setDuration(formatTime(items.getJSONObject(i).getJSONObject("contentDetails").getString("duration")));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static Movie getFullDescriptionVideo(String json, Movie movie) {
try {
JSONObject rootJson = new JSONObject(json);
JSONArray items = rootJson.getJSONArray("items");
String fullDes = items.getJSONObject(0).getJSONObject("snippet").getString("description");
String description;
if(!fullDes.contains("\n")) {
description = fullDes;
} else {
String[] dess = fullDes.split("\n");
description = dess.length > 1 ? dess[0] + "\n" + dess[1] : dess[0];
}
movie.setDescription(description);
movie.setPublishAt(formatPublishTime(items.getJSONObject(0).getJSONObject("snippet").getString("publishedAt")));
} catch (Exception e) {
e.printStackTrace();
}
return movie;
}
private static String formatTime(String ptTime) {
int ptH, ptM, ptS;
if(ptTime.contains("H") && ptTime.contains("M") && ptTime.contains("S")) {
ptH = Integer.parseInt(ptTime.substring(2, ptTime.indexOf("H")));
ptM = Integer.parseInt(ptTime.substring(ptTime.indexOf("H")+1, ptTime.indexOf("M")));
ptS = Integer.parseInt(ptTime.substring(ptTime.indexOf("M")+1, ptTime.indexOf("S")));
return ptH + ":" + ptM + ":" + formatNum(ptS);
} else if (!ptTime.contains("H") && ptTime.contains("M") && ptTime.contains("S")) {
ptM = Integer.parseInt(ptTime.substring(2, ptTime.indexOf("M")));
ptS = Integer.parseInt(ptTime.substring(ptTime.indexOf("M")+1, ptTime.indexOf("S")));
return ptM + ":" + formatNum(ptS);
} else if (!ptTime.contains("H") && !ptTime.contains("M") && ptTime.contains("S")) {
ptS = Integer.parseInt(ptTime.substring(2, ptTime.indexOf("S")));
return "00:" + formatNum(ptS);
} else if (!ptTime.contains("H") && ptTime.contains("M") && !ptTime.contains("S")) {
ptM = Integer.parseInt(ptTime.substring(2, ptTime.indexOf("M")));
return ptM + ":" + "00";
} else if (ptTime.contains("H") && !ptTime.contains("M") && ptTime.contains("S")) {
ptH = Integer.parseInt(ptTime.substring(2, ptTime.indexOf("H")));
ptS = Integer.parseInt(ptTime.substring(ptTime.indexOf("H")+1, ptTime.indexOf("S")));
return ptH + ":00:" + formatNum(ptS);
} else if (ptTime.contains("H") && !ptTime.contains("M") && !ptTime.contains("S")) {
ptH = Integer.parseInt(ptTime.substring(2, ptTime.indexOf("H")));
return ptH + ":00:00";
} else if (ptTime.contains("H") && ptTime.contains("M") && !ptTime.contains("S")) {
ptH = Integer.parseInt(ptTime.substring(2, ptTime.indexOf("H")));
ptM = Integer.parseInt(ptTime.substring(ptTime.indexOf("H")+1, ptTime.indexOf("M")));
return ptH + ":" + ptM + ":" + "00";
}
return "--:--";
}
private static String formatNum(int msh) {
return msh >= 10 ? String.valueOf(msh) : "0" + msh;
}
private static String formatPublishTime(String publishAt) {
publishAt = publishAt.substring(0, publishAt.lastIndexOf("T"));
return publishAt;
}
}
|
package tm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 tm.pojo.Hotel;
import tm.pojo.RetrievalCondition;
import tm.service.HotelService;
import tm.utils.PageHandler;
import java.util.ArrayList;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@Controller
@RequestMapping(value = "/hotelRetrieval")
public class HotelRetrievalController {
private RetrievalCondition retrievalCondition;
private List<Hotel> list;
private HotelService hotelService;
private PageHandler pageHandler;
@Autowired
public void setPageHandler(PageHandler pageHandler) {
this.pageHandler = pageHandler;
}
@Autowired
public void setRetrievalCondition(RetrievalCondition retrievalCondition) {
this.retrievalCondition = retrievalCondition;
}
@Autowired
public void setList(List<Hotel> list) {
this.list = list;
}
@Autowired
public void setHotelService(HotelService hotelService) {
this.hotelService = hotelService;
}
@RequestMapping(method = RequestMethod.GET)
public String hotelRetrieval(Model model) {
// list = hotelService.listPage(0,20);
// model.addAttribute("hotels",list);
model.addAttribute(retrievalCondition);
model.addAttribute("path","/hotelRetrieval/");
model.addAttribute("title","农家乐信息检索");
return "commonRetrieval";
}
@RequestMapping(value = "/page")
public String pageSubmit(RetrievalCondition condition, @RequestParam int pageNum) {
if(condition.getCondition() != null){
retrievalCondition.setCondition(condition.getCondition());
retrievalCondition.setValue(condition.getValue());
}
pageHandler.setPage(pageNum);
return "redirect:/hotelRetrieval/list";
}
@RequestMapping(value = "/list")
public String page(Model model){
list = new ArrayList<>();
switch (retrievalCondition.getCondition()) {
case "all":
list = hotelService.listPage();break;
case "byName":
list.add(hotelService.findByName(retrievalCondition.getValue()));
}
model.addAttribute("hotels", list);
model.addAttribute("retrievalCondition", retrievalCondition);
pageHandler.setModel(model,"/hotelRetrieval/page");
return "hotelRetrieval";
}
@RequestMapping(value = "/detail/{id}", method = GET)
public String detail(
@PathVariable("id") int id,
Model model) {
Hotel hotel = hotelService.findById(id);
model.addAttribute(hotel);
return "hotelDetail";
}
@RequestMapping(value = "/modify/{id}", method = GET)
public String modify( @PathVariable("id") int id,
Model model) {
Hotel hotel = hotelService.findById(id);
model.addAttribute(hotel);
return "hotelModify";
}
@RequestMapping(value = "/modify/{id}", method = POST)
public String submit( @PathVariable("id") int id,
Model model, Hotel hotel) {
hotelService.update(hotel);
model.addAttribute(hotel);
return "redirect:/hotelRetrieval/detail/" + id;
}
}
|
package com.imagsky.exception;
/**
*
*/
public interface ErrorCodeThrowable {
public abstract String getErrorCode();
}
|
package br.com.simcit.filmes.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import br.com.simcit.filmes.model.Filme;
/**
* Classe que será resposável por fazer a manipulação do banco de dados;
* Por padrão utilizamos o banco de dados interno do android, o SQLite;
* Para utizamos precisamos extender da classe SQLiteOpenHelper
* Para saber mais sobre Salvar Dados usando SQLite: https://developer.android.com/training/basics/data-storage/databases.html
*/
public class FilmeDao extends SQLiteOpenHelper {
private static final String DATABASE = "filmes.db";
private static final int VERSAO = 1;
private static final String TABELA = "filmes";
public FilmeDao(Context context) {
//Definimos o nome e versão do banco.
super(context, DATABASE, null, VERSAO);
}
//Se o banco de dados não existir o metodo onCreate é chamado é a hora certa para criamos o banco de dados.
@Override
public void onCreate(SQLiteDatabase db) {
//Pegamos o bancodeDados que foi criado, o parametro db e executamos nossa instrução sql.
db.execSQL("CREATE TABLE " + TABELA + " ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"titulo TEXT, " +
"genero INTEGER, " +
"classificacao TEXT," +
"ano INTEGER)");
}
//Metodo chamado semrpe que a versão do banco de dados for alterada.
// Momento perfeito para fazermos alterações no banco de dados.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/**
* Método resposavel por inserir o filme no banco de dados
*/
public void inserir(Filme filme) {
//Recebemos o objeto filme por parâmetro e preenchemos o nosso ContentValues,
//que conterá os dados que serão inseridos da tabela.
//Obs.: A chave deve ser igual ao nome da coluna da tabela.
ContentValues valores = new ContentValues();
valores.put("titulo", filme.getTitulo());
valores.put("genero", filme.getCategoria());
valores.put("ano", filme.getAno());
valores.put("classificacao", filme.getClassificacao());
//Otemos a instância do banco com permissões de escrita e passamos através do metodo
// insert(tabela que queremos inserir, coluna que será null, valores que serão inseridos)
getWritableDatabase().insert(TABELA, null, valores);
}
/**
* Método resposavel por alterar um filme no banco de dados
*/
public void alterar(Filme filme) {
//Recebemos o filme por parametro
//Definimos qual é a condição where
String whereClause = "id = ?";
//Criamos um Vetor contendo os valores que serão passados por essa condição
String whereArgs[] = {String.valueOf(filme.getId())};
//Criamos e preenchemos os ContentValues
ContentValues valores = new ContentValues();
valores.put("titulo", filme.getTitulo());
valores.put("genero", filme.getCategoria());
valores.put("ano", filme.getAno());
valores.put("classificacao", filme.getClassificacao());
//Otemos a instância do banco com permissões de escrita e passamos através do metodo
// update(tabela que queremos alterar os dados, os valores que serão alterados,
// condição where, argumentos da condição where);
getWritableDatabase().update(TABELA, valores, whereClause, whereArgs);
}
/**
* Método resposavel por excluir um filme no banco de dados
*/
public void excluir(Filme filme) {
//Recebemos o filme por parametro
//Definimos qual é a condição where
String whereClause = "id = ?";
//Criamos um vetor contendo os valores que serão passados por essa condição
String whereArgs[] = {String.valueOf(filme.getId())};
//Otemos a instância do banco com permissões de escrita e passamos através do metodo
// delete(a tabela que queremos excluir os dados, condição where, argumentos da condição where);
getWritableDatabase().delete(TABELA, whereClause, whereArgs);
}
/**
* Método resposavel por obter todos os filmes do banco de dados e retornar através de um ArrayList
*/
public ArrayList<Filme> getFilmes() {
// Criamos um cursor que irá receber os dados retornados pelo banco.
// obtemos a instância do banco com permissões de leitura e através do método query(
// a tabela que queremos consultar, vetor com as colunas que queremos, argumentos de selecao,
// vetor com os valores do argumento de selecao, groupBy, having, ordenado por)
Cursor cursor = getReadableDatabase().query(TABELA, null, null, null, null, null, "titulo");
//Criamos um arrayList que conterá os filmes rertornados pelo banco de dados
ArrayList<Filme> filmes = new ArrayList<>();
//Através de um laço, navegamos pelo cursor e a cada interação criamos um filme e
// armazenamos ele no arrayList
while (cursor.moveToNext()) {
Filme filme = new Filme();
filme.setId(cursor.getInt(cursor.getColumnIndex("id")));
filme.setTitulo(cursor.getString(cursor.getColumnIndex("titulo")));
filme.setCategoria(cursor.getInt(cursor.getColumnIndex("genero")));
filme.setClassificacao(cursor.getString(cursor.getColumnIndex("classificacao")));
filme.setAno(cursor.getInt(cursor.getColumnIndex("ano")));
filmes.add(filme);
}
//Fechamos o cursor para liberamrmos a memória
cursor.close();
//Retornamos o arrayList com os filmes
return filmes;
}
} |
package leetCode;
import java.util.Date;
public class SudokuSolver {
public void solveSudoku(char[][] board) {
Date date = new Date();
long start = date.getTime();
Board sodokuBoard = new Board();
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < board.length; c++) {
int value = board[r][c] - '0';
if (value > 0) {
sodokuBoard.set(r, c, value);
}
}
}
sodokuBoard.print();
int setCount = sodokuBoard.getSetCount();
while (!sodokuBoard.isOk() && sodokuBoard.checkBoard()) {
sodokuBoard.setBoard();
if (sodokuBoard.getSetCount() == setCount) {
System.out.println("guess!");
if (sodokuBoard.guess()) {
}
} else {
setCount = sodokuBoard.getSetCount();
}
}
if (sodokuBoard.isOk()) {
date = new Date();
long end = date.getTime();
System.out.println("解完!耗时:" + (end - start) + "毫秒");
} else {
System.out.println("无解!");
}
// sodokuBoard.print();
}
}
class Board {
private int[] rowSurplus;
private int[] colSurplus;
private int[] boxSurplus;
private Cell[][] cells;
private int setCount;
public Board() {
init();
}
/**
* 初始化
*/
private void init() {
setCount = 0;
rowSurplus = new int[9];
colSurplus = new int[9];
boxSurplus = new int[9];
for (int i = 0; i < 9; i++) {
this.rowSurplus[i] = 1;
this.colSurplus[i] = 1;
this.boxSurplus[i] = 1;
}
cells = new Cell[9][9];
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
cells[r][c] = new Cell();
}
}
}
public boolean setBoard() {
if (checkBoard()) {
setUnique();
for (int i = 0; i < 9; i++) {
for (int value = 1; value <= 9; value++) {
setRow(i, value);
setCol(i, value);
setBox(i, value);
}
}
return true;
} else {
return false;
}
}
/**
* 为某个格子填值
*
* @param r
* @param c
* @param value
*/
public boolean set(int r, int c, int value) {
if (checkValue(r, c, value)) {
removeRow(r, c, value);
removeCol(r, c, value);
removeBox(r, c, value);
this.cells[r][c].set(value);
this.setCount++;
return true;
} else {
return false;
}
}
/**
* 遍历board,为只剩一个候选值的格子填值
*
* @return
*/
public boolean setUnique() {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (cells[r][c].getSurplus() == 1) {
int value = cells[r][c].getUnique();
if (value > 0) {
set(r, c, value);
}
}
}
}
print();
return true;
}
/**
* 对于给定的值value和格子(r,c),去除同一行其他格子的value候选
*
* @param r
* @param value
*/
public void removeRow(int r, int c, int value) {
for (int i = 0; i < 9; i++) {
if (i != c) {
this.cells[r][i].remove(value);
}
}
}
/**
* 对于给定的值value和格子(r,c),去除同一列其他格子的value候选
*
* @param c
* @param value
*/
public void removeCol(int r, int c, int value) {
for (int i = 0; i < 9; i++) {
if (i != r) {
this.cells[i][c].remove(value);
}
}
}
/**
* 对于给定的值value和格子(r,c),去除所在九宫格其他格子的value候选
*
* @param r
* @param c
* @param value
*/
public void removeBox(int r, int c, int value) {
int r0 = (r / 3) * 3;
int c0 = (c / 3) * 3;
for (int i = r0; i < r0 + 3; i++) {
for (int j = c0; j < c0 + 3; j++) {
if (i != r && j != c) {
this.cells[i][j].remove(value);
}
}
}
}
/**
* 对于给定行r和值value,如果value只有唯一候选位,填值
*
* @param r
* @param value
*/
public void setRow(int r, int value) {
if (checkRow(r, value)) {
int index = -1;
int count = 0;
for (int c = 0; c < 9; c++) {
if (cells[r][c].getNumber()[value - 1] > 0) {
index = c;
count++;
}
}
if (count == 1) {
set(r, index, value);
}
}
}
/**
* 对于给定列c和值value,如果value只有唯一候选位,填值
*
* @param c
* @param value
*/
public void setCol(int c, int value) {
if (checkCol(c, value)) {
int index = -1;
int count = 0;
for (int r = 0; r < 9; r++) {
if (cells[r][c].getNumber()[value - 1] > 0) {
index = r;
count++;
}
}
if (count == 1) {
set(index, c, value);
}
}
}
/**
* 对于给定九宫格b和值value,如果value只有唯一候选位,填值
*
* @param b
* @param value
*/
public void setBox(int b, int value) {
int r0 = b / 3;
int c0 = b % 3;
if (checkBox(r0 * 3, c0 * 3, value)) {
int index_r = -1;
int index_c = -1;
int count = 0;
for (int r = r0 * 3; r < r0 * 3 + 3; r++) {
for (int c = c0 * 3; c < c0 * 3 + 3; c++) {
if (cells[r][c].getNumber()[value - 1] > 0) {
index_r = r;
index_c = c;
count++;
}
}
}
if (count == 1) {
set(index_r, index_c, value);
}
}
}
/**
* 对于给定的格子(r,c),如果其所在行r,列c和九宫格上均无value,返回true
*
* @param r
* @param c
* @param value
* @return
*/
public boolean checkValue(int r, int c, int value) {
if (checkRow(r, value) && checkCol(c, value) && checkBox(r, c, value)) {
return true;
} else {
return false;
}
}
/**
* 给定行r和值value,如果r上已有value,返回false
*
* @param r
* @param value
*/
public boolean checkRow(int r, int value) {
for (int i = 0; i < 9; i++) {
if (this.cells[r][i].getValue() == value) {
return false;
}
}
return true;
}
/**
* 给定列c和值value,如果c上已有value,返回false
*
* @param c
* @param value
*/
public boolean checkCol(int c, int value) {
for (int i = 0; i < 9; i++) {
if (this.cells[i][c].getValue() == value) {
return false;
}
}
return true;
}
/**
* 给定格子(r,c)和值value,如果(r,c)所在九宫格上已有value,返回false
*
* @param i
* 0-9
* @param j
* 0-9
* @param value
*/
public boolean checkBox(int r, int c, int value) {
for (int i = (r / 3) * 3; i < (r / 3) * 3 + 3; i++) {
for (int j = (c / 3) * 3; j < (c / 3) * 3 + 3; j++) {
if (this.cells[i][j].getValue() == value) {
return false;
}
}
}
return true;
}
/**
* 遍历盘面所有格子,如果有一个格子没有值可填,返回false
*
* @return
*/
public boolean checkBoard() {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
int count = 0;
for (int value = 1; value <= 9; value++) {
if (cells[r][c].getNumber()[value - 1] > 0) {
count++;
break;
}
}
if (count == 0) {
return false;
}
}
}
return true;
}
public boolean isOk() {
if (this.getSetCount() == 81) {
print();
return true;
} else {
return false;
}
}
/**
* 猜值
*
* @return
*/
public boolean guess() {
GuessValue guessValue = new GuessValue(this);
int index = guessValue.getArternateValues();
if (index < 0) {
return false;
} else {
set(guessValue.getR(), guessValue.getC(),
guessValue.getValues()[index]);
return true;
}
}
/**
* 打印结果
*/
public void print() {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
int value = cells[r][c].getValue();
if (value > 0) {
System.out.print(value);
} else {
System.out.print(".");
}
}
System.out.println("");
}
System.out.println("");
}
public Cell[][] getCells() {
return cells;
}
public void setCells(Cell[][] cells) {
this.cells = cells;
}
public int getSetCount() {
return setCount;
}
public void setSetCount(int setCount) {
this.setCount = setCount;
}
}
class GuessValue {
private Board[] tempBoards;
private Board sokudoBoard;
private int[] values;
private int[] guessResult;
private int setCount;
private int r;
private int c;
public GuessValue(Board board) {
init(board);
this.sokudoBoard = board;
}
private void init(Board board) {
this.r = -1;
this.c = -1;
this.values = new int[2];
this.tempBoards = new Board[2];
this.guessResult = new int[2];
for (int i = 0; i < 2; i++) {
tempBoards[i] = new Board();
guessResult[i] = -1;
values[i] = -1;
}
this.setCount = board.getSetCount();
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
tempBoards[0].set(r, c, board.getCells()[r][c].getValue());
tempBoards[1].set(r, c, board.getCells()[r][c].getValue());
}
}
}
public int doGuess(int r, int c, int[] values) {
tempBoards[0].set(this.r, this.c, values[0]);
this.setCount = tempBoards[0].getSetCount();
do {
tempBoards[0].setBoard();
if (this.setCount == tempBoards[0].getSetCount()) {
guessResult[0] = 0;
if (tempBoards[0].isOk()) {
guessResult[0] = 1;
}
break;
} else {
this.setCount = tempBoards[0].getSetCount();
}
} while (tempBoards[0].checkBoard());
tempBoards[1].set(this.r, this.c, values[1]);
this.setCount = tempBoards[1].getSetCount();
do {
tempBoards[1].setBoard();
if (this.setCount == tempBoards[1].getSetCount()) {
guessResult[1] = 0;
if (tempBoards[1].isOk()) {
guessResult[1] = 1;
}
break;
} else {
this.setCount = tempBoards[1].getSetCount();
}
} while (tempBoards[1].checkBoard());
if (guessResult[0] == 1 || guessResult[1] == 1) {
if (guessResult[0] == 1) {
System.out.println(this.r + "," + this.c + ",value="
+ values[0]);
return 0;
} else {
System.out.println(this.r + "," + this.c + ",value="
+ values[1]);
return 1;
}
} else if (guessResult[0] == -1 || guessResult[1] == -1) {
if (guessResult[0] == -1) {
return 1;
} else {
return 0;
}
} else {
return -1;
}
}
/**
* 寻找只有两个候选值的单元格
*
* @return
*/
public int getArternateValues() {
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (tempBoards[0].getCells()[r][c].getSurplus() == 2
&& this.values[1] <= 0) {
this.r = r;
this.c = c;
for (int i = 0; i < 9; i++) {
if (tempBoards[0].getCells()[r][c].getNumber()[i] > 0) {
if (this.values[0] <= 0) {
this.values[0] = i + 1;
} else {
this.values[1] = i + 1;
}
}
}
int index = doGuess(r, c, this.values);
if (index >= 0) {
return index;
} else {
init(this.sokudoBoard);
continue;
}
}
}
}
return -1;
}
public Board[] getTempBoards() {
return tempBoards;
}
public void setTempBoards(Board[] tempBoards) {
this.tempBoards = tempBoards;
}
public int[] getGuessResult() {
return guessResult;
}
public void setGuessResult(int[] guessResult) {
this.guessResult = guessResult;
}
public int getSetCount() {
return setCount;
}
public void setSetCount(int setCount) {
this.setCount = setCount;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
public int getC() {
return c;
}
public void setC(int c) {
this.c = c;
}
public void setValues(int[] values) {
this.values = values;
}
public int[] getValues() {
return values;
}
}
class Cell {
private int surplus;
private int value;
private int[] number = new int[9];
public Cell() {
this.surplus = 9;
this.value = -1;
for (int i = 0; i < number.length; i++) {
number[i] = 1;
}
}
/**
* 确定值
*
* @param c
*/
public void set(int value) {
if (this.value < 0 && (value >= 1 && value <= 9)) {
this.value = value;
this.surplus = 1;
for (int i = 0; i < 9; i++) {
number[i] = 0;
}
number[value - 1] = 1;
}
}
/**
* 去掉一个候选值
*
* @param c
*/
public boolean remove(int value) {
if (this.value < 0 && (value >= 1 && value <= 9)) {
if (this.number[value - 1] > 0) {
this.number[value - 1] = 0;
this.surplus--;
// if (this.surplus == 1) {
// for (int i = 0; i < 9; i++) {
// if (this.number[i] > 0) {
// set(i + 1);
// return true;
// }
// }
// return false;
// }
if (this.surplus == 0) {
return false;
}
}
}
return true;
}
/**
* 获取剩余唯一值
*
* @return
*/
public int getUnique() {
if (this.surplus > 1) {
return -1;
} else {
for (int i = 0; i < 9; i++) {
if (this.number[i] > 0) {
return i + 1;
}
}
}
return -1;
}
public int getSurplus() {
return surplus;
}
public void setSurplus(int surplus) {
this.surplus = surplus;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int[] getNumber() {
return number;
}
public void setNumber(int[] number) {
this.number = number;
}
}
|
package application.model.bank;
import application.model.exceptions.FundsException;
import application.model.exceptions.PaymentRefusedException;
import application.util.MySimpleStringProperty;
import javafx.beans.property.StringProperty;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Random;
public class Bank implements Serializable {
private final StringProperty name;
private final int bankPrefix = new Random().nextInt(90000) + 10000;
private ArrayList<Customer> customers = new ArrayList<>();
public int getBankPrefix() {
return bankPrefix;
}
public String getName() {
return name.get();
}
public StringProperty getNameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
public int getCustomersNumber() {
return customers.size();
}
public ArrayList<Customer> getCustomers() {
return customers;
}
public void addCustomer(Customer customer) {
customers.add(customer);
}
public void setCustomers(ArrayList<Customer> customers) {
this.customers = customers;
}
public Bank() {
this(null);
}
public Bank(String name) {
this.name = new MySimpleStringProperty(name);
}
public void chargeCard(int cardNumber, BigDecimal amount)
throws FundsException, PaymentRefusedException {
if (new Random().nextInt(100) + 1 > 20) {
Card card = findCard(cardNumber);
if (card == null) throw new PaymentRefusedException("Card not found");
card.charge(amount);
}
else {
throw new PaymentRefusedException("Bank has refused transaction");
}
}
public Card findCard(int cardNumber) {
for (Customer customer : customers) {
for (Card card : customer.getCards())
if (card.getCardNumber() == cardNumber) return card;
}
return null;
}
}
|
package classes;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
@Entity
public class Personne {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@NotNull
private String nom;
@NotNull
private String prenom;
private String numTel;
public Personne(String nom, String prenom, String numTel) {
super();
this.nom = nom;
this.prenom = prenom;
this.numTel = numTel;
}
protected Personne() {
this.nom ="";
this.prenom ="";
this.numTel ="";
};
public String getNom() {
return nom;
}
public String getNumTel() {
return numTel;
}
public String getPrenom() {
return prenom;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setNom(String nom) {
this.nom = nom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public void setNumTel(String numTel) {
this.numTel = numTel;
}
@Override
public String toString() {
return "Personne [nom=" + nom + ", prenom=" + prenom + ", numTel=" + numTel + "]";
}
}
|
package de.cuuky.varo.combatlog;
import org.bukkit.Bukkit;
import de.cuuky.varo.Main;
import de.cuuky.varo.alert.Alert;
import de.cuuky.varo.alert.AlertType;
import de.cuuky.varo.config.config.ConfigEntry;
import de.cuuky.varo.config.messages.ConfigMessages;
import de.cuuky.varo.logger.logger.EventLogger.LogType;
import de.cuuky.varo.player.VaroPlayer;
import de.cuuky.varo.player.event.BukkitEventType;
import de.cuuky.varo.player.stats.stat.Strike;
public class Combatlog {
/*
* OLD CODE
*/
public Combatlog(VaroPlayer player) {
player.onEvent(BukkitEventType.KICKED);
new Alert(AlertType.COMBATLOG, player.getName() + " hat sich im Kampf ausgeloggt!");
if(ConfigEntry.STRIKE_ON_COMBATLOG.getValueAsBoolean()) {
player.getStats().addStrike(new Strike("CombatLog", player, "CONSOLE"));
Main.getLoggerMaster().getEventLogger().println(LogType.ALERT, ConfigMessages.ALERT_COMBAT_LOG_STRIKE.getValue(player));
} else
Main.getLoggerMaster().getEventLogger().println(LogType.ALERT, ConfigMessages.ALERT_COMBAT_LOG.getValue(player));
Bukkit.broadcastMessage(ConfigMessages.COMBAT_LOGGED_OUT.getValue(player));
}
}
|
package com.yusys.workFlow;
import java.util.List;
import java.util.Map;
public interface WFContractDao {
//查询项目业务数据
public Map<String, String> queryWFContractData(String id);
//根据id修改项目计划对应信息审批状态
public void updateContractById(Map<String,String> map);
//通过流程实例id获取审批过程信息
public List<Map<String,Object>> queryAppIdByInstId(Map<String,Object> map);
//根据id修改项目应信息的当前审批人
public void updateCurrPersonById(Map<String,String> map);
}
|
public class Locker {
public static void main(String[] args) {
boolean[] coins = new boolean[11];
//Open all multiples of 1 before moving on to 2
for (int i = 1; i < coins.length; i++) {
coins[i] = true;
}
//open every locker for every multiple of i
for (int i = 2; i <= 10; i++) {
for (int j = 1; i * j <= 10; j++) {
coins[i * j] = (coins[i * j] == true) ? false : true;
}
}
//Display the indices of the open lockers
for (int i = 0; i < coins.length; i++) {
if (coins[i] == true)
System.out.println("Coins " + i + " is Head.");
}
}
} |
/*
* Copyright 2008, Myron Marston <myron DOT marston AT gmail DOT com>
*
* This file is part of Fractal Composer.
*
* Fractal Composer 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.
*
* Fractal Composer 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 Fractal Composer. If not, see <http://www.gnu.org/licenses/>.
*/
package com.myronmarston.music.settings;
import com.myronmarston.music.GermIsEmptyException;
import com.myronmarston.music.OutputManager;
import com.myronmarston.util.Subscriber;
import org.simpleframework.xml.*;
/**
* An abstract class containing a common interface and common logic shared
* by the Voice and Section classes.
*
* @param <M> the main type--Voice or Section
* @param <O> the other type--Voice, if this is a Section, or Section,
* if this is a voice
* @author Myron
*/
@Root
public abstract class AbstractVoiceOrSection<M extends AbstractVoiceOrSection, O extends AbstractVoiceOrSection> implements Subscriber {
@Element
private FractalPiece fractalPiece;
@Attribute
private int uniqueIndex;
private VoiceSectionList voiceSections;
private String className = null;
/**
* Constructor.
*
* @param fractalPiece The FractalPiece that this Voice or
* Section is a part of
* @param uniqueIndex unique index for this voice or section
*/
protected AbstractVoiceOrSection(FractalPiece fractalPiece, int uniqueIndex) {
this.uniqueIndex = uniqueIndex;
this.fractalPiece = fractalPiece;
}
/**
* Gets the FractalPiece that this Voice or Section is a part of.
*
* @return The FractalPiece that this Voice or Section is a part of
*/
public FractalPiece getFractalPiece() {
return this.fractalPiece;
}
/**
* Gets an index that is unique for each voice or section in the list. This
* is also 1-based so as to be human readable. This is intended to support
* fractalcomposer.com so as to provide a unique div id. The regular index
* cannot be used because adding/removing items via AJAX can result in
* duplicate div ids.
*
* @return the unique index
*/
public int getUniqueIndex() {
return uniqueIndex;
}
/**
* Sets the unique index.
*
* @param uniqueIndex the unique index
*/
protected void setUniqueIndex(int uniqueIndex) {
this.uniqueIndex = uniqueIndex;
}
/**
* Gets a list of VoiceSections. This is guarenteed to never return null.
* The list of VoiceSections will be a subset of all the VoiceSections for
* the entire FractalPiece. Specifically, if this is a Voice, the list will
* contain each VoiceSection for this Voice, and for each Section. If this
* is a Section, the list will contain each VoiceSection for this Section,
* and for each Voice.
*
* @return the list of VoiceSections
*/
public VoiceSectionList getVoiceSections() {
if (voiceSections == null) voiceSections = new VoiceSectionList(this.getFractalPiece().getVoiceSections(), this);
return voiceSections;
}
/**
* Returns the FractalPiece's list of this type. When implemented by the
* Voice class, this should return a list of all Voices in the fractal
* piece. When implemented by the Section class, this should return a list
* of al the Sections in the fractal piece.
*
* @return a List of Voices (if the implementing type is Voice) or a list
* of Sections (if the implementing type is Section)
*/
protected abstract VoiceOrSectionList<M, O> getListOfMainType();
/**
* When implemented by the Voice class, this should return a list of all the
* Sections in the fractal piece. When implemented by the Section class,
* this should return a list of all the Voices in the fractal piece.
*
* @return a List of Voices (if the implementing type is Section) or a List
* of Sections (if the implementing type is Voice)
*/
protected abstract VoiceOrSectionList<O, M> getListOfOtherType();
/**
* Creates a VoiceSectionHashMapKey, combining this object with an object
* of the other type, based on the index.
*
* @param index The index in the list of the other type to combine
* with to create the hash map key
* @return A VoiceSectionHashMapKey that can be used to get a
* specific VoiceSection
*/
protected abstract VoiceSectionHashMapKey getHashMapKeyForOtherTypeIndex(int index);
/**
* Creates a VoiceSectionHashMapKey, combining this object with an object
* of the other type, based on the unique index.
* @param uniqueIndex The unique index in the list of the other type to
* combine with to create the hash map key
* @return A VoiceSectionHashMapKey that can be used to get a
* specific VoiceSection
*/
protected abstract VoiceSectionHashMapKey getHashMapKeyForOtherTypeUniqueIndex(int uniqueIndex);
/**
* Instantiates and returns a VoiceSection, using this and the passed voice
* or section.
* @param vOrS a Voice or Section to use in the instantiating
* @return a new VoiceSection
*/
protected abstract VoiceSection instantiateVoiceSection(O vOrS);
/**
* Creates the output manager for this voice or section.
*
* @return the output manager
* @throws com.myronmarston.music.GermIsEmptyException if the germ is empty
*/
public abstract OutputManager createOutputManager() throws GermIsEmptyException;
/**
* Gets the name of this class--e.g., "Voice" or "Section".
*
* @return the name of this type
*/
public String getClassName() {
if (className == null) className = this.getClass().getSimpleName();
return className;
}
/**
* Sets all voice sections for this voice or section to rest.
*
* @param val true to rest; false to not rest
*/
public void setRestOnAllVoiceSections(boolean val) {
for (VoiceSection vs : this.getVoiceSections()) {
vs.setRest(val);
}
}
/**
* Clears the cached voice section results. Should be called whenever a
* setting is changed that is used by the voice sections.
*/
protected void clearVoiceSectionResults() {
for (VoiceSection vs : this.getVoiceSections()) {
vs.clearVoiceSectionResult();
}
}
}
|
package fr.iutinfo.skeleton.api;
import fr.iutinfo.skeleton.auth.AuthFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import java.util.List;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
@Path("/voeux")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class VoeuxResource {
private static VoeuxDao dao = BDDFactory.getDbi().open(VoeuxDao.class);
final static Logger logger = LoggerFactory.getLogger(SecureResource.class);
Gson gson = new Gson();
@GET
@Path("{login}")
public Response getVoeux(@PathParam("login") String login) {
List<Voeu> reponse = dao.getVoeuxByLogin(login);
return Response.status(200).entity(gson.toJson(reponse)).build();
}
@PUT
public Response addVoeuTo(@QueryParam("login") String login,@QueryParam("feno") int feno) {
dao.addVoeuTo(login, feno);
return Response.status(200).entity(gson.toJson(login)).build();
}
@DELETE public Response removeVoeuTo(@QueryParam("login") String login,@QueryParam("feno") int feno) {
dao.removeVoeuTo(login,feno);
return Response.status(200).entity("Ok").build();
}
}
|
package com.projeto.jpa.javajpademo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JavajpademoApplication {
public static void main(String[] args) {
SpringApplication.run(JavajpademoApplication.class, args);
}
}
|
/* ====================================================================
*
* Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved.
*
* ==================================================================== *
*/
package com.aof.component.prm.bid;
import java.io.Serializable;
import java.util.Set;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
* @author CN01458
* @version 2005-6-28
*/
public class SalesStep implements Serializable {
private Long id;
private SalesStepGroup stepGroup;
private Integer seqNo;
private String description;
private Integer percentage;
private Set activities;
/**
* @param id
* @param stepGroup
* @param seqNo
* @param description
* @param percentage
* @param activities
*/
public SalesStep(Long id, SalesStepGroup stepGroup, Integer seqNo,
String description, Integer percentage, Set activities) {
super();
this.id = id;
this.stepGroup = stepGroup;
this.seqNo = seqNo;
this.description = description;
this.percentage = percentage;
this.activities = activities;
}
/**
* @param id
*/
public SalesStep(Long id) {
super();
this.id = id;
}
/**
*
*/
public SalesStep() {
super();
}
/**
* @return Returns the activities.
*/
public Set getActivities() {
return activities;
}
/**
* @param activities The activities to set.
*/
public void setActivities(Set activities) {
this.activities = activities;
}
/**
* @return Returns the description.
*/
public String getDescription() {
return description;
}
/**
* @param description The description to set.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return Returns the id.
*/
public Long getId() {
return id;
}
/**
* @param id The id to set.
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return Returns the percentage.
*/
public Integer getPercentage() {
return percentage;
}
/**
* @param percentage The percentage to set.
*/
public void setPercentage(Integer percentage) {
this.percentage = percentage;
}
/**
* @return Returns the seqNo.
*/
public Integer getSeqNo() {
return seqNo;
}
/**
* @param seqNo The seqNo to set.
*/
public void setSeqNo(Integer seqNo) {
this.seqNo = seqNo;
}
/**
* @return Returns the stepGroup.
*/
public SalesStepGroup getStepGroup() {
return stepGroup;
}
/**
* @param stepGroup The stepGroup to set.
*/
public void setStepGroup(SalesStepGroup stepGroup) {
this.stepGroup = stepGroup;
}
public String toString() {
return new ToStringBuilder(this)
.append("Id", getId())
.toString();
}
public boolean equals(Object other) {
if ( !(other instanceof SalesStep) ) return false;
SalesStep castOther = (SalesStep) other;
return new EqualsBuilder()
.append(this.getId(), castOther.getId())
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder()
.append(getId())
.toHashCode();
}
}
|
package com.xsis.batch197.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
@Entity
@Table(name = "kelasdetail")
public class KelasDetailModel {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "kelasdetail_seq")
@TableGenerator(name = "kelasdetail_seq", table = "tbl_sequences",pkColumnName = "seq_id", valueColumnName = "seq_value", initialValue = 0, allocationSize = 1)
@Column(name = "id")
private int id;
@Column(name = "kelas_id", nullable = false)
private int kelasId;
@Column(name = "mahasiswa_id", nullable = false)
private int mahasiswaId;
@ManyToMany
@JoinColumn(name = "kelas_id", foreignKey=@ForeignKey(name="fk_kelas_kelasdetail"), updatable = false, insertable = false)
private List<KelasModel> listKelas = new ArrayList<KelasModel>();
@ManyToMany
@JoinColumn(name = "mahasiswa_id", foreignKey=@ForeignKey(name="fk_mahasiswa_kelasdetail"), updatable = false, insertable = false)
private List<MahasiswaModel> listMhs = new ArrayList<MahasiswaModel>();
@Column(name = "Bobot", nullable=false)
private int bobot;
@Column(name = "Status", length = 10, nullable=false)
private String status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getKelasId() {
return kelasId;
}
public void setKelasId(int kelasId) {
this.kelasId = kelasId;
}
public int getMahasiswaId() {
return mahasiswaId;
}
public void setMahasiswaId(int mahasiswaId) {
this.mahasiswaId = mahasiswaId;
}
public List<KelasModel> getListKelas() {
return listKelas;
}
public void setListKelas(List<KelasModel> listKelas) {
this.listKelas = listKelas;
}
public List<MahasiswaModel> getListMhs() {
return listMhs;
}
public void setListMhs(List<MahasiswaModel> listMhs) {
this.listMhs = listMhs;
}
public int getBobot() {
return bobot;
}
public void setBobot(int bobot) {
this.bobot = bobot;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
|
package com.xianzaishi.wms.tmscore.dto;
import com.xianzaishi.wms.tmscore.vo.PickingWallPositionStatuDO;
public class PickingWallPositionStatuDTO extends PickingWallPositionStatuDO {
} |
package com.sdz.base;
import java.util.Scanner;
public class Entrees
{
@SuppressWarnings({ "resource", "unused" })
public static void main(String[] args)
{
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// lien de l'exercice "https://openclassrooms.com/fr/courses/26832-apprenez-a-programmer-en-java/20615-apprenez-a-lire-les-entrees-clavier"
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/*
* Importation de la class java.util.scanner
* Création d'un objet Scanner, Création d'une variable String afin de récupérer l'entrée précédente
* affichage de la variable String avec System.out.println
* */
Scanner sc1 = new Scanner(System.in);
System.out.println("Veuillez saisir un mot : ");
String str = sc1.nextLine();
System.out.println("Vous avez saisi : "+str);
/*
* Création d'un objet Scanner, Création d'une variable int afin de récupérer l'entrée précédente
* affichage de la variable int avec System.out.println
* */
Scanner sc2 = new Scanner(System.in);
System.out.println("Veuillez saisir un entier : ");
int nbr1 = sc2.nextInt();
System.out.println("Vous avez saisi le nombre : "+nbr1);
/*
* Création d'un objet Scanner, Création d'une variable double
* récupération en int de l'entrée précédente et cast en double
* affichage de la variable double avec System.out.println
* */
Scanner sc3 = new Scanner(System.in);
System.out.println("Veuillez saisir un entier : ");
double nbr2 = (double)sc3.nextInt();
System.out.println("Vous avez saisi : "+nbr2);
/*
* Création d'un objet Scanner, Création d'une variable String, int et double
* Récupération en cascade de chacune des valeurs
* affichage des variables String, int, double avec System.out.println
* */
Scanner sc4 = new Scanner(System.in);
System.out.println("Entré un mot : ");
String mot = sc4.nextLine();
System.out.println("Entré un int : ");
int valueInt = sc4.nextInt();
System.out.println("Entré un double : ");
double valueDouble = sc4.nextDouble();
System.out.println("Vous avez entrée les infos suivantes : "+mot+" - "+valueInt+" - "+valueDouble);
/*
* Création d'un objet Scanner, Création d'une variable String et d'une variable char
* Affectation de l'entrée dans la variable String
* Affectation du premier caractère de la valeur String dans la variable char
* Affichage du caractère avec System.out.println
* */
System.out.println("Saisissez une lettre :");
Scanner sc = new Scanner(System.in);
String mot2 = sc.nextLine();
char carac = mot2.charAt(0);
System.out.println("Vous avez saisi le caractère : " + carac);
/*
*
* */
Scanner scan = new Scanner(System.in);
System.out.println("Saisissez un entier : ");
int int1 = scan.nextInt();
System.out.println("Saisissez une chaîne : ");
//l'entrée ne sera pas demandé et affichera direct "FIN ! "
String mot3 = scan.nextLine();
System.out.println("FIN ! ");
Scanner scan2 = new Scanner(System.in);
System.out.println("Saisissez un entier : ");
int int2 = scan2.nextInt();
System.out.println("Saisissez une chaîne : ");
//On vide la ligne avant d'en lire une autre
scan2.nextLine();
String mot4 = scan2.nextLine();
System.out.println("Vous avez écris => '"+mot4+"'");
System.out.println("FIN ! ");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.