text
stringlengths
10
2.72M
/** * A Trio is a special that consists of a Sandwich, * Salad, and Drink. Price is highest two items. * * @author Ben Godfrey * @version 12 APRIL 2018 */ public class Trio implements MenuItem { /** The Sandwich item. */ private Sandwich mSandwich; /** The Salad item. */ private Salad mSalad; /** The Drink item. */ private Drink mDrink; /** * Creates a new Trio. * * @param sandwich The sandwich item. * @param salad The salad item. * @param drink The drink item. */ public Trio (Sandwich sandwich, Salad salad, Drink drink) { mSandwich = sandwich; mSalad = salad; mDrink = drink; } public String getName() { return String.format("%s/%s/%s Trio", mSandwich.getName(), mSalad.getName(), mDrink.getName()); } public double getPrice() { double[] prices = new double[] { mSandwich.getPrice(), mSalad.getPrice(), mDrink.getPrice() }; double low = prices[0]; for (double d: prices) if (Math.min(d, low) == d) low = d; double price = 0; for (double d: prices) if (d != low) price += d; return price; } public String toString() { return String.format("%n[Trio: name:\"%s\"%n price: $%d.%d]%n", getName(), (int)getPrice() / 1, (int)((getPrice() * 100) % 100)); } }
package com.choa.deal; import java.sql.Date; public class DealDTO { /*private int num;*/ private int numBook; private String product; private String idSeller; private String idBuyer; /*private Date dealDate;*/ private String status; private String name; private String tel; private String email; private String address; private Date dealdate; /*public int getNum() { return num; } public void setNum(int num) { this.num = num; }*/ public Date getDealdate() { return dealdate; } public void setDealdate(Date dealdate) { this.dealdate = dealdate; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getNumBook() { return numBook; } public void setNumBook(int numBook) { this.numBook = numBook; } public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } public String getIdSeller() { return idSeller; } public void setIdSeller(String idSeller) { this.idSeller = idSeller; } public String getIdBuyer() { return idBuyer; } public void setIdBuyer(String idBuyer) { this.idBuyer = idBuyer; } /*public Date getDealDate() { return dealDate; } public void setDealDate(Date dealDate) { this.dealDate = dealDate; }*/ /*public String getStatus() { return status; } public void setStatus(String status) { this.status = status; }*/ public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
package org.sodeja.model; import java.util.Collection; import java.util.Locale; public interface LocalizableResource { public String getId(); public void setId(String id); public String getLocalizedValue(Locale locale); public void setLocalizedValue(Locale locale, String str); public Collection<Locale> getAvailableLocales(); }
package me.maxthetomas.plasm; import org.bukkit.plugin.Plugin; public abstract class ThisPlugin { public static Plugin p; public static void constructor(Plugin p) { ThisPlugin.p = p; } public static Plugin get() { return p; } }
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Launch7 { public static void main(String[] args) { WebDriver driver=new ChromeDriver(); driver.get("https://www.magento.com"); WebElement myacct=driver.findElement(By.linkText("My Account")); myacct.click(); WebElement email=driver.findElement(By.id("email")); email.sendKeys("lastamiriya@gmail.com"); WebElement pass=driver.findElement(By.id("pass")); pass.sendKeys("Welcome12345"); WebElement login=driver.findElement(By.id("send 2")); login.click(); WebElement logout=driver.findElement(By.linkText("logout")); logout.click(); } }
package com.automationpractice.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class WomenPage { private static final String WOMEN_PAGE_URL = "http://automationpractice.com/index.php?id_category=3&controller=category"; private WebDriver driver; @FindBy(xpath = "//div[@class='content_scene_cat_bg']") private WebElement womenImg; @FindBy(xpath = "//*[@id=\"center_column\"]/ul/li[2]/div/div[1]/div/a[1]/img") private WebElement blouse; public WomenPage(WebDriver driver) { this.driver = driver; PageFactory.initElements(this.driver, this); } public void waitUntilWomenImgIsLoaded(){ WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOf(womenImg)); } public String getURL(){ return WOMEN_PAGE_URL; } public void blouseClick(){ blouse.click(); } }
package research; import java.util.ArrayList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ScrollBar; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; public class ViewContent { static GridPane gpaneView; private static int lastRowResearchViewed = 0; private static ArrayList<Integer> orderedIndicesOfDiplayedTables = new ArrayList<Integer>(); private static boolean editContentMode = false; private static ArrayList<ArrayList<TextArea>> editedResearchFields = new ArrayList<ArrayList<TextArea>>(); private static ArrayList<ArrayList<String>> tableNamesAndIds = new ArrayList<ArrayList<String>>(); private static Font fontForHeadings = new Font("Helsinki", 14); private static GridPane initViewPane() { GridPane gridPane = new GridPane(); //gridPane.setGridLinesVisible(true); gridPane.setHgap(10); gridPane.setVgap(20); gridPane.setPadding(new Insets(30,10,30,30)); // setting the widths of the output columns ColumnConstraints column = new ColumnConstraints(200); // title gridPane.getColumnConstraints().add(column); column = new ColumnConstraints(70); // date gridPane.getColumnConstraints().add(column); column = new ColumnConstraints(80); // source type gridPane.getColumnConstraints().add(column); column = new ColumnConstraints(500); // summary gridPane.getColumnConstraints().add(column); column = new ColumnConstraints(50); // link gridPane.getColumnConstraints().add(column); column = new ColumnConstraints(90); // source text gridPane.getColumnConstraints().add(column); // adding the titles for the outputted research Text titleTitle = new Text("Title"); titleTitle.setFont(fontForHeadings); gridPane.add(titleTitle, 0, 0); Text dateTitle = new Text("Date"); dateTitle.setFont(fontForHeadings); gridPane.add(dateTitle, 1, 0); Text sourceTitle = new Text("Source"); sourceTitle.setFont(fontForHeadings); gridPane.add(sourceTitle, 2, 0); Text summaryTitle = new Text("Summary"); summaryTitle.setFont(fontForHeadings); gridPane.add(summaryTitle, 3, 0); Text linkTitle = new Text("Link"); linkTitle.setFont(fontForHeadings); gridPane.add(linkTitle, 4, 0); Text sourceTextTitle = new Text("Source Text"); sourceTextTitle.setFont(fontForHeadings); gridPane.add(sourceTextTitle, 5, 0); return gridPane; } public static GridPane createViewGridPane() { // displaying the topics and their checklists on the left GridPane gpane = WindowFX.initAndAddTopicsToGridPane(); WindowFX.borderPane.setLeft(gpane); gpaneView = initViewPane(); // the gridpane that contains all the output // when a checkbox is selected, the relevant table data is displayed for (int i = 0; i < WindowFX.checkBoxes.size(); i++) { final int iFinal = i; WindowFX.checkBoxes.get(i).setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { if (WindowFX.checkBoxes.get(iFinal).isSelected()) { displayTableData(iFinal, "Text"); orderedIndicesOfDiplayedTables.add(iFinal); } else { orderedIndicesOfDiplayedTables.remove(orderedIndicesOfDiplayedTables.indexOf(iFinal)); removeTableData("Text"); } } }); } WindowFX.borderPane.setCenter(gpaneView); return gpaneView; } protected static void removeTableData(String formRedisplay) { gpaneView.getChildren().clear(); WindowFX.checkBoxes.clear(); createViewGridPane(); lastRowResearchViewed = 0; for (int i = 0; i < orderedIndicesOfDiplayedTables.size(); i++) { int index = orderedIndicesOfDiplayedTables.get(i); WindowFX.checkBoxes.get(index).setSelected(true); displayTableData(index, formRedisplay); } } protected static void displayTableData(int nthTable, String form) { String tableName = WindowFX.checkBoxes.get(nthTable).getId(); try { String[][] allData = Data.getAllData(tableName); int i; for (i = 0; i < allData.length; i++) { final int finalI = i; if (form.equals("Text")) { Text title = new Text(allData[i][1]); title.setWrappingWidth(200); gpaneView.add(title, 0, lastRowResearchViewed + i+1); Text date = new Text(allData[i][2]); date.setWrappingWidth(70); gpaneView.add(date, 1, lastRowResearchViewed + i+1); Text source = new Text(allData[i][3]); source.setWrappingWidth(80); gpaneView.add(source, 2, lastRowResearchViewed + i+1); Text summary = new Text(allData[i][4]); summary.setWrappingWidth(500); gpaneView.add(summary, 3, lastRowResearchViewed + i+1); Button link = new Button("Link"); gpaneView.add(link, 4, lastRowResearchViewed + i+1); if (allData[finalI][5].length() == 0) { link.setDisable(true); } link.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { new WindowFX().getHostServices().showDocument(allData[finalI][5]); } }); // displaying and implementing the button that opens the source text outputOpenSourceButton(allData[i][6], lastRowResearchViewed + i + 1, allData[i][1], false, WindowFX.tableNames.get(nthTable), allData[finalI][0]); } else if (form.equals("TextField")) { TextArea title = new TextArea(allData[i][1]); gpaneView.add(title, 0, lastRowResearchViewed + i+1); TextArea date = new TextArea(allData[i][2]); gpaneView.add(date, 1, lastRowResearchViewed + i+1); TextArea source = new TextArea(allData[i][3]); gpaneView.add(source, 2, lastRowResearchViewed + i+1); TextArea summary = new TextArea(allData[i][4]); gpaneView.add(summary, 3, lastRowResearchViewed + i+1); // adding all the textAreas into an arraylist that can be used to get current text and subsequently // update the database ArrayList<TextArea> rowChangedResearch = new ArrayList<TextArea>(); rowChangedResearch.add(title); rowChangedResearch.add(date); rowChangedResearch.add(source); rowChangedResearch.add(summary); editedResearchFields.add(rowChangedResearch); ArrayList<String> rowNamesIds = new ArrayList<String>(); rowNamesIds.add(tableName); rowNamesIds.add(String.valueOf(finalI+1)); tableNamesAndIds.add(rowNamesIds); Button link = new Button("Edit link"); gpaneView.add(link, 4, lastRowResearchViewed + i+1); link.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { Stage stage = new Stage(); stage.setTitle("Edit link"); VBox vbox = new VBox(); vbox.setPadding(new Insets(10)); vbox.setSpacing(3); stage.setScene(new Scene(vbox, 400, 200)); Text newLink = new Text("Enter a new link"); vbox.getChildren().add(newLink); TextField enterNewLink = new TextField(); vbox.getChildren().add(enterNewLink); Button submitNewLink = new Button("Save new link"); vbox.getChildren().add(submitNewLink); submitNewLink.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { String newLink = enterNewLink.getText(); String tableName = WindowFX.tableNames.get(nthTable); String id = allData[finalI][0]; try { Data.updateColumn(tableName, "SourceLink", newLink, id); } catch (Exception e) {} stage.close(); } }); stage.show(); } }); // displaying and implementing the button that opens the source text outputOpenSourceButton(allData[i][6], lastRowResearchViewed + i + 1, allData[i][1], true, WindowFX.tableNames.get(nthTable), allData[finalI][0]); } else { throw new InvalidFormForOutput("Unknown form for output."); } } lastRowResearchViewed += i; } catch (Exception e) { e.printStackTrace(); } } private static void outputOpenSourceButton(String sourceText, int rowToAdd, String sourceTitle, boolean editMode, String tableName, String id) { Button sourceTextButton = editMode ? new Button("Edit source") : new Button("Open source"); gpaneView.add(sourceTextButton, 5, rowToAdd); if (!editMode) { try { if (sourceText.length() == 0) sourceTextButton.setDisable(true); } catch (NullPointerException e) { sourceTextButton.setDisable(true); } } sourceTextButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { Stage stage = new Stage(); stage.setTitle(sourceTitle); VBox vbox = new VBox(); vbox.setPadding(new Insets(10)); vbox.setSpacing(3); stage.setScene(new Scene(vbox, 1000, 595)); TextArea textArea = new TextArea(sourceText); textArea.setPrefSize(1000, 500); textArea.setWrapText(true); vbox.getChildren().add(textArea); if (editMode) { Button submitNewSourceText = new Button("Save new source text"); vbox.getChildren().add(submitNewSourceText); submitNewSourceText.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { String newSourceText = textArea.getText(); try { Data.updateColumn(tableName, "SourceText", newSourceText, id); } catch (Exception e) {} stage.close(); } }); } stage.show(); } }); } public static HBox createViewMenuPane() { int buttonSizeX = 120; int buttonSizeY = 15; HBox menu = new HBox(); menu.setPadding(new Insets(15,12,15,12)); menu.setSpacing(10); menu.setStyle("-fx-background-color: #336699;"); menu = ManipulateTables.addButtons(menu); Button editContent = new Button("Edit content"); editContent.setPrefSize(buttonSizeX, buttonSizeY); editContent.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { if (!editContentMode) { removeTableData("TextField"); editContent.setText("Save your edits"); editContent.setStyle("-fx-text-inner-color: green;"); editContentMode ^= true; } else { saveEditedContent(); editContent.setText("Edit content"); editContent.setStyle("-fx-text-inner-color: black;"); editContentMode ^= true; } } }); menu.getChildren().add(editContent); // button to switch views and allow you add content String switchViewButtonText = WindowFX.viewMode ? "Switch to add" : "View content"; Button switchViewButton = new Button(switchViewButtonText); switchViewButton.setId("SwitchViewButton"); switchViewButton.setPrefSize(buttonSizeX,buttonSizeY); switchViewButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { WindowFX.viewMode ^= true; // flipping the view mode truth value as it is changing WindowFX.clearAllComponents(); // removing all components from previous mode lastRowResearchViewed = 0; WindowFX.menuPane = AddContent.createMenuPane(); WindowFX.gridPane = AddContent.createGridPane(); } }); menu.getChildren().add(switchViewButton); WindowFX.borderPane.setTop(menu); return menu; } protected static void saveEditedContent() { for (int i = 0; i < editedResearchFields.size(); i++) { try { Data.updateColumn(tableNamesAndIds.get(i).get(0), "Title", WindowFX.formatInput(editedResearchFields.get(i).get(0).getText()), tableNamesAndIds.get(i).get(1)); Data.updateColumn(tableNamesAndIds.get(i).get(0), "Date", WindowFX.formatInput(editedResearchFields.get(i).get(1).getText()), tableNamesAndIds.get(i).get(1)); Data.updateColumn(tableNamesAndIds.get(i).get(0), "SourceType", WindowFX.formatInput(editedResearchFields.get(i).get(2).getText()), tableNamesAndIds.get(i).get(1)); Data.updateColumn(tableNamesAndIds.get(i).get(0), "Conclusion", WindowFX.formatInput(editedResearchFields.get(i).get(3).getText()), tableNamesAndIds.get(i).get(1)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package com.example.notanotherweatherapp; import android.Manifest; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import com.example.notanotherweatherapp.Common.Common; import com.example.notanotherweatherapp.Database.DBManager; import com.example.notanotherweatherapp.Helper.Helper; import com.example.notanotherweatherapp.Helper.Message; import com.example.notanotherweatherapp.Model.OpenWeatherMap; import androidx.core.app.ActivityCompat; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.squareup.picasso.Picasso; import java.lang.reflect.Type; import java.text.ParseException; public class MainActivity extends AppCompatActivity implements LocationListener { TextView txtCity, txtLastUpdate, txtDescription, txtHumidity, txtTime, txtCelsius; EditText editCity; ImageView imageView; Button btnHistory, btnRefresh; LocationManager locationManager; String provider; static double lat, lon; OpenWeatherMap openWeatherMap = new OpenWeatherMap(); DBManager db = new DBManager(this); int MY_PERMISSION = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtCity = findViewById(R.id.txtCity); txtLastUpdate = findViewById(R.id.txtLastUpdate); txtCelsius = findViewById(R.id.txtCelsius); txtDescription = findViewById(R.id.txtDescription); txtHumidity = findViewById(R.id.txtHumidity); txtTime = findViewById(R.id.txtTime); imageView = findViewById(R.id.imageView); editCity = findViewById(R.id.customCityEdit); btnHistory = findViewById(R.id.btnHistory); btnRefresh = findViewById(R.id.btnRefresh); btnHistory.setOnClickListener(onClick); editCity.setOnEditorActionListener(new EditText.OnEditorActionListener(){ @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if(actionId == EditorInfo.IME_ACTION_DONE){ String city = editCity.getText().toString(); if(city.isEmpty() || city == null){ return false; } else{ if(getInputStatus(city) == "Coordinates"){ String params[] = editCity.getText().toString().split(", "); if (params.length != 2){ Message.message(MainActivity.this, "Incorrect format, example usage: 25.04, 12.03"); return false; } double latCustom = Double.parseDouble(params[0]); double lonCustom = Double.parseDouble(params[1]); new getWeatherAsync().execute(Common.APIRequest(String.valueOf(latCustom), String.valueOf(lonCustom))); } else{ new getWeatherAsync().execute(Common.APIRequest(city)); } View view = getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } return true; } return false; } }); // Getting coordinates locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); provider = locationManager.getBestProvider(new Criteria(), false); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission.INTERNET, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_PERMISSION); } Location location = locationManager.getLastKnownLocation(provider); if (location == null) { Log.e("TAG", "No Location Loaded"); } } @Override protected void onPause() { super.onPause(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission.INTERNET, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_PERMISSION); locationManager.removeUpdates(this); } } @Override protected void onResume() { super.onResume(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission.INTERNET, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_PERMISSION); } locationManager.requestLocationUpdates(provider, 400, 1, this); } @Override public void onLocationChanged(Location location) { lat = location.getLatitude(); lon = location.getLongitude(); refresh(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } private class getWeatherAsync extends AsyncTask<String,Void,String>{ ProgressDialog pd = new ProgressDialog(MainActivity.this); @Override protected void onPreExecute(){ super.onPreExecute(); pd.setTitle("Executing..."); pd.show(); } @Override protected String doInBackground(String... params) { String stream = null; String urlString = params[0]; Helper http = new Helper(); stream = http.getHttpData(urlString); return stream; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); if(s == null){ txtCity.setText(String.format("Error, Connection could not be established")); return; } if(s.contains("ERROR")){ pd.dismiss(); displayError("Could Not Find City or Coordinates"); return; } Gson gson = new Gson(); Type mType = new TypeToken<OpenWeatherMap>(){}.getType(); openWeatherMap = gson.fromJson(s, mType); pd.dismiss(); saveToDB(openWeatherMap); txtCity.setText(String.format("%s, %s, ", openWeatherMap.getName(), openWeatherMap.getSys().getCountry())); txtLastUpdate.setText(String.format("Last updated: %s", Common.getDateNow())); txtDescription.setText(String.format("%s", openWeatherMap.getWeather().get(0).getDescription())); txtHumidity.setText(String.format("%s", openWeatherMap.getMain().getHumidity())); txtTime.setText(String.format("%s/%s", Common.unixTimeStampToDate(openWeatherMap.getSys().getSunrise()), Common.unixTimeStampToDate(openWeatherMap.getSys().getSunset()))); txtCelsius.setText(String.format("%s", (int)openWeatherMap.getMain().getTemp()) + "°"); imageView.setVisibility(View.VISIBLE); Picasso.get() .load(Common.getImage(openWeatherMap.getWeather().get(0).getIcon())) .into(imageView); } private void saveToDB(OpenWeatherMap map){ db.open(); db.insertData(map); db.close(); } } private View.OnClickListener onClick = new View.OnClickListener() { @Override public void onClick(View v) { switch(v.getId()){ case R.id.btnHistory: Intent myIntent = new Intent(MainActivity.this, HistoryActivity.class); MainActivity.this.startActivity(myIntent); break; case R.id.btnRefresh: refresh(); break; default: break; } } }; private void refresh(){ new getWeatherAsync().execute(Common.APIRequest(String.valueOf(lat), String.valueOf(lon))); } private String getInputStatus(String input){ if(input.isEmpty()){ return "Empty"; } if(input.matches(".*\\d.*")){ return "Coordinates"; } return "City"; } private void displayError(String error){ txtCity.setText(error); txtLastUpdate.setText(""); txtDescription.setText(""); txtHumidity.setText(""); txtTime.setText(""); txtCelsius.setText(""); imageView.setVisibility(View.INVISIBLE); } }
package specification; import designer.ui.editor.element.Element; import designer.ui.editor.element.EndElement; import java.util.HashMap; import java.util.Map; /** * Created by Tomas Hanus on 4/17/2015. */ public class EndTransition extends EndElement { private String exitStatus; private HashMap<Element, End> endOccurences; public EndTransition() { this.endOccurences = new HashMap<Element, End>(); } public EndTransition(String id) { this.setId(id); this.endOccurences = new HashMap<Element, End>(); } public EndTransition(String id, String exitStatus) { this.setId(id); this.exitStatus = exitStatus; this.endOccurences = new HashMap<Element, End>(); } public void addEndForElement(Element element) { End newEnd = new End(getId(), exitStatus); if (element instanceof Decision) { if (((Decision) element).canAddEnd(getId())) { ((Decision) element).addEnd(newEnd); this.endOccurences.put(element, newEnd); } } else if (element instanceof Step) { if (((Step) element).canAddEnd(getId())) { ((Step) element).addEnd(newEnd); this.endOccurences.put(element, newEnd); } } else if (element instanceof Flow) { if (((Flow) element).canAddEnd(getId())) { ((Flow) element).addEnd(newEnd); this.endOccurences.put(element, newEnd); } } } public void addEndForElement(Element element, End end) { this.endOccurences.put(element, end); } public void removeEndForElement(Element element) { if (element instanceof Decision) { ((Decision) element).removeEnd(getId()); } else if (element instanceof Step) { ((Step) element).removeEnd(getId()); } else if (element instanceof Flow) { ((Flow) element).removeEnd(getId()); } this.endOccurences.remove(element); } public String getOnForElement(Element element) { if (this.endOccurences == null) return null; for (Map.Entry<Element, End> entry : this.endOccurences.entrySet()) { Element key = entry.getKey(); End value = entry.getValue(); if (element.getId().equals(key.getId())) { return value.getOn(); } } return null; } public void setOnForElement(Element element, String newOn) { if (this.endOccurences == null) return; for (Map.Entry<Element, End> entry : this.endOccurences.entrySet()) { Element key = entry.getKey(); End value = entry.getValue(); if (element.getId().equals(key.getId())) { if (key instanceof Decision) { ((Decision) key).getEnd(getId()).setOn(newOn); } else if (key instanceof Step) { ((Step) key).getEnd(getId()).setOn(newOn); } else if (key instanceof Flow) { ((Flow) key).getEnd(getId()).setOn(newOn); } value.setOn(newOn); } } } public String getExitStatus() { return exitStatus; } public void setExitStatus(String newExitStatus) { this.exitStatus = newExitStatus; if (this.endOccurences == null) return; for (Map.Entry<Element, End> entry : this.endOccurences.entrySet()) { Element key = entry.getKey(); End value = entry.getValue(); if (key instanceof Decision) { ((Decision) key).getEnd(getId()).setExitStatus(newExitStatus); } else if (key instanceof Step) { ((Step) key).getEnd(getId()).setExitStatus(newExitStatus); } else if (key instanceof Flow) { ((Flow) key).getEnd(getId()).setExitStatus(newExitStatus); } value.setExitStatus(newExitStatus); } } }
package eu.europeana.api2.v2.model.enums; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import eu.europeana.corelib.definitions.model.ThumbSize; import eu.europeana.corelib.definitions.solr.DocType; import eu.europeana.corelib.utils.ImageUtils; public enum DefaultImage { TT(ThumbSize.TINY, DocType.TEXT, "/images/item-text-tiny.gif"), TI(ThumbSize.TINY, DocType.IMAGE, "/images/item-image-tiny.gif"), TS(ThumbSize.TINY, DocType.SOUND, "/images/item-sound-tiny.gif"), TV(ThumbSize.TINY, DocType.VIDEO, "/images/item-video-tiny.gif"), T3(ThumbSize.TINY, DocType._3D, "/images/item-3d-tiny.gif"), MT(ThumbSize.MEDIUM, DocType.TEXT, "/images/item-text.gif"), MI(ThumbSize.MEDIUM, DocType.IMAGE, "/images/item-image.gif"), MS(ThumbSize.MEDIUM, DocType.SOUND, "/images/item-sound.gif"), MV(ThumbSize.MEDIUM, DocType.VIDEO, "/images/item-video.gif"), M3(ThumbSize.MEDIUM, DocType._3D, "/images/item-3d.gif"), LT(ThumbSize.LARGE, DocType.TEXT, "/images/item-text-large.gif"), LI(ThumbSize.LARGE, DocType.IMAGE, "/images/item-image-large.gif"), LS(ThumbSize.LARGE, DocType.SOUND, "/images/item-sound-large.gif"), LV(ThumbSize.LARGE, DocType.VIDEO, "/images/item-video-large.gif"), L3(ThumbSize.LARGE, DocType._3D, "/images/item-3d-large.gif"), UNKNOWN(null, null, "/images/unknown.png"); private ThumbSize size; private DocType type; private String image; private byte[] cache = null; private DefaultImage(ThumbSize size, DocType type, String image) { this.size = size; this.type = type; this.image = image; loadImage(); } private void loadImage() { try { BufferedImage buf = ImageIO.read(getClass().getResourceAsStream( image)); cache = ImageUtils.toByteArray(buf); } catch (IOException e) { // ignore, unknown image will be provided by default behavior. } } public static byte[] getImage(ThumbSize size, DocType type) { for (DefaultImage image : DefaultImage.values()) { if ((image.size == size) && (image.type == type)) { return image.cache; } } return null; } public byte[] getCache() { return cache; } }
package uk.gov.companieshouse.api.testdata.service; import uk.gov.companieshouse.api.testdata.model.entity.CompanyProfile; public interface CompanyProfileService extends DataService<CompanyProfile> { /** * Checks whether a company with the given {@code companyNumber} is present * * @param companyNumber * @return True if a company exists. False otherwise */ boolean companyExists(String companyNumber); }
package bits; public class WordProduct { public int maxProduct(String[] words) { if (words == null || words.length == 0) { return 0; } int len = words.length; int[] wordValues = new int[words.length]; for (int i = 0; i < len; i++) { String s = words[i]; for (char c : s.toCharArray()) { wordValues[i] |= 1 << (c - 'a') ; } } int maxLength = 0; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { if ((wordValues[i] & wordValues[j]) == 0) { maxLength = Math.max(maxLength, words[i].length() * words[j].length()); } } } return maxLength; } public static void main(String[] args) { // TODO Auto-generated method stub String[] words = new String[] { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" }; WordProduct wordProduct = new WordProduct(); System.out.println(wordProduct.maxProduct(words)); } }
package com.tencent.mm.plugin.chatroom.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import com.tencent.mm.bg.d; import com.tencent.mm.plugin.report.service.h; class ChatroomInfoUI$16 implements OnClickListener { final /* synthetic */ ChatroomInfoUI hLX; ChatroomInfoUI$16(ChatroomInfoUI chatroomInfoUI) { this.hLX = chatroomInfoUI; } public final void onClick(DialogInterface dialogInterface, int i) { h.mEJ.h(14553, new Object[]{Integer.valueOf(4), Integer.valueOf(4), ChatroomInfoUI.b(this.hLX)}); ChatroomInfoUI.a(this.hLX, true); if (ChatroomInfoUI.x(this.hLX)) { this.hLX.finish(); return; } Intent intent = new Intent(); intent.putExtra("Chat_User", ChatroomInfoUI.o(this.hLX).field_username); intent.addFlags(67108864); d.e(this.hLX, ".ui.chatting.ChattingUI", intent); } }
package com.navnath.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.navnath.service.BankAccountServices; @RestController public class BankAccountController { @Autowired private BankAccountServices bankAccountServices; @GetMapping(value = "/testConnectivity") public ResponseEntity<String> testConnectivity() { return ResponseEntity.ok("{Status }" + bankAccountServices.testConnectivity() ); } }
//This class is responsible for creating the seeds used in the game import java.awt.Image; public class Particle extends movingObject { private Image picture; public Particle (int x, int y, int h, int v, Image pic) { super (x,y,h,v); setPicture(pic); } public void setPicture(Image picture) { this.picture = picture; } public Image getPicture() { return picture; } }
package com.sinata.rwxchina.component_basic.basic.basiclist.adapter; import android.content.Context; import android.graphics.Color; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RatingBar; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.sinata.rwxchina.basiclib.HttpPath; import com.sinata.rwxchina.basiclib.entity.BaseShopInfo; import com.sinata.rwxchina.basiclib.utils.imageUtils.ImageUtils; import com.sinata.rwxchina.component_basic.R; import java.util.List; /** * @author HRR * @datetime 2017/12/22 * @describe 娱乐商铺列表适配器 * @modifyRecord */ public class BasicListAdapter extends BaseQuickAdapter<BaseShopInfo, BaseViewHolder> { private Context mC; public BasicListAdapter(Context context, @LayoutRes int layoutResId, @Nullable List<BaseShopInfo> data) { super(layoutResId, data); this.mC = context; } @Override protected void convert(BaseViewHolder helper, BaseShopInfo item) { String star = item.getShop_starlevel(); ImageUtils.showImage(mC, HttpPath.IMAGEURL + item.getShop_logo(), (ImageView) helper.getView(R.id.item_entertainment_list_image)); helper.setText(R.id.item_entertainment_list_name, item.getShop_name()) .setText(R.id.item_entertainment_list_ratingnum, "(" + star + "分)") .setText(R.id.item_entertainment_list_address, item.getShop_address()) .setText(R.id.item_entertainment_list_miles, item.getDistance() + "km"); //美食显示人均价格,其他显示最低价 if ("3".equals(item.getShop_type())) { helper.setText(R.id.item_entertainment_list_RMB, item.getShop_people_avgmoney()); helper.getView(R.id.item_entertainment_list_avg).setVisibility(View.VISIBLE); helper.setText(R.id.item_entertainment_list_price, "元"); helper.setTextColor(R.id.item_entertainment_list_price, Color.parseColor("#ff720a")); } else { helper.getView(R.id.item_entertainment_list_avg).setVisibility(View.GONE); helper.setText(R.id.item_entertainment_list_RMB, "¥" + item.getShop_goodsmoney_min()); helper.getView(R.id.item_entertainment_list_price).setVisibility(View.VISIBLE); } //设置评论星 RatingBar bar = helper.getView(R.id.item_entertainment_list_rating); if (TextUtils.isEmpty(star)) { star = "0"; } bar.setRating(Float.parseFloat(star)); String tuan = item.getShop_tuan().replace(",", " "); String quan = item.getShop_juan().replace(",", " "); LinearLayout quanll = helper.getView(R.id.item_entertianment_list_quan); LinearLayout groupll = helper.getView(R.id.item_entertainment_list_group); //判断团购是否为空 if (TextUtils.isEmpty(tuan)) { groupll.setVisibility(View.GONE); } else { groupll.setVisibility(View.VISIBLE); helper.setText(R.id.item_entertainment_list_group_tv, tuan); } //判断代金券是否为空 if (TextUtils.isEmpty(quan)) { quanll.setVisibility(View.GONE); } else { quanll.setVisibility(View.VISIBLE); helper.setText(R.id.item_entertainment_list_voucher, quan); } //没有团购和代金券 if (TextUtils.isEmpty(tuan) && TextUtils.isEmpty(quan)) { helper.getView(R.id.item_entertianment_list_line).setVisibility(View.GONE); helper.getView(R.id.item_entertianment_service).setVisibility(View.GONE); } } }
package com.example.tarea1; public class Datos{ String direccion; String telefono; String horario; String website; String email; public Datos(String dir,String tel,String schedule, String web_site, String e_mail){ direccion = dir; telefono = tel; horario = schedule; website = web_site; email = e_mail; } public String getdireccion(){ return direccion; } public String gettelefono(){ return telefono; } public String gethorario(){ return horario; } public String getwebsite(){ return website; } public String getemail(){ return email; } }
import java.util.ArrayList; import java.util.Scanner; public class Customer implements IDisplay { // creating object of scanner class Scanner input = new Scanner(System.in); Scanner displayInput = new Scanner(System.in); // properties of Customer Class private int customerId; private String firstName; private String lastName; private String fullName; private String emailId; private double totalAmount; ArrayList<Bill> bills = new ArrayList<Bill>(); // constructor public Customer(int customerId, String firstName, String lastName, String emailId, double totalAmount, ArrayList<Bill> bills) { this.customerId = customerId; this.firstName = firstName; this.lastName = lastName; this.fullName = firstName + " " + lastName; this.emailId = emailId; this.totalAmount = totalAmount; this.bills = bills; } // getters and setters public int getCustomerId() { return customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public double getTotalAmount() { return totalAmount; } public void setTotalAmount(double totalAmount) { this.totalAmount = totalAmount; } public ArrayList<Bill> getBills() { return bills; } public void setBills(ArrayList<Bill> bills) { this.bills = bills; } // Methods of Customer class // Creating the method to get customer by id public void getCustomerById(Customer[] C) { System.out.println("Enter the id of Customer you want to search for"); // getting the id from the user int newId = displayInput.nextInt(); boolean found = true; for (int i = 0; i < C.length; i++) { if (newId == C[i].customerId) { // displaying the info System.out.println("The customer found is: " + C[i].fullName); found = false; } } // displaying the error if (found) System.out.println("Sorry, the Id you enetered does not belong to any customer!"); } // defining method of interface public void Display(Customer[] CustomerList) { System.out.println("Enter Y to display information of all customers or Enter N to exit: "); String userInput = input.nextLine(); if (userInput.equalsIgnoreCase("y")) { // calling fucntion to sort the customers according to their id's Customer[] C = sortCustomers(CustomerList); // running for loop to get to each and every customer in the list for (int i = 0; i < C.length; i++) { // Calling method to sort bills of a particular customer C[i].bills = sortBills(C[i].bills); System.out.println(""); System.out.println(""); System.out.println("Customer Id: " + C[i].customerId); System.out.println("Customer FullName: " + C[i].fullName); System.out.println("Customer Email Id: " + C[i].emailId); System.out.println("-----Bill information-----"); try { System.out.println( "****************************************************************************************"); // running for loop to get all the bills of each customer for (int j = 0; j < C[i].bills.size(); j++) { System.out.println(""); System.out.println("Bill Id: " + C[i].bills.get(j).getBillId()); System.out.println("Bill Date: " + C[i].bills.get(j).getBillDate()); System.out.println("Bill Type: " + C[i].bills.get(j).getBillType()); System.out.println("Bill Amount: $" + C[i].bills.get(j).getTotalBillAmount()); // handling cases related to particular type of child classes of bill by object // casting if (C[i].bills.get(j).getBillType() == "Hydro") { Hydro h = (Hydro) C[i].bills.get(j); System.out.println("Company Name: " + h.getAgencyName()); System.out.println("Unit Consumed: " + h.getUnitConsumed()); } if (C[i].bills.get(j).getBillType() == "Internet") { Internet it = (Internet) C[i].bills.get(j); System.out.println("Provider Name: " + it.getProviderName()); System.out.println("Internet Usage: " + it.getGbUsed()); } if (C[i].bills.get(j).getBillType() == "Mobile") { Mobile m = (Mobile) C[i].bills.get(j); System.out.println("Manufacturer Name: " + m.getMobileManufacturerName()); System.out.println("Plan Name: " + m.getPlanName()); System.out.println("Mobile Number: " + m.getMobileNumber()); System.out.println("Internet Usage: " + m.getInternetGbUsed()); System.out.println("Minutes Usage: " + m.getMinutesUsed()); } } double totalBill = 0.0; int k = 0; // getting the sum of the bills while (k < C[i].bills.size()) { totalBill += C[i].bills.get(k).getTotalBillAmount(); k++; } if (C[i].bills.size() > 0) { System.out.println( "****************************************************************************************"); System.out.println("Total Bill Amount to Pay: $" + totalBill); System.out.println( "****************************************************************************************"); } else System.out.println(C[i].fullName + " has no more bills to pay!"); } catch (Exception e) { System.out.println(e.getMessage()); } } } else if (userInput.equalsIgnoreCase("n")) System.out.println("Thanks"); else { System.out.println("Please enter the correct value!"); Display(CustomerList); } } // function defination to sort the customers in the customer list public Customer[] sortCustomers(Customer[] unsortedCustomerList) { int tempId = 0; for (int j = 0; j < unsortedCustomerList.length; j++) { for (int i = 0; i < unsortedCustomerList.length - 1; i++) { if (unsortedCustomerList[i + 1].getCustomerId() < unsortedCustomerList[i].getCustomerId()) { tempId = unsortedCustomerList[i].getCustomerId(); unsortedCustomerList[i].setCustomerId(unsortedCustomerList[i + 1].getCustomerId()); unsortedCustomerList[i + 1].setCustomerId(tempId); } } } return unsortedCustomerList; } // function to sort bills of a particular customer in the bills ArrayList public ArrayList<Bill> sortBills(ArrayList<Bill> List) { for (int j = 0; j < List.size(); j++) { double tempBillAmount = 0; for (int i = 0; i < List.size() - 1; i++) { if (List.get(i + 1).getTotalBillAmount() < List.get(i).getTotalBillAmount()) { tempBillAmount = List.get(i).getTotalBillAmount(); List.get(i).setTotalBillAmount(List.get(i + 1).getTotalBillAmount()); List.get(i + 1).setTotalBillAmount(tempBillAmount); } } } return List; } }
/* * 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 modelo; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author Damian */ public class PIntervencion extends Intervencion implements IPersistencia{ private Conexion conexion; public PIntervencion(Conexion conexion) { this.conexion = conexion; } public PIntervencion() { } public PIntervencion(Conexion conexion, String fec, String descripcion, int numero, String tipo) { super(fec, descripcion, numero, tipo); this.conexion = conexion; } public void agregar() { String sql = "INSERT INTO intervenciones SET numero='"+getNumero()+"', "+ "tipo='"+getTipo()+"', fecha='"+getFec()+"'"+", descripcion='"+getDescripcion()+"'"; try{ conexion.getSentencia().execute(sql); } catch(SQLException e){ System.out.println("Error al insertar datos "); } } public void modificar() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public void eliminar() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public boolean buscar() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public ResultSet lista() { String sql = "SELECT * FROM intervenciones "; try{ conexion.getSentencia().executeQuery(sql); return conexion.getSentencia().getResultSet(); } catch(SQLException e){ System.out.println("Error al intentar recuperar la lista"); } return null; } }
/* Java Power Info utility, (C)2021 IC Book Labs View Panel for single table */ package powerinfo; import javax.swing.*; import javax.swing.table.*; public class ViewerTable extends ViewPanel { private final JPanel p; // complex panel private final JScrollPane sp1; // scroll panels private final JTable table; // tables private final AbstractTableModel atm; // tables models private final BoxLayout bl; // layout manager public ViewerTable ( int x, int y, AbstractTableModel z1 ) { atm = z1; // Built panel components table = new JTable( atm ); sp1 = new JScrollPane( table ); // Built panel and set layout p = new JPanel(); bl = new BoxLayout( p, BoxLayout.X_AXIS ); p.setLayout( bl ); p.add( sp1 ); } // Return panel @Override public JPanel getP() { return p; } // Return table @Override public JTable getTable() { return table; } // Return combo box @Override public JComboBox getCombo() { return null; } // Return clear button @Override public JButton getClearButton() { return null; } // Return run button @Override public JButton getRunButton() { return null; } }
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_models; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.web.bind.annotation.CrossOrigin; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name = "RECIPE_TYPE") @CrossOrigin public class RecipeType implements Serializable { /** * */ private static final long serialVersionUID = 431117213266848807L; public int recipe_type_idd; public String restaurant_type_descr; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "recipe_type_id") public int getRecipe_type_idd() { return recipe_type_idd; } public void setRecipe_type_idd(int recipe_type_idd) { this.recipe_type_idd = recipe_type_idd; } @Column(name = "descr") public String getDescr() { return restaurant_type_descr; } public void setDescr(String descr) { this.restaurant_type_descr = descr; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + recipe_type_idd; result = prime * result + ((restaurant_type_descr == null) ? 0 : restaurant_type_descr.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RecipeType other = (RecipeType) obj; if (recipe_type_idd != other.recipe_type_idd) return false; if (restaurant_type_descr == null) { if (other.restaurant_type_descr != null) return false; } else if (!restaurant_type_descr.equals(other.restaurant_type_descr)) return false; return true; } @Override public String toString() { return "RecipeType [recipe_type_idd=" + recipe_type_idd + ", restaurant_type_descr=" + restaurant_type_descr + "]"; } public RecipeType(int recipe_type_idd, String restaurant_type_descr) { super(); this.recipe_type_idd = recipe_type_idd; this.restaurant_type_descr = restaurant_type_descr; } public RecipeType() { super(); // TODO Auto-generated constructor stub } }
package problem_solve.bfs.baekjoon; import java.util.*; public class BaekJoon2667 { // 아파트 단지 번호 붙이기 private static String apart[]; private static boolean visited[][]; private static List<Integer> list; public static void main(String[] args){ Scanner scan = new Scanner(System.in); int size = Integer.parseInt(scan.nextLine()); apart = new String[size]; visited = new boolean[size][size]; list = new ArrayList<>(); for(int i=0; i < size; i++){ apart[i] = scan.nextLine(); } for(int i=0; i < size; i++){ for(int j=0; j < size; j++){ if(!visited[i][j] && apart[i].charAt(j) == '1'){ list.add(bfs(i, j, size)); } } } Collections.sort(list); int s = list.size(); System.out.println(s); for(int i=0; i < s; i++){ System.out.println(list.get(i)); } } public static int bfs(int y, int x, int size){ Queue<Apart> q = new LinkedList<>(); q.add(new Apart(x, y)); visited[y][x] = true; int ret_val = 1; int[] moveX = {-1, 0, 1, 0}; int[] moveY = {0, 1, 0, -1}; while(!q.isEmpty()){ Apart ap = q.remove(); for(int i=0; i < 4; i++){ int nextX = ap.getX() + moveX[i]; int nextY = ap.getY() + moveY[i]; if(0 <= nextX && nextX < size && 0 <= nextY && nextY < size && !visited[nextY][nextX] && apart[nextY].charAt(nextX) == '1'){ visited[nextY][nextX] = true; q.add(new Apart(nextX, nextY)); ret_val++; } } } return ret_val; } } class Apart{ private int x; private int y; Apart(int x, int y){ this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } }
/* * 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 UI.ChuongTrinh; import BUS.bus_ChuongTrinh; import DTO.dto_ChungChi; import DTO.dto_ChuongTrinh; import java.util.ArrayList; import javax.swing.ButtonGroup; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JComboBox; import javax.swing.JOptionPane; /** * * @author USER */ public class FormThemChuongTrinh extends javax.swing.JFrame { /** * Creates new form FormThemChuongTrinh */ public FormThemChuongTrinh() { initComponents(); setupForm(); } /*Khu vực của Tân*/ // biến tự định nghĩa static DefaultComboBoxModel static_dfcDsChungChi; static ArrayList<dto_ChungChi> static_dsChungChi; // HÀM SETUP FORM public void setupForm() { static_dsChungChi = new ArrayList<dto_ChungChi>(); // static_dsChungChi = new bus_ChuongTrinh().layDsChungChi(); // if (static_dsChungChi != null) { // for (int i = 0; i < static_dsChungChi.size(); i++) { // cbTenCc.addItem(static_dsChungChi.get(i)); // } // } static_dfcDsChungChi = new DefaultComboBoxModel(); static_dfcDsChungChi.addElement(static_dsChungChi); // addAll cbTenCc.setModel(static_dfcDsChungChi); ButtonGroup btnGroup = new ButtonGroup(); btnGroup.add(radCong); btnGroup.add(radTrungBinhCong); ButtonGroup btnGroupTrangThai = new ButtonGroup(); btnGroupTrangThai.add(radDong); btnGroupTrangThai.add(radMo); } // HÀM THÊM CHƯƠNG TRÌNH public void themChuongTrinh() { dto_ChuongTrinh ct = new dto_ChuongTrinh(); ct = layThongTinNhap(); if (ct != null) { int rs = new bus_ChuongTrinh().themChuongTrinh(ct); if (rs == 0) { JOptionPane.showMessageDialog(null, "Không thành công"); } else { UI_ChuongTrinh.hienThiDsChuongTrinh(0); JOptionPane.showMessageDialog(null, "Thành công"); } } } // HÀM LẤY THÔNG TIN NHẬP public dto_ChuongTrinh layThongTinNhap() { dto_ChungChi cc = (dto_ChungChi) static_dfcDsChungChi.getSelectedItem(); dto_ChuongTrinh ct = null; String strTen = txtTenCt.getText(); String strDiemDauVao = txtDiemDauVao.getText(); String strDiemDauRa = txtDiemDauRa.getText(); boolean isCkNghe = ckNghe.isSelected(); boolean isCkNoi = ckNoi.isSelected(); boolean isCkDoc = ckDoc.isSelected(); boolean isCkViet = ckViet.isSelected(); boolean isCkTinhTong = radCong.isSelected(); boolean isCkTinhTrungBinhCong = radTrungBinhCong.isSelected(); boolean isCkDong = radDong.isSelected(); boolean isCkMo = radMo.isSelected(); String strNoiDung = txtNoiDung.getText(); int kqkt = kiemTraThongTinNhap(cc, strTen, strDiemDauVao, strDiemDauRa, isCkNghe, isCkNoi, isCkDoc, isCkViet, isCkTinhTong, isCkTinhTrungBinhCong, strNoiDung, isCkDong, isCkMo); if (kqkt == 0) { JOptionPane.showMessageDialog(null, "Chưa nhập đủ thông tin"); } else if (kqkt == 1) { JOptionPane.showMessageDialog(null, "Điểm nhập vào không hợp lệ"); } else if (kqkt == 2) { Float diemDauRa = 0F; Float diemDauVao = 0F; try { diemDauVao = Float.parseFloat(strDiemDauVao); diemDauRa = Float.parseFloat(strDiemDauRa); } catch (Exception ex) { ex.printStackTrace(); } ct = new dto_ChuongTrinh(); ct.setMaCc(cc.getMaCc()); ct.setTenCt(strTen); ct.setDiemDauVao(diemDauVao); ct.setDiemDauRa(diemDauRa); ct.setNoiDung(strNoiDung); if (isCkNghe == true) { ct.setTinhNghe(1); } else { ct.setTinhNghe(0); } if (isCkNoi == true) { ct.setTinhNoi(1); } else { ct.setTinhNoi(0); } if (isCkDoc == true) { ct.setTinhDoc(1); } else { ct.setTinhDoc(0); } if (isCkViet == true) { ct.setTinhViet(1); } else { ct.setTinhViet(0); } if (isCkTinhTong == true) { ct.setCachTinhDiem(1); } else { ct.setCachTinhDiem(2); } if (isCkDong == true) { ct.setTrangThai(0); } else { ct.setTrangThai(1); } } return ct; } // HÀM KIỂM TRA THÔNG TIN NHẬP VÀO: 0 là thông tin nhập chưa đủ, 1-chuyển đổi số thất bại, 2-Thông tin nhập không hợp lệ, 3-thành công public int kiemTraThongTinNhap(dto_ChungChi cc, String strTen, String diemDauVao, String diemDauRa, boolean ckNghe, boolean ckNoi, boolean ckDoc, boolean ckViet, boolean ckTong, boolean ckTrungBinhCong, String noiDung, boolean ckDong, boolean ckMo) { if (cc == null) { return 0; } if (ckNghe == ckNoi == ckDoc == ckViet == ckTong == ckTrungBinhCong == ckDong == ckMo == false) { return 0; } if (strTen.isEmpty() || diemDauVao.isEmpty() || diemDauRa.isEmpty() || noiDung.isEmpty()) { return 0; } else { Float dauRa; Float dauVao; try { dauVao = Float.parseFloat(diemDauVao); dauRa = Float.parseFloat(diemDauRa); } catch (Exception ex) { System.out.println("Chuyển đổi sang số thất bại"); return 1; // Thông tin nhập không hợp lệ. } if (dauRa <= dauVao || dauRa > cc.getDiemToiDa()) { return 1; // thông tin nhập không hợp lệ } } return 2;//thanh cong } /** * 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() { pnThem = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); txtTenCt = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); txtNoiDung = new javax.swing.JTextArea(); btnXacNhan = new javax.swing.JButton(); txtDiemDauVao = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); txtDiemDauRa = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); cbTenCc = new javax.swing.JComboBox<>(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); ckNghe = new javax.swing.JCheckBox(); ckNoi = new javax.swing.JCheckBox(); ckDoc = new javax.swing.JCheckBox(); ckViet = new javax.swing.JCheckBox(); radCong = new javax.swing.JRadioButton(); radTrungBinhCong = new javax.swing.JRadioButton(); jLabel9 = new javax.swing.JLabel(); txtMaCc = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); txtDiemToiDa = new javax.swing.JTextField(); lblLogo = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); radDong = new javax.swing.JRadioButton(); radMo = new javax.swing.JRadioButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Tạo Chương Trình Mới"); setResizable(false); pnThem.setBackground(new java.awt.Color(255, 255, 255)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setText("Tạo Mới"); jLabel2.setText("Tên Chương Trình"); jLabel3.setText("Điểm Đầu Vào"); txtTenCt.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel4.setText("Ghi Chú"); txtNoiDung.setColumns(20); txtNoiDung.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N txtNoiDung.setRows(5); txtNoiDung.setPreferredSize(new java.awt.Dimension(150, 74)); jScrollPane1.setViewportView(txtNoiDung); btnXacNhan.setBackground(new java.awt.Color(91, 155, 213)); btnXacNhan.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnXacNhan.setForeground(new java.awt.Color(255, 255, 255)); btnXacNhan.setText("XÁC NHẬN"); btnXacNhan.setContentAreaFilled(false); btnXacNhan.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); btnXacNhan.setFocusable(false); btnXacNhan.setOpaque(true); btnXacNhan.setPreferredSize(new java.awt.Dimension(209, 40)); btnXacNhan.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnXacNhanActionPerformed(evt); } }); txtDiemDauVao.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N txtDiemDauVao.setForeground(new java.awt.Color(0, 102, 153)); txtDiemDauVao.setHorizontalAlignment(javax.swing.JTextField.CENTER); jLabel5.setText("Điểm Đầu Ra"); txtDiemDauRa.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N txtDiemDauRa.setForeground(new java.awt.Color(0, 102, 153)); txtDiemDauRa.setHorizontalAlignment(javax.swing.JTextField.CENTER); jLabel6.setText("Chứng Chỉ"); cbTenCc.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N cbTenCc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbTenCcActionPerformed(evt); } }); jLabel7.setText("Cách Tính Tổng Điểm Thành Phần"); jLabel8.setText("Điểm Thành Phần"); ckNghe.setText("Nghe"); ckNoi.setText("Nói"); ckDoc.setText("Đọc"); ckViet.setText("Viết"); radCong.setBackground(new java.awt.Color(255, 255, 255)); radCong.setText("Cộng Tất Cả"); radTrungBinhCong.setBackground(new java.awt.Color(255, 255, 255)); radTrungBinhCong.setText("Trung Bình Cộng"); jLabel9.setText("Mã Chứng Chỉ"); txtMaCc.setEditable(false); txtMaCc.setHorizontalAlignment(javax.swing.JTextField.CENTER); jLabel10.setText("Điểm Tối Đa"); txtDiemToiDa.setEditable(false); txtDiemToiDa.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N txtDiemToiDa.setHorizontalAlignment(javax.swing.JTextField.CENTER); lblLogo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ielts.png"))); // NOI18N lblLogo.setText("Ảnh 300x150"); jLabel11.setText("Trạng Thái"); radDong.setBackground(new java.awt.Color(255, 255, 255)); radDong.setText("Đóng "); radMo.setBackground(new java.awt.Color(255, 255, 255)); radMo.setText("Mở"); javax.swing.GroupLayout pnThemLayout = new javax.swing.GroupLayout(pnThem); pnThem.setLayout(pnThemLayout); pnThemLayout.setHorizontalGroup( pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnThemLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnXacNhan, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(241, 241, 241)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnThemLayout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnThemLayout.createSequentialGroup() .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnThemLayout.createSequentialGroup() .addComponent(jLabel4) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane1)) .addGap(24, 24, 24)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnThemLayout.createSequentialGroup() .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(lblLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(cbTenCc, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(pnThemLayout.createSequentialGroup() .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnThemLayout.createSequentialGroup() .addComponent(txtMaCc, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnThemLayout.createSequentialGroup() .addComponent(jLabel9) .addGap(100, 100, 100))) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(txtDiemToiDa, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel11) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtTenCt, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnThemLayout.createSequentialGroup() .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel7) .addGroup(pnThemLayout.createSequentialGroup() .addComponent(ckNghe) .addGap(18, 18, 18) .addComponent(ckNoi) .addGap(18, 18, 18) .addComponent(ckDoc) .addGap(18, 18, 18) .addComponent(ckViet)) .addComponent(jLabel8) .addGroup(pnThemLayout.createSequentialGroup() .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(radCong) .addComponent(radDong)) .addGap(18, 18, 18) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(radMo) .addComponent(radTrungBinhCong)))) .addGap(59, 59, 59)) .addGroup(pnThemLayout.createSequentialGroup() .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(txtDiemDauVao, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(61, 61, 61) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnThemLayout.createSequentialGroup() .addComponent(txtDiemDauRa) .addGap(24, 24, 24)) .addGroup(pnThemLayout.createSequentialGroup() .addComponent(jLabel5) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnThemLayout.createSequentialGroup() .addComponent(jLabel1) .addGap(123, 123, 123))))))) ); pnThemLayout.setVerticalGroup( pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnThemLayout.createSequentialGroup() .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(pnThemLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(pnThemLayout.createSequentialGroup() .addGap(26, 26, 26) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtTenCt, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel5)))) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnThemLayout.createSequentialGroup() .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtDiemDauVao, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtDiemDauRa, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(36, 36, 36) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ckNghe) .addComponent(ckNoi) .addComponent(ckDoc) .addComponent(ckViet)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel7)) .addGroup(pnThemLayout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbTenCc, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtDiemToiDa, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtMaCc, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 14, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(radCong) .addComponent(radTrungBinhCong)) .addGap(18, 18, 18) .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnThemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(radDong) .addComponent(radMo)) .addGap(4, 4, 4) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnXacNhan, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnThem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnThem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btnXacNhanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXacNhanActionPerformed themChuongTrinh(); }//GEN-LAST:event_btnXacNhanActionPerformed private void cbTenCcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbTenCcActionPerformed dto_ChungChi cc = (dto_ChungChi) static_dfcDsChungChi.getSelectedItem(); txtMaCc.setText(cc.getMaCc() + ""); txtDiemToiDa.setText(cc.getDiemToiDa() + ""); lblLogo.setIcon(new ImageIcon(cc.getSrcImg())); }//GEN-LAST:event_cbTenCcActionPerformed /** * @param args the command line arguments */ 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(FormThemChuongTrinh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormThemChuongTrinh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormThemChuongTrinh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormThemChuongTrinh.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 FormThemChuongTrinh().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnXacNhan; private javax.swing.JComboBox<String> cbTenCc; private javax.swing.JCheckBox ckDoc; private javax.swing.JCheckBox ckNghe; private javax.swing.JCheckBox ckNoi; private javax.swing.JCheckBox ckViet; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblLogo; private javax.swing.JPanel pnThem; private javax.swing.JRadioButton radCong; private javax.swing.JRadioButton radDong; private javax.swing.JRadioButton radMo; private javax.swing.JRadioButton radTrungBinhCong; private javax.swing.JTextField txtDiemDauRa; private javax.swing.JTextField txtDiemDauVao; private javax.swing.JTextField txtDiemToiDa; private javax.swing.JTextField txtMaCc; private javax.swing.JTextArea txtNoiDung; private javax.swing.JTextField txtTenCt; // End of variables declaration//GEN-END:variables }
// USING AN ARRAY class MaxPriorityQueue_array { int length; int[] arr; int middleIndex; int greatest_idx = -1; // STORE the index of the greatest of the 2 children public MaxPriorityQueue_array(int[] arr) { this.arr = arr; length = arr.length; middleIndex = (int) ((length - 1) / 2); } public void createPriorityQueue() { // go to the start of the array, down with index middleIndex = (int) ((arr.length - 1) / 2); for (int i = middleIndex; i >= 0; i--) goDown(i); } // store value y in x and viceversa public void swap(int idx1, int idx2) { int tmp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = tmp; } // used by create a new heap from array or add a new element, to keep the heap a // max/min heap // percolate down items not in order to maintain a the greatest/smallest value public void goDown(int pos) { int left = 2 * pos + 1; int right = left + 1; if (left < length) greatest_idx = left; // init from left child if (right < length && arr[right] > arr[left]) greatest_idx = right; // take the greatest_idx of the 2 children if (greatest_idx != -1 && arr[greatest_idx] > arr[pos]) { swap(pos, greatest_idx); goDown(greatest_idx); } } public void add(int item) { copyArrayInAnother(0, length - 1, length + 1); arr[length - 1] = item; createPriorityQueue(); } public int getHeapValue() { int heapValue = arr[0]; copyArrayInAnother(1, length - 1, length - 1); createPriorityQueue(); return heapValue; } public void removeItem(int item) { int index = find(item); if (index == -1) { System.out.println("Element not present."); return; } copyArrayInAnother_ExcludingIndexInterval(0, index, index + 1, length - 1); createPriorityQueue(); } public void copyArrayInAnother(int start, int end, int newArrayLength) { int[] tmp_arr = new int[newArrayLength]; int count = 0; for (int i = start; i <= end; i++) { tmp_arr[count] = arr[i]; count++; } arr = tmp_arr; length = arr.length; } public int find(int item) { for (int i = 0; i < arr.length; i++) if (arr[i] == item) return i; return -1; } public void copyArrayInAnother_ExcludingIndexInterval(int start1, int end1, int start2, int end2) { int newArrayLength = (end1 - start1) + (end2 - start2) + 1; int[] tmp_arr = new int[newArrayLength]; int count = 0; for (int i = start1; i < end1; i++) { tmp_arr[count] = arr[i]; count++; } for (int i = start2; i <= end2; i++) { tmp_arr[count] = arr[i]; count++; } arr = tmp_arr; length = arr.length; } public void printArr() { for (int i : arr) System.out.print(i + " "); System.out.println(""); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.webbeans.test.interceptors.resolution; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.spi.AnnotatedType; import jakarta.enterprise.inject.spi.InterceptionType; import jakarta.enterprise.inject.spi.Interceptor; import java.util.ArrayList; import java.util.Collection; import org.apache.webbeans.component.BeanAttributesImpl; import org.apache.webbeans.component.InterceptorBean; import org.apache.webbeans.component.creation.BeanAttributesBuilder; import org.apache.webbeans.component.creation.CdiInterceptorBeanBuilder; import org.apache.webbeans.test.AbstractUnitTest; import org.apache.webbeans.test.interceptors.factory.beans.ClassInterceptedClass; import org.apache.webbeans.test.interceptors.resolution.beans.UtilitySampleBean; import org.apache.webbeans.test.interceptors.resolution.interceptors.TestIntercepted1; import org.apache.webbeans.test.interceptors.resolution.interceptors.TestInterceptor1; import org.apache.webbeans.test.interceptors.resolution.interceptors.TestInterceptorParent; import org.apache.webbeans.test.component.intercept.webbeans.SecureAndTransactionalInterceptor; import org.apache.webbeans.test.component.intercept.webbeans.TransactionalInterceptor; import org.apache.webbeans.test.component.intercept.webbeans.bindings.Transactional; import org.junit.Assert; import org.junit.Test; /** * Tests for the various InterceptorBeanBuilder implementations. */ public class CdiInterceptorBeanBuilderTest extends AbstractUnitTest { @Test public void testClassLevelSingleInterceptor() throws Exception { Collection<String> beanXmls = new ArrayList<String>(); beanXmls.add(getXmlPath(this.getClass().getPackage().getName(), InterceptorResolutionServiceTest.class.getSimpleName())); Collection<Class<?>> beanClasses = new ArrayList<Class<?>>(); beanClasses.add(ClassInterceptedClass.class); beanClasses.add(Transactional.class); beanClasses.add(TransactionalInterceptor.class); beanClasses.add(TestIntercepted1.class); beanClasses.add(TestInterceptor1.class); beanClasses.add(TestInterceptorParent.class); beanClasses.add(UtilitySampleBean.class); startContainer(beanClasses, beanXmls); { // take an Interceptor class which is not listed in beans.xml and verify that is is not enabled AnnotatedType<SecureAndTransactionalInterceptor> annotatedType = getBeanManager().createAnnotatedType(SecureAndTransactionalInterceptor.class); BeanAttributesImpl<SecureAndTransactionalInterceptor> beanAttributes = BeanAttributesBuilder.forContext(getWebBeansContext()).newBeanAttibutes(annotatedType).build(); CdiInterceptorBeanBuilder<SecureAndTransactionalInterceptor> ibb = new CdiInterceptorBeanBuilder<SecureAndTransactionalInterceptor>(getWebBeansContext(), annotatedType, beanAttributes); Assert.assertFalse(ibb.isInterceptorEnabled()); } { AnnotatedType<TransactionalInterceptor> annotatedType = getBeanManager().createAnnotatedType(TransactionalInterceptor.class); BeanAttributesImpl<TransactionalInterceptor> beanAttributes = BeanAttributesBuilder.forContext(getWebBeansContext()).newBeanAttibutes(annotatedType).build(); CdiInterceptorBeanBuilder<TransactionalInterceptor> ibb = new CdiInterceptorBeanBuilder<TransactionalInterceptor>(getWebBeansContext(), annotatedType, beanAttributes); ibb.defineCdiInterceptorRules(); Interceptor<TransactionalInterceptor> bean = ibb.getBean(); Assert.assertNotNull(bean); Assert.assertNotNull(bean.getInterceptorBindings()); Assert.assertEquals(1, bean.getInterceptorBindings().size()); Assert.assertTrue(bean.intercepts(InterceptionType.AROUND_INVOKE)); Assert.assertFalse(bean.intercepts(InterceptionType.AROUND_TIMEOUT)); Assert.assertFalse(bean.intercepts(InterceptionType.POST_CONSTRUCT)); } shutDownContainer(); } @Test public void testClassLevelParentInterceptor() throws Exception { Collection<String> beanXmls = new ArrayList<String>(); beanXmls.add(getXmlPath(this.getClass().getPackage().getName(), InterceptorResolutionServiceTest.class.getSimpleName())); Collection<Class<?>> beanClasses = new ArrayList<Class<?>>(); beanClasses.add(TestIntercepted1.class); beanClasses.add(TestInterceptor1.class); beanClasses.add(TestInterceptorParent.class); beanClasses.add(UtilitySampleBean.class); startContainer(beanClasses, beanXmls); AnnotatedType<TestInterceptor1> annotatedType = getBeanManager().createAnnotatedType(TestInterceptor1.class); BeanAttributesImpl<TestInterceptor1> beanAttributes = BeanAttributesBuilder.forContext(getWebBeansContext()).newBeanAttibutes(annotatedType).build(); CdiInterceptorBeanBuilder<TestInterceptor1> ibb = new CdiInterceptorBeanBuilder<TestInterceptor1>(getWebBeansContext(), annotatedType, beanAttributes); ibb.defineCdiInterceptorRules(); InterceptorBean<TestInterceptor1> bean = ibb.getBean(); Assert.assertNotNull(bean); Assert.assertTrue(bean.intercepts(InterceptionType.AROUND_INVOKE)); Assert.assertTrue(bean.intercepts(InterceptionType.AROUND_TIMEOUT)); Assert.assertTrue(bean.intercepts(InterceptionType.PRE_DESTROY)); Assert.assertTrue(bean.intercepts(InterceptionType.POST_CONSTRUCT)); Assert.assertFalse(bean.intercepts(InterceptionType.PRE_PASSIVATE)); Assert.assertFalse(bean.intercepts(InterceptionType.POST_ACTIVATE)); Assert.assertEquals(1, bean.getInterceptorBindings().size()); Assert.assertEquals(1, bean.getInterceptorMethods(InterceptionType.AROUND_INVOKE).length); Assert.assertEquals(1, bean.getInterceptorMethods(InterceptionType.AROUND_TIMEOUT).length); Assert.assertEquals(2, bean.getInterceptorMethods(InterceptionType.POST_CONSTRUCT).length); Assert.assertEquals(2, bean.getInterceptorMethods(InterceptionType.PRE_DESTROY).length); CreationalContext<TestInterceptor1> cc = getBeanManager().createCreationalContext(bean); TestInterceptor1 interceptorInstance = bean.create(cc); Assert.assertNotNull(interceptorInstance); shutDownContainer(); } }
import java.util.ArrayList; import java.util.Scanner; public class Traukinys extends TraukinioVeiksmai { private boolean traukinysVaz; private static int vietos = 3; ArrayList<Keleiviai> keleiviuSarasas = new ArrayList<Keleiviai>(); Scanner sc = new Scanner(System.in); public void menu() { System.out.println("1- traukinys vaziuoja\n2- traukinys sustoja\n3- laipinimas\n4- islaipina\n5- keleiviu sarasas."); } public void sarasas() { for (Keleiviai keleivis:keleiviuSarasas) { System.out.println("Keleivis: "+keleivis.getVardas()+" "+keleivis.getPavarde()); } } public void traukinysLaipina() { if (traukinysVaz == true) { traukinysVaziuoja(); menu();} else if ((traukinysVaz == false) & (keleiviuSarasas.size() < vietos)) { System.out.println("Vardas Pavarde"); String vardas1 = sc.next(); String pavarde1 = sc.next(); keleiviuSarasas.add(new Keleiviai(vardas1,pavarde1)); menu(); } else if ((traukinysVaz == false) & (keleiviuSarasas.size() == vietos)) { System.out.println("Traukinys pilnas!"); menu(); } // Keleiviai keleiviai = new Keleiviai(vardas, pavarde); // keleiviuSarasas.add(keleiviai); // uzimtosVietos = keleiviuSarasas.size(); // } public void traukinysIsLaipina() { System.out.println("Keleivivi islipa."); keleiviuSarasas.clear(); menu(); } public void traukinysVaziuoja() { traukinysVaz = true; System.out.println("Traukinys vaziuoja"); } public void traukinysStovi() { traukinysVaz = false; System.out.println("Traukinys stovi"); } public boolean isTraukinysVaz() { return traukinysVaz; } public void setTraukinysVaz(boolean traukinysVaz) { this.traukinysVaz = traukinysVaz; } public int getVietos() { return vietos; } }
package marchal.gabriel.tl; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; import marchal.gabriel.bl.Coleccionista.Coleccionista; import marchal.gabriel.bl.Usuario.Usuario; import java.io.IOException; import java.net.URL; import java.sql.SQLException; import java.time.LocalDate; import java.util.ResourceBundle; public class EditarPerfilController extends MainController implements Initializable { static LocalDate fechaDeNacimiento; /** * Labels predeterminados */ @FXML Label miNombre; @FXML Label miIdentificacion; @FXML Label miFechaNacimiento; @FXML ImageView miAvatar; @FXML Label labelDireccion; @FXML Label miDireccion; @FXML ComboBox avatarInput; /** * Inputs segun seleccion */ @FXML TextField nuevoIdentificacion; @FXML DatePicker nuevoFechaNacimiento; @FXML TextArea nuevoDireccion; @FXML TextField nuevoNombre; @FXML Button botonDireccion; @FXML Button btnMisIntereses; static Usuario usuario; public EditarPerfilController() throws Exception { } @Override public void initialize(URL location, ResourceBundle resources) { avatarInput.getItems().addAll( "avatar1", "avatar2", "avatar3", "avatar4", "avatar5", "avatar6", "avatar7", "avatar8", "avatar9", "avatar10" ); usuario = getUsuarioLogeado(); System.out.println(usuario); try { miAvatar.setImage(new Image(String.valueOf(getClass().getResource(usuario.getAvatar())))); } catch (Exception e) { miAvatar.setImage(new Image ("https://repository-images.githubusercontent.com/15949540/b0a70b80-cb15-11e9-8338-661f601406a1")); System.out.println(e.getMessage()); } miNombre.setText(usuario.getNombre()); miIdentificacion.setText(usuario.getIdentificacion()); fechaDeNacimiento = getUsuarioLogeado().getFechaNacimiento(); miFechaNacimiento.setText(retornarString_LOCALDATE(fechaDeNacimiento)); if(!(usuario instanceof Coleccionista)){ miDireccion.setVisible(false); labelDireccion.setVisible(false); nuevoDireccion.setVisible(false); botonDireccion.setVisible(false); btnMisIntereses.setVisible(false); }else { miDireccion.setText(((Coleccionista)usuario).getDireccion()); } } public void cambiarAvatar(javafx.event.ActionEvent actionEvent) throws Exception { String imagen = "../assets/avatars/"+avatarInput.getSelectionModel().getSelectedItem().toString()+".png"; miAvatar.setImage(new Image (String.valueOf(getClass().getResource(imagen)))); } public void clickCambiarIdentificacion(javafx.event.ActionEvent actionEvent)throws Exception{ miIdentificacion.setText(nuevoIdentificacion.getText()); } public void clickCambiarFechaNaci(javafx.event.ActionEvent actionEvent)throws Exception{ // Validar 18 anios if(validarMayorEdad(nuevoFechaNacimiento.getValue())){ fechaDeNacimiento = nuevoFechaNacimiento.getValue(); miFechaNacimiento.setText(retornarString_LOCALDATE(fechaDeNacimiento)); }else { Alert alert = new Alert(Alert.AlertType.ERROR,"Tiene que ser mayor de edad"); alert.show(); } } public void clickCambiarDireccion(javafx.event.ActionEvent actionEvent)throws Exception{ miDireccion.setText(nuevoDireccion.getText()); } public void clickCambiarNombre(javafx.event.ActionEvent actionEvent)throws Exception{ miNombre.setText(nuevoNombre.getText()); } public void clickGuardarCambios(javafx.event.ActionEvent actionEvent) throws Exception { String avatar = ""; if (avatarInput.getSelectionModel().getSelectedItem() == null) { avatar = getUsuarioLogeado().getAvatar(); } else { avatar = "../assets/avatars/" + avatarInput.getSelectionModel().getSelectedItem().toString() + ".png"; } try { if (usuario instanceof Coleccionista) { usuario.setAvatar(avatar); usuario.setIdentificacion(miIdentificacion.getText()); usuario.setFechaNacimiento(fechaDeNacimiento); ((Coleccionista) usuario).setDireccion(miDireccion.getText()); usuario.setNombre(miNombre.getText()); } else { usuario.setAvatar(avatar); usuario.setIdentificacion(miIdentificacion.getText()); usuario.setFechaNacimiento(fechaDeNacimiento); usuario.setNombre(miNombre.getText()); } if (daoUsuario.editarPerfilUsuario(usuario) == 1) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Informacion cambiado de manera exitosa."); alert.show(); clickVolverPerfil(actionEvent); } else { Alert alert = new Alert(Alert.AlertType.ERROR, "Hubo un error en la actualizacion de datos.\nFavor corregir e volver a intentar."); alert.show(); } } catch (Exception e) { System.out.println(e.getMessage()); } } public void clickMisIntereses(javafx.event.ActionEvent actionEvent) throws Exception { cambiarJavaFXScene(actionEvent,"ConfigurarMisIntereses"); } }
package com.blackvelvet.cybos.bridge.cpdib.events; import com4j.*; /** * _IDibEvents Interface */ @IID("{B8944520-09C3-11D4-8232-00105A7C4F8C}") public abstract class _IDibEvents { // Methods: /** * <p> * method Received * </p> */ @DISPID(1) public void received() { throw new UnsupportedOperationException(); } // Properties: }
package listing; import utilities.ResourceManager; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.util.logging.Level; public class PythonListing extends AbstractListing { private static final String TESTS_FOLDER = "/testList/"; private static final String TESTS_EXTENSION = "txt"; private static final String SCRIPT_NAME = "discover.py"; public PythonListing(String projectPath){ super(projectPath, TESTS_FOLDER, TESTS_EXTENSION); } public void createListingScript(){ String scriptPath = ResourceManager.getResourcePath(SCRIPT_NAME) + File.separator + SCRIPT_NAME; try { FileUtils.copyFileToDirectory(new File(scriptPath), new File(this.getProjectPath())); } catch (IOException e){ LOGGER.log(Level.SEVERE, e.toString(), e); } } public void executeListingScript(){ ProcessBuilder pb = new ProcessBuilder("python3", SCRIPT_NAME); pb.directory(this.getTestsDirectory()); try { pb.start(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.toString(), e); } } }
package com.shafear.notes.mvp.presenter; import android.content.Intent; import com.shafear.notes.global.G; import com.shafear.notes.mvp.model.MNotes; import com.shafear.notes.mvp.view.VAddNote; import com.shafear.notes.xnotes.XNote; /** * Created by shafe_000 on 2015-02-08. */ public class PAddNote { public void choosedAddNote() { showAddNoteScreen(); } public void choosedSubmitNote(XNote xNote){ MNotes mNotes = new MNotes(); mNotes.addNote(xNote); PShowNotes pShowNotes = new PShowNotes(); pShowNotes.showNotesListScreen(); } private void showAddNoteScreen() { Intent intent = new Intent(G.ACTIVITY.getApplicationContext(), VAddNote.class); G.ACTIVITY.startActivity(intent); } }
package com.yicheng.dao.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.stereotype.Repository; import com.yicheng.dao.ClothMaterialDao; import com.yicheng.pojo.ClothMaterial; @Repository public class ClothMaterialDaoImpl extends HibernateDaoBase implements ClothMaterialDao { @Override public int create(ClothMaterial clothMaterial) { return (Integer) getHibernateTemplate().save(clothMaterial); } @Override public void update(ClothMaterial clothMaterial) { getHibernateTemplate().update(clothMaterial); } @Override public void delete(int id) { getHibernateTemplate().delete(new ClothMaterial(id)); } @Override public void deleteByCloth(int clothId) { Session session = super.getSession(true); Query query = null; try { query = session.createQuery("delete ClothMaterial where clothId = " + clothId); query.executeUpdate(); }catch(Exception e) { logger.error(e.getMessage()); e.printStackTrace(); }finally { session.close(); } } @SuppressWarnings("unchecked") @Override public List<ClothMaterial> getByCloth(int clothId) { Session session = super.getSession(true); Query query = null; try { query = session.createQuery("from ClothMaterial where clothId = " + clothId + " order by id asc"); return query.list(); }catch(Exception e) { logger.error(e.getMessage()); e.printStackTrace(); }finally { session.close(); } return null; } }
package com.zpjr.cunguan.entity.module; /** * Description: 描述 * Autour: LF * Date: 2017/8/22 16:47 */ public class MyCardRechangeResponseModule extends ApiResponseModule{ private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } }
package exp_1; import java.util.Stack; import java.util.NoSuchElementException; public class Queue<E> extends Stack<E>{ private static final long serialVersionUID = 1L; static final int dump=1024; private Stack<E> stk; //构造函数 对泛型成员函数实例化 public Queue() { stk = new Stack<>(); } //获取队列大小 @Override public int size() { int size = 0; size = super.size()+stk.size(); return size; } //入队函数 向队尾插入相应元素 失败抛出栈错误 @Override public boolean add(E e) throws IllegalStateException, ClassCastException, NullPointerException, IllegalArgumentException{ if(super.size() >= dump && !stk.empty()) //队满 throw new IllegalStateException(); if(super.size() < dump) //入队栈没有满 super.push(e); else //入队栈满了 出队栈没有元素 { int temp = super.size(); for(int i=temp-1; i>=0; i--) { stk.push(super.get(i)); } super.clear(); super.push(e); } return true; } //入队函数 向队尾插入相应元素 失败返回false public boolean offer(E e) throws ClassCastException, NullPointerException, IllegalArgumentException{ if(super.size() >= dump && !stk.empty()) return false; if(super.size() < dump) super.push(e); else { int temp =super.size(); for(int i=temp-1; i>=0; i--) { stk.push(super.get(i)); } super.clear(); super.push(e); } return true; } //出队函数 将出队栈的栈顶元素出栈 失败抛出栈错误 public E remove() throws NoSuchElementException{ E temp; if(super.empty()) throw new NoSuchElementException(); //入队栈为空 if(!stk.empty()) temp = stk.pop(); //出队栈不为空 else { //出队栈为空 int length = super.size(); for(int i=length-1; i>=0; i--) { stk.push(super.get(i)); } super.clear(); temp = stk.pop(); for(int i=0; i<length-1; i++) { super.push(stk.pop()); } } return temp; } //出队函数 将出队栈的栈顶元素出栈 失败返回false public E poll() { E temp; if(super.empty()) return null; //入队栈为空 if(!stk.empty()) temp=stk.pop(); //出队栈不为空 else { //出队栈为空 int length = super.size(); for(int i=length-1; i>=0; i--) { stk.push(super.get(i)); } super.clear(); temp = stk.pop(); for(int i=0; i<length-1; i++) { super.push(stk.pop()); } } return temp; } //获取队首元素 空队列返回null public E peek() { if(super.empty()) return null; //入队栈为空 E temp; if(!stk.empty()) temp=stk.peek(); //出队栈不为空 else{ int length = super.size(); for(int i=length-1; i>=0; i--) { stk.push(super.get(i)); } super.clear(); temp = stk.peek(); for(int i=0; i<=length-1; i++) super.push(stk.pop()); } return temp; } //获取队首元素 空队列抛出异常 public E element() throws NoSuchElementException{ E temp; if(super.empty()) throw new NoSuchElementException(); //入队栈为空 if(!stk.empty()) temp=stk.peek(); //出队栈不为空 else { //出队栈为空 int length = super.size(); for(int i=length-1; i>=0; i--) { stk.push(super.get(i)); } super.clear(); temp = stk.peek(); for(int i=0; i<=length-1; i++) { super.push(stk.pop()); } } return temp; } @SuppressWarnings("unchecked") //重写拷贝 深拷贝 @Override public Object clone() { Queue<E> dl=new Queue<E>(); dl.addAll((Stack<E>) super.clone()); dl.stk=(Stack<E>) stk.clone(); return dl; } //打印队列中的元素 重写toString @Override public synchronized String toString() { StringBuffer buff = new StringBuffer(); int length_1 = stk.size(); int length_2 = super.size(); for(int i=length_1-1; i>=0; i--) buff.append(stk.get(i)+" "); for(int i=0; i<length_2; i++) buff.append(super.get(i)+ " "); return buff.toString(); } //重写equals @Override public boolean equals(Object ob) throws ClassCastException{ if(ob instanceof Queue) return this.toString().equals(ob.toString()); else throw new ClassCastException(); } }
package com.wooklab.designpattern.strategypattern.duck.type; public interface FlyBehavior { void fly(); }
package manage.studentgui; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Date; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import manage.app.Application; import manage.bean.S_user; import manage.dbutil.ConnectionManager; import manage.gui.LoginFrame; import manage.service.impl.S_userServiceImpl; public class RegisterFrame3 extends JFrame { /** * 标签 */ private JLabel lblUserId; private JLabel lblUsername; private JLabel lblPassword; private JLabel lblTelephone; /** * 文本框 */ private JTextField txtUserId; private JTextField txtUsername; private JTextField txtTelephone; private JPasswordField txtPassword; /** * 按钮 */ private JButton btnSubmit; private JButton btnCancel; private JButton btnLogin; /** * 面板 */ private JPanel panel; private JPanel panel10; private JPanel panel1; private JPanel panel2; private JPanel panel3; private JPanel panel4; private int userid; private String username; private String password; private int telephone; /** * 学生管理应用程序 */ private static Application app; /** * 构造方法 * * @param title */ public RegisterFrame3(String title) { super(title); // 创建学生管理应用程序 app = new Application(); Application.loginFrame=new LoginFrame(); Application.loginFrame.setVisible(false); initGUI(); } /** * 初始化用户界面 */ private void initGUI() { // 创建对象 lblUserId=new JLabel("学 号:"); lblUsername = new JLabel("用户名:"); lblPassword = new JLabel("密 码:"); lblTelephone = new JLabel("电 话:"); txtUserId = new JTextField("", 15); txtUsername = new JTextField("", 15); txtPassword = new JPasswordField("", 15); txtTelephone = new JTextField("", 15); btnSubmit = new JButton("提交[S]"); btnCancel = new JButton("取消[C]"); btnLogin = new JButton("登录[L]"); panel = (JPanel) getContentPane(); panel10 = new JPanel(); panel1 = new JPanel(); panel2 = new JPanel(); panel3 = new JPanel(); panel4 = new JPanel(); // 添加组件 panel.setLayout(new GridLayout(5, 1)); panel.add(panel10); panel.add(panel1); panel.add(panel2); panel.add(panel3); panel.add(panel4); panel10.add(lblUserId); panel10.add(txtUserId); panel1.add(lblUsername); panel1.add(txtUsername); panel2.add(lblPassword); panel2.add(txtPassword); panel3.add(lblTelephone); panel3.add(txtTelephone); panel4.add(btnSubmit); panel4.add(btnCancel); panel4.add(btnLogin); // 设置属性 setSize(350, 300); // 设置窗口大小 setLocationRelativeTo(null);// 让窗口居中 setResizable(false); // 窗口不可调整大小 pack(); // 使窗口恰好容纳组件 setVisible(true); // 让窗口可见 btnSubmit.setMnemonic(KeyEvent.VK_O); // 设置热键字母 btnCancel.setMnemonic(KeyEvent.VK_C);// 设置热键字母 btnLogin.setMnemonic(KeyEvent.VK_R);// 设置热键字母 txtPassword.setEchoChar('*');// 设置回显字符 /* * 注册监听器,编写事件处理代码 采用匿名内部类方式来实现 */ // 提交按钮单击事件 btnSubmit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { register(); } }); // 提交按钮按键事件 btnSubmit.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == 10) { register(); } } }); // 取消按钮单击事件 btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 显示登录窗口 Application.loginFrame.setVisible(true); setVisible(false); // 关闭当前窗口 dispose(); } }); // 登录按钮按键事件 btnLogin.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // 显示登录窗口 Application.loginFrame.setVisible(true); // 关闭当前窗口 dispose(); } }); // 用户名文本框按键事件 txtUserId.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == 10) { txtUsername.requestFocus(); } } }); // 用户名文本框按键事件 txtUsername.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == 10) { txtPassword.requestFocus(); } } }); // 密码文本框按键事件 txtPassword.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == 10) { txtTelephone.requestFocus(); } } }); // 电话文本框按键事件 txtTelephone.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == 10) { register(); } } }); } /** * 注册方法 */ private void register() { // 获取用户名 userid=0; userid=Integer.parseInt(txtUserId.getText().trim()); username = txtUsername.getText().trim(); // 获取密码 password = new String(txtPassword.getPassword()); // 获取电话 telephone = Integer.parseInt(txtTelephone.getText().trim()); // 定义用户服务对象 S_userServiceImpl s_userServiceImpl=new S_userServiceImpl(); S_user user=new S_user(); // 创建用户 user.setUser_id(userid); user.setUser_name(username); user.setPassword(password); user.setUser_tel(telephone); // 添加用户 int count = insert(user); // 判断是否添加成功 if (count > 0) { setVisible(false); dispose(); Application.loginFrame.setVisible(true); JOptionPane.showMessageDialog(null, "恭喜!注册成功!", "学生成绩管理系统", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "您已经注册过!", "学生成绩管理系统", JOptionPane.INFORMATION_MESSAGE); } } public int insert(S_user user) { // 定义插入记录数 int count = 0; // 获得数据库连接 Connection conn = ConnectionManager.getConnection(); // 定义SQL字符串 String strSQL = "INSERT INTO s_user " + " VALUES (?, ?, ?,?)"; try { // 创建预备语句对象 PreparedStatement pstmt = conn.prepareStatement(strSQL); // 设置占位符的值 pstmt.setInt(1,user.getUser_id()); pstmt.setString(2, user.getUser_name()); pstmt.setString(3, user.getPassword()); pstmt.setInt(4,user.getUser_tel()); // 执行更新操作,插入新记录 count = pstmt.executeUpdate(); // 关闭预备语句对象 pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(conn); } // 返回插入记录数 return count; } }
package ru.hse.rpg; public interface LevelUpStrategy { /** * Returns character level computed based on provided experience points * @param experience * @return */ int level(int experience); }
import java.util.Scanner; class Main { public static void main(String[] args) { // put your code here Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); for (int i = n; i <= m; i++){ if(i % 3 == 0){ if (i % 5 == 0) System.out.println("FizzBuzz"); else System.out.println("Fizz"); } else if(i % 5 == 0) System.out.println("Buzz"); else System.out.println(i); } } }
package org.alienideology.jcord.handle; import org.alienideology.jcord.Identity; /** * IDiscordObject - Generic Discord Objects * Such as Guild, User, Channel * * @author AlienIdeology */ public interface IDiscordObject { /** * Get the identity this object belongs to. * * @return The identity. */ Identity getIdentity(); }
package com.frantzoe.phonebook.contacts; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnore; import com.frantzoe.phonebook.users.User; import java.io.Serializable; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javax.persistence.*; import org.hibernate.validator.constraints.NotBlank; @Entity(name = "Contact") @Table(name = "contact") /* uniqueConstraints = { @UniqueConstraint(columnNames = { "first_name", "last_name" }) }) */ public class Contact implements Serializable { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotBlank @Column(name = "first_name") private String firstName; @NotBlank @Column(name = "last_name") private String lastName; @NotBlank @Column(name = "email") private String email; @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "contacts") @JsonIgnore private Set<User> users = new HashSet<User>(); public Contact() { super(); } public Contact(String firstName, String lastName, String email) { this.firstName = firstName; this.lastName = lastName; this.email = email; } public Contact(String firstName, String lastName, String email, Set<User> users) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.users = users; } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public Set<User> getUsers() { return this.users; } public void setUsers(Set<User> users) { this.users = users; } @Override public String toString() { String result = String.format("Contact [id=%d, firstName='%s', lastName='%s']%n", id, firstName, lastName); if (users != null) { for(User user : users) { result += String.format("Publisher[id=%d, firstName='%s', lastName='%s']%n", user.getId(), user.getFirstName(), user.getLastName()); } } return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Contact contact = (Contact) o; return Objects.equals(firstName, contact.firstName) && Objects.equals(lastName, contact.lastName) && Objects.equals(email, contact.email); } @Override public int hashCode() { return Objects.hash(firstName) + Objects.hash(lastName) + Objects.hash(email); } }
package com.espendwise.manta.web.controllers; import com.espendwise.manta.model.view.ProfilePasswordMgrView; import com.espendwise.manta.service.DatabaseUpdateException; import com.espendwise.manta.service.ProfileService; import com.espendwise.manta.spi.SuccessMessage; import com.espendwise.manta.util.Utility; import com.espendwise.manta.util.alert.ArgumentedMessage; import com.espendwise.manta.util.validation.ValidationException; import com.espendwise.manta.web.forms.ProfilePasswordMgrForm; import com.espendwise.manta.web.resolver.DatabaseWebUpdateExceptionResolver; import com.espendwise.manta.web.util.*; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.context.request.WebRequest; import java.util.List; @Controller @RequestMapping(UrlPathKey.PROFILE.PASSWORD_MANAGEMENT) public class ProfilePasswordMgrController extends BaseController { private static final Logger logger = Logger.getLogger(ProfilePasswordMgrController.class); private ProfileService profileService; @Autowired public ProfilePasswordMgrController(ProfileService profileService) { this.profileService = profileService; } public String handleDatabaseUpdateException(DatabaseUpdateException ex, WebRequest request) { WebErrors webErrors = new WebErrors(request); webErrors.putErrors(ex, new DatabaseWebUpdateExceptionResolver()); return "profile/passwordManagement"; } @SuccessMessage @RequestMapping(value = "", method = RequestMethod.POST) public String save(WebRequest request, @ModelAttribute(SessionKey.PROFILE_PASSWORD_MANAGEMENT) ProfilePasswordMgrForm passwordMgrForm, Model model) throws Exception { logger.info("save()=> BEGIN, passwordMgrForm: "+passwordMgrForm); WebErrors webErrors = new WebErrors(request); List<? extends ArgumentedMessage> validationErrors = WebAction.validate(passwordMgrForm); if (!validationErrors.isEmpty()) { webErrors.putErrors(validationErrors); model.addAttribute(SessionKey.PROFILE_PASSWORD_MANAGEMENT, passwordMgrForm); return "profile/passwordManagement"; } passwordMgrForm.setExpiryInDays(Utility.getIntegerStringValue(passwordMgrForm.getExpiryInDays())); passwordMgrForm.setNotifyExpiryInDays(Utility.getIntegerStringValue(passwordMgrForm.getNotifyExpiryInDays())); ProfilePasswordMgrView passwordView = new ProfilePasswordMgrView(this.getStoreId()); passwordView.setAllowChangePassword(passwordMgrForm.isAllowChangePassword()); passwordView.setReqPasswordResetUponInitLogin(passwordMgrForm.isReqPasswordResetUponInitLogin()); passwordView.setReqPasswordResetInDays(passwordMgrForm.isReqPasswordResetInDays()); passwordView.setExpiryInDays(passwordMgrForm.getExpiryInDays()); passwordView.setNotifyExpiryInDays(passwordMgrForm.getNotifyExpiryInDays()); try { passwordView = profileService.savePasswordManagementInfo(passwordView); } catch (DatabaseUpdateException e) { e.printStackTrace(); return handleDatabaseUpdateException(e, request); } logger.info("save()=> END."); return "profile/passwordManagement"; } @RequestMapping(value = "", method = RequestMethod.GET) public String show(@ModelAttribute(SessionKey.PROFILE_PASSWORD_MANAGEMENT) ProfilePasswordMgrForm passwordMgrForm, Model model) { logger.info("show()=> BEGIN"); ProfilePasswordMgrView passwordView = profileService.getPasswordManagementInfo(this.getStoreId()); passwordMgrForm.setAllowChangePassword(passwordView.isAllowChangePassword()); passwordMgrForm.setReqPasswordResetUponInitLogin(passwordView.isReqPasswordResetUponInitLogin()); passwordMgrForm.setReqPasswordResetInDays(passwordView.isReqPasswordResetInDays()); passwordMgrForm.setExpiryInDays(passwordView.getExpiryInDays()); passwordMgrForm.setNotifyExpiryInDays(passwordView.getNotifyExpiryInDays()); model.addAttribute(SessionKey.PROFILE_PASSWORD_MANAGEMENT, passwordMgrForm); logger.info("show()=> END."); return "profile/passwordManagement"; } @ModelAttribute(SessionKey.PROFILE_PASSWORD_MANAGEMENT) public ProfilePasswordMgrForm initModel() { ProfilePasswordMgrForm form = new ProfilePasswordMgrForm(); form.initialize(); return form; } }
package com.e6soft.form.service; import java.io.File; import java.io.InputStream; import java.util.List; import org.springframework.web.multipart.MultipartFile; import com.e6soft.core.service.BaseService; import com.e6soft.form.model.FormFile; public interface FormFileService extends BaseService<FormFile,String> { public String uploadFile(MultipartFile file); /** * 上传资源文件 * @param file * @return */ public String uploadResource(MultipartFile file); public File downloadFile(String id); public void updateFileList(String attachId,String []fileList); public List<FormFile> queryByAttachId(String attachId); public String uploadFile(String fileName,byte[] fileBytes); public String uploadFile(String fileName,InputStream input); }
import java.util.Random; import java.util.Arrays; public class MineSweeper{ // generate field // fill up with mines // write checkNeighbours method // fill up with numbers protected final int[][] DIRECTIONS = new int[][]{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; private char[][] field; private final int MINLENGTH = 1; private final int MAXLENGTH = 20; private final int MINERATE = 2; public MineSweeper(){ field = generateEmptyField(); field = fillWithMines(field); field = fillWithNumbers(field); } public char[][] getField(){ return field; } private char[][] generateEmptyField(){ int row = generateIntBetween(MINLENGTH, MAXLENGTH); char[][] field = new char[row][]; for(int i = 0; i < field.length; i++){ int column = generateIntBetween(MINLENGTH, MAXLENGTH); field[i] = new char[column]; } return field; } private char[][] fillWithMines(char[][] field){ for(int i = 0; i < field.length; i++){ for(int j = 0; j < field[i].length; j++){ if(generateIntBetween(0, 10) < MINERATE){ field[i][j] = '*'; } else { field[i][j] = '.'; } } } return field; } private char[][] fillWithNumbers(char[][] field){ for(int i = 0; i < field.length; i++){ for(int j = 0; j < field[i].length; j++){ if(field[i][j] == '.'){ int num = countNeighboringMines(i, j); field[i][j] = (num == 0) ? '.' : (char) (num + 48); } } } return field; } private int countNeighboringMines(int i, int j){ int count = 0; for (int[] dir : DIRECTIONS){ int di = i + dir[0]; int dj = j + dir[1]; if(di >= 0 && di < field.length && dj >= 0 && dj < field[di].length && field[di][dj] == '*'){ count++; } } return count; } private int generateIntBetween(int from, int to){ Random random = new Random(); int result = random.nextInt(); while(result < from || result >= to){ result = random.nextInt(to); } return result; } public static void main(String[] args){ MineSweeper ms = new MineSweeper(); for(int i = 0; i < ms.getField().length; i++){ System.out.println(Arrays.toString(ms.getField()[i])); } } }
package second; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class Main { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "C://Program Files//Selenium//drivers//chrome83//chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); //keeps going if can't find within 10 sec driver.get("http://kavim-t.co.il/"); WebDriverWait waitVar=new WebDriverWait(driver,10); try { WebElement topmenu=driver.findElement(By.className("top_menu_listitem")); //waitVar.until(ExpectedConditions.elementToBeClickable(topmenu)); //Thread.sleep(5000); topmenu.click(); WebElement search=driver.findElement(By.id("keySearch")); //waitVar.until(ExpectedConditions.elementToBeClickable(search)); //Thread.sleep(5000); search.click(); search.clear(); search.sendKeys("3"); WebElement clicker=driver.findElement(By.id("lnkSearch")); //waitVar.until(ExpectedConditions.elementToBeClickable(clicker)); clicker.click(); WebElement title=driver.findElement(By.cssSelector("[class='title_topline search_general_topborder']")); String t=title.getText(); if(t.contains("3")==true) {System.out.println("valid");} else {System.out.println("not valid");} }catch (Exception ex) {ex.printStackTrace();} finally { Thread.sleep(5000); driver.close(); System.out.println("### Test End ###"); } } }
import java.util.*; import java.io.*; import timing.*; public class Uno_02 extends Thread{ static int result = 0; static int tmp=0; static boolean calc_3= true; static boolean calc_5= true; public void run(){ //private static File res= new File("result_02.txt"); //private static BufferedWriter out; /* 01 : mine :266333:wrong: it sums the multiple of both, 2 times than !!*/ /* 01_1: now i changed for taking care of this....*/ int i=1; while(calc_3 || calc_5){ if(calc_5){ if ((tmp=5*i)<1000) { if ( tmp % 3 != 0 ) result += tmp; } else {calc_5 = false;}; } if(calc_3){ if ((tmp=3*i)<1000) { result += tmp; } else {calc_3 = false;}; } i++; }//while /* 02 : method from internet, better for (int i = 0; i < 1000; ++i) { if (i % 3 == 0 || i % 5 == 0) //out.write(String.valueOf(i)); //out.write("\n"); result += i; } */ //output System.out.println("Totale : " + result); } public static void main(String args[]){ Chronometer chron = new Chronometer(); Uno_02 problem = new Uno_02(); chron.run(problem); System.out.println(chron.getElapsedTime()); } }
/******************************************************************************* * Copyright (C) 2011 Peter Brewer. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * Peter Brewer ******************************************************************************/ package org.tellervo.desktop.io.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextPane; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.border.EmptyBorder; import javax.swing.table.TableColumn; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import jsyntaxpane.DefaultSyntaxKit; import org.netbeans.swing.outline.DefaultOutlineModel; import org.netbeans.swing.outline.Outline; import org.netbeans.swing.outline.OutlineModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tellervo.desktop.core.App; import org.tellervo.desktop.gui.widgets.TridasEntityPickerDialog; import org.tellervo.desktop.gui.widgets.TridasEntityPickerPanel; import org.tellervo.desktop.gui.widgets.TridasTreeViewPanel; import org.tellervo.desktop.gui.widgets.TridasEntityPickerPanel.EntitiesAccepted; import org.tellervo.desktop.io.ConversionWarningTableModel; import org.tellervo.desktop.io.LineHighlighter; import org.tellervo.desktop.io.control.ExpandImportTreeEvent; import org.tellervo.desktop.io.control.FileSelectedEvent; import org.tellervo.desktop.io.control.ImportEntitySaveEvent; import org.tellervo.desktop.io.control.ImportMergeEntitiesEvent; import org.tellervo.desktop.io.control.ImportNodeSelectedEvent; import org.tellervo.desktop.io.control.ImportSwapEntityEvent; import org.tellervo.desktop.io.control.ReplaceHierarchyEvent; import org.tellervo.desktop.io.model.ImportEntityListComboBox; import org.tellervo.desktop.io.model.ImportModel; import org.tellervo.desktop.io.model.TridasRepresentationTableTreeRow; import org.tellervo.desktop.io.model.TridasRepresentationTreeModel; import org.tellervo.desktop.io.model.TridasRepresentationTableTreeRow.ImportStatus; import org.tellervo.desktop.model.TellervoModelLocator; import org.tellervo.desktop.tridasv2.ui.TellervoPropertySheetPanel; import org.tellervo.desktop.tridasv2.ui.TellervoPropertySheetTable; import org.tellervo.desktop.tridasv2.ui.TridasPropertyEditorFactory; import org.tellervo.desktop.tridasv2.ui.TridasPropertyRendererFactory; import org.tellervo.desktop.tridasv2.ui.support.TridasEntityDeriver; import org.tellervo.desktop.tridasv2.ui.support.TridasEntityProperty; import org.tellervo.desktop.ui.Alert; import org.tellervo.desktop.ui.Builder; import org.tellervo.desktop.ui.FilterableComboBoxModel; import org.tellervo.desktop.ui.I18n; import org.tellervo.desktop.util.PopupListener; import org.tridas.interfaces.ITridas; import org.tridas.interfaces.ITridasSeries; import org.tridas.io.enums.Charsets; import org.tridas.io.exceptions.ConversionWarning; import org.tridas.io.exceptions.InvalidDendroFileException; import org.tridas.io.exceptions.InvalidDendroFileException.PointerType; import org.tridas.schema.NormalTridasVariable; import org.tridas.schema.TridasMeasurementSeries; import org.tridas.schema.TridasObject; import org.tridas.schema.TridasProject; import org.tridas.schema.TridasRadius; import org.tridas.schema.TridasSample; import org.tridas.schema.TridasValue; import org.tridas.schema.TridasValues; import org.tridas.schema.TridasVariable; import org.tridas.util.TridasObjectEx; import com.dmurph.mvc.MVC; import com.l2fprod.common.propertysheet.Property; import com.l2fprod.common.propertysheet.PropertySheet; import com.l2fprod.common.propertysheet.PropertySheetPanel; import com.lowagie.text.Font; import net.miginfocom.swing.MigLayout; import javax.swing.JComboBox; public class ImportView extends JFrame{ private final static Logger log = LoggerFactory.getLogger(ImportView.class); private static final long serialVersionUID = -9142222993569420620L; /** The MVC Import Model **/ private ImportModel model; /** Main panel into which everything is placed **/ private final JPanel contentPanel = new JPanel(); /** Panel and tree-table (outline) for displaying tridas representation of file **/ private JPanel panelTreeTable; private Outline treeTable; /** Panel and text area for displaying original legacy file **/ private JPanel panelOrigFile; /** Panel for displaying ring with data**/ private JPanel panelData; /** Panel and table for displaying conversion warnings **/ private JPanel panelWarnings; private JTable tblWarnings; /** Tabbed pane for original file, metadata and data tabs**/ private JTabbedPane tabbedPane; /** Left/Right split pane**/ private JSplitPane horizSplitPane; /** Top/Bottom split pane **/ private JSplitPane vertSplitPane; /** Our property sheet panel (contains table and description) */ private TellervoPropertySheetPanel propertiesPanel; /** Our properties table */ private TellervoPropertySheetTable propertiesTable; /** Panel containing the edit/save changes/cancel buttons for the current entity */ private JPanel bottombar; /** Panel containing combo box and buttons for selecting entities from db*/ private JPanel topbar; /** The lock/unlock button for making changes to the currently selected entity */ private JToggleButton editEntity; /** The save button when unlocked */ private JButton editEntitySave; /** The cancel button when unlocked */ private JButton editEntityCancel; /** Text associated with lock/unlock button */ private JLabel editEntityText; /** Labels **/ private JLabel lblConversionWarnings; private JLabel lblTridasRepresentationOf; private JLabel lblTopBarSummaryTitle; /** Finish button **/ private JButton btnFinish; /** Set from db button **/ private JButton btnMergeObjects; private JButton btnExpandNodes; private JButton btnContractNodes; private JButton btnAssignByCode; private JButton btnReparseFile; private JTextPane txtErrorMessage; private ImportEntityListComboBox topChooser; private JButton changeButton; private JButton cancelChangeButton; private static final String CHANGE_STATE = I18n.getText("general.change"); private static final String CHOOSE_STATE = I18n.getText("general.choose"); private boolean changingTop; private ChoiceComboBoxActionListener topChooserListener; private JEditorPane dataPane; private JScrollPane scrollPane_1; private JComboBox cboEncoding; private JLabel lblCharacterEncoding; /** * Standard constructor for Import Dialog with no file provided */ public ImportView() { topChooserListener = new ChoiceComboBoxActionListener(this); model = TellervoModelLocator.getInstance().getImportModel(); MVC.showEventMonitor(); initComponents(); linkModel(); initListeners(); initLocale(); } /** * Constructor with file already specified * @param file */ public ImportView(File file, String fileType) { if(usingOldImporter(file, fileType)) return; topChooserListener = new ChoiceComboBoxActionListener(this); model = TellervoModelLocator.getInstance().getImportModel(); //MVC.showEventMonitor(); initComponents(); linkModel(); initListeners(); initLocale(); FileSelectedEvent event = new FileSelectedEvent(model, file, fileType); event.dispatch(); } /** * * @param file * @param fileType * @return */ private Boolean usingOldImporter(File file, String fileType) { return false; } /** * Initialise the GUI components */ private void initComponents() { DefaultSyntaxKit.initKit(); setTitle("Import to Database"); setBounds(100, 100, 804, 734); getContentPane().setLayout(new BorderLayout(0, 0)); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel); { } contentPanel.setLayout(new BorderLayout(0, 0)); { vertSplitPane = new JSplitPane(); vertSplitPane.setOneTouchExpandable(true); vertSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); contentPanel.add(vertSplitPane); { panelWarnings = new JPanel(); panelWarnings.setBorder(new EmptyBorder(5, 5, 5, 5)); vertSplitPane.setRightComponent(panelWarnings); panelWarnings.setLayout(new BorderLayout(0, 8)); { lblConversionWarnings = new JLabel("Conversion warnings:"); panelWarnings.add(lblConversionWarnings, BorderLayout.NORTH); } { JScrollPane scrollPane = new JScrollPane(); lblConversionWarnings.setLabelFor(scrollPane); panelWarnings.add(scrollPane); { tblWarnings = new JTable(); scrollPane.setViewportView(tblWarnings); } } } horizSplitPane = new JSplitPane(); vertSplitPane.setLeftComponent(horizSplitPane); horizSplitPane.setOneTouchExpandable(true); horizSplitPane.setBorder(null); horizSplitPane.setDividerLocation(0.5); tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.setBorder(null); horizSplitPane.setRightComponent(tabbedPane); { JPanel panelMetadata = new JPanel(); panelMetadata.setLayout(new BorderLayout()); topbar = new JPanel(); bottombar = new JPanel(); topbar.setLayout(new BoxLayout(topbar, BoxLayout.X_AXIS)); bottombar.setLayout(new BoxLayout(bottombar, BoxLayout.X_AXIS)); ////////// TOP BAR lblTopBarSummaryTitle = new JLabel(""); topChooser = new ImportEntityListComboBox(); changeButton = new JButton(CHANGE_STATE); cancelChangeButton = new JButton(I18n.getText("general.revert")); topbar.add(lblTopBarSummaryTitle); topbar.add(Box.createHorizontalStrut(6)); topbar.add(topChooser); topbar.add(Box.createHorizontalStrut(6)); topbar.add(changeButton); topbar.add(Box.createHorizontalStrut(6)); topbar.add(cancelChangeButton); topbar.add(Box.createHorizontalGlue()); topbar.setBorder(BorderFactory.createEmptyBorder(2, 8, 2, 8)); changingTop = false; cancelChangeButton.setVisible(false); panelMetadata.add(topbar, BorderLayout.NORTH); ////////// BOTTOM BAR editEntity = new JToggleButton(); editEntity.setIcon(scaleIcon20x20((ImageIcon) Builder.getIcon("lock.png", Builder.ICONS, 32))); editEntity.setSelectedIcon(scaleIcon20x20((ImageIcon) Builder.getIcon("unlock.png", Builder.ICONS, 32))); editEntity.setBorderPainted(false); editEntity.setContentAreaFilled(false); editEntity.setFocusable(false); bottombar.add(editEntity); editEntityText = new JLabel(I18n.getText("general.initializing").toLowerCase()); editEntityText.setLabelFor(editEntity); editEntitySave = new JButton(I18n.getText("general.saveChanges")); editEntityCancel = new JButton(I18n.getText("general.cancel")); // don't let an errant enter key fire these buttons! editEntitySave.setDefaultCapable(false); editEntityCancel.setDefaultCapable(false); bottombar.add(editEntityText); bottombar.add(Box.createHorizontalGlue()); bottombar.add(editEntitySave); bottombar.add(Box.createHorizontalStrut(6)); bottombar.add(editEntityCancel); bottombar.add(Box.createHorizontalStrut(6)); panelMetadata.add(bottombar, BorderLayout.SOUTH); // Create metadata table and panel to hold it propertiesTable = new TellervoPropertySheetTable(); propertiesPanel = new TellervoPropertySheetPanel(propertiesTable); //propertiesPanel.getTable().setEnabled(false); // Set various properties of the properties panel! propertiesPanel.setRestoreToggleStates(true); propertiesPanel.setToolBarVisible(false); propertiesPanel.setDescriptionVisible(true); propertiesPanel.setMode(PropertySheet.VIEW_AS_CATEGORIES); propertiesPanel.getTable().setRowHeight(24); propertiesPanel.getTable().setRendererFactory(new TridasPropertyRendererFactory()); propertiesPanel.getTable().setEditorFactory(new TridasPropertyEditorFactory()); panelMetadata.add(propertiesPanel, BorderLayout.CENTER); tabbedPane.addTab("Extracted TRiDaS Metadata", null, panelMetadata, null); } { panelData = new JPanel(); tabbedPane.addTab("Extracted Data", null, panelData, null); panelData.setLayout(new BorderLayout(0, 0)); scrollPane_1 = new JScrollPane(); panelData.add(scrollPane_1); dataPane = new JEditorPane(); dataPane.setEditable(false); scrollPane_1.setViewportView(dataPane); tabbedPane.setEnabledAt(1, false); } panelOrigFile = new JPanel(); tabbedPane.insertTab("Original file", null, panelOrigFile, null, 0); panelOrigFile.setLayout(new MigLayout("", "[159.00px][173.00][grow]", "[fill][][707px,grow,fill]")); cboEncoding = new JComboBox(); lblCharacterEncoding = new JLabel("Character encoding:"); panelOrigFile.add(lblCharacterEncoding, "flowx,cell 0 1,alignx left"); for (String s : Charsets.getReadingCharsets()) { if (s.equals(Charset.defaultCharset().displayName())) { continue; } cboEncoding.addItem(s); } panelOrigFile.add(cboEncoding, "cell 1 1 2 1,alignx left"); { } txtErrorMessage = new JTextPane(); txtErrorMessage.setForeground(Color.RED); txtErrorMessage.setVisible(false); panelOrigFile.add(txtErrorMessage, "cell 0 0 3 1,growx,aligny top"); { panelTreeTable = new JPanel(); panelTreeTable.setBorder(new EmptyBorder(5, 5, 5, 5)); horizSplitPane.setLeftComponent(panelTreeTable); panelTreeTable.setLayout(new BorderLayout(0, 0)); { //btnMergeObjects = new JButton("Merge objects together"); //panelTreeTable.add(btnMergeObjects, BorderLayout.SOUTH); } { lblTridasRepresentationOf = new JLabel("TRiDaS representation of file:"); panelTreeTable.add(lblTridasRepresentationOf, BorderLayout.NORTH); treeTable = new Outline(); // Set the renderdata treeTable.setRenderDataProvider(new TridasOutlineRenderData()); // Add tree to scroll pane JScrollPane treeTableScrollPane = new JScrollPane(); treeTableScrollPane.setViewportView(treeTable); panelTreeTable.add(treeTableScrollPane, BorderLayout.CENTER); } } } { JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPanel, BorderLayout.SOUTH); { btnFinish = new JButton("Finish"); buttonPanel.add(btnFinish); } } pack(); //this.setSize(new Dimension(800,600)); vertSplitPane.setDividerLocation(0.8); horizSplitPane.setDividerLocation(0.5); setExtendedState(getExtendedState() | Frame.MAXIMIZED_BOTH); setIconImage(Builder.getApplicationIcon()); chooseOrCancelUIUpdate(); enableEditing(false); updateConversionWarningsTable(); initToolbar(); } /** * Set up the toolbar */ private void initToolbar() { JToolBar toolBar = new JToolBar("Toolbar"); btnMergeObjects = new JButton("Merge all objects"); btnMergeObjects.setToolTipText("Merge all objects"); btnMergeObjects.setIcon(Builder.getIcon("merge.png", 22)); toolBar.add(btnMergeObjects); btnExpandNodes = new JButton("Expand nodes"); btnExpandNodes.setToolTipText("Expand nodes"); btnExpandNodes.setIcon(Builder.getIcon("view_tree.png", 22)); toolBar.add(btnExpandNodes); btnContractNodes = new JButton("Contract nodes"); btnContractNodes.setToolTipText("Contract nodes"); btnContractNodes.setIcon(Builder.getIcon("contract_tree.png", 22)); toolBar.add(btnContractNodes); btnAssignByCode = new JButton("Assign by code"); btnAssignByCode.setToolTipText("Assign by code"); btnAssignByCode.setIcon(Builder.getIcon("barcode.png", 22)); toolBar.add(btnAssignByCode); btnReparseFile = new JButton("Reparse file"); btnReparseFile.setToolTipText("Reparse file"); btnReparseFile.setIcon(Builder.getIcon("reload.png", 22)); toolBar.add(btnReparseFile); getContentPane().add(toolBar, BorderLayout.PAGE_START); } /** * Link to MVC Model so that we can update the GUI when events are detected */ private void linkModel() { model.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); if(name.equals(ImportModel.ORIGINAL_FILE)) { updateOriginalFile(null); } else if (name.equals(ImportModel.CONVERSION_WARNINGS)) { // New conversion warnings so set the table updateConversionWarningsTable(); } else if (name.equals(ImportModel.SELECTED_ROW)) { // An entity in the tree-table has been selected so // update the metadata panel // Check that the tree table is expanded to show the selected node int selRow = treeTable.getSelectedRow(); DefaultMutableTreeNode guiSelectedEntity = (DefaultMutableTreeNode) treeTable.getValueAt(selRow, 0); DefaultMutableTreeNode modelSelectedEntity = model.getSelectedRow().getDefaultMutableTreeNode(); if((guiSelectedEntity==null) || (!guiSelectedEntity.equals(modelSelectedEntity))) { TreePath path = getPath(modelSelectedEntity); treeTable.getOutlineModel().getTreePathSupport().expandPath(path); } // Set up entity model listeners linkRowModel(); // Update the metadata panel updateMetadataPanel(); updateEntityChooser(); // Enable/disable assign by code button depending on selected entity type if((modelSelectedEntity.getUserObject() instanceof TridasMeasurementSeries) || (modelSelectedEntity.getUserObject() instanceof TridasSample)) { btnAssignByCode.setEnabled(true); } else { btnAssignByCode.setEnabled(false); } } else if (name.equals(ImportModel.TREE_MODEL)) { // Tree model has changed so update the tree-table updateTreeTable(); } else if (name.equals(ImportModel.INVALID_FILE_EXCEPTION)) { setGUIForInvalidFile(); } } }); } private void linkRowModel() { model.getSelectedRow().addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { String name = evt.getPropertyName(); if(name.equals(TridasRepresentationTableTreeRow.CURRENT_ENTITY)) { propertiesPanel.readFromObject(model.getSelectedRow().getCurrentEntity()); } } }); } /** * Set up the MVC listeners for dispatching events from this GUI */ private void initListeners() { final Component glue = (Component) this; final JFrame glue2 = this; // Listen to entities being selected in tree table this.treeTable.addMouseListener(new PopupListener() { @Override public void mouseClicked(MouseEvent e) { selectCurrentEntity(); } @Override public void showPopup(MouseEvent e) { log.debug("showPopup called"); int selRow = treeTable.getSelectedRow(); DefaultMutableTreeNode selectedEntity = (DefaultMutableTreeNode) treeTable.getValueAt(selRow, 0); showPopupMenu((JComponent) e.getSource(), e.getX(), e.getY(), selectedEntity); } }); // Listen for set from db button press this.btnFinish.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Integer outstanding = model.getCountOutstandingEntities(); String plural="y that has"; if(outstanding>1)plural = "ies that have"; if(outstanding>0) { Object[] options = {"Yes", "No", "Cancel"}; int n = JOptionPane.showOptionDialog(glue, "You still have "+outstanding+" entit"+plural+" not been imported.\n" + "Are you sure you want to close the import dialog?", "Outstanding entities", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if(n==JOptionPane.YES_OPTION) dispose(); } else { dispose(); } } }); this.changeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(changeButton.getText().equals(CHANGE_STATE)) { changingTop = true; } else if (changeButton.getText().equals(CHOOSE_STATE)) { changingTop = false; propertiesTable.setHasWatermark(false); TridasRepresentationTableTreeRow oldrow = model.getSelectedRow(); DefaultMutableTreeNode node = new DefaultMutableTreeNode((ITridas) topChooser.getSelectedItem()); TridasRepresentationTableTreeRow newrow = new TridasRepresentationTableTreeRow(node, ImportStatus.STORED_IN_DATABASE); ImportSwapEntityEvent event = new ImportSwapEntityEvent(model, newrow, oldrow); event.dispatch(); } chooseOrCancelUIUpdate(); } }); this.cancelChangeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changingTop = false; chooseOrCancelUIUpdate(); } }); editEntity.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(editEntity.isSelected()) { log.debug("Starting to edit entity"); } else { log.debug("Stopping entity edit"); } enableEditing(editEntity.isSelected()); } }); editEntitySave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // TODO Need to replace 'null' below with this dialog saveChanges(); } }); editEntityCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(isUserOkWithLoosingAnyChanges()) { model.getSelectedRow().revertChanges(); editEntity.setSelected(false); enableEditing(false); selectCurrentEntity(); } } }); btnMergeObjects.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ImportMergeEntitiesEvent event = new ImportMergeEntitiesEvent(model, TridasObject.class); event.dispatch(); } }); btnExpandNodes.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ExpandImportTreeEvent e2 = new ExpandImportTreeEvent(true, model.getTreeModel(), treeTable); e2.dispatch(); } }); btnContractNodes.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ExpandImportTreeEvent e2 = new ExpandImportTreeEvent(false, model.getTreeModel(), treeTable); e2.dispatch(); } }); btnAssignByCode.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode modelSelectedEntity = model.getSelectedRow().getDefaultMutableTreeNode(); updateHierarchyByCodeDialog(modelSelectedEntity, glue2); } }); btnReparseFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //default icon, custom title int n = JOptionPane.showConfirmDialog( glue2, "Any changes you've not committed to the database will be lost.\n"+ "Are you sure you want to continue?", "Confirm", JOptionPane.YES_NO_OPTION); if(n==JOptionPane.YES_OPTION) { File file = null; String fileType = null; try{ file = model.getFileToImport(); fileType = model.getFileType(); } catch (Exception e2) { Alert.error("Error", "Unable to reparse file: "+e2.getLocalizedMessage()); } FileSelectedEvent event = new FileSelectedEvent(model, file, fileType); event.dispatch(); } } }); } private void selectCurrentEntity() { // Check the user isn't part way through changing this entity if(!isUserOkWithLoosingAnyChanges()) return; if(changingTop) { changingTop =false; chooseOrCancelUIUpdate(); } int selRow = treeTable.getSelectedRow(); DefaultMutableTreeNode selectedEntity = (DefaultMutableTreeNode) treeTable.getValueAt(selRow, 0); ImportStatus status = (ImportStatus) treeTable.getValueAt(selRow, 1); TridasRepresentationTableTreeRow row = new TridasRepresentationTableTreeRow(selectedEntity, status); ImportNodeSelectedEvent event = new ImportNodeSelectedEvent(model, row); event.dispatch(); model.setSelectedRow(row); } private void saveChanges() { ITridas entity = model.getSelectedRow().getCurrentEntity(); propertiesPanel.writeToObject(entity); log.debug("About to save entity " + entity.getTitle()); if(entity instanceof TridasMeasurementSeries) { TridasMeasurementSeries en = (TridasMeasurementSeries) entity; if(en.isSetValues()) { if(en.getValues().get(0).isSetVariable()) { TridasVariable variable = new TridasVariable(); variable.setNormalTridas(NormalTridasVariable.RING_WIDTH); en.getValues().get(0).setVariable(variable); } } model.getSelectedRow().setCurrentEntity(en); } ImportEntitySaveEvent event = new ImportEntitySaveEvent(model, null); event.dispatch(); } /** * Localise the GUI components */ private void initLocale() { } protected void showPopupMenu(JComponent source, int x, int y, final DefaultMutableTreeNode selectedEntity) { // define the popup JPopupMenu popupMenu = new JPopupMenu(); final JFrame glue = this; if(selectedEntity.getUserObject() instanceof TridasMeasurementSeries) { JMenuItem setHierarchyMenu = new JMenuItem("Set hierarchy by labcode"); setHierarchyMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { updateHierarchyByCodeDialog(selectedEntity, glue); } }); popupMenu.add(setHierarchyMenu); popupMenu.setOpaque(true); popupMenu.setLightWeightPopupEnabled(false); popupMenu.show(source, x, y); } } private void updateHierarchyByCodeDialog(DefaultMutableTreeNode selectedEntity, JFrame glue) { ITridas newParent = null; if((selectedEntity.getUserObject() instanceof TridasMeasurementSeries)) { newParent = TridasEntityPickerDialog.pickEntity(glue, "Select entity", ITridasSeries.class, EntitiesAccepted.SPECIFIED_ENTITY_UP_TO_PROJECT); log.debug("User wants to set hierarchy of "+ ((ITridas) selectedEntity.getUserObject()).getTitle() + " using labcode for " + newParent.getTitle()); } else if((selectedEntity.getUserObject() instanceof TridasSample)) { newParent = TridasEntityPickerDialog.pickSpecificEntity(this, "Select entity", TridasSample.class); log.debug("User wants to set hierarchy of "+ ((ITridas) selectedEntity.getUserObject()).getTitle() + " using labcode for " + newParent.getTitle()); } if(newParent==null) return; ReplaceHierarchyEvent event = new ReplaceHierarchyEvent(model, glue, selectedEntity ,newParent ); event.dispatch(); ExpandImportTreeEvent e2 = new ExpandImportTreeEvent(true, model.getTreeModel(), treeTable); e2.dispatch(); return; } /** * Set up the conversion warnings table with the provided warnings * @param warnings */ private void updateConversionWarningsTable() { ConversionWarning[] warnings = model.getConversionWarnings(); if(warnings==null) { vertSplitPane.setDividerLocation(1.0); return; } if(warnings.length==0) { vertSplitPane.setDividerLocation(1.0); return; } ConversionWarningTableModel cwModel = new ConversionWarningTableModel(warnings); tblWarnings.setModel(cwModel); lblConversionWarnings.setText("Conversion warnings ("+warnings.length+"):"); TableColumn col = tblWarnings.getColumnModel().getColumn(0); int width = 70; col.setMinWidth(width); col.setPreferredWidth(width); col = tblWarnings.getColumnModel().getColumn(1); col.setMinWidth(width); col.setPreferredWidth(width); col = tblWarnings.getColumnModel().getColumn(2); col.setMinWidth(width); col.setPreferredWidth(5000); vertSplitPane.setDividerLocation(0.8); } /** * Update the data panel to show the ring width values * * @param row */ private void updateDataPanel() { ITridas entity = (ITridas) model.getSelectedRow().getDefaultMutableTreeNode().getUserObject(); if(!(entity instanceof TridasMeasurementSeries)) { // Not a series if(tabbedPane.getSelectedIndex()==2) { // Select the metadata tab if currently on the data tab tabbedPane.setSelectedIndex(1); } // Disable the data tab tabbedPane.setEnabledAt(2, false); return; } TridasMeasurementSeries series = (TridasMeasurementSeries) entity; log.debug("Values group count = "+series.getValues().size()); log.debug("Value count = "+series.getValues().get(0).getValues().size()); TridasVariable var = new TridasVariable(); var.setNormalTridas(NormalTridasVariable.RING_WIDTH); TridasValues seriesGroup = series.getValues().get(0); seriesGroup.setVariable(var); List<TridasValue> values = seriesGroup.getValues(); ArrayList<Number> valuesint = new ArrayList<Number>(); ArrayList<Integer> countint = new ArrayList<Integer>(); StringBuilder datavals = new StringBuilder(); if(seriesGroup.isSetUnit()) { if(seriesGroup.getUnit().isSetNormalTridas()) { datavals.append("Units="+seriesGroup.getUnit().getNormalTridas().toString()+"\n\n"); } } for(TridasValue v : values) { valuesint.add(Integer.valueOf(v.getValue())); countint.add(v.getCount()); datavals.append(v.getValue()+"\n"); } dataPane.setText(datavals.toString()); //panelData.setLayout(new BorderLayout()); //panelData.add(dataPane, BorderLayout.CENTER); tabbedPane.setEnabledAt(2, true); } /** * Set the metadata panel to show the provided entity * @param parentNode * @param entity */ private void updateMetadataPanel() { if(!isUserOkWithLoosingAnyChanges()) { return; } // Enable or disable the data page depending on current entity type updateDataPanel(); // Set the text in the top bar //setTopBarSummaryTitle(parentNode); // Extract the entity and entity type from the select table tree row ITridas currentEntity = model.getSelectedRow().getCurrentEntity(); Class<? extends ITridas> currentEntityType = model.getSelectedRow().getCurrentEntityClass(); // Extract the parent entity try{ ITridas parentEntity = model.getSelectedRow().getParentEntity(); log.debug("Set parent entity successfully to: " + parentEntity.getTitle()); } catch (Exception e){ log.warn("Unable to set parent entity"); } // Swapping entities so disable editing //enableEditing(false); // Derive a property list List<TridasEntityProperty> properties = TridasEntityDeriver.buildDerivationList(currentEntityType); Property[] propArray = properties.toArray(new Property[properties.size()]); // Set properties for current entity type propertiesPanel.setProperties(propArray); propertiesTable.expandAllBranches(true); // Add data to table from entity if(currentEntity!=null) { propertiesPanel.readFromObject(currentEntity); propertiesPanel.setEnabled(true); editEntity.setVisible(true); } else { propertiesPanel.setEnabled(false); editEntity.setVisible(false); } // Set the watermark text across metadata panel if(model.getSelectedRow().getImportStatus().equals(ImportStatus.PENDING)) { propertiesTable.setHasWatermark(true); propertiesTable.setWatermarkText(I18n.getText("general.preview").toUpperCase()); } else if(model.getSelectedRow().getImportStatus().equals(ImportStatus.IGNORE)) { propertiesTable.setHasWatermark(true); propertiesTable.setWatermarkText("IGNORED"); } else { propertiesTable.setHasWatermark(false); } // Update the combo box list //ImportEntityListChangedEvent ev = new ImportEntityListChangedEvent(model.getCurrentEntityModel(), currentEntity, parentEntity); //ev.dispatch(); // Set the top chooser to the correct current value selectInTopChooser(); } /** * Called by either button press to update the UI state */ private void chooseOrCancelUIUpdate() { // disable/enable editing editEntity.setEnabled(!changingTop); topChooser.setEnabled(changingTop); changeButton.setText(changingTop ? CHOOSE_STATE : CHANGE_STATE); cancelChangeButton.setVisible(changingTop); //propertiesTable.setEditable(changingTop); } /** * Update the entity chooser combo box based on the current entity * and its parent * * @param thisEntity * @param parentEntity */ private void updateEntityChooser() { List<? extends ITridas> entities = model.getSelectedRow().getEntityList(); topChooser.setList(entities); ITridas currentEntity = model.getSelectedRow().getCurrentEntity(); ITridas parentEntity = model.getSelectedRow().getParentEntity(); if (currentEntity instanceof TridasProject) { // This entity is a project so set list to null as // projects aren't supported setTopChooserEnabled(false, "Projects are not supported in Tellervo"); return; } else if(currentEntity instanceof TridasObject) { // This entity is an object so grab object dictionary setTopChooserEnabled(true, null); return; } // Otherwise, check that the parent is already in db by checking // the identifier domain and set list accordingly try{ if (parentEntity.getIdentifier().getDomain().equals(App.domain)) { if(currentEntity instanceof TridasMeasurementSeries) { setTopChooserEnabled(false, null); return; } else { setTopChooserEnabled(true, null); return; } } else { setTopChooserEnabled(false, "Fix parent entity first"); } } catch (Exception e) { setTopChooserEnabled(false, "Fix parent entity first"); return; } this.topbar.repaint(); } /** * Set whether the top chooser combo box panel is enabled or not * * @param b * @param message */ private void setTopChooserEnabled(Boolean b, String message) { topChooser.setVisible(b); changeButton.setVisible(b); lblTopBarSummaryTitle.setText(message); } /** * Set the tree-table panel to show the data specified in the * provided treeModel. * @param treeModel */ private void updateTreeTable() { TridasRepresentationTreeModel treeModel = model.getTreeModel(); OutlineModel mdl = DefaultOutlineModel.createOutlineModel( treeModel, treeModel, true, "TRiDaS Entities"); this.treeTable.setModel(mdl); ExpandImportTreeEvent e2 = new ExpandImportTreeEvent(true, model.getTreeModel(), treeTable); e2.dispatch(); } /** * Update the GUI to show the original legacy file. If the highlightline * integer is included then this line will be highlighted for the user. * Typically used to show an error. * * @param highlightline */ private void updateOriginalFile(Integer highlightline) { final JEditorPane txtOriginalFile = new JEditorPane(); JScrollPane scrollPane = new JScrollPane(txtOriginalFile); try{ panelOrigFile.remove(3);} catch (Exception e){} panelOrigFile.add(scrollPane, "cell 0 2 3 1,grow"); txtOriginalFile.setEditable(false); txtOriginalFile.setFont(new java.awt.Font("Courier", 0, 12)); txtOriginalFile.setContentType("text/xml"); // Original file has changed so update GUI to show its contents String contents = model.getFileToImportContents(); if(contents!=null) { txtOriginalFile.setText(contents); } if(highlightline!=null) { try{ txtOriginalFile.addCaretListener(new LineHighlighter(Color.red, highlightline )); this.tabbedPane.setSelectedIndex(0); int pos=1; for(int i=0; i<highlightline; i++) { pos = txtOriginalFile.getText().indexOf("\n", pos+1); } txtOriginalFile.setCaretPosition(pos); } catch (NumberFormatException ex) {} } } /** * Set the GUI to illustrate an invalid file * @param fileException */ private void setGUIForInvalidFile() { InvalidDendroFileException e = model.getFileException(); if(e==null) return; String error = e.getLocalizedMessage(); // Try and highlight the line in the input file that is to blame if poss if( e.getPointerType().equals(PointerType.LINE) && e.getPointerNumber()!=null && !e.getPointerNumber().equals("0")) { Integer line = null; try{ line = Integer.parseInt(e.getPointerNumber()); error+="\n\n"+"The file is shown below with the problematic line highlighted."; } catch (NumberFormatException ex) {} updateOriginalFile(line); } tabbedPane.setEnabledAt(1, false); horizSplitPane.setDividerLocation(0.0); panelTreeTable.setVisible(false); panelWarnings.setVisible(false); txtErrorMessage.setVisible(true); txtErrorMessage.setText(error); pack(); this.tabbedPane.setSelectedIndex(0); } /** Scale an icon down to 20x20 */ private ImageIcon scaleIcon20x20(ImageIcon icon) { return new ImageIcon(icon.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH)); } /** * Select an item in the combo box * Use because TridasEntity.equals compares things we don't care about * * @param thisEntity */ private void selectInTopChooser() { // disable actionListener firing when we change combobox selection topChooserListener.setEnabled(false); ITridas currentEntity = model.getSelectedRow().getCurrentEntity(); try { if (currentEntity == null) { topChooser.setSelectedItem(ImportEntityListComboBox.NEW_ITEM); return; } else if (!currentEntity.isSetIdentifier()) { log.debug("No identifier"); topChooser.setSelectedItem(ImportEntityListComboBox.NEW_ITEM); return; } else if (!currentEntity.getIdentifier().isSetDomain()) { log.debug("No domain"); topChooser.setSelectedItem(ImportEntityListComboBox.NEW_ITEM); return; } else if (!currentEntity.getIdentifier().getDomain().equals(App.domain)) { log.debug("Different domain - this one is: "+currentEntity.getIdentifier().getDomain()+ " and not "+App.domain); topChooser.setSelectedItem(ImportEntityListComboBox.NEW_ITEM); return; } else { log.debug("Correct domain: "+currentEntity.getIdentifier().getDomain()); } FilterableComboBoxModel model = (FilterableComboBoxModel) topChooser.getModel(); // find it in the list... ITridas listEntity; if ((listEntity = entityInList(currentEntity, model.getElements())) != null) { topChooser.setSelectedItem(listEntity); return; } // blech, it wasn't in the list -> add it model.insertElementAt(currentEntity, 2); topChooser.setSelectedItem(currentEntity); } finally { // deal with the selection handleComboSelection(false); // re-enable combo box actionlistener firing topChooserListener.setEnabled(true); } } /** * Silly actionListener class that we can add/remove when we want to programmatically change the combo box * without triggering side effects */ private class ChoiceComboBoxActionListener implements ActionListener { private final ImportView panel; private boolean enabled; public ChoiceComboBoxActionListener(ImportView panel) { this.panel = panel; this.enabled = true; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void actionPerformed(ActionEvent e) { if(enabled) { panel.handleComboSelection(true); } } } /** * Checks to see if the entity is in the given list * * @param entity * @param list * @return The entity in the list (may be another instance) or null */ private ITridas entityInList(ITridas entity, List<?> list) { for(Object o : list) { if(o instanceof ITridas) { ITridas otherEntity = (ITridas) o; if(matchEntities(entity, otherEntity)) return otherEntity; } } return null; } /** * Initialize the state when we: * a) choose something new in the combo box (load children!) * b) programmatically set something in the combo box (don't load children!) */ private void handleComboSelection(boolean loadChildren) { /* Object obj = topChooser.getSelectedItem(); //fixes bug where combobox is hidden in derived series if(obj == null){ return; } else if(obj instanceof ITridas) { temporarySelectingEntity = (ITridas) obj; if(propertiesTable.hasWatermark()){ propertiesTable.setWatermarkText(I18n.getText("general.preview")); } // start loading the list of children right away //if(loadChildren && currentMode != EditType.RADIUS) // lists.prepareChildList(temporarySelectingEntity); propertiesPanel.readFromObject(temporarySelectingEntity); } */ } /** * Compare entities based on type, title, and site code (if they're TridasObjectEx) * @param e1 * @param e2 * @return */ private boolean matchEntities(ITridas e1, ITridas e2) { // either are null? -> no match if(e1 == null || e2 == null) return false; // easy way out: identity! if(e1 == e2) return true; // they're not related classes -> not equal! if(!(e1.getClass().isAssignableFrom(e2.getClass()) || e2.getClass().isAssignableFrom(e1.getClass()))) return false; // compare lab codes for TridasObjectExes if(e1 instanceof TridasObjectEx && e2 instanceof TridasObjectEx) { TridasObjectEx obj1 = (TridasObjectEx) e1; TridasObjectEx obj2 = (TridasObjectEx) e2; // not the same lab code -> not equal if(obj1.hasLabCode() && obj2.hasLabCode() && !obj1.getLabCode().equals(obj2.getLabCode())) return false; } // we found a match! if(e1.getTitle().equals(e2.getTitle())) return true; return false; } /** * Get the tree path for a node * * @param node * @return */ @SuppressWarnings("unchecked") private TreePath getPath(TreeNode node) { @SuppressWarnings("rawtypes") List list = new ArrayList(); // Add all nodes to list while (node != null) { list.add(node); node = node.getParent(); } Collections.reverse(list); // Convert array of nodes to TreePath return new TreePath(list.toArray()); } /** * Called to enable editing * Responsible for loading the duplicate copy into the editor * * @param enabled */ protected void enableEditing(boolean enabled) { propertiesTable.setEditable(enabled); String entityname = "entity"; try{ entityname = TridasTreeViewPanel.getFriendlyClassName(model.getSelectedRow().getCurrentEntityClass()); } catch (Exception e){} editEntityText.setFont(editEntityText.getFont().deriveFont(Font.BOLD)); editEntityText.setText(enabled ? I18n.getText("metadata.currentlyEditingThis") + " " + entityname : I18n.getText("metadata.clickLockToEdit") + " " +entityname); editEntity.setSelected(enabled); if(enabled) { // Remove any 'preview' watermark propertiesTable.setHasWatermark(false); } // disable choosing other stuff while we're editing // but only if something else doesn't disable it first if(topChooser.isEnabled()) { topChooser.setEnabled(!enabled); changeButton.setEnabled(!enabled); } // show/hide our buttons editEntitySave.setEnabled(true); editEntityCancel.setEnabled(true); editEntitySave.setVisible(enabled); editEntityCancel.setVisible(enabled); } /** * @return true if the user wants to lose changes, false otherwise */ private boolean isUserOkWithLoosingAnyChanges() { if(changingTop|| editEntity.isSelected()) { int ret = JOptionPane.showConfirmDialog(this, I18n.getText("question.confirmChangeForm"), I18n.getText("question.continue"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if(ret==JOptionPane.YES_OPTION) { changingTop =false; enableEditing(false); chooseOrCancelUIUpdate(); } return (ret == JOptionPane.YES_OPTION); } else { enableEditing(false); return true; } } /** * @return true if the user wants to lose the new selection, false otherwise */ @SuppressWarnings("unused") private boolean isUserOkWithLoosingSelection() { // nothing new has been selected, nothing to lose Class<? extends ITridas> currentEntityType = model.getSelectedRow().getCurrentEntityClass(); if(!model.getSelectedRow().isDirty()) return true; int ret = JOptionPane.showConfirmDialog(this, I18n.getText("question.confirmChangeForm"), I18n.getText("question.continue"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); return (ret == JOptionPane.YES_OPTION); } }
package com.epam.bd; public class ImpressionWritable { }
package AllSortMethods; public class MergeSort { public static void main(String[] args) { int [] a = {2,4,8,6,5,90,34,21}; MergeSort(a, 0, a.length-1); System.out.println("结果为:"); for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } //递归版本的归并排序 public static void MergeSort(int [] A, int i, int j){ if(i == j) return; int mid = (i+j)/2; MergeSort(A, i, mid); MergeSort(A, mid+1, j); Merge(A, i, mid, j); } public static void Merge(int[] A, int i, int mid, int j){ int p1 = i; int p2 = mid+1; int p3 = 0; int [] C = new int[j-i+1]; //保存临时结果的数组 while(p1<=mid && p2<=j){ if(A[p1] <= A[p2]){ C[p3++] = A[p1++]; }else{ C[p3++] = A[p2++]; } } //把剩下的加到临时数组的末尾 while(p1<=mid) C[p3++] = A[p1++]; while(p2<=j) C[p3++] = A[p2++]; //最后再把结果覆盖回原数组,起始是i for (int k = 0; k < C.length; k++) { A[i++] = C[k]; //归并合并的时候起始是i,结束是j } } }
package ch03.ex03_10; public class LinkedList implements Cloneable { private Object object; LinkedList next; //コンストラクタ public LinkedList(Object object, LinkedList next) { this.object = object; this.next = next; } //コンストラクタ public LinkedList(Object object) { this(object, null); } public void show() { System.out.println(this); if (object instanceof Vehicle) { Vehicle tmpVehicle = (Vehicle) object; tmpVehicle.toString(); } if(next != null) next.show(); } public String toString(){ if (object instanceof Vehicle) { String tmpv; Vehicle tmpVehicle = (Vehicle) object; tmpv = tmpVehicle.toString(); if(next != null) tmpv += next.toString(); return tmpv; } return null; } public Object getObj() { return object; } public void setObj(Object object) { this.object = object; } public LinkedList getNextNode() { return next; } public void setNextNode(LinkedList nextNode) { this.next = nextNode; } public int countList(){ if(next == null) return 1; else return 1 + next.countList(); } public Object clone() { try { LinkedList list = (LinkedList) super.clone(); if (next != null) { list.next = (LinkedList) next.clone(); } return list; } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } } public static void main(String[] args) { Vehicle car = new Vehicle("Mike"); car.setVelocity(2.0); car.setDirection(Math.PI / 2); Vehicle train = new Vehicle("Joe"); train.setVelocity(4.0); train.setDirection(Math.PI * 2); Vehicle airplane = new Vehicle("Nick"); airplane.setVelocity(8.0); airplane.setDirection(Math.PI); LinkedList item3 = new LinkedList(airplane, null); LinkedList item2 = new LinkedList(train, item3); LinkedList item1 = new LinkedList(car, item2); System.out.println("LinkedList"); item1.show(); // 複製を作成 LinkedList cloneList = (LinkedList) item1.clone(); // 速度を変更してみる Vehicle tmpVehicle = (Vehicle)cloneList.getNextNode().getObj(); tmpVehicle.setVelocity(100); System.out.println("Velocity change"); cloneList.show(); // リストの順番を入れ替えてみる item1.next = item3; item3.next = item2; item2.next = null; System.out.println("Node change"); item1.show(); System.out.println("\n"); System.out.println("Node change Clone"); cloneList.show(); } }
package com.yygame.common.utils; /** * @author yzy */ public abstract class PathUtil { /** * 合理化路径, 将 \\ 转成 / * * @param path 路径 * @return 返回替换 \\ // 的地址 */ public static String normalizePath(String path) { if (null != path) { return path.replaceAll("[/\\\\]+", "/"); } return null; } }
package com.mertbozkurt.readingisgood.dto.book; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.mertbozkurt.readingisgood.model.Order; import lombok.Getter; import lombok.Setter; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.List; @Getter @Setter @JsonInclude(JsonInclude.Include.ALWAYS) public class BookDTO { private long id; @JsonProperty("title") private String title; @JsonProperty("auther") private String auther; @JsonProperty("year") private int year; @JsonProperty("publisher") public String publisher; @JsonProperty("price") public double price; }
package com.example.pratibha.whattocook; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button addRecipeButton; private Button searchRecipeButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addRecipeButton = (Button) findViewById(R.id.addRecipe); searchRecipeButton = (Button) findViewById(R.id.searchRecipe); addRecipeButton.setOnClickListener(buttonListener); searchRecipeButton.setOnClickListener(buttonListener); } private View.OnClickListener buttonListener = new View.OnClickListener() { @Override public void onClick(View v) { Intent i; switch(v.getId()) { case R.id.addRecipe: // start the music i = new Intent(getApplicationContext(), PlaySoundService1.class); startService(i); // start new activity with layout i = new Intent(getApplicationContext(), AddRecipeActivity.class); startActivity(i); break; case R.id.searchRecipe: // start the music i = new Intent(getApplicationContext(), PlaySoundService2.class); startService(i); // start new activity with layout i = new Intent(getApplicationContext(), AddIngredientsActivity.class); startActivity(i); break; } } }; }
public class Pera extends Produto { public Pera() { super(10.50, "PÍra"); } @Override public double getPreco() { return this.getPrecoUnitario()*this.getQtde(); } }
import javax.swing.*; import java.awt.*; import java.util.Arrays; class NumberInterface { //本次生成的题目数 private static int number = 0; //总共生成的题目数 private static int finalNumber = 0; //未因难度不同而添加运算符时生成的题目数组 private static String[] preEquations = {}; //因难度不同而添加运算符时生成的最终题目数组 private static String[] finalEquations = {}; NumberInterface() { JFrame jFrame = new JFrame("输入题数"); jFrame.setSize(400,105); jFrame.setLocationRelativeTo(null); jFrame.setLayout(new BorderLayout()); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel jPanel_notice = new JPanel(); JLabel jLabel_choose = new JLabel("请输入想要生成的题目数量(在10至30之间):"); JTextField jTextField_number = new JTextField(); jTextField_number.setPreferredSize(new Dimension(40, 25)); jPanel_notice.add(jLabel_choose); jPanel_notice.add(jTextField_number); jFrame.add(jPanel_notice, BorderLayout.CENTER); JPanel jPanel_button = new JPanel(); JButton jButton_reset = new JButton("重置"); JButton jButton_confirm = new JButton("确认"); jPanel_button.add(jButton_reset); jPanel_button.add(jButton_confirm); jButton_reset.addActionListener(e -> jTextField_number.setText("")); jButton_confirm.addActionListener(e -> { number = Integer.parseInt(jTextField_number.getText()); if (number >= 10 && number <= 30) { finalNumber += number; preEquations = Arrays.copyOf(preEquations, preEquations.length + number); finalEquations = Arrays.copyOf(finalEquations, finalEquations.length + number); if (DegreeInterface.getDegree() == 0) { new Equation(number, finalNumber - number, 1, preEquations, finalEquations); } if (DegreeInterface.getDegree() == 1) { new JuniorEquation(number, finalNumber - number, 0, preEquations, finalEquations); } if (DegreeInterface.getDegree() == 2) { new HighEquation(number, finalNumber - number, 0, preEquations, finalEquations); } jFrame.setVisible(false); jFrame.dispose(); MainInterface.setNumber(number); new MainInterface(finalEquations); } else { JOptionPane.showMessageDialog(null, "题目数量不在范围内!", "错误", JOptionPane.ERROR_MESSAGE); jTextField_number.setText(""); } }); jFrame.add(jPanel_button, BorderLayout.SOUTH); jFrame.setVisible(true); } static int getNumber() { return number; } }
package com.vwaber.udacity.popularmovies.data; import android.net.Uri; import android.provider.BaseColumns; class FavoritesContract { private FavoritesContract() {} static final String CONTENT_AUTHORITY = "com.vwaber.udacity.popularmovies"; private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); static final String PATH_FAVORITES = "favorites"; static final class FavoritesEntry implements BaseColumns { static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon() .appendPath(PATH_FAVORITES) .build(); static final String TABLE_NAME = "favorites"; static final String COLUMN_DATE = "date"; static final String COLUMN_TMDB_ID = "tmdb_id"; } }
package com.sdk4.boot.controller.file; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.sdk4.boot.bo.LoginUser; import com.sdk4.boot.common.BaseResponse; import com.sdk4.boot.domain.File; import com.sdk4.boot.exception.BaseError; import com.sdk4.boot.fileupload.*; import com.sdk4.boot.service.AuthService; import com.sdk4.boot.service.FileService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.tika.Tika; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.net.URLEncoder; import java.util.List; import java.util.Map; /** * 文件上传 * * @author sh */ @Slf4j @RestController @RequestMapping("file") public class FileUploadController { @Autowired AuthService authService; @Autowired FileService fileService; @RequestMapping(value = { "upload" }, produces = "application/json;charset=utf-8") public BaseResponse<Map> upload(HttpServletRequest request, HttpServletResponse response) { BaseResponse<Map> ret = new BaseResponse<>(); String type = request.getParameter("type"); if (StringUtils.isEmpty(type)) { ret.put(BaseError.MISSING_PARAMETER.getCode(), "上传文件类型type不能为空"); } else { FileTypeConfig ftc = FileUploadHelper.getFileTypeConfig(type); LoginUser loginUser = authService.getLoginUserFromSession(); if (ftc == null) { ret.put(BaseError.INVALID_PARAMETER.getCode(), "上传文件类型type不正确"); } else if (ftc.getLoginRequired() && loginUser == null) { ret.put(BaseError.NOT_LOGIN); } else { List<FileUploadInfo> files = FileUploadHelper.getFileUploadInfos(request); if (files.isEmpty()) { ret.put(BaseError.BIZ_FAIL.getCode(), "未上传文件"); } else { Map data = Maps.newHashMap(); List<Map<String, Object>> success = Lists.newArrayList(); List<Map<String, Object>> error = Lists.newArrayList(); for (FileUploadInfo info : files) { if (ftc.getMaxSize() != null && ftc.getMaxSize() > 0 && info.getFileSize() > ftc.getMaxSize()) { addError(error, info, "文件大小不能大于" + ftc.getMaxSize()); } else if (CollectionUtils.isNotEmpty(ftc.getExt()) && !ftc.getExt().contains(info.getSuffix())) { addError(error, info, "文件类型只能上传" + StringUtils.join(ftc.getExt(), ",") + "类型的文件"); } else { FileSaveInfo saveInfo = FileUploadHelper.saveFile(type, info); if (saveInfo == null) { addError(error, info, "文件上传失败"); } else { BaseResponse<File> callResult = fileService.saveUploadFile(type, info, saveInfo, loginUser); if (callResult.isSuccess()) { Map<String, Object> item = Maps.newHashMap(); item.put("key", info.getFileKey()); item.put("size", info.getFileSize()); item.put("id", saveInfo.getFileId()); item.put("url", saveInfo.getUrl()); success.add(item); } else { addError(error, info, "文件信息保存失败"); } } } } data.put("type", type); data.put("success", success.size()); data.put("fail", error.size()); if (error.size() > 0) { ret.put(BaseError.BIZ_FAIL.getCode(), "文件上传失败"); data.put("errors", error); } else { ret.put(0, "文件上传成功"); data.put("files", success); } ret.setData(data); } } } return ret; } private static int FILE_BASE_URL_LEN = "/file/resource/".length(); @ResponseBody @RequestMapping(value = { "resource/**" }) public String file(HttpServletRequest request, HttpServletResponse response) { String uri = request.getRequestURI(); String fileUri = uri.substring(FILE_BASE_URL_LEN); int typeAt = fileUri.indexOf('/'); int suffixAt = fileUri.lastIndexOf('.'); if (typeAt > 0 && suffixAt > 0) { String type = fileUri.substring(0, typeAt); String suffix = fileUri.substring(suffixAt + 1); String objectKey = fileUri.substring(0, suffixAt); try { java.io.File file = FileUploadHelper.readFile(type, objectKey); if (file != null && file.exists()) { Tika tika = new Tika(); String contentType = tika.detect(file); if (StringUtils.isEmpty(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } if (false) { response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("filename." + suffix, "UTF-8")); } OutputStream out = response.getOutputStream(); out.write(FileUtils.readFileToByteArray(file)); out.flush(); } } catch (Exception e) { log.error("输入文件流失败: {}", fileUri, e); } } return null; } private void addError(List<Map<String, Object>> error, FileUploadInfo uploadInfo, String errorMessage) { Map<String, Object> item = Maps.newHashMap(); item.put("key", uploadInfo.getFileKey()); item.put("size", uploadInfo.getFileSize()); item.put("error", errorMessage); error.add(item); } }
/** * LICENSE * * This source file is subject to the MIT license that is bundled * with this package in the file MIT.txt. * It is also available through the world-wide-web at this URL: * http://www.opensource.org/licenses/mit-license.html */ package org.code_factory.jpa.nestedset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.code_factory.jpa.nestedset.model.Category; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * @author Roman Borschel <roman@code-factory.org> */ public class BasicTest extends FunctionalNestedSetTest { private Category progCat; private Category javaCat; private Category netCat; @AfterMethod @Override protected void closeEntityManager() { super.closeEntityManager(); this.progCat = null; this.javaCat = null; this.netCat = null; } /** * Helper method that creates a basic tree that looks as follows: * * Programming * / \ * Java .NET * */ private void createBasicTree() { this.progCat = new Category(); this.progCat.setName("Programming"); this.javaCat = new Category(); this.javaCat.setName("Java"); this.netCat = new Category(); this.netCat.setName(".NET"); em.getTransaction().begin(); Node<Category> rootNode = nsm.createRoot(this.progCat); rootNode.addChild(this.javaCat); rootNode.addChild(this.netCat); em.getTransaction().commit(); em.clear(); nsm.clear(); } @Test public void testBuildTree(){ Category root1 = new Category(); root1.setLeftValue(1); root1.setRightValue(8); root1.setRootValue(0); root1.setLevel(0); root1.setId(100L); root1.setName("Programming"); Category javaCat2 = new Category(); javaCat2.setLeftValue(2); javaCat2.setRightValue(3); javaCat2.setRootValue(0); javaCat2.setLevel(1); javaCat2.setId(101L); javaCat2.setName("Java"); Category netCat2 = new Category(); netCat2.setLeftValue(4); netCat2.setRightValue(7); netCat2.setRootValue(0); netCat2.setLevel(1); netCat2.setId(102L); netCat2.setName(".NET"); Category wpfCat = new Category(); wpfCat.setName("WPF"); wpfCat.setLeftValue(5); wpfCat.setRightValue(6); wpfCat.setRootValue(0); wpfCat.setLevel(2); wpfCat.setId(103L); List<Category> listTree = new ArrayList<Category>(); listTree.add(root1); listTree.add(javaCat2); listTree.add(netCat2); listTree.add(wpfCat); List<Node<Category>> tree = new ArrayList<Node<Category>>(); for (Category n : listTree) { tree.add(nsm.getNode(n)); } // Now move it under the .NET category where it really belongs /* Programming / \ Java .NET | WPF */ nsm.buildTree(tree,0); System.out.println(tree.toString()); } @Test public void testCreateRoot() { Category cat = new Category(); cat.setName("Java"); em.getTransaction().begin(); nsm.createRoot(cat); em.getTransaction().commit(); em.clear(); Category cat2 = em.find(Category.class, cat.getId()); assert 1 == cat2.getLeftValue(); assert 2 == cat2.getRightValue(); assert 0 == cat2.getLevel(); assert cat != cat2; assert true == nsm.getNode(cat2).isRoot(); } @Test public void testFetchTree() { this.createBasicTree(); // List<Node<Category>> treeTest = nsm.fetchTreeAsList(Category.class, 0 , 2); // treeTest = nsm.fetchTreeAsList(Category.class, 0 , 1); List<Node<Category>> tree = nsm.fetchTreeAsList(Category.class); assert tree.size() == 3; Iterator<Node<Category>> iter = tree.iterator(); for (int i = 0; i < 3; i++) { Node node = iter.next(); if (i == 0) { assert 1 == node.getLeftValue(); assert 6 == node.getRightValue(); assert 0 == node.getLevel(); } else if (i == 1) { assert 2 == node.getLeftValue(); assert 3 == node.getRightValue(); assert 1 == node.getLevel(); } else { assert 4 == node.getLeftValue(); assert 5 == node.getRightValue(); assert 1 == node.getLevel(); } } } @Test public void testBasicTreeNavigation() { this.createBasicTree(); Category progCat2 = em.find(Category.class, this.progCat.getId()); Node<Category> progCatNode = nsm.getNode(progCat2); assert 1 == progCatNode.getLeftValue(); assert 6 == progCatNode.getRightValue(); assert 0 == progCatNode.getLevel(); assert null == progCatNode.getParent(); List<Node<Category>> children = progCatNode.getChildren(); assert 2 == children.size(); Iterator<Node<Category>> childIter = children.iterator(); Node child1 = childIter.next(); Node child2 = childIter.next(); assert 2 == child1.getLeftValue(); assert 3 == child1.getRightValue(); assert false == child1.hasChildren(); assert false == child2.hasChildren(); assert 0 == child1.getChildren().size(); assert 0 == child2.getChildren().size(); assert progCat2 == child1.getParent().unwrap(); assert progCat2 == child2.getParent().unwrap(); } @Test public void testAddingNodesToTree() { this.createBasicTree(); assert 0 == this.nsm.getNodes().size(); Node<Category> root = this.nsm.getNode(em.find(Category.class, this.progCat.getId())); // Assert basic tree state, a Programming category with 2 child categories. assert 1 == root.getLeftValue(); assert 6 == root.getRightValue(); assert 2 == root.getChildren().size(); assert 2 == root.getChildren().size(); assert 3 == this.nsm.getNodes().size(); // Add PHP category under Programming em.getTransaction().begin(); Category phpCat = new Category(); phpCat.setName("PHP"); root.addChild(phpCat); em.getTransaction().commit(); assert 6 == phpCat.getLeftValue(); assert 7 == phpCat.getRightValue(); assert 8 == root.getRightValue(); assert 3 == root.getChildren().size(); // Add Java EE category under Java em.getTransaction().begin(); Category jeeCat = new Category(); jeeCat.setName("Java EE"); Node<Category> javaNode = this.nsm.getNode(em.find(Category.class, this.javaCat.getId())); javaNode.addChild(jeeCat); em.getTransaction().commit(); assert 3 == root.getChildren().size(); assert 3 == jeeCat.getLeftValue(); assert 4 == jeeCat.getRightValue(); assert 2 == jeeCat.getLevel(); assert 2 == javaNode.getLeftValue(); assert 5 == javaNode.getRightValue(); assert 10 == root.getRightValue(); assert 5 == this.nsm.getNodes().size(); } /** * Tests creating new nodes and moving them around in a tree. */ @Test public void testMovingNodes() { this.createBasicTree(); em.getTransaction().begin(); Node<Category> progNode = this.nsm.getNode(em.find(Category.class, this.progCat.getId())); // Create a new WPF category, placing it under "Programming" first. /* Programming / | \ Java .NET WPF */ Category wpfCat = new Category(); wpfCat.setName("WPF"); Node<Category> wpfNode = progNode.addChild(wpfCat); assert 6 == wpfNode.getLeftValue(); assert 7 == wpfNode.getRightValue(); assert 1 == wpfNode.getLevel(); assert 8 == progNode.getRightValue(); // Now move it under the .NET category where it really belongs /* Programming / \ Java .NET | WPF */ Node<Category> netNode = this.nsm.getNode(em.find(Category.class, this.netCat.getId())); wpfNode.moveAsLastChildOf(netNode); assert 4 == netNode.getLeftValue(); assert 7 == netNode.getRightValue(); assert 5 == wpfNode.getLeftValue(); assert 6 == wpfNode.getRightValue(); assert 2 == wpfNode.getLevel(); assert 8 == progNode.getRightValue(); // Create another category "EJB" under "Programming" that doesnt really belong there /* Programming / | \ Java .NET EJB | WPF */ Category ejbCat = new Category(); ejbCat.setName("EJB"); Node<Category> ejbNode = progNode.addChild(ejbCat); assert 8 == ejbNode.getLeftValue(); assert 9 == ejbNode.getRightValue(); assert 10 == progNode.getRightValue(); // Move it under "Java" where it belongs /* Programming / \ Java .NET | | EJB WPF */ Node<Category> javaNode = this.nsm.getNode(em.find(Category.class, this.javaCat.getId())); ejbNode.moveAsLastChildOf(javaNode); assert 3 == ejbNode.getLeftValue(); assert 4 == ejbNode.getRightValue(); assert 2 == ejbNode.getLevel(); assert 5 == javaNode.getRightValue(); assert 6 == netNode.getLeftValue(); assert 9 == netNode.getRightValue(); assert 10 == progNode.getRightValue(); em.getTransaction().commit(); } @Test public void testDeleteNode() { this.createBasicTree(); em.getTransaction().begin(); // fetch the tree Node<Category> progNode = nsm.fetchTree(Category.class, this.progCat.getRootValue()); assertEquals(progNode.getChildren().size(), 2); assert 1 == progNode.getLeftValue(); assert 6 == progNode.getRightValue(); // delete the .NET node Category netCat2 = em.find(Category.class, this.netCat.getId()); Node<Category> netNode = nsm.getNode(netCat2); netNode.delete(); // check in-memory state of tree assert 1 == progNode.getLeftValue(); assert 4 == progNode.getRightValue(); assertFalse(em.contains(netCat2)); assertTrue(em.contains(progNode.unwrap())); assertEquals(progNode.getChildren().size(), 1); try { nsm.getNode(netCat2); fail("Retrieving node for deleted category should fail."); } catch (IllegalArgumentException expected) {} em.getTransaction().commit(); } }
package com.jim.multipos.utils.managers; import android.content.Context; /** * Created by Developer on 5/23/17. */ public class CurrencyManager { private static CurrencyManager instance; private Context context; public static CurrencyManager getInstance(Context context) { if (instance == null) { instance = new CurrencyManager(context); } return instance; } private CurrencyManager(Context context) { this.context = context; } }
import java.awt.image.BufferedImage; /** * Class which provides image processing utility methods. * * @author Giovanbattista * */ public class ImageProcessing { /** * This method iterates through the entire image and applies the recoloring. * * @param originalImage original image. * @param resultImage result image. * @param leftCorner value of the left corner of the image. * @param topCorner value of the top corner of the image. * @param width width of the image. * @param height height of the image. */ public static void recolorImage(BufferedImage originalImage, BufferedImage resultImage, int leftCorner, int topCorner, int width, int height) { for (int x = leftCorner; x < leftCorner + width && x < originalImage.getWidth(); x++) { for (int y = topCorner; y < topCorner + height && y < originalImage.getHeight(); y++) { recolorPixel(originalImage, resultImage, x, y); } } } /** * Recolors the pixel at the x and y coordinates obtained from the original * image into the result image. * * @param originalImage original image. * @param resultImage result image. * @param x x coordinate of the pixel to recolor. * @param y y coordinate of the pixel to recolor. */ public static void recolorPixel(BufferedImage originalImage, BufferedImage resultImage, int x, int y) { int rgb = originalImage.getRGB(x, y); int red = getRed(rgb); int green = getGreen(rgb); int blue = getBlue(rgb); int newRed; int newGreen; int newBlue; if (isShadeOfGray(red, green, blue)) { newRed = Math.min(255, red + 10); newGreen = Math.max(0, green - 80); newBlue = Math.max(0, blue - 20); } else { newRed = red; newGreen = green; newBlue = blue; } int newRGB = createRGBFromColors(newRed, newGreen, newBlue); setRGB(resultImage, x, y, newRGB); } /** * Assign the rgb color value to the image. * * @param image target buffer image. * @param x pixel x coordinate. * @param y pixel y coordinate. * @param rgb rgb value. */ public static void setRGB(BufferedImage image, int x, int y, int rgb) { image.getRaster().setDataElements(x, y, image.getColorModel().getDataElements(rgb, null)); } /** * Determines if a pixel is a shade of gray. Check if all the three components * have similar color intensity, with no one stronger than the rest. * * @param red red value. * @param green green value. * @param blue blue value. * @return return true if a pixel with the specified color values is a shade of * gray, false otherwise. */ public static boolean isShadeOfGray(int red, int green, int blue) { /** * Check if the color is almost a perfect mix of green red and blue we know it's * a shade of gray. 30 is the distance used to determine their proximity. */ return Math.abs(red - green) < 30 && Math.abs(red - blue) < 30 && Math.abs(green - blue) < 30; } /** * Build the pixel rgb compound value from the individual value of red, green * and blue. * * @param red red value. * @param green green value. * @param blue blue value. * @return return the rgb compound value from red, green and blue. */ public static int createRGBFromColors(int red, int green, int blue) { int rgb = 0; /** * rgb computed applying the logical OR with the individual values, bit shifting * properly. */ rgb |= blue; // no shift needed cause blue is the rightmost byte value rgb |= green << 8; // one byte left shift rgb |= red << 16; // two bytes left shift rgb |= 0xFF000000; // set the alpha value to the highest value to make the pixel opaque return rgb; } /** * Return only the blue value from the specified rgb value. * * @param rgb rgb value. * @return return the blue value from the specified rgb value. */ public static int getBlue(int rgb) { /** * Apply a bit mask excluding the rightmost byte which is exactly the blue * component. */ return rgb & 0x000000FF; } /** * Return only the green value from the specified rgb value. * * @param rgb rgb value. * @return return the green value from the specified rgb value. */ public static int getGreen(int rgb) { /** * Apply a bit mask excluding the alpha, red and blue component and shift 8 * bytes to the right cause green is the second byte from the right. */ return (rgb & 0x0000FF00) >> 8; } /** * Return only the red value from the specified rgb value. * * @param rgb rgb value. * @return return the red value from the specified rgb value. */ public static int getRed(int rgb) { /** * Apply a bit mask excluding the alpha, green and blue component and shift 16 * bytes to the right cause red is the third byte from the right. */ return (rgb & 0x00FF0000) >> 16; } }
package chatroom.client; import chatroom.model.message.*; import java.util.ArrayList; import java.util.concurrent.TimeUnit; /** * This Thread pulls a Message from the Queue provided by the ListeningThread and handles the Message accordingly by * its type. */ public class ClientMessageHandler extends Thread { private Client client; public ClientMessageHandler(Client client) { this.client = client; } @Override public void run() { while (client.isRunning()) { try { Message m = client.getClientListener().getMessageQueue().poll(1, TimeUnit.SECONDS); if (m == null) { continue; } handleMessage(m); } catch (InterruptedException e) { e.printStackTrace(); } } System.err.println("Shutting down Message Handler!"); } /** * Handles the message by calling various methods depending on its type. * @param message the message received from the server */ public void handleMessage(Message message) { switch (client.getMessageTypeDictionary().getType(message.getType())) { case PUBLICTEXTMSG: PublicTextMessage publicTextMessage = ((PublicTextMessage) message); client.getBridge().AddMessageToView(publicTextMessage.getSender(), publicTextMessage.getMessage()); String publicString = publicTextMessage.getSender() + ": " + publicTextMessage.getMessage(); System.out.println(publicString); break; case PUBLICSERVERMSG: PublicServerMessage publicServerMessage = ((PublicServerMessage) message); client.getBridge().AddMessageToView("SERVER", publicServerMessage.getMessage()); System.out.println("*** " + publicServerMessage.getMessage() + " ***"); break; case TARGETSERVERMSG: TargetedServerMessage targetedServerMessage = ((TargetedServerMessage) message); client.getBridge().AddMessageToView("SERVER", targetedServerMessage.getMessage()); System.out.println("Server: " + targetedServerMessage.getMessage()); break; case TARGETTEXTMSG: TargetedTextMessage targetedTextMessage = ((TargetedTextMessage) message); client.getBridge().addPrivateMessage(targetedTextMessage.getSender(), targetedTextMessage.getMessage(), false); break; case WARNINGMSG: WarningMessage warningMessage = ((WarningMessage) message); switch (warningMessage.getSeverity()) { case 0: client.getBridge().issueBox(warningMessage.getMessage(), false); break; case 1: case 2: client.getBridge().issueBox(warningMessage.getMessage(), true); break; } break; case ROOMLISTMSG: RoomListMessage roomListMessage = ((RoomListMessage) message); client.setRoomMessageList(roomListMessage.getRoomList()); client.getBridge().onRoomUpdate(client.getRooms()); break; case ROOMCHANGERESPONSEMSG: RoomChangeResponseMessage roomChangeResponseMessage = ((RoomChangeResponseMessage) message); client.setActiveRoom(roomChangeResponseMessage.getRoomName()); client.getBridge().onRoomChangeRequestAccepted(roomChangeResponseMessage.getRoomName()); if (roomChangeResponseMessage.isSuccessful()) { client.getBridge().AddMessageToView("SERVER", "You are now talking in Room\"" + roomChangeResponseMessage.getRoomName() + "\""); } break; case SERVERUSERLISTMSG: ServerUserListMessage serverUserListMessage = ((ServerUserListMessage) message); client.setServerUserList(serverUserListMessage.getServerUserList()); client.getBridge().allUsersUpdate((ArrayList<String>) client.getAllUsers()); break; case ROOMUSERLISTMSG: RoomUserListMessage roomUserListMessage = ((RoomUserListMessage) message); client.setRoomUserList((ArrayList<String>) roomUserListMessage.getUserList()); client.getBridge().userRoomUpdate((ArrayList<String>) roomUserListMessage.getUserList()); break; case ROOMNAMEEDITMSG: RoomNameEditMessage roomNameEditMessage = ((RoomNameEditMessage) message); client.setActiveRoom(roomNameEditMessage.getNewName()); client.getBridge().onRoomChangeRequestAccepted(roomNameEditMessage.getNewName()); break; case PRIVATEROOMSTARTREQMSG: PrivateChatStartRequestMessage privateChatStartRequestMessage = ((PrivateChatStartRequestMessage) message); client.getBridge().processStartRequestForPrivateChat(privateChatStartRequestMessage.getRequester()); break; case PRIVATEROOMENDREQMSG: PrivateChatEndRequestMessage privateChatEndRequestMessage = ((PrivateChatEndRequestMessage) message); client.getBridge().changePrivateChatActiveStatus(privateChatEndRequestMessage.getRequester()); client.getBridge().addPrivateMessage(privateChatEndRequestMessage.getRequester(), privateChatEndRequestMessage.getRequester() + " has disconnected from chat!", true); break; case LOGINRESPONSEMSG: client.getBridge().onServerLoginAnswer(((LoginResponseMessage) message).getResponse()); switch (((LoginResponseMessage) message).getResponse()) { case SUCCESS: client.setLoggedIn(true); System.out.println("*** You are logged in! ***"); break; case CREATED_ACCOUNT: client.setLoggedIn(true); System.out.println("*** This name was not given. Created a new Account! ***"); break; case ALREADY_LOGGED_IN: System.out.println("*** Someone is already using your Account!!!! ***"); System.out.println("*** Your Account might be in danger. Contact an admin! ***"); break; case WRONG_PASSWORD: System.out.println("*** Wrong password! Please try again! ***"); break; } break; } } }
package org.springframework.sync.diffsync; import java.util.List; import lombok.Getter; import org.springframework.sync.Patch; import org.springframework.sync.operations.PatchOperation; @Getter public class VersionedPatch extends Patch { private final long serverVersion; private final long clientVersion; public VersionedPatch(List<PatchOperation> operations, long serverVersion, long clientVersion) { super(operations); this.serverVersion = serverVersion; this.clientVersion = clientVersion; } }
package com.ak.profile_management.concepts; public class Requirement { Skill skill; Location location; public Requirement() { } public Requirement(Skill skill, Location location) { super(); this.skill = skill; this.location = location; } public Skill getSkill() { return skill; } public void setSkill(Skill skill) { this.skill = skill; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } }
package ProjectPersonal.Thethreecarddealer; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Pair; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import java.io.IOException; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.Vector; /** * JavaFX App */ public class App extends Application { CardGuess player = new CardGuess(); ProbabilityGame player2 = new ProbabilityGame(); NimTypeZero player3 = new NimTypeZero(); TextField s1,s2,s3,s4,s5,s6,s7,s8,s9,s10; Button b1,b2,b3,b4, returna, Home, Exit; Label n1,n2,n3, card, cardV, cardS, choiceA, choiceS,choiceC,choiceN, info; HBox c1,c2,c3,c4,c5,c6,c7; VBox con1,con2, con3; Image game1,game2, game3, gameBackground,gameBackground2,gameBackground3, scene1; ImageView g1, g2,g3,gb1,gb2,gb3,sc1; BorderPane startPane,secondPane,thirdPane; Scene scene,secondary,third; int value; public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws IOException { //Probability Game s1 = new TextField(); b1 = new Button(); n1 = new Label("Probability Game"); b1.setGraphic(n1); n1.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); //NimTypeZero Game s2 = new TextField(); b2 = new Button(); n2 = new Label("Nim Type Zero"); b2.setGraphic(n2); n2.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: blue;"); //Card Guessing Game. s3 = new TextField(); b3 = new Button(); n3 = new Label("Card Guessing Game"); b3.setGraphic(n3); n3.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: Green;"); //Creating startPane screen. c1 = new HBox(b1,b2,b3); // create a background fill BackgroundFill bf = new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY); // create Background Background background = new Background(bf); //creating a label for directions on selecting a game. Label y = new Label("Select one of the games above."); y.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 25pt; -fx-text-fill: green;"); //Scene background creation. scene1 = new Image("Capture.jpg"); sc1 = new ImageView(scene1); //Completing a BorderPane. startPane = new BorderPane(); startPane.setTop(c1); startPane.setBackground(background); startPane.setCenter(sc1); startPane.setBottom(y); //Probability Game. b1.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent a) { secondPane = new BorderPane(); //informing the user on what to do. info = new Label(" Welcome the Probabilities. Please fill out the form below to select a card."); Label info2 = new Label(" If you do not want to select a card, type none into Card Value and then click the Submit button."); Label info3 = new Label(" Remember if you are choosing a card, all selections must be filled out."); Label info4 = new Label("If you like to return to the main screen to select a different game press the Return Button."); Label info5 = new Label(); VBox q = new VBox(info,info2,info3,info4,info5); info.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: black;"); info2.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: black;"); info3.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); info4.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: black;"); //making the form that will be filled by the player; cardV = new Label("Card Value: "); s4 = new TextField(); c2 = new HBox(cardV,s4); cardS = new Label("Suite: "); s5 = new TextField(); c3 = new HBox(cardS,s5); cardV.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: green;"); cardS.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: green;"); b4 = new Button("Submit"); returna = new Button ("Return"); HBox t = new HBox(b4,returna); con2 = new VBox(c2,c3,t); //Game will be played here. b4.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent a) {gamePlay1(stage); }}); //returns to the entrance. returna.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent a) { stage.setScene(scene); stage.show(); }}); secondPane.setCenter(con2); secondPane.setTop(q); secondary = new Scene(secondPane,1000,1000); stage.setScene(secondary); stage.show(); }});; //Nim Type Zero game. b2.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {GamePlay2(stage);}});; //Card Guessing game. b3.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {GamePlay3(stage);}});; scene = new Scene(startPane, 640, 480); stage.setScene(scene); stage.show(); } //this function will play the Probability game. public void gamePlay1(Stage stage) { player2.makeDeck();// making the deck first. Vector <String> finalize = new Vector<String>(); Label results = new Label("The size of the deck of cards is: " ); Label fa = new Label(String.valueOf(player2.getDeck().size())); Label space = new Label(); HBox cam = new HBox(results,fa); VBox resspace = new VBox(cam,space); //this will only be used if the user has select none. Random rand = new Random(); int cardplayed = rand.nextInt(52); //player's request. String cardChoice = s4.getText(); String suiteChoice = s5.getText(); //test to see if the player choose none. if(cardChoice.equals("none")){ finalize = player2.selectCard(player2.getDeck().get(cardplayed).getCard(),player2.getDeck().get(cardplayed).getShape()); } else { finalize = player2.selectCard(cardChoice,suiteChoice); } //print out all information //card and Suite will be shown first. Label cardSuitea = new Label("Your card and Suite are: "); Label f1 = new Label( finalize.get(0) + " "+ finalize.get(1)); Label space2 = new Label(); HBox combine = new HBox(cardSuitea,f1); VBox a1 = new VBox(combine, space2); //Probability of selecting the same card is next. Label sameCard = new Label("IF the card was return to the deck,The probability of "); Label sameCard2 = new Label("selecting the same card is: "); Label f2 = new Label(finalize.get(2)); Label space3 = new Label(); HBox combine2 = new HBox(sameCard2,f2); VBox b1 = new VBox(sameCard,combine2,space3); //Probability of selecting a different card with the same suite. Label sameSuite = new Label("IF the card was not placed back into the deck. The probability of "); Label sameSuite2 = new Label("selecting a diffrenet card with the same suite is: "); Label f3 = new Label(finalize.get(3)); HBox combine3 = new HBox(sameSuite2,f3); Label space4 = new Label(); VBox c1 = new VBox(sameSuite,combine3,space4); //Probability of selecting a different card with the same color. Label sameColor = new Label("IF the card was not placed back into the deck. The probability of "); Label sameColor2 = new Label("selecting a diffrenet card with the same color is: "); Label f4 = new Label(finalize.get(4)); HBox combine4 = new HBox(sameColor2,f4); Label space5 = new Label(); VBox d1 = new VBox(sameColor, combine4,space5); //Probability of selecting a different card with the same number. Label sameNum = new Label("IF the card was not placed back into the deck. The probability of "); Label sameNum2 = new Label("selecting a diffrenet card with the same suite is: "); Label f5 = new Label(finalize.get(5)); HBox combine5 = new HBox(sameNum2,f5); Label space6 = new Label(); VBox e1 = new VBox(sameNum,combine5, space6); //if the player wants to select a new card, new game or exit the program. Label res = new Label("Here is the results for you chosen card."); Label ra1a = new Label("To choose another card click the Return button."); Label r = new Label("IF you want to play a different game press the Home button."); Label e = new Label("To exit the game select Exit button."); Label space7 = new Label(); //Buttons that are needed. Exit = new Button("Exit"); Home = new Button("Home"); Button ra1 = new Button("Return"); HBox menuBoxes = new HBox(Home,ra1,Exit); //main VBoxes to be displayed. VBox Top = new VBox(res,r,ra1a,e,space7,menuBoxes); VBox Center = new VBox(resspace,a1,b1,c1,d1,e1); //set on actions for all three buttons. Home.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {stage.setScene(scene);stage.show();}});; ra1.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {stage.setScene(secondary);stage.show();}});; Exit.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {System.exit(0);}});; //set all words to specific color. //These are all for the introduction. res.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: black;"); ra1a.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: black;"); r.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: black;"); e.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: black;"); //These are for the results presentation. results.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); cardSuitea.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); sameCard.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); sameCard2.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); sameColor.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); sameColor2.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); sameSuite.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); sameSuite2.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); sameColor.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); sameColor2.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); sameNum.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); sameNum2.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: red;"); //These are the answers for probabilities. fa.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: blue;"); f1.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: blue;"); f2.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: blue;"); f3.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: blue;"); f4.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: blue;"); f5.setStyle("-fx-font-family: Time New Roman; -fx-font-size: 15pt; -fx-text-fill: blue;"); //making the third borderPane for results. BorderPane third = new BorderPane(); third.setTop(Top); third.setCenter(Center); Scene three = new Scene(third, 1000,1000); stage.setScene(three); stage.show(); } //-----------------------End of GamePlay1 Method--------------------------------------------------------------------------------------- //-----------------------Methods for GamePlay2----------------------------------------------------------------------------------------- //main game play for two. public void GamePlay2(Stage stage) { VBox t; Label a = new Label("Welcome players to Nim Type Zero."); Label b = new Label ("Before we begin,let me your dealer, explain the rules."); Label c = new Label("You will each be dealt four cards, from a deck of 40 cards."); Label d = new Label ("The object of this game is to be the player who does not go over 9."); Label e = new Label("Any players who go over 9 will not recieve a point."); Label f = new Label("There will be three rounds and at the end of the third round the winnner will be anounced."); Label g = new Label ("Since I am unable to see you, I must warn all players..."); Label h = new Label ("ANY CHEATING WILL AUTOMATICLY END THE GAME!!!"); Label i = new Label("Lets us begin the game."); Label space = new Label(); player3.gameTime(); Label j = new Label("Click the Home button if you want ot play a different game."); Label k = new Label("Click the Exit button to exit the system."); Label l = new Label("Click the Start button to enter the game."); Label m = new Label(); //Introduction words. a.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); b.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); c.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); d.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); e.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); f.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); g.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); h.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); i.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); j.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); k.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); l.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); //these buttons wiil be used and the set on action. Button start = new Button("Start"); Button exit = new Button("Exit"); Button home = new Button("Home"); HBox v = new HBox(home, start,exit); TextField starter = new TextField();starter.setText("0"); String currentPlayer = player3.dealerStands(player3.dealersPosition); start.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {res1(stage,currentPlayer,currentPlayer,starter, 0, 1);}});; home.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {stage.setScene(scene);stage.show();}});; exit.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {System.exit(0);}});; t = new VBox(a,b,c,d,e,f,g,h,i,space,j,k,l,m,v); //making the third borderPane for results. BorderPane third = new BorderPane(); third.setCenter(v); Scene three = new Scene(third, 1000,1000); stage.setScene(three); stage.show(); } //these methods are the actual game. public void res1(Stage stage,String previousPlayer,String currentPlayer,TextField responds, int count, int rounds) { //testing to see if has reached over nine int count2= count + Integer.parseInt(responds.getText()); int rounds2 = rounds + 1; player3.lmp(currentPlayer,responds.getText()); HBox cards = new HBox(); VBox t = null; String previousPlayer2 = currentPlayer; String currentPlayer2 = player3.nextPlayers(currentPlayer); if(count2 > 9) { if (rounds == 3) {finizi1(stage);} else { rounds2 = rounds2 - 1; //we are starting with a new deck every time so that the players do not complain about cheating. player3.gameTime(); Label a = new Label( "Player: " + currentPlayer + " You will start the next round."); player3.winners(currentPlayer);//this function call will state who wins each round. count = 0; Label b = new Label("The count value: "+count); Label c = new Label("Player: " + currentPlayer); Label g = new Label("Once you select your card, press the Submit button."); cards = printCards(currentPlayer); Label d = new Label(" Select your Card: "); TextField e = new TextField(); HBox f = new HBox(d,e); Button submit = new Button("Submit"); t = new VBox(a,b,c,cards,g,f,submit); //setting all the text a certain size and style. a.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); b.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); c.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); d.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); e.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); submit.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); //set on action submit button. submit.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {res2(stage,previousPlayer2,currentPlayer2,e, 0, 1);}}); } } //if count is not high then 9 then else { rounds2 = rounds2 - 1; Label b = new Label("The count value: "+count); Label c = new Label("Player: " + currentPlayer); Label g = new Label("Once you select your card, press the Submit button."); cards = printCards(currentPlayer); Label d = new Label(" Select your Card: "); TextField e = new TextField(); HBox f = new HBox(d,e); Button submit = new Button("Submit"); t = new VBox(b,c,cards,g,f,submit); //setting all the text a certain size and style. g.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); b.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); c.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); d.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); submit.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); //set on action submit button. submit.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {res1(stage,previousPlayer2,currentPlayer2,e, count2, rounds2);}}); } //making the third borderPane for results. BorderPane third = new BorderPane(); third.setCenter(t); Scene three = new Scene(third, 1000,1000); stage.setScene(three); stage.show(); } public void res2(Stage stage,String previousPlayer,String currentPlayer,TextField responds, int count, int rounds) { //testing to see if has reached over nine int count2 = count + Integer.parseInt(responds.getText()); player3.lmp(currentPlayer,responds.getText()); int rounds2 = rounds + 1; HBox cards = new HBox(); VBox t = null; String previousPlayer2 = currentPlayer; String currentPlayer2 = player3.nextPlayers(currentPlayer); if(count2 > 9) { if (rounds == 3) {finizi1(stage);} else { //we are starting with a new deck every time so that the players do not complain about cheating. player3.gameTime(); Label a = new Label( "Player: " + currentPlayer + " You will start the next round."); player3.winners(currentPlayer);//this function call will state who wins each round. count = 0; Label b = new Label("The count value: "+count); Label c = new Label("Player: " + currentPlayer); Label g = new Label("Once you select your card, press the Submit button."); cards = printCards(currentPlayer); Label d = new Label(" Select your Card: "); TextField e = new TextField(); HBox f = new HBox(d,e); Button submit = new Button("Submit"); t = new VBox(a,b,c,cards,g,f,submit); //setting all text inside all the labels. a.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); b.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); c.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); d.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); e.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); submit.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); //set on action submit button. submit.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {res1(stage,previousPlayer2,currentPlayer2,e, 0, rounds2);}}); } } //if count is not high then 9 then else { rounds = rounds - 1; Label b = new Label("The count value: "+count); Label c = new Label("Player: " + currentPlayer); Label g = new Label("Once you select your card, press the Submit button."); cards = printCards(currentPlayer); Label d = new Label(" Select your Card: "); TextField e = new TextField(); HBox f = new HBox(d,e); Button submit = new Button("Submit"); t = new VBox(b,c,cards,g,f,submit); //setting all text inside all the labels. b.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); c.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); d.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); e.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); submit.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); //set on action submit button. submit.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {res1(stage,previousPlayer2,currentPlayer2,e, count2, rounds2);}}); } //making the third borderPane for results. BorderPane third = new BorderPane(); third.setCenter(t); Scene three = new Scene(third, 1000,1000); stage.setScene(three); stage.show(); } //This method will help print out all cards. public HBox printCards(String currentPlayer) { HBox cards = null; String[] x = new String[4]; x = player3.printCards(currentPlayer); Label a = new Label(x[0] + " "+ x[1] + x[2] + " "+ x[3]); a.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: blue;"); cards = new HBox(a); return cards; } //Finalization Methods. public void finizi1(Stage stage) { VBox t = null; Queue<String> temp = new LinkedList<>(); temp = player3.findWinner(player3.rounds); if(temp.size() == 4) { Label a = new Label ("Darn a draw want to play again..."); Label b = new Label("then recompile the program again,"); Label c = new Label ("or do not waste my time."); t = new VBox(a,b,c); //seting all text labels. a.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); b.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); c.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); } else { Label a = new Label("The winner(s) of the game is/ are..."); Label b = new Label( "For all other players who lost..."); Label c = new Label( " I challange you to a game and if you beat me I will increase your score."); Label d = new Label( "What do you say,will you accepted my challenge?"); Label e = new Label( "To accept the dealers challenge type 1 for yes or 2 for no and click the Submit button."); Label space = new Label(); Label f = new Label("Your responds: "); TextField g = new TextField(); Button submit = new Button("Submit"); t = new VBox(a,b,c,d,e,space,f); //set on action submit. submit.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {}}); //setting all text labels. a.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); b.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); c.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); d.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); e.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); f.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); submit.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); } //making the third borderPane for results. BorderPane third = new BorderPane(); third.setCenter(t); Scene three = new Scene(third, 1000,1000); stage.setScene(three); stage.show(); } public void finizi2(Stage stage, TextField responds) { int x = Integer.parseInt(responds.getText()); VBox t = null; if(x == 2) { Label a = new Label( "To bad...\n" ); Label b = new Label( "It does not matter you were propably would of loose to me anyways."); Label c = new Label ( "HAHAHAHA!!!"); System.exit(0); t = new VBox(a,b,c); //setting all text labels a.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); b.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); c.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); } else { Label a = new Label( "Your such a fool to challenge me!"); Label b = new Label( "No matter I know I will win."); t = new VBox(a,b); //setting all text labels. a.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); b.setStyle("-fx-font-family: Edwardian Script ITC; -fx-font-size: 25pt; -fx-text-fill: black;"); // call the function for the third game. GamePlay3(stage); } //making the third borderPane for results. BorderPane third = new BorderPane(); third.setCenter(t); Scene three = new Scene(third, 1000,1000); stage.setScene(three); stage.show(); } //-----------------------End of GamePlay2 methods-------------------------------------------------------------------------------------- //-----------------------Methods for GamePlay3----------------------------------------------------------------------------------------- //This function will allow us to play Card Guess game. public void GamePlay3(Stage stage) { //The welcoming screen. Label x = new Label ( "Ok let me explain the game so a novice like you can under stand it easily."); Label y = new Label ("I have a regular deck of 52 cards."); Label z = new Label ("Your job is to picture one card, together not seperate, and I will try to guess your card."); Label a1 = new Label("To make things intresting, I have converted each card with a special value."); Label b = new Label("The values are: "); Label c = new Label ("2 through 10 will be the value shown on the card."); Label d = new Label ( " While A = 1, J = 11, Q = 12 and K = 13."); Label e = new Label("These values are none negotiable."); Label f = new Label ("So, choose your card and lets begin the game."); Label ty2 = new Label("Use the Submit button for your responds."); Label g = new Label(); //Make two useful buttons. Label ty = new Label("If you want to select a new game press the Home button."); Label ty1 = new Label("If you want to Exit the game press the Exit button."); Label begingame = new Label("Click the Start button to begin the game."); Label spacea = new Label(); VBox ty2a = new VBox(ty,ty1,begingame,spacea); VBox ted = new VBox(x,y,z,a1,b,c,d,e,f,ty2,g,ty2a);//combining the introduction sentances. Button start = new Button("Start"); Button Home2 = new Button("Home"); Button Exit2 = new Button("Exit"); HBox cre = new HBox(Home2,start,Exit2); //set on actions for all two buttons. start.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {gameThree( stage);}});; Home2.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {stage.setScene(scene);stage.show();}});; Exit2.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {System.exit(0);}});; //setting all text inside labels. x.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); y.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); z.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); b.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); c.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); d.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); e.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); f.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ty2.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); a1.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); start.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); Home2.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); Exit2.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); //Creating the BorderPane for this page. BorderPane fa2 = new BorderPane(); fa2.setTop(ted); fa2.setCenter(cre); Scene newTrade = new Scene(fa2,1000,1000); stage.setScene(newTrade); stage.show(); } //starting game three. public void gameThree(Stage stage) { VBox tm1 = null; //time to play the game. if (player.getLowerbound() != player.getCurrent()) { Label ask = new Label ("Is your card value greater then or less then/equal to "); Label ask2 = new Label ( player.getCurrent() + "?"); Label ask3 = new Label( "1) Type 1 for greater then."); Label ask4 = new Label ("2) Type 2 for less then/ equal to."); Label spaceab = new Label(); Label gamep = new Label("Type your responds here: "); TextField newtxt = new TextField(); Label click = new Label("Click the Enter Button to submit your respond."); HBox vb = new HBox(gamep, newtxt); Button xp = new Button("Enter"); tm1 = new VBox(ask,ask2,ask3,ask4,click,spaceab,vb,xp); //continuing until Lowerbound equal Current. xp.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {continousCall(stage, newtxt);}});; //setting all text inside labels ask.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ask2.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ask3.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ask4.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); gamep.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); click.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); xp.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); } //creating the playing scene. BorderPane two = new BorderPane(); two.setCenter(tm1); Scene nexx = new Scene(two,600,600); stage.setScene(nexx); stage.show(); } //These two Methods will call each other until Lowerbound equals Current. public void continousCall(Stage stage, TextField newtxt) { player.FindCard(newtxt.getText()); VBox tm1a = new VBox(); if (player.getLowerbound() != player.getCurrent()) { Label aska = new Label ("Is your card value greater then or less then/equal to "); Label ask2a = new Label ( player.getCurrent() + "?"); Label ask3a = new Label( "1) Type 1 for greater then."); Label ask4a = new Label ("2) Type 2 for less then/ equal to."); Label spaceab = new Label(); Label gamep = new Label("Type your responds here: "); TextField newtxta = new TextField(); Label clicka = new Label("Click the Enter Button to submit your respond."); HBox vba = new HBox(gamep, newtxta); Button xpa = new Button("Enter"); tm1a = new VBox(aska,ask2a,ask3a,ask4a,clicka,spaceab,vba,xpa); //set on action for xpa. xpa.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {continousCall2(stage, newtxta);}});; //setting for text inside label. aska.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ask2a.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ask3a.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ask4a.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); gamep.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); clicka.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); xpa.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); } else { //Requesting the color of the card will help find the suites. Label st1 = new Label( "I believe I got some idea what the card value is."); Label st2 = new Label( "But before I can give you my guess I need you to tell me the color of the card."); Label st3 = new Label( "Type 1 for red.\n Type 2 for black."); Label spa = new Label(); Label click2 = new Label("Click the Enter Button to submit your respond."); Label sp = new Label("Type your responds here: "); TextField ne = new TextField(); HBox tn = new HBox(sp,ne); Button xp2 = new Button("Enter"); tm1a = new VBox(st1,st2,st3,spa,click2,tn,xp2); xp2.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {Finalization(stage,ne,player.getUpperbound());}});; //setting for text inside label. st1.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); st2.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); st3.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); click2.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); sp.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); tm1a.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); } value = player.getUpperbound(); //making new borderPane. BorderPane twoa = new BorderPane(); twoa.setCenter(tm1a); twoa.setTop(new Label("Here")); Scene nexxa = new Scene(twoa,600,600); stage.setScene(nexxa); stage.show(); } public void continousCall2(Stage stage, TextField newtxt) { String s = newtxt.getText(); player.FindCard(s); VBox tm1a = null; if (player.getLowerbound() != player.getCurrent()) { Label ask = new Label ("Is your card value greater then or less then/equal to "); Label ask2 = new Label ( player.getCurrent() + "?"); Label ask3 = new Label( "1) Type 1 for greater then."); Label ask4 = new Label ("2) Type 2 for less then/ equal to."); Label spaceab = new Label(); Label gamep = new Label("Type your responds here: "); TextField newtxta = new TextField(); Label click = new Label("Click the Enter Button to submit your respond."); HBox vb = new HBox(gamep, newtxta); Button xp = new Button("Enter"); tm1a = new VBox(ask,ask2,ask3,ask4,click,spaceab,vb,xp); //setting xp button on action. xp.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {continousCall(stage, newtxt);}});; //setting text inside label. ask.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ask2.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ask3.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ask4.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); gamep.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); click.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); xp.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); } else { //Requesting the color of the card will help find the suites. Label st1 = new Label( "I believe I got some idea what the card value is."); Label st2 = new Label( "But before I can give you my guess I need you to tell me the color of the card."); Label st3 = new Label( "Type 1 for red.\n Type 2 for black."); Label spa = new Label(); Label click2 = new Label("Click the Enter Button to submit your respond."); Label sp = new Label("Type your responds here: "); TextField ne = new TextField(); HBox tn = new HBox(sp,ne); Button xp2 = new Button("Enter"); tm1a = new VBox(st1,st2,st3,spa,click2,tn,xp2); //set xp2 button on action. xp2.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {Finalization(stage,ne,player.getUpperbound());}});; //setting text inside all labels. st1.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); st2.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); st3.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); st3.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); sp.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); click2.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); xp2.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); } value = player.getUpperbound(); //making new borderPane. BorderPane twoa = new BorderPane(); twoa.setCenter(tm1a); Scene nexxa = new Scene(twoa,600,600); stage.setScene(nexxa); stage.show(); } //Finalization of 2 method results. public void Finalization(Stage stage,TextField reponds,int value) { //used to determine the suites depending on color. Pair<String, String> red = new Pair<>("Hearts","Spades"); Pair<String, String> black = new Pair<>("Diamond","Clubs"); VBox newt = null; String second; String res = reponds.getText(); if(res.equals("1")) { Label ta1 = new Label( "I am ready to give you my answer."); Label ta2 = new Label ("Your card is..."); Label ta3 = new Label(value+" "+red.getKey()); Label ta4 = new Label("If this is not your card allow me a second chance."); Label ta5 = new Label("To allow the dealer a second chance, type 1."); Label ta6 = new Label("If the dealer was correct type 0."); Label ta8 = new Label(); Label ta7 = new Label("Click the Enter Button to submit your respond."); Label ta8a = new Label("Type your responds here: "); TextField the = new TextField(); HBox ta9 = new HBox(ta8a,the); Button xp2 = new Button("Enter"); newt = new VBox(ta1,ta2,ta3,ta4,ta5,ta6,ta8,ta7,ta9,xp2); second = red.getValue(); //setting xp2 button set on action. xp2.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {Finalization2(stage,the,value,second);}});; //setting all text inside labels. ta1.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta2.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta3.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta4.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta5.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta6.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta8.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta7.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta8a.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); xp2.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); } else if(res.equals("2")) { Label ta1 = new Label( "I am ready to give you my answer."); Label ta2 = new Label ("Your card is..."); Label ta3 = new Label(value+" "+black.getKey()); Label ta4 = new Label("If this is not your card allow me a second chance."); Label ta5 = new Label("To allow the dealer a second chance, type 1."); Label ta6 = new Label("If the dealer was correct type 0."); Label ta8 = new Label(); Label ta7 = new Label("Click the Enter Button to submit your respond."); Label ta8a = new Label("Type your responds here: "); TextField the = new TextField(); HBox ta9 = new HBox(ta8a,the); Button xp2 = new Button("Enter"); newt = new VBox(ta1,ta2,ta3,ta4,ta5,ta6,ta8,ta7,ta9,xp2); second = black.getValue(); //xp2 button set on action. xp2.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {Finalization2(stage,the,value,second);}});; //setting all text inside labels. ta1.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta2.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta3.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta4.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta5.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta6.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta8.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta7.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); ta8a.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); xp2.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); } //BorderPane and Scene creation. BorderPane twoa = new BorderPane(); twoa.setCenter(newt); Scene nexxa = new Scene(twoa,600,600); stage.setScene(nexxa); stage.show(); } public void Finalization2(Stage stage,TextField reponds,int value,String second) { String z = reponds.getText(); VBox end = null; //depending on the player(s) respond will determine the ending cout statements. if (z.equals("1")) { Label f1 = new Label( "I am ready to try again."); Label f2 = new Label( "Your card is..."); Label f3 = new Label(value + " " + second); Label f4 = new Label( "If it is not your card then you must of made a mistake."); Label f5 = new Label( "Therefore, I win this round." + "See I knew you where all a bunch of loser(s)."); Label space1 = new Label(); end = new VBox(f1,f2,f3,f4,f5,space1); //setting a text inside labels. f1.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); f2.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); f3.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); f4.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); f5.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); } else if (z.equals( "0")) { Label f6 = new Label("So, let me see if I got this straight."); Label f7 = new Label("You are pathetic to allow a dealer like myslef to beat you so easily."); Label f8 = new Label( "I do not associate with loosers."+"So, get lost looser!!!"); Label space2 = new Label(); end = new VBox(f6,f7,f8,space2); //setting a text inside labels. f6.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); f7.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); f8.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); } else { Label f9 = new Label("So, you beat me, big deal."); Label f10 = new Label ("Your still a loser and I do not associate with losers."); Label f11 = new Label("Get lost you bunch of loser(s)."); Label space3 = new Label(); end = new VBox(f9,f10,f11,space3); //setting a text inside labels f9.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); f10.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); f11.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); } //request the user either choose another game by pressing the home button or leaving with the exit button. Label f12 = new Label("Click the Home button to choose another game or the Exit button to exit the program."); Label f13 = new Label(); Button a1 = new Button("Home"); Button a2 = new Button("Exit"); HBox line = new HBox(a1,a2); VBox t = new VBox(end,f12,f13,line); //setting up the home and exit button. a1.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {stage.setScene(scene);stage.show();}});; a2.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent a) {System.exit(0);}});; //setting all remaining text labels. f12.setStyle("-fx-font-family: Arial Black; -fx-font-size: 15pt; -fx-text-fill: black;"); a1.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: red;"); a2.setStyle("-fx-font-family: Times New Roman; -fx-font-size: 25pt; -fx-text-fill: blue;"); //BorderPane and Scene creation. BorderPane twoa = new BorderPane(); twoa.setCenter(t); Scene nexxa = new Scene(twoa,600,600); stage.setScene(nexxa); stage.show(); } }
package cn.smallclover.reflect.example_1; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class Main implements OnClickListener{ private Button button = new Button(); public Main() throws Exception { // init(); init2(); } public void click() { System.out.println("Button clicked"); } @Override public void onClick() { click(); } public void init() throws Exception { OnClickListenerHandler h = new OnClickListenerHandler(this); /* Method method = Main.class.getMethod("click", null); Method method = Main.class.getMethod("onClick", null); h.addMethod("onClick", method);*/ /* OnClickListener clickProxy = (OnClickListener) Proxy.newProxyInstance(OnClickListener.class.getClassLoader(), new Class[] { OnClickListener.class }, h);*/ OnClickListener clickProxy = (OnClickListener) Proxy.newProxyInstance(Main.class.getClassLoader(), Main.class.getInterfaces(), h); /* Method clickMethod = button.getClass().getMethod("setOnClickListener", OnClickListener.class); clickMethod.invoke(button, clickProxy); clickProxy.onClick();*/ clickProxy.onClick(); } public void init2() throws NoSuchMethodException, SecurityException{ OnClickListenerHandler h = new OnClickListenerHandler(this); Method method = Main.class.getMethod("click", null); h.addMethod("onClick", method); OnClickListener clickProxy = (OnClickListener) Proxy.newProxyInstance(OnClickListener.class.getClassLoader(), OnClickListener.class.getInterfaces(), h); } public static void main(String[] args) throws Exception { Main main = new Main(); // main.button.click(); } }
package com.koshcheyev.quadrangle.observer; import com.koshcheyev.quadrangle.entity.Quadrangle; /** * Created by Andrew on 21.03.2017. */ public interface QuadrangleObserver { void updateData(Quadrangle o); }
package com.example.hyperlocal; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class HyperlocalApplication implements AsyncConfigurer{ public static void main(String[] args) { SpringApplication.run(HyperlocalApplication.class, args); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.restrictions.validator; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.cms2.model.restrictions.CMSTimeRestrictionModel; import de.hybris.platform.cmsfacades.constants.CmsfacadesConstants; import de.hybris.platform.cmsfacades.data.TimeRestrictionData; import de.hybris.platform.cmsfacades.dto.UpdateRestrictionValidationDto; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; @UnitTest @RunWith(MockitoJUnitRunner.class) public class UpdateTimeRestrictionTest { private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-M-dd hh:mm:ss"); @InjectMocks private UpdateTimeRestrictionValidator validator; private Errors errors; private UpdateRestrictionValidationDto validationDto; private TimeRestrictionData data; @Test public void shouldPassValidationForUpdateTimeRestriction() throws ParseException { final Date activeFrom = simpleDateFormat.parse("2016-01-01 00:00:00"); final Date activeUntil = simpleDateFormat.parse("2016-12-31 00:00:00"); data = new TimeRestrictionData(); data.setActiveFrom(activeFrom); data.setActiveUntil(activeUntil); errors = new BeanPropertyBindingResult(data, data.getClass().getSimpleName()); validationDto = new UpdateRestrictionValidationDto(); validationDto.setRestriction(data); validator.validate(validationDto, errors); assertThat(errors.getAllErrors(), empty()); } @Test public void shouldFailActiveFrom_ActiveUntil_RequiredFields() throws ParseException { data = new TimeRestrictionData(); errors = new BeanPropertyBindingResult(data, data.getClass().getSimpleName()); validationDto = new UpdateRestrictionValidationDto(); validationDto.setRestriction(data); validator.validate(validationDto, errors); final List<ObjectError> errorList = errors.getAllErrors(); assertThat(errors.getErrorCount(), equalTo(2)); assertThat(((FieldError) errorList.get(0)).getField(), equalTo(CMSTimeRestrictionModel.ACTIVEFROM)); assertThat((errorList.get(0)).getCode(), equalTo(CmsfacadesConstants.FIELD_REQUIRED)); assertThat(((FieldError) errorList.get(1)).getField(), equalTo(CMSTimeRestrictionModel.ACTIVEUNTIL)); assertThat((errorList.get(1)).getCode(), equalTo(CmsfacadesConstants.FIELD_REQUIRED)); } @Test public void shouldFailInvalidDateRange_BeforeDateGreaterThanAfterDate() throws ParseException { final Date activeFrom = simpleDateFormat.parse("2016-01-01 24:00:00"); final Date activeUntil = simpleDateFormat.parse("2016-01-01 00:00:00"); data = new TimeRestrictionData(); data.setActiveFrom(activeFrom); data.setActiveUntil(activeUntil); errors = new BeanPropertyBindingResult(data, data.getClass().getSimpleName()); validationDto = new UpdateRestrictionValidationDto(); validationDto.setRestriction(data); validator.validate(validationDto, errors); final List<ObjectError> errorList = errors.getAllErrors(); assertThat(errors.getErrorCount(), equalTo(1)); assertThat(((FieldError) errorList.get(0)).getField(), equalTo(CMSTimeRestrictionModel.ACTIVEUNTIL)); assertThat((errorList.get(0)).getCode(), equalTo(CmsfacadesConstants.INVALID_DATE_RANGE)); } @Test public void shouldFailInvalidDateRange_SameDate() throws ParseException { final Date activeFrom = simpleDateFormat.parse("2016-01-01 24:00:00"); final Date activeUntil = simpleDateFormat.parse("2016-01-01 20:00:00"); data = new TimeRestrictionData(); data.setActiveFrom(activeFrom); data.setActiveUntil(activeUntil); errors = new BeanPropertyBindingResult(data, data.getClass().getSimpleName()); validationDto = new UpdateRestrictionValidationDto(); validationDto.setRestriction(data); validator.validate(validationDto, errors); final List<ObjectError> errorList = errors.getAllErrors(); assertThat(errors.getErrorCount(), equalTo(1)); assertThat(((FieldError) errorList.get(0)).getField(), equalTo(CMSTimeRestrictionModel.ACTIVEUNTIL)); assertThat((errorList.get(0)).getCode(), equalTo(CmsfacadesConstants.INVALID_DATE_RANGE)); } }
package com.cs4125.bookingapp.ui.main; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.SavedStateHandle; import androidx.lifecycle.ViewModel; import com.cs4125.bookingapp.entities.User; import com.cs4125.bookingapp.repositories.BookingRepositoryImpl; import com.cs4125.bookingapp.repositories.ResultCallback; import com.cs4125.bookingapp.repositories.UserRepository; import com.cs4125.bookingapp.repositories.UserRepositoryImpl; import okhttp3.ResponseBody; public class LoginViewModel extends ViewModel { private UserRepository repository; private SavedStateHandle state; public LoginViewModel(SavedStateHandle savedStateHandle) { state = savedStateHandle; } public void init() { if(state.contains("user_repository")) { this.repository = state.get("user_repository"); } else { this.repository = new UserRepositoryImpl(); state.set("user_repository", this.repository); } } public LiveData<String> login(User user){ MutableLiveData<String> liveString = new MutableLiveData<>(); repository.loginUser(user, new ResultCallback() { @Override public void onResult(String result) { liveString.postValue(result); } @Override public void onFailure(Throwable error) { liveString.postValue(error.toString()); } }); return liveString; } }
package StringProcessing; /** * A method 'substring()' is used to extract sub-string from the string. * * @author Bohdan Skrypnyk */ public class StringPlace { public static void main(String args[]) { String str = "This is a test. This is, too"; String search = "is"; String substr = "was"; String result = ""; int i; do { // change all matched strings System.out.println(str); // get the index of the searched string // if the search string was not found, return -1 i = str.indexOf(search); if (i != -1) { // add to result, a substring before the search string result = str.substring(0, i); // add defined substring to result result += substr; // add to result a substring which is starting on the searched string // and going to the end of the string result += str.substring(i + search.length()); // rewrite original string str = result; } } while (i != -1); // if there is no search string will end loop } }
package com.eduardozanela.service; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import com.eduardozanela.dto.AwardsDTO; import com.eduardozanela.dto.AwardsWinnersDTO; import com.eduardozanela.dto.ResponseDTO; import com.eduardozanela.entity.AwardsEntity; import com.eduardozanela.repository.AwardsRepository; @Service public class AwardsService { private final String YES = "yes"; @Autowired private AwardsRepository repo; @Autowired private ModelMapper mapper; public ResponseEntity<ResponseDTO> filterAwards(){ List<AwardsEntity> awardsEntities = repo.findByWinner(YES); List<AwardsEntity> entityList = awardsEntities.stream().sorted(Comparator.comparingInt(AwardsEntity::getYear)).collect(Collectors.toList()); Map<String, List<AwardsEntity>> group = new HashMap<>(); for(AwardsEntity e : entityList) { for(String p : e.getProducers()) { if(group.containsKey(p)){ group.get(p).add(e); } else { ArrayList<AwardsEntity> list = new ArrayList<>(); list.add(e); group.put(p, list); } } } group = group.entrySet().stream() .filter(x -> x.getValue().size() > 1) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return calculateDiffBetweenAwards(group); } private ResponseEntity<ResponseDTO> calculateDiffBetweenAwards(Map<String, List<AwardsEntity>> map){ AwardsWinnersDTO max = new AwardsWinnersDTO(); AwardsWinnersDTO min = new AwardsWinnersDTO(); Integer maxYear = 0; Integer minYear = null; for(String key : map.keySet()) { List<AwardsEntity> awards = map.get(key); for (int i = 0; i < awards.size() - 1; i++) { if ((awards.get(i + 1).getYear() - awards.get(i).getYear()) > maxYear) { maxYear = (awards.get(i + 1).getYear() - awards.get(i).getYear()); max = new AwardsWinnersDTO(key, maxYear, awards.get(i).getYear(), awards.get(i + 1).getYear()); } if (minYear == null || (awards.get(i + 1).getYear() - awards.get(i).getYear()) < minYear) { minYear = (awards.get(i + 1).getYear() - awards.get(i).getYear()); min = new AwardsWinnersDTO(key, minYear, awards.get(i).getYear(), awards.get(i + 1).getYear()); } } } ResponseDTO responseDTO = new ResponseDTO(); responseDTO.getMax().add(max); responseDTO.getMin().add(min); return ResponseEntity.ok().body(responseDTO); } public ResponseEntity<List<AwardsDTO>> getAllAwards() { List<AwardsDTO> winners = new ArrayList<>(); repo.findAll().stream().forEach(a -> winners.add(mapper.map(a, AwardsDTO.class))); return ResponseEntity.ok().body(winners); } public ResponseEntity<AwardsDTO> findAwardsById(Integer id) { Optional<AwardsEntity> findById = repo.findById(id); if(findById.isPresent()) { return ResponseEntity.ok().body(mapper.map(findById.get(), AwardsDTO.class)); } return ResponseEntity.notFound().build(); } }
package br.com.fiap.model.entidades; import java.util.ArrayList; import java.util.List; public class GrupoInteresse { List<String> interesse = new ArrayList<>(); }
package com.hcl.dmu.demand.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "dmu_skill") public class SkillsEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "primary_skill") private String primarySkill; @Column(name = "secondary_skill") private String secondarySkill; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPrimarySkill() { return primarySkill; } public void setPrimarySkill(String primarySkill) { this.primarySkill = primarySkill; } public String getSecondarySkill() { return secondarySkill; } public void setSecondarySkill(String secondarySkill) { this.secondarySkill = secondarySkill; } @Override public String toString() { return "SkillsEntity [id=" + id + ", primarySkill=" + primarySkill + ", SecondarySkill=" + secondarySkill + "]"; } }
package com.linsr.mvpdemo; /** * Description * * @author linsenrong on 2018/3/12 10:59 */ public interface BaseView<T> { void setPresenter(T presenter); }
package com.ai.slp.order.dao.mapper.bo; import java.sql.Timestamp; public class OrdOdProd { private long prodDetalId; private String tenantId; private long orderId; private String prodType; private long supplierId; private String sellerId; private String prodId; private String prodName; private String prodSn; private String skuId; private String standardProdId; private String supplyId; private String storageId; private String routeId; private Timestamp validTime; private Timestamp invalidTime; private String state; private long buySum; private long salePrice; private long costPrice; private long totalFee; private long discountFee; private long operDiscountFee; private String operDiscountDesc; private long adjustFee; private long jf; private String prodDesc; private String extendInfo; private Timestamp updateTime; private String updateChlId; private String updateOperId; private String skuStorageId; private String isInvoice; private long couponFee; private long jfFee; private String cusServiceFlag; public long getProdDetalId() { return prodDetalId; } public void setProdDetalId(long prodDetalId) { this.prodDetalId = prodDetalId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId == null ? null : tenantId.trim(); } public long getOrderId() { return orderId; } public void setOrderId(long orderId) { this.orderId = orderId; } public String getProdType() { return prodType; } public void setProdType(String prodType) { this.prodType = prodType == null ? null : prodType.trim(); } public long getSupplierId() { return supplierId; } public void setSupplierId(long supplierId) { this.supplierId = supplierId; } public String getSellerId() { return sellerId; } public void setSellerId(String sellerId) { this.sellerId = sellerId == null ? null : sellerId.trim(); } public String getProdId() { return prodId; } public void setProdId(String prodId) { this.prodId = prodId == null ? null : prodId.trim(); } public String getProdName() { return prodName; } public void setProdName(String prodName) { this.prodName = prodName == null ? null : prodName.trim(); } public String getProdSn() { return prodSn; } public void setProdSn(String prodSn) { this.prodSn = prodSn == null ? null : prodSn.trim(); } public String getSkuId() { return skuId; } public void setSkuId(String skuId) { this.skuId = skuId == null ? null : skuId.trim(); } public String getStandardProdId() { return standardProdId; } public void setStandardProdId(String standardProdId) { this.standardProdId = standardProdId == null ? null : standardProdId.trim(); } public String getSupplyId() { return supplyId; } public void setSupplyId(String supplyId) { this.supplyId = supplyId == null ? null : supplyId.trim(); } public String getStorageId() { return storageId; } public void setStorageId(String storageId) { this.storageId = storageId == null ? null : storageId.trim(); } public String getRouteId() { return routeId; } public void setRouteId(String routeId) { this.routeId = routeId == null ? null : routeId.trim(); } public Timestamp getValidTime() { return validTime; } public void setValidTime(Timestamp validTime) { this.validTime = validTime; } public Timestamp getInvalidTime() { return invalidTime; } public void setInvalidTime(Timestamp invalidTime) { this.invalidTime = invalidTime; } public String getState() { return state; } public void setState(String state) { this.state = state == null ? null : state.trim(); } public long getBuySum() { return buySum; } public void setBuySum(long buySum) { this.buySum = buySum; } public long getSalePrice() { return salePrice; } public void setSalePrice(long salePrice) { this.salePrice = salePrice; } public long getCostPrice() { return costPrice; } public void setCostPrice(long costPrice) { this.costPrice = costPrice; } public long getTotalFee() { return totalFee; } public void setTotalFee(long totalFee) { this.totalFee = totalFee; } public long getDiscountFee() { return discountFee; } public void setDiscountFee(long discountFee) { this.discountFee = discountFee; } public long getOperDiscountFee() { return operDiscountFee; } public void setOperDiscountFee(long operDiscountFee) { this.operDiscountFee = operDiscountFee; } public String getOperDiscountDesc() { return operDiscountDesc; } public void setOperDiscountDesc(String operDiscountDesc) { this.operDiscountDesc = operDiscountDesc == null ? null : operDiscountDesc.trim(); } public long getAdjustFee() { return adjustFee; } public void setAdjustFee(long adjustFee) { this.adjustFee = adjustFee; } public long getJf() { return jf; } public void setJf(long jf) { this.jf = jf; } public String getProdDesc() { return prodDesc; } public void setProdDesc(String prodDesc) { this.prodDesc = prodDesc == null ? null : prodDesc.trim(); } public String getExtendInfo() { return extendInfo; } public void setExtendInfo(String extendInfo) { this.extendInfo = extendInfo == null ? null : extendInfo.trim(); } public Timestamp getUpdateTime() { return updateTime; } public void setUpdateTime(Timestamp updateTime) { this.updateTime = updateTime; } public String getUpdateChlId() { return updateChlId; } public void setUpdateChlId(String updateChlId) { this.updateChlId = updateChlId == null ? null : updateChlId.trim(); } public String getUpdateOperId() { return updateOperId; } public void setUpdateOperId(String updateOperId) { this.updateOperId = updateOperId == null ? null : updateOperId.trim(); } public String getSkuStorageId() { return skuStorageId; } public void setSkuStorageId(String skuStorageId) { this.skuStorageId = skuStorageId == null ? null : skuStorageId.trim(); } public String getIsInvoice() { return isInvoice; } public void setIsInvoice(String isInvoice) { this.isInvoice = isInvoice == null ? null : isInvoice.trim(); } public long getCouponFee() { return couponFee; } public void setCouponFee(long couponFee) { this.couponFee = couponFee; } public long getJfFee() { return jfFee; } public void setJfFee(long jfFee) { this.jfFee = jfFee; } public String getCusServiceFlag() { return cusServiceFlag; } public void setCusServiceFlag(String cusServiceFlag) { this.cusServiceFlag = cusServiceFlag == null ? null : cusServiceFlag.trim(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (adjustFee ^ (adjustFee >>> 32)); result = prime * result + (int) (buySum ^ (buySum >>> 32)); result = prime * result + (int) (costPrice ^ (costPrice >>> 32)); result = prime * result + (int) (couponFee ^ (couponFee >>> 32)); result = prime * result + ((cusServiceFlag == null) ? 0 : cusServiceFlag.hashCode()); result = prime * result + (int) (discountFee ^ (discountFee >>> 32)); result = prime * result + ((extendInfo == null) ? 0 : extendInfo.hashCode()); result = prime * result + ((invalidTime == null) ? 0 : invalidTime.hashCode()); result = prime * result + ((isInvoice == null) ? 0 : isInvoice.hashCode()); result = prime * result + (int) (jf ^ (jf >>> 32)); result = prime * result + (int) (jfFee ^ (jfFee >>> 32)); result = prime * result + ((operDiscountDesc == null) ? 0 : operDiscountDesc.hashCode()); result = prime * result + (int) (operDiscountFee ^ (operDiscountFee >>> 32)); result = prime * result + (int) (orderId ^ (orderId >>> 32)); result = prime * result + ((prodDesc == null) ? 0 : prodDesc.hashCode()); result = prime * result + (int) (prodDetalId ^ (prodDetalId >>> 32)); result = prime * result + ((prodId == null) ? 0 : prodId.hashCode()); result = prime * result + ((prodName == null) ? 0 : prodName.hashCode()); result = prime * result + ((prodSn == null) ? 0 : prodSn.hashCode()); result = prime * result + ((prodType == null) ? 0 : prodType.hashCode()); result = prime * result + ((routeId == null) ? 0 : routeId.hashCode()); result = prime * result + (int) (salePrice ^ (salePrice >>> 32)); result = prime * result + ((sellerId == null) ? 0 : sellerId.hashCode()); result = prime * result + ((skuId == null) ? 0 : skuId.hashCode()); result = prime * result + ((skuStorageId == null) ? 0 : skuStorageId.hashCode()); result = prime * result + ((standardProdId == null) ? 0 : standardProdId.hashCode()); result = prime * result + ((state == null) ? 0 : state.hashCode()); result = prime * result + ((storageId == null) ? 0 : storageId.hashCode()); result = prime * result + (int) (supplierId ^ (supplierId >>> 32)); result = prime * result + ((supplyId == null) ? 0 : supplyId.hashCode()); result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode()); result = prime * result + (int) (totalFee ^ (totalFee >>> 32)); result = prime * result + ((updateChlId == null) ? 0 : updateChlId.hashCode()); result = prime * result + ((updateOperId == null) ? 0 : updateOperId.hashCode()); result = prime * result + ((updateTime == null) ? 0 : updateTime.hashCode()); result = prime * result + ((validTime == null) ? 0 : validTime.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OrdOdProd other = (OrdOdProd) obj; if (adjustFee != other.adjustFee) return false; if (buySum != other.buySum) return false; if (costPrice != other.costPrice) return false; if (couponFee != other.couponFee) return false; if (cusServiceFlag == null) { if (other.cusServiceFlag != null) return false; } else if (!cusServiceFlag.equals(other.cusServiceFlag)) return false; if (discountFee != other.discountFee) return false; if (extendInfo == null) { if (other.extendInfo != null) return false; } else if (!extendInfo.equals(other.extendInfo)) return false; if (invalidTime == null) { if (other.invalidTime != null) return false; } else if (!invalidTime.equals(other.invalidTime)) return false; if (isInvoice == null) { if (other.isInvoice != null) return false; } else if (!isInvoice.equals(other.isInvoice)) return false; if (jf != other.jf) return false; if (jfFee != other.jfFee) return false; if (operDiscountDesc == null) { if (other.operDiscountDesc != null) return false; } else if (!operDiscountDesc.equals(other.operDiscountDesc)) return false; if (operDiscountFee != other.operDiscountFee) return false; if (orderId != other.orderId) return false; if (prodDesc == null) { if (other.prodDesc != null) return false; } else if (!prodDesc.equals(other.prodDesc)) return false; if (prodDetalId != other.prodDetalId) return false; if (prodId == null) { if (other.prodId != null) return false; } else if (!prodId.equals(other.prodId)) return false; if (prodName == null) { if (other.prodName != null) return false; } else if (!prodName.equals(other.prodName)) return false; if (prodSn == null) { if (other.prodSn != null) return false; } else if (!prodSn.equals(other.prodSn)) return false; if (prodType == null) { if (other.prodType != null) return false; } else if (!prodType.equals(other.prodType)) return false; if (routeId == null) { if (other.routeId != null) return false; } else if (!routeId.equals(other.routeId)) return false; if (salePrice != other.salePrice) return false; if (sellerId == null) { if (other.sellerId != null) return false; } else if (!sellerId.equals(other.sellerId)) return false; if (skuId == null) { if (other.skuId != null) return false; } else if (!skuId.equals(other.skuId)) return false; if (skuStorageId == null) { if (other.skuStorageId != null) return false; } else if (!skuStorageId.equals(other.skuStorageId)) return false; if (standardProdId == null) { if (other.standardProdId != null) return false; } else if (!standardProdId.equals(other.standardProdId)) return false; if (state == null) { if (other.state != null) return false; } else if (!state.equals(other.state)) return false; if (storageId == null) { if (other.storageId != null) return false; } else if (!storageId.equals(other.storageId)) return false; if (supplierId != other.supplierId) return false; if (supplyId == null) { if (other.supplyId != null) return false; } else if (!supplyId.equals(other.supplyId)) return false; if (tenantId == null) { if (other.tenantId != null) return false; } else if (!tenantId.equals(other.tenantId)) return false; if (totalFee != other.totalFee) return false; if (updateChlId == null) { if (other.updateChlId != null) return false; } else if (!updateChlId.equals(other.updateChlId)) return false; if (updateOperId == null) { if (other.updateOperId != null) return false; } else if (!updateOperId.equals(other.updateOperId)) return false; if (updateTime == null) { if (other.updateTime != null) return false; } else if (!updateTime.equals(other.updateTime)) return false; if (validTime == null) { if (other.validTime != null) return false; } else if (!validTime.equals(other.validTime)) return false; return true; } }
/* * Copyright ApeHat.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.apehat.newyear.validation.annotation; import java.lang.annotation.*; /** * The annotation {@code NonNull} be annotated to method and parameter, to * validate the return value of method (or the incoming parameter) isn't null. * <p> * If this be annotated to method, and method return null value, will throw * {@link AssertionError}. If the return type statement of method is * void, this annotation will be ignore. * <p> * Or, if this be annotated to parameter, after method (or constructor) be * invoked, will validate be annotated parameters, at first. If there are * null, will throw {@link IllegalArgumentException} * * @author hanpengfei * @since 1.0 */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD}) public @interface NonNull { }
package com.swatcat.testfirebasepushesapp; import android.content.Intent; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; /** * Created by max_ermakov on 2/17/17. */ public class FireIDService extends FirebaseInstanceIdService { @Override public void onTokenRefresh() { String tkn = FirebaseInstanceId.getInstance().getToken(); Log.d("Not","Token ["+tkn+"]"); Intent intent = new Intent(this,MainActivity.class); intent.putExtra(MainActivity.FIREBASE_TOKEN,tkn); startActivity(intent); } }
package com.rlbas; public class Fibinoici { public static void main(String[] args) { int n1 = 0,n2 = 1, n3, count = 10, i; System.out.print(n1+ " " +n2); for (i=0; i<count ; ++i ) { n3 = n1+n2; System.out.print(" "+n3); n1 = n2; n2 = n3; } } }
package com.joyfulmath.calculator.houseloan; import java.util.ArrayList; import com.joyfulmath.calculator.R; import com.joyfulmath.calculator.Engine.CaculaterEngine.EngineResultParam; import com.joyfulmath.calculator.Engine.GeneralEngineType.MonthLoanResult; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class RealResultAdapter extends BaseAdapter { private static final String TAG = "SuperCalculater.RealResultAdapter"; private EngineResultParam mEngineResult = null; ArrayList<MonthLoanResult> result = null; private Context mContext = null; public RealResultAdapter(EngineResultParam param, Context context) { mContext = context; setResult(param); } public void setResult(EngineResultParam param) { mEngineResult = param; if (mEngineResult != null) { result = mEngineResult.result; } else { result = new ArrayList<MonthLoanResult>(); result.clear(); } Log.i(TAG, "[setResult]:result size:" + result.size()); } @Override public int getCount() { // Log.i(TAG, "getCount"); // TODO Auto-generated method stub return result.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub // Log.i(TAG, "getItem"); return result.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub // Log.i(TAG, "getItemId"); return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub // Log.i(TAG, "[getView]:" + position); ViewHolder viewHolder = null; MonthLoanResult monthResult = result.get(position); if (convertView == null) { viewHolder = new ViewHolder(); convertView = LayoutInflater.from(mContext).inflate( R.layout.layout_re_result_list_item, null); viewHolder.indexView = (TextView) convertView .findViewById(R.id.result_item_index); viewHolder.interestView = (TextView) convertView .findViewById(R.id.result_item_interest); viewHolder.captialView = (TextView) convertView .findViewById(R.id.result_item_captial); viewHolder.returnView = (TextView) convertView .findViewById(R.id.result_item_return); viewHolder.remainView = (TextView) convertView .findViewById(R.id.result_item_remain); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.indexView.setText(String.valueOf(position)); viewHolder.returnView.setText(String.valueOf(monthResult.mReturn)); viewHolder.interestView.setText(String.valueOf(monthResult.mInterest)); viewHolder.captialView.setText(String.valueOf(monthResult.mReturnCaptial)); viewHolder.remainView.setText(String.valueOf(monthResult.mLastCaptial)); return convertView; } private class ViewHolder { TextView indexView; TextView interestView; TextView captialView; TextView returnView; TextView remainView; } }
package vetores.exemplos; import java.util.Scanner; public class Exemplo1{ public static void main (String[] args){ Scanner entrada = new Scanner(System.in); String[] arrayNome = new String[5]; int i = 0; while(i<5){ System.out.println("Digite um nome: "); arrayNome[i] = entrada.next(); i++; } for(i=0;i<5;i++){ System.out.println("O nome " + (i+1) + " captado foi " + arrayNome[i]); } entrada.close(); } }
package code; import java.util.ArrayList; //This method takes in the the current turn number (starts at zero and increments with each commit), //(curTurn), then does a println of the current player, by dividing the curTurn by the //number of players (passed in as playerNumber) and utilizing the remainder public class PlayerDisplay { public PlayerDisplay(int curTurn, int playerNumber, ArrayList<String> playerNames) { switch(playerNumber){ case 2: if(curTurn % 2 == 0){ System.out.println("It is "+playerNames.get(0)+"'s turn"); } else{ System.out.println("It is "+playerNames.get(1)+"'s turn"); } break; case 3: if(curTurn % 3 == 0){ System.out.println("It is "+playerNames.get(0)+"'s turn"); } else if(curTurn %3 == 1){ System.out.println("It is "+playerNames.get(1)+"'s turn"); } else{ System.out.println("It is "+playerNames.get(2)+"'s turn"); } break; case 4: if(curTurn % 4 == 0){ System.out.println("It is "+playerNames.get(0)+"'s turn"); } else if(curTurn %4 == 1){ System.out.println("It is "+playerNames.get(1)+"'s turn"); } else if(curTurn%4 == 2){ System.out.println("It's "+playerNames.get(2)+"'s turn"); } else{ System.out.println("It is "+playerNames.get(3)+"'s turn"); } break; case 5: if(curTurn % 5 == 0){ System.out.println("It is "+playerNames.get(0)+"'s turn"); } else if(curTurn %5 == 1){ System.out.println("It is "+playerNames.get(1)+"'s turn"); } else if(curTurn%5 == 2){ System.out.println("It's "+playerNames.get(2)+"'s turn"); } else if(curTurn%5 == 3){ System.out.println("It's "+playerNames.get(3)+"'s turn"); } else{ System.out.println("It is "+playerNames.get(4)+"'s turn"); } break; case 6: if(curTurn % 6 == 0){ System.out.println("It is "+playerNames.get(0)+"'s turn"); } else if(curTurn %6 == 1){ System.out.println("It is "+playerNames.get(1)+"'s turn"); } else if(curTurn%6 == 2){ System.out.println("It's "+playerNames.get(2)+"'s turn"); } else if(curTurn%6 == 3){ System.out.println("It's "+playerNames.get(3)+"'s turn"); } else if(curTurn%6 == 4){ System.out.println("It's "+playerNames.get(4)+"'s turn"); } else{ System.out.println("It is "+playerNames.get(5)+"'s turn"); } break; case 7: if(curTurn % 7 == 0){ System.out.println("It is "+playerNames.get(0)+"'s turn"); } else if(curTurn %7 == 1){ System.out.println("It is "+playerNames.get(1)+"'s turn"); } else if(curTurn%7 == 2){ System.out.println("It's "+playerNames.get(2)+"'s turn"); } else if(curTurn%7 == 3){ System.out.println("It's "+playerNames.get(3)+"'s turn"); } else if(curTurn%7 == 4){ System.out.println("It's "+playerNames.get(4)+"'s turn"); } else if(curTurn%7 == 5){ System.out.println("It's "+playerNames.get(5)+"'s turn"); } else{ System.out.println("It is "+playerNames.get(6)+"'s turn"); } break; case 8: if(curTurn % 8 == 0){ System.out.println("It is "+playerNames.get(0)+"'s turn"); } else if(curTurn %8 == 1){ System.out.println("It is "+playerNames.get(1)+"'s turn"); } else if(curTurn%8 == 2){ System.out.println("It's "+playerNames.get(2)+"'s turn"); } else if(curTurn%8 == 3){ System.out.println("It's "+playerNames.get(3)+"'s turn"); } else if(curTurn%8 == 4){ System.out.println("It's "+playerNames.get(4)+"'s turn"); } else if(curTurn%8 == 5){ System.out.println("It's "+playerNames.get(5)+"'s turn"); } else if(curTurn%8 == 6){ System.out.println("It's "+playerNames.get(6)+"'s turn"); } else{ System.out.println("It is "+playerNames.get(7)+"'s turn"); } break; } } }
package Interface; public class HistoriqueObjet { private String etat_objet; private String nom_objet; private String droit_acces; private String date_action; private String type_operation; private String special; public HistoriqueObjet(String etat_objet,String nom_objet,String droit_acces, String date_action, String type_operation, String special){ this.etat_objet = etat_objet; this.nom_objet = nom_objet; this.droit_acces= droit_acces; this.date_action = date_action; this.type_operation= type_operation; this.special = special; } public String getEtat_objet() { return etat_objet; } public void setEtat_objet(String etat_objet) { this.etat_objet = etat_objet; } public String getNom_objet() { return nom_objet; } public void setNom_objet(String nom_objet) { this.nom_objet = nom_objet; } public String getDroit_acces() { return droit_acces; } public void setDroit_acces(String droit_acces) { this.droit_acces = droit_acces; } public String getDate_action() { return date_action; } public void setDate_action(String date_action) { this.date_action = date_action; } public String getType_operation() { return type_operation; } public void setType_operation(String type_operation) { this.type_operation = type_operation; } public String getSpecial() { return special; } public void setSpecial(String special) { this.special = special; } @Override public String toString() { return "HistoriqueObjet{" + "etat_objet='" + etat_objet + '\'' + ", nom_objet='" + nom_objet + '\'' + ", droit_acces='" + droit_acces + '\'' + ", date_action='" + date_action + '\'' + ", type_operation='" + type_operation + '\'' + ", special='" + special + '\'' + '}'; } }
package com.jim.multipos.ui.reports.product_profit; import com.github.mjdev.libaums.fs.UsbFile; import com.jim.multipos.core.BaseTableReportPresenter; public interface ProductProfitPresenter extends BaseTableReportPresenter { void filterConfigsChanged(int configs); void exportExcel(String fileName, String path); void exportPdf(String fileName, String path); void exportExcelToUSB(String filename, UsbFile root); void exportPdfToUSB(String filename, UsbFile root); void onBarcodeReaded(String barcode); void onActionClicked(Object[][] objects, int row, int column); }
package org.gnunet.integration.fs; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.gnunet.integration.internal.util.Counter; import akka.actor.UntypedActor; import akka.event.Logging; import akka.event.LoggingAdapter; public class BoomFSWorker extends UntypedActor { private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); public static Map<String, Counter> counters = new HashMap<String, Counter>(); private final String name; private static int msgReceivedCount = 0; private static int startCount = 0; private static int stopCount = 0; public static final Long IO_EXCEPTION = 1L; public static final Long ILLEGAL_ARGUMENT_EXCEPTION = 2L; public static final Long NULL_POINTER_EXCEPTION = 3L; public static final Long RUNTIME_EXCEPTION = -1L; public BoomFSWorker(final String name) { this.name = name; } @Override public void preStart() { log.info("Starting BoomFSWorker instance # {} {}", self().hashCode(), self().path()); startCount++; counters.put(name, new Counter()); } @Override public void postStop() { log.info("Stopping BoomFSWorker instance # {} {}", self().hashCode(), self().path()); stopCount++; counters.remove(name); } @Override public void onReceive(final Object message) throws Exception { msgReceivedCount++; counters.get(name).incMsg(); if (message instanceof SearchMsg) { SearchMsg cmd = (SearchMsg) message; if (cmd.getTimeout().equals(IO_EXCEPTION)) { log.warning("{}, receive message IOException msgReceivedCount={} msgInstanceCount={}", self().path(), msgReceivedCount, counters.get(name).getMsgCount()); throw new IOException(); } else if (cmd.getTimeout().equals(ILLEGAL_ARGUMENT_EXCEPTION)) { log.warning("{}, receive message IllegalArgumentException msgReceivedCount={} msgInstanceCount={}", self().path(), msgReceivedCount, counters.get(name).getMsgCount()); throw new IllegalArgumentException(); } else if (cmd.getTimeout().equals(NULL_POINTER_EXCEPTION)) { log.warning("{}, receive message NullPointerException msgReceivedCount={} msgInstanceCount={}", self().path(), msgReceivedCount, counters.get(name).getMsgCount()); throw new NullPointerException(); } else { log.warning("{}, bad bad bad !!!!!!! msgReceivedCount={} msgInstanceCount={}", self().path(), msgReceivedCount, counters.get(name).getMsgCount()); throw new RuntimeException("BoomFSWorker received an unknow message"); } } else { unhandled(message); } } public static int getMsgReceivedCount() { return msgReceivedCount; } public static int getStartCount() { return startCount; } public static int getStopCount() { return stopCount; } public static Map<String, Counter> getCounters() { return counters; } public static void resetCounter() { msgReceivedCount = 0; startCount = 0; stopCount = 0; counters = new HashMap<String, Counter>(); } }
package com.chuxin.family.utils; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.media.RingtoneManager; import android.net.Uri; import android.text.TextUtils; import com.chuxin.family.global.CxGlobalParams; import com.chuxin.family.mate.CxMateParams; import com.chuxin.family.net.UserApi; import com.chuxin.family.parse.been.data.CxMateProfileDataField; import com.chuxin.family.parse.been.data.CxUserProfileDataField; import com.chuxin.family.resource.CxResourceString; import com.chuxin.androidpush.sdk.push.RKPush; public class CxUserProfileKeeper { //*********************用户自己的资料************************** private final String PROFILE_FIELD_ICON_BIG = "icon_big";//头像 private final String PROFILE_FIELD_ICON_MID = "icon_mid"; private final String PROFILE_FIELD_ICON_SMALL = "icon_small"; private final String PROFILE_FIELD_CHAT_BG_BIG = "chat_bg_big";//聊天背景 private final String PROFILE_FIELD_CHAT_BG_SMALL = "chat_bg_small"; private final String PROFILE_FIELD_ZONE_BG = "zone_bg";//空间背景 private final String PROFILE_FIELD_FAMILY_BIG = "family_big";//家庭背景 private final String PROFILE_FIELD_MATE_ID = "mate_id"; private final String PROFILE_FIELD_PAIR = "pair"; private final String PROFILE_FIELD_PAIR_ID = "pair_id"; private final String PROFILE_FIELD_USER_ID = "user_id"; private final String PROFILE_FILE_NAME = "profile_name"; private final String PROFILE_FIELD_GENDER = "gender"; private final String PROFILE_FIELD_GROUP_SHOW_ID = "group_show_id"; private final String PROFILE_FIELD_TOGETHER_DAY = "together_day"; private final String PROFILE_FIELD_PUSH_SOUND = "push_sound"; private final String PROFILE_FIELD_SINGLE_MODE = "single_mode"; private final String PROFILE_FIELD_VERSION_TYPE = "version_type"; //*********************对方的资料************************** private final String PROFILE_FIELD_MATE_ICON = "mate_icon"; private final String PROFILE_FIELD_MATE_NAME = "mate_name"; //获取用户自己的资料成功后调用此代码 public void saveProfile(final CxUserProfileDataField profile, Context ctx){ if (null == profile) { return; } SharedPreferences sp = ctx.getSharedPreferences(PROFILE_FILE_NAME, Context.MODE_PRIVATE); Editor edit = sp.edit(); CxGlobalParams global = CxGlobalParams.getInstance(); global.setIconBig(profile.getIcon_big()); edit.putString(PROFILE_FIELD_ICON_BIG, profile.getIcon_big()); global.setIconMid(profile.getIcon_mid()); edit.putString(PROFILE_FIELD_ICON_MID, profile.getIcon_mid()); global.setIconSmall(profile.getIcon_small()); edit.putString(PROFILE_FIELD_ICON_SMALL, profile.getIcon_small()); global.setChatBackgroundBig(profile.getChat_big()); edit.putString(PROFILE_FIELD_CHAT_BG_BIG, profile.getChat_big()); global.setChatBackgroundSmall(profile.getChat_small()); edit.putString(PROFILE_FIELD_CHAT_BG_SMALL, profile.getChat_small()); global.setTogetherDayStr(profile.getTogetherDay()); global.setFamily_big(profile.getFamily_big()); edit.putString(PROFILE_FIELD_FAMILY_BIG, profile.getFamily_big()); global.setUserId(profile.getUid()); edit.putString(PROFILE_FIELD_USER_ID, profile.getUid()); global.setVersion(profile.getGender()); edit.putInt(PROFILE_FIELD_GENDER, profile.getGender()); global.setTogetherDayStr(profile.getTogetherDay()); edit.putString(PROFILE_FIELD_TOGETHER_DAY, profile.getTogetherDay()); String pushSoundStr = profile.getPush_sound(); edit.putString(PROFILE_FIELD_PUSH_SOUND, pushSoundStr); global.setSingle_mode(profile.getSingle_mode()); edit.putInt(PROFILE_FIELD_SINGLE_MODE, profile.getSingle_mode()); global.setVersion_type(profile.getVersion_type()); edit.putInt(PROFILE_FIELD_VERSION_TYPE, profile.getVersion_type()); // global.setPartnerName(profile.getName()); global.setIsLogin(true); CxLog.i("getPartner_id", profile.getPartner_id()); String tempMateId = profile.getPartner_id(); CxLog.i("tempMateId", tempMateId+", boolean:"+TextUtils.isEmpty(tempMateId) +", equal:"+(null == tempMateId)+",null String:"+("null".equals(tempMateId))); edit.putString(PROFILE_FIELD_MATE_ID, tempMateId); if (TextUtils.isEmpty(tempMateId/*profile.getPartner_id()*/)) { //未结对 global.setPair(0); //0表示未结对(1表示结对) edit.putInt(PROFILE_FIELD_PAIR, 0); }else{ global.setPair(1); //1表示结对(0表示未结对) edit.putInt(PROFILE_FIELD_PAIR, 1); global.setPartnerId(profile.getPartner_id()); //对方UID global.setPairId(profile.getPair_id()); //结对号 edit.putString(PROFILE_FIELD_PAIR_ID, profile.getPair_id()); global.setZoneBackground(profile.getBg_big()); //二人空间的背景图 edit.putString(PROFILE_FIELD_ZONE_BG, profile.getBg_big()); //只有结对的情况才获取对方的资料 //如果结对且伴侣UID不为空,就要同时开启线程去获取伴侣资料 // UserApi.getInstance().getUserPartnerProfile(userMateProfileCallback); global.setGroup_show_id(profile.getGroup_show_id()); edit.putString(PROFILE_FIELD_GROUP_SHOW_ID, profile.getGroup_show_id()); } edit.commit(); String tempSound = pushSoundStr; if (null != tempSound) { if (tempSound.equalsIgnoreCase("w_rk_naughty_push.caf") || tempSound.equalsIgnoreCase("h_rk_naughty_push.caf")) { global.setPushSoundType(0); if(tempSound.equalsIgnoreCase("w_rk_naughty_push.caf")){ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push_first_s"); }else{ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push_first"); } }else if(tempSound.equalsIgnoreCase("w_rk_fa_role_push.caf") || tempSound.equalsIgnoreCase("h_rk_fa_role_push.caf")){ global.setPushSoundType(1); if(tempSound.equalsIgnoreCase("w_rk_fa_role_push.caf")){ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push_s"); }else{ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push"); } }else{ global.setPushSoundType(2); RKPush.S_NOTIFY_SOUND_URI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); } }else{ global.setPushSoundType(1); if(profile.getGender()==0){ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push_s"); }else{ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push"); } } // global.setAppStatus(true); global.setAppNormal(profile.getUid()); } //脱网的时候调此段代码(个人资料和对方的名称、头像) public void readProfile(Context ctx){ SharedPreferences sp = ctx.getSharedPreferences(PROFILE_FILE_NAME, Context.MODE_PRIVATE); CxGlobalParams global = CxGlobalParams.getInstance(); global.setIconBig(sp.getString(PROFILE_FIELD_ICON_BIG, null)); global.setIconMid(sp.getString(PROFILE_FIELD_ICON_MID, null)); global.setIconSmall(sp.getString(PROFILE_FIELD_ICON_SMALL, null)); global.setChatBackgroundBig(sp.getString(PROFILE_FIELD_CHAT_BG_BIG, null)); global.setChatBackgroundSmall(sp.getString(PROFILE_FIELD_CHAT_BG_SMALL, null)); global.setFamily_big(sp.getString(PROFILE_FIELD_FAMILY_BIG, null)); global.setUserId(sp.getString(PROFILE_FIELD_USER_ID, null)); global.setVersion(sp.getInt(PROFILE_FIELD_GENDER, -1)); String tempMateId = sp.getString(PROFILE_FIELD_MATE_ID, null); global.setPartnerName(sp.getString(PROFILE_FIELD_MATE_NAME, null)); global.setPartnerIconBig(sp.getString(PROFILE_FIELD_MATE_ICON, null)); global.setTogetherDayStr(sp.getString(PROFILE_FIELD_TOGETHER_DAY, null)); global.setAppNormal(sp.getString(PROFILE_FIELD_USER_ID, null)); global.setGroup_show_id(sp.getString(PROFILE_FIELD_GROUP_SHOW_ID, null)); global.setSingle_mode(sp.getInt(PROFILE_FIELD_SINGLE_MODE, 0)); global.setVersion_type(sp.getInt(PROFILE_FIELD_VERSION_TYPE, 0)); global.setIsLogin(false); //这种情况是走脱网,用户未登录 if (TextUtils.isEmpty(tempMateId/*profile.getPartner_id()*/)) { //未结对 global.setPair(0); //0表示未结对(1表示结对) }else{ global.setPair(1); //1表示结对(0表示未结对) global.setPartnerId(tempMateId); //对方UID global.setPairId(sp.getString(PROFILE_FIELD_PAIR_ID, null)); //结对号 global.setZoneBackground(sp.getString(PROFILE_FIELD_ZONE_BG, null)); //二人空间的背景图 } String tempSound = sp.getString(PROFILE_FIELD_PUSH_SOUND, null); if (null != tempSound) { if (tempSound.equalsIgnoreCase("w_rk_naughty_push.caf") || tempSound.equalsIgnoreCase("h_rk_naughty_push.caf")) { global.setPushSoundType(0); if(tempSound.equalsIgnoreCase("w_rk_naughty_push.caf")){ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push_first_s"); }else{ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push_first"); } }else if(tempSound.equalsIgnoreCase("w_rk_fa_role_push.caf") || tempSound.equalsIgnoreCase("h_rk_fa_role_push.caf")){ global.setPushSoundType(1); if(tempSound.equalsIgnoreCase("w_rk_fa_role_push.caf")){ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push_s"); }else{ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push"); } }else{ global.setPushSoundType(2); RKPush.S_NOTIFY_SOUND_URI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); } }else{ global.setPushSoundType(1); if(sp.getInt(PROFILE_FIELD_GENDER, -1)==0){ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push_s"); }else{ RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://" + ctx.getPackageName() + "/raw/" + "rk_fa_role_push"); } } } //对方的资料职存储头像和名称 public void saveMateProfile(String mateIcon, String mateName, Context ctx){ SharedPreferences sp = ctx.getSharedPreferences(PROFILE_FILE_NAME, Context.MODE_PRIVATE); Editor edit = sp.edit(); CxGlobalParams.getInstance().setPartnerIconBig(mateIcon); edit.putString(PROFILE_FIELD_MATE_ICON, mateIcon); CxGlobalParams.getInstance().setPartnerName(mateName); edit.putString(PROFILE_FIELD_MATE_NAME, mateName); edit.commit(); } }
package com.zhixinhuixue.querykylin.datasource; import com.zhixinhuixue.querykylin.entity.KylinProperties; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.io.PrintWriter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.Driver; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.LinkedList; import java.util.Properties; import java.util.logging.Logger; /** * 创建数据源 * * @author hsh * @create 2020年12月17日 */ public class KylinDataSource implements DataSource { private static final org.slf4j.Logger log = LoggerFactory.getLogger(KylinDataSource.class); private LinkedList<Connection> connectionPoolList = new LinkedList<>(); private long maxWaitTime; /** * kylin datasource * * @param kylinProperties */ public KylinDataSource(KylinProperties kylinProperties) { try { this.maxWaitTime = kylinProperties.getMaxWaitTime(); Driver driverManager = (Driver) Class.forName(kylinProperties.getDriverClassName()).newInstance(); Properties info = new Properties(); info.put("user", kylinProperties.getUsername()); info.put("password", kylinProperties.getPassword()); for (int i = 0; i < kylinProperties.getPoolSize(); i++) { Connection connection = driverManager.connect(kylinProperties.getJdbcUrl(), info); // 将代理对象放入到连接池中 connectionPoolList.add(ConnectionProxy.getProxy(connection, connectionPoolList)); } log.info("PrestoDataSource has initialized {} size connection pool", connectionPoolList.size()); } catch (Exception e) { log.error("kylinDataSource initialize error, ex: ", e); } } @Override public Connection getConnection() throws SQLException { synchronized (connectionPoolList) { if (connectionPoolList.size() <= 0) { try { // 线程有开启,就绪,运行,阻塞,销毁过程,wait() 方法使该线程让出cpu,进入到阻塞阻塞状态,停止该线程 connectionPoolList.wait(maxWaitTime); } catch (InterruptedException e) { throw new SQLException("getConnection timeout..." + e.getMessage()); } } return connectionPoolList.removeFirst(); } } @Override public Connection getConnection(String username, String password) throws SQLException { return null; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } @Override public PrintWriter getLogWriter() throws SQLException { return null; } @Override public void setLogWriter(PrintWriter out) throws SQLException { } @Override public void setLoginTimeout(int seconds) throws SQLException { } @Override public int getLoginTimeout() throws SQLException { return 0; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } /** * 动态代理对象执行方法时,会调用该类中invoke方法 * */ static class ConnectionProxy implements InvocationHandler { private Object obj; private LinkedList<Connection> pool; private String DEFAULT_CLOSE_METHOD = "close"; /** * 构造方法 * * @param obj connection * @param pool 连接池 */ private ConnectionProxy(Object obj, LinkedList<Connection> pool) { this.obj = obj; this.pool = pool; } /** * 返回connection 的代理对象 * * @param o * @param pool * @return */ public static Connection getProxy(Object o, LinkedList<Connection> pool) { /** * 类加载器: connection 的类加载器 * 实现的接口: connection 接口 * InvocationHandler 的子类 : 实现invoke方法 * * 返回结果 代理类 */ Object proxed = Proxy.newProxyInstance(o.getClass().getClassLoader(), new Class[]{Connection.class}, new ConnectionProxy(o, pool)); return (Connection) proxed; } /** * 代理对象执行某个方法时,会调用该方法 * * @param proxy 代理对象 * @param method 方法 * @param args 方法参数 * @return * @throws Throwable */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals(DEFAULT_CLOSE_METHOD)) { synchronized (pool) { pool.add((Connection) proxy); // notify 方法唤醒一个阻塞状态的线程(另一个线程),与wait(),sleep() 等方法一起用 pool.notify(); } return null; } else { return method.invoke(obj, args); } } } }
package tug; import java.util.Random; public class TeamMember extends Thread { String Team; public TeamMember(String name, String team){ super(name); Team = team; } @Override public void run() { var r = new Random(); while (Game.flag) { Game.pullTheRope(this); try { Thread.sleep(100 + r.nextInt(500)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package cn.itsite.abase.mvvm.model.base; import cn.itsite.abase.mvvm.contract.base.BaseContract; /** * Author:leguang on 2016/10/9 0009 10:35 * Email:langmanleguang@qq.com * <p> * 所有Model类的基类,负责模型层的内容,包括数据获取和处理以及部分业务逻辑代码。 */ public abstract class BaseRepository implements BaseContract.Model { public final String TAG = BaseRepository.class.getSimpleName(); }
package mark.practice.kafka.tut1; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.serialization.StringDeserializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.Properties; public class ConsumerAssignAndSeekDemo { public static Logger log = LoggerFactory.getLogger(ConsumerAssignAndSeekDemo.class); public static void main(String[] args) { Properties properties = new Properties(); properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, ProducerDemo.KAFKA_SERVERS); properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties); TopicPartition topicPartition = new TopicPartition(ProducerCallbackDemo.KAFKA_TOPIC, 0); consumer.assign(Arrays.asList(topicPartition)); long offsetToReadFrom = 15l; consumer.seek(topicPartition, offsetToReadFrom); int numMessagesToRead = 5; int numMessagesReadSoFar = 0; boolean keepOnReading = true; while (true) { ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord<String, String> record : consumerRecords) { numMessagesReadSoFar++; log.info(String.format("Key: %s, Value: %s", record.key(), record.value())); log.info(String.format("Partition: %d, Offsets: %d", record.partition(), record.offset())); if (numMessagesReadSoFar >= numMessagesToRead) { keepOnReading = false; break; } } } } }
//Mohammad Salman Mesam //Student ID: 260860161 public class Basket { private Reservation [] Reservations; public Basket() { this.Reservations=new Reservation[0]; } public Reservation[] getProducts() { Reservation [] shallowcopy = new Reservation [Reservations.length]; for(int i=0;i<Reservations.length;i++) { shallowcopy[i]=Reservations[i]; } return shallowcopy; //pointer of this equals pointer of that } public int add(Reservation r) { if(Reservations.length==0) { Reservations = new Reservation[1]; Reservations[0]=r; return Reservations.length; } Reservation[] thenewguy = new Reservation[Reservations.length+1]; for(int i=0;i<Reservations.length;i++) { thenewguy [i] = Reservations[i]; } thenewguy[Reservations.length]= r; this.Reservations=thenewguy;; return thenewguy.length; } public boolean remove(Reservation k) { int j=85; for(int i =0;i<Reservations.length;i++) { if(k.equals(Reservations[i]) || j==1){ if(i==Reservations.length-1) { } else { Reservations[i]=Reservations[i+1]; j=1; } } } if(j==1) { Reservation[] thebadguy = new Reservation[Reservations.length-1]; for(int c=0;c<Reservations.length-1;c++) { thebadguy[c]=Reservations[c]; } this.Reservations=thebadguy; return true; }else return false; } public void clear () { for(int i=0;i<Reservations.length;i++) { Reservations[i]= null; } Reservations=new Reservation[0]; } public int getNumOfReservations() { return Reservations.length; } public int getTotalCost() { int cost = 0 ; for(int i=0;i<Reservations.length;i++) { cost+=Reservations[i].getCost(); } return cost; } }
package com.stark.design23.visitor; /** * Created by Stark on 2018/3/28. * 访问者 */ public class Visitor { //通过重载对让不同工人执行命令 public void run(WorkerA workerA) { workerA.runA(); } public void run(WorkerB workerB) { workerB.runB(); } }
package mfh.db; public interface ConnectionProvider { String databaseName="mdb"; String dbUserTable="user"; String driverName="com.mysql.jdbc.Driver"; String dbConnectionURL="jdbc:mysql://localhost/"; String dbUserName="root"; String dbUserPassword=""; }
package com.fleet.seata.user.service; import com.fleet.seata.user.entity.User; import org.springframework.stereotype.Component; /** * @author April Han */ @Component public interface UserService { User get(Integer id); boolean pay(Integer id, Integer money); }
/** * Copyright 2010 Tobias Sarnowski * * 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.eveonline.api.map; import com.eveonline.api.ApiListResult; import com.eveonline.api.ApiResult; /** * @author Tobias Sarnowski */ public interface FacWarSystems<S extends FacWarSystems.SolarSystem> extends ApiListResult<S> { interface SolarSystem extends ApiResult { /** * @return the solar system's ID */ long getId(); /** * @return the solar system's name */ String getName(); /** * @return a non-zero ID if the occupying faction is not the sovereign faction. */ long getOccupyingFactionId(); /** * @return the occupying faction's name */ String getOccupyingFactionName(); /** * @return if the system is contested by another faction */ boolean isContested(); } }
/* * 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 cantante; import grupo.Grupo; import javax.swing.JOptionPane; /** * * @author ESTUDIANTE */ public class Ejercicio { /** * @param args the command line arguments */ public static void main(String[] args) { try{ int res = Integer.parseInt(JOptionPane.showInputDialog("Menú: \n 1.Persona\n 2.Grupo Personas\n3.Salir")); switch(res){ case 1: Persona persona = new Persona("Julia", "Gonzalez", 25, "Desarrollo de moviles"); HacerCantar(persona); persona.Trabajar(); Canario canario = new Canario(); HacerCantar(canario); break; case 2: Grupo grupo = new Grupo("Marlen", "Espinosa", 20, "Desarrollo web"); int respuesta = 1; do{ try{ int caso = Integer.parseInt(JOptionPane.showInputDialog("Menù \n1.Crear cliente\n2.Actualizar cliente\n3.Eliminar cliente\n4.Listar cliente\n5.Salir")); int index = -1; String Nombre = ""; String Apellido = ""; int Edad = -1; String trabajo = ""; switch(caso){ case 1: Nombre = JOptionPane.showInputDialog("Ingrese el nombre del cliente"); Apellido = JOptionPane.showInputDialog("Ingrese el apellido del cliente."); Edad = Integer.parseInt(JOptionPane.showInputDialog("Ingrese la edad del cliente")); trabajo = JOptionPane.showInputDialog("Oficio del cliente"); JOptionPane.showMessageDialog(null, grupo.Add(Nombre, Apellido, Edad, trabajo)); break; case 2: index = Integer.parseInt(JOptionPane.showInputDialog("Ingrese id cliente a modificar")); if(grupo.IsExistID(index)){ Persona person = grupo.GetPerson(index); Nombre = JOptionPane.showInputDialog(null, "Ingrese el nombre del cliente", null, JOptionPane.QUESTION_MESSAGE,null,null, person.getNombre()).toString(); Apellido = JOptionPane.showInputDialog(null, "Ingrese el apellido del cliente.", null, JOptionPane.QUESTION_MESSAGE,null,null,person.getApellido()).toString(); Edad = Integer.parseInt(JOptionPane.showInputDialog(null, "Ingrese la edad del cliente.", null, JOptionPane.QUESTION_MESSAGE,null,null, person.getEdad()).toString()); trabajo = JOptionPane.showInputDialog(null, "Oficio del cliente.", null, JOptionPane.QUESTION_MESSAGE,null,null,person.getTrabajo()).toString(); JOptionPane.showMessageDialog(null, grupo.Update(index, Nombre, Apellido, Edad, trabajo)); }else{ JOptionPane.showMessageDialog(null,"El id ingresado no existe"); } break; case 3: index = Integer.parseInt(JOptionPane.showInputDialog("Ingrese ID del cliente a eliminar")); JOptionPane.showMessageDialog(null,grupo.Delete(index)); break; case 4: JOptionPane.showMessageDialog(null,grupo.ListAll()); break; case 5: respuesta = 0; break; default: JOptionPane.showMessageDialog(null,"Valor ingresado no vàlido"); break; } }catch(Exception e){ respuesta = 0; JOptionPane.showMessageDialog(null,"Error: "+e.getMessage()); } try{ if(respuesta != 0) respuesta = Integer.parseInt(JOptionPane.showInputDialog("Menù \n ¿Desea continuar? \n1.SI\n 2.NO")); }catch(Exception e){ respuesta = 0; JOptionPane.showMessageDialog(null,"Error: "+ e.getMessage()); } }while(respuesta == 1); break; case 3: break; default: JOptionPane.showMessageDialog(null,"Item no válido"); break; } }catch(Exception e ){ JOptionPane.showMessageDialog(null, "Error: "+e.getMessage()); } } public static void HacerCantar(Cantante c){ c.cantar(); } }
package wildCards; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EmptyStackException; public class WildCards { public static void main(String[] args) { Stack<Number> numberStack=new Stack<>(); Iterable<Integer>integers=new ArrayList<>(); numberStack.pushAll(integers); Collection<Object> objects=new ArrayList<>(); numberStack.popAll(objects); } } class Stack<E>{ private E[] elements; private int size=0; private static final int DEFAULT_INITIAL_CAPACITY =16; public Stack(){ elements=(E[])new Object[DEFAULT_INITIAL_CAPACITY]; } public void push(E e){ elements[size++]=e; } public E pop(){ if(size==0) throw new EmptyStackException(); E result=elements[--size]; elements[size]=null;//Eliminate obsolete reference return result; } public void pushAll(Iterable<? extends E> src){ for (E e:src) { push(e); } } public void popAll(Collection<? super E> dst){ while (!dst.isEmpty()) dst.add(pop()); } }
/** * The TestMovie class tests and utilizes the methods found within the Movie class! * * @author C. Thurston * @version 5/8/2014 */ import java.util.*; public class testMovie4 { public static void printMovies(ArrayList<Movie> list) { for(Movie current : list) { System.out.println(current.toString()); } } public static void sortYears(ArrayList<Movie> list, int low, int high) { if( low == high) return; int mid = ( low + high) / 2; sortYears(list, low, mid); sortYears(list, mid+1, high); mergeYears(list, low, mid, high); } public static void mergeYears(ArrayList<Movie> list, int low, int mid, int high) { ArrayList<Movie> temp = new ArrayList<Movie>(); int i = low, j = mid + 1, n = 0; temp.clear(); while(i <= mid || j <= high) { if(i > mid) { temp.add(n, list.get(j)); j++; } else if (j > high) { temp.add(n, list.get(i)); i++; } else if ( list.get(i).year > list.get(j).year) { temp.add(n, list.get(i)); } else { temp.add(n, list.get(j)); } n++; } for(int k = low; k <= high; k++) { list.remove(k); list.add(k, temp.get(k - low)); } temp.clear(); } public static void sortTitles(ArrayList<Movie> list, int low, int high) { if( low == high) return; int mid = ( low + high) / 2; sortTitles(list, low, mid); sortTitles(list, mid+1, high); mergeTitles(list, low, mid, high); } public static void mergeTitles(ArrayList<Movie> list, int low, int mid, int high) { ArrayList<Movie> temp = new ArrayList<Movie>(); int i = low, j = mid + 1, n = 0; temp.clear(); while(i <= mid || j <= high) { if(i > mid) { temp.add(n, list.get(j)); j++; } else if (j > high) { temp.add(n, list.get(i)); i++; } else if ( list.get(i).title.compareTo(list.get(j).title) < 0) { temp.add(n, list.get(i)); } else { temp.add(n, list.get(j)); } n++; } for(int k = low; k <= high; k++) { list.remove(k); list.add(k, temp.get(k - low)); } } public static void sortStudio(ArrayList<Movie> list, int low, int high) { if( low == high) return; int mid = ( low + high) / 2; sortStudio(list, low, mid); sortStudio(list, mid+1, high); mergeStudio(list, low, mid, high); } public static void mergeStudio(ArrayList<Movie> list, int low, int mid, int high) { ArrayList<Movie> temp = new ArrayList<Movie>(); int i = low, j = mid + 1, n = 0; temp.clear(); while(i <= mid || j <= high) { if(i > mid) { temp.add(n, list.get(j)); j++; } else if (j > high) { temp.add(n, list.get(i)); i++; } else if ( list.get(i).studio.compareTo(list.get(j).studio) < 0) { temp.add(n, list.get(i)); } else { temp.add(n, list.get(j)); } n++; } for(int k = low; k <= high; k++) { list.remove(k); list.add(k, temp.get(k - low)); } temp.clear(); } public static void main(String[] args) { ArrayList<Movie> list = new ArrayList<Movie>(); list.add(new Movie("Brave", 2012, "Pixar")); list.add(new Movie("The Avengers", 2012, "Marvel")); list.add(new Movie("The Amazing Spiderman", 2012, "Sony")); list.add(new Movie("Iron Man 2", 2010, "Marvel")); list.add(new Movie("X-Men: First Class", 2012, "Sony")); list.add(new Movie("Toy Story 3", 2010, "Pixar")); list.add(new Movie("Drive", 2011, "Bold")); list.add(new Movie("Men in Black", 1997, "Columbia")); list.add(new Movie("Bunraku", 2010, "Snoot")); list.add(new Movie("Pulp Fiction", 1994, "Miramax")); int size = list.size(); System.out.println("Before sorting:"); printMovies(list); System.out.println(); System.out.println("Sorting by title ascending:"); sortTitles(list, 0, size); printMovies(list); System.out.println(); System.out.println("Sorting by year descending:"); sortYears(list, 0, size); printMovies(list); System.out.println(); System.out.println("Sorting by studio ascending:"); sortStudio(list, 0, size); printMovies(list); System.out.println(); } }
package nc; import nc.control.*; import nc.model.*; import nc.view.*; /** * Created by samok on 17.05.2017. */ public class Main { public static void main(String[] args) { ModelOutput model = new ModelOutput(); Controller cont = new Controller(model); NetView view = new NetView(model); model.addObserver(view); cont.start(); } }
package banking.ui; import framework.commands.Command; import framework.commands.CommandManager; import framework.commands.CreatePartyCommand; import framework.dto.PartyDTO; import framework.ui.AddCutomerDialog; import framework.util.GeneratorUtil; import framework.util.ValidatorUtil; import banking.services.PartyServiceImp; public class JDialog_AddCutomer extends AddCutomerDialog { public JDialog_AddCutomer(String custType) { super(custType); } @Override public void JButtonOK_actionPerformed(java.awt.event.ActionEvent event) { try { isAddNew = true; pojoP = new PartyDTO(); pojoP.setName(JTextField_NAME.getText()); pojoP.setCity(JTextField_CT.getText()); pojoP.setEmail(JTextField_EM.getText()); pojoP.setZip(JTextField_ZIP.getText()); pojoP.setStreet(JTextField_STR.getText()); pojoP.setState(JTextField_ST.getText()); if ("P".equalsIgnoreCase(custType)) { pojoP.setBirthDate(GeneratorUtil.getDateFromString(JTextField_BD.getText())); pojoP.setType("P"); } else { if (ValidatorUtil.isNumeric(JTextField_NoOfEmp.getText())) { pojoP.setNumberOfEmployees(Integer.parseInt(JTextField_NoOfEmp.getText())); } else { pojoP.setNumberOfEmployees(0); } pojoP.setType("C"); } Command command = new CreatePartyCommand(PartyServiceImp.getInstance(), pojoP); CommandManager manager = CommandManager.getInstance(); manager.setCommand(command); manager.invokeCommand(); } catch (RuntimeException e) { e.printStackTrace(); } dispose(); } }
package com.finix.manager.impl; import java.util.HashMap; import java.util.Map; import com.finix.bean.DistrictAdministratorBean; import com.finix.bean.GovernmentUserBean; import com.finix.dao.IDistrictAdministratorDao; import com.finix.dao.impl.DistrictAdministratorDaoImpl; import com.finix.manager.IDistrictAdministratorManager; public class DistrictAdministratorManagerImpl implements IDistrictAdministratorManager { IDistrictAdministratorDao districtAdministratorDao = new DistrictAdministratorDaoImpl(); //getDistrictAdminrDetails public DistrictAdministratorBean getDistrictAdminDetails(DistrictAdministratorBean districtAdministratorBean)throws Exception { districtAdministratorBean=districtAdministratorDao.getDistrictAdminDetails(districtAdministratorBean); return districtAdministratorBean; } @Override public String checkDistrictOldPasswordAvailable(String oldPassword,DistrictAdministratorBean districtAdministratorBean) throws Exception { String status=""; status = districtAdministratorDao.checkDistrictOldPasswordAvailable(oldPassword,districtAdministratorBean); return status; } @Override public DistrictAdministratorBean updateDistrictPasswordDetails(DistrictAdministratorBean districtAdministratorBean) throws Exception { districtAdministratorBean=districtAdministratorDao.updateDistrictPasswordDetails(districtAdministratorBean); return districtAdministratorBean; } //getTalukDetails public Map<Integer, String> getTalukDetails(GovernmentUserBean governmentUserBean) throws Exception { Map<Integer, String> talukMap = new HashMap<Integer, String>(); talukMap = districtAdministratorDao.getTalukDetails(governmentUserBean); return talukMap; } }
package com.pybeta.ui.utils; import android.view.View; import android.widget.ImageView; import android.widget.TextView; /** * Class that stores references to children of a view that get updated when the * item in the view changes */ public abstract class ItemView { /** * Create item view storing references to children of given view to be * accessed when the view is ready to display an item * * @param view */ public ItemView(final View view) { // Intentionally left blank } /** * Get text view with id * * @param view * @param id * @return text view */ protected TextView textView(final View view, final int id) { return (TextView) view.findViewById(id); } /** * Get image view with id * * @param view * @param id * @return text view */ protected ImageView imageView(final View view, final int id) { return (ImageView) view.findViewById(id); } }
package exercise_chpater10; import java.util.Scanner; import exercise_chapter7.reverse; public class PalindromeIgnoreNonAlphanumeric { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a string: "); String s = input.nextLine(); System.out.println("is " + s + " a palindrome ignoring nonalphanumeric charachters? " + isPalindrome(s)); } public static boolean isPalindrome(String s) { String s1 = filter(s); String s2 = reverseString(s1); return s2.equals(s1); } public static String filter(String s) { StringBuilder string = new StringBuilder(); for(int i = 0; i < s.length(); i++) { if(Character.isLetterOrDigit(s.charAt(i))) { string.append(s.charAt(i)); } } return string.toString(); } public static String reverseString(String s) { StringBuilder string = new StringBuilder(s); string.reverse(); return string.toString(); } }