text
stringlengths 10
2.72M
|
|---|
/*
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.gs.tablasco.verify;
import com.gs.tablasco.TableTestUtils;
import com.gs.tablasco.VerifiableTable;
import com.gs.tablasco.verify.indexmap.IndexMapTableVerifier;
import org.junit.*;
import org.junit.rules.TestName;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class MultiTableVerifierTest
{
private static final CellComparator CELL_COMPARATOR = new ToleranceCellComparator(new CellFormatter(1.0, false));
@Rule
public final TestName testName = new TestName();
private MultiTableVerifier verifier;
private File resultsFile;
private int expectedTables;
@Before
public void setUp()
{
this.resultsFile = new File(TableTestUtils.getOutputDirectory(), MultiTableVerifierTest.class.getSimpleName() + '_' + this.testName.getMethodName() + ".html");
this.resultsFile.delete();
ColumnComparators columnComparators = new ColumnComparators.Builder().build();
this.verifier = new MultiTableVerifier(new IndexMapTableVerifier(columnComparators, true, IndexMapTableVerifier.DEFAULT_BEST_MATCH_THRESHOLD, false, false));
}
@After
public void tearDown() throws IOException, SAXException, NoSuchMethodException
{
Class<? extends Throwable> expected = this.getClass().getMethod(this.testName.getMethodName()).getAnnotation(Test.class).expected();
if (Test.None.class.equals(expected))
{
Assert.assertTrue(this.resultsFile.exists());
Document html = TableTestUtils.parseHtml(this.resultsFile);
Assert.assertEquals(this.expectedTables, html.getElementsByTagName("table").getLength());
}
}
@Test
public void missingTable()
{
Map<String, ResultTable> results = verifyTables(createTables("assets"), createTables("assets", "liabs"));
Assert.assertEquals(newPassTable(), results.get("assets").getVerifiedRows());
Assert.assertEquals(newMissingTable(), results.get("liabs").getVerifiedRows());
this.expectedTables = 2;
}
@Test
public void surplusTable()
{
Map<String, ResultTable> results = this.verifyTables(createTables("assets", "liabs"), createTables("liabs"));
Assert.assertEquals(newSurplusTable(), results.get("assets").getVerifiedRows());
Assert.assertEquals(newPassTable(), results.get("liabs").getVerifiedRows());
this.expectedTables = 2;
}
@Test
public void misnamedTable()
{
Map<String, ResultTable> results = this.verifyTables(createTables("assets", "liabs"), createTables("assets", "liabz"));
Assert.assertEquals(newPassTable(), results.get("assets").getVerifiedRows());
Assert.assertEquals(newSurplusTable(), results.get("liabs").getVerifiedRows());
Assert.assertEquals(newMissingTable(), results.get("liabz").getVerifiedRows());
this.expectedTables = 3;
}
@Test(expected = IllegalStateException.class)
public void noExpectedColumns()
{
this.verifyTables(
Collections.singletonMap("table", TableTestUtils.createTable(1, "Col")),
Collections.singletonMap("table", TableTestUtils.createTable(0)));
}
@Test(expected = IllegalStateException.class)
public void noActualColumns()
{
this.verifyTables(
Collections.singletonMap("table", TableTestUtils.createTable(0)),
Collections.singletonMap("table", TableTestUtils.createTable(1, "Col")));
}
private Map<String, ResultTable> verifyTables(Map<String, VerifiableTable> actualResults, Map<String, VerifiableTable> expectedResults)
{
Map<String, ResultTable> results = this.verifier.verifyTables(expectedResults, actualResults);
HtmlFormatter htmlFormatter = new HtmlFormatter(this.resultsFile, new HtmlOptions(false, HtmlFormatter.DEFAULT_ROW_LIMIT, false, false, false, Collections.emptySet()));
htmlFormatter.appendResults(this.testName.getMethodName(), results, null);
return results;
}
private List<List<ResultCell>> newMissingTable()
{
return Arrays.asList(
Collections.singletonList(ResultCell.createMissingCell(CELL_COMPARATOR.getFormatter(), "Heading")),
Collections.singletonList(ResultCell.createMissingCell(CELL_COMPARATOR.getFormatter(), "Value")));
}
private List<List<ResultCell>> newSurplusTable()
{
return Arrays.asList(
Collections.singletonList(ResultCell.createSurplusCell(CELL_COMPARATOR.getFormatter(), "Heading")),
Collections.singletonList(ResultCell.createSurplusCell(CELL_COMPARATOR.getFormatter(), "Value")));
}
private static List<List<ResultCell>> newPassTable()
{
return Arrays.asList(
Collections.singletonList(ResultCell.createMatchedCell(CELL_COMPARATOR, "Heading", "Heading")),
Collections.singletonList(ResultCell.createMatchedCell(CELL_COMPARATOR, "Value", "Value")));
}
private static Map<String, VerifiableTable> createTables(String... names)
{
Map<String, VerifiableTable> tables = new HashMap<>();
for (String name : names)
{
tables.put(name, new VerifiableTable()
{
@Override
public int getRowCount()
{
return 1;
}
@Override
public int getColumnCount()
{
return 1;
}
@Override
public String getColumnName(int columnIndex)
{
return "Heading";
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
return "Value";
}
});
}
return tables;
}
}
|
package consumer;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.*;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.domain.FIPAException;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.TypeVariable;
import java.util.*;
import graphics.utility;
import graphics.volume;
import org.jfree.ui.RefineryUtilities;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import xml.AgentName;
import xml.FileManager;
import xml.XMLReader;
public class Consumer extends Agent {
private int phase;
private FileManager file_manager;
private ArrayList<String> objectives_list;
private ArrayList<String> agenda_items;
private HashMap<String, ArrayList<String>> beliefs_about_others;
private ArrayList<String> beliefs_about_myagent;
public ArrayList<double[]> received_history;
public ArrayList<String> Buyers;
protected final ArrayList<Double> utilities = new ArrayList<>();
public double[][] volumes;
public double calculatedscore;
private AID system_agent = new AID("Coalition", AID.ISLOCALNAME);
private AID opponent = new AID();
protected boolean prices_received_recently = false;
protected ConsumerGui gui = null;
protected ConsumerInputGui input_gui = new ConsumerInputGui(this);
public final int N_PERIODS = 2;
public int PERIODS, VOLUME, risk, ES;
public String HOURS="1,2,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,1,1";
private XMLReader xmlr;
//Negotiation deadline
private Date deadline;
public String contract, contractduration;
public ArrayList<Double> prices_target, volumes_target, prices_limit;
private ArrayList<Double> volumes_limit, volumes_min;
private ArrayList<String> personal_info;
public String negotiation_strategy;
public int other_prices, DR;;
public double sharing_risk;
private String negotiation_preference, negotiation_riskpreference,
negotiation_contract, negotiation_protocol;
int counteroffer;
@Override
protected void setup() {
// initializations
phase = 0;
objectives_list = new ArrayList<>();
agenda_items = new ArrayList<>();
beliefs_about_others = new HashMap();
beliefs_about_myagent = new ArrayList<>();
received_history = new ArrayList<>();
Buyers = new ArrayList<>();
volumes = null;
calculatedscore = 0.0;
PERIODS = N_PERIODS;
VOLUME = 0;
risk = 0;
ES = 0;
deadline = new Date(System.currentTimeMillis()+86400L * 7000);
other_prices = 0;
sharing_risk = 0.5;
file_manager = new FileManager("Consumers\\" + getLocalName());
xmlr = new XMLReader( this.getAID().getLocalName(), "Consumers");
registerWithDF("Coalition Member", "Energy Consumer");
this.addBehaviour(new MessageManager());
executePhase(0);
}
public FileManager getFileManager() {
return file_manager;
}
void checkCO(){
if(gui.counteroffer == 1){
counteroffer=1;
System.out.println("Entrou");
}
}
public void InitGui() {
gui = new ConsumerGui(this);
}
private void registerWithDF(String ServiceType, String ServiceName){
// YELLOW PAGES REGISTER ***************
DFAgentDescription ADcrpt = new DFAgentDescription();
ADcrpt.setName(getAID());
ServiceDescription SDcrpt = new ServiceDescription();
SDcrpt.setType(ServiceType);
SDcrpt.setName(ServiceName);
//SDcrpt.addOntologies("Coordination Ontology");
//SDcrpt.addOntologies("Negotiation Ontology");
ADcrpt.addServices(SDcrpt);
try{
DFService.register(this, ADcrpt);
} catch(FIPAException e){}
}
public boolean isPricesReceivedRecently() {
return prices_received_recently;
}
public void setPricesReceivedRecently(boolean prices_asked) {
this.prices_received_recently = prices_asked;
}
public void updateBelifsFile() {
file_manager.printXmlBelief(getLocalName(), getLocalName(), getBelifsAboutMyAgent());
Object[] keys = getBelifsAboutOthers().keySet().toArray();
for (int i = 0; i < keys.length; i++) {
file_manager.printXmlBelief(getLocalName(), keys[i].toString(), getBelifsAboutOthers().get(keys[i]));
}
}
public HashMap<String, ArrayList<String>> getBelifsAboutOthers() {
return this.beliefs_about_others;
}
public ArrayList<String> getBelifsAboutMyAgent() {
return this.beliefs_about_myagent;
}
public AID getOpponent() {
return this.opponent;
}
public void setOpponent(AID opponent) {
this.opponent = opponent;
}
public int getPhase() {
return phase;
}
public ArrayList<String> getAgendaItems() {
return agenda_items;
}
public void setAgendaItems(ArrayList<String> agenda_items) {
this.agenda_items = agenda_items;
}
public ArrayList<String> getObjectivesList() {
return objectives_list;
}
public void setObjectivesList(ArrayList<String> objectives_list) {
this.objectives_list = objectives_list;
}
public ConsumerGui getGui() {
return gui;
}
public ConsumerInputGui getInputGui() {
return input_gui;
}
public int checkIfReadyToNegotiate() {
if (this.prices_target != null && this.prices_limit != null && this.negotiation_strategy != null && this.other_prices != 0/*&& this.negotiation_protocol != null && this.deadline != null*/) {
executePhase(3);
return 1;
}
return 0;
}
protected void terminateAgent() {
ACLMessage msg_end = new ACLMessage(ACLMessage.INFORM);
msg_end.setContent("END NEGOTIATION");
msg_end.setConversationId("TERMINATE AGENT ID");
msg_end.setOntology("COALITION");
msg_end.setProtocol("END");
msg_end.setReplyWith(String.valueOf(System.currentTimeMillis()));
msg_end.addReceiver(getOpponent());
// ends the negotiation
send(msg_end);
// doDelete();
gui.dispose();
}
protected void utility(ConsumerGui parent, int choice,String title) {
String[] Name ={"Sent Proposals", "Received Proposals","Calculated Proposals"};
utility demo = null;
if (choice==1){
demo = new utility(title, utilities, 2, "Time", "Buyer's Utility", Name, choice,1,calculatedscore);
}else{
demo = new utility(title, utilities, 2, "Proposal", "Buyer's Utility", Name, choice,1,calculatedscore);
}
demo.pack();
demo.setLocation(parent.getX()-100, parent.getY()+100);
// RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
protected void volume(ConsumerGui parent, String title) {
volume demo = null;
String[] lines={"Initial Volume","Actual Volume"};
String[] columns=new String[PERIODS];
for(int i=0; i<PERIODS; i++){
columns[i]=""+(i+1);
}
demo = new volume(title, volumes,lines, columns);
demo.pack();
demo.setLocation(parent.getX()-150, parent.getY()+100);
// RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
public int checkIfContract() {
if (this.contract != null) {
return 1;
}
return 0;
}
public void executePhase(int phase) {
this.phase = phase;
switch (phase) {
case 0:
//Ask personal info to send to market agent
if(Buyers.size()==0){
input_gui.askPersonalInfo();
Buyers.add(getLocalName());
}
for(int i=0;i<Buyers.size();i++){
if(getLocalName().equals(Buyers.get(i))){
i=Buyers.size();
}else{
input_gui.askPersonalInfo();
Buyers.add(getLocalName());
}
}
addBehaviour(new helloAndGetOpponent());
break;
//Read objectives, plan creation and interpretarion
case 1:
//read belifs about opponent in file: Agent Data\%opponent-name%\beliefs_%opponent-name%.xml
readBeliefs(getOpponent().getLocalName());
readBeliefs(getLocalName());
//initiate GUI
InitGui();
//Enable necessary buttons;
gui.guiEnableButtons(1);
String searchPartialBelief = searchPartialBelief(getOpponent().getLocalName(), "prices");
if (!"-1".equals(searchPartialBelief(getOpponent().getLocalName(), "prices"))) {
phase = 2;
gui.updateLog2("Awaiting seller price information", Color.BLUE);
}
break;
case 3:
gui.guiEnableButtons(2);
break;
case 4:
//Initiates negotiation
//ConsumerMarketAgent market_buyer = new ConsumerMarketAgent(this, input_gui);
ConsumerMarketAgent market_buyer = new ConsumerMarketAgent(this);
market_buyer.purchase("", ArrayListToArray(prices_target), ArrayListToArray(prices_limit),
ArrayListToArray(volumes_target), ArrayListToArray(volumes_limit), ArrayListToArray(volumes_min),
negotiation_strategy,negotiation_preference,negotiation_riskpreference, DR, deadline, contract, ArrayListToArray(volumes_target),Double.parseDouble(contractduration),
ArrayListToArray(transformOpponentBeliefToPrice(getOpponent().getLocalName())));
break;
}
}
public void askUserProfile() {
// Asks user for the profile values and adds a profile value to it's beliefs
String profile = getInputGui().askUserProfile(gui);
addBelif("myagent", getLocalName() + ";" + "profile;" + profile);
}
private void readBeliefs(String name) {
ArrayList<String> beliefs = file_manager.readBeliefsFile(name);
for (int i = 1; i < beliefs.size(); i++) {
addBelif(beliefs.get(0), beliefs.get(i));
}
}
public ArrayList<String> transformOpponentBeliefToPriceString(String name) {
// Creates an array containing the opponented prices, based on the agent's own belief
if (getBelifsAboutOthers().containsKey(name)) {
ArrayList<String> prices = new ArrayList<>();
String belief = searchBelief(name, "prices");
if (belief != null) {
String[] content_split = belief.split(";");
String[] content_split_2 = content_split[2].split("-");
for (int j = 0; j < content_split_2.length; j++) {
prices.add(content_split_2[j].split("_")[0]);
prices.add(content_split_2[j].split("_")[1]);
}
}
return prices;
}
return null;
}
public ArrayList<Double> transformOpponentBeliefToPrice(String name) {
if (getBelifsAboutOthers().containsKey(name)) {
ArrayList<Double> prices = new ArrayList<>();
String belief = searchBelief(name, "prices");
if (belief != null) {
String[] content_split = belief.split(";");
String[] content_split_2 = content_split[2].split("-");
for (int j = 0; j < content_split_2.length; j++) {
prices.add(Double.valueOf(content_split_2[j].split("_")[1]));
}
}
return prices;
}
return null;
}
public ArrayList<Double> transformMyBeliefToVolume() {
if (searchBelief("myagent", "volumes") != null) {
ArrayList<Double> volumes = new ArrayList<>();
String belief = searchBelief("myagent", "volumes");
if (belief != null) {
String[] content_split = belief.split(";");
String[] content_split_2 = content_split[2].split("-");
for (int j = 0; j < content_split_2.length; j++) {
volumes.add(Double.valueOf(content_split_2[j].split("_")[1]));
}
}
return volumes;
}
return null;
}
public ArrayList<Double> transformMyBeliefToContract() {
if (searchBelief("myagent", "volumes") != null) {
ArrayList<Double> contract = new ArrayList<>();
String belief = searchBelief("myagent", "contract");
if (belief != null) {
String[] content_split = belief.split(";");
String[] content_split_2 = content_split[2].split("-");
for (int j = 0; j < content_split_2.length; j++) {
contract.add(Double.valueOf(content_split_2[j].split("_")[1]));
}
}
return contract;
}
return null;
}
public String transformPrimitiveValuesToString(ArrayList<String> values) {
String s = "";
for (int i = 0; i < values.size() - 2; i = i + 2) {
s = s + values.get(i) + "-" + values.get(i + 1) + "-";
}
s = s + values.get(values.size() - 2) + "-" + values.get(values.size() - 1);
return s;
}
protected void addBelif(String name, String belief) {
// While adding a belief, if one already exists witht he same description, the new one replaces it
if (name.equals("myagent") || name.equals(getLocalName())) {
if (searchBelief(getLocalName(), belief.split(";")[1]) != null) {
removePartialBelief(getLocalName(), belief.split(";")[1]);
}
getBelifsAboutMyAgent().add(belief);
} else if (getBelifsAboutOthers().containsKey(name)) {
if (searchBelief(name, belief.split(";")[1]) != null) {
removePartialBelief(name, belief.split(";")[1]);
}
ArrayList<String> list = getBelifsAboutOthers().get(name);
list.add(belief);
getBelifsAboutOthers().put(name, list);
} else {
ArrayList<String> list = new ArrayList<>();
list.add(belief);
getBelifsAboutOthers().put(name, list);
}
}
private boolean beliefExists(String name, String belief) {
//checks if the belief is owned by the agent (must be completly equal, not just the description)
if (name.equals("myagent") || name.equals(getLocalName())) {
for (int i = 0; i < getBelifsAboutMyAgent().size(); i++) {
if (getBelifsAboutMyAgent().get(i).equals(belief)) {
return true;
}
}
} else if (getBelifsAboutOthers().containsKey(name)) {
for (int i = 0; i < getBelifsAboutOthers().get(name).size(); i++) {
if (getBelifsAboutOthers().get(name).get(i).equals(belief)) {
return true;
}
}
}
return false;
}
protected String searchPartialBelief(String name, String belief) {
// Checks if any belifs currently owned by the agent contains the segment in part_belif, if so returns it
if ((name.equals("myagent") || name.equals(getLocalName())) && !getBelifsAboutMyAgent().isEmpty()) {
for (int i = 0; i < getBelifsAboutMyAgent().size(); i++) {
if (getBelifsAboutMyAgent().get(i).contains(belief)) {
return getBelifsAboutMyAgent().get(i);
}
}
} else if (getBelifsAboutOthers().containsKey(name)) {
for (int i = 0; i < getBelifsAboutOthers().get(name).size(); i++) {
if (getBelifsAboutOthers().get(name).get(i).contains(belief)) {
return getBelifsAboutOthers().get(name).get(i);
}
}
}
return "-1";
}
protected String searchBelief(String name, String belief_header) {
// Checks if the belief is owned by the agent (must be completly equal) and returns it
if ((name.equals("myagent") || name.equals(getLocalName())) && !getBelifsAboutMyAgent().isEmpty()) {
for (int i = 0; i < getBelifsAboutMyAgent().size(); i++) {
if (getBelifsAboutMyAgent().get(i).split(";")[1].equals(belief_header)) {
return getBelifsAboutMyAgent().get(i);
}
}
} else if (getBelifsAboutOthers().containsKey(name)) {
for (int i = 0; i < getBelifsAboutOthers().get(name).size(); i++) {
if (getBelifsAboutOthers().get(name).get(i).split(";")[1].equals(belief_header)) {
return getBelifsAboutOthers().get(name).get(i);
}
}
}
return null;
}
private void removeBelief(String name, String belief) {
// Removes the exact belief received in the string
if (name.equals("myagent") || name.equals(getLocalName())) {
for (int i = 0; i < getBelifsAboutMyAgent().size(); i++) {
if (getBelifsAboutMyAgent().get(i).equals(belief)) {
getBelifsAboutMyAgent().remove(i);
}
}
} else if (getBelifsAboutOthers().containsKey(name)) {
for (int i = 0; i < getBelifsAboutOthers().get(name).size(); i++) {
if (getBelifsAboutOthers().get(name).get(i).equals(belief)) {
getBelifsAboutOthers().get(name).remove(i);
if (getBelifsAboutOthers().get(name).isEmpty()) {
getBelifsAboutOthers().remove(name);
return;
}
}
}
}
}
private void removePartialBelief(String name, String belief) {
// Removes a belief that partially contain the received belief
if (name.equals("myagent") || name.equals(getLocalName())) {
for (int i = 0; i < getBelifsAboutMyAgent().size(); i++) {
if (getBelifsAboutMyAgent().get(i).contains(belief)) {
getBelifsAboutMyAgent().remove(i);
}
}
} else if (getBelifsAboutOthers().containsKey(name)) {
for (int i = 0; i < getBelifsAboutOthers().get(name).size(); i++) {
if (getBelifsAboutOthers().get(name).get(i).contains(belief)) {
getBelifsAboutOthers().get(name).remove(i);
}
}
}
}
public double[] ArrayListToArray(ArrayList<Double> array_list) {
double[] array = new double[this.PERIODS];
for (int i = 0; i < this.PERIODS; i++) {
array[i] = array_list.get(i);
}
return array;
}
public void setPricesTarget(ArrayList<Double> price_target_final) {
this.prices_target = price_target_final;
}
public void setContractDuration(String contract_target_final) {
this.contractduration = contract_target_final;
}
public void setVolumesTarget(ArrayList<Double> volume_target_final) {
this.volumes_target = volume_target_final;
}
public void setPricesLimit(ArrayList<Double> price_limit_final) {
this.prices_limit = price_limit_final;
}
public void setVolumesLimit(ArrayList<Double> volume_limit_final) {
this.volumes_limit = volume_limit_final;
}
public void setVolumesMin(ArrayList<Double> volume_min_final) {
this.volumes_min = volume_min_final;
}
public void setNegotiationProtocol(String protocol) {
this.negotiation_protocol = protocol;
}
public void setNegotiationStrategy(String strategy) {
this.negotiation_strategy = strategy;
}
public void setDemandResponse(int DR) {
this.DR = DR;
}
public void setNegotiationContract(String contract) {
this.negotiation_contract = contract;
}
public void setNegotiationPreference(String preference) {
this.negotiation_preference = preference;
}
public void setNegotiationRiskPreference(String preference) {
this.negotiation_riskpreference = preference;
}
protected void defineDeadline() {
// addBehaviour(new deadlineDefinitionProtocol(null));
}
// protected void defineContract() {
// addBehaviour(new Buyer.contractDefinitionProtocol(null));
// }
protected void setPersonalInfo(ArrayList<String> personal_info) {
this.personal_info = personal_info;
}
void sendProfile() {
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.setOntology("COALITION");
msg.setProtocol("INFORM");
msg.setConversationId("PROFILE ID");
String content = searchBelief("myagent", "profile");
msg.addReceiver(getOpponent());
msg.setContent(content);
send(msg);
// printMessage(msg, false, "Sending profile");
}
class MessageManager extends CyclicBehaviour {
//MessageTemplate mt_ontology = MessageTemplate.and(MessageTemplate.MatchOntology("market_ontology"), MessageTemplate.MatchProtocol("no_protocol"));
private MessageTemplate Ontology = MessageTemplate.MatchOntology("COALITION");
private MessageTemplate Protocol = MessageTemplate.MatchProtocol("PRE_NEGOTIATION");
MessageTemplate mt_ontology = MessageTemplate.and(Ontology, Protocol);
@Override
public void action() {
ACLMessage msg = myAgent.receive(mt_ontology);
if (msg != null) {
if (msg.getContent().contains("prices;")) {
addBelif(msg.getContent().split(";")[0], msg.getContent());
setPricesReceivedRecently(true);
gui.updateLog2("Prices received from Coalition...", Color.BLUE);
other_prices = 1;
if (phase == 2) {
phase = 3;
}
} else if (msg.getContent().equals("INITIATE DEADLINE DEFINITION")) {
addBehaviour(new deadlineDefinitionProtocol(msg));
} else if (msg.getConversationId().equals("CONFIG")){
//loadAgentConfig();
} else if (msg.getContent().equals("init_contract_definition_protocol")) {
addBehaviour(new contractDefinitionProtocol(msg));
} else if (msg.getContent().equals("end_negotiation")) {
input_gui.finish(gui,"");
gui.setVisible(false);
}
} else {block();}
}
/*public void action() {
ACLMessage msg = myAgent.receive(mt_ontology);
if (msg != null) {
if (msg.getContent().contains("prices;")) {
addBelif(msg.getContent().split(";")[0], msg.getContent());
setPricesReceivedRecently(true);
gui.updateLog2("Prices received from seller", Color.BLUE);
other_prices=1;
checkIfReadyToNegotiate();
// if (phase == 2) {
// phase = 3;
// }
} else if (msg.getContent().equals("init_deadline_definition_protocol")) {
addBehaviour(new deadlineDefinitionProtocol(msg));
}
else if (msg.getContent().equals("init_contract_definition_protocol")) {
addBehaviour(new contractDefinitionProtocol(msg));
} else if (msg.getContent().equals("end_negotiation")) {
input_gui.finish(gui,"");
// doDelete();
gui.setVisible(false);
}
} else {
block();
}*/
//}
}
private class helloAndGetOpponent extends Behaviour {
//private MessageTemplate mt = MessageTemplate.and(MessageTemplate.and(MessageTemplate.MatchOntology("market_ontology"), MessageTemplate.MatchProtocol("hello_protocol")), MessageTemplate.MatchPerformative(ACLMessage.PROPOSE));
//private int step = 0;
private MessageTemplate Ontology = MessageTemplate.MatchOntology("COALITION");
private MessageTemplate Protocol = MessageTemplate.MatchProtocol("HELLO");
private MessageTemplate Performative = MessageTemplate.MatchPerformative(ACLMessage.PROPOSE);
private MessageTemplate mt = MessageTemplate.and(MessageTemplate.and(Ontology, Protocol), Performative);
private int step = 0;
@Override
public void action() {
switch (step) {
case 0:
ACLMessage msg_exist = new ACLMessage(ACLMessage.INFORM);
String agent_info = ";name_" + personal_info.get(0) + ";address_" + personal_info.get(1) + ";telephone_" + personal_info.get(2) + ";fax_" + personal_info.get(3) + ";email_" + personal_info.get(4) + ";";
msg_exist.setContent(getLocalName() + ";is_buyer" + agent_info);
msg_exist.setOntology("COALITION");
msg_exist.setProtocol("CONTACT");
msg_exist.addReceiver(system_agent);
send(msg_exist);
ACLMessage msg_cfp_seller = new ACLMessage(ACLMessage.CFP);
msg_cfp_seller.setContent("PROPOSE OPONENT");
msg_cfp_seller.setOntology("COALITION");
msg_cfp_seller.setProtocol("CONTACT");
addBelif("myagent", getLocalName() + ";waiting_for_coalition");
msg_cfp_seller.addReceiver(system_agent);
send(msg_cfp_seller);
//mt = MessageTemplate.and(MessageTemplate.and(MessageTemplate.MatchOntology("market_ontology"), MessageTemplate.MatchProtocol("hello_protocol")), MessageTemplate.MatchPerformative(ACLMessage.PROPOSE));
mt = MessageTemplate.and(MessageTemplate.and(Ontology, Protocol), Performative);
step = 1;
block();
break;
case 1:
ACLMessage msg = myAgent.receive(mt);
if (msg != null) {
if (beliefExists("myagent", getLocalName() + ";waiting_for_coalition")) {
removeBelief("myagent", getLocalName() + ";waiting_for_coalition");
String[] content_information = msg.getContent().split(";");
setOpponent(new AID(content_information[0], AID.ISLOCALNAME));
step = 2;
}
} else {block();}
/* ACLMessage msg = myAgent.receive(mt);
if (msg != null) {
if (msg != null) {
if (beliefExists("myagent", getLocalName() + ";waiting_for_opponent")) {
removeBelief("myagent", getLocalName() + ";waiting_for_opponent");
String[] content_information = msg.getContent().split(";");
setOpponent(new AID(content_information[0], AID.ISLOCALNAME));
step = 2;
}
} else {
block();
}
} else {
block();
}/**/
case 2:
mt = MessageTemplate.and(MessageTemplate.and(MessageTemplate.MatchOntology("contract_ontology"), MessageTemplate.MatchProtocol("hello_protocol")), MessageTemplate.MatchPerformative(ACLMessage.PROPOSE));
msg = myAgent.receive(mt);
if (msg != null) {
if (msg.getOntology().equals("contract_ontology")) {
setNegotiationContract(msg.getContent());
step=3;
}
} else {block();}
case 3:
mt = MessageTemplate.and(MessageTemplate.and(MessageTemplate.MatchOntology("day_ontology"), MessageTemplate.MatchProtocol("hello_protocol")), MessageTemplate.MatchPerformative(ACLMessage.PROPOSE));
msg = myAgent.receive(mt);
if (msg != null) {
if (msg.getOntology().equals("day_ontology")) {
setContractDuration(msg.getContent());
step=4;
}
} else { block(); }
case 4:
mt = MessageTemplate.and(MessageTemplate.and(MessageTemplate.MatchOntology("inf_ontology"), MessageTemplate.MatchProtocol("hello_protocol")), MessageTemplate.MatchPerformative(ACLMessage.PROPOSE));
msg = myAgent.receive(mt);
if (msg != null) {
if (msg.getOntology().equals("inf_ontology")) {
PERIODS = Integer.parseInt(msg.getContent());
volumes=new double[2][PERIODS];
if(PERIODS==N_PERIODS){
step = 6;
}else{
step=5;
}
}
} else { block(); }
case 5:
mt = MessageTemplate.and(MessageTemplate.and(MessageTemplate.MatchOntology("hour_ontology"), MessageTemplate.MatchProtocol("hello_protocol")), MessageTemplate.MatchPerformative(ACLMessage.PROPOSE));
msg = myAgent.receive(mt);
if (msg != null) {
if (msg.getOntology().equals("hour_ontology")) {
HOURS = msg.getContent();
step = 6;
}
}else { block();}
case 6:
mt = MessageTemplate.and(MessageTemplate.and(MessageTemplate.MatchOntology("volume_ontology"), MessageTemplate.MatchProtocol("hello_protocol")), MessageTemplate.MatchPerformative(ACLMessage.PROPOSE));
msg = myAgent.receive(mt);
if (msg != null) {
if (msg.getOntology().equals("volume_ontology")) {
VOLUME = Integer.parseInt(msg.getContent());
step = 7;
}
} else { block(); }
case 7:
mt = MessageTemplate.and(MessageTemplate.and(MessageTemplate.MatchOntology("risk_ontology"), MessageTemplate.MatchProtocol("hello_protocol")), MessageTemplate.MatchPerformative(ACLMessage.PROPOSE));
msg = myAgent.receive(mt);
if (msg != null) {
if (msg.getOntology().equals("risk_ontology")) {
risk = Integer.parseInt(msg.getContent());
step = 8;
}
} else { block(); }
// case 8:
// mt = MessageTemplate.and(MessageTemplate.and(MessageTemplate.MatchOntology("ES_ontology"), MessageTemplate.MatchProtocol("hello_protocol")), MessageTemplate.MatchPerformative(ACLMessage.PROPOSE));
// msg = myAgent.receive(mt);
// if (msg != null) {
// if (msg != null) {
// if (msg.getOntology().equals("ES_ontology")) {
//
// ES = Integer.parseInt(msg.getContent());
//
//
// step = 9;
//
// }
// } else {
// block();
// }
//
// } else {
// block();
// }
}
}
@Override
public boolean done() {
if (step == 8) {
executePhase(1);
return true;
} else {
return false;
}
}
}
private class deadlineDefinitionProtocol extends Behaviour {
private int step = 0;
ACLMessage msg = null;
ACLMessage reply = null;
MessageTemplate mt = null;
public deadlineDefinitionProtocol(ACLMessage msg) {
this.msg = msg;
}
@Override
public void action() {
switch (step) {
case 0:
if (msg != null) { // Protocol initiated by opponent
reply = msg.createReply();
reply.setPerformative(ACLMessage.AGREE);
reply.setProtocol("deadline_definition_protocol");
reply.setReplyWith(String.valueOf(System.currentTimeMillis()));
mt = MessageTemplate.and(MessageTemplate.and(
MessageTemplate.MatchOntology("market_ontology"),
MessageTemplate.MatchProtocol("deadline_definition_protocol")), MessageTemplate.MatchInReplyTo(reply.getReplyWith()));
send(reply);
step = 2; //Wait for a propose
block();
break;
} else { //Send a request for protocol init
msg = new ACLMessage(ACLMessage.REQUEST);
msg.setContent("init_deadline_definition_protocol");
msg.setOntology("market_ontology");
msg.setProtocol("no_protocol");
msg.setReplyWith(String.valueOf(System.currentTimeMillis()));
msg.addReceiver(getOpponent());
mt = MessageTemplate.and(MessageTemplate.and(
MessageTemplate.MatchOntology("market_ontology"),
MessageTemplate.MatchProtocol("deadline_definition_protocol")),
MessageTemplate.MatchInReplyTo(msg.getReplyWith()));
send(msg);
step = 1; //Wait for protocol init agree
block();
break;
}
case 1: //Wait for protocol init agree
msg = receive(mt);
if (msg == null) {
block();
break;
}
if (msg.getPerformative() == ACLMessage.AGREE) {
//Send first proposal
String date = getInputGui().askDeadline(gui, null);
System.out.println(" \n date " +date);
if (date == null) {
//Send end protocol inform
reply = msg.createReply();
reply.setPerformative(ACLMessage.INFORM);
reply.setContent("end_deadline_definition_protocol");
send(reply);
step = 3;
break;
}
reply = msg.createReply();
reply.setPerformative(ACLMessage.PROPOSE);
reply.setContent(date);
reply.setReplyWith(String.valueOf(System.currentTimeMillis()));
mt = MessageTemplate.and(MessageTemplate.and(
MessageTemplate.MatchOntology("market_ontology"),
MessageTemplate.MatchProtocol("deadline_definition_protocol")),
MessageTemplate.MatchInReplyTo(reply.getReplyWith()));
send(reply);
step = 2; //Wait for a propose
block();
break;
}
case 2: //Wait for proposal
msg = receive(mt);
if (msg == null) {
block();
break;
}
if (msg.getPerformative() == ACLMessage.PROPOSE) {
String date = getInputGui().askDeadline(gui, msg.getContent());
System.out.println(" \n date " +date);
if (date == null) {
//Send end protocol inform
reply = msg.createReply();
reply.setPerformative(ACLMessage.INFORM);
reply.setContent("end_deadline_definition_protocol");
send(reply);
step = 3;
break;
} else if (date.equals(msg.getContent())) {
// Accept proposal
reply = msg.createReply();
reply.setPerformative(ACLMessage.ACCEPT_PROPOSAL);
reply.setContent(date);
reply.setReplyWith(String.valueOf(System.currentTimeMillis()));
mt = MessageTemplate.and(MessageTemplate.and(
MessageTemplate.MatchOntology("market_ontology"),
MessageTemplate.MatchProtocol("deadline_definition_protocol")),
MessageTemplate.MatchInReplyTo(reply.getReplyWith()));
send(reply);
deadline = new Date(Long.valueOf(msg.getContent()));
checkIfReadyToNegotiate();
block();
break;
// Send propose msg
} else if (date != null) {
// Send proposal
reply = msg.createReply();
reply.setPerformative(ACLMessage.PROPOSE);
reply.setContent(date);
reply.setReplyWith(String.valueOf(System.currentTimeMillis()));
mt = MessageTemplate.and(MessageTemplate.and(
MessageTemplate.MatchOntology("market_ontology"),
MessageTemplate.MatchProtocol("deadline_definition_protocol")),
MessageTemplate.MatchInReplyTo(reply.getReplyWith()));
send(reply);
block();
break;
} else {
// Send end protocol inform
reply = msg.createReply();
reply.setPerformative(ACLMessage.INFORM);
reply.setContent("end_deadline_definition_protocol");
send(reply);
step = 3;
break;
}
} else if (msg.getPerformative() == ACLMessage.ACCEPT_PROPOSAL) {
deadline = new Date(Long.valueOf(msg.getContent()));
checkIfReadyToNegotiate();
// Send end protocol inform
reply = msg.createReply();
reply.setPerformative(ACLMessage.INFORM);
reply.setContent("end_deadline_definition_protocol");
send(reply);
step = 3;
break;
} else if (msg.getPerformative() == ACLMessage.INFORM) {
if (msg.getContent().contains("end_deadline_definition_protocol")) {
step = 3;
break;
}
}
break;
}
}
@Override
public boolean done() {
if (step == 3) {
return true;
}
return false;
}
}
private class contractDefinitionProtocol extends Behaviour {
private int step = 0;
ACLMessage msg = null;
ACLMessage reply = null;
MessageTemplate mt = null;
public contractDefinitionProtocol(ACLMessage msg) {
this.msg = msg;
}
@Override
public void action() {
switch (step) {
case 0:
if (msg != null) { // Protocol initiated by opponent
reply = msg.createReply();
reply.setPerformative(ACLMessage.AGREE);
reply.setProtocol("contract_definition_protocol");
reply.setReplyWith(String.valueOf(System.currentTimeMillis()));
mt = MessageTemplate.and(MessageTemplate.and(
MessageTemplate.MatchOntology("market_ontology"),
MessageTemplate.MatchProtocol("contract_definition_protocol")), MessageTemplate.MatchInReplyTo(reply.getReplyWith()));
send(reply);
step = 2; //Wait for a propose
block();
break;
} else { //Send a request for protocol init
msg = new ACLMessage(ACLMessage.REQUEST);
msg.setContent("init_contract_definition_protocol");
msg.setOntology("market_ontology");
msg.setProtocol("no_protocol");
msg.setReplyWith(String.valueOf(System.currentTimeMillis()));
msg.addReceiver(getOpponent());
mt = MessageTemplate.and(MessageTemplate.and(
MessageTemplate.MatchOntology("market_ontology"),
MessageTemplate.MatchProtocol("contract_definition_protocol")),
MessageTemplate.MatchInReplyTo(msg.getReplyWith()));
send(msg);
step = 1; //Wait for protocol init agree
block();
break;
}
case 1: //Wait for protocol init agree
msg = receive(mt);
if (msg == null) {
block();
break;
}
if (msg.getPerformative() == ACLMessage.AGREE) {
//send first proposal
String contract = getInputGui().askContract(gui, null);
if (contract == null) {
//Send end protocol inform
reply = msg.createReply();
reply.setPerformative(ACLMessage.INFORM);
reply.setContent("end_contract_definition_protocol");
send(reply);
step = 3;
break;
}
reply = msg.createReply();
reply.setPerformative(ACLMessage.PROPOSE);
reply.setContent(contract);
reply.setReplyWith(String.valueOf(System.currentTimeMillis()));
mt = MessageTemplate.and(MessageTemplate.and(
MessageTemplate.MatchOntology("market_ontology"),
MessageTemplate.MatchProtocol("contract_definition_protocol")),
MessageTemplate.MatchInReplyTo(reply.getReplyWith()));
send(reply);
step = 2; //Wait for a propose
block();
break;
}
case 2: //Wait for proposal
msg = receive(mt);
if (msg == null) {
block();
break;
}
if (msg.getPerformative() == ACLMessage.PROPOSE) {
String contract = getInputGui().askContract(gui, msg.getContent());
if (contract == null) {
//Send end protocol inform
reply = msg.createReply();
reply.setPerformative(ACLMessage.INFORM);
reply.setContent("end_contract_definition_protocol");
send(reply);
step = 3;
break;
} else if (contract.equals(msg.getContent())) {
// Accept proposal
reply = msg.createReply();
reply.setPerformative(ACLMessage.ACCEPT_PROPOSAL);
reply.setContent(contract);
reply.setReplyWith(String.valueOf(System.currentTimeMillis()));
mt = MessageTemplate.and(MessageTemplate.and(
MessageTemplate.MatchOntology("market_ontology"),
MessageTemplate.MatchProtocol("contract_definition_protocol")),
MessageTemplate.MatchInReplyTo(reply.getReplyWith()));
send(reply);
contract = msg.getContent();
checkIfReadyToNegotiate();
block();
break;
// Send propose msg
} else if (contract != null) {
// Send proposal
reply = msg.createReply();
reply.setPerformative(ACLMessage.PROPOSE);
reply.setContent(contract);
reply.setReplyWith(String.valueOf(System.currentTimeMillis()));
mt = MessageTemplate.and(MessageTemplate.and(
MessageTemplate.MatchOntology("market_ontology"),
MessageTemplate.MatchProtocol("contract_definition_protocol")),
MessageTemplate.MatchInReplyTo(reply.getReplyWith()));
send(reply);
block();
break;
}
} else if (msg.getPerformative() == ACLMessage.ACCEPT_PROPOSAL) {
contract = msg.getContent();
checkIfReadyToNegotiate();
//Send end protocol inform
reply = msg.createReply();
reply.setPerformative(ACLMessage.INFORM);
reply.setContent("end_contract_definition_protocol");
send(reply);
step = 3;
break;
} else if (msg.getPerformative() == ACLMessage.INFORM) {
if (msg.getContent().contains("end_contract_definition_protocol")) {
step = 3;
break;
}
}
break;
}
}
@Override
public boolean done() {
if (step == 3) {
return true;
}
return false;
}
}
}
|
package com.arthur.bishi.meituan0404;
import java.util.ArrayList;
import java.util.Scanner;
/**
* @title: No4
* @Author ArthurJi
* @Date: 2021/4/4 10:12
* @Version 1.0
*/
public class No4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
int[][] table = new int[n][n];
int[][] ans = new int[n][n];
ArrayList<int[]>[] map = new ArrayList[n * n + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
table[i][j] = scanner.nextInt();
if (map[table[i][j]] == null) {
map[table[i][j]] = new ArrayList<int[]>();
}
map[table[i][j]].add(new int[]{i, j});
}
}
if(map[1] == null) {
System.out.println(-1);
return;
}
for (int i = 2; i <= k; i++) {
if (map[i] == null) {
System.out.println(-1);
return;
}
for (int[] cur : map[i]) {
int min = Integer.MAX_VALUE;
for (int[] pre : map[i - 1]) {
min = Math.min(min, Math.abs(cur[0] - pre[0]) + Math.abs(cur[1] - pre[1]));
}
ans[cur[0]][cur[1]] = min;
}
}
int res = Integer.MAX_VALUE;
for (int[] m : map[k]) {
res = Math.min(ans[m[0]][m[1]], res);
}
System.out.println(res);
}
}
|
/*
* 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 views;
import Common.Email_Send;
import Models.getAllData;
import Models.sensor;
import java.awt.event.ActionEvent;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import service.ServiceInterface;
public class Dashboard extends javax.swing.JFrame {
private static ServiceInterface s1;
public Dashboard() {
initComponents();
try {
GetDataToTable();
} catch (RemoteException ex) {
Logger.getLogger(Dashboard.class.getName()).log(Level.SEVERE, null, ex);
} catch (NotBoundException ex) {
Logger.getLogger(Dashboard.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Sensor ID", "Floor No", "Room No", "CO2 Level", "Smoke Level", "Status"
}
));
jScrollPane1.setViewportView(jTable1);
jButton1.setText("Admin Login");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel1.setText("Dashboard");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51))
.addGroup(layout.createSequentialGroup()
.addGap(143, 143, 143)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 642, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(209, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(51, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(65, 65, 65)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(108, 108, 108))
);
setSize(new java.awt.Dimension(1010, 560));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
AdminLogin login = new AdminLogin();
this.setVisible(false);
login.setVisible(true);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Dashboard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Dashboard().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
List<getAllData> allDatasExists;
private void GetDataToTable() throws RemoteException, NotBoundException {
allDatasExists = new ArrayList<>();
new Thread(new Runnable() {
@Override
public void run() {
try {
Registry reg = LocateRegistry.getRegistry("localhost", 9090);
s1 = (ServiceInterface) reg.lookup("Sensor_server");
while (true) {
List<getAllData> allDatas = s1.allData();
DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
dtm.setRowCount(0);
int i = 0;
for (getAllData data : allDatas) {
Vector v = new Vector();
v.add(data.getSensor());
v.add(data.getFloor());
v.add(data.getRoom());
v.add(data.getCo2_level());
v.add(data.getSmoke_level());
// v.add(sensor.getStatus_val());
// v.add((sensor.getStatus_val().equals("Active")) ? "<html><p style='color:red'>ACTIVE</p></html>" : "<html><p style='color:green'>DEACTIVE</p></html>");
int n=Integer.parseInt(data.getCo2_level());
int m=Integer.parseInt(data.getSmoke_level());
if(n >5 || m>5){
String user_email="akulatheepan@gmail.com";
v.add("<html><p style='color:red'>ACTIVE</p></html>");
new Email_Send().sendEmail("Fire Alarm Activated ", user_email, "Warning!!! The Floor Number: "+data.getFloor()+", The Room Number: " + data.getRoom() + " alarm has been activated. Please call 101 for Fire Emergency Services");
System.out.println("Email sent");
}
else{
v.add("<html><p style='color:green'>NOT ACTIVE</p></html>");
}
dtm.addRow(v);
}
Thread.sleep(15000);
} } catch (Exception e) {
System.out.println(e);
}
}
}).start();
}
}
|
package com.lenovohit.ssm.treat.manager.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.lenovohit.ssm.treat.dao.FrontendRestDao;
import com.lenovohit.ssm.treat.manager.HisAssayManager;
import com.lenovohit.ssm.treat.model.AssayItem;
import com.lenovohit.ssm.treat.model.AssayRecord;
import com.lenovohit.ssm.treat.model.MedicalRecord;
import com.lenovohit.ssm.treat.model.Patient;
public class HisAssayManagerImpl implements HisAssayManager{
@Autowired
private FrontendRestDao frontendRestDao;
@Override
public List<AssayRecord> getAssayRecordPage(Patient patient) {
List<AssayRecord> assayRecord = frontendRestDao.getForList("assay/page", AssayRecord.class);
return assayRecord;
}
@Override
public List<AssayItem> getAssayItem(String id) {
List<AssayItem> assayItem = frontendRestDao.getForList("assay/"+id, AssayItem.class);
return assayItem;
}
@Override
public AssayRecord print(AssayRecord record) {
// TODO Auto-generated method stub
return null;
}
}
|
package es.uji.geotec.activityrecorder;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PermissionsManager {
public static final int REQUEST_CODE = 53;
private List<String> permissionsRequired = Arrays.asList(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
);
private Context context;
private List<String> notGranted;
public PermissionsManager(Context context) {
this.context = context;
this.notGranted = new ArrayList<>();
}
public boolean checkIfPermissionsNeeded() {
notGranted.clear();
for (String permission : permissionsRequired) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
notGranted.add(permission);
}
}
return !notGranted.isEmpty();
}
public void requestPermissions() {
if (notGranted.size() > 0) {
ActivityCompat.requestPermissions((Activity) context, notGranted.toArray(new String[notGranted.size()]), REQUEST_CODE);
}
}
}
|
package q2;
public class A
{
public int foo(int a)
{
bar();
return 0;
}
private void bar()
{
baz(4);
}
public int baz(int a)
{
return a + a;
}
}
|
package com.wonjin.computer.hw4projectwonjin.commonWonjin;
import android.content.Context;
import android.util.Log;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Calendar;
/**
* Created by computer on 2019-02-15.
*/
public class FirebaseBroker extends DatabaseBroker {
String defaultGroup = "제1스터디그룹@@@@제2스터디그룹@@@@제3스터디그룹@@@@제4스터디그룹";
String defaultUser = "root####root####@@@@jmlee####jmlee####제1스터디그룹";
String defaultSettings = "maxContinueBookingSlots:2####maxTotalBookingSlots:4";
// group -----------------------------------------------------------------------
public void setGroupOnDataBrokerListener(Context context, DatabaseBroker.OnDataBrokerListener onDataBrokerListener) {
groupDataBrokerListener = onDataBrokerListener;
DatabaseReference databaseReferenceForGroup = FirebaseDatabase.getInstance().getReference().child(rootPath).child("group");
databaseReferenceForGroup.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
groupDatabaseStr = dataSnapshot.getValue(String.class);
if (groupDatabaseStr == null) {
groupDatabaseStr = defaultGroup;
}
if (groupDataBrokerListener != null) {
groupDataBrokerListener.onChange(groupDatabaseStr);
}
}
@Override
public void onCancelled(DatabaseError error) {
groupDatabaseStr = defaultGroup;
}
});
}
public ArrayList<String> loadGroupDatabase(Context context) {
String[] groupDatabase = groupDatabaseStr.split("@@@@");
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < groupDatabase.length; i++) {
if (groupDatabase[i].length() == 0) continue;
arrayList.add(groupDatabase[i]);
}
return arrayList;
}
public void saveGroupDatabase(Context context, ArrayList<String> groupDatabase) {
groupDatabaseStr = "";
for (int i = 0; i < groupDatabase.size(); i++) {
if (groupDatabase.get(i).length() == 0) continue;
groupDatabaseStr += groupDatabase.get(i);
if (i != groupDatabase.size() - 1) {
groupDatabaseStr += "@@@@";
}
}
DatabaseReference databaseReferenceForGroup = FirebaseDatabase.getInstance().getReference().child(rootPath).child("group");
databaseReferenceForGroup.setValue(groupDatabaseStr);
databaseReferenceForGroup.keepSynced(true);
}
// user -----------------------------------------------------------------------
public void setUserOnDataBrokerListener(Context context, DatabaseBroker.OnDataBrokerListener onDataBrokerListener){
userOnDataBrokerListener = onDataBrokerListener;
DatabaseReference databaseReferenceForGroup = FirebaseDatabase.getInstance().getReference().child(rootPath).child("user");
databaseReferenceForGroup.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("jmlee", "here1"+rootPath);
userDatabaseStr = dataSnapshot.getValue(String.class);
if (userDatabaseStr == null) {
userDatabaseStr = defaultUser;
}
if (userOnDataBrokerListener != null) {
userOnDataBrokerListener.onChange(userDatabaseStr);
}
}
@Override
public void onCancelled(DatabaseError error) {
Log.i("jmlee", "here2");
Log.i("jmlee", error.getMessage());
userDatabaseStr = defaultUser;
}
});
}
public ArrayList<User> loadUserDatabase(Context context){
String[] userDatabase = userDatabaseStr.split("@@@@");
ArrayList<User> arrayList = new ArrayList<>();
for(int i=0;i<userDatabase.length;i++){
if(userDatabase[i].length() == 0) continue;
arrayList.add(new User(userDatabase[i]));
}
return arrayList;
}
public void saveUserDatabase(Context context, ArrayList<User> userDatabase){
userDatabaseStr = "";
for(int i=0;i<userDatabase.size();i++){
userDatabaseStr += userDatabase.get(i).toString();
if(i != userDatabase.size()-1){
userDatabaseStr += "@@@@";
}
}
DatabaseReference databaseReferenceForGroup = FirebaseDatabase.getInstance().getReference().child(rootPath).child("user");
databaseReferenceForGroup.setValue(userDatabaseStr);
databaseReferenceForGroup.keepSynced(true);
}
// booking -----------------------------------------------------------------------
public void setBookingOnDataBrokerListener(Context context, String userGroup, DatabaseBroker.OnDataBrokerListener onDataBrokerListener){
this.userGroup = userGroup;
bookingOnDataBrokerListener = onDataBrokerListener;
DatabaseReference databaseReferenceForBooking = FirebaseDatabase.getInstance().getReference().child(rootPath).child("booking").child(userGroup);
databaseReferenceForBooking.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
bookingDatabaseStr = dataSnapshot.getValue(String.class);
if(bookingDatabaseStr == null){
bookingDatabaseStr = "";
}
if(bookingOnDataBrokerListener != null){
bookingOnDataBrokerListener.onChange(bookingDatabaseStr);
}
}
@Override
public void onCancelled(DatabaseError error) {
bookingDatabaseStr = "";
}
});
}
public String[] loadBookingDatabase(Context context, String userGroup){
String[] bookingDatabase = new String[50];
for(int i=0;i<bookingDatabase.length;i++){
bookingDatabase[i] = "";
}
if(bookingDatabaseStr.length()==0 || userGroup != this.userGroup){
return bookingDatabase;
}
String[] bookings = bookingDatabaseStr.split("@@@@");
for(int i=1;i<bookings.length;i++){
if(bookings[i].length()==0){
continue;
}
String[] info= bookings[i].split(":");
int time = Integer.parseInt(info[0]); // 330: 3시 30분
int index = (time/100)*2+((time%100)/30);
bookingDatabase[index] = info[1];
}
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String dateStr = String.format("%04d-%02d-%02d", year, month, day);
if(!bookings[0].equals(dateStr)) {
bookingDatabase[0] = bookingDatabase[48];
bookingDatabase[1] = bookingDatabase[49];
for(int i=2;i<bookingDatabase.length;i++){
bookingDatabase[i]= "";
}
}
return bookingDatabase;
}
public void saveBookingDatabase(Context context, String userGroup, String[] bookingDatabase){
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String dateStr = String.format("%04d-%02d-%02d", year, month, day);
bookingDatabaseStr = dateStr;
for(int i=0;i<bookingDatabase.length;i++){
if(bookingDatabase[i].length() == 0) continue;
bookingDatabaseStr += "@@@@";
int index = (i/2)*100+(i%2)*30;
bookingDatabaseStr += index + ":" + bookingDatabase[i];
}
this.userGroup = userGroup;
DatabaseReference databaseReferenceForBooking = FirebaseDatabase.getInstance().getReference().child(rootPath).child("booking").child(userGroup);
databaseReferenceForBooking.setValue(bookingDatabaseStr);
databaseReferenceForBooking.keepSynced(true);
}
// settings -----------------------------------------------------------------------
public void setSettingsOnDataBrokerListener(Context context, DatabaseBroker.OnDataBrokerListener onDataBrokerListener){
settingsOnDataBrokerListener = onDataBrokerListener;
DatabaseReference databaseReferenceForGroup = FirebaseDatabase.getInstance().getReference().child(rootPath).child("settings");
databaseReferenceForGroup.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
settingsDatabaseStr = dataSnapshot.getValue(String.class);
if (settingsDatabaseStr == null) {
settingsDatabaseStr = defaultSettings;
}
if (settingsOnDataBrokerListener != null) {
settingsOnDataBrokerListener.onChange(settingsDatabaseStr);
}
}
@Override
public void onCancelled(DatabaseError error) {
settingsDatabaseStr = defaultSettings;
}
});
}
public Settings loadSettingsDatabase(Context context){
Settings settings = new Settings(settingsDatabaseStr);
return settings;
}
public void saveSettingsDatabase(Context context, Settings settingsDatabase){
settingsDatabaseStr = settingsDatabase.toString();
DatabaseReference databaseReferenceForGroup = FirebaseDatabase.getInstance().getReference().child(rootPath).child("settings");
databaseReferenceForGroup.setValue(settingsDatabaseStr);
databaseReferenceForGroup.keepSynced(true);
}
public void setCheckDatabaseRoot(DatabaseBroker.OnDataBrokerListener onDataBrokerListener){
checkOnDataBrokerListener = onDataBrokerListener;
Log.i("jmlee", "here");
DatabaseReference databaseReferenceForGroup = FirebaseDatabase.getInstance().getReference().child("databaseRoot");
databaseReferenceForGroup.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String databaseRootStr = dataSnapshot.getValue(String.class);
String[] databaseRoots = databaseRootStr.split("@@@@");
for (int i = 0; i < databaseRoots.length; i++) {
if (rootPath.equals(databaseRoots[i])) {
if (checkOnDataBrokerListener != null) {
checkOnDataBrokerListener.onChange(databaseRoots[i]);
return;
}
}
}
if (checkOnDataBrokerListener != null) {
checkOnDataBrokerListener.onChange("");
}
}
@Override
public void onCancelled(DatabaseError error) {
if (checkOnDataBrokerListener != null) {
checkOnDataBrokerListener.onChange("");
}
}
});
}
public void resetDatabase(Context context){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child(rootPath);
databaseReference.removeValue();
}
}
|
package thirdparty.javaworld;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.text.*;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.StyleSheet;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.ImageObserver;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Dictionary;
/**
* Big ugly class to load images off the classpath if they're not an absolute URL (starting with http:// etc).
*
* Code originally came from <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip109.html">this JavaWorld article</a> with a few cleanups and modifications.
*
* @see ClasspathHTMLEditorKit
*/
public class ClasspathImageView extends View implements ImageObserver, MouseListener, MouseMotionListener {
// --- Attribute Values ------------------------------------------
public static final String
TOP = "top",
TEXTTOP = "texttop",
MIDDLE = "middle",
ABSMIDDLE = "absmiddle",
CENTER = "center",
BOTTOM = "bottom";
// --- Construction ----------------------------------------------
/**
* Creates a new view that represents an IMG element.
*
* @param elem the element to create a view for
*/
public ClasspathImageView(Element elem) {
super(elem);
initialize(elem);
StyleSheet sheet = getStyleSheet();
attr = sheet.getViewAttributes(this);
}
private void initialize(Element elem) {
synchronized (this) {
loading = true;
fWidth = fHeight = 0;
}
int width = 0;
int height = 0;
boolean customWidth = false;
boolean customHeight = false;
try {
fElement = elem;
// Request image from document's cache:
AttributeSet attr = elem.getAttributes();
if (isURL()) {
URL src = getSourceURL();
if (src != null) {
Dictionary cache = (Dictionary) getDocument().getProperty(IMAGE_CACHE_PROPERTY);
if (cache != null) {
fImage = (Image) cache.get(src);
} else {
fImage = Toolkit.getDefaultToolkit().getImage(src);
}
}
}
else
{
/******** Code to load from relative path *************/
String src = (String) fElement.getAttributes().getAttribute(HTML.Attribute.SRC);
// System.out.println("src = " + src);
// let's just get a URL from the classpath, and feed that to the DefaultToolKit
URL imageUrl = ClasspathImageView.class.getResource(src);
// System.out.println("imageUrl.toExternalForm() = " + imageUrl.toExternalForm());
fImage = Toolkit.getDefaultToolkit().createImage(imageUrl);
// @todo MCB / LG - this seems to lock up idea every so often. Commenting out and images still seem to load.
// try {
// waitForImage();
// }
// catch (InterruptedException e) {
// fImage = null;
// }
/******************************************************/
}
// Get height/width from params or image or defaults:
height = getIntAttr(HTML.Attribute.HEIGHT, -1);
customHeight = (height > 0);
if (!customHeight && fImage != null) {
height = fImage.getHeight(this);
}
if (height <= 0) {
height = DEFAULT_HEIGHT;
}
width = getIntAttr(HTML.Attribute.WIDTH, -1);
customWidth = (width > 0);
if (!customWidth && fImage != null) {
width = fImage.getWidth(this);
}
if (width <= 0) {
width = DEFAULT_WIDTH;
}
// Make sure the image starts loading:
if (fImage != null) {
if (customWidth && customHeight) {
Toolkit.getDefaultToolkit().prepareImage(fImage, height,
width, this);
} else {
Toolkit.getDefaultToolkit().prepareImage(fImage, -1, -1,
this);
}
}
/********************************************************
// Rob took this out. Changed scope of src.
if( DEBUG ) {
if( fImage != null )
System.out.println("ImageInfo: new on "+src+
" ("+fWidth+"x"+fHeight+")");
else
System.out.println("ImageInfo: couldn't get image at "+
src);
if(isLink())
System.out.println(" It's a link! Border = "+
getBorder());
//((AbstractDocument.AbstractElement)elem).dump(System.out,4);
}
********************************************************/
} finally {
synchronized (this) {
loading = false;
if (customWidth || fWidth == 0) {
fWidth = width;
}
if (customHeight || fHeight == 0) {
fHeight = height;
}
}
}
}
/**
* Determines if path is in the form of a URL
*/
private boolean isURL() {
String src =
(String) fElement.getAttributes().getAttribute(HTML.Attribute.SRC);
return src.toLowerCase().startsWith("file") ||
src.toLowerCase().startsWith("http");
}
/** Checks to see if the absolute path is availabe thru an application
global static variable or thru a system variable. If so, appends
the relative path to the absolute path and returns the String. */
// private String processSrcPath(String src) {
// String val = src;
//
// File imageFile = new File(src);
// if (imageFile.isAbsolute()) return src;
//
// //try to get application images path...
// if (ImageTest.ApplicationImagePath != null) {
// String imagePath = ImageTest.ApplicationImagePath;
// val = (new File(imagePath, imageFile.getPath())).toString();
// }
// //try to get system images path...
// else {
// String imagePath = System.getProperty("system.image.path.key");
// if (imagePath != null) {
// val = (new File(imagePath, imageFile.getPath())).toString();
// }
// }
//
// //System.out.println("src before: " + src + ", src after: " + val);
// return val;
// }
/**
* Added this guy to make sure an image is loaded - ie no broken
* images. So far its used only for images loaded off the disk (non-URL).
* It seems to work marvelously. By the way, it does the same thing as
* MediaTracker, but you dont need to know the component its being
* rendered on. Rob
*/
private void waitForImage() throws InterruptedException {
int w = fImage.getWidth(this);
int h = fImage.getHeight(this);
while (true) {
int flags = Toolkit.getDefaultToolkit().checkImage(fImage, w, h, this);
if (((flags & ERROR) != 0) || ((flags & ABORT) != 0)) {
throw new InterruptedException();
} else if ((flags & (ALLBITS | FRAMEBITS)) != 0) {
return;
}
Thread.sleep(10);
//System.out.println("rise and shine...");
}
}
/**
* Fetches the attributes to use when rendering. This is
* implemented to multiplex the attributes specified in the
* model with a StyleSheet.
*/
public AttributeSet getAttributes() {
return attr;
}
/**
* Is this image within a link?
*/
boolean isLink() {
//! It would be nice to cache this but in an editor it can change
// See if I have an HREF attribute courtesy of the enclosing A tag:
AttributeSet anchorAttr = (AttributeSet)
fElement.getAttributes().getAttribute(HTML.Tag.A);
if (anchorAttr != null) {
return anchorAttr.isDefined(HTML.Attribute.HREF);
}
return false;
}
/**
* Returns the size of the border to use.
*/
int getBorder() {
return getIntAttr(HTML.Attribute.BORDER, isLink() ? DEFAULT_BORDER : 0);
}
/**
* Returns the amount of extra space to add along an axis.
*/
int getSpace(int axis) {
return getIntAttr(axis == X_AXIS ? HTML.Attribute.HSPACE : HTML.Attribute.VSPACE,
0);
}
/**
* Returns the border's color, or null if this is not a link.
*/
Color getBorderColor() {
StyledDocument doc = (StyledDocument) getDocument();
return doc.getForeground(getAttributes());
}
/**
* Returns the image's vertical alignment.
*/
float getVerticalAlignment() {
String align = (String) fElement.getAttributes().getAttribute(HTML.Attribute.ALIGN);
if (align != null) {
align = align.toLowerCase();
if (align.equals(TOP) || align.equals(TEXTTOP)) {
return 0.0f;
} else if (align.equals(this.CENTER) || align.equals(MIDDLE)
|| align.equals(ABSMIDDLE)) {
return 0.5f;
}
}
return 1.0f; // default alignment is bottom
}
boolean hasPixels(ImageObserver obs) {
return fImage != null && fImage.getHeight(obs) > 0
&& fImage.getWidth(obs) > 0;
}
/**
* Return a URL for the image source,
* or null if it could not be determined.
*/
private URL getSourceURL() {
String src = (String) fElement.getAttributes().getAttribute(HTML.Attribute.SRC);
if (src == null) {
return null;
}
URL reference = ((HTMLDocument) getDocument()).getBase();
try {
URL u = new URL(reference, src);
return u;
} catch (MalformedURLException e) {
return null;
}
}
/**
* Look up an integer-valued attribute. <b>Not</b> recursive.
*/
private int getIntAttr(HTML.Attribute name, int deflt) {
AttributeSet attr = fElement.getAttributes();
if (attr.isDefined(name)) { // does not check parents!
int i;
String val = (String) attr.getAttribute(name);
if (val == null) {
i = deflt;
} else {
try {
i = Math.max(0, Integer.parseInt(val));
} catch (NumberFormatException x) {
i = deflt;
}
}
return i;
} else {
return deflt;
}
}
/**
* Establishes the parent view for this view.
* Seize this moment to cache the AWT Container I'm in.
*/
public void setParent(View parent) {
super.setParent(parent);
fContainer = parent != null ? getContainer() : null;
if (parent == null && fComponent != null) {
fComponent.getParent().remove(fComponent);
fComponent = null;
}
}
/**
* My attributes may have changed.
*/
public void changedUpdate(DocumentEvent e, Shape a, ViewFactory f) {
if (DEBUG) {
System.out.println("ImageView: changedUpdate begin...");
}
super.changedUpdate(e, a, f);
float align = getVerticalAlignment();
int height = fHeight;
int width = fWidth;
initialize(getElement());
boolean hChanged = fHeight != height;
boolean wChanged = fWidth != width;
if (hChanged || wChanged || getVerticalAlignment() != align) {
if (DEBUG) {
System.out.println("ImageView: calling preferenceChanged");
}
getParent().preferenceChanged(this, hChanged, wChanged);
}
if (DEBUG) {
System.out.println("ImageView: changedUpdate end; valign=" + getVerticalAlignment());
}
}
// --- Painting --------------------------------------------------------
/**
* Paints the image.
*
* @param g the rendering surface to use
* @param a the allocated region to render into
* @see javax.swing.text.View#paint
*/
public void paint(Graphics g, Shape a) {
Color oldColor = g.getColor();
fBounds = a.getBounds();
int border = getBorder();
int x = fBounds.x + border + getSpace(X_AXIS);
int y = fBounds.y + border + getSpace(Y_AXIS);
int width = fWidth;
int height = fHeight;
int sel = getSelectionState();
// Make sure my Component is in the right place:
/*
if( fComponent == null ) {
fComponent = new Component() { };
fComponent.addMouseListener(this);
fComponent.addMouseMotionListener(this);
fComponent.setCursor(Cursor.getDefaultCursor()); // use arrow cursor
fContainer.add(fComponent);
}
fComponent.setBounds(x,y,width,height);
*/
// If no pixels yet, draw gray outline and icon:
if (!hasPixels(this)) {
g.setColor(Color.lightGray);
g.drawRect(x, y, width - 1, height - 1);
g.setColor(oldColor);
loadIcons();
Icon icon = fImage == null ? sMissingImageIcon : sPendingImageIcon;
if (icon != null) {
icon.paintIcon(getContainer(), g, x, y);
}
}
// Draw image:
if (fImage != null) {
g.drawImage(fImage, x, y, width, height, this);
// Use the following instead of g.drawImage when
// BufferedImageGraphics2D.setXORMode is fixed (4158822).
// Use Xor mode when selected/highlighted.
//! Could darken image instead, but it would be more expensive.
/*
if( sel > 0 )
g.setXORMode(Color.white);
g.drawImage(fImage,x, y,
width,height,this);
if( sel > 0 )
g.setPaintMode();
*/
}
// If selected exactly, we need a black border & grow-box:
Color bc = getBorderColor();
if (sel == 2) {
// Make sure there's room for a border:
int delta = 2 - border;
if (delta > 0) {
x += delta;
y += delta;
width -= delta << 1;
height -= delta << 1;
border = 2;
}
bc = null;
g.setColor(Color.black);
// Draw grow box:
g.fillRect(x + width - 5, y + height - 5, 5, 5);
}
// Draw border:
if (border > 0) {
if (bc != null) {
g.setColor(bc);
}
// Draw a thick rectangle:
for (int i = 1; i <= border; i++) {
g.drawRect(x - i, y - i, width - 1 + i + i, height - 1 + i + i);
}
g.setColor(oldColor);
}
}
/**
* Request that this view be repainted.
* Assumes the view is still at its last-drawn location.
*/
protected void repaint(long delay) {
if (fContainer != null && fBounds != null) {
fContainer.repaint(delay,
fBounds.x, fBounds.y, fBounds.width, fBounds.height);
}
}
/**
* Determines whether the image is selected, and if it's the only thing selected.
*
* @return 0 if not selected, 1 if selected, 2 if exclusively selected.
* "Exclusive" selection is only returned when editable.
*/
protected int getSelectionState() {
int p0 = fElement.getStartOffset();
int p1 = fElement.getEndOffset();
if (fContainer instanceof JTextComponent) {
JTextComponent textComp = (JTextComponent) fContainer;
int start = textComp.getSelectionStart();
int end = textComp.getSelectionEnd();
if (start <= p0 && end >= p1) {
if (start == p0 && end == p1 && isEditable()) {
return 2;
} else {
return 1;
}
}
}
return 0;
}
protected boolean isEditable() {
return fContainer instanceof JEditorPane
&& ((JEditorPane) fContainer).isEditable();
}
/**
* Returns the text editor's highlight color.
*/
protected Color getHighlightColor() {
JTextComponent textComp = (JTextComponent) fContainer;
return textComp.getSelectionColor();
}
// --- Progressive display ---------------------------------------------
// This can come on any thread. If we are in the process of reloading
// the image and determining our state (loading == true) we don't fire
// preference changed, or repaint, we just reset the fWidth/fHeight as
// necessary and return. This is ok as we know when loading finishes
// it will pick up the new height/width, if necessary.
public boolean imageUpdate(Image img, int flags, int x, int y,
int width, int height) {
if (fImage == null || fImage != img) {
return false;
}
// Bail out if there was an error:
if ((flags & (ABORT | ERROR)) != 0) {
fImage = null;
repaint(0);
return false;
}
// Resize image if necessary:
short changed = 0;
if ((flags & ImageObserver.HEIGHT) != 0) {
if (!getElement().getAttributes().isDefined(HTML.Attribute.HEIGHT)) {
changed |= 1;
}
}
if ((flags & ImageObserver.WIDTH) != 0) {
if (!getElement().getAttributes().isDefined(HTML.Attribute.WIDTH)) {
changed |= 2;
}
}
synchronized (this) {
if ((changed & 1) == 1) {
fWidth = width;
}
if ((changed & 2) == 2) {
fHeight = height;
}
if (loading) {
// No need to resize or repaint, still in the process of
// loading.
return true;
}
}
if (changed != 0) {
// May need to resize myself, asynchronously:
if (DEBUG) {
System.out.println("ImageView: resized to " + fWidth + "x" + fHeight);
}
Document doc = getDocument();
try {
if (doc instanceof AbstractDocument) {
((AbstractDocument) doc).readLock();
}
preferenceChanged(this, true, true);
} finally {
if (doc instanceof AbstractDocument) {
((AbstractDocument) doc).readUnlock();
}
}
return true;
}
// Repaint when done or when new pixels arrive:
if ((flags & (FRAMEBITS | ALLBITS)) != 0) {
repaint(0);
} else if ((flags & SOMEBITS) != 0) {
if (sIsInc) {
repaint(sIncRate);
}
}
return ((flags & ALLBITS) == 0);
}
/*
/**
* Static properties for incremental drawing.
* Swiped from Component.java
* @see #imageUpdate
*/
private static boolean sIsInc = true;
private static int sIncRate = 100;
// --- Layout ----------------------------------------------------------
/**
* Determines the preferred span for this view along an
* axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @returns the span the view would like to be rendered into.
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view.
*/
public float getPreferredSpan(int axis) {
//if(DEBUG)System.out.println("ImageView: getPreferredSpan");
int extra = 2 * (getBorder() + getSpace(axis));
switch (axis) {
case View.X_AXIS:
return fWidth + extra;
case View.Y_AXIS:
return fHeight + extra;
default:
throw new IllegalArgumentException("Invalid axis: " + axis);
}
}
/**
* Determines the desired alignment for this view along an
* axis. This is implemented to give the alignment to the
* bottom of the icon along the y axis, and the default
* along the x axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @returns the desired alignment. This should be a value
* between 0.0 and 1.0 where 0 indicates alignment at the
* origin and 1.0 indicates alignment to the full span
* away from the origin. An alignment of 0.5 would be the
* center of the view.
*/
public float getAlignment(int axis) {
switch (axis) {
case View.Y_AXIS:
return getVerticalAlignment();
default:
return super.getAlignment(axis);
}
}
/**
* Provides a mapping from the document model coordinate space
* to the coordinate space of the view mapped to it.
*
* @param pos the position to convert
* @param a the allocated region to render into
* @return the bounding box of the given position
* @throws javax.swing.text.BadLocationException
* if the given position does not represent a
* valid location in the associated document
* @see javax.swing.text.View#modelToView
*/
public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
int p0 = getStartOffset();
int p1 = getEndOffset();
if ((pos >= p0) && (pos <= p1)) {
Rectangle r = a.getBounds();
if (pos == p1) {
r.x += r.width;
}
r.width = 0;
return r;
}
return null;
}
/**
* Provides a mapping from the view coordinate space to the logical
* coordinate space of the model.
*
* @param x the X coordinate
* @param y the Y coordinate
* @param a the allocated region to render into
* @return the location within the model that best represents the
* given point of view
* @see javax.swing.text.View#viewToModel
*/
public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) {
Rectangle alloc = (Rectangle) a;
if (x < alloc.x + alloc.width) {
bias[0] = Position.Bias.Forward;
return getStartOffset();
}
bias[0] = Position.Bias.Backward;
return getEndOffset();
}
/**
* Set the size of the view. (Ignored.)
*
* @param width the width
* @param height the height
*/
public void setSize(float width, float height) {
// Ignore this -- image size is determined by the tag attrs and
// the image itself, not the surrounding layout!
}
/**
* Change the size of this image. This alters the HEIGHT and WIDTH
* attributes of the Element and causes a re-layout.
*/
protected void resize(int width, int height) {
if (width == fWidth && height == fHeight) {
return;
}
fWidth = width;
fHeight = height;
// Replace attributes in document:
MutableAttributeSet attr = new SimpleAttributeSet();
attr.addAttribute(HTML.Attribute.WIDTH, Integer.toString(width));
attr.addAttribute(HTML.Attribute.HEIGHT, Integer.toString(height));
((StyledDocument) getDocument()).setCharacterAttributes(
fElement.getStartOffset(),
fElement.getEndOffset(),
attr, false);
}
// --- Mouse event handling --------------------------------------------
/**
* Select or grow image when clicked.
*/
public void mousePressed(MouseEvent e) {
Dimension size = fComponent.getSize();
if (e.getX() >= size.width - 7 && e.getY() >= size.height - 7
&& getSelectionState() == 2) {
// Click in selected grow-box:
if (DEBUG) {
System.out.println("ImageView: grow!!! Size=" + fWidth + "x" + fHeight);
}
Point loc = fComponent.getLocationOnScreen();
fGrowBase = new Point(loc.x + e.getX() - fWidth,
loc.y + e.getY() - fHeight);
fGrowProportionally = e.isShiftDown();
} else {
// Else select image:
fGrowBase = null;
JTextComponent comp = (JTextComponent) fContainer;
int start = fElement.getStartOffset();
int end = fElement.getEndOffset();
int mark = comp.getCaret().getMark();
int dot = comp.getCaret().getDot();
if (e.isShiftDown()) {
// extend selection if shift key down:
if (mark <= start) {
comp.moveCaretPosition(end);
} else {
comp.moveCaretPosition(start);
}
} else {
// just select image, without shift:
if (mark != start) {
comp.setCaretPosition(start);
}
if (dot != end) {
comp.moveCaretPosition(end);
}
}
}
}
/**
* Resize image if initial click was in grow-box:
*/
public void mouseDragged(MouseEvent e) {
if (fGrowBase != null) {
Point loc = fComponent.getLocationOnScreen();
int width = Math.max(2, loc.x + e.getX() - fGrowBase.x);
int height = Math.max(2, loc.y + e.getY() - fGrowBase.y);
if (e.isShiftDown() && fImage != null) {
// Make sure size is proportional to actual image size:
float imgWidth = fImage.getWidth(this);
float imgHeight = fImage.getHeight(this);
if (imgWidth > 0 && imgHeight > 0) {
float prop = imgHeight / imgWidth;
float pwidth = height / prop;
float pheight = width * prop;
if (pwidth > width) {
width = (int) pwidth;
} else {
height = (int) pheight;
}
}
}
resize(width, height);
}
}
public void mouseReleased(MouseEvent e) {
fGrowBase = null;
//! Should post some command to make the action undo-able
}
/**
* On double-click, open image properties dialog.
*/
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
//$ IMPLEMENT
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
// --- Static icon accessors -------------------------------------------
private Icon makeIcon(final String gifFile) throws IOException {
/* Copy resource into a byte array. This is
* necessary because several browsers consider
* Class.getResource a security risk because it
* can be used to load additional classes.
* Class.getResourceAsStream just returns raw
* bytes, which we can convert to an image.
*/
InputStream resource = ClasspathImageView.class.getResourceAsStream(gifFile);
if (resource == null) {
System.err.println(ClasspathImageView.class.getName() + "/" +
gifFile + " not found.");
return null;
}
BufferedInputStream in =
new BufferedInputStream(resource);
ByteArrayOutputStream out =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int n;
while ((n = in.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
in.close();
out.flush();
buffer = out.toByteArray();
if (buffer.length == 0) {
System.err.println("warning: " + gifFile +
" is zero-length");
return null;
}
return new ImageIcon(buffer);
}
private void loadIcons() {
try {
if (sPendingImageIcon == null) {
sPendingImageIcon = makeIcon(PENDING_IMAGE_SRC);
}
if (sMissingImageIcon == null) {
sMissingImageIcon = makeIcon(MISSING_IMAGE_SRC);
}
} catch (Exception x) {
System.err.println("ImageView: Couldn't load image icons");
}
}
protected StyleSheet getStyleSheet() {
HTMLDocument doc = (HTMLDocument) getDocument();
return doc.getStyleSheet();
}
// --- member variables ------------------------------------------------
private AttributeSet attr;
private Element fElement;
private Image fImage;
private int fHeight, fWidth;
private Container fContainer;
private Rectangle fBounds;
private Component fComponent;
private Point fGrowBase; // base of drag while growing image
private boolean fGrowProportionally; // should grow be proportional?
/**
* Set to true, while the receiver is locked, to indicate the reciever
* is loading the image. This is used in imageUpdate.
*/
private boolean loading;
// --- constants and static stuff --------------------------------
private static Icon sPendingImageIcon,
sMissingImageIcon;
private static final String
PENDING_IMAGE_SRC = "/icons/icn_plan_disabled.gif", // both stolen from HotJava
MISSING_IMAGE_SRC = "/icons/icn_plan_failed.gif";
private static final boolean DEBUG = false;
//$ move this someplace public
static final String IMAGE_CACHE_PROPERTY = "imageCache";
// Height/width to use before we know the real size:
private static final int
DEFAULT_WIDTH = 32,
DEFAULT_HEIGHT = 32,
// Default value of BORDER param: //? possibly move into stylesheet?
DEFAULT_BORDER = 2;
}
|
package com.example.repository;
import com.example.domain.Atleta;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDate;
import java.util.List;
/**
* Created by jun on 05/12/2016.
*/
public interface AtletaRepository extends JpaRepository<Atleta, Long>{
List<Atleta> findByNacionalidadContains(String nacionalidad);
List<Atleta> findByFechaNacimientoBefore(LocalDate fechaNacimiento);
List<Atleta> findByNombreIs(String nombre);
}
|
package com.company.resume.Repositories;
import com.company.resume.Models.Job;
import com.company.resume.Models.Organization;
import com.company.resume.Models.Skill;
import org.springframework.data.repository.CrudRepository;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public interface JobRepository extends CrudRepository<Job, Long>{
// HashSet<Job> findAllByJobSkillsContains(HashSet<Skill> skills);
//
// HashSet<Job> findJobByJobSkillsIn(HashSet<Skill> mySkills);
HashSet<Job> findAllByJobOrg(Organization organization);
Iterable<Job> findAllByJobSkillsIn(Set<Skill> skills);
}
|
package com.design.pattern.proxy;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Author: 98050
* @Time: 2019-02-17 22:07
* @Feature:
*/
public class Test {
public static void main(String[] args) {
/**
* 静态代理
*/
UserService userService = new UserServiceImpl();
UserServiceProxy userServiceProxy = new UserServiceProxy(userService);
userServiceProxy.add();
System.out.println("-------------------------------------------");
/**
* 动态代理
*/
InvocationHandlerImpl invocationHandler = new InvocationHandlerImpl(userService);
ClassLoader loader = userService.getClass().getClassLoader();
Class<?>[] interfaces = userService.getClass().getInterfaces();
UserService newProxy = (UserService) Proxy.newProxyInstance(loader, interfaces, invocationHandler);
newProxy.add();
System.out.println("-------------------------------------------");
/**
* CGLIB动态代理
*/
CglibProxy cglibProxy = new CglibProxy();
UserService userService1 = (UserService) cglibProxy.getInstance(new UserServiceImpl());
userService1.add();
Employee employee = new Employee();
InvocationHandlerImpl invocationHandler1 = new InvocationHandlerImpl(employee);
ClassLoader loader2 = employee.getClass().getClassLoader();
Class<?>[] interfaces2 = employee.getClass().getInterfaces();
Employee o = (Employee) Proxy.newProxyInstance(loader2, interfaces2, invocationHandler1);
o.add();
}
}
|
package demo.oops;
public class AbstractionDemo {
public static void main(String[] args) {
Food obj= new Briyani();
Food obj1= new Friedrice("10");
Food obj2= new Cheesecake("433");
obj.prepare();
obj2.prepare();
obj1.prepare();
}
}
|
package io.github.ihongs.serv.master;
import io.github.ihongs.Cnst;
import io.github.ihongs.Core;
import io.github.ihongs.HongsException;
import io.github.ihongs.action.ActionHelper;
import io.github.ihongs.db.DB;
import io.github.ihongs.db.Model;
import io.github.ihongs.db.Table;
import io.github.ihongs.db.util.FetchCase;
import io.github.ihongs.serv.auth.AuthKit;
import io.github.ihongs.util.Synt;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 用户基础信息模型
* @author Hongs
*/
public class User
extends Model {
public User()
throws HongsException {
this(DB.getInstance("master").getTable("user"));
}
public User(Table table)
throws HongsException {
super(table);
}
@Override
public String add(Map data) throws HongsException {
permit(null, data);
return super.add(data);
}
@Override
public int put(String id, Map data) throws HongsException {
permit( id , data);
return super.put(id, data);
}
@Override
public int del(String id, FetchCase caze) throws HongsException {
permit( id , null);
return super.del(id, caze);
}
@Override
public Map getList(Map rd, FetchCase caze) throws HongsException {
if (caze == null) {
caze = new FetchCase();
}
Map sd = super.getList(rd, caze);
// 管辖范围限制标识: 0 一般用户, 1 管理员, 2 管理层
if (Synt.declare(rd.get("bind-scope"), false )) {
sd.put("scope", caze.getOption("SCOPE", 0));
}
return sd;
}
@Override
protected void filter(FetchCase caze, Map req)
throws HongsException {
/**
* 非超级管理员或在超级管理组
* 限制查询为当前管辖范围以内
*/
if (Synt.declare (req.get("bind-scope"), false)) {
ActionHelper helper = Core.getInstance(ActionHelper.class);
String mid = (String) helper.getSessibute ( Cnst.UID_SES );
String pid = Synt.declare(req.get("dept_id"),"");
if (!Cnst.ADM_UID.equals( mid )) {
Set set = AuthKit.getUserDepts(mid);
if (!set.contains(Cnst.ADM_GID)) {
set = AuthKit.getMoreDepts(set);
if (!set.contains(pid)) {
caze.by (FetchCase.DISTINCT ); // 去重复
caze.gotJoin("depts")
.from ("a_master_dept_user")
.by (FetchCase.INNER)
.on ("`depts`.`user_id` = `user`.`id`")
.filter ("`depts`.`dept_id` IN (?)" , set );
}
} else caze.setOption("SCOPE" , 2 );
} else caze.setOption("SCOPE" , 1 );
}
/**
* 如果有指定 dept_id
* 则关联 a_master_dept_user 来约束范围
* 当其为横杠时表示取那些没有关联的用户
*/
Object pid = req.get("dept_id");
if (null != pid && ! "".equals(pid)) {
if ( "-".equals (pid ) ) {
caze.gotJoin("depts")
.from ("a_master_dept_user")
.by (FetchCase.INNER)
.on ("`depts`.`user_id` = `user`.`id`")
.filter ("`depts`.`dept_id` IS NULL" /**/ );
} else {
caze.gotJoin("depts")
.from ("a_master_dept_user")
.by (FetchCase.INNER)
.on ("`depts`.`user_id` = `user`.`id`")
.filter ("`depts`.`dept_id` IN (?)" , pid );
}
}
super.filter(caze, req);
}
protected void permit(String id, Map data) throws HongsException {
if (data != null) {
// 加密密码
data.remove ("passcode");
if (data.containsKey("password") ) {
String pw = Synt.declare(data.get("password"), "");
String pc = Core.newIdentity();
pc = AuthKit.getCrypt(pw + pc);
pw = AuthKit.getCrypt(pw + pc);
data.put("password" , pw);
data.put("passcode" , pc);
}
// 登录账号, 空串可能导致重复
if (data.containsKey("username") ) {
String un = Synt.declare(data.get("username"), "");
if (un.isEmpty()) {
data.put("username", null);
}
}
// 状态变更, 联动权限更新时间
if (data.containsKey("state")) {
data.put("rtime", System.currentTimeMillis() / 1000);
}
// 权限限制, 仅能赋予当前登录用户所有的权限
if (data.containsKey("roles")) {
data.put("rtime", System.currentTimeMillis() / 1000);
List list = Synt.asList(data.get( "roles" ));
AuthKit.cleanUserRoles (list, id);
// if ( list.isEmpty() ) {
// throw new HongsException(400)
// .setLocalizedContent("master.user.role.error")
// .setLocalizedContext("master");
// }
data.put("roles", list);
}
// 部门限制, 仅能指定当前登录用户下属的部门
if (data.containsKey("depts")) {
data.put("rtime", System.currentTimeMillis() / 1000);
List list = Synt.asList(data.get( "depts" ));
AuthKit.cleanUserDepts (list, id);
if ( list.isEmpty() ) {
throw new HongsException(400)
.setLocalizedContent("master.user.dept.error")
.setLocalizedContext("master");
}
data.put("depts", list);
}
}
if (id != null) {
// 超级管理员可操作任何用户
// 但允许操作自身账号
ActionHelper helper = Core.getInstance(ActionHelper.class);
String uid = (String) helper.getSessibute ( Cnst.UID_SES );
if (Cnst.ADM_UID.equals(uid) || id.equals ( uid )) {
return;
}
// 超级管理组可操作任何用户
// 但不包含超级管理员
Set cur = AuthKit.getUserDepts(uid);
if (cur.contains(Cnst.ADM_GID)
&& !Cnst.ADM_UID.equals( id )) {
return;
}
// 仅可以操作下级用户
Set tar = AuthKit.getLessDepts( id);
Dept dept = new Dept();
for (Object gid : cur) {
Set cld = new HashSet(dept.getChildIds((String) gid, true));
cld.retainAll(tar);
if(!cld.isEmpty()) {
return;
}
}
throw new HongsException(400)
.setLocalizedContent("master.user.unit.error")
.setLocalizedContext("master");
}
}
}
|
package me.ivt.com.ui.paint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
/**
* desc:
*/
public class PaintView extends View {
private Paint mPaint;
public PaintView(Context context) {
super(context);
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//重置
mPaint.reset();
mPaint.setColor(Color.RED);
// mPaint.setAlpha(255);
// mPaint.setStyle(Paint.Style.FILL);//填充 如果是个圆的话 会将里面填充起来
mPaint.setStyle(Paint.Style.STROKE);//描边
// mPaint.setStyle(Paint.Style.FILL_AND_STROKE);//填充并描边
//画笔的宽度
mPaint.setStrokeWidth(10);
//设置线帽
mPaint.setStrokeCap(Paint.Cap.ROUND);//圆形
// mPaint.setStrokeCap(Paint.Cap.BUTT);//没有
// mPaint.setStrokeCap(Paint.Cap.SQUARE);//方形
// mPaint.setStrokeJoin(Paint.Join.MITER);
// mPaint.setStrokeJoin(Paint.Join.ROUND);
// mPaint.setStrokeJoin(Paint.Join.BEVEL);
//测试1
Path path=new Path();
path.moveTo(100,100);
path.lineTo(300,100);
path.lineTo(100,300);
mPaint.setStrokeJoin(Paint.Join.MITER);
canvas.drawPath(path,mPaint);
path.moveTo(100,400);
path.lineTo(300,500);
path.lineTo(100,700);
mPaint.setStrokeJoin(Paint.Join.ROUND);
canvas.drawPath(path,mPaint);
path.moveTo(100,800);
path.lineTo(300,800);
path.lineTo(100,1100);
mPaint.setStrokeJoin(Paint.Join.BEVEL);
canvas.drawPath(path,mPaint);
String str="老子就是邹世清Abcd";
float measureText = mPaint.measureText(str);//获得额文本的宽度,是一个比较粗略的结果
float[] mesauredWidth=new float[10];
int textWidths = mPaint.getTextWidths(str, mesauredWidth);//获取文本的宽度, 是一个标记精准的结果
Paint.FontMetrics fontMetrics=mPaint.getFontMetrics();
float top = fontMetrics.top;
float ascent = fontMetrics.ascent;
float descent = fontMetrics.descent;
float bottom = fontMetrics.bottom;
}
}
|
/*
* 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 javaprogram;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
*
* @author KPSingh
*/
public class JavaProgram {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<String, String>();
myMap.put("1", "One");
myMap.put("2", "Two");
myMap.put("3", "One");
myMap.put("4", "Three");
myMap.put("5", "Two");
myMap.put("6", "Three");
Set<String> mySet = new HashSet<String>();
for (Iterator itr = myMap.entrySet().iterator(); itr.hasNext();)
{
Map.Entry<String, String> entrySet = (Map.Entry) itr.next();
String value = entrySet.getValue();
if (!mySet.add(value))
{
itr.remove();
}
}
System.out.println("mymap :" + myMap);
}
}
|
package cards.basics;
import cards.Card;
/**
* The "Basic" type of cards, consisting of Attack, Dodge, Peach, and Wine
* (Battle expansion)
*
* @author Harry
*
*/
public abstract class Basic extends Card {
private static final long serialVersionUID = -4758707277276652122L;
public Basic(int num, Suit suit, int id) {
super(num, suit, CardType.BASIC, id);
}
public Basic(int num, Suit suit) {
super(num, suit, CardType.BASIC);
}
public Basic(Color color) {
super(color, CardType.BASIC);
}
public Basic() {
super(Color.COLORLESS, CardType.BASIC);
}
}
|
package com.example.yixu.fullcircle;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class AttractionListAdapter extends ArrayAdapter<String> {
public AttractionListAdapter(Context context, String [] AttractionList) {
super(context, R.layout.custom_row_layout_for_listing,AttractionList);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater hotelRowInflater = LayoutInflater.from(getContext());
View hotelListingView = hotelRowInflater.inflate(R.layout.custom_row_layout_for_listing, parent, false);
String attraction = getItem(position);
ImageView hotelIcon = (ImageView)hotelListingView.findViewById(R.id.hotelIconImgView);
hotelIcon.setImageResource(R.drawable.hotel_icon);
TextView hotelName = (TextView) hotelListingView.findViewById(R.id.hotelName);
hotelName.setText(attraction);
return hotelListingView;
}
@Override
public void remove(String object) {
super.remove(object);
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow 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 any later version. *
* *
* Data Crow 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 net.datacrow.console.components.panels;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import net.datacrow.console.ComponentFactory;
import net.datacrow.console.Layout;
import net.datacrow.core.resources.DcResources;
import net.datacrow.core.services.Region;
import net.datacrow.core.services.SearchMode;
import net.datacrow.core.services.plugin.IServer;
public class OnlineServicePanel extends JPanel implements ActionListener {
private JComboBox comboServers = ComponentFactory.getComboBox();
private JComboBox comboRegions = ComponentFactory.getComboBox();
private JComboBox comboModes = ComponentFactory.getComboBox();
private boolean modeSelectionAllowed = false;
private JCheckBox checkUseOnlineService = ComponentFactory.getCheckBox(DcResources.getText("lblUseOnlineService"));
public OnlineServicePanel(Collection<IServer> servers, boolean modeSelectionAllowed, boolean toggle) {
this.modeSelectionAllowed = modeSelectionAllowed;
build(servers, toggle);
}
public boolean useOnlineService() {
return checkUseOnlineService.isSelected();
}
public IServer getServer() {
return checkUseOnlineService.isSelected() ? (IServer) comboServers.getSelectedItem() : null;
}
public Region getRegion() {
return checkUseOnlineService.isSelected() ? (Region) comboRegions.getSelectedItem() : null;
}
public SearchMode getMode() {
return checkUseOnlineService.isSelected() && modeSelectionAllowed ?
(SearchMode) comboModes.getSelectedItem() : null;
}
public void setServer(String name) {
IServer server;
for (int idx = 0; idx < comboServers.getItemCount(); idx++) {
server = (IServer) comboServers.getItemAt(idx);
if (server.getName().equals(name))
comboServers.setSelectedItem(server);
}
}
public void setRegion(String code) {
if (comboRegions == null || comboRegions.getItemCount() == 0) return;
Region region;
for (int idx = 0; idx < comboRegions.getItemCount(); idx++) {
region = (Region) comboRegions.getItemAt(idx);
if (region.getCode().equals(code))
comboRegions.setSelectedItem(region);
}
}
public void setMode(String displayName) {
if (comboModes == null || comboModes.getItemCount() == 0) return;
SearchMode mode;
for (int idx = 0; idx < comboModes.getItemCount(); idx++) {
mode = (SearchMode) comboModes.getItemAt(idx);
if (mode.getDisplayName().equals(displayName))
comboModes.setSelectedItem(mode);
}
}
private void applyServer() {
IServer server = getServer();
comboRegions.removeAllItems();
comboModes.removeAllItems();
if (server != null) {
for (Region region : server.getRegions())
comboRegions.addItem(region);
if (server.getSearchModes() != null) {
for (SearchMode mode : server.getSearchModes())
comboModes.addItem(mode);
}
comboModes.setVisible(comboModes.getItemCount() > 0);
}
repaint();
}
public void clear() {
comboServers = null;
comboRegions = null;
comboModes = null;
checkUseOnlineService = null;
removeAll();
}
public void setUseOnlineService(boolean b) {
checkUseOnlineService.setSelected(b);
}
private void toggleServer() {
boolean b = checkUseOnlineService.isSelected();
comboRegions.setEnabled(b);
comboServers.setEnabled(b);
comboModes.setEnabled(b);
}
private void build(Collection<IServer> servers, boolean toggle) {
setLayout(Layout.getGBL());
for (IServer server : servers)
comboServers.addItem(server);
comboServers.addActionListener(this);
comboServers.setActionCommand("applyServer");
checkUseOnlineService.addActionListener(this);
checkUseOnlineService.setActionCommand("toggleServer");
if (toggle)
add(checkUseOnlineService, Layout.getGBC(0, 0, 2, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(5, 5, 5, 5), 0, 0));
add(comboServers, Layout.getGBC(0, 1, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(5, 5, 5, 5), 0, 0));
add(comboRegions, Layout.getGBC(1, 1, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(5, 5, 5, 5), 0, 0));
if (modeSelectionAllowed)
add(comboModes, Layout.getGBC(0, 2, 1, 1, 1.0, 1.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
new Insets(5, 5, 5, 5), 0, 0));
setBorder(ComponentFactory.getTitleBorder(DcResources.getText("lblOnlineServiceConfig")));
checkUseOnlineService.setSelected(true);
comboServers.setSelectedIndex(0);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("toggleServer"))
toggleServer();
else if (e.getActionCommand().equals("applyServer"))
applyServer();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
clear();
}
}
|
package com.edasaki.rpg.spells;
import com.edasaki.rpg.spells.archer.ArrowRain;
import com.edasaki.rpg.spells.archer.DoubleShot;
import com.edasaki.rpg.spells.archer.ExplodingArrow;
import com.edasaki.rpg.spells.archer.Hurricane;
import com.edasaki.rpg.spells.archer.QuadShot;
import com.edasaki.rpg.spells.archer.TripleShot;
public class SpellbookArcher extends Spellbook {
public static final Spell DOUBLE_SHOT = new Spell("Double Shot", 1, 10, 1, 0, new String[] {
"Shoot two arrows dealing 80% damage each.",
"Shoot two arrows dealing 90% damage each.",
"Shoot two arrows dealing 100% damage each.",
"Shoot two arrows dealing 110% damage each.",
"Shoot two arrows dealing 120% damage each.",
"Shoot two arrows dealing 130% damage each.",
"Shoot two arrows dealing 140% damage each.",
"Shoot two arrows dealing 150% damage each.",
"Shoot two arrows dealing 160% damage each.",
"Shoot two arrows dealing 170% damage each.",
}, null, new DoubleShot());
public static final Spell TRIPLE_SHOT = new Spell("Triple Shot", 2, 10, 1, 1, new String[] {
"Shoot three arrows dealing 70% damage each.",
"Shoot three arrows dealing 80% damage each.",
"Shoot three arrows dealing 90% damage each.",
"Shoot three arrows dealing 100% damage each.",
"Shoot three arrows dealing 110% damage each.",
"Shoot three arrows dealing 120% damage each.",
"Shoot three arrows dealing 130% damage each.",
"Shoot three arrows dealing 140% damage each.",
"Shoot three arrows dealing 150% damage each.",
"Shoot three arrows dealing 160% damage each.",
}, new Object[] {
DOUBLE_SHOT,
10
}, new TripleShot());
public static final Spell QUAD_SHOT = new Spell("Quad Shot", 3, 10, 1, 2, new String[] {
"Shoot four arrows dealing 60% damage each.",
"Shoot four arrows dealing 70% damage each.",
"Shoot four arrows dealing 80% damage each.",
"Shoot four arrows dealing 90% damage each.",
"Shoot four arrows dealing 100% damage each.",
"Shoot four arrows dealing 110% damage each.",
"Shoot four arrows dealing 120% damage each.",
"Shoot four arrows dealing 130% damage each.",
"Shoot four arrows dealing 140% damage each.",
"Shoot four arrows dealing 150% damage each.",
}, new Object[] {
TRIPLE_SHOT,
10
}, new QuadShot());
public static final Spell ARROW_RAIN = new Spell("Arrow Rain", 4, 10, 2, 0, new String[] {
"Summon a shower of arrows dealing 110% damage each.",
"Summon a shower of arrows dealing 120% damage each.",
"Summon a shower of arrows dealing 130% damage each.",
"Summon a shower of arrows dealing 140% damage each.",
"Summon a shower of arrows dealing 150% damage each.",
"Summon a shower of arrows dealing 160% damage each.",
"Summon a shower of arrows dealing 170% damage each.",
"Summon a shower of arrows dealing 180% damage each.",
"Summon a shower of arrows dealing 190% damage each.",
"Summon a shower of arrows dealing 200% damage each.",
}, null, new ArrowRain());
public static final Spell HURRICANE = new Spell("Hurricane", 8, 15, 2, 1, new String[] {
"Shoot a barrage of 16 arrows dealing 26% damage each.",
"Shoot a barrage of 17 arrows dealing 27% damage each.",
"Shoot a barrage of 18 arrows dealing 28% damage each.",
"Shoot a barrage of 19 arrows dealing 29% damage each.",
"Shoot a barrage of 20 arrows dealing 30% damage each.",
"Shoot a barrage of 21 arrows dealing 31% damage each.",
"Shoot a barrage of 22 arrows dealing 32% damage each.",
"Shoot a barrage of 23 arrows dealing 33% damage each.",
"Shoot a barrage of 24 arrows dealing 34% damage each.",
"Shoot a barrage of 25 arrows dealing 35% damage each.",
"Shoot a barrage of 26 arrows dealing 36% damage each.",
"Shoot a barrage of 27 arrows dealing 37% damage each.",
"Shoot a barrage of 28 arrows dealing 38% damage each.",
"Shoot a barrage of 29 arrows dealing 39% damage each.",
"Shoot a barrage of 30 arrows dealing 40% damage each.",
}, new Object[] {
ARROW_RAIN,
6
}, new Hurricane());
// public static final Spell BLUNT_ARROW = new Spell("Blunt Arrow", 2, 1, 3, 0, new String[] {
// "Fire a blunt arrow that knocks an enemy a short distance away.",
// }, null, new BluntArrow());
public static final Spell EXPLODING_ARROW = new Spell("Exploding Arrow", 2, 10, 3, 1, new String[] {
"Fire an arrow that explodes on impact with an enemy to deal 130% damage to nearby enemies.",
"Fire an arrow that explodes on impact with an enemy to deal 150% damage to nearby enemies.",
"Fire an arrow that explodes on impact with an enemy to deal 170% damage to nearby enemies.",
"Fire an arrow that explodes on impact with an enemy to deal 190% damage to nearby enemies.",
"Fire an arrow that explodes on impact with an enemy to deal 210% damage to nearby enemies.",
"Fire an arrow that explodes on impact with an enemy to deal 230% damage to nearby enemies.",
"Fire an arrow that explodes on impact with an enemy to deal 250% damage to nearby enemies.",
"Fire an arrow that explodes on impact with an enemy to deal 270% damage to nearby enemies.",
"Fire an arrow that explodes on impact with an enemy to deal 290% damage to nearby enemies.",
"Fire an arrow that explodes on impact with an enemy to deal 310% damage to nearby enemies.",
}, null, new ExplodingArrow());
public static final Spell BOW_MASTERY = new Spell("Bow Mastery", 0, 5, 1, 7, new String[] {
"Deal 2% increased base damage.",
"Deal 4% increased base damage.",
"Deal 6% increased base damage.",
"Deal 8% increased base damage.",
"Deal 10% increased base damage.",
}, null, new PassiveSpellEffect());
public static final Spell KEEN_EYES = new Spell("Keen Eyes", 0, 5, 1, 8, new String[] {
"Gain +2% Crit Chance.",
"Gain +4% Crit Chance.",
"Gain +6% Crit Chance.",
"Gain +8% Crit Chance.",
"Gain +10% Crit Chance.",
}, null, new PassiveSpellEffect());
public static final Spell RAPID_FIRE = new Spell("Rapid Fire", 0, 3, 2, 8, new String[] {
"Increase your attack speed by 10%.",
"Increase your attack speed by 20%.",
"Increase your attack speed by 30%.",
}, null, new PassiveSpellEffect());
private static final Spell[] SPELL_LIST = {
DOUBLE_SHOT,
TRIPLE_SHOT,
QUAD_SHOT,
ARROW_RAIN,
HURRICANE,
// BLUNT_ARROW,
EXPLODING_ARROW,
BOW_MASTERY,
KEEN_EYES,
RAPID_FIRE
};
// DON'T FORGET TO ADD TO SPELL_LIST
public static final Spellbook INSTANCE = new SpellbookArcher();
@Override
public Spell[] getSpellList() {
return SPELL_LIST;
}
}
|
package com.tyj.venus.controller.admin;
import com.tyj.venus.controller.BaseController;
import com.tyj.venus.entity.Gadmin;
import com.tyj.venus.entity.Menu;
import com.tyj.venus.service.GadminService;
import com.tyj.venus.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Controller
@RequestMapping(value = "admin/role")
public class RoleController extends BaseController {
@Autowired
private GadminService gadminService;
@Autowired
private MenuService menuService;
@GetMapping("")
public String index(Model model, HttpServletRequest request, @RequestParam(value = "page", defaultValue = "1") Integer page) {
String keywords = request.getParameter("keywords");
Sort sort = new Sort(Sort.Direction.DESC, "gid");
Page<Gadmin> roles = gadminService.findAllByLikeName("gname", keywords, page, 10, sort);
model.addAttribute("list", roles);
model.addAttribute("page", page);
model.addAttribute("keywords", keywords);
return "admin/role-list";
}
@GetMapping("/add")
public String roleAdd() {
return "admin/role-add";
}
@GetMapping("/edit/{gadmin}")
public String roleEdit(Model model, Gadmin gadmin) {
model.addAttribute("gadmin", gadmin);
return "admin/role-edit";
}
@GetMapping("/set-permission/{gadmin}")
public String setPermission(Gadmin gadmin, Model model) {
List <Menu> menus = menuService.getRecursionList(menuService.findAll());
model.addAttribute("permission", gadmin.getMenus());
System.out.println(menus);
model.addAttribute("menus", menus);
model.addAttribute("gadmin", gadmin);
return "admin/set-permission";
}
@PostMapping("set-permission/{gadmin}")
@ResponseBody
public String setPermissionAct(Gadmin gadmin, Model model, HttpServletRequest request) {
Enumeration em = request.getParameterNames();
Set<Menu> menuSet = new HashSet<Menu>();
while (em.hasMoreElements()) {
String name = (String) em.nextElement();
if (name.contains("action_")) {
String[] values = request.getParameterValues(name);
String[] s_temp = name.split("_");
String menu_id = s_temp[1].replace("[]", "");
menuSet.add(new Menu(Integer.parseInt(menu_id)));
for (int i = 0; i < values.length; i++) {
menuSet.add(new Menu(Integer.parseInt(values[i])));
}
}
}
gadmin.setMenus(menuSet);
gadminService.update(gadmin);
this.adminLog("设置权限-[" + gadmin.getGname() + "]");
return this.outPutData("权限修改成功");
}
@DeleteMapping("/del/{gadmin}")
@ResponseBody
public String roleDel(Gadmin gadmin) {
this.adminLog("删除角色[" + gadmin.getGname() + "]");
gadminService.delete(gadmin);
return this.outPutData("删除成功");
}
@PostMapping("/save")
@ResponseBody
public String save(@Valid Gadmin gadmin, BindingResult result, HttpServletRequest request) {
if (result.hasErrors()) {//验证
List<ObjectError> error = result.getAllErrors();
for (ObjectError e : error) {
return this.outPutErr(e.getDefaultMessage());
}
return null;
} else {//验证通过
if (gadmin.getGid() == null) {//新增
Gadmin gadmin_new = gadminService.save(gadmin);
if (gadmin_new != null) {
this.adminLog("添加角色[" + gadmin.getGname() + "]");
return this.outPutData("保存成功");
}
} else {//更新
Gadmin gadmin_temp = gadminService.get(gadmin.getGid());
gadmin.setMenus(gadmin_temp.getMenus());
Gadmin gadmin_new = gadminService.update(gadmin);
if (gadmin_new != null) {
this.adminLog("修改角色[" + gadmin.getGname() + "]");
return this.outPutData("保存成功");
}
}
return this.outPutErr("保存失败,请重试");
}
}
}
|
package com.xnarum.thonline.entity.idd001;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
@XmlAccessorType(XmlAccessType.FIELD)
public class AccountStatusQueryRequestBody {
@XmlElement(name="THAcct")
private String accountNo;
// @XmlElement(name="THIdType")
// private String idType;
//
@XmlElement(name="THICNo")
private String idNumber;
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
// public String getIdType() {
// return idType;
// }
//
// public void setIdType(String idType) {
// this.idType = idType;
// }
//
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
}
|
package Tutorial.P3_ActorTool.S4_FSM_State.UserStorage;
/**
* Created by lamdevops on 6/11/17.
*/
public enum State {
Connected, Disconnected
}
|
package com.beike.form.background.guest;
import java.sql.Timestamp;
/**
* Title : GuestBranchForm
* <p/>
* Description :分公司表单对象
* <p/>
* CopyRight : CopyRight (c) 2011
* </P>
* Company : Sinobo
* </P>
* JDK Version Used : JDK 5.0 +
* <p/>
* Modification History :
* <p/>
* <pre>NO. Date Modified By Why & What is modified</pre>
* <pre>1 2011-06-03 lvjx Created<pre>
* <p/>
*
* @author lvjx
* @version 1.0.0.2011-06-03
*/
public class GuestBranchForm {
private int branchId; //分店ID PK
private String branchCnName; //分店名称
private int branchCountryId; //分店所属国
private int branchProvinceId; //分店所属省
private int branchCityId; //分店所属市
private int branchCityAreaId; //区ID
private String branchAddress; //分店详细地址
private String branchRegionId; //周边地标
private String branchBusinessTime; //营业时间
private String branchBookPhone; //预订电话
private String branchLon; //经度
private String branchLat; //维度
private String branchStatus; //分店状态(0,ACTIVE;1,UNACTIVE)
private int guestId; //公司ID
private String brandName; //品牌名称
private Timestamp branchCreateTime; //分店创建时间
private Timestamp branchModifyTime; //分店修改时间
public int getBranchId() {
return branchId;
}
public void setBranchId(int branchId) {
this.branchId = branchId;
}
public String getBranchCnName() {
return branchCnName;
}
public void setBranchCnName(String branchCnName) {
this.branchCnName = branchCnName;
}
public int getBranchCountryId() {
return branchCountryId;
}
public void setBranchCountryId(int branchCountryId) {
this.branchCountryId = branchCountryId;
}
public int getBranchProvinceId() {
return branchProvinceId;
}
public void setBranchProvinceId(int branchProvinceId) {
this.branchProvinceId = branchProvinceId;
}
public int getBranchCityId() {
return branchCityId;
}
public void setBranchCityId(int branchCityId) {
this.branchCityId = branchCityId;
}
public int getBranchCityAreaId() {
return branchCityAreaId;
}
public void setBranchCityAreaId(int branchCityAreaId) {
this.branchCityAreaId = branchCityAreaId;
}
public String getBranchAddress() {
return branchAddress;
}
public void setBranchAddress(String branchAddress) {
this.branchAddress = branchAddress;
}
public String getBranchRegionId() {
return branchRegionId;
}
public void setBranchRegionId(String branchRegionId) {
this.branchRegionId = branchRegionId;
}
public String getBranchBusinessTime() {
return branchBusinessTime;
}
public void setBranchBusinessTime(String branchBusinessTime) {
this.branchBusinessTime = branchBusinessTime;
}
public String getBranchBookPhone() {
return branchBookPhone;
}
public void setBranchBookPhone(String branchBookPhone) {
this.branchBookPhone = branchBookPhone;
}
public String getBranchLon() {
return branchLon;
}
public void setBranchLon(String branchLon) {
this.branchLon = branchLon;
}
public String getBranchLat() {
return branchLat;
}
public void setBranchLat(String branchLat) {
this.branchLat = branchLat;
}
public String getBranchStatus() {
return branchStatus;
}
public void setBranchStatus(String branchStatus) {
this.branchStatus = branchStatus;
}
public int getGuestId() {
return guestId;
}
public void setGuestId(int guestId) {
this.guestId = guestId;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public Timestamp getBranchCreateTime() {
return branchCreateTime;
}
public void setBranchCreateTime(Timestamp branchCreateTime) {
this.branchCreateTime = branchCreateTime;
}
public Timestamp getBranchModifyTime() {
return branchModifyTime;
}
public void setBranchModifyTime(Timestamp branchModifyTime) {
this.branchModifyTime = branchModifyTime;
}
}
|
package com.stefanini.service;
import java.util.ArrayList;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import com.stefanini.model.Modelo;
import com.stefanini.repository.ModeloRepository;
@Stateless
public class ModeloService {
@Inject
private ModeloRepository modeloRepository;
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void incluir(Modelo modelo){
modeloRepository.incluir(modelo);
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public ArrayList<Modelo> listar(){
return (ArrayList<Modelo>) modeloRepository.lista();
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Modelo busca(int id){
return modeloRepository.busca(id);
}
}
|
package sh1457.test.com.grand;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "gesturedb";
private static final String TABLE_GESTURES = "gestures";
private static final String KEY_ID = "id";
private static final String KEY_GSTRING = "gstring";
private final ArrayList<Gesture> gesture_list = new ArrayList<>();
DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_GESTURES_TABLE = "CREATE TABLE " + TABLE_GESTURES + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_GSTRING + " TEXT" + ")";
db.execSQL(CREATE_GESTURES_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_GESTURES);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
void Add_Gesture(Gesture gesture) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, gesture.getID()); // Gesture ID
values.put(KEY_GSTRING, gesture.getString()); // Gesture String
db.insert(TABLE_GESTURES, null, values);
db.close(); // Closing database connection
}
Gesture Get_Gesture(int id) {
SQLiteDatabase db = this.getReadableDatabase();
String gstring;
int gid=-1;
Cursor cursor = db.query(TABLE_GESTURES, new String[] { KEY_ID, KEY_GSTRING }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
try {
assert cursor != null;
gid = cursor.getInt(0);
}catch (NullPointerException e) {
Log.e("get_gesture", "cursor is null" + e);
}
gstring=cursor.getString(1);
Gesture gesture = new Gesture(gid, gstring);
cursor.close();
db.close();
return gesture;
}
ArrayList<Gesture> Get_Gestures() {
String gstring;
int gid;
try {
gesture_list.clear();
String selectQuery = "SELECT * FROM " + TABLE_GESTURES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
gid = cursor.getInt(0);
gstring=cursor.getString(1);
Gesture gesture = new Gesture(gid, gstring);
// Adding gesture to list
gesture_list.add(gesture);
}while (cursor.moveToNext());
}
cursor.close();
db.close();
return gesture_list;
}catch(NullPointerException e) {
Log.e("get_all_gesture", "cursor is null" + e);
}catch (Exception e) {
Log.e("get_all_gesture", "" + e);
}
return gesture_list;
}
void Delete_Gesture(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_GESTURES, KEY_ID + " = ?",
new String[] { String.valueOf(id) });
db.close();
}
public int Get_Total_Gestures() {
String countQuery = "SELECT * FROM " + TABLE_GESTURES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
|
package com.xixiwan.platform.sys.entity;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.xixiwan.platform.base.BaseEntity;
import com.xixiwan.platform.module.common.util.DateUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* <p>
* 用户表
* </p>
*
* @author Sente
* @since 2018-09-28
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class SysUser extends BaseEntity<SysUser> {
private static final long serialVersionUID = 1L;
/**
* 头像
*/
private String avatar;
/**
* 账号
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 名字
*/
private String name;
/**
* 生日
*/
@JsonSerialize(using = LocalDateSerializer.class)
@JsonDeserialize(using = LocalDateDeserializer.class)
@DateTimeFormat(pattern = DateUtils.DATE_FMT_3)
private LocalDate birthday;
/**
* 性别(1:男 2:女)
*/
private Integer sex;
/**
* 邮箱
*/
private String email;
/**
* 电话
*/
private String phone;
/**
* 创建时间
*/
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime createtime;
/**
* 状态(1:正常 2:禁用 3:锁定 4:删除)
*/
private Integer status;
/**
* 登录失败次数
*/
private Integer failtimes;
/**
* 密码过期时间
*/
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime expiredtime;
}
|
package com.zzh.cloud;
/**
* 添加该注解,目的就是让应用启动后,含有该注解的文件不会被应用扫描到。
*/
public @interface ExcludeFromComponentScan {
}
|
/*
* #%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.constants.HeadingSize;
import com.dianaui.universal.core.client.ui.constants.Styles;
import com.dianaui.universal.core.client.ui.html.Div;
import com.google.gwt.user.client.ui.HasHTML;
/**
* Page header with optional subtext
* <h3>UiBinder example</h3>
* <pre>
* {@code
* <b:PageHeader subText="Some subtext">Page header title</b:PageHeader>
* }
* </pre>
*
* @author Sven Jacobs
* @author Joshua Godi
* @author <a href='mailto:donbeave@gmail.com'>Alexey Zhokhov</a>
*/
public class PageHeader extends Div implements HasHTML {
private Heading heading = new Heading(HeadingSize.H1);
public PageHeader() {
setStyleName(Styles.PAGE_HEADER);
add(heading);
}
/**
* Creates a Heading with the passed in size and text.
*
* @param text text for the heading
*/
public PageHeader(final String text) {
this();
setText(text);
}
/**
* Creates a Heading with the passed in size and text.
*
* @param text text for the heading
* @param subtext subtext for the heading
*/
public PageHeader(final String text, final String subtext) {
this(text);
setSubText(subtext);
}
public Heading getHeading() {
return heading;
}
/**
* @return subtext of the heading
*/
public String getSubText() {
return heading.getText();
}
/**
* @param subtext the subtext of the heading
*/
public void setSubText(final String subtext) {
heading.setSubText(subtext);
}
@Override
public String getText() {
return heading.getText();
}
@Override
public void setText(final String text) {
heading.setText(text);
}
@Override
public String getHTML() {
return heading.getHTML();
}
@Override
public void setHTML(final String html) {
heading.setHTML(html);
}
}
|
package clustering;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;
import java.util.Map;
import java.util.Random;
import clustering.database.ClusterDatabase;
public class EmitDataPoints extends BaseRichSpout {
SpoutOutputCollector _collector;
Integer count=0;
Random _rand=new Random();
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
_collector = collector;
}
public void nextTuple() {
Utils.sleep(100);
String ser_matrices[];
int[][][] matrices = {{{1,2,3},{4,5,6}},{{3,4,5},{6,7,8}}};
ser_matrices=ClusterDatabase.get_serialized_two_d_matrices();
EmitMatrixWithClosestCluster.emit_matrix_with_closes_cluster_center(_collector, ser_matrices,matrices[_rand.nextInt(matrices.length)]);
}
@Override
public void ack(Object id) {
}
@Override
public void fail(Object id) {
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("index","matrix"));
}
}
|
package xyz.carbule8.video.pojo;
public enum VideoStatus {
UPLOAD_SUCCESS, // 上传完成
TRANSCODING, // 转码中
TRANSCODING_SUCCESS, // 转码成功
TRANSCODING_FAILED, // 转码失败
UPLOAD_OSS, // 上传oss中
UPLOAD_OSS_FAILED, // 上传oss失败
COMPLETE; // 完成
}
|
package com.example.donisaurus.ecomplaint.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by Donisaurus on 1/8/2017.
*/
public class ModelComment {
@SerializedName("id_komentar")
@Expose
private Integer idKomentar;
@SerializedName("id_post")
@Expose
private Integer idPost;
@SerializedName("id_user_komentar")
@Expose
private Integer idUserKomentar;
@SerializedName("komentar")
@Expose
private String komentar;
@SerializedName("tanggal_komentar")
@Expose
private String tanggalKomentar;
@SerializedName("user_yg_komen")
@Expose
private String userYgKomen;
public Integer getIdKomentar() {
return idKomentar;
}
public void setIdKomentar(Integer idKomentar) {
this.idKomentar = idKomentar;
}
public Integer getIdPost() {
return idPost;
}
public void setIdPost(Integer idPost) {
this.idPost = idPost;
}
public Integer getIdUserKomentar() {
return idUserKomentar;
}
public void setIdUserKomentar(Integer idUserKomentar) {
this.idUserKomentar = idUserKomentar;
}
public String getKomentar() {
return komentar;
}
public void setKomentar(String komentar) {
this.komentar = komentar;
}
public String getTanggalKomentar() {
return tanggalKomentar;
}
public void setTanggalKomentar(String tanggalKomentar) {
this.tanggalKomentar = tanggalKomentar;
}
public String getUserYgKomen() {
return userYgKomen;
}
public void setUserYgKomen(String userYgKomen) {
this.userYgKomen = userYgKomen;
}
}
|
package Entyties.Project.Development.BuildingWrapper.BuildingObject.BuildingParameter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class BuildingParameter {
@JsonProperty("Id")
private int id;
@JsonProperty("Name")
private String name;
@JsonProperty("IsDefault")
private boolean isDefault;
@JsonProperty("CreatedOn")
private String createdOn;
@JsonProperty("ModifiedOn")
private String modifiedOn;
@JsonProperty("TowersParallel")
private boolean towersParallel;
@JsonProperty("ParallelPkgLen")
private int parallelPkgLen;
@JsonProperty("HeadInPkgLen")
private int headInPkgLen;
@JsonProperty("DiagonalPkgLen")
private int diagonalPkgLen;
@JsonProperty("AreaPkgSurface")
private int areaPkgSurface;
@JsonProperty("AreaPkgStructure")
private int areaPkgStructure;
@JsonProperty("PkgStructureType")
private int pkgStructureType;
@JsonProperty("MinimumPkgSpacesFloor")
private int minimumPkgSpacesFloor;
@JsonProperty("LinerDepth")
private int linerDepth;
@JsonProperty("MinTowerLen")
private int minTowerLen;
@JsonProperty("MaxTowerDep")
private int maxTowerDep;
@JsonProperty("MaxTowerLenRes")
private int maxTowerLenRes;
@JsonProperty("MaxTowerLenComm")
private int maxTowerLenComm;
@JsonProperty("CirculationPercent")
private int circulationPercent;
@JsonProperty("GroundLevelHeight")
private int groundLevelHeight;
@JsonProperty("BaseLevelHeight")
private int baseLevelHeight;
@JsonProperty("TowerLevelHeight")
private int towerLevelHeight;
@JsonProperty("ParkingLevelHeight")
private int parkingLevelHeight;
@JsonProperty("UserId")
private int userId;
@JsonProperty("BuildingId")
private int buildingId;
@JsonProperty("ScoutLotArea")
private boolean scoutLotArea;
@JsonProperty("ParkingSlope")
private int parkingSlope;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isDefault() {
return isDefault;
}
public void setDefault(boolean aDefault) {
isDefault = aDefault;
}
public String getCreatedOn() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn = createdOn;
}
public String getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(String modifiedOn) {
this.modifiedOn = modifiedOn;
}
public boolean isTowersParallel() {
return towersParallel;
}
public void setTowersParallel(boolean towersParallel) {
this.towersParallel = towersParallel;
}
public int getParallelPkgLen() {
return parallelPkgLen;
}
public void setParallelPkgLen(int parallelPkgLen) {
this.parallelPkgLen = parallelPkgLen;
}
public int getHeadInPkgLen() {
return headInPkgLen;
}
public void setHeadInPkgLen(int headInPkgLen) {
this.headInPkgLen = headInPkgLen;
}
public int getDiagonalPkgLen() {
return diagonalPkgLen;
}
public void setDiagonalPkgLen(int diagonalPkgLen) {
this.diagonalPkgLen = diagonalPkgLen;
}
public int getAreaPkgSurface() {
return areaPkgSurface;
}
public void setAreaPkgSurface(int areaPkgSurface) {
this.areaPkgSurface = areaPkgSurface;
}
public int getAreaPkgStructure() {
return areaPkgStructure;
}
public void setAreaPkgStructure(int areaPkgStructure) {
this.areaPkgStructure = areaPkgStructure;
}
public int getPkgStructureType() {
return pkgStructureType;
}
public void setPkgStructureType(int pkgStructureType) {
this.pkgStructureType = pkgStructureType;
}
public int getMinimumPkgSpacesFloor() {
return minimumPkgSpacesFloor;
}
public void setMinimumPkgSpacesFloor(int minimumPkgSpacesFloor) {
this.minimumPkgSpacesFloor = minimumPkgSpacesFloor;
}
public int getLinerDepth() {
return linerDepth;
}
public void setLinerDepth(int linerDepth) {
this.linerDepth = linerDepth;
}
public int getMinTowerLen() {
return minTowerLen;
}
public void setMinTowerLen(int minTowerLen) {
this.minTowerLen = minTowerLen;
}
public int getMaxTowerDep() {
return maxTowerDep;
}
public void setMaxTowerDep(int maxTowerDep) {
this.maxTowerDep = maxTowerDep;
}
public int getMaxTowerLenRes() {
return maxTowerLenRes;
}
public void setMaxTowerLenRes(int maxTowerLenRes) {
this.maxTowerLenRes = maxTowerLenRes;
}
public int getMaxTowerLenComm() {
return maxTowerLenComm;
}
public void setMaxTowerLenComm(int maxTowerLenComm) {
this.maxTowerLenComm = maxTowerLenComm;
}
public int getCirculationPercent() {
return circulationPercent;
}
public void setCirculationPercent(int circulationPercent) {
this.circulationPercent = circulationPercent;
}
public int getGroundLevelHeight() {
return groundLevelHeight;
}
public void setGroundLevelHeight(int groundLevelHeight) {
this.groundLevelHeight = groundLevelHeight;
}
public int getBaseLevelHeight() {
return baseLevelHeight;
}
public void setBaseLevelHeight(int baseLevelHeight) {
this.baseLevelHeight = baseLevelHeight;
}
public int getTowerLevelHeight() {
return towerLevelHeight;
}
public void setTowerLevelHeight(int towerLevelHeight) {
this.towerLevelHeight = towerLevelHeight;
}
public int getParkingLevelHeight() {
return parkingLevelHeight;
}
public void setParkingLevelHeight(int parkingLevelHeight) {
this.parkingLevelHeight = parkingLevelHeight;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getBuildingId() {
return buildingId;
}
public void setBuildingId(int buildingId) {
this.buildingId = buildingId;
}
public boolean isScoutLotArea() {
return scoutLotArea;
}
public void setScoutLotArea(boolean scoutLotArea) {
this.scoutLotArea = scoutLotArea;
}
public int getParkingSlope() {
return parkingSlope;
}
public void setParkingSlope(int parkingSlope) {
this.parkingSlope = parkingSlope;
}
@Override
public String toString() {
return "BuildingParameter{" +
"id=" + id +
", name='" + name + '\'' +
", isDefault=" + isDefault +
", createdOn='" + createdOn + '\'' +
", modifiedOn='" + modifiedOn + '\'' +
", towersParallel=" + towersParallel +
", parallelPkgLen=" + parallelPkgLen +
", headInPkgLen=" + headInPkgLen +
", diagonalPkgLen=" + diagonalPkgLen +
", areaPkgSurface=" + areaPkgSurface +
", areaPkgStructure=" + areaPkgStructure +
", pkgStructureType=" + pkgStructureType +
", minimumPkgSpacesFloor=" + minimumPkgSpacesFloor +
", linerDepth=" + linerDepth +
", minTowerLen=" + minTowerLen +
", maxTowerDep=" + maxTowerDep +
", maxTowerLenRes=" + maxTowerLenRes +
", maxTowerLenComm=" + maxTowerLenComm +
", circulationPercent=" + circulationPercent +
", groundLevelHeight=" + groundLevelHeight +
", baseLevelHeight=" + baseLevelHeight +
", towerLevelHeight=" + towerLevelHeight +
", parkingLevelHeight=" + parkingLevelHeight +
", userId=" + userId +
", buildingId=" + buildingId +
", scoutLotArea=" + scoutLotArea +
", parkingSlope=" + parkingSlope +
'}';
}
}
|
package application;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Program {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
SimpleDateFormat sdf3 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
SimpleDateFormat sdf4 = new SimpleDateFormat("EEE, dd MMMMM yyyy hh:mm aaa");
sdf3.setTimeZone(TimeZone.getTimeZone("GMT"));
sdf4.setTimeZone(TimeZone.getTimeZone("GMT"));
Date x1 = new Date();
Date x2 = new Date(System.currentTimeMillis());
Date x3 = new Date(0L);
Date x4 = new Date(1000L * 60L * 60L * 5L);
Date y1 = sdf1.parse("25/06/2018");
Date y2 = sdf2.parse("25/06/2018 15:42:07");
Date y3 = Date.from(Instant.parse("2018-06-25T15:42:07Z"));
System.out.println("------------- Sem formato");
System.out.println("x1: " + x1);
System.out.println("x2: " + x2);
System.out.println("x3: " + x3);
System.out.println("x4: " + x4);
System.out.println("y1: " + y1);
System.out.println("y2: " + y2);
System.out.println("y3: " + y3);
System.out.println("------------- Formato 02");
System.out.println("x1: " + sdf2.format(x1));
System.out.println("x2: " + sdf2.format(x2));
System.out.println("x3: " + sdf2.format(x3));
System.out.println("x4: " + sdf2.format(x4));
System.out.println("y1: " + sdf2.format(y1));
System.out.println("y2: " + sdf2.format(y2));
System.out.println("y3: " + sdf2.format(y3));
System.out.println("------------- Formato 03 - com GMT Brasil");
System.out.println("x1: " + sdf3.format(x1));
System.out.println("x2: " + sdf3.format(x2));
System.out.println("x3: " + sdf3.format(x3));
System.out.println("x4: " + sdf3.format(x4));
System.out.println("y1: " + sdf3.format(y1));
System.out.println("y2: " + sdf3.format(y2));
System.out.println("y3: " + sdf3.format(y3));
// Usando o Calendar
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date d = Date.from(Instant.parse("2018-06-25T15:42:07Z"));
System.out.println(sdf.format(d));
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.HOUR_OF_DAY, 4);
d = cal.getTime();
System.out.println("Horário atual com 4 horas acrescentadas; " + sdf.format(d));
// Usando o Calendar para obter uma unidade de tempo
SimpleDateFormat sdf0 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date dt = Date.from(Instant.parse("2018-06-25T15:42:07Z"));
System.out.println(sdf0.format(d));
Calendar caly = Calendar.getInstance();
caly.setTime(dt);
int minutes = caly.get(Calendar.MINUTE);
int month = 1 + caly.get(Calendar.MONTH);
int year = caly.get(Calendar.YEAR) - 55;
System.out.println("Minutes: " + minutes);
System.out.println("Month: " + month);
System.out.println("Year.: " + year);
// Minha data de aniversário
Date dtnasc = Date.from(Instant.parse("1964-08-27T23:00:00Z"));
System.out.println();
Calendar caldtnasc = Calendar.getInstance();
caldtnasc.setTime(dtnasc);
int dsem = caldtnasc.get(Calendar.DAY_OF_WEEK);
System.out.println("Dia da semana que eu nasci: " + dsem);
System.out.println("Data Nascimento: " + dtnasc);
System.out.println("Data Nascimento: " + sdf2.format(dtnasc));
System.out.println("Data Nascimento: " + sdf3.format(dtnasc));
System.out.println("Data Nascimento: " + sdf1.format(dtnasc));
System.out.println("Data Nascimento: " + sdf4.format(dtnasc));
}
}
|
package com.example.isvirin.storeclient.data.entity.daoconverter;
public enum CategoryType {
TEXT, LIST, PICTURE
}
|
package com.stackroute.pe2;
public class PalindromeChecker {
public String checkForPalindrome(int num) {
int temp = num;
int rev = 0;
int rem;
String result="";
while(temp > 0 || temp<0) {
rem = temp % 10;
rev = (rev * 10) + rem;
temp= temp/10;
}
if(num>0)
{
if (rev == num)
result="Number is Palindrome.";
else
result="Number not a Palindrome.";
}
else if(num<0) {
if (rev == num) {
result="Number is a Negative Palindrome.";
} else {
result="Number not a Palindrome";
}
}
return result;
}
}
|
package org.digdata.swustoj.model;
import java.util.Map;
public interface ModelOperation<T> {
public T addAttr(String key, Object value);
public T addAttrs(Map<String, Object> map);
public T deleteAttr(String key);
public T deleteAttrs(String... args);
}
|
import java.util.Scanner;
/**
RECITATION 5: CODING ACTIVITY #1:
JAVA PROGRAM THAT TAKES IN INFORMATION BETWEEN TWO STUDENTS, AND THEN COMPARES
THERE INFORMATION. THIS PROGRAM WAS PRACTICE FOR CONSTRUCTORS, CLASSES
OBJECTS, INSTANCE VARIABLES, INSTANCE METHODS. FINISHED ON 2/17/2021
*/
/**
* This is the coding activity class that takes in student info and compares them.
* @author mgebremariam7
* @version 1.2
*/
public class CodeActRFive {
/**
* This is the main method that takes in and prints out student info.
* @param args This is for the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type in your name, major, GTID, and year:");
GTStudent student1 = new GTStudent(scan.nextLine(), scan.nextLine(), scan.nextInt(), scan.nextInt());
System.out.println("Now just type in your name, then gtID:");
scan.nextLine();
String name2 = scan.nextLine();
int gt2 = scan.nextInt();
GTStudent student2 = new GTStudent(name2, gt2);
System.out.println(student1.toString());
System.out.println(student2.toString());
student1.compareGT(student2);
}
}
/**
*This is the GTStudent class which is used for student instance data.
* @author mgebremariam7
* @version 1.1
*/
class GTStudent {
private String name;
private String major;
private int gtID;
private int year;
public GTStudent() {
}
public GTStudent(String name, String major, int gtID, int year) {
this.name = name;
this.major = major;
this.gtID = gtID;
this.year = year;
}
public GTStudent(String name, int gtID) {
this.name = name;
this.gtID = gtID;
this.major = "Computer Science";
this.year = 1;
}
public GTStudent(GTStudent copyStudent) {
}
/**
*Getter for name variable.
* @return String representing name of student
*/
public String getName() {
return this.name;
}
/**
* Setter for name variable.
* @param name String representing name entered by user
*/
public void setName(String name) {
this.name = name;
}
/**
* Getter for major variable.
* @return String representing the major of student
*/
public String getMajor() {
return this.major;
}
/**
* Setter for major variable.
* @param major String representing a students major
*/
public void setMajor(String major) {
this.major = major;
}
/**
* Getter for gtID variable.
* @return int representing the student gtID number
*/
public int getGTID() {
return this.gtID;
}
/**
* Setter for the gtID variable.
* @param gtID int representing the students gtID number
*/
public void setGTID(int gtID) {
this.gtID = gtID;
}
/**
* Getter for year variable.
* @return int representing the students year
*/
public int getYear() {
return this.year;
}
/**
* Setter for year variable.
* @param year int representing the students year
*/
public void setYear(int year) {
this.year = year;
}
/**
* Method that returns all field data for an object as a string.
* @return String formatted field data for object
*/
public String toString() {
return String.format("name, major, gtID, year: %s, %s, %d, %d", name,major,gtID,year);
}
/**
* Method that takes in the two students and compares field data.
* @param student2 Object: the second student instance
*/
public void compareGT(GTStudent student2) {
if ((this.name).equals(student2.name)) {
System.out.println(this.name + " and " + student2.name
+ " have the same name!");
} else {
System.out.println(this.name + " and " + student2.name
+ " DO NOT have the same name!");
}
if ((this.major).equals(student2.getMajor())) {
System.out.println(this.name + " and " + student2.name
+ " have the same major -" + student2.major + "!");
} else {
System.out.println(this.name + " and " + student2.name
+ " DO NOT have the same major " + this.major + "!");
}
if (this.gtID == student2.gtID) {
System.out.println(this.name + " and " + student2.name
+ " have the same GTID!(Same student? X-files theme plays)");
} else {
System.out.println(this.name + " and " + student2.name
+ " DO NOT have the same GTID!(that seems about right)");
}
if (this.year == student2.year) {
System.out.println(this.name + " and " + student2.name
+ " have the same year!(theyre in this together!)");
} else {
System.out.println(this.name + " and " + student2.name
+ " DO NOT have the same year!(sad day bois)");
}
}
}
|
package panafana.example.panaf.wouldyourather;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
public class GenerateRandomName {
String finalname;
@RequiresApi(api = Build.VERSION_CODES.O)
GenerateRandomName(Context ctx, int choice) throws IOException {
// Open the file
ArrayList<String> maleNames = new ArrayList<String>();
ArrayList<String> femaleNames = new ArrayList<String>();
ArrayList<String> maleAdj = new ArrayList<String>();
ArrayList<String> femaleAdj = new ArrayList<String>();
AssetManager assets = ctx.getAssets();
InputStream is = assets.open("maleNames.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
maleNames.add(strLine);
}
//Close the input stream
br.close();
InputStream is2 = assets.open("maleAdj.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
String strLine2;
//Read File Line By Line
while ((strLine2 = br2.readLine()) != null) {
// Print the content on the console
maleAdj.add(strLine2);
//System.out.println(strLine2);
}
//Close the input stream
br2.close();
InputStream is3 = assets.open("femaleNames.txt");
BufferedReader br3 = new BufferedReader(new InputStreamReader(is3));
String strLine3;
//Read File Line By Line
while ((strLine3 = br3.readLine()) != null) {
// Print the content on the console
femaleNames.add(strLine3);
//System.out.println(strLine2);
}
//Close the input stream
br3.close();
InputStream is4 = assets.open("femaleAdj.txt");
BufferedReader br4 = new BufferedReader(new InputStreamReader(is4));
String strLine4;
//Read File Line By Line
while ((strLine4 = br4.readLine()) != null) {
// Print the content on the console
femaleAdj.add(strLine4);
//System.out.println(strLine2);
}
//Close the input stream
br4.close();
final int max,max2;
if(choice ==0){
max2 = maleAdj.size();
max = maleNames.size();
}else if (choice ==1 ){
max2 = femaleAdj.size();
max = femaleNames.size();
}else {
max2 = maleAdj.size();
max = maleNames.size();
}
final int min = 0;
final int randomName = new Random().nextInt((max - min) + 1) + min;
final int min2 = 0;
final int random2Surname = new Random().nextInt((max2 - min2) + 1) + min2;
String chosenName ;
String chosenAdj;
if(choice ==0){
chosenName = maleNames.get(randomName);
chosenAdj = maleAdj.get(random2Surname);
}else if (choice ==1 ){
chosenName = femaleNames.get(randomName);
chosenAdj = femaleAdj.get(random2Surname);
}else {
chosenName = maleNames.get(randomName);
chosenAdj = femaleAdj.get(random2Surname);
}
chosenName= chosenName.substring(0,1).toUpperCase()+chosenName.substring(1).toLowerCase();
chosenAdj = chosenAdj.substring(0,1).toUpperCase()+chosenAdj.substring(1).toLowerCase();
System.out.println("name "+chosenName);
System.out.println("adj "+chosenAdj);
byte[] temp = chosenAdj.getBytes();
System.out.println("adj2 "+(new String(temp,"UTF-8")));
finalname=chosenAdj+" "+chosenName;
}
String getName(){
return this.finalname;
}
}
|
package pl.calculator.repositoryRepresentation.json;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
public class HistoryJsonFormat {
public String getString(HashMap<Integer, ArrayList<String>> history) {
return new Gson().toJson(history);
}
}
|
public class Checker {
public boolean isDayOfWeek(String string) {
if (string.matches("mon|tue|wed|thu|fri|sat|sun")) {
return true;
}
return false;
}
public boolean allVowels(String string) {
if (string.matches("[a|i|e|o|u]*")) {
return true;
}
return false;
}
public boolean timeOfDay(String string) {
if(string.matches("(?:[01]\\d|2[0-3]):(?:[0-5]\\d):(?:[0-5]\\d)")) {
return true;
}
return false;
}
}
|
package practise.AppiumFramework;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.android.AndroidKeyCode;
import methods.Stockmethods;
import pageObjects.Login;
import pageObjects.StockButtons;
import pageObjects.portfolio;
import pageObjects.watchlist;
public class Stockapp4 extends base{
@Test
public void StockValidation() throws IOException, InterruptedException
{
ExcelDataConfig excel=new ExcelDataConfig("C:\\Users\\Satyawand\\Desktop\\appium\\framework\\AppiumFramework\\excel\\data1.xlsx");
service=startServer();
AndroidDriver<AndroidElement> driver=capabilities("stockapp");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Stockmethods mn = new Stockmethods();
mn.Login1();
Thread.sleep(1000);
StockButtons s = new StockButtons(driver);
watchlist w = new watchlist(driver);
w.findst.click();
w.search.sendKeys(excel.getData(0, 1, 0));
driver.hideKeyboard();
w.rel.click();
s.watchbtn.click();
s.imagebtn.click();
w.imgview.click();
w.search.sendKeys(excel.getData(0, 2, 0));
driver.hideKeyboard();
w.hdfc.click();
s.watchbtn.click();
s.imagebtn.click();
w.imgview.click();
w.search.sendKeys(excel.getData(0, 3, 0));
driver.hideKeyboard();
w.maruti.click();
s.watchbtn.click();
s.imagebtn.click();
w.imgview.click();
w.search.sendKeys(excel.getData(0, 4, 0));
driver.hideKeyboard();
w.polycab.click();
s.watchbtn.click();
s.imagebtn.click();
driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector()).scrollIntoView(text(\"Watchlist\"));");
driver.findElement(By.xpath("//*[@text='Watchlist']")).click();
mn.Validation1();
portfolio p = new portfolio(driver);
mn.BuyStocks();
driver.findElement(By.xpath("//*[@text='Portfolio']")).click();
mn.Validation2();
s.imagebtn.click();
p.Myaccount.click();
System.out.println( driver.findElement(By.id("com.alifesoftware.stocktrainer:id/totalPortfolioValue")).getText());
s.imagebtn.click();
driver.findElement(By.xpath("//*[@text='Portfolio']")).click();
mn.SellStocks();
driver.findElementByXPath("//*[@content-desc='Open navigation drawer']").click();
p.Myaccount.click();
System.out.println( driver.findElement(By.id("com.alifesoftware.stocktrainer:id/totalPortfolioValue")).getText());
}
}
|
// Name: Frederik V. Kjemtrup
// Student Email: fkjemt12@student.aau.dk
// Student Nr: 99055
package test;
import TwilightImperium.*;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Array;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
public class DemonstrationTests {
@Test
public void PlayerPropertiesCorrect() {
Player Crassus = new Player("Crassus", "The Emirates of Hacan", "Blue");
Player Pompey = new Player("Pompey", "Federation of Sol", "Red");
assertTrue(Crassus.getName() == "Crassus" && Crassus.getRace() == "The Emirates of Hacan" && Crassus
.getColor() == "Blue");
assertTrue(Pompey.getName() == "Pompey" && Pompey.getRace() == "Federation of Sol" && Pompey.
getColor() == "Red");
}
@Test
public void ShipPropertiesCorrect() {
Player Crassus = new Player("Crassus", "The Emirates of Hacan", "Blue");
Player Pompey = new Player("Pompey", "Federation of Sol", "Red");
// Crassus Ships initialised
ShipDestroyer CrassusDestroyer = new ShipDestroyer(Crassus);
ShipDreadnought CrassusDreadnoughtOne = new ShipDreadnought(Crassus);
ShipDreadnought CrassusDreadnoughtTwo = new ShipDreadnought(Crassus);
// Pompey ships initialised
ShipCruiser PompeyCruiserOne = new ShipCruiser(Pompey);
ShipCruiser PompeyCruiserTwo = new ShipCruiser(Pompey);
ShipCarrier PompeyCarrier = new ShipCarrier(Pompey);
// All ship properties (including ownership attributed in the constructor) have already been tested in
// ShipTests.java, so we may settle for testing that each of the six ships are ships of the proper type.
assertTrue(CrassusDestroyer instanceof ShipDestroyer &&
CrassusDreadnoughtOne instanceof ShipDreadnought &&
CrassusDreadnoughtTwo instanceof ShipDreadnought &&
PompeyCruiserOne instanceof ShipCruiser &&
PompeyCruiserTwo instanceof ShipCruiser &&
PompeyCarrier instanceof ShipCarrier);
}
@Test
public void DoSystemsHaveProperPlanets() {
// Building seven planets
Planet MecatolRex = new Planet("Mecatol Rex", 0);
Planet VegaMinor = new Planet("Vega Minor", 2);
Planet VegaMajor = new Planet("Vega Major", 3);
Planet Industrex = new Planet("Industrex", 6);
Planet RigelI = new Planet("Rigel I", 4);
Planet RigelII = new Planet("Rigel II", 5);
Planet Mirage = new Planet("Mirage", 1);
// Building ArrayLists to put planets in
ArrayList<Planet> CenterPlanets = new ArrayList<Planet>();
ArrayList<Planet> NorthPlanets = new ArrayList<Planet>();
ArrayList<Planet> NorthEastPlanets = new ArrayList<Planet>();
ArrayList<Planet> SouthEastPlanets = new ArrayList<Planet>();
ArrayList<Planet> SouthPlanets = new ArrayList<Planet>();
ArrayList<Planet> SouthWestPlanets = new ArrayList<Planet>();
ArrayList<Planet> NorthWestPlanets = new ArrayList<Planet>();
// Adding planets to relevant arraylists
CenterPlanets.add(MecatolRex);
NorthPlanets.add(VegaMajor);
NorthPlanets.add(VegaMinor);
SouthEastPlanets.add(Industrex);
SouthPlanets.add(RigelI);
SouthPlanets.add(RigelII);
NorthWestPlanets.add(Mirage);
// Building the seven systems as specified
SolarSystem CenterSystem = new SolarSystem("Center System", CenterPlanets, null);
SolarSystem NorthSystem = new SolarSystem("North System", NorthPlanets, null);
SolarSystem NorthEastSystem = new SolarSystem("North East System", NorthEastPlanets, null);
SolarSystem SouthEastSystem = new SolarSystem("South East System", SouthEastPlanets, null);
SolarSystem SouthSystem = new SolarSystem("South System", SouthPlanets, null);
SolarSystem SouthWestSystem = new SolarSystem("South West System", SouthWestPlanets, null);
SolarSystem NorthWestSystem = new SolarSystem("North West System", NorthWestPlanets, null);
// Test that each system has proper number of planets
assertTrue(CenterSystem.getPlanets().size() == 1 &&
NorthSystem.getPlanets().size() == 2 &&
NorthEastSystem.getPlanets().size() == 0 &&
SouthEastSystem.getPlanets().size() == 1 &&
SouthSystem.getPlanets().size() == 2 &&
SouthWestSystem.getPlanets().size() == 0 &&
NorthWestSystem.getPlanets().size() == 1);
// Test that each system has the expected planets
assertTrue(CenterSystem.getPlanets().get(0) == MecatolRex &&
NorthSystem.getPlanets().get(0) == VegaMajor &&
NorthSystem.getPlanets().get(1) == VegaMinor &&
SouthEastSystem.getPlanets().get(0) == Industrex &&
SouthSystem.getPlanets().get(0) == RigelI &&
SouthSystem.getPlanets().get(1) == RigelII &&
NorthWestSystem.getPlanets().get(0) == Mirage);
// The above two tests guarantee that only the specified planets are contained in a given system.
}
@Test
public void AreShipsInProperSystems() {
// We test that ships are where they need to be
// Players initialised
Player Crassus = new Player("Crassus", "The Emirates of Hacan", "Blue");
Player Pompey = new Player("Pompey", "Federation of Sol", "Red");
// Crassus Ships initialised
ShipDestroyer CrassusDestroyer = new ShipDestroyer(Crassus);
ShipDreadnought CrassusDreadnoughtOne = new ShipDreadnought(Crassus);
ShipDreadnought CrassusDreadnoughtTwo = new ShipDreadnought(Crassus);
// Pompey ships initialised
ShipCruiser PompeyCruiserOne = new ShipCruiser(Pompey);
ShipCruiser PompeyCruiserTwo = new ShipCruiser(Pompey);
ShipCarrier PompeyCarrier = new ShipCarrier(Pompey);
// Planet lists initialised
ArrayList<Planet> CenterPlanets = new ArrayList<Planet>();
ArrayList<Planet> NorthPlanets = new ArrayList<Planet>();
ArrayList<Planet> NorthEastPlanets = new ArrayList<Planet>();
ArrayList<Planet> SouthEastPlanets = new ArrayList<Planet>();
ArrayList<Planet> SouthPlanets = new ArrayList<Planet>();
ArrayList<Planet> SouthWestPlanets = new ArrayList<Planet>();
ArrayList<Planet> NorthWestPlanets = new ArrayList<Planet>();
// Initialising ship lists
ArrayList<ShipUnits> CenterShips = new ArrayList<ShipUnits>();
ArrayList<ShipUnits> NorthShips = new ArrayList<ShipUnits>();
ArrayList<ShipUnits> NorthEastShips = new ArrayList<ShipUnits>();
ArrayList<ShipUnits> SouthEastShips = new ArrayList<ShipUnits>();
ArrayList<ShipUnits> SouthShips = new ArrayList<ShipUnits>();
ArrayList<ShipUnits> SouthWestShips = new ArrayList<ShipUnits>();
ArrayList<ShipUnits> NorthWestShips = new ArrayList<ShipUnits>();
// Building systems first before adding ships with .AddShip() method
SolarSystem CenterSystem = new SolarSystem("Center System", CenterPlanets, CenterShips);
SolarSystem NorthSystem = new SolarSystem("North System", NorthPlanets, NorthShips);
SolarSystem NorthEastSystem = new SolarSystem("North East System", NorthEastPlanets, NorthEastShips);
SolarSystem SouthEastSystem = new SolarSystem("South East System", SouthEastPlanets, SouthEastShips);
SolarSystem SouthSystem = new SolarSystem("South System", SouthPlanets, SouthShips);
SolarSystem SouthWestSystem = new SolarSystem("South West System", SouthWestPlanets, SouthWestShips);
SolarSystem NorthWestSystem = new SolarSystem("North West System", NorthWestPlanets, NorthWestShips);
// Adding ships to proper systems
CenterSystem.AddShip(CrassusDestroyer);
CenterSystem.AddShip(CrassusDreadnoughtOne);
CenterSystem.AddShip(CrassusDreadnoughtTwo);
NorthSystem.AddShip(PompeyCarrier);
NorthSystem.AddShip(PompeyCruiserOne);
NorthSystem.AddShip(PompeyCruiserTwo);
// Test that each system has proper number of planets
assertTrue(CenterSystem.getShips().size() == 3 && NorthSystem.getShips().size() == 3);
// Test that each system has the expected Ships
assertTrue(CenterSystem.getShips().get(0) == CrassusDestroyer &&
CenterSystem.getShips().get(1) == CrassusDreadnoughtOne &&
CenterSystem.getShips().get(2) == CrassusDreadnoughtTwo &&
NorthSystem.getShips().get(0) == PompeyCarrier &&
NorthSystem.getShips().get(1) == PompeyCruiserOne &&
NorthSystem.getShips().get(2) == PompeyCruiserTwo);
// The above two tests guarantee that only the specified specified ships are contained in a given system.
// We have not tested whether other systems contain ships. This is possible, but we choose to
// disregard the eventuality.
}
// Having manually checked our implementation each step of the way, we are now ready to write the smallest test
// input with the most important assertion to test:
@Test
public void IsGalaxyBuilt() {
Galaxy TestGalaxy = Demonstration.ProblemSeven();
assertTrue(TestGalaxy instanceof Galaxy);
assertTrue(TestGalaxy.getContainedShips().size() == 6); // Correct number of ships included
assertTrue(TestGalaxy.getContainedPlanets().size() == 7); // Ditto for planets
}
}
|
package com.caio.localiza.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.caio.localiza.domain.Carro;
@Repository //Anotação de repositório //Tipo de objeto, tipo do identificador
public interface CarroRepository extends JpaRepository<Carro, Integer> {
//Interface, classe que não pode ser instanciada diretamente
}
|
package com.tianwotian.mytaobao.bean;
/**
* Created by user on 2016/9/2.
*/
public class LoginFailed {
String error;
String errorName;
public String getError(){
return error;
}
public String getErrorName(){
return errorName;
}
}
|
package com.mygdx.game.tetris;
/**
* Created by kyozanuro on 3/25/2017.
*/
public class TouchScreenInputHandler {
}
|
package com.ketanbd.moviecatalogservice.com.ketanbd.model;
import java.util.List;
public class Movie {
private String moviename;
private float rating;
private int releaseYear;
private List<String> tags;
//Constructor
public Movie(String moviename, float rating, int releaseYear, List<String> tags) {
this.moviename = moviename;
this.rating = rating;
this.releaseYear = releaseYear;
this.tags = tags;
}
//Getters
public String getMoviename() {
return moviename;
}
public float getRating() {
return rating;
}
public int getReleaseYear() {
return releaseYear;
}
public List<String> getTags() {
return tags;
}
//Setters
public void setMoviename(String moviename) {
this.moviename = moviename;
}
public void setRating(float rating) {
this.rating = rating;
}
public void setReleaseYear(int releaseYear) {
this.releaseYear = releaseYear;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
}
|
/** A type to represent a generic shape */
public abstract class Shape {
/** returns the area of the shape */
public abstract double area();
/** returns the perimeter of the shape */
public abstract double perimeter();
/** compare the area of this shape to the input shape */
public boolean isLargerThan(Shape s) {
return this.area() > s.area();
}
}
|
package com.gxjtkyy.standardcloud.common.domain.vo;
import lombok.Data;
/**
* 附录ID
* @Package com.gxjtkyy.standardcloud.common.domain.vo
* @Author lizhenhua
* @Date 2018/6/28 17:08
*/
@Data
public class AttachVO extends BaseVO{
/**id*/
private String id;
/**附录名称*/
private String attachName;
/**url*/
private String url;
}
|
package com.java.learning.myoverloading;
public class MyRunClass {
public static void main(String[] args) {
Student std = new Student();
std.print(90, 75, 89);
std.print();
std.print('A', 'B');
}
}
|
package observer;
import observer.headhunter.JavaDeveloperJobsSite;
import observer.headhunter.Subscriber;
import observer.headhunter.interfaces.Observer;
/**
* Определяет отношение "один ко многим" между объектами таким образом, что изменение состояние одного объекта
* автоматически оповещает и обновляет все его зависимости. При этом наблюдатели могут свободно подписываться и
* отписываться от этих оповещений, а так же реализовывать какую то логику при получении оповещения. Шаблон оччень
* распространен в стандартных библиотеках java и различных фреймворках.
* Практически все классы, в названиях которых есть Listener относятся к этому шаблону.
*
* Реализация:
* 1.Необходимо разделить функциональность на две части, независимое ядро, которое станет наблюдаемым и опциональрные
* зависимые части, которые будут налюдателями.
* 2.Для наблюдателей выделить общий интерфейс, в котором необходимо описать метод оповещения.
* 3.Создать интерфейс для наблюдаемого класса, в нем необходимо описать методы оповещения, регистрации и снятия с
* регистрации наблюдателей. Такой интерфейс должен работать только с общим интерфейсом подписчиков.
* 4.Написать класс реализующий интерфейс наблюдаемого объекта, методы необходимо реализвать так, что бы после каждого
* изменения состояния они слали оповещения зарегистрированным наблюдателям.
* 5.Реализовать конкретных наблюдателей и метод получения обновления. Возможно это будут какие то параметры, через
* которые наблюдаемый объект сможет отправлять какие то данные наблюдателям, либо наблюдатель, получив оповещение, сам
* возьмёт из наблюдаемого объекта нужные данные.
* 6.Клиент сам создает необходимых наблюдателей и регистрирует у наблюдаемого объекта.
*
* @author Vladimir Ryazanov (v.ryazanov13@gmail.com)
*/
public class Example {
public static void main(String[] args) {
//Данный объект будет наблюдаемым
JavaDeveloperJobsSite javaDeveloperJobsSite = new JavaDeveloperJobsSite();
javaDeveloperJobsSite.addVacancy("Junior Java Developer");
javaDeveloperJobsSite.addVacancy("Middle Java Developer");
//Создаем 2 объекта наблюдателей
Observer firstObserver = new Subscriber("Ivan");
Observer secondObserver = new Subscriber("Vova");
//Регистрируем наблюдателей у наблюдаемого
javaDeveloperJobsSite.addObserver(firstObserver);
javaDeveloperJobsSite.addObserver(secondObserver);
//При добавлении вакансии происходит автоматическое оповещение наблюдателей
javaDeveloperJobsSite.addVacancy("Senior Java Developer");
//При удалении вакансии так же происходит автоматическое оповещение
javaDeveloperJobsSite.removeVacancy("Junior Java Developer");
//Снимаем с регистрации первого наблюдателя
javaDeveloperJobsSite.removeObserver(firstObserver);
//Теперь оповещение получает только второй наблюдатель
javaDeveloperJobsSite.addVacancy("Senior Java Developer");
}
}
|
package com.t11e.discovery.datatool;
public class NoSuchProfileException
extends RuntimeException
{
private static final long serialVersionUID = 4612076116278889313L;
public NoSuchProfileException(final String name)
{
super("No profile with name: " + name);
}
}
|
public class Selectionsort {
public static int[] selectionsort(int [] array)
{
int index,temp;
for(int i=0;i<array.length-1;i++)
{
index=i;
for (int j=i+1;j<array.length;j++)
{
if(array[j]<array[i])
index=j;
}
temp=array[index];
array[index]=array[i];
array[i]=temp;
}
return array;
}
public static void main(String[] args)
{
int [] array={10,20,34,56,2,88,45};
int [] sortedarray=selectionsort(array);
for (int i=0;i<sortedarray.length;i++)
{
System.out.print(sortedarray[i]+" ,");
}
System.out.println("\n");
}
}
|
package net.maizegenetics.analysis.imputation;
import java.util.HashMap;
import net.maizegenetics.taxa.Taxon;
public class SubpopulationFinder {
final static HashMap<String, Integer> taxaToPopMap = new HashMap<String, Integer>();
static {
taxaToPopMap.put("Z001E0215",0);
taxaToPopMap.put("Z001E0229",0);
taxaToPopMap.put("Z001E0262",2);
taxaToPopMap.put("Z001E0274",2);
taxaToPopMap.put("Z001E0279",2);
taxaToPopMap.put("Z002E0207",0);
taxaToPopMap.put("Z002E0217",0);
taxaToPopMap.put("Z002E0271",2);
taxaToPopMap.put("Z003E0212",0);
taxaToPopMap.put("Z003E0220",0);
taxaToPopMap.put("Z003E0264",2);
taxaToPopMap.put("Z003E0266",2);
taxaToPopMap.put("Z003E0272",2);
taxaToPopMap.put("Z004E0208",0);
taxaToPopMap.put("Z004E0232",1);
taxaToPopMap.put("Z005E0204",0);
taxaToPopMap.put("Z005E0210",0);
taxaToPopMap.put("Z005E0211",0);
taxaToPopMap.put("Z005E0212",0);
taxaToPopMap.put("Z005E0213",0);
taxaToPopMap.put("Z005E0215",0);
taxaToPopMap.put("Z005E0233",1);
taxaToPopMap.put("Z005E0249",1);
taxaToPopMap.put("Z005E0267",2);
taxaToPopMap.put("Z005E0269",2);
taxaToPopMap.put("Z005E0270",2);
taxaToPopMap.put("Z006E0203",0);
taxaToPopMap.put("Z006E0204",0);
taxaToPopMap.put("Z006E0206",0);
taxaToPopMap.put("Z006E0215",0);
taxaToPopMap.put("Z006E0216",0);
taxaToPopMap.put("Z006E0219",0);
taxaToPopMap.put("Z006E0224",0);
taxaToPopMap.put("Z006E0225",0);
taxaToPopMap.put("Z006E0226",0);
taxaToPopMap.put("Z006E0228",0);
taxaToPopMap.put("Z006E0232",1);
taxaToPopMap.put("Z006E0233",1);
taxaToPopMap.put("Z006E0245",1);
taxaToPopMap.put("Z006E0255",1);
taxaToPopMap.put("Z007E0213",0);
taxaToPopMap.put("Z007E0217",0);
taxaToPopMap.put("Z007E0219",0);
taxaToPopMap.put("Z007E0223",0);
taxaToPopMap.put("Z007E0230",1);
taxaToPopMap.put("Z007E0284",2);
taxaToPopMap.put("Z008E0253",1);
taxaToPopMap.put("Z008E0261",2);
taxaToPopMap.put("Z009E0214",0);
taxaToPopMap.put("Z009E0219",0);
taxaToPopMap.put("Z009E0223",0);
taxaToPopMap.put("Z009E0243",1);
taxaToPopMap.put("Z009E0257",2);
taxaToPopMap.put("Z009E0259",2);
taxaToPopMap.put("Z009E0266",2);
taxaToPopMap.put("Z009E0284",2);
taxaToPopMap.put("Z010E0214",0);
taxaToPopMap.put("Z010E0267",2);
taxaToPopMap.put("Z010E0280",2);
taxaToPopMap.put("Z010E0283",2);
taxaToPopMap.put("Z011E0217",0);
taxaToPopMap.put("Z011E0226",0);
taxaToPopMap.put("Z011E0230",1);
taxaToPopMap.put("Z012E0231",1);
taxaToPopMap.put("Z012E0260",2);
taxaToPopMap.put("Z012E0278",2);
taxaToPopMap.put("Z013E0204",2);
taxaToPopMap.put("Z013E0207",2);
taxaToPopMap.put("Z013E0208",0);
taxaToPopMap.put("Z013E0211",0);
taxaToPopMap.put("Z013E0218",0);
taxaToPopMap.put("Z013E0221",2);
taxaToPopMap.put("Z013E0222",0);
taxaToPopMap.put("Z013E0224",2);
taxaToPopMap.put("Z013E0225",2);
taxaToPopMap.put("Z013E0226",0);
taxaToPopMap.put("Z013E0227",2);
taxaToPopMap.put("Z013E0228",2);
taxaToPopMap.put("Z013E0229",2);
taxaToPopMap.put("Z013E0231",2);
taxaToPopMap.put("Z013E0232",2);
taxaToPopMap.put("Z013E0233",2);
taxaToPopMap.put("Z013E0234",2);
taxaToPopMap.put("Z013E0235",2);
taxaToPopMap.put("Z013E0236",2);
taxaToPopMap.put("Z013E0238",2);
taxaToPopMap.put("Z013E0239",2);
taxaToPopMap.put("Z013E0240",2);
taxaToPopMap.put("Z013E0241",2);
taxaToPopMap.put("Z013E0242",1);
taxaToPopMap.put("Z013E0247",1);
taxaToPopMap.put("Z013E0249",2);
taxaToPopMap.put("Z013E0250",2);
taxaToPopMap.put("Z013E0251",2);
taxaToPopMap.put("Z013E0253",2);
taxaToPopMap.put("Z013E0256",2);
taxaToPopMap.put("Z013E0285",2);
taxaToPopMap.put("Z013E0286",2);
taxaToPopMap.put("Z013E0287",2);
taxaToPopMap.put("Z013E0288",2);
taxaToPopMap.put("Z013E0289",2);
taxaToPopMap.put("Z013E0290",2);
taxaToPopMap.put("Z013E0291",2);
taxaToPopMap.put("Z013E0292",2);
taxaToPopMap.put("Z013E0293",2);
taxaToPopMap.put("Z013E0294",2);
taxaToPopMap.put("Z013E0295",2);
taxaToPopMap.put("Z013E0296",2);
taxaToPopMap.put("Z013E0297",2);
taxaToPopMap.put("Z013E0298",2);
taxaToPopMap.put("Z013E0299",2);
taxaToPopMap.put("Z013E0300",2);
taxaToPopMap.put("Z013E0301",2);
taxaToPopMap.put("Z013E0302",2);
taxaToPopMap.put("Z013E0303",2);
taxaToPopMap.put("Z013E0304",2);
taxaToPopMap.put("Z013E0305",2);
taxaToPopMap.put("Z013E0306",2);
taxaToPopMap.put("Z013E0307",2);
taxaToPopMap.put("Z013E0308",2);
taxaToPopMap.put("Z013E0309",2);
taxaToPopMap.put("Z013E0310",2);
taxaToPopMap.put("Z013E0311",2);
taxaToPopMap.put("Z013E0312",2);
taxaToPopMap.put("Z013E0313",2);
taxaToPopMap.put("Z013E0314",2);
taxaToPopMap.put("Z013E0315",2);
taxaToPopMap.put("Z013E0316",2);
taxaToPopMap.put("Z013E0317",2);
taxaToPopMap.put("Z013E0318",2);
taxaToPopMap.put("Z013E0319",2);
taxaToPopMap.put("Z013E0320",2);
taxaToPopMap.put("Z013E0321",2);
taxaToPopMap.put("Z013E0322",2);
taxaToPopMap.put("Z013E0323",2);
taxaToPopMap.put("Z013E0324",2);
taxaToPopMap.put("Z014E0206",0);
taxaToPopMap.put("Z014E0208",0);
taxaToPopMap.put("Z014E0259",2);
taxaToPopMap.put("Z015E0203",0);
taxaToPopMap.put("Z015E0204",1);
taxaToPopMap.put("Z015E0230",1);
taxaToPopMap.put("Z015E0232",1);
taxaToPopMap.put("Z015E0235",1);
taxaToPopMap.put("Z015E0237",1);
taxaToPopMap.put("Z015E0238",1);
taxaToPopMap.put("Z015E0242",1);
taxaToPopMap.put("Z015E0243",1);
taxaToPopMap.put("Z015E0282",2);
taxaToPopMap.put("Z016E0213",0);
taxaToPopMap.put("Z016E0220",0);
taxaToPopMap.put("Z016E0238",1);
taxaToPopMap.put("Z016E0251",1);
taxaToPopMap.put("Z016E0254",1);
taxaToPopMap.put("Z016E0274",2);
taxaToPopMap.put("Z018E0220",0);
taxaToPopMap.put("Z018E0223",0);
taxaToPopMap.put("Z018E0228",0);
taxaToPopMap.put("Z018E0273",2);
taxaToPopMap.put("Z019E0209",0);
taxaToPopMap.put("Z019E0226",0);
taxaToPopMap.put("Z019E0263",2);
taxaToPopMap.put("Z020E0208",0);
taxaToPopMap.put("Z020E0232",1);
taxaToPopMap.put("Z020E0234",1);
taxaToPopMap.put("Z020E0270",2);
taxaToPopMap.put("Z020E0281",2);
taxaToPopMap.put("Z021E0205",0);
taxaToPopMap.put("Z021E0216",0);
taxaToPopMap.put("Z021E0235",1);
taxaToPopMap.put("Z021E0239",1);
taxaToPopMap.put("Z021E0241",1);
taxaToPopMap.put("Z021E0270",2);
taxaToPopMap.put("Z021E0275",2);
taxaToPopMap.put("Z021E0278",2);
taxaToPopMap.put("Z021E0283",2);
taxaToPopMap.put("Z022E0207",0);
taxaToPopMap.put("Z022E0215",0);
taxaToPopMap.put("Z022E0219",0);
taxaToPopMap.put("Z022E0221",0);
taxaToPopMap.put("Z022E0272",2);
taxaToPopMap.put("Z023E0217",0);
taxaToPopMap.put("Z023E0225",0);
taxaToPopMap.put("Z023E0229",0);
taxaToPopMap.put("Z023E0230",1);
taxaToPopMap.put("Z023E0231",1);
taxaToPopMap.put("Z023E0265",2);
taxaToPopMap.put("Z023E0269",2);
taxaToPopMap.put("Z023E0272",2);
taxaToPopMap.put("Z023E0274",2);
taxaToPopMap.put("Z024E0203",0);
taxaToPopMap.put("Z024E0205",0);
taxaToPopMap.put("Z024E0212",0);
taxaToPopMap.put("Z024E0258",2);
taxaToPopMap.put("Z024E0264",2);
taxaToPopMap.put("Z024E0268",2);
taxaToPopMap.put("Z024E0273",2);
taxaToPopMap.put("Z024E0276",2);
taxaToPopMap.put("Z024E0282",2);
taxaToPopMap.put("Z024E0287",2);
taxaToPopMap.put("Z024E0289",2);
taxaToPopMap.put("Z025E0211",0);
taxaToPopMap.put("Z025E0213",0);
taxaToPopMap.put("Z025E0218",0);
taxaToPopMap.put("Z025E0226",0);
taxaToPopMap.put("Z025E0238",1);
taxaToPopMap.put("Z025E0245",1);
taxaToPopMap.put("Z025E0246",1);
taxaToPopMap.put("Z025E0250",1);
taxaToPopMap.put("Z025E0270",2);
taxaToPopMap.put("Z026E0222",0);
taxaToPopMap.put("Z026E0225",0);
taxaToPopMap.put("Z026E0230",1);
taxaToPopMap.put("Z026E0231",1);
taxaToPopMap.put("Z026E0232",1);
taxaToPopMap.put("Z026E0263",2);
taxaToPopMap.put("Z026E0269",2);
taxaToPopMap.put("Z026E0277",2);
taxaToPopMap.put("Z026E0280",2);
}
public static int getNamSubPopulation(String taxonname) {
String shortname;
int colonpos = taxonname.indexOf(':');
if (colonpos < 0) shortname = taxonname;
else shortname = taxonname.substring(0, colonpos);
int entry = Integer.parseInt(shortname.substring(5, 9));
if (entry < 68) return 0;
else if (entry < 135) return 1;
else if (entry < 201) return 2;
Integer pop = taxaToPopMap.get(shortname);
if (pop == null) return -1;
else return pop;
}
public static int getNamSubPopulation(Taxon taxon) {
return getNamSubPopulation(taxon.getName());
}
}
|
/*
* 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 rs.ac.bg.fon.ps.domain;
import java.io.Serializable;
import java.util.Objects;
/**
*
* @author Mr OLOGIZ
*/
public class PripadnostGrupama implements Serializable{
private Grupa grupa;
private NalogClana nalogClana;
public PripadnostGrupama() {
}
public PripadnostGrupama(Grupa grupa, NalogClana nalogClana) {
this.grupa = grupa;
this.nalogClana = nalogClana;
}
public NalogClana getNalogClana() {
return nalogClana;
}
public void setNalogClana(NalogClana nalogClana) {
this.nalogClana = nalogClana;
}
public Grupa getGrupa() {
return grupa;
}
public void setGrupa(Grupa grupa) {
this.grupa = grupa;
}
@Override
public String toString() {
return "PripadnostGrupama{" + "grupa=" + grupa + ", nalogClana=" + nalogClana + '}';
}
@Override
public int hashCode() {
int hash = 3;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final PripadnostGrupama other = (PripadnostGrupama) obj;
if (!Objects.equals(this.grupa, other.grupa)) {
return false;
}
if (!Objects.equals(this.nalogClana, other.nalogClana)) {
return false;
}
return true;
}
}
|
/**
*
*/
package com.jspmyadmin.app.table.export.logic;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.jspmyadmin.app.table.export.beans.ExportBean;
import com.jspmyadmin.framework.connection.AbstractLogic;
import com.jspmyadmin.framework.connection.ApiConnection;
import com.jspmyadmin.framework.constants.Constants;
import com.jspmyadmin.framework.web.utils.Bean;
/**
* @author Yugandhar Gangu
* @created_at 2016/07/27
*
*/
public class ExportLogic extends AbstractLogic {
/**
*
* @param bean
* @throws SQLException
* @throws IOException
*/
public void fillBean(Bean bean) throws SQLException {
ExportBean exportBean = (ExportBean) bean;
ApiConnection apiConnection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
ResultSetMetaData metaData = null;
StringBuilder builder = null;
try {
apiConnection = getConnection(bean.getRequest_db());
builder = new StringBuilder();
builder.append("SELECT * FROM `");
builder.append(bean.getRequest_table());
builder.append("` WHERE 1 = 2");
statement = apiConnection.getStmtSelect(builder.toString());
resultSet = statement.executeQuery();
metaData = resultSet.getMetaData();
String[] column_list = new String[metaData.getColumnCount()];
for (int i = 0; i < metaData.getColumnCount(); i++) {
column_list[i] = metaData.getColumnName(i + 1);
}
exportBean.setColumn_list(column_list);
} finally {
close(resultSet);
close(statement);
close(apiConnection);
}
}
/**
*
* @param bean
* @throws SQLException
* @throws IOException
* @throws ClassNotFoundException
* @throws ParserConfigurationException
* @throws TransformerException
* @throws JSONException
*/
public File exportFile(Bean bean) throws SQLException, IOException, ClassNotFoundException,
ParserConfigurationException, TransformerException, JSONException {
ExportBean exportBean = (ExportBean) bean;
ApiConnection apiConnection = null;
PreparedStatement statement = null;
PreparedStatement hexStatement = null;
ResultSet hexResultSet = null;
ResultSet resultSet = null;
StringBuilder builder = null;
File file = null;
FileOutputStream fileOutputStream = null;
OutputStreamWriter outputStreamWriter = null;
BufferedWriter bufferedWriter = null;
try {
apiConnection = getConnection(bean.getRequest_db());
builder = new StringBuilder("SELECT ");
for (int i = 0; i < exportBean.getColumn_list().length; i++) {
if (i != 0) {
builder.append(Constants.SYMBOL_COMMA);
}
builder.append(Constants.SYMBOL_TEN);
builder.append(exportBean.getColumn_list()[i]);
builder.append(Constants.SYMBOL_TEN);
}
builder.append(" FROM `");
builder.append(bean.getRequest_table());
builder.append(Constants.SYMBOL_TEN);
statement = apiConnection.getStmtSelect(builder.toString());
resultSet = statement.executeQuery();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
file = new File(super.getTempFilePath());
file.setExecutable(true, false);
file.setReadable(true, false);
file.setWritable(true, false);
fileOutputStream = new FileOutputStream(file);
outputStreamWriter = new OutputStreamWriter(fileOutputStream);
bufferedWriter = new BufferedWriter(outputStreamWriter);
if (Constants.CSV.equalsIgnoreCase(exportBean.getExport_type())) {
// 0 - string, 1 - number, 2 - binary
int[] typeMap = new int[exportBean.getColumn_list().length];
for (int i = 0; i < exportBean.getColumn_list().length; i++) {
if (i != 0) {
bufferedWriter.write(Constants.SYMBOL_COMMA);
}
bufferedWriter.write(Constants.SYMBOL_DOUBLE_QUOTE);
bufferedWriter.write(exportBean.getColumn_list()[i]);
bufferedWriter.write(Constants.SYMBOL_DOUBLE_QUOTE);
String className = resultSetMetaData.getColumnClassName(i + 1);
if (Constants.BYTE_TYPE.equals(className)) {
typeMap[i] = 2;
} else {
typeMap[i] = 1;
}
}
while (resultSet.next()) {
bufferedWriter.newLine();
for (int i = 0; i < exportBean.getColumn_list().length; i++) {
if (i != 0) {
bufferedWriter.write(Constants.SYMBOL_COMMA);
}
bufferedWriter.write(Constants.SYMBOL_DOUBLE_QUOTE);
if (typeMap[i] == 2) {
byte[] byteValue = resultSet.getBytes(i + 1);
if (byteValue != null) {
hexStatement = apiConnection.getStmtSelect("SELECT HEX(?) FROM DUAL");
hexStatement.setBytes(1, byteValue);
hexResultSet = hexStatement.executeQuery();
hexResultSet.next();
bufferedWriter.write(Constants.SYMBOL_HEX);
bufferedWriter.write(hexResultSet.getString(1));
close(hexResultSet);
close(hexStatement);
} else {
bufferedWriter.write(Constants.NULL);
}
} else {
String value = resultSet.getString(i + 1);
if (value != null) {
bufferedWriter.write(value);
} else {
bufferedWriter.write(Constants.NULL);
}
}
bufferedWriter.write(Constants.SYMBOL_DOUBLE_QUOTE);
}
}
} else if (Constants.XML.equalsIgnoreCase(exportBean.getExport_type())) {
// 0 - string, 1 - number, 2 - binary
int[] typeMap = new int[exportBean.getColumn_list().length];
for (int i = 0; i < exportBean.getColumn_list().length; i++) {
String className = resultSetMetaData.getColumnClassName(i + 1);
if (Constants.BYTE_TYPE.equals(className)) {
typeMap[i] = 2;
} else {
Class<?> klass = Class.forName(className);
if (klass == Short.class || klass == Integer.class || klass == Long.class
|| klass == Boolean.class || klass == Float.class || klass == Double.class
|| klass == BigDecimal.class || klass == BigInteger.class) {
typeMap[i] = 1;
} else {
typeMap[i] = 0;
}
}
}
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement(Constants.JSPMYADMIN_EXPORT);
rootElement.setAttribute(Constants.DATABASE, exportBean.getRequest_db());
rootElement.setAttribute(Constants.TABLE, exportBean.getRequest_table());
document.appendChild(rootElement);
Element rowsElement = document.createElement(Constants.DATA);
rootElement.appendChild(rowsElement);
int count = 1;
while (resultSet.next()) {
Element rowElement = document.createElement(Constants.ROW);
rowElement.setAttribute(Constants.COUNT, String.valueOf(count++));
for (int i = 0; i < exportBean.getColumn_list().length; i++) {
Element columnElement = document.createElement(Constants.COLUMN);
columnElement.setAttribute(Constants.NAME, resultSetMetaData.getColumnName(i + 1));
switch (typeMap[i]) {
case 2:
columnElement.setAttribute(Constants.TYPE, Constants.BINARY);
byte[] byteValue = resultSet.getBytes(i + 1);
if (byteValue != null) {
hexStatement = apiConnection.getStmtSelect("SELECT HEX(?) FROM DUAL");
hexStatement.setBytes(1, byteValue);
hexResultSet = hexStatement.executeQuery();
hexResultSet.next();
columnElement.appendChild(document.createTextNode(hexResultSet.getString(1)));
close(hexResultSet);
close(hexStatement);
} else {
columnElement.appendChild(document.createTextNode(Constants.NULL));
}
break;
case 1:
columnElement.setAttribute(Constants.TYPE, Constants.NUMBER);
String value = resultSet.getString(i + 1);
if (value != null) {
columnElement.appendChild(document.createTextNode(value));
} else {
columnElement.appendChild(document.createTextNode(Constants.NULL));
}
break;
default:
columnElement.setAttribute(Constants.TYPE, Constants.STRING);
value = resultSet.getString(i + 1);
if (value != null) {
columnElement.appendChild(document.createTextNode(value));
} else {
columnElement.appendChild(document.createTextNode(Constants.NULL));
}
break;
}
rowElement.appendChild(columnElement);
}
rowsElement.appendChild(rowElement);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, Constants.YES.toLowerCase());
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(bufferedWriter);
transformer.transform(domSource, streamResult);
} else if (Constants.JSON.equalsIgnoreCase(exportBean.getExport_type())) {
// 0 - string, 1 - number, 2 - binary
int[] typeMap = new int[exportBean.getColumn_list().length];
for (int i = 0; i < exportBean.getColumn_list().length; i++) {
String className = resultSetMetaData.getColumnClassName(i + 1);
if (Constants.BYTE_TYPE.equals(className)) {
typeMap[i] = 2;
} else {
Class<?> klass = Class.forName(className);
if (klass == Short.class || klass == Integer.class || klass == Long.class
|| klass == Boolean.class || klass == Float.class || klass == Double.class
|| klass == BigDecimal.class || klass == BigInteger.class) {
typeMap[i] = 1;
} else {
typeMap[i] = 0;
}
}
}
bufferedWriter.write("[");
JSONObject jsonObject = new JSONObject();
jsonObject.put(Constants.TYPE, Constants.METADATA);
jsonObject.put(Constants.DATABASE, exportBean.getRequest_db());
jsonObject.put(Constants.TABLE, exportBean.getRequest_table());
bufferedWriter.write(jsonObject.toString());
bufferedWriter.write(Constants.SYMBOL_COMMA);
bufferedWriter.newLine();
bufferedWriter.write("{\"type\":\"data\",\"value\":[");
bufferedWriter.newLine();
while (resultSet.next()) {
jsonObject = new JSONObject();
for (int i = 0; i < exportBean.getColumn_list().length; i++) {
String value = null;
switch (typeMap[i]) {
case 2:
byte[] byteValue = resultSet.getBytes(i + 1);
if (byteValue != null) {
hexStatement = apiConnection.getStmtSelect("SELECT HEX(?) FROM DUAL");
hexStatement.setBytes(1, byteValue);
hexResultSet = hexStatement.executeQuery();
hexResultSet.next();
value = Constants.SYMBOL_HEX + hexResultSet.getString(1);
close(hexResultSet);
close(hexStatement);
}
break;
case 1:
default:
value = resultSet.getString(i + 1);
break;
}
if (value != null) {
jsonObject.put(resultSetMetaData.getColumnName(i + 1), value);
} else {
jsonObject.put(resultSetMetaData.getColumnName(i + 1), Constants.NULL);
}
}
bufferedWriter.write(jsonObject.toString());
bufferedWriter.write(Constants.SYMBOL_COMMA);
bufferedWriter.newLine();
}
bufferedWriter.write("]}]");
}
} finally {
close(bufferedWriter);
close(outputStreamWriter);
close(fileOutputStream);
close(hexResultSet);
close(hexStatement);
close(resultSet);
close(statement);
close(apiConnection);
}
return file;
}
}
|
package LeetCode;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public static void main(String[] args) {
}
/*
* Idea: map the values and indices. On iteration check to see if the target-num is key in the map
* -> return the indices of num and target-num
*
* O(N)
* */
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>(); //map val to index
int[] ans = new int[2];
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
ans[0] = map.get(target-nums[i]);
ans[1] = i;
} else {
map.put(nums[i], i);
}
}
return ans;
}
}
|
package com.zantong.mobilecttx.api;
import com.zantong.mobilecttx.base.bean.BaseResult;
import com.zantong.mobilecttx.card.dto.BindCarDTO;
import com.zantong.mobilecttx.home.bean.HomeResult;
import com.zantong.mobilecttx.home.dto.HomeDataDTO;
import retrofit2.http.Body;
import retrofit2.http.POST;
import rx.Observable;
/**
* Created by jianghw on 2017/4/26.
* 服务器接口
*/
public interface ICttxService {
/**
* 1.首页信息
*/
@POST("cttx/homePage")
Observable<HomeResult> homePage(@Body HomeDataDTO id);
/**
* 48.绑定行驶证接口
*/
@POST("cttx/bindingVehicle")
Observable<BaseResult> commitCarInfoToNewServer(@Body BindCarDTO bindCarDTO);
}
|
public class Outcast {
private final WordNet wordNet;
public Outcast(WordNet wordnet) {
this.wordNet = wordnet;
}
public String outcast(String[] nouns) {
String outcast = null;
int maxDistance = 0;
for (String noun : nouns) {
int currentDistance = 0;
for (String otherNoun : nouns) {
int distance = wordNet.distance(noun, otherNoun);
currentDistance += distance;
}
if (currentDistance > maxDistance) {
maxDistance = currentDistance;
outcast = noun;
}
}
return outcast;
}
}
|
package com.syl.orders.feign;
import com.codingapi.txlcn.tc.support.DTXUserControls;
import com.syl.model.goods.Goods;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class GoodsServiceFallback implements GoodsFeign{
public List<Goods> get(){
return new ArrayList<>();
}
@Override
public int reduceStock(List<Goods> goodsList) {
DTXUserControls.rollbackCurrentGroup(); //只需换一下回滚API就可以了
return 100;
}
}
|
package com.example.demo.model;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Logger;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import javassist.bytecode.ByteArray;
import javassist.bytecode.stackmap.TypeData;
import org.apache.commons.io.IOUtils;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import javax.imageio.ImageIO;
public class QRCodeGenerator {
public static void generateQRCodeImage(String text, int width, int height, String filePath)
throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
// Path path = FileSystems.getDefault().getPath(filePath);
Path path5 = Paths.get("D:\\picSpring\\QRcode_"+ text+".png");
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path5);
}
public static byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
Path path5 = Paths.get("D:\\picSpring\\pongQRcode_"+ text+".png");
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path5);
//ห้ามลบของเก่า ก่อนเอาภาพจากเครื่อง
// ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
// MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
// byte[] pngData = pngOutputStream.toByteArray();
// return pngData;
BufferedImage image = ImageIO.read(new File("D:\\picSpring\\QRcode_"+text+".png"));
//
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] bytes = baos.toByteArray();
return bytes;
}
// public ResponseEntity<Byte[]> getImagePok() {
// try {
// Path file = Paths.get("D:\\picSpring\\").resolve("QRcode_pokas_1998@hotmail.com.png");
// Resource resource = new UrlResource(file.toUri());
// if (resource.exists() || resource.isReadable()) {
// Byte[] byteArray = StreamUtils.copyToByteArray(resource.getInputStream());
//
// return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(byteArray);
//
// } else {
// throw new RuntimeException("error");
//
// }
//
// } catch (MalformedURLException e) {
// e.printStackTrace();
// return null;
// }
// }
}
|
package com.touchtrip.main.model.service;
import static com.touchtrip.common.JDBCTemplate.*;
import java.sql.Connection;
import java.util.ArrayList;
import com.touchtrip.main.model.dao.MainDAO;
import com.touchtrip.main.model.vo.MainAllFamous;
import com.touchtrip.main.model.vo.MainTop6Famous;
public class IntroToMainService {
private Connection con;
private MainDAO dao = new MainDAO();
public ArrayList<MainTop6Famous> selectTop6Famous() {
con = getConnection();
ArrayList<MainTop6Famous> listTop6 = new ArrayList<>();
listTop6 = dao.selectTop6Famous(con);
return listTop6;
}
public ArrayList<MainAllFamous> selectAllFamous() {
con = getConnection();
ArrayList<MainAllFamous> listAll = new ArrayList<>();
listAll = dao.selectAllFamous(con);
return listAll;
}
public ArrayList<MainAllFamous> settingPage(int currentPage) {
con = getConnection();
ArrayList<MainAllFamous> listPage = dao.settingPage(con, currentPage);
close(con);
return listPage;
}
public int countPage() {
con = getConnection();
int countPage = dao.countPage(con);
close(con);
return countPage;
}
public ArrayList<MainAllFamous> selectArea(int value) {
con = getConnection();
ArrayList<MainAllFamous> listArea = dao.selectArea(con, value);
close(con);
return listArea;
}
}
|
package raig.org;
public class HandlerBang implements Handler {
Handler successor;
HandlerBang(Handler successor) {
this.successor = successor;
}
@Override
public String handleRequest(int number) {
String resultSuccessor = "";
if ( successor != null ) {
resultSuccessor = successor.handleRequest(number);
}
String resultBang = "";
if ( number % 7 == 0) {
resultBang = "Bang";
}
return resultBang + resultSuccessor;
}
}
|
/**
* Created by Зая on 13.05.2016.
*/
public enum Group {
FRIENDS, FAMILY, JOB_COLLEAGUES, DOCTORS, OTHER
}
|
import javax.swing.JOptionPane;
public class Exerc3{
public static void main (String[] args){
double numero = Double.parseDouble(JOptionPane.showInputDialog("Digite o Número: "));
if(numero>=0){
double resultado = Math.pow(numero, 0.5);
JOptionPane.showMessageDialog(null, "O valor é: " + resultado);
} else{
double resultado = Math.pow(numero, 2);
JOptionPane.showMessageDialog(null, "O valor é: " + resultado);
}
}
}
|
package com.citibank.newcpb.vo;
import java.util.ArrayList;
import java.util.Date;
import com.citibank.newcpb.enums.TableTypeEnum;
import com.citibank.newcpb.util.FormatUtils;
public class AcctMgrtVO {
private String accountGrbNumber;
private String accountGrbCpfCnpjNumber;
private String accountGrbName;
private String accountCustodiaNumber;
private String accountCustodiaCpfCnpjNumber;
private String accountCustodiaName;
private String migrationDateString;
private Date migrationDate;
private String customerNumber;
private String relationNumber;
private String emNumber;
private Date lastAuthDate; // Data e hora da última autorizacao
private String lastAuthUser; // Usuario que realizou a ultima autorizacao
private Date lastUpdDate; // Data e hora da última atualização
private String lastUpdUser; // Usuario que realizou a ultima atualizacao
private String recStatCode; // Status do Registro
private TableTypeEnum tableOrigin; // Tipo da Tabela de Origem (CAD/MOV/HIST)
public String getAccountGrbNumber() {
return accountGrbNumber;
}
public void setAccountGrbNumber(String accountGrbNumber) {
this.accountGrbNumber = accountGrbNumber;
}
public String getAccountGrbCpfCnpjNumber() {
return accountGrbCpfCnpjNumber;
}
public void setAccountGrbCpfCnpjNumber(String accountGrbCpfCnpjNumber) {
this.accountGrbCpfCnpjNumber = accountGrbCpfCnpjNumber;
}
public String getAccountGrbName() {
return accountGrbName;
}
public void setAccountGrbName(String accountGrbName) {
this.accountGrbName = accountGrbName;
}
public String getAccountCustodiaCpfCnpjNumber() {
return accountCustodiaCpfCnpjNumber;
}
public void setAccountCustodiaCpfCnpjNumber(String accountCustodiaCpfCnpjNumber) {
this.accountCustodiaCpfCnpjNumber = accountCustodiaCpfCnpjNumber;
}
public String getAccountCustodiaName() {
return accountCustodiaName;
}
public void setAccountCustodiaName(String accountCustodiaName) {
this.accountCustodiaName = accountCustodiaName;
}
public String getAccountCustodiaNumber() {
return accountCustodiaNumber;
}
public void setAccountCustodiaNumber(String accountCustodiaNumber) {
this.accountCustodiaNumber = accountCustodiaNumber;
}
public String getMigrationDateString() {
return migrationDateString;
}
public void setMigrationDateString(String migrationDateString) {
this.migrationDateString = migrationDateString;
}
public Date getMigrationDate() {
return migrationDate;
}
public void setMigrationDate(Date migrationDate) {
this.migrationDate = migrationDate;
}
public String getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}
public String getRelationNumber() {
return relationNumber;
}
public void setRelationNumber(String relationNumber) {
this.relationNumber = relationNumber;
}
public String getEmNumber() {
return emNumber;
}
public void setEmNumber(String emNumber) {
this.emNumber = emNumber;
}
public Date getLastAuthDate() {
return lastAuthDate;
}
public void setLastAuthDate(Date lastAuthDate) {
this.lastAuthDate = lastAuthDate;
}
public String getLastAuthUser() {
return lastAuthUser;
}
public void setLastAuthUser(String lastAuthUser) {
this.lastAuthUser = lastAuthUser;
}
public Date getLastUpdDate() {
return lastUpdDate;
}
public void setLastUpdDate(Date lastUpdDate) {
this.lastUpdDate = lastUpdDate;
}
public String getLastUpdUser() {
return lastUpdUser;
}
public void setLastUpdUser(String lastUpdUser) {
this.lastUpdUser = lastUpdUser;
}
public String getRecStatCode() {
return recStatCode;
}
public void setRecStatCode(String recStatCode) {
this.recStatCode = recStatCode;
}
public TableTypeEnum getTableOrigin() {
return tableOrigin;
}
public void setTableOrigin(TableTypeEnum tableOrigin) {
this.tableOrigin = tableOrigin;
}
public String getLastUpdUserSafe() {
if(lastUpdUser!=null){
return lastUpdUser;
}else{
return "";
}
}
public String getLastUpdDateFormatedSafe() {
if(lastUpdDate!=null){
return FormatUtils.dateToString(lastUpdDate, FormatUtils.C_FORMAT_DATE_DD_MM_YYYY_HHMMSS);
}else{
return "";
}
}
public String getRecStatCodeText() {
if(recStatCode!=null){
if(recStatCode.equals("U")){
return "Alteração";
}else if(recStatCode.equals("A")){
return "Inclusão";
}else if(recStatCode.equals("I")){
return "Exclusão";
}else{
return "";
}
}else{
return "";
}
}
public ArrayList<String> equals(AcctMgrtVO other) {
ArrayList<String> idDiffList = new ArrayList<String>();
if (other != null){
if (this.accountGrbNumber != null && other.accountGrbNumber != null) {
if (!this.accountGrbNumber.equals(other.accountGrbNumber)) {
idDiffList.add("accountGrbNumber");
}
} else if ((this.accountGrbNumber == null && other.accountGrbNumber != null) || (other.accountGrbNumber == null && this.accountGrbNumber != null)) {
idDiffList.add("accountGrbNumber");
}
if (this.accountCustodiaNumber != null && other.accountCustodiaNumber != null) {
if (!this.accountCustodiaNumber.equals(other.accountCustodiaNumber)) {
idDiffList.add("accountCustodiaNumber");
}
} else if ((this.accountCustodiaNumber == null && other.accountCustodiaNumber != null) || (other.accountCustodiaNumber == null && this.accountCustodiaNumber != null)) {
idDiffList.add("accountCustodiaNumber");
}
if (this.migrationDateString != null && other.migrationDateString != null) {
if (!this.migrationDateString.equals(other.migrationDateString)) {
idDiffList.add("migrationDateString");
}
} else if ((this.migrationDateString == null && other.migrationDateString != null) || (other.migrationDateString == null && this.migrationDateString != null)) {
idDiffList.add("migrationDateString");
}
}else{
idDiffList.add("accountGrbNumber");
idDiffList.add("accountCustodiaNumber");
idDiffList.add("migrationDateString");
}
return idDiffList;
}
}
|
package com.auro.scholr.quiz.data.model.response;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ExamImageResModel {
@SerializedName("id_name")
@Expose
private String idName;
@SerializedName("status")
@Expose
private String status;
@SerializedName("error")
@Expose
private Boolean error;
@SerializedName("message")
@Expose
private String message;
@SerializedName("eklavvya_exam_id")
@Expose
private String eklavvyaExamId;
@SerializedName("url")
@Expose
private String url;
public String getIdName() {
return idName;
}
public void setIdName(String idName) {
this.idName = idName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Boolean getError() {
return error;
}
public void setError(Boolean error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getEklavvyaExamId() {
return eklavvyaExamId;
}
public void setEklavvyaExamId(String eklavvyaExamId) {
this.eklavvyaExamId = eklavvyaExamId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
package com.huadin.huadin;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.huadin.utils.LogUtil;
import com.zhy.autolayout.AutoLayoutActivity;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.ViewsById;
import java.util.List;
@EActivity(R.layout.activity_contact)
public class ContactActivity extends AutoLayoutActivity
{
private static final String TAG = "ContactActivity";
private String urlPhone;
private PopupWindow popupWindow;
@ViewById(R.id.tvTitle)
TextView title;
@ViewsById({R.id.contact_http, R.id.contact_phone})
List<TextView> tvList;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_contact);
}
@AfterViews
public void setTitle()
{
title.setText(R.string.system_setting_contact);
urlPhone = tvList.get(1).getText().toString();
}
@Click(R.id.title_btn_back)
public void back()
{
finish();
}
@Click(R.id.contact_layout_http)
public void sendHttp()
{
String uri = "http://www.95598.cn/person/index.shtml";
String action = "android.intent.action.VIEW";
visitHttp(action, uri);
}
@Click(R.id.contact_layout_phone)
public void callPhone()
{
String callPhone = "tel:" + urlPhone;
String action = Intent.ACTION_CALL;
visitHttp(action, callPhone);
}
@Click(R.id.contact_sina)
public void sinaHttp()
{
String uri = "http://weibo.com/sgcc";
String action = "android.intent.action.VIEW";
visitHttp(action, uri);
}
private void visitHttp(String action, String uri)
{
Uri url = Uri.parse(uri);
Intent intent = new Intent();
intent.setAction(action);
intent.setData(url);
startActivity(intent);
}
@Click(R.id.contact_weixin)
public void weiXin()
{
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.layout_sg, null);
if (popupWindow == null) popupWindow = new PopupWindow(view, 256, 256);
popupWindow.showAtLocation(findViewById(R.id.contact_weixin), Gravity.CENTER, 0, 100);
}
@Click(R.id.contact_layout)
public void dismiss()
{
if (popupWindow != null)
{
popupWindow.dismiss();
popupWindow = null;
}
}
protected void onDestroy()
{
super.onDestroy();
LogUtil.log(TAG, "Contact - onDestroy");
}
}
|
package com.chenws.netty.protobuf.mul.handler;
import com.chenws.netty.protobuf.mul.proto.NettyMulProtobuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* Created by chenws on 2020/3/22.
*/
public class PBMulClientHandler extends SimpleChannelInboundHandler<NettyMulProtobuf.MultipleMessage> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, NettyMulProtobuf.MultipleMessage msg) throws Exception {
// System.out.println("客户端收到信息:" + msg.getStudent().getAddress());
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// NettyMulProtobuf.MultipleMessage build = NettyMulProtobuf.MultipleMessage.newBuilder()
// .setDataType(NettyMulProtobuf.MultipleMessage.DataType.StudentType).setStudent(NettyMulProtobuf.Student.newBuilder().setAddress("student address")
// .setAge(10).setName("student name").build()).build();
NettyMulProtobuf.MultipleMessage build = NettyMulProtobuf.MultipleMessage.newBuilder()
.setDataType(NettyMulProtobuf.MultipleMessage.DataType.SchoolType).setSchool(
NettyMulProtobuf.School.newBuilder().setSchoolName("school name")
.setSchoolAddress("school address")
.build()
).build();
ctx.writeAndFlush(build);
}
}
|
package pe.edu.pucp.musicsoft.mysql;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import pe.edu.pucp.musicsoft.config.DBManager;
import pe.edu.pucp.musicsoft.dao.EmpresaDiscograficaDAO;
import pe.edu.pucp.musicsoft.model.EmpresaDiscografica;
public class EmpresaDiscograficaMySQL implements EmpresaDiscograficaDAO{
Connection con;
CallableStatement cs;
@Override
public ArrayList<EmpresaDiscografica> listar(String nombre) {
ArrayList<EmpresaDiscografica> empresas = new ArrayList<>();
try{
con = DriverManager.getConnection(DBManager.url, DBManager.user, DBManager.password);
cs = con.prepareCall("{call LISTAR_EMPRESAS_DISCOGRAFICAS(?)}");
cs.setString("_NOMBRE_EMPRESA", nombre);
ResultSet rs = cs.executeQuery();
while(rs.next()){
EmpresaDiscografica empresa = new EmpresaDiscografica();
empresa.setIdEmpresa(rs.getInt("ID_EMPRESA_DISCOGRAFICA"));
empresa.setNombreEmpresa(rs.getString("NOMBRE_EMPRESA"));
empresas.add(empresa);
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}finally{
try{con.close();}catch(Exception ex){System.out.println(ex.getMessage());}
}
return empresas;
}
}
|
package User.Register;
import User.Welcome.UserWelcome;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import User.login.UserLogin;
public class printDetails {
public static String print() {
return
" \n \n \n \n Congrats user Registered sucessfully"+
"\n user id = "+UserRegister.userid+
"\n password is = ********"+
"\n name = "+TitleCase.titleCase(UserRegister.userArray[0].getName())+
"\n email is = "+UserRegister.userArray[0].getEmail()+
"\n dateOfBirth = "+UserRegister.userArray[0].getDob()+
"\n phone no. = "+UserRegister.userArray[0].phoneno+
"\n income = "+incomeFormat.currencyFormat(UserRegister.userArray[0].getIncome());
}
}
|
package cn.novelweb.annotation.log.util;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.novelweb.annotation.log.pojo.AccessLogInfo;
import cn.novelweb.ip.IpUtils;
import cn.novelweb.ip.Region;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.concurrent.Future;
/**
* <p>封装一些关于日志注解需要用到的公共方法</p>
* <p>2019-12-05 22:03</p>
*
* @author Dai Yuanchuan
**/
public class Annotation {
/**
* 判断是否存在注解 存在就获取注解信息
*
* @param joinPoint 切点信息
* @param annotationClass 需要获取的注解类
* @param <A> 注解信息
* @return 如果存在则返回注解信息,否则返回NULL
*/
public static <A extends java.lang.annotation.Annotation> A getAnnotation
(JoinPoint joinPoint, Class<A> annotationClass) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null) {
return method.getAnnotation(annotationClass);
}
return null;
}
/**
* 初始化日志信息
*
* @param title 模块名称
* @param isGetIp 是否需要获取用户IP的实际地理位置
* @param e 异常信息
* @return 返回带有默认数据的日志信息
*/
public static AccessLogInfo initInfo(final String title, final boolean isGetIp, final Exception e) {
// 获取Request信息
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
// 初始化日志信息
AccessLogInfo accessLogInfo = AccessLogInfo.builder()
.ip("127.0.0.1")
.requestUri("")
.location("0-0-内网IP 内网IP")
.build();
String userAgent = "无法获取User-Agent信息";
if (requestAttributes != null) {
userAgent = requestAttributes.getRequest().getHeader("User-Agent");
accessLogInfo.setIp(ServletUtil.getClientIP(requestAttributes.getRequest()));
accessLogInfo.setRequestUri(requestAttributes.getRequest().getRequestURI());
accessLogInfo.setMethod(requestAttributes.getRequest().getMethod());
accessLogInfo.setRequest(requestAttributes.getRequest());
}
Future<Region> future = null;
if (isGetIp) {
// 异步获取IP实际地理位置信息
future = ThreadUtil.execAsync(() -> IpUtils.getIpLocationByBtree(accessLogInfo.getIp()));
}
// 获取/赋值 浏览器、os系统等信息
UserAgent ua = UserAgentUtil.parse(userAgent);
if (ua != null) {
accessLogInfo.setBrowser(ua.getBrowser().toString());
accessLogInfo.setBrowserVersion(ua.getVersion());
accessLogInfo.setBrowserEngine(ua.getEngine().toString());
accessLogInfo.setBrowserEngineVersion(ua.getEngineVersion());
accessLogInfo.setIsMobile(ua.isMobile());
accessLogInfo.setOs(ua.getOs().toString());
accessLogInfo.setPlatform(ua.getPlatform().getName());
}
accessLogInfo.setSpider(SpiderUtils.parseSpiderType(userAgent));
accessLogInfo.setUserAgent(userAgent);
// 访问的模块、状态、时间等
accessLogInfo.setTitle(title);
accessLogInfo.setStatus(e != null ? 1 : 0);
accessLogInfo.setCreateTime(new Date());
// 访问出现的异常信息
if (e != null) {
if (e.getCause() != null) {
accessLogInfo.setErrorCause(e.getCause().toString());
accessLogInfo.setErrorMsg(e.getCause().getMessage());
} else {
accessLogInfo.setErrorCause(e.getLocalizedMessage());
accessLogInfo.setErrorMsg(e.getMessage());
}
} else {
accessLogInfo.setErrorCause("");
accessLogInfo.setErrorMsg("");
}
if (future != null) {
try {
Region region = future.get();
accessLogInfo.setLocation(region.getCountry() + "-"
+ region.getProvince() + "-" + region.getCity() + " "
+ region.getIsp());
} catch (Exception e1) {
accessLogInfo.setErrorCause(e1.getCause().toString());
accessLogInfo.setErrorMsg(e1.getCause().getMessage());
accessLogInfo.setStatus(1);
}
}
return accessLogInfo;
}
}
|
/*
* UNIVERSIDAD ICESI
* ALGORITMOS Y PROGRAMACION II
* PROYECTO FINAL DEL CURSO
* SANTIAGO RODAS Y JULIAN ANDRES RIVERA
* GRUPO BANCARIO
*/
package excepciones;
public class Mayor183Excepcion extends Exception {
// ---------------------------------------------------------------------------------------
private static final long serialVersionUID = 1L;
// ---------------------------------------------------------------------------------------
public Mayor183Excepcion(String mensaje) {
super("EL NUMERO DE DIAS NO ES CORRECTO");
}
// ---------------------------------------------------------------------------------------
}
|
package com.mzq.controller;
import com.google.code.kaptcha.Producer;
import com.mzq.pojo.UserInfo;
import com.mzq.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.List;
/**
* @Author: mazhq
* @Date: 2019/3/30 15:09
*/
@Controller //@RestController 返回的是json对象 = @Controller + @ResponseBody
@RequestMapping(value = "/user")
public class UserInfoController {
@Autowired
private UserInfoService userInfoService;
@Autowired
private Producer captchaProducer;
/**
* 验证码
* @return
*/
@GetMapping(value = "/test")
@ResponseBody
public String test(){
String text = captchaProducer.createText();
return text;
}
/**
* 获取用户列表
*/
@GetMapping(value = "/list")
public ModelAndView getAllUserInfos() {
List<UserInfo> list = userInfoService.getAllUserInfos();
ModelAndView modelAndView = new ModelAndView();
// 设置数据
modelAndView.addObject("userList", list);
// 设置视图名称
modelAndView.setViewName("index");
return modelAndView;
}
/**
* delete
*
* @param userId
* @return
*/
@DeleteMapping(value = "/deleteUserInfo/{userId}")
@ResponseBody
public int deleteUserInfo(@PathVariable(value = "userId") int userId) {
int i = userInfoService.deleteUserInfo(userId);
return i;
}
/**
* 根据id更新用户
*
* @param userInfo
* @return
*/
@PostMapping(value = "/updateUserInfo")
@ResponseBody
public String updateUserInfo(UserInfo userInfo) {
userInfoService.updateUserInfo(userInfo);
return "1";
}
/**
* 新增用户
*
* @param userInfo
* @return
*/
@PostMapping(value = "/insertUserInfo")
@ResponseBody
public String insert(UserInfo userInfo) {
userInfoService.insert(userInfo);
return "1";
}
/**
* 登录的方法 实际上是查询的sql的相关操作
*
* @param userName
* @param password
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(@RequestParam("userName") String userName,
@RequestParam("password") String password,
HttpServletRequest request) {
//调用业务层方法
UserInfo userInfo = userInfoService.getUserInfoByUserNameAndPassword(userName, password);
//登录信息存放到Session
HttpSession session = request.getSession();
session.setAttribute("user", userInfo);
return "index";
}
/**
* 获取用户和用户发布的文章
*/
@RequestMapping(value = "/getUserInfoAndArticles", method = RequestMethod.GET)
public ModelAndView getUserInfoAndArticles(@RequestParam("userId")int userId){
// 调用业务层
UserInfo userInfo = userInfoService.getUserInfoAndArticle(userId);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("userInfoAndArticles",userInfo);
modelAndView.setViewName("details");
return modelAndView;
}
}
|
package com.example.microservicedemo.model;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
@ToString
@EqualsAndHashCode
//@Table(name = "User")
public class User {
@Id
private String id;
private String name;
private Boolean active;
private String email;
public User() {
}
public User(final String id, final String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public Boolean getActive() {
return active;
}
public void setActive(final Boolean active) {
this.active = active;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
}
|
package proyecto;
import java.awt.*;
import java.io.*;
public class principal {
public static void main(String[] args) throws IOException{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
clsVentana ven = new clsVentana(); //ventana nueva
ven.setVisible(true); // ventana visible
ven.setResizable(false); // no se redimensiona
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
|
package com.pronix.android.apssaataudit;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.StrictMode;
import com.pronix.android.apssaataudit.common.Constants;
import java.io.File;
/**
* Created by ravi on 12/29/2017.
*/
public class ssaat extends Application {
@Override
public void onCreate() {
super.onCreate();
// MultiDex.install(this);
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
// AndroidUtils.showMsg(AndroidUtils.getExceptionRootMessage(throwable), MicroXtend.this.getApplicationContext());
System.out.println(throwable.getMessage());
System.exit(0);
}
});
setAppDirectorypath();
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
}
public void setAppDirectorypath() {
try {
String device = Build.DEVICE.toUpperCase();
if (device.equals("GENERIC") || device.equals("SDK")) {
Constants.ROOTDIRECTORYPATH = getFilesDir().getAbsolutePath();
} else {
File[] file = this.getExternalFilesDirs(null);
Constants.ROOTDIRECTORYPATH = file[0].getAbsolutePath();
}
} catch (Exception e) {
}
}
}
|
package com.esum.framework.security.cms.encrypt;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class CMSEncrypt {
protected Logger log = LoggerFactory.getLogger(this.getClass());
private static CMSEncrypt mCMSEncrypt = null;
private static Object lock = new Object();
public static CMSEncrypt getInstance() {
synchronized (lock) {
if (mCMSEncrypt == null) {
mCMSEncrypt = new CMSEncryptWithBC();
}
}
return mCMSEncrypt;
}
public abstract byte[] encrypt(byte[] data, X509Certificate recipientCert,
String algorithm) throws CMSEncryptException;
public abstract byte[] decrypt(byte[] data, X509Certificate cert,
PrivateKey key) throws CMSEncryptException;
}
|
package ru.otus.sua.L05;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class SingleBigListWorker {
private static Logger log = Logger.getLogger(SingleBigListWorker.class.getName());
int listSize;
int waitMillis;
boolean leakageMode;
// private ForkJoinPool pool; // FJP тоже работает, оставлено специально
private ExecutorService pool;
public SingleBigListWorker(int listSize, int waitMillis, boolean leakageMode) {
this.listSize = listSize;
this.waitMillis = waitMillis;
this.leakageMode = leakageMode;
// pool = new ForkJoinPool(1); // FJP тоже работает, оставлено специально
pool = Executors.newFixedThreadPool(1);
pool.submit(new ListSpinRoll());
}
private class ListSpinRoll implements Runnable {
List<Integer> list;
@Override
public void run() {
log.info("Process of creation and deletion big List<Int> will started after " + waitMillis + "ms.");
waiter();
//noinspection InfiniteLoopStatement
while (true) {
list = new Random().ints(listSize, 1, listSize).boxed().collect(Collectors.toList());
log.info("Create List<Int> with size = " + list.size());
if (leakageMode) {
leakerNeverReturn();
} else {
log.info("Wait " + waitMillis + "ms. for list existence before remove its.");
waiter();
log.info("Delete List<Int>, and wait " + 2 * waitMillis + "ms.");
list = null;
waiter();
waiter();
}
}
}
private void waiter() {
try {
TimeUnit.MILLISECONDS.sleep(waitMillis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void leakerNeverReturn() {
List<Double> leekList = new ArrayList<>();
List<Double> doubleList = list.stream().mapToDouble(Integer::doubleValue).boxed().collect(Collectors.toList());
//noinspection InfiniteLoopStatement
while (true) {
leekList.addAll(doubleList);
leekList.removeIf(i -> i > (double) (listSize / 2));
log.info("LeekList<Double>.size()=" + leekList.size());
waiter();
}
}
}
}
|
/**
* Copyright (C) 2015 nshmura
* Copyright (C) 2015 The Android Open Source Project
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ys.uilibrary.rv;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
/**
* 点击自动切换 像导航栏Tab
*/
public class AutoRecycleLayout extends RecyclerView {
protected static final long DEFAULT_SCROLL_DURATION = 200;
protected static final float DEFAULT_POSITION_THRESHOLD = 0.6f;
protected static final float POSITION_THRESHOLD_ALLOWABLE = 0.001f;
protected int mTabMinWidth;
protected int mTabMaxWidth;
protected int mIndicatorHeight;
protected LinearLayoutManager mLinearLayoutManager;
protected RecyclerOnScrollListener mRecyclerOnScrollListener;
protected int mIndicatorPosition;
protected int mIndicatorOffset;
protected int mScrollOffset;
protected float mOldPositionOffset;
protected float mPositionThreshold;
protected boolean mRequestScrollToTab;
protected boolean mScrollEanbled = true;
public AutoRecycleLayout(Context context) {
this(context, null);
}
public AutoRecycleLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AutoRecycleLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setWillNotDraw(false);
mLinearLayoutManager = new LinearLayoutManager(getContext()) {
@Override
public boolean canScrollHorizontally() {
return mScrollEanbled;
}
};
mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
setLayoutManager(mLinearLayoutManager);
setItemAnimator(null);
mPositionThreshold = DEFAULT_POSITION_THRESHOLD;
}
@Override
protected void onDetachedFromWindow() {
if (mRecyclerOnScrollListener != null) {
removeOnScrollListener(mRecyclerOnScrollListener);
mRecyclerOnScrollListener = null;
}
super.onDetachedFromWindow();
}
public void setAutoSelectionMode(boolean autoSelect) {
if (mRecyclerOnScrollListener != null) {
removeOnScrollListener(mRecyclerOnScrollListener);
mRecyclerOnScrollListener = null;
}
if (autoSelect) {
mRecyclerOnScrollListener = new RecyclerOnScrollListener(this, mLinearLayoutManager);
addOnScrollListener(mRecyclerOnScrollListener);
}
}
public void setCurrentItem(int position, boolean smoothScroll) {
if (smoothScroll && position != mIndicatorPosition) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
startAnimation(position);
} else {
scrollToTab(position); //FIXME add animation
}
} else {
scrollToTab(position);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void startAnimation(final int position) {
float distance = 1;
View view = mLinearLayoutManager.findViewByPosition(position);
if (view != null) {
float currentX = view.getX() + view.getMeasuredWidth() / 2.f;
float centerX = getMeasuredWidth() / 2.f;
distance = Math.abs(centerX - currentX) / view.getMeasuredWidth();
}
ValueAnimator animator;
if (position < mIndicatorPosition) {
animator = ValueAnimator.ofFloat(distance, 0);
} else {
animator = ValueAnimator.ofFloat(-distance, 0);
}
animator.setDuration(DEFAULT_SCROLL_DURATION);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
scrollToTab(position, (float) animation.getAnimatedValue(), true);
}
});
animator.start();
}
protected void scrollToTab(int position) {
scrollToTab(position, 0, false);
}
protected void scrollToTab(int position, float positionOffset, boolean fitIndicator) {
int scrollOffset = 0;
View selectedView = mLinearLayoutManager.findViewByPosition(position);
View nextView = mLinearLayoutManager.findViewByPosition(position + 1);
if (selectedView != null) {
int width = getMeasuredWidth();
float scroll1 = width / 2.f - selectedView.getMeasuredWidth() / 2.f;
if (nextView != null) {
float scroll2 = width / 2.f - nextView.getMeasuredWidth() / 2.f;
float scroll = scroll1 + (selectedView.getMeasuredWidth() - scroll2);
float dx = scroll * positionOffset;
scrollOffset = (int) (scroll1 - dx);
mScrollOffset = (int) dx;
mIndicatorOffset = (int) ((scroll1 - scroll2) * positionOffset);
} else {
scrollOffset = (int) scroll1;
mScrollOffset = 0;
mIndicatorOffset = 0;
}
if (fitIndicator) {
mScrollOffset = 0;
mIndicatorOffset = 0;
}
mIndicatorPosition = position;
} else {
if (getMeasuredWidth() > 0 && mTabMaxWidth > 0 && mTabMinWidth == mTabMaxWidth) { //fixed size
int width = mTabMinWidth;
int offset = (int) (positionOffset * -width);
int leftOffset = (int) ((getMeasuredWidth() - width) / 2.f);
scrollOffset = offset + leftOffset;
}
mRequestScrollToTab = true;
}
stopScroll();
mLinearLayoutManager.scrollToPositionWithOffset(position, scrollOffset);
if (mIndicatorHeight > 0) {
invalidate();
}
mOldPositionOffset = positionOffset;
}
protected static class RecyclerOnScrollListener extends OnScrollListener {
AutoRecycleLayout mRecyclerTabLayout;
LinearLayoutManager mLinearLayoutManager;
RecyclerOnScrollListener(AutoRecycleLayout autoRecycleLayout,
LinearLayoutManager linearLayoutManager) {
mRecyclerTabLayout = autoRecycleLayout;
mLinearLayoutManager = linearLayoutManager;
}
public int mDx;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
mDx += dx;
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
switch (newState) {
case SCROLL_STATE_IDLE:
if (mDx > 0) {
selectCenterTabForRightScroll();
} else {
selectCenterTabForLeftScroll();
}
mDx = 0;
break;
case SCROLL_STATE_DRAGGING:
case SCROLL_STATE_SETTLING:
}
}
void selectCenterTabForRightScroll() {
int first = mLinearLayoutManager.findFirstVisibleItemPosition();
int last = mLinearLayoutManager.findLastVisibleItemPosition();
int center = mRecyclerTabLayout.getWidth() / 2;
for (int position = first; position <= last; position++) {
View view = mLinearLayoutManager.findViewByPosition(position);
if (view.getLeft() + view.getWidth() >= center) {
mRecyclerTabLayout.setCurrentItem(position, false);
break;
}
}
}
void selectCenterTabForLeftScroll() {
int first = mLinearLayoutManager.findFirstVisibleItemPosition();
int last = mLinearLayoutManager.findLastVisibleItemPosition();
int center = mRecyclerTabLayout.getWidth() / 2;
for (int position = last; position >= first; position--) {
View view = mLinearLayoutManager.findViewByPosition(position);
if (view.getLeft() <= center) {
mRecyclerTabLayout.setCurrentItem(position, false);
break;
}
}
}
}
}
|
package dbAssignment.opti_home_shop.data.model;
import java.util.Objects;
import javax.persistence.*;
import com.sun.istack.NotNull;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
@javax.persistence.Entity
@Table(name = "articlerating")
public class ArticleRating {
@Id
@Column(name = "AR_Id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
@NotNull
private int AR_Id;
public int getAR_Id() {
return this.AR_Id;
}
@Column
@NotNull
private String AR_Describtion;
public String getAR_Describtion() {
return this.AR_Describtion;
}
public void setAR_Describtion(String value) {
this.AR_Describtion = value;
}
@Column
@NotNull
private byte AR_Rating;
public byte getAR_Rating() {
return this.AR_Rating;
}
public void setAR_Rating(byte value) {
this.AR_Rating = value;
}
@Column
@NotNull
@CreationTimestamp
private java.sql.Timestamp AR_CreateDate;
public java.sql.Timestamp getAR_CreateDate() {
return this.AR_CreateDate;
}
@Column
@NotNull
@UpdateTimestamp
private java.sql.Timestamp AR_UpdateDate;
public java.sql.Timestamp getAR_UpdateDate() {
return this.AR_UpdateDate;
}
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
@JoinColumn(name = "A_Id")
@NotNull
private Article article;
public Article getArticle() {
return article;
}
public void setArticle(Article article) {
this.article = article;
}
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
@JoinColumn(name = "CA_Id")
@NotNull
private Customeraccount customeraccount;
public Customeraccount getCustomeraccount() {
return customeraccount;
}
public void setCustomeraccount(Customeraccount customeraccount) {
this.customeraccount = customeraccount;
}
public ArticleRating(String AR_Describtion_, byte AR_Rating_, Article article, Customeraccount customeraccount) {
this.AR_Describtion = AR_Describtion_;
this.AR_Rating = AR_Rating_;
this.article = article;
this.customeraccount = customeraccount;
}
public ArticleRating() {
}
@Override
public String toString() {
return "" + AR_Rating + ", " + AR_Describtion;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ArticleRating articleRating = (ArticleRating) o;
return Objects.equals(AR_Id, articleRating.AR_Id);
}
@Override
public int hashCode() {
return Objects.hash(AR_Id, AR_Describtion, AR_Rating, AR_CreateDate);
}
}
|
package com.hhdb.csadmin.plugin.tool_bar;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.UnsupportedLookAndFeelException;
import com.hh.frame.swingui.base.IEventRoute;
import com.hh.frame.swingui.event.EventTypeEnum;
import com.hh.frame.swingui.event.HHEvent;
import com.hhdb.csadmin.common.bean.HHEventRoute;
import com.hhdb.csadmin.common.util.UiUtil;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UiUtil.setLookAndFeel();
IEventRoute eventRoute= new HHEventRoute();
// LoginPlugin loginPlugin=new LoginPlugin();
// eventRoute.addPlugin("com.hhdb.csadmin.plugin.login");
// loginPlugin.init(eventRoute);
HHEvent loginEvent=new HHEvent("begin","com.hhdb.csadmin.plugin.tool_bar",EventTypeEnum.GET_OBJ.name());
HHEvent reply=eventRoute.processEvent(loginEvent);
JFrame frame=new JFrame();
frame.add((JComponent)reply.getObj());
frame.setVisible(true);
}
}
|
/*
* Welcome to use the TableGo Tools.
*
* http://vipbooks.iteye.com
* http://blog.csdn.net/vipbooks
* http://www.cnblogs.com/vipbooks
*
* Author:bianj
* Email:edinsker@163.com
* Version:5.8.0
*/
package com.lenovohit.hwe.pay.model;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.lenovohit.hwe.base.model.AuditableModel;
/**
* PAY_CASH_ERROR
*
* @author zyus
* @version 1.0.0 2017-12-22
*/
@Entity
@Table(name = "PAY_CASH")
public class Cash extends AuditableModel implements java.io.Serializable {
/** 版本号 */
private static final long serialVersionUID = -7199491244543238242L;
public static final String CASH_STAT_INITIAL = "A";// 初始化
public static final String CASH_STAT_PAY_SUCCESS = "0";// 支付成功
public static final String CASH_STAT_PAY_FAILURE = "1";// 支付失败
public static final String CASH_STAT_PAY_FINISH = "2";// 交易完成
public static final String CASH_STAT_CLOSED = "9";// 关闭 超时关闭 手工关闭 废单
public static final String CASH_STAT_EXCEPTIONAL = "E";// 异常
public static final String CASH_STAT_REVERSE = "R";// 冲账
/** settleId */
private String settleId;
/** settleNo */
private String settleNo;
/** appCode */
private String appCode;
/** appName */
private String appName;
/**
* APP - APP SSM - SSM SSB - SSB
*/
private String appType;
/** terminalCode */
private String terminalCode;
/** terminalName */
private String terminalName;
/** terminalUser */
private String terminalUser;
/** amt */
private BigDecimal amt;
/** ret */
private String ret;
/** msg */
private String msg;
/** printStat */
private String printStat;
/** printBatchNo */
private String printBatchNo;
/** optStatus */
private String optStatus;
/** optTime */
private Date optTime;
/** optId */
private String optId;
/** optName */
private String optName;
/** operation */
private String operation;
/** status */
private String status;
private Settlement settlement;
/**
* 获取settleId
*
* @return settleId
*/
@Column(name = "SETTLE_ID", nullable = true, length = 32)
public String getSettleId() {
return this.settleId;
}
/**
* 设置settleId
*
* @param settleId
*/
public void setSettleId(String settleId) {
this.settleId = settleId;
}
/**
* 获取settleNo
*
* @return settleNo
*/
@Column(name = "SETTLE_NO", nullable = true, length = 50)
public String getSettleNo() {
return this.settleNo;
}
/**
* 设置settleNo
*
* @param settleNo
*/
public void setSettleNo(String settleNo) {
this.settleNo = settleNo;
}
/**
* 获取appCode
*
* @return appCode
*/
@Column(name = "APP_CODE", nullable = true, length = 32)
public String getAppCode() {
return this.appCode;
}
/**
* 设置appCode
*
* @param appCode
*/
public void setAppCode(String appCode) {
this.appCode = appCode;
}
/**
* 获取appName
*
* @return appName
*/
@Column(name = "APP_NAME", nullable = true, length = 50)
public String getAppName() {
return this.appName;
}
/**
* 设置appName
*
* @param appName
*/
public void setAppName(String appName) {
this.appName = appName;
}
/**
* 获取APP - APP
SSM - SSM
SSB - SSB
*
* @return APP - APP
SSM - SSM
SSB - SSB
*/
@Column(name = "APP_TYPE", nullable = true, length = 3)
public String getAppType() {
return this.appType;
}
/**
* 设置APP - APP
SSM - SSM
SSB - SSB
*
* @param appType
* APP - APP
SSM - SSM
SSB - SSB
*/
public void setAppType(String appType) {
this.appType = appType;
}
/**
* 获取terminalCode
*
* @return terminalCode
*/
@Column(name = "TERMINAL_CODE", nullable = true, length = 50)
public String getTerminalCode() {
return this.terminalCode;
}
/**
* 设置terminalCode
*
* @param terminalCode
*/
public void setTerminalCode(String terminalCode) {
this.terminalCode = terminalCode;
}
/**
* 获取terminalName
*
* @return terminalName
*/
@Column(name = "TERMINAL_NAME", nullable = true, length = 70)
public String getTerminalName() {
return this.terminalName;
}
/**
* 设置terminalName
*
* @param terminalName
*/
public void setTerminalName(String terminalName) {
this.terminalName = terminalName;
}
/**
* 获取terminalUser
*
* @return terminalUser
*/
@Column(name = "TERMINAL_USER", nullable = true, length = 50)
public String getTerminalUser() {
return this.terminalUser;
}
/**
* 设置terminalUser
*
* @param terminalUser
*/
public void setTerminalUser(String terminalUser) {
this.terminalUser = terminalUser;
}
/**
* 获取amt
*
* @return amt
*/
@Column(name = "AMT", nullable = true)
public BigDecimal getAmt() {
return this.amt;
}
/**
* 设置amt
*
* @param amt
*/
public void setAmt(BigDecimal amt) {
this.amt = amt;
}
/**
* 获取ret
*
* @return ret
*/
@Column(name = "RET", nullable = true, length = 20)
public String getRet() {
return this.ret;
}
/**
* 设置ret
*
* @param ret
*/
public void setRet(String ret) {
this.ret = ret;
}
/**
* 获取msg
*
* @return msg
*/
@Column(name = "MSG", nullable = true, length = 500)
public String getMsg() {
return this.msg;
}
/**
* 设置msg
*
* @param msg
*/
public void setMsg(String msg) {
this.msg = msg;
}
/**
* 获取printStat
*
* @return printStat
*/
@Column(name = "PRINT_STAT", nullable = true, length = 1)
public String getPrintStat() {
return this.printStat;
}
/**
* 设置printStat
*
* @param printStat
*/
public void setPrintStat(String printStat) {
this.printStat = printStat;
}
/**
* 获取printBatchNo
*
* @return printBatchNo
*/
@Column(name = "PRINT_BATCH_NO", nullable = true, length = 50)
public String getPrintBatchNo() {
return this.printBatchNo;
}
/**
* 设置printBatchNo
*
* @param printBatchNo
*/
public void setPrintBatchNo(String printBatchNo) {
this.printBatchNo = printBatchNo;
}
/**
* 获取optStatus
*
* @return optStatus
*/
@Column(name = "OPT_STATUS", nullable = true, length = 1)
public String getOptStatus() {
return this.optStatus;
}
/**
* 设置optStatus
*
* @param optStatus
*/
public void setOptStatus(String optStatus) {
this.optStatus = optStatus;
}
/**
* 获取optTime
*
* @return optTime
*/
@Column(name = "OPT_TIME", nullable = true)
public Date getOptTime() {
return this.optTime;
}
/**
* 设置optTime
*
* @param optTime
*/
public void setOptTime(Date optTime) {
this.optTime = optTime;
}
/**
* 获取optId
*
* @return optId
*/
@Column(name = "OPT_ID", nullable = true, length = 32)
public String getOptId() {
return this.optId;
}
/**
* 设置optId
*
* @param optId
*/
public void setOptId(String optId) {
this.optId = optId;
}
/**
* 获取optName
*
* @return optName
*/
@Column(name = "OPT_NAME", nullable = true, length = 50)
public String getOptName() {
return this.optName;
}
/**
* 设置optName
*
* @param optName
*/
public void setOptName(String optName) {
this.optName = optName;
}
/**
* 获取operation
*
* @return operation
*/
@Column(name = "OPERATION", nullable = true, length = 200)
public String getOperation() {
return this.operation;
}
/**
* 设置operation
*
* @param operation
*/
public void setOperation(String operation) {
this.operation = operation;
}
/**
* 获取status
*
* @return status
*/
@Column(name = "STATUS", nullable = true, length = 1)
public String getStatus() {
return this.status;
}
/**
* 设置status
*
* @param status
*/
public void setStatus(String status) {
this.status = status;
}
@Transient
public Settlement getSettlement() {
return settlement;
}
public void setSettlement(Settlement settlement) {
this.settlement = settlement;
}
}
|
/*
* 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 rs.ac.bg.fon.ps.view.forms;
import java.awt.event.ActionListener;
/**
*
* @author Mr OLOGIZ
*/
public class FrmNalogClanaCRUD extends javax.swing.JDialog {
/**
* Creates new form FrmNalogClanaCRUD
*/
public FrmNalogClanaCRUD(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
bgPlatio = new javax.swing.ButtonGroup();
bgPol = new javax.swing.ButtonGroup();
panelBackGround = new javax.swing.JPanel();
lblIdClana = new javax.swing.JLabel();
lblImeClana = new javax.swing.JLabel();
lblPrezimeClana = new javax.swing.JLabel();
lblBrojTelefonaClana = new javax.swing.JLabel();
lblUlicaBroj = new javax.swing.JLabel();
lblPlatio = new javax.swing.JLabel();
lblJBMG = new javax.swing.JLabel();
txtId = new javax.swing.JTextField();
txtIme = new javax.swing.JTextField();
txtPrezime = new javax.swing.JTextField();
txtUlicaBroj = new javax.swing.JTextField();
txtBrojTelefona1 = new javax.swing.JTextField();
txtJBMG = new javax.swing.JTextField();
rbDa = new javax.swing.JRadioButton();
rbNe = new javax.swing.JRadioButton();
lblPol = new javax.swing.JLabel();
rbMuski = new javax.swing.JRadioButton();
rbZenski = new javax.swing.JRadioButton();
rbOstalo = new javax.swing.JRadioButton();
lblBackground = new javax.swing.JLabel();
btnObrisiNalog = new javax.swing.JButton();
btnPotvrdiIzmene = new javax.swing.JButton();
btnOmoguciIzmene = new javax.swing.JButton();
lblErrorMessage = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
panelBackGround.setBackground(new java.awt.Color(0, 0, 0));
panelBackGround.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
lblIdClana.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblIdClana.setForeground(new java.awt.Color(255, 255, 255));
lblIdClana.setText("id:");
panelBackGround.add(lblIdClana, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 9, -1, -1));
lblImeClana.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblImeClana.setForeground(new java.awt.Color(255, 255, 255));
lblImeClana.setText("ime:");
panelBackGround.add(lblImeClana, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 39, -1, -1));
lblPrezimeClana.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblPrezimeClana.setForeground(new java.awt.Color(255, 255, 255));
lblPrezimeClana.setText("prezime:");
panelBackGround.add(lblPrezimeClana, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 71, -1, -1));
lblBrojTelefonaClana.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblBrojTelefonaClana.setForeground(new java.awt.Color(255, 255, 255));
lblBrojTelefonaClana.setText("broj telefona:");
panelBackGround.add(lblBrojTelefonaClana, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 106, -1, -1));
lblUlicaBroj.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblUlicaBroj.setForeground(new java.awt.Color(255, 255, 255));
lblUlicaBroj.setText("ulica i broj (sprat i stan):");
panelBackGround.add(lblUlicaBroj, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 141, -1, -1));
lblPlatio.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblPlatio.setForeground(new java.awt.Color(255, 255, 255));
lblPlatio.setText("platio/platila:");
panelBackGround.add(lblPlatio, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 179, -1, -1));
lblJBMG.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblJBMG.setForeground(new java.awt.Color(255, 255, 255));
lblJBMG.setText("JBMG:");
panelBackGround.add(lblJBMG, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 260, -1, -1));
txtId.setBackground(new java.awt.Color(0, 0, 0));
txtId.setForeground(new java.awt.Color(255, 255, 255));
txtId.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
panelBackGround.add(txtId, new org.netbeans.lib.awtextra.AbsoluteConstraints(215, 10, 230, -1));
txtIme.setBackground(new java.awt.Color(0, 0, 0));
txtIme.setForeground(new java.awt.Color(255, 255, 255));
txtIme.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
panelBackGround.add(txtIme, new org.netbeans.lib.awtextra.AbsoluteConstraints(215, 40, 230, -1));
txtPrezime.setBackground(new java.awt.Color(0, 0, 0));
txtPrezime.setForeground(new java.awt.Color(255, 255, 255));
txtPrezime.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
panelBackGround.add(txtPrezime, new org.netbeans.lib.awtextra.AbsoluteConstraints(215, 72, 230, -1));
txtUlicaBroj.setBackground(new java.awt.Color(0, 0, 0));
txtUlicaBroj.setForeground(new java.awt.Color(255, 255, 255));
txtUlicaBroj.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
panelBackGround.add(txtUlicaBroj, new org.netbeans.lib.awtextra.AbsoluteConstraints(215, 142, 230, -1));
txtBrojTelefona1.setBackground(new java.awt.Color(0, 0, 0));
txtBrojTelefona1.setForeground(new java.awt.Color(255, 255, 255));
txtBrojTelefona1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
panelBackGround.add(txtBrojTelefona1, new org.netbeans.lib.awtextra.AbsoluteConstraints(215, 107, 230, -1));
txtJBMG.setBackground(new java.awt.Color(0, 0, 0));
txtJBMG.setForeground(new java.awt.Color(255, 255, 255));
txtJBMG.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));
panelBackGround.add(txtJBMG, new org.netbeans.lib.awtextra.AbsoluteConstraints(215, 259, 230, -1));
rbDa.setBackground(new java.awt.Color(0, 0, 0));
bgPlatio.add(rbDa);
rbDa.setFont(new java.awt.Font("Microsoft YaHei", 1, 11)); // NOI18N
rbDa.setForeground(new java.awt.Color(255, 255, 255));
rbDa.setText("da");
panelBackGround.add(rbDa, new org.netbeans.lib.awtextra.AbsoluteConstraints(215, 176, -1, -1));
rbNe.setBackground(new java.awt.Color(0, 0, 0));
bgPlatio.add(rbNe);
rbNe.setFont(new java.awt.Font("Microsoft YaHei", 1, 11)); // NOI18N
rbNe.setForeground(new java.awt.Color(255, 255, 255));
rbNe.setText("ne");
panelBackGround.add(rbNe, new org.netbeans.lib.awtextra.AbsoluteConstraints(272, 176, -1, -1));
lblPol.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblPol.setForeground(new java.awt.Color(255, 255, 255));
lblPol.setText("pol:");
panelBackGround.add(lblPol, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 220, -1, -1));
rbMuski.setBackground(new java.awt.Color(0, 0, 0));
bgPol.add(rbMuski);
rbMuski.setFont(new java.awt.Font("Microsoft YaHei", 1, 11)); // NOI18N
rbMuski.setForeground(new java.awt.Color(255, 255, 255));
rbMuski.setText("muski");
panelBackGround.add(rbMuski, new org.netbeans.lib.awtextra.AbsoluteConstraints(215, 217, -1, -1));
rbZenski.setBackground(new java.awt.Color(0, 0, 0));
bgPol.add(rbZenski);
rbZenski.setFont(new java.awt.Font("Microsoft YaHei", 1, 11)); // NOI18N
rbZenski.setForeground(new java.awt.Color(255, 255, 255));
rbZenski.setText("zenski");
panelBackGround.add(rbZenski, new org.netbeans.lib.awtextra.AbsoluteConstraints(276, 217, -1, -1));
rbOstalo.setBackground(new java.awt.Color(0, 0, 0));
bgPol.add(rbOstalo);
rbOstalo.setFont(new java.awt.Font("Microsoft YaHei", 1, 11)); // NOI18N
rbOstalo.setForeground(new java.awt.Color(255, 255, 255));
rbOstalo.setText("ostalo");
panelBackGround.add(rbOstalo, new org.netbeans.lib.awtextra.AbsoluteConstraints(345, 217, -1, -1));
lblBackground.setIcon(new javax.swing.ImageIcon(getClass().getResource("/rs/ac/bg/fon/ps/images/weightv2.png"))); // NOI18N
panelBackGround.add(lblBackground, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 120, 300, -1));
btnObrisiNalog.setBackground(new java.awt.Color(255, 255, 255));
btnObrisiNalog.setFont(new java.awt.Font("Microsoft YaHei", 1, 11)); // NOI18N
btnObrisiNalog.setText("Obriši nalog");
panelBackGround.add(btnObrisiNalog, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 10, 140, -1));
btnPotvrdiIzmene.setBackground(new java.awt.Color(255, 255, 255));
btnPotvrdiIzmene.setFont(new java.awt.Font("Microsoft YaHei", 1, 11)); // NOI18N
btnPotvrdiIzmene.setText("Potvrdi promene");
panelBackGround.add(btnPotvrdiIzmene, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 90, 140, -1));
btnOmoguciIzmene.setBackground(new java.awt.Color(255, 255, 255));
btnOmoguciIzmene.setFont(new java.awt.Font("Microsoft YaHei", 1, 11)); // NOI18N
btnOmoguciIzmene.setText("Omogući promene");
panelBackGround.add(btnOmoguciIzmene, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 50, 140, -1));
lblErrorMessage.setFont(new java.awt.Font("Microsoft YaHei", 1, 12)); // NOI18N
lblErrorMessage.setForeground(new java.awt.Color(255, 0, 51));
panelBackGround.add(lblErrorMessage, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 320, -1, -1));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelBackGround, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(panelBackGround, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
public void OmoguciIzmeneNalogaAddActionListener(ActionListener actionListener) {
btnOmoguciIzmene.addActionListener(actionListener);
}
public void ObrisiNalogAddActionListener(ActionListener actionListener) {
btnObrisiNalog.addActionListener(actionListener);
}
public void IzmeniNalogAddActionListener(ActionListener actionListener) {
btnPotvrdiIzmene.addActionListener(actionListener);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup bgPlatio;
private javax.swing.ButtonGroup bgPol;
private javax.swing.JButton btnObrisiNalog;
private javax.swing.JButton btnOmoguciIzmene;
private javax.swing.JButton btnPotvrdiIzmene;
private javax.swing.JLabel lblBackground;
private javax.swing.JLabel lblBrojTelefonaClana;
private javax.swing.JLabel lblErrorMessage;
private javax.swing.JLabel lblIdClana;
private javax.swing.JLabel lblImeClana;
private javax.swing.JLabel lblJBMG;
private javax.swing.JLabel lblPlatio;
private javax.swing.JLabel lblPol;
private javax.swing.JLabel lblPrezimeClana;
private javax.swing.JLabel lblUlicaBroj;
private javax.swing.JPanel panelBackGround;
private javax.swing.JRadioButton rbDa;
private javax.swing.JRadioButton rbMuski;
private javax.swing.JRadioButton rbNe;
private javax.swing.JRadioButton rbOstalo;
private javax.swing.JRadioButton rbZenski;
private javax.swing.JTextField txtBrojTelefona1;
private javax.swing.JTextField txtId;
private javax.swing.JTextField txtIme;
private javax.swing.JTextField txtJBMG;
private javax.swing.JTextField txtPrezime;
private javax.swing.JTextField txtUlicaBroj;
// End of variables declaration//GEN-END:variables
public javax.swing.ButtonGroup getBgPlatio() {
return bgPlatio;
}
public void setBgPlatio(javax.swing.ButtonGroup bgPlatio) {
this.bgPlatio = bgPlatio;
}
public javax.swing.ButtonGroup getBgPol() {
return bgPol;
}
public void setBgPol(javax.swing.ButtonGroup bgPol) {
this.bgPol = bgPol;
}
public javax.swing.JButton getBtnObrisiNalog() {
return btnObrisiNalog;
}
public void setBtnObrisiNalog(javax.swing.JButton btnObrisiNalog) {
this.btnObrisiNalog = btnObrisiNalog;
}
public javax.swing.JButton getBtnOmoguciIzmene() {
return btnOmoguciIzmene;
}
public void setBtnOmoguciIzmene(javax.swing.JButton btnOmoguciIzmene) {
this.btnOmoguciIzmene = btnOmoguciIzmene;
}
public javax.swing.JButton getBtnPotvrdiIzmene() {
return btnPotvrdiIzmene;
}
public void setBtnPotvrdiIzmene(javax.swing.JButton btnPotvrdiIzmene) {
this.btnPotvrdiIzmene = btnPotvrdiIzmene;
}
public javax.swing.JRadioButton getRbDa() {
return rbDa;
}
public void setRbDa(javax.swing.JRadioButton rbDa) {
this.rbDa = rbDa;
}
public javax.swing.JRadioButton getRbMuski() {
return rbMuski;
}
public void setRbMuski(javax.swing.JRadioButton rbMuski) {
this.rbMuski = rbMuski;
}
public javax.swing.JRadioButton getRbNe() {
return rbNe;
}
public void setRbNe(javax.swing.JRadioButton rbNe) {
this.rbNe = rbNe;
}
public javax.swing.JRadioButton getRbOstalo() {
return rbOstalo;
}
public void setRbOstalo(javax.swing.JRadioButton rbOstalo) {
this.rbOstalo = rbOstalo;
}
public javax.swing.JRadioButton getRbZenski() {
return rbZenski;
}
public void setRbZenski(javax.swing.JRadioButton rbZenski) {
this.rbZenski = rbZenski;
}
public javax.swing.JTextField getTxtBrojTelefona1() {
return txtBrojTelefona1;
}
public void setTxtBrojTelefona1(javax.swing.JTextField txtBrojTelefona1) {
this.txtBrojTelefona1 = txtBrojTelefona1;
}
public javax.swing.JTextField getTxtId() {
return txtId;
}
public void setTxtId(javax.swing.JTextField txtId) {
this.txtId = txtId;
}
public javax.swing.JTextField getTxtIme() {
return txtIme;
}
public void setTxtIme(javax.swing.JTextField txtIme) {
this.txtIme = txtIme;
}
public javax.swing.JTextField getTxtJBMG() {
return txtJBMG;
}
public void setTxtJBMG(javax.swing.JTextField txtJBMG) {
this.txtJBMG = txtJBMG;
}
public javax.swing.JTextField getTxtPrezime() {
return txtPrezime;
}
public void setTxtPrezime(javax.swing.JTextField txtPrezime) {
this.txtPrezime = txtPrezime;
}
public javax.swing.JTextField getTxtUlicaBroj() {
return txtUlicaBroj;
}
public void setTxtUlicaBroj(javax.swing.JTextField txtUlicaBroj) {
this.txtUlicaBroj = txtUlicaBroj;
}
public javax.swing.JLabel getLblErrorMessage() {
return lblErrorMessage;
}
public void setLblErrorMessage(javax.swing.JLabel lblErrorMessage) {
this.lblErrorMessage = lblErrorMessage;
}
}
|
package com.srividhyagk.Imdb;
import java.util.List;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ReviewRepository extends CrudRepository<Reviews,Integer>{
List<Reviews> findByUser_id(int user_id);
List<Reviews> findByMovie_id(int movie_id);
List<Reviews> findByRating(int rating);
}
|
package BRE;
import LOG.LogClient;
import LOG.LogLevel;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class BREClient {
private static final String ruleUrl
= "http://localhost:3000/rule";
private static final String answerUrl
= "http://localhost:3000/rule/answer";
private static String ruleParameters = "<rule id='%d'>" + "<clause>%s</clause>" + "<relatives>%s</relatives>" + "</rule>";
private static String answerParameters = "<response>\n" +
" <user_id>%d</user_id>\n" +
" <rule_id>%d</rule_id>\n" +
" <answer>%s</answer>\n" +
"</response>\n";
private static HttpURLConnection conn;
public static String request(String url, String urlParameters) {
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
try {
URL myUrl = new URL(url);
conn = (HttpURLConnection) myUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/xml");
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
StringBuilder content;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
String line;
content = new StringBuilder();
while ((line = in.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
}
return content.toString();
} catch (IOException e) {
System.out.println("Rule ve relative uyusmuyor!");
LogClient.LogDesc("Relatives don't have correct rule format.", -1, LogLevel.FAIL);
} finally {
conn.disconnect();
}
return "";
}
public static int add(String query, int ruleID, String relatives) {
String response = request(ruleUrl, String.format(ruleParameters, ruleID, query, relatives));
response = response.toLowerCase();
System.out.println(response);
if (response.contains("T")) {
return 1;
}
return -1;
}
public static String approve(int ruleID, int relativeID, String answer) {
String response = request(answerUrl, String.format(answerParameters, relativeID, ruleID, answer));
return response;
}
}
|
package com.weiziplus.springboot.common.config;
/**
* 设置全局静态常量
*
* @author wanglongwei
* @data 2019/5/6 15:50
*/
public class GlobalConfig {
/**
* 身份验证,请求头,token
*/
public final static String TOKEN = "token";
/**
* 空字符串
*/
public static final String UNDEFINED = "undefined";
/**
* 用户允许登录为0,禁止为1
*/
public static final Integer ALLOW_LOGIN = 0;
/**
* 允许使用为0,禁止为1
*/
public static final Integer IS_STOP = 0;
/**
* 超级管理员id为1
*/
public static final Long SUPER_ADMIN_ID = 1L;
/**
* 超级管理员角色id为1
*/
public static final Long SUPER_ADMIN_ROLE_ID = 1L;
/**
* 系统功能表中角色管理id为3
*/
public static final Long SYS_FUNCTION_ROLE_ID = 3L;
}
|
package com.example.reminder_app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class NotificationReciever extends BroadcastReceiver {
@Override // we can execute the code here without opening our app
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("toastmsg");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); // only works when inside the application
}
}
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Task4 {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
String temp;
try {
FileReader fileReader = new FileReader
("src/task4/main/resources/task4.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((temp = bufferedReader.readLine()) != null) {
strings.add(temp);
}
fileReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer text = new StringBuffer();
for (int i = 0; i < strings.size(); i++) {
text.append(strings.get(i) + " ");
}
List<String> directOration = new ArrayList<>();
Pattern pattern = Pattern.compile("[\"][^\"]+[\"]");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
directOration.add(matcher.group());
}
for (int i = 0; i < directOration.size(); i++) {
System.out.println((i + 1) + ") " + directOration.get(i));
}
}
}
|
package com.lidaye.shopIndex.mapper;
public interface ShopImageMapper {
}
|
import org.junit.Test;
import pages.InboxPage;
import pages.LogInPage;
import pages.appendice.CommonConstants;
import static junit.framework.TestCase.assertTrue;
public class SendNewLetterTest extends BaseSpec{
InboxPage inboxPage = new InboxPage();
LogInPage logInPage = new LogInPage();
@Test
public void sendNewLetterTest() {
given:
logInPage.visit();
logInPage.logIn();
when:
inboxPage.check();
inboxPage.sendNewLetter(CommonConstants.EMAIL, CommonConstants.LETTER_TOPIC, CommonConstants.LETTER_BODY);
then:
assertTrue(inboxPage.isLetterReceived(CommonConstants.LETTER_TOPIC, CommonConstants.LETTER_BODY));
}
}
|
package stephen.ranger.ar.lighting;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.vecmath.Vector3f;
import stephen.ranger.ar.Camera;
import stephen.ranger.ar.IntersectionInformation;
import stephen.ranger.ar.PBRTMath;
import stephen.ranger.ar.RTStatics;
import stephen.ranger.ar.photons.Photon;
import stephen.ranger.ar.photons.PhotonTree;
import stephen.ranger.ar.photons.Photon.LightAttribution;
public class GlobalIlluminationLightingModel extends LightingModel {
public PhotonTree photons = null;
public GlobalIlluminationLightingModel() {
}
@Override
public void setCamera(final Camera camera) {
this.camera = camera;
final long startTimePhotonMap = System.nanoTime();
photons = computePhotonMap();
final long endTimePhotonMap = System.nanoTime();
System.out.println("Created Photon Map in " + (endTimePhotonMap - startTimePhotonMap) / 1000000000. + " seconds");
}
@Override
public float[] getPixelColor(final IntersectionInformation info, final int depth) {
final float[] color = new float[] { 0, 0, 0 };
final Vector3f origin = new Vector3f(info.intersection);
final Vector3f dir = new Vector3f();
final Random random = new Random();
float weight;
IntersectionInformation newInfo;
final float[] location = new float[3];
int[] indices;
// final Vector3f invDir = new Vector3f(info.ray.direction);
// invDir.scale(-1f);
// final float falloff = invDir.dot(info.normal);
int ctr = 0;
for (int i = 0; i < RTStatics.PHOTON_COLLECTION_RAY_COUNT; i++) {
weight = RTStatics.cosSampleHemisphere(dir, info.normal, random);
newInfo = camera.getClosestIntersection(null, origin, dir, info.normal, depth);
final float falloff = dir.dot(info.normal);
if (newInfo != null) {
ctr++;
newInfo.intersection.get(location);
indices = photons.kNearest(location, RTStatics.COLLECTION_COUNT_THRESHOLD);
final float[] spawnedColor = radialBasisPhotonAverageIrradiance(newInfo, indices);
color[0] += spawnedColor[0] * falloff / weight;
color[1] += spawnedColor[1] * falloff / weight;
color[2] += spawnedColor[2] * falloff / weight;
}
}
if (ctr > 0) {
final float[] diffuseColor = info.intersectionObject.getDiffuse();
color[0] = color[0] / ctr * diffuseColor[0];
color[1] = color[1] / ctr * diffuseColor[1];
color[2] = color[2] / ctr * diffuseColor[2];
}
return color;
}
private float[] radialBasisPhotonAverageIrradiance(final IntersectionInformation info, final int[] indices) {
float maxDistanceSquared = -Float.MAX_VALUE;
final float[] averageColor = new float[] { 1, 1, 1 };
float total = 0f;
if (indices.length > 0) {
for (final int index : indices) {
final Photon p = photons.get(index);
maxDistanceSquared = Math.max(maxDistanceSquared, RTStatics.getDistanceSquared(info.intersection, p.location));
}
final float prefix = 1f / (indices.length * maxDistanceSquared) * 3f / PBRTMath.F_PI;
float temp;
for (final int index : indices) {
final Photon p = photons.get(index);
final Vector3f invDir = new Vector3f(p.incomingDir);
invDir.scale(-1f);
invDir.normalize();
final float cosTerm = Math.abs(invDir.dot(info.normal));
if (cosTerm > 0f) {
temp = 1f - RTStatics.getDistanceSquared(info.intersection, p.location) / maxDistanceSquared;
total += temp * temp * cosTerm * p.intensity;
averageColor[0] += p.color[0];
averageColor[1] += p.color[1];
averageColor[2] += p.color[2];
}
}
total *= prefix;
averageColor[0] *= total;
averageColor[1] *= total;
averageColor[2] *= total;
}
return averageColor;
}
// @Override
// public float[] getPixelColor(final IntersectionInformation info, final int depth) {
// final float[] color = new float[] { 0, 0, 0 };
// final float[] diffuse, specular;
//
// if (info != null) {
// diffuse = info.intersectionObject.getColor(info, camera, depth);
// // diffuse = info.intersectionObject.getDiffuse();
// specular = info.intersectionObject.getSpecular();
// final Vector3f invDir = new Vector3f(info.ray.direction);
// invDir.scale(-1f);
// final float falloff = invDir.dot(info.normal);
//
// // final float[] temp = getPhotonMapLuminocity(info);
// //
// // color[0] += temp[0] * falloff * diffuse[0]; // direct diffuse
// // color[1] += temp[0] * falloff * diffuse[1];
// // color[2] += temp[0] * falloff * diffuse[2];
//
// final float[] irradiance = collectPhotons(info);
//
// color[0] += irradiance[0] * falloff * diffuse[0]; // indirect diffuse
// color[1] += irradiance[0] * falloff * diffuse[1];
// color[2] += irradiance[0] * falloff * diffuse[2];
//
// // color[0] += irradiance[1] * falloff * specular[0]; // indirect specular
// // color[1] += irradiance[1] * falloff * specular[1];
// // color[2] += irradiance[1] * falloff * specular[2];
//
// // get photons and their colors
// // color = getPhotonLocations(info);
// }
//
// return color;
// }
//
// private float[] collectPhotons(final IntersectionInformation info) {
// final float[] values = new float[] { 0, 0 };
// float[] temp;
//
// final int rayCount = RTStatics.PHOTON_COLLECTION_RAY_COUNT;
// final Random random = new Random();
//
// for (int x = 0; x < rayCount; x++) {
// final Vector3f dir = new Vector3f();
// final float weight = RTStatics.cosSampleHemisphere(dir, info.normal, random);
// // final Vector3f dir = RTStatics.getReflectionDirection(info);
// // final float weight = 1f;
//
// final IntersectionInformation collectionInfo = camera.getClosestIntersection(null, info.intersection, dir, info.normal, 0);
//
// if (collectionInfo != null) {
// temp = getPhotonMapLuminocity(collectionInfo);
//
// final Vector3f invDir = new Vector3f(info.ray.direction);
// invDir.scale(-1f);
// final float falloff = invDir.dot(info.normal);
//
// values[0] += temp[0] * falloff / weight;
// values[1] += temp[1] * falloff / weight;
// }
// }
//
// values[0] /= rayCount;
// values[1] /= rayCount;
//
// return values;
// }
//
// private float[] getPhotonLocations(final IntersectionInformation info) {
// final int[] indices = photons.kNearest(new float[] { info.intersection.x, info.intersection.y, info.intersection.z }, 1);
//
// if (indices.length > 0 && indices[0] >= 0) {
// final Photon p = photons.get(indices[0]);
// final float[] color = Arrays.copyOf(p.color, 3);
// color[0] *= p.intensity;
// color[1] *= p.intensity;
// color[2] *= p.intensity;
// return color;
// } else {
// return new float[] { 0, 0, 0 };
// }
// }
//
// private float[] getPhotonMapLuminocity(final IntersectionInformation info) {
// final List<Photon> diffusePhotons = new ArrayList<Photon>();
// final List<Photon> specularPhotons = new ArrayList<Photon>();
//
// if (info != null) {
// final int[] indices = photons.kNearest(new float[] { info.intersection.x, info.intersection.y, info.intersection.z },
// RTStatics.COLLECTION_COUNT_THRESHOLD);
// // final int[] indices = new int[] { this.photons.nearestNeighbor(new float[] { info.intersection.x, info.intersection.y, info.intersection.z }) };
// Photon photon;
//
// if (indices.length > 0) {
// for (final int index : indices) {
// photon = photons.get(index);
//
// if (photon.value.cell == LightAttribution.DIFFUSE.cell) {
// diffusePhotons.add(photon);
// } else {
// specularPhotons.add(photon);
// }
// }
// }
// }
//
// final float[] output = new float[] { 0, 0 };
//
// output[0] = radialBasisPhotonAverageIrradiance(info, diffusePhotons);
// output[1] = radialBasisPhotonAverageIrradiance(info, specularPhotons);
//
// // output[0] = average(diffusePhotons);
// // output[1] = average(specularPhotons);
//
// return output;
// }
//
// private float average(final List<Photon> photons) {
// float intensity = 0;
//
// for (final Photon p : photons) {
// intensity += p.intensity;
// }
//
// return photons.size() == 0 ? 0 : intensity / photons.size();
// }
//
//
// private float radialBasisPhotonAverageIrradiance(final IntersectionInformation info, final List<Photon> photons) {
// float maxDistanceSquared = -Float.MAX_VALUE;
// float total = 0;
//
// if (photons.size() > 0) {
// for (final Photon p : photons) {
// maxDistanceSquared = Math.max(maxDistanceSquared, RTStatics.getDistanceSquared(info.intersection, p.location));
// }
//
// final float prefix = 1f / (photons.size() * maxDistanceSquared) * 3f / PBRTMath.F_PI;
// float temp;
// final Vector3f invDir = new Vector3f();
//
// for (final Photon p : photons) {
// invDir.set(p.incomingDir);
// invDir.scale(-1f);
// final float dot = invDir.dot(info.normal);
//
// if (dot > 0f) {
// temp = 1f - RTStatics.getDistanceSquared(info.intersection, p.location) / maxDistanceSquared;
// total += temp * temp * dot * p.intensity;
// }
// }
//
// total *= prefix;
// }
//
// return total;
// }
protected PhotonTree computePhotonMap() {
final Vector3f originDirection = new Vector3f();
originDirection.sub(camera.light.origin);
originDirection.normalize();
final List<Photon> photons = new ArrayList<Photon>();
RTStatics.setProgressBarString("Computing Photon Map...");
RTStatics.setProgressBarMinMax(0, RTStatics.NUM_PHOTONS);
int ctr = 0;
final Random random = new Random();
final Vector3f lightDir = new Vector3f(camera.light.origin);
lightDir.scale(-1f);
lightDir.normalize();
System.out.println("light direction: " + lightDir);
/**
* Random photons
*/
for (int i = 0; i < RTStatics.NUM_PHOTONS; i++) {
// Vector3f dir = RTStatics.getVectorMarsagliaHemisphere(lightDir);
Vector3f dir = new Vector3f();
RTStatics.cosSampleHemisphere(dir, lightDir, new Random());
Vector3f origin = new Vector3f(camera.light.origin);
Vector3f normal = null;
float intensity = RTStatics.STARTING_INTENSITY;
final float weight = 1f;
final float[] emissionColor = camera.light.emission.getColorComponents(new float[3]);
for (int m = 0; m < RTStatics.NUM_REFLECTIONS; m++) {
final float chance = random.nextFloat();
final LightAttribution value = chance < 0.8f ? LightAttribution.DIFFUSE : chance < 0.8f ? LightAttribution.SPECULAR : null;
if (value != null && intensity > 0f) {
final IntersectionInformation info = camera.getClosestIntersection(null, origin, dir, normal, 0);
if (info != null) {
final float[] color = info.intersectionObject.getColor(info, camera, 0);
emissionColor[0] *= color[0];
emissionColor[1] *= color[1];
emissionColor[2] *= color[2];
photons.add(new Photon(emissionColor, new float[] { info.intersection.x, info.intersection.y, info.intersection.z }, new float[] { dir.x,
dir.y, dir.z }, new float[] { info.normal.x, info.normal.y, info.normal.z }, intensity * weight, value));
origin = info.intersection;
dir = RTStatics.getReflectionDirection(info.normal, dir);
// weight = RTStatics.cosSampleHemisphere(dir, info.normal, random);
normal = info.normal;
final Vector3f invDir = new Vector3f(dir);
invDir.scale(-1f);
intensity *= Math.max(0f, info.normal.dot(invDir));
} else {
m = RTStatics.NUM_REFLECTIONS;
}
ctr++;
} else {
m = RTStatics.NUM_REFLECTIONS;
}
}
}
System.out.println("num photons: " + ctr);
RTStatics.setProgressBarValue(RTStatics.NUM_PHOTONS);
RTStatics.setProgressBarMinMax(0, photons.size());
RTStatics.setProgressBarValue(0);
RTStatics.setProgressBarString("Creating Photon Map KD-Tree");
return new PhotonTree(photons.toArray(new Photon[photons.size()]));
}
}
|
package com.generic.core.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class MVCWebApplicationInitializer implements WebApplicationInitializer{
public static final String DISPATCHER_SERVLET_NAME = "dispatcher";
public static final String DISPATCHER_SERVLET_MAPPING = "/";
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
//Registration of a Spring Application Context
AnnotationConfigWebApplicationContext annotatedRootApplicationContext = new AnnotationConfigWebApplicationContext();
annotatedRootApplicationContext.register(ApplicationContext.class);
//Registration of a Web Application Context
ServletRegistration.Dynamic dispacher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(annotatedRootApplicationContext));
dispacher.setLoadOnStartup(1);
dispacher.addMapping(DISPATCHER_SERVLET_MAPPING);
//Setting up a Spring Application Context Listener
servletContext.addListener(new ContextLoaderListener(annotatedRootApplicationContext));
}
}
|
package com.codingchili.instance.model.dialog;
import com.codingchili.instance.context.GameContext;
import com.codingchili.instance.context.InstanceSettings;
import com.codingchili.instance.model.admin.AdminEvent;
import com.codingchili.instance.model.entity.*;
import com.codingchili.instance.model.events.*;
import com.codingchili.instance.model.npc.NoSuchNpcException;
import com.codingchili.realm.configuration.RealmSettings;
import java.lang.reflect.Method;
import java.util.function.Consumer;
import com.codingchili.core.listener.Receiver;
import com.codingchili.core.protocol.*;
/**
* @author Robin Duda
* <p>
* Implements admin commands.
*/
public class AdminEngine implements Receiver<AdminEvent> {
private Protocol<AdminEvent> protocol = new Protocol<>(this);
private GameContext game;
public AdminEngine(GameContext game) {
this.game = game;
}
@Api
@Description("spawn the given entity id at the mouse position.")
public void spawn(AdminEvent event) {
game.spawner().spawn(new SpawnConfig()
.setId(event.getId())
.setPoint(event.getVector().toPoint())
).orElseThrow(() -> new NoSuchNpcException(event.getEntity()));
}
@Api
@Description("promotes the given user account to admin")
public void promote(AdminEvent event) {
PlayerCreature player = game.getById(event.getEntity());
realm(settings -> settings.getAdmins().add(player.getAccount()));
}
@Api
@Description("remove admin privileges from target.")
public void demote(AdminEvent event) {
PlayerCreature player = game.getById(event.getEntity());
realm(settings -> settings.getAdmins().remove(player.getAccount()));
}
private void realm(Consumer<RealmSettings> modifier) {
RealmSettings settings = game.instance().realm();
modifier.accept(settings);
settings.save();
}
private void instance(Consumer<InstanceSettings> modifier) {
InstanceSettings settings = game.instance().settings();
modifier.accept(settings);
settings.save();
}
@Api
@Description("gives the target quantity exp")
public void exp(AdminEvent event) {
Creature target = game.getById(event.getEntity());
game.spells().experience(target, event.getQuantity());
}
@Api
@Description("kick the targeted user")
public void kick(AdminEvent event) {
game.remove(game.getById(event.getEntity()));
}
@Api
@Description("teleport to the given instance id")
public void tele(AdminEvent event) {
game.movement().travel(game.getById(event.getEntity()), event.getId());
}
@Api
@Description("create an item in the targeted creatures inventory.")
public void item(AdminEvent event) {
game.inventory().item(game.getById(event.getEntity()), event.getId(), event.getQuantity());
}
@Api
@Description("smites the targeted creature millions of dmg.")
public void smite(AdminEvent event) {
game.spells().damage(game.getById(event.getTarget()), game.getById(event.getEntity()))
.effect("slay")
.critical(true)
.magical(-32_000_000.0)
.apply();
}
@Api
@Description("display a notification banner for the instance.")
public void banner(AdminEvent event) {
game.publish(new NotificationEvent(event.getMessage()));
}
@Api
@Description("get the id of the logged in account of the player")
public void identify(AdminEvent event) {
game.getById(event.getTarget()).handle(
new Identification(game.getById(event.getEntity()))
);
}
@Api
public void help(AdminEvent event) {
game.getById(event.getTarget()).handle(new CommandList());
}
@Override
public void handle(AdminEvent event) {
protocol.get(event.getCommand(), Role.ADMIN).submit(event);
}
private static class Identification implements Event {
private String message;
public Identification(Entity creature) {
if (creature instanceof PlayerCreature) {
PlayerCreature player = (PlayerCreature) creature;
message = player.getName() + "@" + player.getAccount();
} else {
message = creature.getName() + "@" + creature.getId();
}
}
public String getMessage() {
return message;
}
@Override
public EventType getRoute() {
return EventType.admin;
}
}
private static class CommandList implements Event {
private static final StringBuilder message = new StringBuilder();
static {
message.append("Available admin commands\n");
for (Method method : AdminEngine.class.getMethods()) {
Api api = method.getAnnotation(Api.class);
Description description = method.getAnnotation(Description.class);
if (api != null) {
message.append(".");
message.append(method.getName());
message.append(" ");
if (description != null) {
message.append(description.value());
} else {
message.append("no description for command.");
}
message.append('\n');
}
}
}
public String getMessage() {
return message.toString();
}
@Override
public EventType getRoute() {
return EventType.admin;
}
}
}
|
package velvet.obj;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class OBJFileUtils
{
public static byte[] readFileAsBytes(String filepath)
{
byte[] buffer = new byte[1024];
InputStream fileStream = OBJFileUtils.class.getResourceAsStream(filepath);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
if(fileStream == null)
{
System.out.println("[VELVET OBJ] Error reading file: Unable to locate file: " + filepath);
return null;
}
try
{
int bytes = 0;
while((bytes = fileStream.read(buffer)) > 0)
byteBuffer.write(buffer, 0, bytes);
fileStream.close();
}
catch(Exception e)
{
System.out.println("[VELVET OBJ] Error reading file: Unable to read bytes from: " + filepath);
e.printStackTrace();
return null;
}
return byteBuffer.toByteArray();
}
public static String readFileAsString(String filepath)
{
return new String(readFileAsBytes(filepath));
}
public static String getContainingFolder(String filepath)
{
int last = filepath.lastIndexOf("/"); //TODO: Allow other methods
return filepath.substring(0, last);
}
public static String stripExtention(String filename)
{
int last = filename.lastIndexOf(".");
return filename.substring(0, last);
}
public static String getFilename(String filepath)
{
String[] tokens = filepath.split("/|\\\\");
String filename = tokens[tokens.length - 1];
return stripExtention(filename);
}
public static String getFileExtention(String filepath)
{
int last = filepath.lastIndexOf(".");
return filepath.substring(last);
}
}
|
package com.UBQGenericLib;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.*;
import org.testng.asserts.SoftAssert;
import com.UBQPageObjectLib.HomePage;
import com.UBQPageObjectLib.LoginPage;
import com.UBQPageObjectLib.BeatMaster;
import com.UBQPageObjectLib.Bugzilla;
import com.UBQPageObjectLib.StockBrowser;
/**
* @author Basanagouda
*
*/
public class BaseClassLoader extends WebDriverCommonLib {
public LoginPage lgn;
public HomePage home;
public WebDriverCommonLib wcl;
// public StoreMaster store;
public String expectedvalue;
public String actualvalue;
/* public UserPage user;
public StaffMaster staff;
public UserRolesPage roles;
public DealerMaster cust;
public SyncWithServer sws;
public BeatMaster beat;
public StaffVehicleMapping svm;
public SupplierMaster slr;
public SalesInvice bentry;
public OrderEntry oentry;
public OrderBrowser obrowser;
public CollectionBulk coll;
public BankAccounts bnk;
public StockTypeTransfer stt;
public StockMovement stm;
public PurchaseOrder plo;
public PurchaseOrderBrowser pob;
public HoldOrReleaseStock hrs;
public StockAdjustment sadj;
public PaymentToSupplier pts;
public ManualCrNoteEntry mentry;
public ManualCrNoteUpdate mupdate;
public PaymentTracking pt;*/
// public VehicleMaster vehicleM;
public StockBrowser stb;
/*public ProductMaster prm;
public PriceMaster pm;
public CollectionCustomerwise collc;
public CollectionBrowser collB;
public StockTransfer stktra;
public StockTransferBrowser stkb;
public OpeningStock ostk;
public SalesInviceBrowser sib;
public ePurchaseInvoice ep;
public PurchaseInvoiceBrowser pib;
public CollectionBulk cbk;
public AdvanceSearchOptions adv;
public ArticleMaster art;
public StockEntry ste;
public StaffEntry se;
public RetailerMaster rem;
public Bugzilla Bug;
public SalesReturnEntry sre;*/
@BeforeClass
public void LoadMethods() throws Exception {
try {
logger.info("Started Loading Methods");
home = PageFactory.initElements(driver, HomePage.class);
wcl = PageFactory.initElements(driver, WebDriverCommonLib.class);
/*store = PageFactory.initElements(driver, StoreMaster.class);
user = PageFactory.initElements(driver, UserPage.class);
staff = PageFactory.initElements(driver, StaffMaster.class);
roles = PageFactory.initElements(driver, UserRolesPage.class);
cust = PageFactory.initElements(driver, DealerMaster.class);
sws = PageFactory.initElements(driver, SyncWithServer.class);
beat = PageFactory.initElements(driver, BeatMaster.class);
svm = PageFactory.initElements(driver, StaffVehicleMapping.class);
slr = PageFactory.initElements(driver, SupplierMaster.class);
bentry = PageFactory.initElements(driver, SalesInvice.class);
oentry = PageFactory.initElements(driver, OrderEntry.class);
coll = PageFactory.initElements(driver, CollectionBulk.class);
bnk = PageFactory.initElements(driver, BankAccounts.class);
stt = PageFactory.initElements(driver, StockTypeTransfer.class);
stm = PageFactory.initElements(driver, StockMovement.class);
prm= PageFactory.initElements(driver,ProductMaster.class);
plo = PageFactory.initElements(driver, PurchaseOrder.class);
pob = PageFactory.initElements(driver, PurchaseOrderBrowser.class);
ep = PageFactory.initElements(driver, ePurchaseInvoice.class);
pib = PageFactory.initElements(driver, PurchaseInvoiceBrowser.class);
hrs = PageFactory.initElements(driver, HoldOrReleaseStock.class);
sadj = PageFactory.initElements(driver, StockAdjustment.class);
pts = PageFactory.initElements(driver, PaymentToSupplier.class);
mentry = PageFactory.initElements(driver, ManualCrNoteEntry.class);
mupdate = PageFactory.initElements(driver, ManualCrNoteUpdate.class);
pt = PageFactory.initElements(driver, PaymentTracking.class);
vehicleM = PageFactory.initElements(driver, VehicleMaster.class);*/
stb = PageFactory.initElements(driver, StockBrowser.class);
/*collc = PageFactory.initElements(driver, CollectionCustomerwise.class);
stktra = PageFactory.initElements(driver, StockTransfer.class);
stkb = PageFactory.initElements(driver, StockTransferBrowser.class);
ostk = PageFactory.initElements(driver, OpeningStock.class);
obrowser = PageFactory.initElements(driver, OrderBrowser.class);
sib = PageFactory.initElements(driver, SalesInviceBrowser.class);
collB = PageFactory.initElements(driver, CollectionBrowser.class);
cbk = PageFactory.initElements(driver, CollectionBulk.class);
art = PageFactory.initElements(driver, ArticleMaster.class);
adv = PageFactory.initElements(driver, AdvanceSearchOptions.class);
ste = PageFactory.initElements(driver,StockEntry.class);
se = PageFactory.initElements(driver,StaffEntry.class);
rem = PageFactory.initElements(driver,RetailerMaster.class);
pm = PageFactory.initElements(driver,PriceMaster.class);
Bug = PageFactory.initElements(driver,Bugzilla.class);*/
ast = new SoftAssert();
logger.info("Completed Loading Methods");
wcl.waitforpageload();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.git.cloud.resmgt.common.action;
import com.git.cloud.common.action.BaseAction;
import com.git.cloud.resmgt.common.model.po.CmHostDatastoreRefPo;
import com.git.cloud.resmgt.common.service.ICmHostDatastoreRefService;
public class CmHostDatastoreRefAction extends BaseAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private ICmHostDatastoreRefService cmHostDatastoreRefServiceImpl;
private CmHostDatastoreRefPo cmHostDatastoreRefPo;
public ICmHostDatastoreRefService getCmHostDatastoreRefServiceImpl() {
return cmHostDatastoreRefServiceImpl;
}
public void setCmHostDatastoreRefServiceImpl(
ICmHostDatastoreRefService cmHostDatastoreRefServiceImpl) {
this.cmHostDatastoreRefServiceImpl = cmHostDatastoreRefServiceImpl;
}
public CmHostDatastoreRefPo getCmHostDatastoreRefPo() {
return cmHostDatastoreRefPo;
}
public void setCmHostDatastoreRefPo(CmHostDatastoreRefPo cmHostDatastoreRefPo) {
this.cmHostDatastoreRefPo = cmHostDatastoreRefPo;
}
}
|
package com.google.apiguide.appcomponents;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import com.google.apiguide.BaseActivity;
import com.google.apiguide.JumpUtil;
import com.google.apiguide.R;
import com.google.apiguide.appcomponents.activity.MyActivity;
import com.google.apiguide.appcomponents.intent.IntentActivity;
import com.google.apiguide.ipc.IpcActivity;
import com.google.apiguide.appcomponents.service.ServiceActivity;
/**
* API指南-应用组件
* Created by kangren on 2017/12/16.
*/
public class AppComponentsActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_components);
findViewById(R.id.intent).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
JumpUtil.jumpTo(mContext, IntentActivity.class);
}
});
findViewById(R.id.activity).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(mContext, MyActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
// intent.addFlags(FLAG_ACTIVITY_NEW_DOCUMENT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
});
findViewById(R.id.service).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
JumpUtil.jumpTo(mContext, ServiceActivity.class);
}
});
}
}
|
package com.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.*;
import com.entity.Product;
/**
* Servlet implementation class FormInput
*/
@WebServlet("/FormInput")
public class FormInput extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
String category = request.getParameter("category");
float price = Float.parseFloat(request.getParameter("price"));
Session session = HibernateUtility.getSession();
Transaction transaction = session.beginTransaction();
Product p = new Product(name, category, price);
session.save(p);
transaction.commit();
session.close();
response.sendRedirect("addSuccess.jsp");
}
}
|
package model;
/**
* RolePriviledgesRelationship entity. @author MyEclipse Persistence Tools
*/
public class RolePriviledgesRelationship implements java.io.Serializable {
// Fields
private Integer id;
private Role role;
private Priviledges priviledges;
// Constructors
/** default constructor */
public RolePriviledgesRelationship() {
}
/** full constructor */
public RolePriviledgesRelationship(Role role, Priviledges priviledges) {
this.role = role;
this.priviledges = priviledges;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
public Priviledges getPriviledges() {
return this.priviledges;
}
public void setPriviledges(Priviledges priviledges) {
this.priviledges = priviledges;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.