text stringlengths 10 2.72M |
|---|
package com.pd.view;
import com.vaadin.annotations.Theme;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
@Theme("valo")
@SpringUI(path = "")
public class Index extends UI {
/**
*
*/
private static final long serialVersionUID = -6457669656179486858L;
@Override
protected void init(VaadinRequest request) {
setContent(new Label("Index"));
}
}
|
package com.gxtc.huchuan.ui.deal.leftMenu;
import com.gxtc.commlibrary.BasePresenter;
import com.gxtc.commlibrary.BaseUiView;
import com.gxtc.huchuan.bean.WxResponse;
/**
* Created by Steven on 17/3/24.
*/
public interface WxLoginContract {
interface View extends BaseUiView<WxLoginContract.Presenter>{
void loginSuccess(WxResponse response);
void loginFailed(String msg);
void showVerifcode(String userName);
}
interface Presenter extends BasePresenter{
void login(String userName, String password,String ver);
}
}
|
package com.kg.wub.system;
public interface Tickable {
public boolean tick(byte[] buffer);
}
|
package kxg.searchaf.url.chunqiu;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import kxg.searchaf.url.Constant;
import kxg.searchaf.util.ProxyUtli;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.TitleTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.SimpleNodeIterator;
public class ParserChunqiuPage {
public ChunqiuPage page;
public HashMap<String, ChunqiuProduct> allprolist;
public ChunqiuProduct product;
public ParserChunqiuPage(ChunqiuPage page,
HashMap<String, ChunqiuProduct> allprolist) {
this.page = page;
this.allprolist = allprolist;
};
public void checkprice() throws Exception {
// System.out.println("checking Chunqiu url [" + page.url + "]");
URL url = new URL(page.url);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setConnectTimeout(Constant.connect_timeout);
urlConnection.connect();
Parser parser = new Parser(urlConnection);
parser.setEncoding(Constant.ENCODE);
NodeFilter input_filter = new AndFilter(new TagNameFilter("tr"),
new HasAttributeFilter("class", "clickFocus"));
OrFilter filters = new OrFilter();
filters.setPredicates(new NodeFilter[] { input_filter });
NodeList list = parser.extractAllNodesThatMatch(filters);
for (int i = 0; i < list.size(); i++) {
Node tag = list.elementAt(i);
product = new ChunqiuProduct();
getName(tag);
// System.out.println(tagText);
}
}
private String processHTML(Node node) {
String html = node.toHtml();
// String html = node.getChildren().elementAt(3).toHtml();
// html = html + node.getChildren().elementAt(5).toHtml();
// html = html + node.getChildren().elementAt(9).toHtml();
// if (node.getChildren().size() > 11) {
// html = html + node.getChildren().elementAt(11).toHtml();
// }
// html = html
// .replaceAll("/webapp/wcs/stores/servlet/ProductDisplay", // html =
// html.replaceAll("//anf", "http://anf");
// String htmldivswatches = node.getChildren().elementAt(11).toHtml();
// htmldivswatches = htmldivswatches.replace("//anf", "http://anf");
return html;
}
private void getPriceList(Node node) throws Exception {
NodeList childList = node.getChildren();
List<String> productvalue = new ArrayList<String>();
processNodeList(childList, productvalue);
// System.out.println(productvalue);
}
private float getprice(String priceStr) throws Exception {
float returnvalue = 0;
try {
// listprice= $80
returnvalue = Float.parseFloat(priceStr.substring(1));
} catch (NumberFormatException ex) {
// listprice= $80-$90
returnvalue = Float.parseFloat(priceStr.substring(1,
priceStr.indexOf("-")));
}
return returnvalue;
}
private void getName(Node node) {
NodeList childList = node.getChildren();
List<String> productvalue = new ArrayList<String>();
processNodeList(childList, productvalue);
// System.out.println(productvalue);
product.hangban = productvalue.get(0);
product.qifeitime = productvalue.get(1).replace(" ", "").trim();
product.qifeitime = product.qifeitime.substring(0, 10) + " "
+ product.qifeitime.substring(18, 23);
// System.out.println(product.qifeitime);
product.qifei = productvalue.get(2);
product.daoda = productvalue.get(3);
product.cangwei = productvalue.get(5);
String price = productvalue.get(7).substring(1);
product.price = new Long(price);
if (productvalue.get(8).indexOf("已售完") > 0) {
// System.out.println(productvalue.get(8));
product.price = 0l;
} else {
allprolist.put(product.hangban + product.qifeitime, product);
// System.out.println(product);
}
}
private void processNodeList(NodeList list, List<String> valueList) {
// 迭代开始
SimpleNodeIterator iterator = list.elements();
while (iterator.hasMoreNodes()) {
Node node = iterator.nextNode();
// 得到该节点的子节点列表
NodeList childList = node.getChildren();
// 孩子节点为空,说明是值节点
if (null == childList) {
// 得到值节点的值
String result = node.toPlainTextString().trim();
// 若包含关键字,则简单打印出来文本
// System.out.println(result);
if (result != null && !"".equals(result))
valueList.add(result);
} // end if
// 孩子节点不为空,继续迭代该孩子节点
else {
processNodeList(childList, valueList);
}// end else
}// end wile
}
public static void main(String[] args) throws Exception {
HashMap<String, ChunqiuProduct> allnewprolist = new HashMap<String, ChunqiuProduct>();
ChunqiuPage page = new ChunqiuPage(
"http://www.china-sss.com/SHA_HKG_False_28");
ParserChunqiuPage parse = new ParserChunqiuPage(page, allnewprolist);
parse.checkprice();
ArrayList<ChunqiuProduct> matchprolist = new ArrayList<ChunqiuProduct>();
Iterator<String> entryKeyIterator = allnewprolist.keySet().iterator();
while (entryKeyIterator.hasNext()) {
String key = entryKeyIterator.next();
ChunqiuProduct product = allnewprolist.get(key);
if (
// !product.hangban.equals("9C8501") &&
product.price <= 299) {
matchprolist.add(product);
}
}
Collections.sort(matchprolist);
for (int i = 0; i < matchprolist.size(); i++) {
ChunqiuProduct matchpro = matchprolist.get(i);
System.out.println(matchpro);
}
allnewprolist = new HashMap<String, ChunqiuProduct>();
page = new ChunqiuPage("http://www.china-sss.com/SHA_HKG_False_89");
parse = new ParserChunqiuPage(page, allnewprolist);
parse.checkprice();
matchprolist = new ArrayList<ChunqiuProduct>();
entryKeyIterator = allnewprolist.keySet().iterator();
while (entryKeyIterator.hasNext()) {
String key = entryKeyIterator.next();
ChunqiuProduct product = allnewprolist.get(key);
if (
// !product.hangban.equals("9C8501") &&
product.price <= 299) {
matchprolist.add(product);
}
}
Collections.sort(matchprolist);
for (int i = 0; i < matchprolist.size(); i++) {
ChunqiuProduct matchpro = matchprolist.get(i);
System.out.println(matchpro);
}
System.out
.println("==================================================");
allnewprolist = new HashMap<String, ChunqiuProduct>();
page = new ChunqiuPage("http://www.china-sss.com/HKG_SHA_False_28");
parse = new ParserChunqiuPage(page, allnewprolist);
parse.checkprice();
matchprolist = new ArrayList<ChunqiuProduct>();
entryKeyIterator = allnewprolist.keySet().iterator();
while (entryKeyIterator.hasNext()) {
String key = entryKeyIterator.next();
ChunqiuProduct product = allnewprolist.get(key);
if (!product.hangban.equals("9C8502") && product.price <= 299) {
matchprolist.add(product);
}
}
Collections.sort(matchprolist);
for (int i = 0; i < matchprolist.size(); i++) {
ChunqiuProduct matchpro = matchprolist.get(i);
System.out.println(matchpro);
}
allnewprolist = new HashMap<String, ChunqiuProduct>();
page = new ChunqiuPage("http://www.china-sss.com/HKG_SHA_False_89");
parse = new ParserChunqiuPage(page, allnewprolist);
parse.checkprice();
matchprolist = new ArrayList<ChunqiuProduct>();
entryKeyIterator = allnewprolist.keySet().iterator();
while (entryKeyIterator.hasNext()) {
String key = entryKeyIterator.next();
ChunqiuProduct product = allnewprolist.get(key);
if (!product.hangban.equals("9C8502") && product.price <= 299) {
matchprolist.add(product);
}
}
Collections.sort(matchprolist);
for (int i = 0; i < matchprolist.size(); i++) {
ChunqiuProduct matchpro = matchprolist.get(i);
System.out.println(matchpro);
}
}
}
|
/*
* ### Copyright (C) 2008 Michael Fuchs ###
* ### All Rights Reserved. ###
*
* Author: Michael Fuchs
* E-Mail: michael.fuchs@unico-group.com
* URL: http://www.michael-a-fuchs.de
*/
package org.dbdoclet.tidbit.action;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.Icon;
import javax.swing.JFileChooser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dbdoclet.antol.AntFileWriter;
import org.dbdoclet.jive.dialog.ErrorBox;
import org.dbdoclet.jive.dialog.InfoBox;
import org.dbdoclet.service.ResourceServices;
import org.dbdoclet.tidbit.Tidbit;
import org.dbdoclet.tidbit.Validator;
import org.dbdoclet.tidbit.application.action.AbstractTidbitAction;
import org.dbdoclet.tidbit.common.StaticContext;
import org.dbdoclet.tidbit.medium.MediumService;
import org.dbdoclet.tidbit.perspective.Perspective;
import org.dbdoclet.tidbit.project.FileManager;
import org.dbdoclet.tidbit.project.Project;
public class ActionSaveProject extends AbstractTidbitAction {
private static final long serialVersionUID = 1L;
private static Log logger = LogFactory.getLog(ActionSaveProject.class);
private boolean isSaveAs = false;
private final Tidbit tidbit;
public ActionSaveProject(Tidbit application, String name, Icon icon) {
this(application, name, icon, false);
}
public ActionSaveProject(Tidbit application, String name, Icon icon,
boolean isSaveAs) {
super(application, name, icon);
tidbit = application;
this.isSaveAs = isSaveAs;
}
@Override
public void action(ActionEvent event) throws Exception {
try {
application.setWaitCursor();
save(isSaveAs);
} finally {
finished();
}
}
@Override
public void finished() {
application.setDefaultCursor();
logger.debug("ActionSaveProject finished.");
}
public boolean save() throws Exception {
return save(false);
}
public boolean save(boolean isSaveAs) throws Exception {
Project project = application.getProject();
if (project == null) {
InfoBox.show(StaticContext.getDialogOwner(),
ResourceServices.getString(res, "C_INFORMATION"),
ResourceServices.getString(res, "C_INFO_NO_ACTIVE_PROJECT"));
return false;
}
if (project.getProjectFile() == null || isSaveAs == true) {
File file = saveDialog();
if (file == null) {
return false;
}
if (project == null || isSaveAs) {
project = new Project(file, project.getProjectDirectory(),
project.getBuildDirectory());
project.setProjectFile(file);
application.setProject(project);
application.addRecent(file);
application.setFrameTitle(file.getName());
wm.disableSaveWidgets();
}
application.addRecent(file);
application.setFrameTitle(file.getName());
}
for (Perspective perspective : application.getPerspectiveList()) {
perspective.syncModel(project);
}
Validator validator = new Validator(tidbit, "save");
if (validator.check() == false) {
return false;
}
FileManager fileManager = project.getFileManager();
if (fileManager.getDocBookFile() == null) {
ErrorBox.show(StaticContext.getDialogOwner(),
res.getString("C_ERROR"),
res.getString("C_ERROR_DOCBOOK_FILE_UNDEFINED"));
return false;
}
AntFileWriter writer = project.createAntWriter();
for (MediumService mediumService : application.getMediumServiceList()) {
mediumService.write(writer, project);
}
writer.save();
for (Perspective perspective : application.getPerspectiveList()) {
perspective.syncView(project);
}
if (isSaveAs == false) {
wm.disableSaveWidgets();
}
application.setFrameTitle(project.getProjectName());
return true;
}
private File saveDialog() throws IOException {
File dir = null;
Project project = application.getProject();
String path = project.getDestinationPath();
if ((path != null) && (path.length() > 0)) {
dir = new File(path);
} else {
dir = new File(".");
}
JFileChooser fc = new JFileChooser(dir);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int rc = fc.showSaveDialog(StaticContext.getDialogOwner());
if (rc == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile();
} else {
return null;
}
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.types;
import pl.edu.icm.unity.exceptions.InternalException;
/**
* General purpose interface for objects which can have its state serialized into Json and then read back.
* We prefer this to the binary Java serialization.
*
* It is assumed that implementations should have a default constructor.
* @author K. Benedyczak
*/
public interface JsonSerializable
{
/**
* @return JSON serialized representation
* @throws InternalException
*/
public String getSerializedConfiguration() throws InternalException;
/**
* Initializes object from JSON
* @param json
* @throws InternalException
*/
public void setSerializedConfiguration(String json) throws InternalException;
}
|
/*!
* Picto
* Copyright 2016 Mozq
*
* 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 net.mozq.picto;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.InvalidPropertiesFormatException;
import java.util.Locale;
import java.util.Properties;
import java.util.TimeZone;
import org.mifmi.commons4j.config.Config;
import org.mifmi.commons4j.config.OrderedProperties;
import org.mifmi.commons4j.config.PropertiesConfig;
public class AppConfig {
private String configName;
private String appName;
private String groupName;
private Config config;
public AppConfig(String configName, String appName, String groupName) throws InvalidPropertiesFormatException, IOException {
this.configName = configName;
this.appName = appName;
this.groupName = groupName;
this.config = Config.loadFromAppConfig(configName, appName, groupName);
}
public String getConfigName() {
return configName;
}
public String getAppName() {
return appName;
}
public String getGroupName() {
return groupName;
}
public void load() throws InvalidPropertiesFormatException, IOException {
this.config = Config.loadFromAppConfig(this.configName, this.appName, this.groupName);
}
public void store(String comments) throws IOException {
this.config.storeToAppConfig(this.configName, this.appName, this.groupName, comments);
}
public void loadFromFile(Path filePath) throws InvalidPropertiesFormatException, IOException {
try (BufferedReader br = Files.newBufferedReader(filePath, Charset.forName("UTF-8"))) {
this.config = new PropertiesConfig(br);
}
}
public void storeToFile(Path filePath, String comments) throws IOException {
Properties props = new OrderedProperties();
Enumeration<String> keys = this.config.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
String value = this.config.getAsString(key);
props.setProperty(key, value);
}
try (BufferedWriter bw = Files.newBufferedWriter(filePath, Charset.forName("UTF-8"))) {
props.store(bw, comments);
bw.flush();
bw.close();
}
}
public String get(String key, String defaultValue) {
return this.config.getAsString(key, defaultValue);
}
public int getInt(String key, int defaultValue) {
return this.config.getAsInt(key, defaultValue);
}
public long getLong(String key, long defaultValue) {
return this.config.getAsLong(key, defaultValue);
}
public double getDouble(String key, double defaultValue) {
return this.config.getAsDouble(key, defaultValue);
}
public boolean getBoolean(String key, boolean defaultValue) {
return this.config.getAsBoolean(key, defaultValue);
}
public <T extends Enum<T>> T getEnum(String key, Class<T> enumType, T defaultValue) {
String value = get(key, null);
if (value == null || value.isEmpty()) {
return defaultValue;
}
return Enum.valueOf(enumType, value);
}
public Locale getLocale(String key, Locale defaultValue) {
String value = get(key, null);
if (value == null || value.isEmpty()) {
return defaultValue;
}
return Locale.forLanguageTag(value);
}
public TimeZone getTimeZone(String key, TimeZone defaultValue) {
String value = get(key, null);
if (value == null || value.isEmpty()) {
return defaultValue;
}
return TimeZone.getTimeZone(value);
}
public AppConfig set(String key, String value) {
this.config.set(key, value);
return this;
}
public AppConfig setInt(String key, int value) {
this.config.set(key, value);
return this;
}
public AppConfig setLong(String key, long value) {
this.config.set(key, value);
return this;
}
public AppConfig setDouble(String key, double value) {
this.config.set(key, value);
return this;
}
public AppConfig setBoolean(String key, boolean value) {
this.config.set(key, value);
return this;
}
public AppConfig setEnum(String key, Enum<?> value) {
return set(key, (value == null) ? null : value.name());
}
public AppConfig setLocale(String key, Locale value) {
return set(key, (value == null) ? null : value.toLanguageTag());
}
public AppConfig setTimeZone(String key, TimeZone value) {
return set(key, (value == null) ? null : value.getID());
}
}
|
import org.junit.Test;
public class TwitterTest {
@Test
public void testShouldPostAndGetLast10HotNewsFeeds(){
Twitter twitter = new Twitter();
twitter.postTweet(1, 79);
twitter.postTweet(1, 80);
twitter.postTweet(1, 81);
twitter.postTweet(1, 82);
twitter.postTweet(1, 83);
twitter.postTweet(1, 84);
twitter.postTweet(1, 85);
twitter.postTweet(1, 86);
twitter.postTweet(1, 87);
twitter.postTweet(1, 88);
twitter.postTweet(1, 89);
twitter.postTweet(1, 90);
// Hot tweets [last 10]
twitter.postTweet(1, 91);
twitter.postTweet(1, 92);
twitter.postTweet(1, 93);
twitter.postTweet(1, 94);
twitter.postTweet(1, 95);
twitter.postTweet(1, 96);
twitter.postTweet(1, 97);
twitter.postTweet(1, 98);
twitter.postTweet(1, 99);
twitter.postTweet(1, 100);
System.out.println(twitter.getNewsFeed(1));
}
}
|
package com.shiyanlou.mybatis.mapper;
import com.shiyanlou.mybatis.model.User2;
import java.util.HashMap;
import java.util.List;
public interface User2Mapper {
public int insertUser2(User2 user) throws Exception;
public int updateUser2(User2 user) throws Exception;
public int deleteUser2(Integer id) throws Exception;
public User2 selectUser2ById(Integer id) throws Exception;
public List<User2> selectAllUser2() throws Exception;
public List<User2> dynamicIfTest(HashMap<String, Object> address) throws Exception;
public List<User2> dyTrimTest(HashMap<String, Object> address) throws Exception;
public List<User2> dywhereTest(HashMap<String, Object> address) throws Exception;
public int dySetUser2(HashMap<String, Object> address) throws Exception;
public List<User2> dyForeachTest(List<Integer> ids) throws Exception;
}
|
package algorithm._9;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) {
System.out.println(new Solution().isPalindrome(121));
}
public boolean isPalindrome(int x) {
if (x == 0) {
return true;
}
if (x < 0 || x % 10 == 0) {
return false;
}
long origin = x;
List<Integer> arrays = new ArrayList<>();
while (x != 0) {
arrays.add(x % 10);
x = x / 10;
}
StringBuilder stringBuilder = new StringBuilder();
arrays.stream().forEach(array -> stringBuilder.append(array));
return origin == Long.parseLong(stringBuilder.toString());
}
}
|
package com.bnade.wow.repository;
import com.bnade.wow.entity.Realm;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 魔兽服务器信息
* Created by liufeng0103@163.com on 2017/7/6.
*/
public interface RealmRepository extends JpaRepository<Realm, Integer> {
}
|
package FunctionalTests;
import org.junit.After;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
/**
* Created by nika.khaladkar on 11/08/2016.
*/
public class Verify_New_User_Journey_For_HAH {
private WebDriver driver;
private String baseURL;
@After
public void tearDown() throws Exception {
driver.quit();
}
//@Test
public void verifyNewUserIsAbleToBuyHAH() throws InterruptedException {
System.setProperty("webdriver.chrome.driver","/Users/nika.khaladkar/software/ChromeDriver/chromedriver");
driver = new ChromeDriver();
baseURL = "https://webshop-release.hivehome.net/";
driver.manage().deleteAllCookies();
driver.get(baseURL);
driver.manage().window().maximize();
//Click on products
driver.findElement(By.xpath(".//*[@data-omniture-ref='TopNav_Products']")).click();
Thread.sleep(3000);
//Click on Heating
driver.findElement(By.xpath(".//*[@data-omniture-ref='Heating_subnav']")).click();
Thread.sleep(3000);
//Click on Buy Now for Heating
driver.findElement(By.xpath(".//*[@data-omniture-ref='HAHshowCTA']")).click();
Thread.sleep(3000);
//Click on Add To basket
driver.findElement(By.xpath(".//*[@data-omniture-ref='Ec_HAH_ATB']")).click();
Thread.sleep(2000);
driver.findElement(By.id("cart-link")).click();
Thread.sleep(2000);
//Click on Buy now on cart page
driver.findElement(By.id("checkout-link")).click();
Thread.sleep(2000);
String login_Email = "order_email";
String email_address = enterEmailAddress(login_Email);
Thread.sleep(2000);
String str = driver.findElement(By.cssSelector("input[value='Start checkout']")).getAttribute("value");
Assert.assertEquals(str,"Start checkout");
driver.findElement(By.cssSelector("input[value='Start checkout']")).click();
enterYourContactDetails(email_address);
enterBookingAppointmentDetails();
enterPaymentDetails();
String orderConfirmationMsg = "Thanks for your order";
String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue(bodyText.contains(orderConfirmationMsg), "Order confirmation message not found!");
WebElement divElement = driver.findElement(By.className("ref_and_date"));
String orderRefNumberDetails = divElement.getText();
System.out.println(orderRefNumberDetails);
driver.quit();
}
public void selectValueFromUnorderedList (WebElement unorderedList, final String value) {
List<WebElement> options = unorderedList.findElements(By.tagName("li"));
for (WebElement option : options) {
if (value.equals(option.getText())) {
option.click();
break;
}
}
}
public void enterYourContactDetails(String email_address) throws InterruptedException{
new Select(driver.findElement(By.id("order_ship_address_attributes_title"))).selectByVisibleText("Mr");
driver.findElement(By.id("order_ship_address_attributes_firstname")).sendKeys("TestUserFirstname");
driver.findElement(By.id("order_ship_address_attributes_lastname")).sendKeys("TestUserLastname");
int randomPhoneNumber;
randomPhoneNumber = 100 + (int)(Math.random() * ((999999999 - 99) + 1));
int initialDigits = 07;
System.out.println("\n");
System.out.println("User Phone number:"+ initialDigits+""+randomPhoneNumber);
driver.findElement(By.id("order_ship_address_attributes_phone")).sendKeys("07"+randomPhoneNumber);
driver.findElement(By.id("order_email_confirmation")).sendKeys(email_address);
System.out.println("User Email address :"+ email_address);
JavascriptExecutor js =(JavascriptExecutor)driver;
js.executeScript("$('#order_hivehome_info_attributes_heating_control_separate_from_boiler').parent('.iradio').iCheck('check');");
driver.findElement(By.id("postcodelookup")).sendKeys("SL2 5GF");
driver.findElement(By.xpath(".//*[@data-omniture-ref='PostcodeLU_CTA']")).click();
Thread.sleep(2000);
WebElement unorderedList = driver.findElement(By.className("lookup-results"));
selectValueFromUnorderedList(unorderedList, "Flat 73 The Junction Grays Place, Slough");
Thread.sleep(2000);
driver.findElement(By.cssSelector("input[value='Next']")).click();
}
public void enterBookingAppointmentDetails() throws InterruptedException{
//driver.findElement(By.xpath(".//*[@data-omniture-ref='BA_Book_CTA']")).click();
driver.findElement(By.cssSelector("a.pick-appointment")).click();
Thread.sleep(4000);
JavascriptExecutor js =(JavascriptExecutor)driver;
js.executeScript("$('#order_terms_and_conditions').parent('.icheckbox').iCheck('check');");
driver.findElement(By.cssSelector("input[value='Next']")).click();
}
public void enterPaymentDetails() throws InterruptedException{
driver.findElement(By.id("card_number")).sendKeys("4263971921001307");
driver.findElement(By.id("card_code")).sendKeys("000");
driver.findElement(By.cssSelector("input[value='Pay securely now']")).click();
Thread.sleep(2000);
//driver.findElement(By.cssSelector("input[value='Submit']")).click();
}
public String enterEmailAddress(String fieldId){
int randomNumber;
randomNumber = 100 + (int)(Math.random() * ((1000000 - 100) + 1));
driver.findElement(By.id(fieldId)).sendKeys("automationtest"+randomNumber+"@yopmail.com");
String generated_emailID = driver.findElement(By.id(fieldId)).getAttribute("value");
return generated_emailID;
}
}
|
/*
* 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 ejercicio01;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
*
* @author examen
*/
public class Usuario {
String fechaDeNacimiento;
public Usuario() {
setFechaDeNacimiento();
}
public void setFechaDeNacimiento() {
Scanner entrada = new Scanner(System.in);
boolean valido = true;
String fecha;
do {
valido = true;
System.out.print("\nIntroduce tu fecha de nacimiento en formato dd/mm/aaaa: ");
fecha = entrada.next();
try {
StringTokenizer fechaToken = new StringTokenizer(fecha, "/");
String dStr = fechaToken.nextToken();
String mStr = fechaToken.nextToken();
String aStr = fechaToken.nextToken();
if (dStr.length() > 2) valido = false;
else if (mStr.length() > 2) valido = false;
else if (aStr.length() != 4) valido = false;
int dInt = Integer.parseInt(dStr);
int mInt = Integer.parseInt(mStr);
int aInt = Integer.parseInt(aStr);
if (dInt < 1 | dInt > 31) valido = false;
else if (mInt < 1 | mInt > 12) valido = false;
else if (aInt < 1800 | aInt > 2015) valido = false;
} catch(Exception e) {
valido = false;
};
if (!valido) System.out.println("La fecha no es válida");
} while(!valido);
fechaDeNacimiento = fecha;
}
}
|
/**
* _28_ImplementsStrStr
*/
public class _28_ImplementsStrStr {
public int strStr(String haystack, String needle) {
return getIndexOf(haystack, needle);
}
public int getIndexOf(String str, String match) {
if (str == null || match == null || str.length() < 1 || match.length() < 1 || str.length() < match.length())
return 0;
char[] ss = str.toCharArray();
char[] ms = match.toCharArray();
int si = 0;
int mi = 0;
int[] next = getNextArray(ms);
while (si < ss.length && mi < ms.length) {
if (ss[si] == ms[mi]) {
si++;
mi++;
} else if (next[mi] == -1) {
si++;
} else {
mi = next[mi];
}
}
return mi == ms.length ? si - mi : -1;
}
public int[] getNextArray(char[] ms) {
if (ms.length == 1)
return new int[]{-1};
int[] next = new int[ms.length];
next[0] = -1;
next[1] = 0;
int pos = 2;
int cn = 0;
while (pos < next.length) {
if (ms[pos - 1] == ms[cn])
next[pos++] = ++cn;
else if (cn > 0) {
cn = next[cn];
} else {
next[pos++] = 0;
}
}
return next;
}
} |
package com.wxt.designpattern.command.test01;
/*********************************
* @author weixiaotao1992@163.com
* @date 2018/12/1 13:53
* QQ:1021061446
*
*********************************/
public class Client {
/**
* 示意,负责创建命令对象,并设定它的接受者
*/
public void assemble(){
//创建接受者
Receiver receiver = new Receiver();
//创建命令对象,设定它的接收者
Command command = new ConcreteCommand(receiver);
//创建Invoker,把命令对象设置进去
Invoker invoker = new Invoker();
invoker.setCommand(command);
//执行命令
invoker.runCommand();
}
}
|
package ALIXAR.U4_POO.T1.A2;
public class principal {
public static void main(String[] args) {
CuentaCorriente c1 = new CuentaCorriente("Adrian", "77977354");
CuentaCorriente c2 = new CuentaCorriente(100);
CuentaCorriente c3 = new CuentaCorriente(100, -50, "66688834");
c1.mostrar_informacion();
System.out.println("");
c2.mostrar_informacion();
System.out.println("");
c3.mostrar_informacion();
}
} |
package com.example.intake;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
/** After loading a patient, this activity gives a physician 2 options:
* display all data for this patient, or record a prescription
* for this patient.*/
public class PhysicianOptionsActivity extends Activity {
/** The health card number for the patient.*/
private String patientHCN;
/** The emergency room where the patient is stored.*/
private EmergencyRoom er;
/** The user type of the app.*/
private String userType;
/** The patient that the options are regarding.*/
private Patient patient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_physician_options);
Intent intent = getIntent();
this.er = (EmergencyRoom)intent.getSerializableExtra("er");
this.patientHCN = (String)intent.getSerializableExtra("hcn");
this.userType = (String)intent.getSerializableExtra("userType");
TextView patientBasicText = (TextView)
findViewById(R.id.basicInfo);
this.patient = er.lookUpPatient(patientHCN);
patientBasicText.setText(patient.getName() + " " + patient.getHealthCardNumber());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.physician_options, menu);
return true;
}
/**
* Takes the user to DisplayThatPatientActivity.
* @param view the view of this activity
*/
public void displayPatient(View view){
Intent intent = new Intent(this, DisplayThatPatientActivity.class);
intent.putExtra("er", er);
intent.putExtra("hcn", patientHCN);
intent.putExtra("userType", userType);
startActivity(intent);
}
/**
* Takes the user to PrescribeMedicationActivity.
* @param view the view of this activity
*/
public void recordPrescriptionInfo(View view){
Intent intent = new Intent(this, PrescribeMedicationActivity.class);
intent.putExtra("er", er);
intent.putExtra("hcn", patientHCN);
intent.putExtra("userType", userType);
startActivity(intent);
}
/**
* Takes the user back to FindPatientActivity.
* @param view the view of this activity
*/
public void goHome(View view){
Intent intent = new Intent(this, FindPatientActivity.class);
intent.putExtra("er", er);
intent.putExtra("userType", userType);
startActivity(intent);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tot.dao.jdbc;
import tot.dao.AbstractDao;
import tot.dao.DaoFactory;
import tot.db.DBUtils;
import tot.util.StringUtils;
import tot.bean.*;
import tot.exception.ObjectNotFoundException;
import tot.exception.DatabaseException;
import java.sql.*;
import java.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Administrator
*/
public class AnswerDaoImplJDBC extends AbstractDao {
private static Log log = LogFactory.getLog(AnswerDaoImplJDBC.class);
/**
* Creates a new instance of EduVersionDaoImplJDBC
*/
public AnswerDaoImplJDBC() {
}
/*
* get last id
*/
public int getLastId() {
DataField df = null;
int returnValue = 0;
String sql = null;
sql = "select id from t_answer order by id desc";
Collection lists = this.getDataList_Limit_Normal(sql, "id", 1, 0);
Iterator iter = lists.iterator();
if (iter.hasNext()) {
df = (DataField) iter.next();
}
if (df != null) {
returnValue = Integer.parseInt(df.getFieldValue("id")) + 1;
} else {
returnValue = 1;
}
return returnValue;
}
/** add Keywords */
public boolean add(int askid, String userid, String content, String attach, Timestamp moditime, int status) {
Connection conn = null;
PreparedStatement ps = null;
boolean returnValue = true;
String sql = "insert into t_answer(AskId,UserId,Content,Attach,PubDate,Status) values(?,?,?,?,?,?)";
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, askid);
ps.setString(2, userid);
ps.setString(3, content);
ps.setString(4, attach);
ps.setTimestamp(5, moditime);
ps.setInt(6, status);
if (ps.executeUpdate() != 1) {
returnValue = false;
}
} catch (SQLException e) {
log.error("add answer error", e);
} finally {
DBUtils.closePrepareStatement(ps);
DBUtils.closeConnection(conn);
}
return returnValue;
}
/*
* mod Keywords
*/
public boolean mod(int id, String content, String attach, Timestamp moditime) {
Connection conn = null;
PreparedStatement ps = null;
boolean returnValue = true;
String sql = "update t_answer set Content=?,Attach=?,PubDate=? where id=?";
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, content);
ps.setString(2, attach);
ps.setTimestamp(3, moditime);
ps.setInt(4, id);
if (ps.executeUpdate() != 1) {
returnValue = false;
}
} catch (SQLException e) {
log.error("mod answer error", e);
} finally {
DBUtils.closePrepareStatement(ps);
DBUtils.closeConnection(conn);
}
return returnValue;
}
public Collection getList(int askid, int currentpage, int pagesize) {
String fields="id,AskId,UserId,Content,Attach,PubDate,Status";
if (DBUtils.getDatabaseType() == DBUtils.DATABASE_MYSQL) {
StringBuffer sql = new StringBuffer(512);
sql.append("SELECT "+fields+" from t_answer where 1=1");
if (askid > 0) {
sql.append(" and AskId=" + askid);
}
sql.append(" order by id desc");
//System.out.println(sql.toString());
return getDataList_mysqlLimit(sql.toString(),fields, pagesize, (currentpage - 1) * pagesize);
} else if (DBUtils.getDatabaseType() == DBUtils.DATABASE_SQLSERVER) {
StringBuffer sql = new StringBuffer(512);
sql.append("SELECT TOP ");
sql.append(pagesize);
sql.append(" id,Title FROM t_answer WHERE (id <=(SELECT MIN(id) FROM (SELECT TOP ");
sql.append((currentpage - 1) * pagesize + 1);
sql.append(" id FROM t_answer");
sql.append(" ORDER BY id DESC) AS t))");
sql.append(" ORDER BY id DESC");
return getData(sql.toString(), "id,Title");
} else {
StringBuffer sql = new StringBuffer(512);
sql.append("select id,Title from t_answer");
return getDataList_Limit_Normal(sql.toString(), "id,Title", pagesize, (currentpage - 1) * pagesize);
}
}
public DataField get(int id) {
String fields = "id,AskId,UserId,Content,Attach,PubDate,Status";
return getFirstData("select " + fields + " from t_answer where id=" + id, fields);
}
public DataField getShow(int id) {
String fields = "Ask_Id,Ask_UserId,Ask_PayNum,Answer_UserId";
StringBuffer sql = new StringBuffer();
sql.append("SELECT t_ask.id,t_ask.UserId,t_ask.PayNum,t_answer.UserId from t_ask,t_answer where t_ask.id=t_answer.AskId and t_answer.id=" + id);
return getFirstData(sql.toString(), fields);
}
public int getTotalCount(int askid) {
StringBuffer sql = new StringBuffer(512);
sql.append("SELECT count(*) FROM t_answer where 1=1");
if (askid > 0) {
sql.append(" and AskId=" + askid);
}
return (this.getDataCount(sql.toString()));
}
public void batDel(String[] s) {
this.bat("delete from t_answer where id=?", s);
}
public void batStatus(String[] s, int val) {
this.bat("update t_answer set Status=" + val + " where id=?", s);
}
public void upStatus(int id,int val) throws ObjectNotFoundException, DatabaseException {
exe("update t_answer set Status="+val+" where id=" + id);
}
public boolean del(int id) throws ObjectNotFoundException, DatabaseException {
return exe("delete from t_answer where id=" + id);
}
}
|
package com.example.demo.domain;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Calendar;
@Data
@NoArgsConstructor
public class Audited {
private String id;
private String created_by;
private Calendar created_date;
private String modified_by;
private Calendar modified_date;
private Integer flag;
}
|
package pcs.is.domain;
import java.util.ArrayList;
class PlanDeCurso {
private Curso curso;
private String programaEducativo;
private String periodo;
private String objetivoGeneral;
private ArrayList<Bibliografia> bibliografia;
private ArrayList<Planeacion> planeacion;
public PlanDeCurso(Curso curso, String programaEducativo, String periodo, String objetivoGeneral) {
this.curso = curso;
this.programaEducativo = programaEducativo;
this.periodo = periodo;
this.objetivoGeneral = objetivoGeneral;
insertarFuente();
}
private void insertarFuente(){
bibliografia= new ArrayList<>();
while(true){
Bibliografia nueva= new Bibliogragfia();
nueva.setAutor();
nueva.setTituloLibro();
nueva.setEditorial();
nueva.setAnio();
bibliografia.add(nueva);
}
}
}
|
package com.contract.system.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.contract.system.model.Service;
public interface ServiceRepository extends JpaRepository<Service, Integer>{
Service findAllByServiceid(Long serviceid);
@Query(value = "select servicename from service;", nativeQuery = true)
public List<String> findName();
public Service findByServicename(String ser);
@Query(value = "select unit from service where servicename = ?1 ;", nativeQuery = true)
public String findUnitByServicename(String servicename);
}
|
package com.nfet.icare.service;
import java.util.List;
import com.nfet.icare.pojo.Fix;
import com.nfet.icare.pojo.Warranty;
import com.nfet.icare.pojo.WarrantyPkg;
public interface OrderService {
//获取用户报修列表
public List<Fix> fixList(String userNo);
//根据报修订单号获取报修详情
public Fix fixDetail(String fixId);
//获取用户延保列表
public List<Warranty> warrantyList(String userNo);
//获取用户延保套餐内容
public WarrantyPkg warrantyPkg(String warrantyNo);
//获取用户上门服务卡内容
public WarrantyPkg warrantyVisit(String warrantyNo);
//根据延保订单号获取延保详情
public Warranty warrantyDetail(String warrantyNo);
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.client.standalone;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.Person;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.servlet.client.MockMvcWebTestClient;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
/**
* {@link MockMvcWebTestClient} equivalent of the MockMvc
* {@link org.springframework.test.web.servlet.samples.standalone.AsyncTests}.
*
* @author Rossen Stoyanchev
*/
class AsyncTests {
private final WebTestClient testClient =
MockMvcWebTestClient.bindToController(new AsyncController()).build();
@Test
void callable() {
this.testClient.get()
.uri("/1?callable=true")
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody().json("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}");
}
@Test
void streaming() {
this.testClient.get()
.uri("/1?streaming=true")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("name=Joe");
}
@Test
void streamingSlow() {
this.testClient.get()
.uri("/1?streamingSlow=true")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("name=Joe&someBoolean=true");
}
@Test
void streamingJson() {
this.testClient.get()
.uri("/1?streamingJson=true")
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody().json("{\"name\":\"Joe\",\"someDouble\":0.5}");
}
@Test
void deferredResult() {
this.testClient.get()
.uri("/1?deferredResult=true")
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody().json("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}");
}
@Test
void deferredResultWithImmediateValue() {
this.testClient.get()
.uri("/1?deferredResultWithImmediateValue=true")
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody().json("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}");
}
@Test
void deferredResultWithDelayedError() {
this.testClient.get()
.uri("/1?deferredResultWithDelayedError=true")
.exchange()
.expectStatus().is5xxServerError()
.expectBody(String.class).isEqualTo("Delayed Error");
}
@Test
void listenableFuture() {
this.testClient.get()
.uri("/1?listenableFuture=true")
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody().json("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}");
}
@Test
void completableFutureWithImmediateValue() throws Exception {
this.testClient.get()
.uri("/1?completableFutureWithImmediateValue=true")
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody().json("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}");
}
@RestController
@RequestMapping(path = "/{id}", produces = "application/json")
private static class AsyncController {
@GetMapping(params = "callable")
Callable<Person> getCallable() {
return () -> new Person("Joe");
}
@GetMapping(params = "streaming")
StreamingResponseBody getStreaming() {
return os -> os.write("name=Joe".getBytes(StandardCharsets.UTF_8));
}
@GetMapping(params = "streamingSlow")
StreamingResponseBody getStreamingSlow() {
return os -> {
os.write("name=Joe".getBytes());
try {
Thread.sleep(200);
os.write("&someBoolean=true".getBytes(StandardCharsets.UTF_8));
}
catch (InterruptedException e) {
/* no-op */
}
};
}
@GetMapping(params = "streamingJson")
ResponseEntity<StreamingResponseBody> getStreamingJson() {
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON)
.body(os -> os.write("{\"name\":\"Joe\",\"someDouble\":0.5}".getBytes(StandardCharsets.UTF_8)));
}
@GetMapping(params = "deferredResult")
DeferredResult<Person> getDeferredResult() {
DeferredResult<Person> result = new DeferredResult<>();
delay(100, () -> result.setResult(new Person("Joe")));
return result;
}
@GetMapping(params = "deferredResultWithImmediateValue")
DeferredResult<Person> getDeferredResultWithImmediateValue() {
DeferredResult<Person> result = new DeferredResult<>();
result.setResult(new Person("Joe"));
return result;
}
@GetMapping(params = "deferredResultWithDelayedError")
DeferredResult<Person> getDeferredResultWithDelayedError() {
DeferredResult<Person> result = new DeferredResult<>();
delay(100, () -> result.setErrorResult(new RuntimeException("Delayed Error")));
return result;
}
@GetMapping(params = "listenableFuture")
@SuppressWarnings("deprecation")
org.springframework.util.concurrent.ListenableFuture<Person> getListenableFuture() {
org.springframework.util.concurrent.ListenableFutureTask<Person> futureTask =
new org.springframework.util.concurrent.ListenableFutureTask<>(() -> new Person("Joe"));
delay(100, futureTask);
return futureTask;
}
@GetMapping(params = "completableFutureWithImmediateValue")
CompletableFuture<Person> getCompletableFutureWithImmediateValue() {
CompletableFuture<Person> future = new CompletableFuture<>();
future.complete(new Person("Joe"));
return future;
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
String errorHandler(Exception ex) {
return ex.getMessage();
}
private void delay(long millis, Runnable task) {
Mono.delay(Duration.ofMillis(millis)).doOnTerminate(task).subscribe();
}
}
}
|
package bag;
/**
* @author YoSaukit
* @date 2019/10/8 19:52
*/
public class No5_Palindromic {
private int lo,maxLen;
public static void main(String[] args) {
No5_Palindromic no5_palindromic = new No5_Palindromic();
System.out.println(no5_palindromic.longestPalindrome("babad"));
}
public String longestPalindrome(String s) {
int len = s.length();
if (len<2)return s;
for (int i = 0; i < len - 1; i++) {
extendPalidrome(s,i,i);
extendPalidrome(s,i,i+1);
}
return s.substring(lo,lo+maxLen);
}
private void extendPalidrome(String s, int j, int k){
while(j>=0 && k<s.length() && s.charAt(j)==s.charAt(k)){
j--;
k++;
}
if (maxLen<k-j-1){
lo = j+1;
maxLen = k-j-1;
}
}
}
|
package v12;
import java.util.Random;
import java.util.concurrent.Callable;
public class Evolver implements Callable<LevelStrategy[]> {
LevelStrategy[] originalPopulation, evolved_population;
int tsize, POPSIZE, evolved_POPSIZE, evolvedSystemSize;
StrategyCreator creator;
Random rd = new Random();
public Evolver(int evolvedSystemSize, LevelStrategy[] originalPopulation, int evolved_POPSIZE) {
this.evolvedSystemSize = evolvedSystemSize;
this.originalPopulation = originalPopulation;
this.evolved_POPSIZE = evolved_POPSIZE;
evolved_population = new LevelStrategy[evolved_POPSIZE];
tsize = MasterVariables.TSIZE;
POPSIZE = originalPopulation.length;
creator = new StrategyCreator();
checkErrors();
}
public Evolver(){
}
public LevelStrategy[] call() {
int indivs, parent1 = -99, parent2 = -99, parent = -99;
int mod_crossovers;
if (evolvedSystemSize == 2)
mod_crossovers = 0;
else
mod_crossovers = (int) (evolved_POPSIZE * MasterVariables.MOD_CROSSOVER_PROB);
for (indivs = 0; indivs < mod_crossovers; indivs++) {
evolved_population[indivs] = new LevelStrategy(evolvedSystemSize, originalPopulation[tournament(
originalPopulation, tsize)].init_strategy,
originalPopulation[tournament(originalPopulation, tsize)].balance_strategy,
originalPopulation[tournament(originalPopulation, tsize)].join_strategy);
}
char[][] init_strategy = new char[evolved_POPSIZE - mod_crossovers][], balance_strategy = null, join_strategy = null;
double random;
for (indivs = 0; indivs < evolved_POPSIZE - mod_crossovers; indivs++) {
random = rd.nextDouble() * (1 - MasterVariables.MOD_CROSSOVER_PROB);
if (random < MasterVariables.REPLICATION_PROB) {
parent = tournament(originalPopulation, MasterVariables.TSIZE);
init_strategy[indivs] = originalPopulation[parent].init_strategy;
parent = -99;
} else if ((random - MasterVariables.REPLICATION_PROB) < MasterVariables.CROSSOVER_PROB) {
parent1 = tournament(originalPopulation, MasterVariables.TSIZE);
parent2 = tournament(originalPopulation, MasterVariables.TSIZE);
init_strategy[indivs] = crossover(originalPopulation[parent1].init_strategy,
originalPopulation[parent2].init_strategy);
parent1 = -99;
parent2 = -99;
} else if ((random - (MasterVariables.CROSSOVER_PROB + MasterVariables.REPLICATION_PROB)) < MasterVariables.SUBTREE_MUT_PROB) {
parent = tournament(originalPopulation, MasterVariables.TSIZE);
init_strategy[indivs] = subtreeMutation(originalPopulation[parent].init_strategy,
MasterVariables.SIMULATECONSTRUCTIVISM);
parent = -99;
} else if ((random - (MasterVariables.CROSSOVER_PROB + MasterVariables.REPLICATION_PROB + MasterVariables.SUBTREE_MUT_PROB)) < MasterVariables.PMUT_PROB) {
parent = tournament(originalPopulation, MasterVariables.TSIZE);
init_strategy[indivs] = pointMutation(originalPopulation[parent].init_strategy,
MasterVariables.PMUT_PER_NODE, MasterVariables.SIMULATECONSTRUCTIVISM);
} else {
init_strategy[indivs] = creator.create_random_indiv(MasterVariables.DEPTH,
MasterVariables.SIMULATECONSTRUCTIVISM);
}
}
if (evolvedSystemSize > 2) {
balance_strategy = new char[evolved_POPSIZE - mod_crossovers][];
join_strategy = new char[evolved_POPSIZE - mod_crossovers][];
int rand;
for (indivs = 0; indivs < evolved_POPSIZE - mod_crossovers; indivs++) {
random = rd.nextDouble() * (1 - MasterVariables.MOD_CROSSOVER_PROB);
if (random < MasterVariables.REPLICATION_PROB) {
parent = tournament(originalPopulation, MasterVariables.TSIZE);
balance_strategy[indivs] = originalPopulation[parent].balance_strategy;
join_strategy[indivs] = originalPopulation[parent].join_strategy;
parent = -99;
} else if ((random - MasterVariables.REPLICATION_PROB) < MasterVariables.CROSSOVER_PROB) {
parent1 = tournament(originalPopulation, MasterVariables.TSIZE);
parent2 = tournament(originalPopulation, MasterVariables.TSIZE);
rand = rd.nextInt(2);
if (rand == 0) {
balance_strategy[indivs] = crossover(originalPopulation[parent1].balance_strategy,
originalPopulation[parent2].balance_strategy);
join_strategy[indivs] = originalPopulation[parent1].join_strategy;
} else {
balance_strategy[indivs] = originalPopulation[parent1].balance_strategy;
join_strategy[indivs] = crossover(originalPopulation[parent1].join_strategy,
originalPopulation[parent2].join_strategy);
}
parent1 = -99;
parent2 = -99;
} else if ((random - (MasterVariables.CROSSOVER_PROB + MasterVariables.REPLICATION_PROB)) < MasterVariables.SUBTREE_MUT_PROB) {
parent = tournament(originalPopulation, MasterVariables.TSIZE);
rand = rd.nextInt(2);
if (rand == 0) {
balance_strategy[indivs] = subtreeMutation(originalPopulation[parent].balance_strategy,
MasterVariables.SIMULATECONSTRUCTIVISM);
join_strategy[indivs] = originalPopulation[parent].join_strategy;
} else {
balance_strategy[indivs] = originalPopulation[parent].balance_strategy;
join_strategy[indivs] = subtreeMutation(originalPopulation[parent].join_strategy,
MasterVariables.SIMULATECONSTRUCTIVISM);
}
parent = -99;
} else if ((random - (MasterVariables.CROSSOVER_PROB + MasterVariables.REPLICATION_PROB + MasterVariables.SUBTREE_MUT_PROB)) < MasterVariables.PMUT_PROB) {
parent = tournament(originalPopulation, MasterVariables.TSIZE);
rand = rd.nextInt(2);
if (rand == 0) {
balance_strategy[indivs] = pointMutation(originalPopulation[parent].balance_strategy,
MasterVariables.PMUT_PER_NODE, MasterVariables.SIMULATECONSTRUCTIVISM);
join_strategy[indivs] = originalPopulation[parent].join_strategy;
} else {
balance_strategy[indivs] = originalPopulation[parent].balance_strategy;
join_strategy[indivs] = pointMutation(originalPopulation[parent].join_strategy,
MasterVariables.PMUT_PER_NODE, MasterVariables.SIMULATECONSTRUCTIVISM);
}
parent = -99;
} else {
parent = tournament(originalPopulation, MasterVariables.TSIZE);
rand = rd.nextInt(2);
if (rand == 0) {
balance_strategy[indivs] = creator.create_random_indiv(MasterVariables.DEPTH,
MasterVariables.SIMULATECONSTRUCTIVISM);
join_strategy[indivs] = originalPopulation[parent].join_strategy;
} else {
balance_strategy[indivs] = originalPopulation[parent].balance_strategy;
join_strategy[indivs] = creator.create_random_indiv(MasterVariables.DEPTH,
MasterVariables.SIMULATECONSTRUCTIVISM);
}
parent = -99;
}
}
}
if (evolvedSystemSize == 2)
for (indivs = mod_crossovers; indivs < evolved_POPSIZE; indivs++)
evolved_population[indivs] = new LevelStrategy(evolvedSystemSize,
init_strategy[indivs - mod_crossovers].clone());
else
for (indivs = mod_crossovers; indivs < evolved_POPSIZE; indivs++)
evolved_population[indivs] = new LevelStrategy(evolvedSystemSize,
init_strategy[indivs - mod_crossovers].clone(), balance_strategy[indivs - mod_crossovers].clone(),
join_strategy[indivs - mod_crossovers].clone());
return evolved_population;
}
int tournament(LevelStrategy[] originalPopulation, int tsize) {
int best = rd.nextInt(originalPopulation.length), i, competitor;
double fbest = -1.0e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(originalPopulation.length);
if (originalPopulation[competitor].fitness > fbest) {
fbest = originalPopulation[competitor].fitness;
best = competitor;
}
}
return (best);
}
int negativeTournament(LevelStrategy[] originalPopulation, int tsize) {
int worst = rd.nextInt(originalPopulation.length), i, competitor;
double fworst = 1.0e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(originalPopulation.length);
if (originalPopulation[competitor].fitness < fworst) {
fworst = originalPopulation[competitor].fitness;
worst = competitor;
}
}
return (worst);
}
char[] crossover(char[] parent1, char[] parent2) {
int xo1start, xo1end, xo2start, xo2end;
char[] offspring;
int len1 = traverse(parent1, 0);
int len2 = traverse(parent2, 0);
int lenoff;
xo1start = 1 + rd.nextInt(len1 - 1); // 1+ because the root of the tree
// shouldn't be replaced
xo1end = traverse(parent1, xo1start);
xo2start = rd.nextInt(len2);
while ((parent2[xo2start] < MasterVariables.FSET_2_START && parent1[xo1start] >= MasterVariables.FSET_2_START)
|| (parent2[xo2start] >= MasterVariables.FSET_2_START && parent1[xo1start] < MasterVariables.FSET_2_START))
xo2start = rd.nextInt(len2);
xo2end = traverse(parent2, xo2start);
lenoff = xo1start + (xo2end - xo2start) + (len1 - xo1end);
offspring = new char[lenoff];
System.arraycopy(parent1, 0, offspring, 0, xo1start);
System.arraycopy(parent2, xo2start, offspring, xo1start, (xo2end - xo2start));
System.arraycopy(parent1, xo1end, offspring, xo1start + (xo2end - xo2start), (len1 - xo1end));
return (offspring);
}
char[] pointMutation(char[] parent, double pmut, boolean simulateConstructivism) {
int len = traverse(parent, 0), i;
int mutsite;
char[] parentcopy = new char[len];
System.arraycopy(parent, 0, parentcopy, 0, len);
for (i = 0; i < len; i++) {
if (rd.nextDouble() < pmut) {
mutsite = i;
if (parentcopy[mutsite] < MasterVariables.FSET_1_START) {
char prim = (char) rd.nextInt(2);
if (prim == 0)
if (simulateConstructivism == false)
prim = (char) (MasterVariables.TSET_1_START + rd.nextInt(MasterVariables.TSET_1_END
- MasterVariables.TSET_1_START + 1));
else
prim = (char) (MasterVariables.TSET_1_START + rd.nextInt(MasterVariables.TSET_2_END
- MasterVariables.TSET_1_START + 1));
else
prim = (char) rd.nextDouble();
parentcopy[mutsite] = prim;
} else
switch (parentcopy[mutsite]) {
case MasterVariables.ADD:
case MasterVariables.SUB:
case MasterVariables.MUL:
case MasterVariables.DIV:
parentcopy[mutsite] = (char) (rd.nextInt(MasterVariables.FSET_1_END
- MasterVariables.FSET_1_START + 1) + MasterVariables.FSET_1_START);
break;
case MasterVariables.GT:
parentcopy[mutsite] = (char) (rd.nextInt(MasterVariables.FSET_2_END
- MasterVariables.FSET_2_START + 1) + MasterVariables.FSET_2_START);
;
break;
case MasterVariables.LT:
parentcopy[mutsite] = (char) (rd.nextInt(MasterVariables.FSET_2_END
- MasterVariables.FSET_2_START + 1) + MasterVariables.FSET_2_START);
;
break;
case MasterVariables.EQ:
parentcopy[mutsite] = (char) (rd.nextInt(MasterVariables.FSET_2_END
- MasterVariables.FSET_2_START + 1) + MasterVariables.FSET_2_START);
;
break;
case MasterVariables.AND:
parentcopy[mutsite] = MasterVariables.OR;
break;
case MasterVariables.OR:
parentcopy[mutsite] = MasterVariables.AND;
break;
}
}
}
return (parentcopy);
}
char[] subtreeMutation(char[] parent, boolean simulateConstructivism) {
int mutStart, mutEnd, parentLen = traverse(parent, 0), subtreeLen, lenOff;
char[] newSubtree, offspring;
// Calculate the mutation starting point.
mutStart = rd.nextInt(parentLen - 1);
mutEnd = traverse(parent, mutStart);
// Grow new subtree. If the replaced tree returned boolean, make sure
// the new subtree returns boolean as well. The new subtree cannot be
// more
// than one level deeper than the replaced one
if (parent[mutStart] >= MasterVariables.FSET_2_START)
newSubtree = creator.grow(1 + rd.nextInt((int) (Math.log(2 + mutEnd - mutStart) / Math.log(2))), true, simulateConstructivism);
else
newSubtree = creator.grow(rd.nextInt(1 + (int) (Math.log(2 + mutEnd - mutStart) / Math.log(2))), false, simulateConstructivism);
subtreeLen = traverse(newSubtree, 0);
lenOff = mutStart + subtreeLen + (parentLen - mutEnd);
offspring = new char[lenOff];
System.arraycopy(parent, 0, offspring, 0, mutStart);
System.arraycopy(newSubtree, 0, offspring, mutStart, subtreeLen);
System.arraycopy(parent, mutEnd, offspring, (mutStart + subtreeLen), (parentLen - mutEnd));
return (offspring);
}
int traverse(char[] buffer, int buffercount) {
if (buffer[buffercount] < MasterVariables.FSET_1_START)
return (++buffercount);
switch (buffer[buffercount]) {
case MasterVariables.ADD:
case MasterVariables.SUB:
case MasterVariables.MUL:
case MasterVariables.DIV:
case MasterVariables.GT:
case MasterVariables.LT:
case MasterVariables.EQ:
case MasterVariables.AND:
case MasterVariables.OR:
return (traverse(buffer, traverse(buffer, ++buffercount)));
}
return (0); // should never get here
}
private void checkErrors() {
if (originalPopulation == null || evolved_population == null || evolvedSystemSize < 2
|| evolvedSystemSize > MasterVariables.MAXSYSTEM || evolved_POPSIZE < 1 ) {
System.out.println("Evolver class error!!");
System.exit(0);
}
}
}
|
package com.jit.consumer02;
import java.util.ArrayList;
import java.util.function.Consumer;
class Test {
public static void main(String[] args) {
ArrayList<Movie> l = new ArrayList<Movie>();
populate(l);
Consumer<Movie> c = m -> {
System.out.println("Movie Name:" + m.name);
System.out.println("Movie Hero:" + m.hero);
System.out.println("Movie Heroine:" + m.heroine);
System.out.println();
};
for (Movie m : l) {
c.accept(m);
}
}
public static void populate(ArrayList<Movie> l) {
l.add(new Movie("Bahubali", "Prabhas", "Anushka"));
l.add(new Movie("Rayees", "Sharukh", "Sunny"));
l.add(new Movie("Dangal", "Ameer", "Ritu"));
l.add(new Movie("Sultan", "Salman", "Anushka"));
}
}
|
package edu.uag.iidis.scec.control;
import edu.uag.iidis.scec.vista.*;
import edu.uag.iidis.scec.modelo.*;
import edu.uag.iidis.scec.servicios.*;
import java.util.Collection;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
public final class MCUCrearTest
extends MappingDispatchAction {
private Log log = LogFactory.getLog(MCURegistrarUsuario.class);
public ActionForward solicitarCrearTest(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug(">solicitarListarTest");
}
// Verifica si la acción fue cancelada por el usuario
if (isCancelled(request)) {
if (log.isDebugEnabled()) {
log.debug("<La acción fue cancelada");
}
return (mapping.findForward("cancelar"));
}
FormaCrearTest forma = (FormaCrearTest)form;
ManejadorTest mr = new ManejadorTest();
Collection resultado = mr.generarTest(forma.getValor());
ActionMessages errores = new ActionMessages();
if (resultado != null) {
if ( resultado.isEmpty() ) {
errores.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors.registroVacio"));
saveErrors(request, errores);
} else {
forma.setTest( resultado );
}
return (mapping.findForward("exito"));
} else {
log.error("Ocurrió un error de infraestructura");
errores.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors.infraestructura"));
saveErrors(request, errores);
return ( mapping.findForward("fracaso") );
}
}
public ActionForward solicitarCrearHistorialTest(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug(">solicitarCrearHistorialTest");
}
// Verifica si la acción fue cancelada por el usuario
if (isCancelled(request)) {
if (log.isDebugEnabled()) {
log.debug("<La acción fue cancelada");
}
return (mapping.findForward("cancelar"));
}
FormaCrearHistorialTest forma = (FormaCrearHistorialTest)form;
ManejadorTest mr = new ManejadorTest();
Collection resultado = mr.generarHistorialTest(forma.getValor());
ActionMessages errores = new ActionMessages();
if (resultado != null) {
if ( resultado.isEmpty() ) {
errores.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors.registroVacio"));
saveErrors(request, errores);
} else {
forma.setHistoriatest( resultado );
}
return (mapping.findForward("exito"));
} else {
log.error("Ocurrió un error de infraestructura");
errores.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors.infraestructura"));
saveErrors(request, errores);
return ( mapping.findForward("fracaso") );
}
}
public ActionForward procesarCrearTest(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug(">procesarRegistroHistorial");
}
// Verifica si la acción fue cancelada por el usuario
if (isCancelled(request)) {
if (log.isDebugEnabled()) {
log.debug("<La acción fue cancelada");
}
return (mapping.findForward("cancelar"));
}
// Se obtienen los datos para procesar el registro
FormaCrearTest forma = (FormaCrearTest)form;
ArrayList<Historial> historiales=new ArrayList();
// Collection historiales;
Long[] respuestas=forma.getRespuestas();
Long[] preguntas=forma.getPreguntas();
Long tempo=new Long("0");
if(log.isDebugEnabled()){
log.debug("Aqui:***"+forma.getName());
if(respuestas==null||preguntas==null){
log.debug("Arreglo es nulo+++++");
}else{}}
for(int a=0;a<respuestas.length;a++){
if(preguntas[a]==null||respuestas[a]==null){log.debug("breaking at "+a);break;}
else{
log.debug("Historial "+a);
Historial historial = new Historial(forma.getidTest(),preguntas[a],respuestas[a],tempo,forma.getName());
historiales.add(historial);}
}
ManejadorHistorial mr= new ManejadorHistorial();
int resultado = mr.crearHistorial(historiales);
ActionMessages errores = new ActionMessages();
switch (resultado) {
case 0:
return (mapping.findForward("exito"));
case 1:
/* errores.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors.nombreHistorialYaExiste",
forma.getNombres()));
saveErrors(request, errores);*/
return (mapping.getInputForward());
case 3:
log.error("Ocurrió un error de infraestructura");
errores.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors.infraestructura"));
saveErrors(request, errores);
return (mapping.getInputForward());
default:
log.warn("ManejadorUsuario.crearUsuario regresó reultado inesperado");
errores.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("errors.infraestructura"));
saveErrors(request, errores);
return (mapping.getInputForward());
}
}
} |
package com.ilids.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.ilids.dao.BookRepository;
import com.ilids.domain.Book;
import com.ilids.domain.User;
@Component
@Transactional
public class BookService {
@Autowired
private UserService userService;
@Autowired
private BookRepository bookRepository;
public List<Book> getAllBooks() {
return bookRepository.getAll();
}
public Book findById(Long id) {
return bookRepository.findById(id);
}
public Book remove(Long id) {
Book book = bookRepository.findById(id);
if (book == null) {
throw new IllegalArgumentException();
}
book.getUser().getBooks().remove(book); //pre remove
bookRepository.delete(book);
return book;
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
public boolean addBookToUser(String bookname, String username) {
Book book = createBook(bookname);
User user = userService.findByCustomField("username", username);
if (user == null) {
throw new IllegalArgumentException();
}
user.addBook(book);
userService.persist(user);
return true;
}
private Book createBook(String name) {
return new Book(name);
}
}
|
package com.mc.library.widgets;
import android.content.Context;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.Scroller;
/**
* 3D立体容器
*/
public class StereoLayout extends ViewGroup {
private static final String TAG = StereoLayout.class.getSimpleName();
private Context mContext;
private Camera mCamera;
private Matrix mMatrix;
private Scroller mScroller;
private VelocityTracker mVelocityTracker;
private int mScaledTouchSlop;
private int mMeasuredWidth;
private int mMeasuredHeight;
private static final int standerSpeed = 2000;
private static final int flingSpeed = 800;
private int mInitializationPosition = 1;
private float mAngle = 90;
private float mResistance = 1.8f;
private boolean m3DEnable = true;
private int mCurrentPosition = mInitializationPosition;
private int addCount;//记录手离开屏幕后,需要新增的页面次数
private int alreadyAdd;//对滑动多页时的已经新增页面次数的记录
private boolean isAdding;//fling时正在添加新页面,在绘制时不需要开启camera绘制效果,否则页面会有闪动
private IStereoListener mIStereoListener;
private float mDownX, mDownY;
private boolean isSliding;
private State mState = State.Normal;
public StereoLayout(Context context) {
this(context, null);
}
public StereoLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public StereoLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
mScaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mCamera = new Camera();
mMatrix = new Matrix();
mScroller = new Scroller(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measureChildren(widthMeasureSpec, heightMeasureSpec);
mMeasuredWidth = getMeasuredWidth();
mMeasuredHeight = getMeasuredHeight();
scrollTo(0, mInitializationPosition * mMeasuredHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childTop = 0;
for (int i = 0; i < getChildCount(); i++) {
View childView = getChildAt(i);
if (childView.getVisibility() != View.GONE) {
childView.layout(0, childTop, childView.getMeasuredWidth(), childTop + childView.getMeasuredHeight());
childTop = childTop + childView.getMeasuredHeight();
}
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
float x = ev.getX();
float y = ev.getY();
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
isSliding = false;
mDownX = x;
mDownY = y;
if (!mScroller.isFinished()) {
//当上一次滑动没有结束时,再次点击,强制滑动在点击位置结束
mScroller.setFinalY(mScroller.getCurrY());
mScroller.abortAnimation();
scrollTo(0, getScrollY());
isSliding = true;
}
break;
case MotionEvent.ACTION_MOVE:
if (!isSliding) {
isSliding = isCanSliding(ev);
}
break;
default:
break;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return isSliding;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_MOVE:
if (isSliding) {
int realDelta = (int) (mDownY - y);
mDownY = y;
if (mScroller.isFinished()) {
//因为要循环滚动
recycleMove(realDelta);
}
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (isSliding) {
isSliding = false;
mVelocityTracker.computeCurrentVelocity(1000);
float yVelocity = mVelocityTracker.getYVelocity();
//滑动的速度大于规定的速度,或者向上滑动时,上一页页面展现出的高度超过1/2。则设定状态为State.ToPrevious
if (yVelocity > standerSpeed || ((getScrollY() + mMeasuredHeight / 2) / mMeasuredHeight < mInitializationPosition)) {
mState = State.ToPrevious;
} else if (yVelocity < -standerSpeed || ((getScrollY() + mMeasuredHeight / 2) / mMeasuredHeight > mInitializationPosition)) {
//滑动的速度大于规定的速度,或者向下滑动时,下一页页面展现出的高度超过1/2。则设定状态为State.ToNext
mState = State.ToNext;
} else {
mState = State.Normal;
}
//根据mState进行相应的变化
changeByState(yVelocity);
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
}
return super.onTouchEvent(event);
}
public boolean isCanSliding(MotionEvent ev) {
float moveX;
float moveY;
moveX = ev.getX();
moveY = ev.getY();
if (Math.abs(moveY - mDownX) > mScaledTouchSlop && (Math.abs(moveY - mDownY) > (Math.abs(moveX - mDownX)))) {
return true;
}
return false;
}
private void changeByState(float yVelocity) {
alreadyAdd = 0;//重置滑动多页时的计数
if (getScrollY() != mMeasuredHeight) {
switch (mState) {
case Normal:
toNormalAction();
break;
case ToPrevious:
toPreviousAction(yVelocity);
break;
case ToNext:
toNextAction(yVelocity);
break;
}
invalidate();
}
}
/**
* mState = State.Normal 时进行的动作
*/
private void toNormalAction() {
int startY;
int delta;
int duration;
mState = State.Normal;
addCount = 0;
startY = getScrollY();
delta = mMeasuredHeight * mInitializationPosition - getScrollY();
duration = (Math.abs(delta)) * 4;
mScroller.startScroll(0, startY, 0, delta, duration);
}
/**
* mState = State.ToPrevious 时进行的动作
*
* @param yVelocity 竖直方向的速度
*/
private void toPreviousAction(float yVelocity) {
int startY;
int delta;
int duration;
mState = State.ToPrevious;
addPre();//增加新的页面
//计算松手后滑动的item个数
int flingSpeedCount = (yVelocity - standerSpeed) > 0 ? (int) (yVelocity - standerSpeed) : 0;
addCount = flingSpeedCount / flingSpeed + 1;
//mScroller开始的坐标
startY = getScrollY() + mMeasuredHeight;
setScrollY(startY);
//mScroller移动的距离
delta = -(startY - mInitializationPosition * mMeasuredHeight) - (addCount - 1) * mMeasuredHeight;
duration = (Math.abs(delta)) * 3;
mScroller.startScroll(0, startY, 0, delta, duration);
addCount--;
}
/**
* mState = State.ToNext 时进行的动作
*
* @param yVelocity 竖直方向的速度
*/
private void toNextAction(float yVelocity) {
int startY;
int delta;
int duration;
mState = State.ToNext;
addNext();
int flingSpeedCount = (Math.abs(yVelocity) - standerSpeed) > 0 ? (int) (Math.abs(yVelocity) - standerSpeed) : 0;
addCount = flingSpeedCount / flingSpeed + 1;
startY = getScrollY() - mMeasuredHeight;
setScrollY(startY);
delta = mMeasuredHeight * mInitializationPosition - startY + (addCount - 1) * mMeasuredHeight;
Log.e(TAG, "多后一页startY " + startY + " yVelocity " + yVelocity + " delta " + delta + " getScrollY() " + getScrollY() + " addCount " + addCount);
duration = (Math.abs(delta)) * 3;
mScroller.startScroll(0, startY, 0, delta, duration);
addCount--;
}
@Override
public void computeScroll() {
//滑动没有结束时,进行的操作
if (mScroller.computeScrollOffset()) {
if (mState == State.ToPrevious) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY() + mMeasuredHeight * alreadyAdd);
if (getScrollY() < (mMeasuredHeight + 2) && addCount > 0) {
isAdding = true;
addPre();
alreadyAdd++;
addCount--;
}
} else if (mState == State.ToNext) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY() - mMeasuredHeight * alreadyAdd);
if (getScrollY() > (mMeasuredHeight) && addCount > 0) {
isAdding = true;
addNext();
addCount--;
alreadyAdd++;
}
} else {
//mState == State.Normal状态
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
}
postInvalidate();
}
//滑动结束时相关用于计数变量复位
if (mScroller.isFinished()) {
alreadyAdd = 0;
addCount = 0;
}
}
/**
* 把第一个item移动到最后一个item位置
*/
private void addNext() {
mCurrentPosition = (mCurrentPosition + 1) % getChildCount();
int childCount = getChildCount();
View view = getChildAt(0);
removeViewAt(0);
addView(view, childCount - 1);
if (mIStereoListener != null) {
mIStereoListener.toNext(mCurrentPosition);
}
}
/**
* 把最后一个item移动到第一个item位置
*/
private void addPre() {
mCurrentPosition = ((mCurrentPosition - 1) + getChildCount()) % getChildCount();
int childCount = getChildCount();
View view = getChildAt(childCount - 1);
removeViewAt(childCount - 1);
addView(view, 0);
if (mIStereoListener != null) {
mIStereoListener.toPrevious(mCurrentPosition);
}
}
private void recycleMove(int delta) {
delta = delta % mMeasuredHeight;
delta = (int) (delta / mResistance);
if (Math.abs(delta) > mMeasuredHeight / 4) {
return;
}
scrollBy(0, delta);
if (getScrollY() < 5 && mInitializationPosition != 0) {
addPre();
scrollBy(0, mMeasuredHeight);
} else if (getScrollY() > (getChildCount() - 1) * mMeasuredHeight - 5) {
addNext();
scrollBy(0, -mMeasuredHeight);
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
if (!isAdding && m3DEnable) {
//当开启3D效果并且当前状态不属于 computeScroll中 addPre() 或者addNext()
//如果不做这个判断,addPre() 或者addNext()时页面会进行闪动一下
//我当时写的时候就被这个坑了,后来通过log判断,原来是computeScroll中的onlayout,和子Child的draw触发的顺序导致的。
//知道原理的朋友希望可以告知下
for (int i = 0; i < getChildCount(); i++) {
drawScreen(canvas, i, getDrawingTime());
}
} else {
isAdding = false;
super.dispatchDraw(canvas);
}
}
private void drawScreen(Canvas canvas, int i, long drawingTime) {
int curScreenY = mMeasuredHeight * i;
//屏幕中不显示的部分不进行绘制
if (getScrollY() + mMeasuredHeight < curScreenY) {
return;
}
if (curScreenY < getScrollY() - mMeasuredHeight) {
return;
}
float centerX = mMeasuredWidth / 2;
float centerY = (getScrollY() > curScreenY) ? curScreenY + mMeasuredHeight : curScreenY;
float degree = mAngle * (getScrollY() - curScreenY) / mMeasuredHeight;
if (degree > 90 || degree < -90) {
return;
}
canvas.save();
mCamera.save();
mCamera.rotateX(degree);
mCamera.getMatrix(mMatrix);
mCamera.restore();
mMatrix.preTranslate(-centerX, -centerY);
mMatrix.postTranslate(centerX, centerY);
canvas.concat(mMatrix);
drawChild(canvas, getChildAt(i), drawingTime);
canvas.restore();
}
public enum State {
Normal, ToPrevious, ToNext
}
public StereoLayout initPosition(int position) {
if (position <= 0 || position >= (getChildCount() - 1)) {
throw new IndexOutOfBoundsException("position ∈ (0, getChildCount() - 1)");
}
mInitializationPosition = position;
mCurrentPosition = position;
return this;
}
public StereoLayout setAngle(float angle) {
if (angle < 0.0f || angle > 180.0f) {
throw new IndexOutOfBoundsException("angle ∈ [0.0f, 180.0f]");
}
mAngle = 180.0f - angle;
return this;
}
public StereoLayout setResistance(float resistance) {
if (resistance <= 0) {
throw new IllegalArgumentException("resistance ∈ (0, ...)");
}
mResistance = resistance;
return this;
}
public StereoLayout set3DEnable(boolean enable) {
m3DEnable = enable;
return this;
}
public StereoLayout setInterpolator(Interpolator interpolator) {
if (interpolator == null) {
throw new NullPointerException("interpolator == null");
}
mScroller = new Scroller(mContext, interpolator);
return this;
}
public StereoLayout toPosition(int position) {
if (position < 0 || position > (getChildCount() - 1)) {
throw new IndexOutOfBoundsException("position ∈ [0, getChildCount() - 1]");
}
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
if (position > mCurrentPosition) {
// setScrollY(mInitializationPosition * mMeasuredHeight);
toNextAction(-standerSpeed - flingSpeed * (position - mCurrentPosition - 1));
} else if (position < mCurrentPosition) {
// setScrollY(mInitializationPosition * mMeasuredHeight);
toPreviousAction(standerSpeed + (mCurrentPosition - position - 1) * flingSpeed);
}
return this;
}
public StereoLayout toPrevious() {
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
toPreviousAction(standerSpeed);
return this;
}
public StereoLayout toNext() {
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
toNextAction(-standerSpeed);
return this;
}
public void setIStereoListener(IStereoListener stereoListener) {
mIStereoListener = stereoListener;
}
public interface IStereoListener {
void toPrevious(int position);
void toNext(int position);
}
} |
package cs414.a5.bawitt.common;
public interface ElectronicPayment extends java.rmi.Remote{
boolean isAccountValid() throws java.rmi.RemoteException;;
boolean isDateValid() throws java.rmi.RemoteException;;
boolean isActNumValid() throws java.rmi.RemoteException;;
boolean isExpDateInFuture() throws java.rmi.RemoteException;
} |
package service;
import model.Book;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface BookService {
Page<Book> findAll(Pageable pageable) ;
Book findById(Long id);
Book save(Book customer);
Book remove(Long id);
Page<Book> findAllByNameContaining(String name, Pageable pageable);
}
|
/*
* Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webui.common.i18n;
import pl.edu.icm.unity.server.utils.UnityMessageSource;
import pl.edu.icm.unity.types.I18nString;
import com.vaadin.ui.TextField;
/**
* Custom field allowing for editing an {@link I18nString}, i.e. a string in several languages.
* By default the default locale is only shown, but a special button can be clicked to show text fields
* to enter translations.
*
* @author K. Benedyczak
*/
public class I18nTextField extends Abstract18nField<TextField>
{
public I18nTextField(UnityMessageSource msg)
{
super(msg);
initUI();
}
public I18nTextField(UnityMessageSource msg, String caption)
{
super(msg, caption);
initUI();
}
@Override
protected TextField makeFieldInstance()
{
return new TextField();
}
}
|
package sop.web.management;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import dwz.web.BaseController;
import net.sf.jxls.transformer.XLSTransformer;
import sop.persistence.beans.Checklist;
//import sop.persistence.beans.Employee;
import sop.services.ChecklistServiceMgr;
/**
* @Author: LCF
* @Date: 2020/1/9 12:43
* @Package: sop.web.management
*/
@Controller("management.checklistController")
@RequestMapping(value = "/management/checklist")
public class ChecklistController extends BaseController {
@Autowired
private ChecklistServiceMgr checklistServiceMgr;
@RequestMapping("/desktop")
public String list() {
return "/management/itemmaster/desktop/desk1";
}
@RequestMapping("/export")
public void export(HttpServletRequest request, HttpServletResponse response) {
// 上面的路径:D:\RRR\project\sop-web\src\main\webapp\resources\itemmaster\templateFileName.xlsx (系统找不到指定的路径。)
String templateFileName = request.getSession().getServletContext()
.getRealPath("/")
+ "/templateFileName.xlsx";
// String templateFileName = ChecklistController.class.getClassLoader().getResource("/itemmaster/templateFileName.xlsx").toString();
String destFileName = "destFileName.xlsx";
// Employee test1 = new Employee(1, "test1");
// // 模拟数据
// List<Employee> staff = new ArrayList<Employee>();
// staff.add(new Employee(1, "test1"));
// staff.add(new Employee(2, "test2"));
// staff.add(new Employee(3, "test3"));
Map<String, Object> beans = new HashMap<String, Object>();
// beans.put("employees", staff);
// beans.put("test1", test1);
XLSTransformer transformer = new XLSTransformer();
InputStream in = null;
OutputStream out = null;
// 设置响应
response.setHeader("Content-Disposition", "attachment;filename="
+ destFileName);
response.setContentType("application/vnd.ms-excel");
try {
in = new BufferedInputStream(new FileInputStream(templateFileName));
Workbook workbook = transformer.transformXLS(in, beans);
out = response.getOutputStream();
// 将内容写入输出流并把缓存的内容全部发出去
workbook.write(out);
out.flush();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
@RequestMapping("/view/{fkOrderProduct}")
public String viewChecklist(@PathVariable("fkOrderProduct") Integer fkOrderProduct, Model model) {
Checklist checklist = checklistServiceMgr.getDetailsByFkOrderProduct(fkOrderProduct);
model.addAttribute("checklist", checklist);
model.addAttribute("fkOrderProduct", fkOrderProduct);
return "/management/order/viewchecklist";
}
}
|
package com.example.android.inventory;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class ProductDetailActivity extends AppCompatActivity
{
private EditText mQuantityField;
private EditText mPriceField;
private TextView mProductNameField;
private ImageView mImageView;
private int mQuantity;
private ArrayList<Product> mProductList;
private InventoryDataSource mDataSource;
private InventoryApplication mInventoryApplication;
private Product mProduct;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mInventoryApplication = (InventoryApplication) getApplication();
mProductList = mInventoryApplication.mProductList;
mDataSource = mInventoryApplication.mDataSource;
setContentView(R.layout.activity_product_detail);
Intent intent = getIntent();
int productIndex = intent.getIntExtra("product_index", 0);
mProduct = mProductList.get(productIndex);
mQuantity = mProduct.getQuantity();
mQuantityField = (EditText) findViewById(R.id.product_quantity_field);
mQuantityField.setText("" + mQuantity);
mPriceField = (EditText) findViewById(R.id.product_price_field);
mPriceField.setText(Util.formatPrice(mProduct.getPriceInCents()));
mPriceField.setOnEditorActionListener(
new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
if(actionId == EditorInfo.IME_ACTION_DONE)
{
updatePrice();
}
return false;
}
});
mProductNameField = (TextView) findViewById(R.id.product_name_field);
mProductNameField.setText("" + mProduct.getName());
mImageView = (ImageView) findViewById(R.id.product_image_view);
String imagePath = mProduct.getImagePath();
Log.d("Image:", imagePath);
try
{
File directory = this.getDir("images", Context.MODE_PRIVATE);
File mypath = new File(directory,imagePath);
FileInputStream fis = new FileInputStream(mypath);
Bitmap bitmap = BitmapFactory.decodeStream(fis);
mImageView.setImageBitmap(bitmap);
}
catch (Exception e)
{
Util.showToast(this, "Unable to open image");
}
}
private void updatePrice()
{
try
{
int price = getPrice();
setPrice(price);
}
catch (Exception e)
{
Toast.makeText(this, R.string.invalid_price_message, Toast.LENGTH_SHORT);
}
}
private void setPrice(int aPriceInCents)
{
String priceString = Util.formatPrice(aPriceInCents);
mPriceField.setText(priceString);
mDataSource.updatePrice(mProduct, aPriceInCents);
}
private int getPrice()
{
String mPriceString = mPriceField.getText().toString();
return Util.priceFromString(mPriceString);
}
public void onIncreaseQuantity(View aView)
{
mQuantity++;
updateQuantity();
}
public void onDecreaseQuantity(View aView)
{
if (mQuantity > 1)
{
mQuantity--;
updateQuantity();
}
}
public void onRemoveProduct(View aView)
{
new AlertDialog.Builder(this)
.setMessage(getString(R.string.dialog_remove_entry_text))
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onDoRemoveProduct();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
public void onOrderProduct(View aView)
{
String subject = "Product order";
String body =
"Hi, \n\n"
+ "I would like to order 10 more boxes of "
+ mProduct.getName() + ".\n\n"
+ "Kind Regards";
composeEmail(subject, body);
}
public void onDoRemoveProduct()
{
mDataSource.deleteProduct(mProduct);
mProductList.remove(mProduct);
mProduct = null;
finish();
}
private void updateQuantity()
{
mQuantityField.setText(Integer.toString(mQuantity));
mDataSource.updateQuantity(mProduct, mQuantity);
}
public void composeEmail(String subject, String text)
{
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, text);
if (intent.resolveActivity(getPackageManager()) != null)
{
startActivity(intent);
}
}
}
|
package interfaces;
public interface AbstractRoom {
void create();
}
|
package com.infoworks.ml.domain.detectors;
import com.it.soul.lab.sql.entity.Entity;
import com.it.soul.lab.sql.entity.Ignore;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import java.util.Map;
/**
* An immutable result returned by a Classifier describing what was recognized.
*/
public class Recognition extends Entity {
/**
*
*/
@Ignore
public static final String NONE_ITEM = "item {\n" +
"\tid: 0, \n" +
"\tname: 'none' \n" +
"}";
/**
* A unique identifier for what has been recognized. Specific to the class, not the instance of
* the object.
*/
private final String id;
/**
* Display name for the recognition.
*/
private final String title;
/**
* A sortable score for how good the recognition is relative to others. Higher should be better.
*/
private final Float confidence;
/** Optional location within the source image for the location of the recognized object. */
@Ignore
private Rectangle2D location;
public Recognition(final String id, final String title, final Float confidence, Rectangle2D location) {
this.id = id;
this.title = title;
this.confidence = confidence;
this.location = location;
}
public Recognition(final String objDetectLabel, final Float confidence) {
this(objDetectLabel, confidence, null);
}
public Recognition(final String objDetectLabel, final Float confidence, Rectangle2D location){
this.id = parseId(objDetectLabel);
this.title = parseTitle(objDetectLabel);
this.confidence = confidence;
this.location = location;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public Float getConfidence() {
return confidence;
}
public Rectangle2D getLocation() {
return location;
}
public void setLocation(Rectangle2D location) {
this.location = location;
}
@Override
public String toString() {
String resultString = "";
if (id != null) {
resultString += "[" + id + "] ";
}
if (title != null) {
resultString += title + " ";
}
if (confidence != null) {
resultString += String.format("(%.1f%%) ", confidence * 100.0f);
}
if (location != null) {
resultString += location + " ";
}
return resultString.trim();
}
protected final String parseTitle(String objDetectLabel){
//item {id: 11, name: 'rocket_logo' }
String[] splits = objDetectLabel.split("name:");
if (splits.length >= 2){
return splits[1].trim()
.replace("}", "")
.trim()
.replace("'", "");
}
return "";
}
protected final String parseId(String objDetectLabel){
//item {id: 11, name: 'rocket_logo' }
String[] splits = objDetectLabel.split(", name:");
if (splits.length >= 1){
return splits[0].trim()
.replace("item {id:", "")
.trim();
}
return "";
}
public Map<String, Double> convertLocation() {
if (getLocation() != null){
Map<String, Double> map = new HashMap<>();
map.put("x", getLocation().getMinX());
map.put("y", getLocation().getMinY());
map.put("width", getLocation().getWidth());
map.put("height", getLocation().getHeight());
return map;
}
return null;
}
}
|
package com.github.fly_spring.demo12.conditional;
/**
* Linux下要创建的Bean类
* @author william
*
*/
public class LinuxListService implements ListService{
@Override
public String showListCmd() {
return "ls";
}
}
|
package test.java.cardprefixlist;
import test.java.cardprefixlist.exceptions.ParsingException;
import test.java.cardprefixlist.exceptions.ProcessingException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
import java.util.regex.Pattern;
/**
* @author Dimitrijs Fedotovs
*/
public class Parser {
private static final Pattern cardPattern = Pattern.compile("^\\d{12,24}$");
private static final Pattern panPattern = Pattern.compile("^\\d{6}$");
public boolean parseFile(String fileName, ParsedLineConsumer consumer, BiConsumer<Integer, String> errorConsumer) throws IOException {
boolean hasErrors = false;
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
int lineNo = 0;
while ((line = reader.readLine()) != null) {
lineNo++;
line = line.trim();
try {
parseLine(line, consumer);
} catch (ProcessingException ex) {
hasErrors = true;
errorConsumer.accept(lineNo, ex.getMessage());
}
}
}
return hasErrors;
}
public void parseLine(String line, ParsedLineConsumer consumer) throws ProcessingException {
String[] parts = line.split(",", 3);
if (parts.length < 3) {
throw new ParsingException("Invalid format");
}
int from = parsePrefix(parts[0]);
int to = parsePrefix(parts[1]);
String name = parts[2].trim();
consumer.accept(from, to, name);
}
public int parsePrefix(String pan) throws ProcessingException {
pan = pan.trim();
if (!panPattern.matcher(pan).matches()) {
throw new ParsingException("PAN should contain numbers only and should be 6 chars long");
}
return Integer.parseInt(pan);
}
public void processCardsPans(Supplier<String> supplier, BiConsumer<String, Integer> consumer, BiConsumer<String, String> errorConsumer) {
String cardNr;
while ((cardNr = supplier.get()) != null) {
try {
validateCardNumber(cardNr);
String strPan = cardNr.substring(0, 6);
int pan = Integer.parseInt(strPan);
consumer.accept(cardNr, pan);
} catch (ProcessingException ex) {
errorConsumer.accept(cardNr, ex.getMessage());
}
}
}
private void validateCardNumber(String cardNr) throws ProcessingException {
if (!cardPattern.matcher(cardNr).matches()) {
throw new ParsingException("Card should contain numbers only and should be 12-24 chars long");
}
}
@FunctionalInterface
public static interface ParsedLineConsumer {
public void accept(int from, int to, String name) throws ProcessingException;
}
} |
/*
* Copyright 2008-2018 shopxx.net. All rights reserved.
* Support: localhost
* License: localhost/license
* FileId: kdKWokUHSAjh4DtHC08l0kf6SDSjVoGV
*/
package net.bdsc.service.impl;
import java.util.List;
import javax.inject.Inject;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import net.bdsc.Page;
import net.bdsc.Pageable;
import net.bdsc.dao.DeliveryCenterDao;
import net.bdsc.entity.DeliveryCenter;
import net.bdsc.entity.Store;
import net.bdsc.service.DeliveryCenterService;
/**
* Service - 发货点
*
* @author 好源++ Team
* @version 6.1
*/
@Service
public class DeliveryCenterServiceImpl extends BaseServiceImpl<DeliveryCenter, Long> implements DeliveryCenterService {
@Inject
private DeliveryCenterDao deliveryCenterDao;
@Override
@Transactional(readOnly = true)
public DeliveryCenter findDefault(Store store) {
return deliveryCenterDao.findDefault(store);
}
@Override
@Transactional
public DeliveryCenter save(DeliveryCenter deliveryCenter) {
Assert.notNull(deliveryCenter, "[Assertion failed] - deliveryCenter is required; it must not be null");
if (BooleanUtils.isTrue(deliveryCenter.getIsDefault())) {
deliveryCenterDao.clearDefault(deliveryCenter.getStore());
}
return super.save(deliveryCenter);
}
@Override
@Transactional
public DeliveryCenter update(DeliveryCenter deliveryCenter) {
Assert.notNull(deliveryCenter, "[Assertion failed] - deliveryCenter is required; it must not be null");
DeliveryCenter pDeliveryCenter = super.update(deliveryCenter);
if (BooleanUtils.isTrue(pDeliveryCenter.getIsDefault())) {
deliveryCenterDao.clearDefault(pDeliveryCenter);
}
return pDeliveryCenter;
}
@Override
@Transactional(readOnly = true)
public Page<DeliveryCenter> findPage(Store store, Pageable pageable) {
return deliveryCenterDao.findPage(store, pageable);
}
@Override
@Transactional(readOnly = true)
public List<DeliveryCenter> findAll(Store store) {
return deliveryCenterDao.findAll(store);
}
} |
package dao;
import entity.DepotDraw_insert;
import entity.DepotDraw_select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class DepotDrawDao {
@Autowired
JdbcTemplate jdbcTemplate;
public List select(String sql, DepotDraw_select depotDraw_select) {
//System.out.println(depotDraw_select.toString());
return jdbcTemplate.queryForList(sql,depotDraw_select.getBdate(),depotDraw_select.getEdate(),depotDraw_select.getDraw_no(),depotDraw_select.getDept(),depotDraw_select.getStore(),depotDraw_select.getState(),depotDraw_select.getCreate());
}
public int insert(String sql, DepotDraw_insert depotDraw_insert) {
return jdbcTemplate.update(sql,depotDraw_insert.getDraw_insert_no(),depotDraw_insert.getStore(),depotDraw_insert.getDept(),depotDraw_insert.getCreate_emp(),depotDraw_insert.getDraw_date(),depotDraw_insert.getState(),depotDraw_insert.getMaker());
}
public int delete(String sql, String id) {
//System.out.println(sql+id);
return jdbcTemplate.update(sql,id);
}
public int audit(String sql, String id, String user) {
//System.out.println(sql+id+user);
return jdbcTemplate.update(sql,user,id);
}
public int remove(String sql, String id) {
return jdbcTemplate.update(sql,id);
}
public List detail_insert_select(String sql, String draw_no, String card_no) {
return jdbcTemplate.queryForList(sql,draw_no,card_no);
}
public int detail_insert(String sql, String draw_no, String card_no) {
//System.out.println(sql+draw_no+card_no);
return jdbcTemplate.update(sql,draw_no,card_no);
}
public List detail_select(String sql, String draw_no) {
return jdbcTemplate.queryForList(sql,draw_no);
}
public int detail_delete(String sql, String id) {
return jdbcTemplate.update(sql,id);
}
}
|
package info.gridworld.grid;
/**
* A <code>SparseGridNode</code> is a element of the linked list which used in a sparse array.
* @author Eduardo
*/
public class SparseGridNode
{
private Object occupant;
private int col;
private SparseGridNode next;//a Reference of next node
public SparseGridNode()
{
col = -1;
occupant = null;
next = null;
}
public SparseGridNode(int colNum, Object obj)
{
col = colNum;
occupant = obj;
next = null;
}
public void setNext(SparseGridNode s)
{
next = s;
}
public SparseGridNode getNext()
{
return next;
}
public int getColNum()
{
return col;
}
public Object getOccupant()
{
return occupant;
}
public Object setOccupant(Object obj)
{
Object oldOccupant = occupant;
occupant = obj;
return oldOccupant;
}
}
|
package com.xinhua.pipline;
import com.xinhua.api.domain.refOrder.RefOrderRequest;
import com.xinhua.api.domain.refOrder.RefOrderResponse;
import com.xinhua.api.domain.xDCBBean.*;
import com.xinhua.xdcb.*;
import javax.xml.namespace.QName;
import javax.xml.ws.Holder;
import java.math.BigDecimal;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by tanghao on 2015/9/17.
*/
public class PiplineUtils {
private static final QName SERVICE_NAME_DRCD = new QName("http://ws.daycancellationorder.exports.bankpolicy.impl.nb.tunan.nci.com/", "dodayCancellationOrder");
private static final QName SERVICE_NAME_XQJF = new QName("http://ws.resultrenewalpayment.irenewalpaymentucc.exports.counterchagre.interfaces.cap.tunan.nci.com/", "IRenewalPaymentUCCWSService");
private static final QName NEWORDER = new QName("http://ws.freshpolicysign.exports.bankpolicy.impl.nb.tunan.nci.com/", "FreshPolicySignAdapterImplService");
private static final QName SERVICE_NAME = new QName("http://ws.freshpolicysign.exports.bankpolicy.impl.nb.tunan.nci.com/", "FreshPolicySignAdapterImplService");
public PiplineUtils() {
}
public static com.xinhua.drcd.SysHeader pipHeader(){
//请求公共头
com.xinhua.drcd. SysHeader requestHeader = new com.xinhua.drcd.SysHeader();
return requestHeader;
}
/**
* 撤单
* @param request
* @return
*/
public static RefOrderResponse dodayCancellationOrder(RefOrderRequest request) {
URL wsdlURL = com.xinhua.drcd.DodayCancellationOrder.WSDL_LOCATION;
com.xinhua.drcd.DodayCancellationOrder ss = new com.xinhua.drcd.DodayCancellationOrder(wsdlURL, SERVICE_NAME_DRCD);
com.xinhua.drcd. IdayCancellationOrderAdapter port = ss.getDayCancellationOrderAdapterImplPort();
//请求报文体
com.xinhua.drcd.SrvReqBody reqBody = new com.xinhua.drcd.SrvReqBody();
//响应头
Holder<com.xinhua.drcd.SysHeader> resHeader = new Holder<com.xinhua.drcd.SysHeader>();
//响应体
Holder<com.xinhua.drcd.SrvResBody> resBody = new Holder<com.xinhua.drcd.SrvResBody>();
com.xinhua.drcd.SrvReqBizBody bizBody = new com.xinhua.drcd.SrvReqBizBody();
com.xinhua.drcd.DayCancellationOrderReqData dayCancellationOrderReqData = new com.xinhua.drcd.DayCancellationOrderReqData();
com.xinhua.drcd.PolicyTempVO policyTempVO = new com.xinhua.drcd.PolicyTempVO();
//投保单号
policyTempVO.setApplyCode(request.getPolNumber());
//交易发起方
policyTempVO.setTransSide(request.getTransSide());
//银行代码
policyTempVO.setBankCode(request.getBankCode());
//网点编码
policyTempVO.setBankBranchCode(request.getBranch());
dayCancellationOrderReqData.setPolicyTempVO(policyTempVO);
reqBody.setBizBody(bizBody);
bizBody.setInputData(dayCancellationOrderReqData);
port.dodayCancellationOrder(pipHeader(), reqBody, resHeader, resBody);
System.out.println("dodayCancellationOrder._dodayCancellationOrder_parametersResHeader=" + resHeader.value);
System.out.println("dodayCancellationOrder._dodayCancellationOrder_parametersResBody=" + resBody.value);
BigDecimal flag = resBody.value.getBizBody().getOutputData().getPolicyTempVO().getResultFlag();
String msg = resBody.value.getBizBody().getOutputData().getPolicyTempVO().getResultMsg();
String bankcode = resBody.value.getBizBody().getOutputData().getPolicyTempVO().getBankCode();
System.out.println(flag.toString());
System.out.println("#########################msg"+msg);
RefOrderResponse response = new RefOrderResponse();
response.setBankCode(bankcode);
response.setResultInfo(msg);
response.setResultCode(flag.toString());
return response;
}
/**
* 续期缴费
* @param request
* @return
*/
/* public static XuQJFResponse resultrenewalpayment(XuQJFRequest request) throws ParseException {
URL wsdlURL = IRenewalPaymentUCCWSService.WSDL_LOCATION;
IRenewalPaymentUCCWSService ss = new IRenewalPaymentUCCWSService(wsdlURL, SERVICE_NAME_XQJF);
com.xinhua.xqjf.IRenewalPaymentUCCWS port = ss.getIRenewalPaymentUCCWSPort();
//请求头
com.xinhua.xqjf.SysHeader header = new com.xinhua.xqjf.SysHeader();
//请求体
com.xinhua.xqjf.SrvReqBody reqBody = new com.xinhua.xqjf.SrvReqBody();
//响应头
Holder<com.xinhua.xqjf.SysHeader> resHeader = new Holder<com.xinhua.xqjf.SysHeader>();
//响应体
Holder<com.xinhua.xqjf.SrvResBody> resBody = new Holder<com.xinhua.xqjf.SrvResBody>();
com.xinhua.xqjf.SrvReqBizBody bizBody = new com.xinhua.xqjf.SrvReqBizBody();
com.xinhua.xqjf.RenewalPaymentInputData renewalPaymentInputData = new com.xinhua.xqjf.RenewalPaymentInputData();
renewalPaymentInputData.setFunctionFlag(request.getFunctionFlag());
List<RenewalPaymentInputInfo> renewalPaymentInputInfolist = new ArrayList();
RenewalPaymentInputInfo renewalPaymentInputInfo = new RenewalPaymentInputInfo();
renewalPaymentInputInfo.setActualBankAccount( request.getActualBankAccount());
renewalPaymentInputInfo.setActualBankCode(request.getActualBankCode());
renewalPaymentInputInfo.setHolderName(request.getHolderName());
renewalPaymentInputInfo.setPolicyCode(request.getPolicyCode());
renewalPaymentInputInfolist.add(renewalPaymentInputInfo);
*//**
* 网点代码,该字段在生成的RenewalPaymentInputInfo类中不存在
*//*
//request.getCipBranchBankCode();
bizBody.setInputData(renewalPaymentInputData);
reqBody.setBizBody(bizBody);
*//**
* 遍历循环节点reqCashDetailList
*//*
//银行上送的reqCashDetailList
//List<ReqCashDetailList> reqCashDetailList = request.getReqCashDetailList();
//上送给新核心的List
// List<RenewalPaymentInputInfo> renewalPaymentInputInfolist = new ArrayList();
//循环遍历,将银行上送的List转成新核心所需的List
//for(ReqCashDetailList reqCash:reqCashDetailList){
// RenewalPaymentInputInfo renewalPaymentInputInfo = new RenewalPaymentInputInfo();
//renewalPaymentInputInfo.setOrganCode(reqCash.getOrganCode());
//renewalPaymentInputInfo.setActualBankAccount(reqCash.getActualBankAccount());
//renewalPaymentInputInfo.setActualBankCode(reqCash.getActualBankCode());
//renewalPaymentInputInfo.setBusiProdCode(reqCash.getBusiProdCode());
//renewalPaymentInputInfo.setCertiCode(reqCash.getCertiCode());
//renewalPaymentInputInfo.setCertiType(reqCash.getCertiType());
//renewalPaymentInputInfo.setFeeAmount(new BigDecimal(reqCash.getFeeAmount()));
//renewalPaymentInputInfo.setFinishTime(DateUtils.strToXml(reqCash.getFinishTime(),"yyyy-MM-dd HH:mm:ss"));
//renewalPaymentInputInfo.setHandler(reqCash.getHandler());
//renewalPaymentInputInfo.setHolderId(new BigDecimal(reqCash.getHolderId()));
//renewalPaymentInputInfo.setHolderName(reqCash.getHolderName());
//renewalPaymentInputInfo.setPaidCount(new BigDecimal(reqCash.getPaidCount()));
//renewalPaymentInputInfo.setPayMode(reqCash.getPayMode());
//renewalPaymentInputInfo.setPolicyCode(reqCash.getPayMode());
//将遍历得到的数据Add到新核心所需的List
//renewalPaymentInputInfolist.add(renewalPaymentInputInfo);
//}
//将遍历后得到的List赋值
//renewalPaymentInputData.setCashDetailList(renewalPaymentInputInfolist);
*//**
* 遍历循环节点reqFpPrintNoList
*//*
//银行上送的reqFpPrintNoList
//List<ReqFpPrintNoList> reqFpPrintNoList = request.getReqFpPrintNoList();
//上送给新核心的List
//List<RenewalPaymentInputFP> renewalPaymentInputFPList = new ArrayList();
//循环遍历,将银行上送的List转成新核心所需的List
//for(ReqFpPrintNoList reqFpPrintNo:reqFpPrintNoList){
//RenewalPaymentInputFP renewalPaymentInputFP = new RenewalPaymentInputFP();
//renewalPaymentInputFP.setFpPrintNo(reqFpPrintNo.getFpPrintNo());
//将遍历得到的数据Add到新核心所需的List
//renewalPaymentInputFPList.add(renewalPaymentInputFP);
//}
//将遍历后得到的List赋值
//renewalPaymentInputData.setFpPrintNoList(renewalPaymentInputFPList);
//bizBody.setInputData(renewalPaymentInputData);
//reqBody.setBizBody(bizBody);
//调用发送方法
port.resultRenewalPayment(header,reqBody, resHeader, resBody);
//获取响应结果
String functionFlag = resBody.value.getBizBody().getOutputData().getFunctionFlag();
String resultFlag = resBody.value.getBizBody().getOutputData().getResultFlag();
String resultReason = resBody.value.getBizBody().getOutputData().getResultReason();
//响应结果的重新赋值
XuQJFResponse response = new XuQJFResponse();
response.setFunctionFlag(functionFlag);
response.setResultFlag(resultFlag);
response.setResultReason(resultReason);
return response;
}*/
/**
* 新单投保
* @param //request
* @return
*/
public static XDCBResponse newOrder(XDCBRequest request){
URL wsdlURL = FreshPolicySignAdapterImplService.WSDL_LOCATION;
FreshPolicySignAdapterImplService ss = new FreshPolicySignAdapterImplService(wsdlURL, SERVICE_NAME);
IFreshPolicySignAdapter port = ss.getFreshPolicySignAdapterImplPort();
SysHeader sysHeader = new SysHeader();
SrvReqBody reqBody = new SrvReqBody();
Holder<SysHeader> resHeader = new Holder<SysHeader>();
Holder<SrvResBody> resBody = new Holder<SrvResBody>();
SrvReqBizBody srvReqBizBody = new SrvReqBizBody();
FreshPolicySignReqData freshPolicySignReqData = new FreshPolicySignReqData();
//TODO 核心文档中不存在
freshPolicySignReqData.setVersionNum("");
List<BillCardVO> nbBillcardVOList = new ArrayList();
BillCardVO nbBillcardVO = new BillCardVO();
//TODO 领用单证业务员编码 工行接口中不存在 非必填
nbBillcardVO.setAssignedAgentCode("");
//TODO 领用单证雇员编码
nbBillcardVO.setAssignedEmpCode("");
//TODO 领用部门 工行接口中不存在 非必填
nbBillcardVO.setAssignedOrganCode("");
//TODO 领用人编码 工行接口中不存在 非必填
nbBillcardVO.setAssignedPartyCode("");
//TODO 领用人名称 工行接口中不存在 非必填
nbBillcardVO.setAssignedPartyName("");
//TODO 领用人类型 工行接口中不存在 非必填
nbBillcardVO.setAssignedPartyType(new BigDecimal("1"));
//TODO 领用时间 工行接口中不存在 非必填
nbBillcardVO.setAssignedTime(DateUtils.nowXmlGre());
//TODO 单证编号 工行接口中不存在 非必填
nbBillcardVO.setBillcardCode("");
//TODO 单证序列号 工行接口中不存在 非必填
nbBillcardVO.setBillcardListId(new BigDecimal("1"));
//TODO 单证号码 工行接口中不存在 非必填
nbBillcardVO.setBillcardNo("");
//TODO 当前单证使用状态 工行接口中不存在 非必填
nbBillcardVO.setBillcardStatus(new BigDecimal("1"));
//TODO 核心系统核销时间 工行接口中不存在 非必填
nbBillcardVO.setConfirmTime(DateUtils.nowXmlGre());
//TODO 核心系统作废时间 工行接口中不存在 非必填
nbBillcardVO.setDiscardTime(DateUtils.nowXmlGre());
nbBillcardVOList.add(nbBillcardVO);
freshPolicySignReqData.setNbBillcardVOList(nbBillcardVOList);
PolicyVO policyVO = new PolicyVO();
policyVO.setApplyCode(request.gethOAppFormNumber());//投保单号
policyVO.setGrossPremAmt(new BigDecimal(request.getGrossPremAmtITD()));//总保费
PolicyBaseInfoVO policyBaseInfoVO = new PolicyBaseInfoVO();
//TODO 0是录单任务,1是问题件任务,由发送文件模板文件头解析得到
policyBaseInfoVO.setActivityId("");
policyBaseInfoVO.setApplyCode(request.gethOAppFormNumber());
//TODO 批次号,由发送文件模板文件头解析得到
policyBaseInfoVO.setBatchId("");
//TODO 财务告知标志 目前未用
policyBaseInfoVO.setFinImpartFlag("");
//TODO 健康告知标志 目前未用
policyBaseInfoVO.setHealthImpartFlag("");
//TODO 是否高额件 Y-是 N-不是
policyBaseInfoVO.setHighAmntFlag("");
//TODO 管理机构代码 工行接口中不存在 非必填
policyBaseInfoVO.setManagecom("1");
//TODO 职业告知标志 目前未用
policyBaseInfoVO.setOccpuImpartFlag("");
//TODO 是否划款件 Y-是 N-不是
policyBaseInfoVO.setPayMode("");
//TODO 切片编号 由发送文件模板解析得到
policyBaseInfoVO.setSectionCode("");
//TODO 切片序列号 由发送文件模板解析得到
policyBaseInfoVO.setSectionNum("");
NuclearVO nuclearVO = new NuclearVO();
//TODO 核保传入内容 工行接口中不存在 非必填
nuclearVO.setMagnumSend("");
//TODO 管理机构代码 工行接口中不存在 非必填
nuclearVO.setManageCom("");
//TODO 操作者 工行接口中不存在 非必填
nuclearVO.setOperator("");
PolicyBeneVOs policyBeneVOs = new PolicyBeneVOs();
//policyBeneVOs.setBenefitNum(new BigDecimal(request.getbCount()));//受益人个数 报文中不存在
policyBeneVOs.setBenefitNum(new BigDecimal("1"));//受益人个数 报文中不存在
PolicyBeneVO policyBeneVO = new PolicyBeneVO();
List<PolicyBeneVO> policyBeneVOlist = new ArrayList();
NbContractBeneVO nbContractBeneVO = new NbContractBeneVO();
nbContractBeneVO.setAddress(request.getLine1());
//TODO 地址ID 工行接口中不存在该字段 非必填
nbContractBeneVO.setAddressId(new BigDecimal("1"));
nbContractBeneVO.setApplyCode(request.gethOAppFormNumber());
//TODO 受益人ID 工行接口中不存在 非必填
nbContractBeneVO.setBeneId(new BigDecimal("1"));
/**
* 受益人循环
*/
/* List<SyrInfoListRequest> syrInfoListRequestslist = request.getSyrInfoListRequest();
for(SyrInfoListRequest syrInfoListRequest:syrInfoListRequestslist){
// 受益类型 身故或者生存受益人
nbContractBeneVO.setBeneType(new BigDecimal(syrInfoListRequest.getSyrType()));
//受益顺序
nbContractBeneVO.setShareOrder(new BigDecimal(syrInfoListRequest.getSyrOrder()));
}*/
//TODO 险种ID 工行接口中不存在 非必填
nbContractBeneVO.setBusiItemId(new BigDecimal("1"));
//TODO 客户ID 工行接口中不存在 非必填
nbContractBeneVO.setCustomerId(new BigDecimal("1"));
//TODO 与被保人关系 枚举 目前传1
nbContractBeneVO.setDesignation("");
//TODO 被保人ID 工行接口文档中不存在 必填
nbContractBeneVO.setInsuredId(new BigDecimal("1"));
nbContractBeneVO.setPolicyCode(request.getPolNumber());//保单号
//TODO 保单ID 工行接口中不存在 非必填
nbContractBeneVO.setPolicyId(new BigDecimal("1"));
//TODO 产品代码或者是责任组ID 工行接口中不存在 非必填
nbContractBeneVO.setProductCode("");
//TODO 收益比例 工行接口中不存在
nbContractBeneVO.setShareRate(new BigDecimal("1"));
policyBeneVO.setContractBenefit(nbContractBeneVO);
policyBeneVOlist.add(policyBeneVO);
policyBeneVOs.setPolicyBenefit(policyBeneVOlist);
PolicyCoverageVOs policyCoverageVOs = new PolicyCoverageVOs();
List<PolicyCoverageVO> policyCoveragelist = new ArrayList();
PolicyCoverageVO policyCoverageVO = new PolicyCoverageVO();
//TODO 险种数目 工行接口中不存在 必填
policyCoverageVOs.setCoverageNum(new BigDecimal("1"));
NbContractBusiProdVO nbContractBusiProdVO = new NbContractBusiProdVO();
nbContractBusiProdVO.setApplyCode(request.gethOAppFormNumber());
//TODO 初审产品ID 工行接口中不存在 核心文档中未标明必填或者非必填
nbContractBusiProdVO.setAuditId(new BigDecimal("1"));
BenefitInsured benefitInsured = new BenefitInsured();
List<BenefitInsured> benefitInsuredlist = new ArrayList();
//TODO 被保人ID 工行接口文档中不存在 必填
benefitInsured.setInsuredId(new BigDecimal("1"));
//TODO 职业风险类别 工行接口中不存在 非必填
benefitInsured.setJobClass(new BigDecimal("1"));
//TODO 被保人顺序 工行接口中不存在 必填
benefitInsured.setOrderId(new BigDecimal("1"));
//TODO 与第一被保人关系 枚举 目前传空
benefitInsured.setRelationToInsured1("");
//TODO 社保标识 工行接口中不存在 必填
benefitInsured.setSociSecu("");
benefitInsuredlist.add(benefitInsured);
nbContractBusiProdVO.setBenefitInsuredList(benefitInsuredlist);
//TODO 险种ID 工行接口中不存在 非必填
nbContractBusiProdVO.setBusiItemId(new BigDecimal("1"));
//TODO 所属业务产品ID 工行接口中不存在 非必填
nbContractBusiProdVO.setBusiPrdId(new BigDecimal("1"));
//TODO 所属业务产品ID 工行接口中不存在 非必填
nbContractBusiProdVO.setBusinessPrdId(new BigDecimal("1"));
//TODO 竞赛编码 工行接口中不存在 非必填
nbContractBusiProdVO.setCampaignCode("");
nbContractBusiProdVO.setDecisionCode(request.getVerifyMode());
//TODO 核保决定ID 工行接口中不存在 非必填
nbContractBusiProdVO.setDecisionId("");
//TODO 核心文档,报文中存在,字段说明中不存在
nbContractBusiProdVO.setGurntPerdType("");
//TODO 核心文档,报文中存在,字段说明中不存在
nbContractBusiProdVO.setGurntPeriod(new BigDecimal("1"));
//TODO 核心文档,报文中存在,字段说明中不存在
nbContractBusiProdVO.setGurntStartDate(DateUtils.nowXmlGre());
//TODO 是否允许犹豫期后进账户 工行接口中不存在 非必填
nbContractBusiProdVO.setHesitation2Acc(new BigDecimal("1"));
//TODO 承保日期 工行接口中不存在 非必填
nbContractBusiProdVO.setIssueDate(DateUtils.nowXmlGre());
//TODO 保单效力状态 工行接口中不存在 必填
nbContractBusiProdVO.setLiabilityState(new BigDecimal("1"));
//TODO 主险代码 工行接口中不存在 非必填
nbContractBusiProdVO.setMasterBusiItemId(new BigDecimal("1"));
nbContractBusiProdVO.setPolicyCode(request.getPolNumber());
//TODO 保单ID 工行提供的接口文档中不存在 非必填
nbContractBusiProdVO.setPolicyId(new BigDecimal("1"));
//TODO 产品组合代码 工行接口中不存在 非必填
nbContractBusiProdVO.setPrdPkgCode("");
nbContractBusiProdVO.setProductCategory(request.getIndicatorCode());
//TODO 产品代码或者是责任组ID 工行接口中不存在 非必填
nbContractBusiProdVO.setProductCode("");
//TODO 产品系统代码 工行接口中不存在 非必填
nbContractBusiProdVO.setProductCodeSys("");
//TODO 产品标准名称 工行接口中不存在 非必填
nbContractBusiProdVO.setProductNameStd("");
//TODO 是否续保标记 工行的主险循环中存在默认续保标志RenewalPermit 待确认
nbContractBusiProdVO.setRenew(new BigDecimal("1"));
//TODO 自动续保标识描述 工行接口中不存在 非必填
nbContractBusiProdVO.setRenewDecision(new BigDecimal("1"));
//TODO 保单生效日期 工行提供的接口文档中不存在 非必填
nbContractBusiProdVO.setValidateDate(DateUtils.nowXmlGre());
//TODO 豁免险标志 工行接口中不存在 非必填
nbContractBusiProdVO.setWaiver(new BigDecimal("1"));
policyCoverageVO.setContractBusiProd(nbContractBusiProdVO);
List<PolicyLiabilityVO> policyLiabilityVOlist = new ArrayList();
PolicyLiabilityVO policyLiabilityVO = new PolicyLiabilityVO();
//TODO 责任信息 工行报文中不存在该信息
NbContractProductVO nbContractProductVO = new NbContractProductVO();
//年龄 非必填
nbContractProductVO.setAge(new BigDecimal("1"));
//金额 非必填
nbContractProductVO.setAmount(new BigDecimal("1"));
//投保单号 必填
nbContractProductVO.setApplyCode("");
//收益人级别 非必填
nbContractProductVO.setBenefitLevel("");
//险种ID 非必填
nbContractProductVO.setBusiItemId(new BigDecimal("1"));
//TODO 所属业务产品ID 工行接口中不存在 非必填
nbContractProductVO.setBusiPrdId(new BigDecimal("1"));
//TODO 初审产品ID 工行接口中不存在 非必填
nbContractProductVO.setBusiProdId(new BigDecimal("1"));
//TODO 业务产品ID 工行接口中不存在 非必填
nbContractProductVO.setBusinessProdId(new BigDecimal("1"));
//缴费年期类型
nbContractProductVO.setChargePeriod("");
//缴费年期
nbContractProductVO.setChargeYear(new BigDecimal("1"));
//TODO 核心文档中,报文中存在,字段说明中不存在
nbContractProductVO.setConField1("");
//TODO 核心文档中,报文中存在,字段说明中不存在
nbContractProductVO.setConField2("");
//TODO 核心文档中,报文中存在,字段说明中不存在
nbContractProductVO.setConField3("");
//TODO 核心文档中,报文中存在,字段说明中不存在
nbContractProductVO.setConField4("");
//TODO 核心文档中,报文中存在,字段说明中不存在
nbContractProductVO.setConField5("");
//保费计算方向
nbContractProductVO.setCountWay("");
//保障年期类型
nbContractProductVO.setCoveragePeriod("");
//保险年期
nbContractProductVO.setCoverageYear(new BigDecimal("1"));
//核保决定
nbContractProductVO.setDecisionCode("");
//TODO 折扣保费 工行接口中不存在 非必填
nbContractProductVO.setDiscntPremAf(new BigDecimal("1"));
//保单终止日期
nbContractProductVO.setExpiryDate(DateUtils.nowXmlGre());
//加费
nbContractProductVO.setExtraPremAf(new BigDecimal("1"));
//保费
nbContractProductVO.setFeeAmount(new BigDecimal("1"));
//TODO 核心文档中,字段:Field1~Field20 报文中存在,字段说明中不存在
nbContractProductVO.setField1("");
nbContractProductVO.setField2("");
nbContractProductVO.setField3("");
nbContractProductVO.setField4("");
nbContractProductVO.setField5("");
nbContractProductVO.setField6("");
nbContractProductVO.setField7("");
nbContractProductVO.setField8("");
nbContractProductVO.setField9("");
nbContractProductVO.setField10("");
nbContractProductVO.setField11("");
nbContractProductVO.setField12("");
nbContractProductVO.setField13("");
nbContractProductVO.setField14("");
nbContractProductVO.setField15("");
nbContractProductVO.setField16("");
nbContractProductVO.setField17("");
nbContractProductVO.setField18("");
nbContractProductVO.setField19("");
nbContractProductVO.setField20("");
//性别
nbContractProductVO.setGender(new BigDecimal("1"));
//健康标记
nbContractProductVO.setHealthServiceFlag(new BigDecimal("1"));
//缴费频率
nbContractProductVO.setInitialType(new BigDecimal("1"));
//被保人分类
nbContractProductVO.setInsuredCategory("");
//产品精算码
nbContractProductVO.setInternalId("");
//TODO 基金集合 工行报文中不存在该信息
List<NbContractInvestRateVO> nbContractInvestRateVOlist = new ArrayList();
NbContractInvestRateVO nbContractInvestRateVO = new NbContractInvestRateVO();
//基金代码
nbContractInvestRateVO.setAccountCode("");
//j基金投资比例
nbContractInvestRateVO.setAssignRate(new BigDecimal("1"));
//保单年度最大区间
nbContractInvestRateVO.setHighPlyYear(new BigDecimal("1"));
//TODO 核心文档中 报文中存在 字段说明中不存在
nbContractInvestRateVO.setItemId(new BigDecimal("1"));
//TODO 主键流水ID 工行接口中不存在 非必填
nbContractInvestRateVO.setListId(new BigDecimal("1"));
//保单年度最小区间
nbContractInvestRateVO.setLowPlyYear(new BigDecimal("1"));
//保单号
nbContractInvestRateVO.setPolicyCode("");
//保单ID
nbContractInvestRateVO.setPolicyId(new BigDecimal("1"));
//投资金来源
nbContractInvestRateVO.setPremType("");
nbContractInvestRateVOlist.add(nbContractInvestRateVO);
nbContractProductVO.setInvestmentList(nbContractInvestRateVOlist);
//TODO 险种责任组ID 工行接口中不存在 非必填
nbContractProductVO.setItemId(new BigDecimal("1"));
//职业风险类别
nbContractProductVO.setJobClass(new BigDecimal("1"));
//责任组标签名称
nbContractProductVO.setLabelName("");
//保单效力状态
nbContractProductVO.setLiabilityState(new BigDecimal("1"));
//TODO 核心文档中 报文中存在 字段说明中不存在
nbContractProductVO.setMasterItemId(new BigDecimal("1"));
//主险编码
nbContractProductVO.setMasterProductCode("");
//方法标记
nbContractProductVO.setMethodFlag("");
//是否比选责任
nbContractProductVO.setOptionType("");
//领取类型
nbContractProductVO.setPayPeriod("");
//领取年期
nbContractProductVO.setPayYear(new BigDecimal("1"));
//保单号
nbContractProductVO.setPolicyCode("");
//保单ID
nbContractProductVO.setPolicyId(new BigDecimal("1"));
//当期缴费频率
nbContractProductVO.setPremFreq(new BigDecimal("1"));
//产品代码
nbContractProductVO.setProductCode("");
//责任组ID
nbContractProductVO.setProductId(new BigDecimal("1"));
//责任组名称
nbContractProductVO.setProductName("");
//产品标准名称
nbContractProductVO.setProductNameStd("");
//是否续保标记
nbContractProductVO.setRenew(new BigDecimal("1"));
//TODO 自动续保标识描述 工行接口中不存在 非必填
nbContractProductVO.setRenewDecision(new BigDecimal("1"));
//保存字段
nbContractProductVO.setSaveColumn("");
//保存表
nbContractProductVO.setSaveTable("");
//保存值
nbContractProductVO.setSaveValue("");
//TODO 核心文档,报文中存在,字段说明中不存在
nbContractProductVO.setShortEndTime(DateUtils.nowXmlGre());
//保费
nbContractProductVO.setStdPremAf(new BigDecimal("1"));
//交单日期
nbContractProductVO.setSubmissionDate(DateUtils.nowXmlGre());
//TODO 核心文档,报文中存在,字段说明中不存在
nbContractProductVO.setThisValue("");
//总保费
nbContractProductVO.setTotalPremAf(new BigDecimal("1"));
//份数
nbContractProductVO.setUnit(new BigDecimal("1"));
//保单生效日期
nbContractProductVO.setValidateDate(DateUtils.nowXmlGre());
policyLiabilityVO.setContractProduct(nbContractProductVO);
policyLiabilityVOlist.add(policyLiabilityVO);
policyCoverageVO.setContractProductList(policyLiabilityVOlist);
//责任扩展信息
List<NbExtraPremVO> nbExtraPremVOlist = new ArrayList();
NbExtraPremVO nbExtraPremVO = new NbExtraPremVO();
//第一被保人疾病伤残EM值 非必填
nbExtraPremVO.setEmCi(new BigDecimal("1"));
//T第一被保人寿险EM值 非必填
nbExtraPremVO.setEmLife(new BigDecimal("1"));
//第一被保人疾病全残EM值 非必填
nbExtraPremVO.setEmTpd(new BigDecimal("1"));
//EM值 非必填
nbExtraPremVO.setEmValue(new BigDecimal("1"));
//加费模式 非必填
nbExtraPremVO.setExtraArith("");
//加费参数 非必填
nbExtraPremVO.setExtraPara(new BigDecimal("1"));
//加费比例 非必填
nbExtraPremVO.setExtraPerc(new BigDecimal("1"));
//加费金额 非必填
nbExtraPremVO.setExtraPrem(new BigDecimal("1"));
//年加费 非必填
nbExtraPremVO.setExtraPremAn(new BigDecimal("1"));
//加费状态 非必填
nbExtraPremVO.setExtraStatus("");
//加费类型 非必填
nbExtraPremVO.setExtraType("");
//险种责任组ID 非必填
nbExtraPremVO.setItemId(new BigDecimal("1"));
//主键流水ID 非必填
nbExtraPremVO.setListId(new BigDecimal("1"));
//下期加费金额 非必填
nbExtraPremVO.setNextExtraPrem(new BigDecimal("1"));
//下一年加费 非必填
nbExtraPremVO.setNextExtraPremAn(new BigDecimal("1"));
//重算标记 非必填
nbExtraPremVO.setReCalcIndi("");
//其他加费原因 非必填
nbExtraPremVO.setReason("");
//加费的开始日期 非必填
nbExtraPremVO.setStartDate(DateUtils.nowXmlGre());
//加费终止日期 非必填
nbExtraPremVO.setEndDate(DateUtils.nowXmlGre());
//保单号 非必填
nbExtraPremVO.setPolicyCode("");
//保单ID 非必填
nbExtraPremVO.setPolicyId(new BigDecimal("1"));
nbExtraPremVOlist.add(nbExtraPremVO);
policyLiabilityVO.setNbExtraPremiumList(nbExtraPremVOlist);
policyCoverageVO.setContractProductList(policyLiabilityVOlist);
List<NbBenefitInsuredVO> nbBenefitInsuredVOlist = new ArrayList();
//险种被保人关系表
NbBenefitInsuredVO nbBenefitInsuredVO = new NbBenefitInsuredVO();
//TODO 险种编码 工行接口中不存在 非必填
nbBenefitInsuredVO.setBusiItemId(new BigDecimal("1"));
//TODO 险种ID 工行接口中不存在 非必填
nbBenefitInsuredVO.setBusiPrdId(new BigDecimal("1"));
//TODO 投保年龄 工行接口中不存在 非必填
nbBenefitInsuredVO.setEntryAge(new BigDecimal("1"));
//TODO 核心文档,报文中存在,字段说明中不存在
nbBenefitInsuredVO.setEntryAgeMonth(new BigDecimal("1"));
//TODO 被保人ID 工行接口中不存在 非必填
nbBenefitInsuredVO.setInsuredId(new BigDecimal("1"));
//TODO 职业风险类别 工行接口中不存在 非必填
nbBenefitInsuredVO.setJobClass(new BigDecimal("1"));
//TODO 是否连身险标识 工行接口中不存在 非必填
nbBenefitInsuredVO.setJointLifeFlag(new BigDecimal("1"));
//TODO 主键流水ID 工行接口中不存在 非必填
nbBenefitInsuredVO.setListId(new BigDecimal("1"));
//TODO 被保人顺序 工行接口中不存在 非必填
nbBenefitInsuredVO.setOrderId(new BigDecimal("1"));
//TODO 保单号 工行报文中无险种被保人关系表节点 非必填
nbBenefitInsuredVO.setPolicyCode("");
//TODO 保单ID 工行报文中无险种被保人关系表节点 非必填
nbBenefitInsuredVO.setPolicyId(new BigDecimal("1"));
//TODO 产品代码 工行报文中无险种被保人关系表节点 非必填
nbBenefitInsuredVO.setProductCode("");
//TODO 产品名称 工行报文中无险种被保人关系表节点 非必填
nbBenefitInsuredVO.setProductNameSys("");
nbBenefitInsuredVOlist.add(nbBenefitInsuredVO);
policyCoverageVO.setPolicyInsuredVOList(nbBenefitInsuredVOlist);
policyCoveragelist.add(policyCoverageVO);
policyCoverageVOs.setPolicyCoverage(policyCoveragelist);
//投保人信息
PolicyHolderVO policyHolderVO = new PolicyHolderVO();
//投保人基本信息
NbPolicyHolderVO nbPolicyHolderVO = new NbPolicyHolderVO();
//地址信息 非必填
nbPolicyHolderVO.setAddressId(new BigDecimal("1"));
//投保人年龄 非必填
nbPolicyHolderVO.setApplicantAge(new BigDecimal("1"));
//投保单号
nbPolicyHolderVO.setApplyCode("");
//投保人客户ID
nbPolicyHolderVO.setCustomerId(new BigDecimal("1"));
//投保人
nbPolicyHolderVO.setJobCode(request.getFullName());
//职业代码
nbPolicyHolderVO.setListId(new BigDecimal("1"));
//保单号
nbPolicyHolderVO.setPolicyCode("");
//保单ID
nbPolicyHolderVO.setPolicyCode("");
policyHolderVO.setNbPolicyHolderVO(nbPolicyHolderVO);
//被保人集合
PolicyInsuredVOs policyInsuredVOs = new PolicyInsuredVOs();
//TODO 被保人数量 工行接口中不存在 必填
policyInsuredVOs.setPolicyInsuredCount(new BigDecimal("1"));
PolicyInsuredVO policyInsuredVO = new PolicyInsuredVO();
List<PolicyInsuredVO> policyInsuredVOList = new ArrayList();
//TODO 被保人ID 工行接口中不存在 非必填
policyInsuredVO.setInsuredId(new BigDecimal("1"));
//TODO 业务员与投保人的关系 工行提供的接口文档中将该字段列入枚举 未标明必填或者非必填
policyInsuredVO.setRelationToPh("");
//被保人信息
NbInsuredListVO nbInsuredListVO = new NbInsuredListVO();
//TODO 地址ID 工行接口中不存在该字段 非必填
nbInsuredListVO.setAddressId(new BigDecimal("1"));
//TODO 被保人信息中的字段:投保单号,工行接口中不存在(核心接口中nbInsuredListVO节点没有该字段)
nbInsuredListVO.setApplyCode("");
//银行上送被保人信息
List<BbrInfoListRequest> bbrInfoList = request.getBbrInfoListRequest();
/* for(BbrInfoListRequest bbrInfoRequest:bbrInfoList){
try {
//被保人生日
nbInsuredListVO.setBirthDay(DateUtils.strToXml(bbrInfoRequest.getBbrBirth(),"yyyy-MM-dd"));
} catch (ParseException e) {
e.printStackTrace();
}
}*/
//TODO 被保人信息中的字段:客户ID,工行接口中不存在(核心接口中nbInsuredListVO节点没有该字段)
nbInsuredListVO.setCustomerId(new BigDecimal("1"));
//TODO 投保年龄 工行接口中不存在 非必填
nbInsuredListVO.setEntryAge(0);
//TODO 签单投保实际年龄 工行接口不存在 非必填
nbInsuredListVO.setIssueAge(0);
//TODO 主键流水ID 工行接口中不存在 非必填
nbInsuredListVO.setListId(new BigDecimal("1"));
//TODO 核心文档中 报文中存在 字段说明中不存在
nbInsuredListVO.setMedicalExamIndi("");
//TODO 被保人顺序 工行接口中不存在 必填
nbInsuredListVO.setOrderId(new BigDecimal("1"));
//TODO 被保人信息中的字段:保单号(核心接口中nbInsuredListVO节点没有该字段)
nbInsuredListVO.setPolicyCode("");
//TODO 被保人信息中的字段:保单ID 工行接口中不存在(核心接口中nbInsuredListVO节点没有该字段)
nbInsuredListVO.setPolicyId(new BigDecimal("1"));
//TODO 与第一被保人关系 枚举 目前传空
nbInsuredListVO.setRelationToInsured1("");
//TODO 业务员与投保人的关系 枚举 目前传空
nbInsuredListVO.setRelationToPh("");
//TODO 与投保无关 非必填
nbInsuredListVO.setStandLife(new BigDecimal("1"));
policyInsuredVO.setNbInsuredListVO(nbInsuredListVO);
List<PolicyBeneVO> policyBeneVOTwoList = new ArrayList();
PolicyBeneVO PolicyBeneVOTwo = new PolicyBeneVO();
NbContractBeneVO nbContractBeneVOTwo = new NbContractBeneVO();
nbContractBeneVOTwo.setAddress(request.getLine1());
//TODO 地址ID 工行接口中不存在该字段 非必填
nbContractBeneVOTwo.setAddressId(new BigDecimal("1"));
nbContractBeneVOTwo.setApplyCode(request.gethOAppFormNumber());
//TODO 受益人ID 工行接口中不存在 非必填
nbContractBeneVOTwo.setBeneId(new BigDecimal("1"));
/**
* 受益人循环
*/
List<SyrInfoListRequest> syrInfoListRequeststwolist = request.getSyrInfoListRequest();
/* for(SyrInfoListRequest syrInfoListRequest:syrInfoListRequeststwolist){
// 受益类型 身故或者生存受益人
nbContractBeneVOTwo.setBeneType(new BigDecimal(syrInfoListRequest.getSyrType()));
//受益顺序
nbContractBeneVOTwo.setShareOrder(new BigDecimal(syrInfoListRequest.getSyrOrder()));
}*/
//TODO 险种ID 工行接口中不存在 非必填
nbContractBeneVOTwo.setBusiItemId(new BigDecimal("1"));
//TODO 客户ID 工行接口中不存在 非必填
nbContractBeneVOTwo.setCustomerId(new BigDecimal("1"));
//TODO 与被保人关系 枚举 目前传1
nbContractBeneVOTwo.setDesignation("");
//TODO 被保人ID 工行接口文档中不存在 必填
nbContractBeneVOTwo.setInsuredId(new BigDecimal("1"));
nbContractBeneVOTwo.setPolicyCode(request.getPolNumber());//保单号
//TODO 保单ID 工行接口中不存在 非必填
nbContractBeneVOTwo.setPolicyId(new BigDecimal("1"));
//TODO 产品代码或者是责任组ID 工行接口中不存在 非必填
nbContractBeneVOTwo.setProductCode("");
//TODO 收益比例 工行接口中不存在
nbContractBeneVOTwo.setShareRate(new BigDecimal("1"));
PolicyBeneVOTwo.setContractBenefit(nbContractBeneVOTwo);
policyBeneVOTwoList.add(PolicyBeneVOTwo);
policyInsuredVO.setPolicyBeneVOList(policyBeneVOTwoList);
List<RiskAmountVO> riskAmountList = new ArrayList();
RiskAmountVO riskAmountVO = new RiskAmountVO();
//TODO 风险类型 非必填
riskAmountVO.setActiveRisk(new BigDecimal("1"));
//TODO 总保额 非必填
riskAmountVO.setRiskSum(new BigDecimal("1"));
//TODO 有效保额 非必填
riskAmountVO.setRiskType("");
//TODO 终止保额 非必填
riskAmountVO.setTerminatedRisk(new BigDecimal("1"));
riskAmountList.add(riskAmountVO);
policyInsuredVO.setRiskAmountList(riskAmountList);
//保单基本元素信息
PolicyMasterVO policyMasterVO = new PolicyMasterVO();
//NbContractMasterVO nbContractMasterVO = new NbContractMasterVO();
InterContractMasterVO interContractMasterVO = new InterContractMasterVO();
//TODO 中介机构代码 工行接口中不存在 非必填
interContractMasterVO.setAgencyCode("");
//投保书号
interContractMasterVO.setApplyCode(request.gethOAppFormNumber());
//TODO 是否自垫标识 工行接口中不存在 非必填
interContractMasterVO.setAplPermit(new BigDecimal("1"));
//TODO 汇缴事件号 工行接口中不存在 非必填
interContractMasterVO.setEventCode("");
//TODO 录单日期 工行接口中不存在 必填
interContractMasterVO.setInputDate(DateUtils.nowXmlGre());
//TODO 保单录入方案 工行接口中不存在 非必填
interContractMasterVO.setInputType("");
//TODO 销售方式 工行接口中将该字段列入枚举 目前上送空 必填
interContractMasterVO.setSaleType("");
//TODO 出单标识 工行接口中不存在该字段 必填
interContractMasterVO.setSubinputType("");
//TODO 代理人管理机构 字段在工行接口中不存在,待解决 必填
interContractMasterVO.setAgentOrgId("");
try {
interContractMasterVO.setApplyDate(DateUtils.strToXml(request.getSubmissionDate(),"yyyy-MM-dd"));//投保日期
} catch (ParseException e) {
e.printStackTrace();
}
//TODO 是否已经对账 非必填
interContractMasterVO.setBillChecked(new BigDecimal("1"));
//TODO 生日单标识 工行接口中不存在 必填
interContractMasterVO.setBirthdayPolIndi(new BigDecimal("1"));
//TODO 保单所属分公司 工行接口中不存在 未标明必填或者非必填
interContractMasterVO.setBranchOrganCode("");
//TODO 营业组 工行提供的接口中不存在 非必填
interContractMasterVO.setChannelId(new BigDecimal("1"));
//TODO 销售渠道机构 工行提供的接口文档中不存在 非必填
interContractMasterVO.setChannelOrgCode("");
//TODO 销售渠道 工行提供的接口文档中不存在 非必填
interContractMasterVO.setChannelType("");
interContractMasterVO.setDecisionCode(request.getVerifyMode());
//TODO 电子函件服务 工行提供的接口文档中不存在 必填
interContractMasterVO.setEServiceFlag(new BigDecimal("1"));
List<MainProductListItem> list = request.getMainProductListItem();
/**
* 主险循环
*/
for(MainProductListItem mainProductListRequest:list){
try {
System.out.print("QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"+mainProductListRequest.getTermDate());
//TODO 银行接口中,以下字段在循环节点中,而核心提供给的该类不是List循环结构
interContractMasterVO.setExpiryDate(DateUtils.strToXml(mainProductListRequest.getTermDate(), "yyyy-MM-dd"));
//nbContractBusiProdVO.setAmount(new Double(mainProductListRequest.getFaceAmt()));
nbContractBusiProdVO.setBusiPrdName(mainProductListRequest.getPlanName());
//nbContractBusiProdVO.setStdPremAf(new Double(mainProductListRequest.getPremium()));
} catch (ParseException e) {
e.printStackTrace();
}
}
//TODO 高额件标识,工行中不存在 必填
interContractMasterVO.setHighSaIndi(new BigDecimal("1"));
//TODO 家庭险保单标志(1/0) 工行接口中途不存在 传空
interContractMasterVO.setInsuredFamily(new BigDecimal("1"));
//TODO 承保日期 工行提供的接口文档中不存在 非必填
interContractMasterVO.setIssueDate(DateUtils.nowXmlGre());
//TODO 手工签单人员代码 工行接口中不存在 必填
interContractMasterVO.setIssueUserCode("");
//TODO 语言编码 工行提供的接口文档中不存在 非必填
interContractMasterVO.setLangCode("");
//TODO 保单效力状态 工行提供的接口文档中不存在 必填
interContractMasterVO.setLiabilityState(new BigDecimal("1"));
interContractMasterVO.setPolicyCode(request.getPolNumber());
//TODO 保单ID 工行提供的接口文档中不存在 非必填
interContractMasterVO.setPolicyId(new BigDecimal("1"));
//TODO 人工核保 工行提供的接口文档中不存在 必填
interContractMasterVO.setManualUwIndi(new BigDecimal("1"));
//TODO 保单的发送形式 工行提供的接口文档中不存在
interContractMasterVO.setMediaType(new BigDecimal("1"));
//TODO 币种代码 工行提供的接口文档中将该字段列入枚举,目前未补充枚举类 非必填
interContractMasterVO.setMoneyCode("");
//TODO 当前操作人员代码 工行接口中不存在 必填
interContractMasterVO.setOperatorUserCode("");
//TODO 保单管理机构 工行文档不存在 必填
interContractMasterVO.setOrganCode("");
//TODO 逾期时间 工行文档中不存在 非必填
interContractMasterVO.setOverdueTime(DateUtils.nowXmlGre());
//TODO 保单完成时间 工行文档中不存在 非必填
interContractMasterVO.setPaCompleteTime(DateUtils.nowXmlGre());
//TODO 保单处理人 工行文档中不存在 非必填
interContractMasterVO.setPaUserCode("b");
interContractMasterVO.setPolicyPwd(request.getPassword());
//TODO 保单类型 工行文档中不存在 必填
interContractMasterVO.setPolicyType("");
//TODO 风险提示是否抄写标识 工行接口中不存在 必填
interContractMasterVO.setRiskIndi(new BigDecimal("1"));
//TODO 销售人员编码 工行接口中不存在 非必填
interContractMasterVO.setSaleAgentCode("");
//TODO 销售人员姓名 工行接口中不存在 非必填
interContractMasterVO.setSaleAgentName("");
//TODO 影像扫描时间 工行接口中不存在 非必填
interContractMasterVO.setScanCompleteTime(DateUtils.nowXmlGre());
//TODO 扫描人员编码 工行接口中不存在 非必填
interContractMasterVO.setScanUserCode("");
interContractMasterVO.setServiceBank(request.getBankCode());
interContractMasterVO.setServiceBankBranch(request.getBranch());
//TODO 网点经办人 工行接口中不存在 非必填
interContractMasterVO.setServiceHandler("");
//TODO 网点经办人编码 工行接口中不存在 非必填
interContractMasterVO.setServiceHandlerCode("");
//TODO 网点经办人姓名 工行接口中不存在 非必填
interContractMasterVO.setServiceHandlerName("");
try {
//TODO 该字段 工行为投保日期,核心为交单日期,而核心的投保日期字段为ApplyDate 重复而且有冲突
interContractMasterVO.setSubmissionDate(DateUtils.strToXml(request.getSubmissionDate(), "yyyy-MM-dd"));
} catch (ParseException e) {
e.printStackTrace();
}
//TODO 提交渠道 工行存在银行交易渠道SourceType 目前上送1 待确认!
interContractMasterVO.setSubmitChannel(new BigDecimal("1"));
//TODO 核保完成时间 工行接口中不存在 非必填
interContractMasterVO.setUwCompleteTime(DateUtils.nowXmlGre());
//TODO 核保人编码 工行接口中不存在 非必填
interContractMasterVO.setUwUserCode(new BigDecimal("1"));
//TODO 保单状态 工行提供的接口文档中不存在 非必填
interContractMasterVO.setProposalStatus("");
//TODO 保单生效日期 工行提供的接口文档中不存在 非必填
interContractMasterVO.setValidateDate(DateUtils.nowXmlGre());
List<PolicyAgentVO> policyAgentVOList = new ArrayList<PolicyAgentVO>();
PolicyAgentVO policyAgentVO = new PolicyAgentVO();
AgentCompBO agentCompBO = new AgentCompBO();
AgentBO agentBO = new AgentBO();
agentBO.setAgentCode(request.getAgentCode());//代理人编码
//TODO 代理人邮件 工行接口文档中不存在 非必填
agentBO.setAgentEmail("");
//TODO 代理人性别 工行接口文档中不存在 非必填
agentBO.setAgentGender(new BigDecimal("1"));
//TODO 代理人级别 工行接口文档中不存在 非必填
agentBO.setAgentLevel(new BigDecimal("1"));
//TODO 代理人电话 工行接口文档中不存在 非必填
agentBO.setAgentMobile("");
//TODO 代理人姓名 工行接口中不存在 非必填
agentBO.setAgentName("");
//TODO 代理人手机 工行接口中不存在 非必填
agentBO.setAgentPhone("");
//TODO 代理人星级 工行接口中不存在 非必填
agentBO.setAgentStarFlag(new BigDecimal("1"));
//TODO 代理人状态 工行接口中不存在 非必填
agentBO.setAgentStatus(new BigDecimal("1"));
//TODO 代理人类型 工行接口中不存在 非必填
agentBO.setAgentType(new BigDecimal("1"));
//TODO 代理人机构代码 工行接口中不存在 必填
agentBO.setAgnetOrganCode("");
//TODO 代理人生日 工行接口中不存在 非必填 目前上送当前时间
agentBO.setBirthday(DateUtils.nowXmlGre());
//TODO 代理人证件类型 工行接口中不存在 非必填
agentBO.setCertType("");
//TODO 代理人证件号码 工行接口中不存在 非必填
agentBO.setCertiCode("");
//TODO 代理人离职日期 工行接口中不存在 非必填
agentBO.setDismissalDate(DateUtils.nowXmlGre());
//TODO 代理人内勤标志 工行接口中不存在 非必填
agentBO.setEmployeeFlag(new BigDecimal("1"));
//TODO 代理人入职日期 工行接口中不存在 非必填
agentBO.setEmploymentDate(DateUtils.nowXmlGre());
//TODO 家庭地址 工行接口中不存在 非必填
agentBO.setHomeAddress("");
//TODO 邮寄地址 工行接口中不存在 非必填
agentBO.setPostalAddress("");
//TODO 销售机构编码 工行接口中不存在 非必填
agentBO.setSalesOrganCode("");
//TODO 诚信级别 工行接口中不存在 非必填
agentBO.setSgentHornerLevel(new BigDecimal("1"));
//TODO 员工编号 工行接口中不存在 非必填
agentBO.setStaffCode("");
SalesOrganBO salesOrganBO = new SalesOrganBO();
//TODO 管理机构代码 工行接口中不存在 非必填
salesOrganBO.setAdminOrganCode("");
//TODO 机构级别 工行接口中不存在 非必填
salesOrganBO.setOrganLevelCode(new BigDecimal("1"));
//TODO 上级机构代码 工行接口中不存在 非必填
salesOrganBO.setParentCode("");
//TODO 销售机构代码 工行接口中不存在 非必填
salesOrganBO.setSalesOrganCode("");
//TODO 销售机构名称 工行接口中不存在 非必填
salesOrganBO.setSalesOrganName("");
agentCompBO.setSalesOrganBO(salesOrganBO);
agentCompBO.setAgentBO(agentBO);
policyAgentVO.setAgentCompBO(agentCompBO);
policyAgentVOList.add(policyAgentVO);
//账号信息
List<PolicyPayerVO> policyPayerList = new ArrayList();
PolicyPayerVO policyPayerVO = new PolicyPayerVO();
//账户信息
List<NbPayerAccountVO> accountList = new ArrayList();
NbPayerAccountVO nbPayerAccountVO = new NbPayerAccountVO();
//银行账号
nbPayerAccountVO.setAccount(request.getAccNo());
//TODO 账户银行 工行接口中不存在 必填
nbPayerAccountVO.setAccountBank("");
//TODO 银行转账账户ID 工行接口中不存在 必填
nbPayerAccountVO.setAccountId(new BigDecimal("1"));
//账户持有人姓名
nbPayerAccountVO.setAccountName(request.getAcctHolderName());
//TODO 客户ID 工行接口中不存在 非必填
nbPayerAccountVO.setCustomerId(new BigDecimal("1"));
//TODO 核心文档,账户信息节点中没有该字段
nbPayerAccountVO.setListId(new BigDecimal("1"));
//TODO 下期缴费银行帐号 工行接口中不存在 必填
nbPayerAccountVO.setNextAccount("");
//TODO 下期缴费账户银行 工行接口中不存在 必填
nbPayerAccountVO.setNextAccountBank("");
//TODO 下期缴费银行转账账户ID 工行接口中不存在 必填
nbPayerAccountVO.setNextAccountId(new BigDecimal("1"));
//TODO 下期缴费账户持有人姓名 工行接口中不存在 非必填
nbPayerAccountVO.setNextAccountName("");
//缴费形式
nbPayerAccountVO.setPayMode(request.getPaymentMethod());
//TODO 续期缴费方式 工行接口中不存在 非必填
nbPayerAccountVO.setPayNext("");
//TODO 付款人ID 工行接口中不存在 非必填
nbPayerAccountVO.setPayerId(new BigDecimal("1"));
//保单号 非必填
nbPayerAccountVO.setPolicyCode("");
//保单ID 非必填
nbPayerAccountVO.setPolicyId(new BigDecimal("1"));
accountList.add(nbPayerAccountVO);
policyPayerVO.setAccountList(accountList);
//保单缴费人信息表 工行报文中没有该节点
NbPayerVO nbPayerVO = new NbPayerVO();
//TODO 地址ID 工行接口中不存在 非必填
nbPayerVO.setAddressId(new BigDecimal("1"));
//TODO 客户ID 工行接口中不存在 非必填
nbPayerVO.setCustomerId(new BigDecimal("1"));
//移动电话 非必填
nbPayerVO.setMobileTel("");
//TODO 付款人ID 工行接口中不存在 非必填
nbPayerVO.setPayerId(new BigDecimal("1"));
//保单号 非必填
nbPayerVO.setPolicyCode("");
//保单ID 非必填
nbPayerVO.setPolicyId(new BigDecimal("1"));
//TODO 与投保人关系 枚举
nbPayerVO.setRelationToPh("");
//TODO 付款比例 工行接口中不存在 非必填
nbPayerVO.setShareRate(new BigDecimal("1"));
//固定电话 非必填
nbPayerVO.setTelephone("");
policyPayerVO.setNbPayerVO(nbPayerVO);
policyPayerList.add(policyPayerVO);
//问题件信息
QustionsVOS qustionsVOs = new QustionsVOS();
//TODO 问题件数量 工行接口中不存在 非必填
qustionsVOs.setQuestionCount(new BigDecimal("1"));
QustionsVO qustionsVO = new QustionsVO();
//TODO 问题内容 工行接口中不存在 非必填
qustionsVO.setQuestionContent("");
//TODO 问题类型 工行接口中不存在 非必填
qustionsVO.setQuestionType("");
qustionsVOs.setQuestion(qustionsVO);
//扣款请求 工行报文中不存在该节点内容
QuquestVO ququestVO = new QuquestVO();
//账户类型 非必填
ququestVO.setAccountType("");
//银行代码 非必填
ququestVO.setBankCode("");
//卡号校验 非必填
ququestVO.setCardvalidity("");
//0有磁有密1无磁无密 非必填
ququestVO.setFeeMode("");
//电话 非必填
ququestVO.setMobile("");
//网点 非必填
ququestVO.setWebSite("");
//接口信息
List<RuleValidationVO> ruleValidationList = new ArrayList();
RuleValidationVO ruleValidationVO = new RuleValidationVO();
//返回接口编号 非必填
ruleValidationVO.setRuleCode("");
//返回接口名称 非必填
ruleValidationVO.setRuleDesc("");
ruleValidationList.add(ruleValidationVO);
policyVO.setBaseInfo(policyBaseInfoVO);
policyVO.setNuclear(nuclearVO);
policyVO.setPolicyBenefitList(policyBeneVOs);
policyVO.setPolicyCoverageList(policyCoverageVOs);
policyVO.setPolicyHolder(policyHolderVO);
policyVO.setPolicyInsuredList(policyInsuredVOs);
policyVO.setPolicyMaster(policyMasterVO);
policyVO.setPolicyPayerList(policyPayerList);
policyVO.setQuestions(qustionsVOs);
policyVO.setQuquest(ququestVO);
policyVO.setRuleValidationList(ruleValidationList);
freshPolicySignReqData.setPolicyVO(policyVO);
srvReqBizBody.setInputData(freshPolicySignReqData);
SRVReqHead srvReqHead = new SRVReqHead();
// srvReqHead.setButtonCode("10");
// srvReqHead.setInputId("10");
// srvReqHead.setIpStr("10");
// srvReqHead.setKeyCode("10");
// srvReqHead.setLogDetail("10");
reqBody.setBizHeader(srvReqHead);
reqBody.setBizBody(srvReqBizBody);
port.doRreshPolicySign(sysHeader, reqBody, resHeader, resBody);
System.out.println("doRreshPolicySign._doRreshPolicySign_parametersResHeader=" + resHeader.value.getResText());
System.out.println("doRreshPolicySign._doRreshPolicySign_parametersResBody=" + resBody.value);
//System.out.println(resBody.value.getBizBody().getFreshPolicySignRspData().getPolicyVO().getApplyCode());
XDCBResponse response = new XDCBResponse();
return response;
}
public static void main(String[] args) {
PiplineUtils piplineUtils = new PiplineUtils();
//piplineUtils.dodayCancellationOrder(new RefOrderRequest());
piplineUtils.newOrder(new XDCBRequest());
}
}
|
package com.staniul.teamspeak.modules.messengers;
import com.staniul.teamspeak.security.clientaccesscheck.ClientGroupAccess;
import com.staniul.teamspeak.commands.CommandResponse;
import com.staniul.teamspeak.commands.Teamspeak3Command;
import com.staniul.teamspeak.commands.validators.ValidateParams;
import com.staniul.teamspeak.query.Client;
import com.staniul.teamspeak.query.Query;
import com.staniul.teamspeak.query.QueryException;
import com.staniul.xmlconfig.CustomXMLConfiguration;
import com.staniul.xmlconfig.annotations.UseConfig;
import com.staniul.xmlconfig.annotations.WireConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Component
@UseConfig("modules/cp.xml")
public class ClientPoker {
@WireConfig
private CustomXMLConfiguration config;
private final Query query;
@Autowired
public ClientPoker(Query query) {
this.query = query;
}
private void internalPokeClients(Set<Integer> groups, String message) throws QueryException {
List<Client> clients;
if (groups == null) clients = query.getClientList();
else clients = query.getClientList().stream()
.filter(c -> c.isInServergroup(groups))
.collect(Collectors.toList());
for (Client client : clients)
query.pokeClient(client.getId(), message, true);
}
private CommandResponse response () {
return new CommandResponse(config.getString("response"));
}
@Teamspeak3Command("!pokeclients")
@ClientGroupAccess("servergroups.admins")
@ValidateParams(NotEmptyParamsValidator.class)
public CommandResponse pokeClients(Client client, String params) throws QueryException {
internalPokeClients(config.getIntSet("groups.clients"), params);
return response();
}
@Teamspeak3Command("!pokeadmins")
@ClientGroupAccess("servergroups.admins")
@ValidateParams(NotEmptyParamsValidator.class)
public CommandResponse pokeAdmins (Client client, String params) throws QueryException {
internalPokeClients(config.getIntSet("groups.admins"), params);
return response();
}
@Teamspeak3Command("!poke")
@ClientGroupAccess("servergroups.admins")
@ValidateParams(NotEmptyParamsValidator.class)
public CommandResponse pokeAll(Client client, String params) throws QueryException {
internalPokeClients(null, params);
return response();
}
}
|
package sg.edu.iss.ad.model;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="CandlesWatchList")
public class UserCandleWatchList {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private long DateTimeActive;
private boolean Active;
@ManyToOne
private Candle Candle;
@ManyToOne
private UserStockWatchList UserStockWatchList;
public UserCandleWatchList() {}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getDateTimeActive() {
return DateTimeActive;
}
public void setDateTimeActive(long dateTimeActive) {
DateTimeActive = dateTimeActive;
}
public Candle getCandle() {
return Candle;
}
public void setCandle(Candle candle) {
Candle = candle;
}
public UserStockWatchList getUserStockWatchList() {
return UserStockWatchList;
}
public void setUserStockWatchList(UserStockWatchList userStockWatchList) {
UserStockWatchList = userStockWatchList;
};
public boolean getActive() {
return Active;
}
public void setActive(boolean active) {
Active = active;
}
}
|
/*
* Welcome to use the TableGo Tools.
*
* http://vipbooks.iteye.com
* http://blog.csdn.net/vipbooks
* http://www.cnblogs.com/vipbooks
*
* Author:bianj
* Email:edinsker@163.com
* Version:5.8.0
*/
package com.lenovohit.hwe.pay.model;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.lenovohit.hwe.base.model.AuditableModel;
/**
* PAY_CASH_BATCH
*
* @author zyus
* @version 1.0.0 2017-12-22
*/
@Entity
@Table(name = "PAY_CASH_BATCH")
public class CashBatch extends AuditableModel implements java.io.Serializable {
/** 版本号 */
private static final long serialVersionUID = 3655251696801994332L;
/** batchNo */
private String batchNo;
/** printTime */
private Date printTime;
/** importTime */
private Date importTime;
/** count */
private Integer count;
/** amt */
private BigDecimal amt;
/** appCode */
private String appCode;
/** appName */
private String appName;
/**
* APP - APP SSM - SSM SSB - SSB
*/
private String appType;
/** terminalCode */
private String terminalCode;
/** terminalName */
private String terminalName;
/** terminalUser */
private String terminalUser;
/** batchDay */
private String batchDay;
/** bankAmt */
private BigDecimal bankAmt;
/** bankCount */
private Integer bankCount;
/** amt1 */
private BigDecimal amt1;
/** amt2 */
private BigDecimal amt2;
/** amt5 */
private BigDecimal amt5;
/** amt10 */
private BigDecimal amt10;
/** amt20 */
private BigDecimal amt20;
/** amt50 */
private BigDecimal amt50;
/** amt100 */
private BigDecimal amt100;
/** count1 */
private Integer count1;
/** count2 */
private Integer count2;
/** count5 */
private Integer count5;
/** count10 */
private Integer count10;
/** count20 */
private Integer count20;
/** count50 */
private Integer count50;
/** count100 */
private Integer count100;
/** A - 初始
0 - 正常
1 - 废弃 */
private String status;
/**
* 获取batchNo
*
* @return batchNo
*/
@Column(name = "BATCH_NO", nullable = true, length = 16)
public String getBatchNo() {
return this.batchNo;
}
/**
* 设置batchNo
*
* @param batchNo
*/
public void setBatchNo(String batchNo) {
this.batchNo = batchNo;
}
/**
* 获取printTime
*
* @return printTime
*/
@Column(name = "PRINT_TIME", nullable = true)
public Date getPrintTime() {
return this.printTime;
}
/**
* 设置printTime
*
* @param printTime
*/
public void setPrintTime(Date printTime) {
this.printTime = printTime;
}
/**
* 获取importTime
*
* @return importTime
*/
@Column(name = "IMPORT_TIME", nullable = true)
public Date getImportTime() {
return this.importTime;
}
/**
* 设置importTime
*
* @param importTime
*/
public void setImportTime(Date importTime) {
this.importTime = importTime;
}
/**
* 获取count
*
* @return count
*/
@Column(name = "COUNT", nullable = true, length = 10)
public Integer getCount() {
return this.count;
}
/**
* 设置count
*
* @param count
*/
public void setCount(Integer count) {
this.count = count;
}
/**
* 获取amt
*
* @return amt
*/
@Column(name = "AMT", nullable = true)
public BigDecimal getAmt() {
return this.amt;
}
/**
* 设置amt
*
* @param amt
*/
public void setAmt(BigDecimal amt) {
this.amt = amt;
}
/**
* 获取appCode
*
* @return appCode
*/
@Column(name = "APP_CODE", nullable = true, length = 32)
public String getAppCode() {
return this.appCode;
}
/**
* 设置appCode
*
* @param appCode
*/
public void setAppCode(String appCode) {
this.appCode = appCode;
}
/**
* 获取appName
*
* @return appName
*/
@Column(name = "APP_NAME", nullable = true, length = 50)
public String getAppName() {
return this.appName;
}
/**
* 设置appName
*
* @param appName
*/
public void setAppName(String appName) {
this.appName = appName;
}
/**
* 获取APP - APP
SSM - SSM
SSB - SSB
*
* @return APP - APP
SSM - SSM
SSB - SSB
*/
@Column(name = "APP_TYPE", nullable = true, length = 3)
public String getAppType() {
return this.appType;
}
/**
* 设置APP - APP
SSM - SSM
SSB - SSB
*
* @param appType
* APP - APP
SSM - SSM
SSB - SSB
*/
public void setAppType(String appType) {
this.appType = appType;
}
/**
* 获取terminalCode
*
* @return terminalCode
*/
@Column(name = "TERMINAL_CODE", nullable = true, length = 50)
public String getTerminalCode() {
return this.terminalCode;
}
/**
* 设置terminalCode
*
* @param terminalCode
*/
public void setTerminalCode(String terminalCode) {
this.terminalCode = terminalCode;
}
/**
* 获取terminalName
*
* @return terminalName
*/
@Column(name = "TERMINAL_NAME", nullable = true, length = 70)
public String getTerminalName() {
return this.terminalName;
}
/**
* 设置terminalName
*
* @param terminalName
*/
public void setTerminalName(String terminalName) {
this.terminalName = terminalName;
}
/**
* 获取terminalUser
*
* @return terminalUser
*/
@Column(name = "TERMINAL_USER", nullable = true, length = 50)
public String getTerminalUser() {
return this.terminalUser;
}
/**
* 设置terminalUser
*
* @param terminalUser
*/
public void setTerminalUser(String terminalUser) {
this.terminalUser = terminalUser;
}
/**
* 获取batchDay
*
* @return batchDay
*/
@Column(name = "BATCH_DAY", nullable = true, length = 20)
public String getBatchDay() {
return this.batchDay;
}
/**
* 设置batchDay
*
* @param batchDay
*/
public void setBatchDay(String batchDay) {
this.batchDay = batchDay;
}
/**
* 获取bankAmt
*
* @return bankAmt
*/
@Column(name = "BANK_AMT", nullable = true)
public BigDecimal getBankAmt() {
return this.bankAmt;
}
/**
* 设置bankAmt
*
* @param bankAmt
*/
public void setBankAmt(BigDecimal bankAmt) {
this.bankAmt = bankAmt;
}
/**
* 获取bankCount
*
* @return bankCount
*/
@Column(name = "BANK_COUNT", nullable = true, length = 10)
public Integer getBankCount() {
return this.bankCount;
}
/**
* 设置bankCount
*
* @param bankCount
*/
public void setBankCount(Integer bankCount) {
this.bankCount = bankCount;
}
/**
* 获取amt1
*
* @return amt1
*/
@Column(name = "AMT1", nullable = true)
public BigDecimal getAmt1() {
return this.amt1;
}
/**
* 设置amt1
*
* @param amt1
*/
public void setAmt1(BigDecimal amt1) {
this.amt1 = amt1;
}
/**
* 获取amt2
*
* @return amt2
*/
@Column(name = "AMT2", nullable = true)
public BigDecimal getAmt2() {
return this.amt2;
}
/**
* 设置amt2
*
* @param amt2
*/
public void setAmt2(BigDecimal amt2) {
this.amt2 = amt2;
}
/**
* 获取amt5
*
* @return amt5
*/
@Column(name = "AMT5", nullable = true)
public BigDecimal getAmt5() {
return this.amt5;
}
/**
* 设置amt5
*
* @param amt5
*/
public void setAmt5(BigDecimal amt5) {
this.amt5 = amt5;
}
/**
* 获取amt10
*
* @return amt10
*/
@Column(name = "AMT10", nullable = true)
public BigDecimal getAmt10() {
return this.amt10;
}
/**
* 设置amt10
*
* @param amt10
*/
public void setAmt10(BigDecimal amt10) {
this.amt10 = amt10;
}
/**
* 获取amt20
*
* @return amt20
*/
@Column(name = "AMT20", nullable = true)
public BigDecimal getAmt20() {
return this.amt20;
}
/**
* 设置amt20
*
* @param amt20
*/
public void setAmt20(BigDecimal amt20) {
this.amt20 = amt20;
}
/**
* 获取amt50
*
* @return amt50
*/
@Column(name = "AMT50", nullable = true)
public BigDecimal getAmt50() {
return this.amt50;
}
/**
* 设置amt50
*
* @param amt50
*/
public void setAmt50(BigDecimal amt50) {
this.amt50 = amt50;
}
/**
* 获取amt100
*
* @return amt100
*/
@Column(name = "AMT100", nullable = true)
public BigDecimal getAmt100() {
return this.amt100;
}
/**
* 设置amt100
*
* @param amt100
*/
public void setAmt100(BigDecimal amt100) {
this.amt100 = amt100;
}
/**
* 获取count1
*
* @return count1
*/
@Column(name = "COUNT1", nullable = true, length = 10)
public Integer getCount1() {
return this.count1;
}
/**
* 设置count1
*
* @param count1
*/
public void setCount1(Integer count1) {
this.count1 = count1;
}
/**
* 获取count2
*
* @return count2
*/
@Column(name = "COUNT2", nullable = true, length = 10)
public Integer getCount2() {
return this.count2;
}
/**
* 设置count2
*
* @param count2
*/
public void setCount2(Integer count2) {
this.count2 = count2;
}
/**
* 获取count5
*
* @return count5
*/
@Column(name = "COUNT5", nullable = true, length = 10)
public Integer getCount5() {
return this.count5;
}
/**
* 设置count5
*
* @param count5
*/
public void setCount5(Integer count5) {
this.count5 = count5;
}
/**
* 获取count10
*
* @return count10
*/
@Column(name = "COUNT10", nullable = true, length = 10)
public Integer getCount10() {
return this.count10;
}
/**
* 设置count10
*
* @param count10
*/
public void setCount10(Integer count10) {
this.count10 = count10;
}
/**
* 获取count20
*
* @return count20
*/
@Column(name = "COUNT20", nullable = true, length = 10)
public Integer getCount20() {
return this.count20;
}
/**
* 设置count20
*
* @param count20
*/
public void setCount20(Integer count20) {
this.count20 = count20;
}
/**
* 获取count50
*
* @return count50
*/
@Column(name = "COUNT50", nullable = true, length = 10)
public Integer getCount50() {
return this.count50;
}
/**
* 设置count50
*
* @param count50
*/
public void setCount50(Integer count50) {
this.count50 = count50;
}
/**
* 获取count100
*
* @return count100
*/
@Column(name = "COUNT100", nullable = true, length = 10)
public Integer getCount100() {
return this.count100;
}
/**
* 设置count100
*
* @param count100
*/
public void setCount100(Integer count100) {
this.count100 = count100;
}
/**
* 获取A - 初始
0 - 正常
1 - 废弃
*
* @return A - 初始
0 - 正常
1 - 废弃
*/
@Column(name = "STATUS", nullable = true, length = 1)
public String getStatus() {
return this.status;
}
/**
* 设置A - 初始
0 - 正常
1 - 废弃
*
* @param status
* A - 初始
0 - 正常
1 - 废弃
*/
public void setStatus(String status) {
this.status = status;
}
} |
/*
* 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 parcial2;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Leonardo
*/
public class Tester {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Estacionamento estacionamento = new Estacionamento();
Automovel a = new Automovel("Leonardo", "DDD8223", "Ford", "74125896325", "3373-0585", Tipo.CARRO);
Automovel a1 = new Automovel("Fulano", "AAA1724", "Ford", "15247856932", "3215-5623", Tipo.CARRO);
Automovel a2 = new Automovel("Joao", "XXX1423", "Ford", "45896321458", "3652-9658", Tipo.CARRO);
Moto m = new Moto("Maria", "AAA9999", "Yamaha", "14523698745", "3265-8522", Tipo.MOTO);
estacionamento.estaciona(a);
estacionamento.estaciona(a2);
estacionamento.estaciona(m);
estacionamento.estaciona(a1);
estacionamento.listarEmOrdem();
estacionamento.retira(m, 20);
estacionamento.listarEmOrdem();
}
} |
package com.arthur.leetcode;
import java.util.Stack;
/**
* @title: No1047
* @Author ArthurJi
* @Date: 2021/3/9 9:56
* @Version 1.0
*/
public class No1047 {
public static void main(String[] args) {
}
public String removeDuplicates(String S) {
char[] s = S.toCharArray();
int top = -1; //当top == -1的时候,说明现在什么都没有了
for (int i = 0; i < s.length; i++) {
if (top == -1 || s[i] != s[top]) {
s[++top] = s[i];
} else {
top--;
}
}
return String.valueOf(s, 0, top + 1);
}
public String removeDuplicates_2(String S) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < S.length(); i++) {
if (stack.isEmpty() || S.charAt(i) != stack.peek()) {
stack.push(S.charAt(i));
} else {
stack.pop();
}
}
StringBuilder ans = new StringBuilder();
for (Character ch : stack) {
ans.append(ch);
}
return String.valueOf(ans);
}
}
/*
1047. 删除字符串中的所有相邻重复项
给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
示例:
输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
*/
|
package StackCalculator;
import StackCalculator.Command.CommandFactory;
import StackCalculator.Command.Invert;
import StackCalculator.Command.Sum;
import StackCalculator.Exceptions.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
try {
calculator.ExecuteCommands("in.txt", "cfg.txt");
} catch (WrongConfigFileFormat wrongConfigFileFormat) {
wrongConfigFileFormat.PrintError();
} catch (WrongAmountOfArguments wrongAmountOfArguments) {
wrongAmountOfArguments.PrintArguments();
} catch (VarNameHasAlreadyExist varNameHasAlreadyExist) {
varNameHasAlreadyExist.PrintError();
} catch (UndefinedVariable undefinedVariable) {
undefinedVariable.PrintError();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package net.minecraftforge.forgespi;
import cpw.mods.modlauncher.api.IEnvironment;
import cpw.mods.modlauncher.api.TypesafeMap;
import net.minecraftforge.api.distmarker.Dist;
import java.util.function.Supplier;
/**
* Global environment variables - allows discoverability with other systems without full forge
* dependency
*/
public class Environment {
public static final class Keys {
/**
* The @{@link Dist} which is running.
* Populated by forge during {@link cpw.mods.modlauncher.api.ITransformationService#initialize(IEnvironment)}
*/
public static final Supplier<TypesafeMap.Key<Dist>> DIST = IEnvironment.buildKey("FORGEDIST", Dist.class);
}
private static Environment INSTANCE;
public static void build(IEnvironment environment) {
if (INSTANCE != null) throw new RuntimeException("Environment is a singleton");
INSTANCE = new Environment(environment);
}
public static Environment get() {
return INSTANCE;
}
private final IEnvironment environment;
private final Dist dist;
private Environment(IEnvironment setup) {
this.environment = setup;
this.dist = setup.getProperty(Keys.DIST.get()).orElseThrow(()->new RuntimeException("Missing DIST in environment!"));
}
public Dist getDist() {
return this.dist;
}
}
|
package ua.com.rd.pizzaservice.domain.discount.pizzadiscount;
import org.junit.Before;
import org.junit.Test;
import ua.com.rd.pizzaservice.domain.pizza.Pizza;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class DiscountEachNPizzaKPercentsTest {
private DiscountEachNPizzaKPercents discount;
@Before
public void setUp() {
discount = new DiscountEachNPizzaKPercents(4, 50.);
}
@Test
public void calculateDiscountForThreePizzasShouldBeZero() {
Map<Pizza, Integer> pizzas = new HashMap<Pizza, Integer>() {{
put(new Pizza("Pizza 1", 100., Pizza.PizzaType.MEAT), 1);
put(new Pizza("Pizza 2", 120., Pizza.PizzaType.SEA), 1);
put(new Pizza("Pizza 3", 110., Pizza.PizzaType.MEAT), 1);
}};
discount.setPizzas(pizzas);
Double expected = 0.;
assertEquals(expected, discount.calculate());
}
@Test
public void calculateDiscountForFourPizzasShouldBeNotZero() {
Map<Pizza, Integer> pizzas = new HashMap<Pizza, Integer>() {{
put(new Pizza("Pizza 1", 100., Pizza.PizzaType.MEAT), 1);
put(new Pizza("Pizza 2", 110., Pizza.PizzaType.SEA), 2);
put(new Pizza("Pizza 3", 120., Pizza.PizzaType.SEA), 1);
}};
discount.setPizzas(pizzas);
Double expected = 60.;
assertEquals(expected, discount.calculate());
}
@Test
public void calculateDiscountForSevenPizzasShouldBeNotZero() {
Map<Pizza, Integer> pizzas = new HashMap<Pizza, Integer>() {{
put(new Pizza("Pizza 1", 100., Pizza.PizzaType.MEAT), 1);
put(new Pizza("Pizza 2", 110., Pizza.PizzaType.SEA), 4);
put(new Pizza("Pizza 3", 120., Pizza.PizzaType.SEA), 2);
}};
discount.setPizzas(pizzas);
Double expected = 60.;
assertEquals(expected, discount.calculate());
}
@Test
public void getDiscountForEightPizzasShouldBeNotZero() {
Map<Pizza, Integer> pizzas = new HashMap<Pizza, Integer>() {{
put(new Pizza("Pizza 1", 100., Pizza.PizzaType.MEAT), 1);
put(new Pizza("Pizza 2", 120., Pizza.PizzaType.SEA), 6);
put(new Pizza("Pizza 3", 140., Pizza.PizzaType.SEA), 1);
}};
discount.setPizzas(pizzas);
Double expected = 130.;
assertEquals(expected, discount.calculate());
}
}
|
package com.gestion.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import com.gestion.entity.InventaireClient;
import com.gestion.service.ServiceInventaireClient;
import fr.cortex2i.utils.HibernateUtils;
/**
* Servlet implementation class ServletRechercheInventaire
*/
@WebServlet("/ServletRechercheInventaire")
public class ServletRechercheInventaire extends HttpServlet {
private static final long serialVersionUID = 1L;
Session s = null ;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletRechercheInventaire() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
s = HibernateUtils.getSession();
String message = null ;
InventaireClient inv = new InventaireClient();
inv.setIdInventaire(Integer.parseInt(request.getParameter("idInvR")));
inv = ServiceInventaireClient.rechercheInventaireClient(s, inv);
if(inv != null)
{
message = "Inventaire existe";
request.setAttribute("invR",inv);
}
else
{
message = "Inventaire n'existe pas!";
}
request.setAttribute("messageR", message);
request.getServletContext().getRequestDispatcher("/ServletGestionInventaire").forward(request, response);
s.close();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
|
package com.apps.nowmusicstream;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.adapter.AdapterPlayListSongList;
import com.apps.interfaces.ClickListenerPlayList;
import com.apps.item.ItemPlayList;
import com.apps.item.ItemSong;
import com.apps.utils.Constant;
import com.apps.utils.DBHelper;
import com.apps.utils.JsonUtils;
import com.apps.utils.ZProgressHUD;
import com.google.android.gms.ads.AdListener;
import java.util.ArrayList;
public class FragmentSongByPlaylist extends Fragment {
DBHelper dbHelper;
RecyclerView recyclerView;
ItemPlayList itemPlayList;
ArrayList<ItemSong> arrayList;
public static AdapterPlayListSongList adapterSongList;
ZProgressHUD progressHUD;
LinearLayoutManager linearLayoutManager;
TextView textView_empty;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_song_by_cat, container, false);
dbHelper = new DBHelper(getActivity());
progressHUD = ZProgressHUD.getInstance(getActivity());
progressHUD.setMessage(getResources().getString(R.string.loading));
progressHUD.setSpinnerType(ZProgressHUD.FADED_ROUND_SPINNER);
itemPlayList = (ItemPlayList) getArguments().getSerializable("playlist");
((MainActivity) getActivity()).getSupportActionBar().setTitle(itemPlayList.getName());
textView_empty = (TextView) rootView.findViewById(R.id.textView_empty_artist);
arrayList = new ArrayList<>();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView_songbycat);
linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
arrayList.addAll(dbHelper.loadDataPlaylist(itemPlayList.getId()));
adapterSongList = new AdapterPlayListSongList(getActivity(), arrayList, new ClickListenerPlayList() {
@Override
public void onClick(int position) {
if (JsonUtils.isNetworkAvailable(getActivity())) {
showInter(position);
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onItemZero() {
setEmpty();
}
});
recyclerView.setAdapter(adapterSongList);
setEmpty();
return rootView;
}
private void setEmpty() {
if (arrayList.size() == 0) {
textView_empty.setVisibility(View.VISIBLE);
} else {
textView_empty.setVisibility(View.GONE);
}
}
private void showInter(final int pos) {
Constant.adCount = Constant.adCount + 1;
if (Constant.adCount % Constant.adDisplay == 0) {
((MainActivity) getActivity()).mInterstitial.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
playIntent(pos);
super.onAdClosed();
}
});
if (((MainActivity) getActivity()).mInterstitial.isLoaded()) {
((MainActivity) getActivity()).mInterstitial.show();
((MainActivity) getActivity()).loadInter();
} else {
playIntent(pos);
}
} else {
playIntent(pos);
}
}
private void playIntent(int position) {
Constant.isOnline = true;
Constant.frag = "play";
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList);
Constant.playPos = position;
((MainActivity) getActivity()).changeText(arrayList.get(position).getMp3Name(), arrayList.get(position).getCategoryName(), position + 1, arrayList.size(), arrayList.get(position).getDuration(), arrayList.get(position).getImageBig(), arrayList.get(position).getAverageRating(), "cat");
Constant.context = getActivity();
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
} |
package ca.usask.cs.srlab.simclipse.ui.view.navigator;
import java.util.ArrayList;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;
public class NavigatorComposedAdapterFactory {
private static ComposedAdapterFactory mnCompAdapterFactory;
public final static ComposedAdapterFactory getAdapterFactory()
{
if (mnCompAdapterFactory == null)
mnCompAdapterFactory = new ComposedAdapterFactory(createFactoryList());
return mnCompAdapterFactory;
}
public final static ArrayList<AdapterFactory> createFactoryList()
{
ArrayList<AdapterFactory> factories = new ArrayList<AdapterFactory>();
factories.add(new ResourceItemProviderAdapterFactory());
// factories.add(new EcoreItemProviderAdapterFactory());
factories.add(new ReflectiveItemProviderAdapterFactory());
return factories;
}
}
|
package com.shiva.lab3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class MainActivity extends Activity{
Button b1,b2,b3,b4;
private TextView t1;
private EditText edittext;
String output="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//_activity = UnityPlayer.currentActivity;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
b1 = (Button) findViewById(R.id.createBtn);
b2 = (Button) findViewById(R.id.insertBtn);
b3 = (Button) findViewById(R.id.retrieveBtn);
b4 = (Button) findViewById(R.id.deleteBtn);
t1 = (TextView) findViewById(R.id.resultView);
edittext=(EditText)findViewById(R.id.editText1);
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
output=runHbaseCreate(edittext.getText().toString());
t1.setText(output);
}
});
b2.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
output=runHbaseInsert(edittext.getText().toString());
t1.setText(output);
}
});
b3.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
output=runHbaseRetrieveAll(edittext.getText().toString());
t1.setText(output);
}
});
b4.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
output=runHbaseDelete(edittext.getText().toString());
t1.setText(output);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
public String runHbaseCreate(String tname)
{
try {
String furl="http://10.0.2.2:8080/HbaseWS/jaxrs/generic/hbaseCreate/"+tname+"/GeoLocation:Date:Accelerometer:Humidity:Temperature";
URL url = new URL(furl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine,result="";
while ((inputLine = in.readLine()) != null) {
// Process each line.
//System.out.println(inputLine);
result+=inputLine;
}
in.close();
return result.toString();
} catch (MalformedURLException me) {
System.out.println(me);
return me.toString();
} catch (IOException ioe) {
System.out.println(ioe);
return ioe.toString();
}
}
public String runHbaseInsert(String tname)
{
try {
String furl= "http://10.0.2.2:8080/HbaseWS/jaxrs/generic/hbaseInsert/"+tname+"/C:-Users-vgz8b-Documents-sensor.txt/GeoLocation:Date:Accelerometer:Humidity:Temperature";
URL url = new URL(furl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine,result="";
while ((inputLine = in.readLine()) != null) {
// Process each line.
System.out.println(inputLine);
result+=inputLine;
}
in.close();
return result.toString();
} catch (MalformedURLException me) {
System.out.println(me);
return me.toString();
} catch (IOException ioe) {
System.out.println(ioe);
return ioe.toString();
}
}
public String runHbaseRetrieveAll(String tname)
{
try {
String furl="http://10.0.2.2:8080/HbaseWS/jaxrs/generic/hbaseRetrieveAll/"+tname;
URL url = new URL(furl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine="",result="";
while ((inputLine = in.readLine()) != null) {
// Process each line.
System.out.println(inputLine);
result+=inputLine;
}
in.close();
return result.toString();
} catch (MalformedURLException me) {
System.out.println(me);
return me.toString();
} catch (IOException ioe) {
System.out.println(ioe);
return ioe.toString();
}
}
public String runHbaseDelete(String tname)
{
try {
String furl="http://10.0.2.2:8080/HbaseWS/jaxrs/generic/hbasedeletel/"+tname;
URL url = new URL(furl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine,result="";
while ((inputLine = in.readLine()) != null) {
// Process each line.
//System.out.println(inputLine);
result+=inputLine;
}
in.close();
return result.toString();
} catch (MalformedURLException me) {
System.out.println(me);
return me.toString();
} catch (IOException ioe) {
System.out.println(ioe);
return ioe.toString();
}
}
}
|
package Application.Controller;
import Application.Algorithm.Parameters;
import Application.Model.ProblemResults;
import Application.Service.PSOService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Arrays;
@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/api/pso")
@Slf4j
public class PSOController {
private PSOService service;
public PSOController(PSOService service){
this.service=service;
}
@GetMapping("/mccormick")
public ResponseEntity<ProblemResults> solveMcCormick(Parameters initParameters, @RequestParam Double[] param1Domain, @RequestParam Double[] param2Domain){
log.info("GET request for solve mccormick");
ProblemResults problemResults = service.solveMcCormick(initParameters, param1Domain, param2Domain);
return new ResponseEntity<ProblemResults>(problemResults, HttpStatus.OK);
}
@GetMapping("/michalewicz")
public ResponseEntity<ProblemResults> solveMichalewicz(Parameters initParameters, @RequestParam Double[] param1Domain, @RequestParam Double[] param2Domain){
log.info("GET request for solve michalewicz");
ProblemResults problemResults = service.solveMichalewicz(initParameters, param1Domain, param2Domain);
return new ResponseEntity<ProblemResults>(problemResults, HttpStatus.OK);
}
@CrossOrigin(origins = "*")
@GetMapping("/ackley")
public ResponseEntity<ProblemResults> solveAckley(Parameters initParameters, @RequestParam Double dimension){
log.info("GET request for solve ackley");
ProblemResults problemResults = service.solveAckley(initParameters, dimension);
return new ResponseEntity<ProblemResults>(problemResults, HttpStatus.OK);
}
}
|
package algorithms.graph.process;
import java.util.Collection;
import algorithms.context.AbstractContextTest;
import algorithms.graph.Edge;
import algorithms.graph.EdgeWeightedGraph;
import algorithms.graph.MST;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
/**
* Created by Chen Li on 2018/5/13.
*/
@Slf4j
public abstract class AbstractMSTTest extends AbstractContextTest {
protected abstract MST getMST();
protected abstract EdgeWeightedGraph getGraph();
@Test
public void doTest() throws Exception {
MST mst = getMST();
EdgeWeightedGraph graph = getGraph();
mst.init(graph);
Collection<Edge> mstEdges = mst.edges();
StringBuilder sb = new StringBuilder();
for (Edge mstEdge : mstEdges) {
sb.append(mstEdge).append("\n");
}
System.out.println(sb);
Thread.sleep(10);
}
}
|
import java.rmi.*;
public interface Interest extends Remote {
public float simple(float p, float t,float r) throws RemoteException;
public float compound(float p,float t,float r,float n) throws RemoteException;
} |
package lab5;
import java.util.Scanner;
public class HSHocSinh extends Nguoi {
private String lop;
private String khoaHoc;
private int kyHoc;
public HSHocSinh() {
super();
}
public HSHocSinh(String lop, String khoaHoc, int kyHoc) {
super();
this.lop = lop;
this.khoaHoc = khoaHoc;
this.kyHoc = kyHoc;
}
void nhap() {
Scanner scanner = new Scanner(System.in);
System.out.println("Nhap lop");
lop = scanner.nextLine();
System.out.println("Nhap khoa hoc");
khoaHoc = scanner.nextLine();
System.out.println("Nhap ky hoc");
kyHoc = scanner.nextInt();
}
void xuat() {
System.out.println("Ten :" + hoTen);
System.out.println("Ngay Sinh :" + ngaySinh);
System.out.println("Que Quan :" + queQuan);
System.out.println("Lop :" + lop);
System.out.println("Khoa hoc :" + khoaHoc);
System.out.println("Ky Hoc :" + kyHoc);
}
}
|
package com.lenovohit.ssm;
public class SSMConstants {
public static String SSM_MACHINE_KEY="ssm_machine";
public static String SSM_PATIENT_KEY="ssm_patient";
}
|
import java.util.LinkedList;
import java.util.Stack;
import java.util.Scanner;
public class CommonSubs {
static int[][] longestCommonSubsequence(int[] a, int[] b) {
// Complete this function
int[][] calcMatr= new int[b.length + 1][a.length + 1];
for (int i = 1; i <calcMatr.length; i++) {
for (int j = 1; j < calcMatr[0].length; j++) {
// System.out.print("A is "+ a[j-1]+" B IS "+b[i-1]+'\n');
if (a[j-1] == b[i-1]) {
calcMatr[i][j] = calcMatr[i - 1][j - 1] + 1;
} else {
calcMatr[i][j] = Math.max(calcMatr[i - 1][j], calcMatr[i][j - 1]);
}
}
}
return calcMatr;
}
static int[] backtrack(int[][] arr,int a[],int b[]) {
int i=arr[0].length-1;
int j=arr.length-1;
Stack stack=new Stack<Integer>();
// System.out.print(i+" "+j);
while(i>0 && j>0){
// System.out.print(i+" "+j);
if(a[i-1]==b[j-1]){
stack.push(b[j-1]);
// System.out.print(b[j-1]+" ");
i--;
j--;
}
else if(arr[j][i-1]>arr[j-1][i]) i--;
else j--;
}
int[] result=new int[stack.size()];
int index=0;
while(!stack.empty()){
result[index++]=(Integer)stack.pop();
// index++;
}
return result;
/* if(number==arr[i][j-1]) backtrack(arr,arr[i][j-1],a,b);
else if(number==arr[i-1][j-1]) backtrack(arr,arr[i-1][j],a,b);
else if(number>arr[i][j-1]&&number>arr[j-1][i]) backtrack(arr,arr[i-1][j-1],a,b);
else if(number>arr[i][j-1]&&number>arr[j-1][i]&&arr[i-1][j-1]==0) return ;
*/
//System.out.print()
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
int a[] = new int[n];
int b[] = new int[m];
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (int j = 0; j < m; j++) {
b[j] = s.nextInt();
}
// for (int i = 0; i < n; i++) System.out.print(a[i] + " ");
//for (int i = 0; i < m; i++) System.out.print(b[i] + " ");
int[][] matrix = longestCommonSubsequence(a, b);
for (int i = 1; i < matrix.length; i++) {
for (int j = 1; j < matrix[0].length; j++) {
// System.out.print(matrix[i][j] + " ");
}
// System.out.println();
}
int result[]=backtrack(matrix,a,b);
for(int i=0;i<result.length;i++) System.out.print(result[i]+" ");
}
}
|
package ioprintwriter.salary;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class SalaryWriter {
private List<String> names;
public SalaryWriter(List<String> names) {
if (names == null) {
throw new IllegalArgumentException("names can't be null");
}
this.names = names;
}
public void writeNamesAndSalaries(Path file) {
if (file == null) {
throw new IllegalArgumentException("file can't be null");
}
try (PrintWriter printWriter = new PrintWriter(Files.newBufferedWriter(file))) {
for (String item : names) {
if (item.startsWith("Dr")) {
printWriter.println(item + ": 500000");
} else if (item.startsWith("Mr")) {
printWriter.println(item + ": 200000");
} else {
printWriter.println(item + ": 100000");
}
}
} catch (IOException ex) {
throw new IllegalStateException("File write error");
}
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables.records;
import java.sql.Timestamp;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record6;
import org.jooq.Row6;
import org.jooq.impl.UpdatableRecordImpl;
import schema.tables.MilestonesMilestonerelationshiptype;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class MilestonesMilestonerelationshiptypeRecord extends UpdatableRecordImpl<MilestonesMilestonerelationshiptypeRecord> implements Record6<Integer, Timestamp, Timestamp, String, String, Byte> {
private static final long serialVersionUID = 1280133920;
/**
* Setter for <code>bitnami_edx.milestones_milestonerelationshiptype.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>bitnami_edx.milestones_milestonerelationshiptype.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>bitnami_edx.milestones_milestonerelationshiptype.created</code>.
*/
public void setCreated(Timestamp value) {
set(1, value);
}
/**
* Getter for <code>bitnami_edx.milestones_milestonerelationshiptype.created</code>.
*/
public Timestamp getCreated() {
return (Timestamp) get(1);
}
/**
* Setter for <code>bitnami_edx.milestones_milestonerelationshiptype.modified</code>.
*/
public void setModified(Timestamp value) {
set(2, value);
}
/**
* Getter for <code>bitnami_edx.milestones_milestonerelationshiptype.modified</code>.
*/
public Timestamp getModified() {
return (Timestamp) get(2);
}
/**
* Setter for <code>bitnami_edx.milestones_milestonerelationshiptype.name</code>.
*/
public void setName(String value) {
set(3, value);
}
/**
* Getter for <code>bitnami_edx.milestones_milestonerelationshiptype.name</code>.
*/
public String getName() {
return (String) get(3);
}
/**
* Setter for <code>bitnami_edx.milestones_milestonerelationshiptype.description</code>.
*/
public void setDescription(String value) {
set(4, value);
}
/**
* Getter for <code>bitnami_edx.milestones_milestonerelationshiptype.description</code>.
*/
public String getDescription() {
return (String) get(4);
}
/**
* Setter for <code>bitnami_edx.milestones_milestonerelationshiptype.active</code>.
*/
public void setActive(Byte value) {
set(5, value);
}
/**
* Getter for <code>bitnami_edx.milestones_milestonerelationshiptype.active</code>.
*/
public Byte getActive() {
return (Byte) get(5);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record6 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row6<Integer, Timestamp, Timestamp, String, String, Byte> fieldsRow() {
return (Row6) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row6<Integer, Timestamp, Timestamp, String, String, Byte> valuesRow() {
return (Row6) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return MilestonesMilestonerelationshiptype.MILESTONES_MILESTONERELATIONSHIPTYPE.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field2() {
return MilestonesMilestonerelationshiptype.MILESTONES_MILESTONERELATIONSHIPTYPE.CREATED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field3() {
return MilestonesMilestonerelationshiptype.MILESTONES_MILESTONERELATIONSHIPTYPE.MODIFIED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field4() {
return MilestonesMilestonerelationshiptype.MILESTONES_MILESTONERELATIONSHIPTYPE.NAME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field5() {
return MilestonesMilestonerelationshiptype.MILESTONES_MILESTONERELATIONSHIPTYPE.DESCRIPTION;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Byte> field6() {
return MilestonesMilestonerelationshiptype.MILESTONES_MILESTONERELATIONSHIPTYPE.ACTIVE;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value2() {
return getCreated();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value3() {
return getModified();
}
/**
* {@inheritDoc}
*/
@Override
public String value4() {
return getName();
}
/**
* {@inheritDoc}
*/
@Override
public String value5() {
return getDescription();
}
/**
* {@inheritDoc}
*/
@Override
public Byte value6() {
return getActive();
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesMilestonerelationshiptypeRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesMilestonerelationshiptypeRecord value2(Timestamp value) {
setCreated(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesMilestonerelationshiptypeRecord value3(Timestamp value) {
setModified(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesMilestonerelationshiptypeRecord value4(String value) {
setName(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesMilestonerelationshiptypeRecord value5(String value) {
setDescription(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesMilestonerelationshiptypeRecord value6(Byte value) {
setActive(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesMilestonerelationshiptypeRecord values(Integer value1, Timestamp value2, Timestamp value3, String value4, String value5, Byte value6) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached MilestonesMilestonerelationshiptypeRecord
*/
public MilestonesMilestonerelationshiptypeRecord() {
super(MilestonesMilestonerelationshiptype.MILESTONES_MILESTONERELATIONSHIPTYPE);
}
/**
* Create a detached, initialised MilestonesMilestonerelationshiptypeRecord
*/
public MilestonesMilestonerelationshiptypeRecord(Integer id, Timestamp created, Timestamp modified, String name, String description, Byte active) {
super(MilestonesMilestonerelationshiptype.MILESTONES_MILESTONERELATIONSHIPTYPE);
set(0, id);
set(1, created);
set(2, modified);
set(3, name);
set(4, description);
set(5, active);
}
}
|
package exercicio04;
import java.util.Calendar;
public class Datetime
{
private static final String YEAR = null;
private static final String MONTH = null;
private static final String DAY_OF_MONTH = null;
public static void main(String[] args) {
Datetime c = Datetime.getInstance();
System.out.println("Data/Hora atual: "+c.getTime());
System.out.println("Ano: "+c.get(Datetime.YEAR));
System.out.println("MÍs: "+c.get(Datetime.MONTH));
System.out.println("Dia do MÍs: "+c.get(Datetime.DAY_OF_MONTH));
}
private String get(String year) {
// TODO Auto-generated method stub
return null;
}
private String getTime() {
// TODO Auto-generated method stub
return null;
}
private static Datetime getInstance() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.edu.realestate.yelp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class YelpEvent extends YelpElement {
private String description;
private boolean free;
private LocalDateTime timeStart;
private LocalDateTime timeEnd;
public YelpEvent(String name, String url, String description, boolean free, LocalDateTime timeStart,
LocalDateTime timeEnd, String address) {
super(name, url, address);
this.description = description;
this.free = free;
this.timeStart = timeStart;
this.timeEnd = timeEnd;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isFree() {
return free;
}
public void setFree(boolean free) {
this.free = free;
}
public LocalDateTime getTimeStart() {
return timeStart;
}
public void setTimeStart(LocalDateTime timeStart) {
this.timeStart = timeStart;
}
public LocalDateTime getTimeEnd() {
return timeEnd;
}
public void setTimeEnd(LocalDateTime timeEnd) {
this.timeEnd = timeEnd;
}
public String formatDateTime(LocalDateTime ldt) {
return ldt.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"));
}
@Override
public String toString() {
return "YelpEvent [" + super.toString() + ", description=" + description + ", free=" + free
+ ", timeStart=" + timeStart + ", timeEnd=" + timeEnd + "]";
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.burgosanchez.tcc.venta.ejb;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author TID01
*/
@Entity
@Table(name = "LOCALIDAD", catalog = "", schema = "TCC")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Localidad.findAll", query = "SELECT l FROM Localidad l")})
public class Localidad implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 30)
@Column(name = "COD_LOCALIDAD")
private String codLocalidad;
@Size(max = 256)
@Column(name = "DESCRIPCION")
private String descripcion;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "localidad")
private List<LocalidadEvento> localidadEventoList;
public Localidad() {
}
public Localidad(String codLocalidad) {
this.codLocalidad = codLocalidad;
}
public String getCodLocalidad() {
return codLocalidad;
}
public void setCodLocalidad(String codLocalidad) {
this.codLocalidad = codLocalidad;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
@XmlTransient
public List<LocalidadEvento> getLocalidadEventoList() {
return localidadEventoList;
}
public void setLocalidadEventoList(List<LocalidadEvento> localidadEventoList) {
this.localidadEventoList = localidadEventoList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (codLocalidad != null ? codLocalidad.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Localidad)) {
return false;
}
Localidad other = (Localidad) object;
if ((this.codLocalidad == null && other.codLocalidad != null) || (this.codLocalidad != null && !this.codLocalidad.equals(other.codLocalidad))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.burgosanchez.tcc.venta.ejb.Localidad[ codLocalidad=" + codLocalidad + " ]";
}
}
|
package com.sda.company.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "company")
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "registration_number")
private String registrationNumber;
@Column(name = "address")
private String address;
@Column(name = "phone_number")
private String phoneNumber;
@Column(name = "email")
private String email;
@OneToMany(mappedBy = "company",
targetEntity = Employee.class,
cascade = CascadeType.ALL,
fetch = FetchType.EAGER
)
@JsonIgnoreProperties("company")
private List<Employee> empoloyeeList;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Employee> getEmpoloyeeList() {
return empoloyeeList;
}
public void setEmpoloyeeList(List<Employee> empoloyeeList) {
this.empoloyeeList = empoloyeeList;
}
}
|
/* CommonFns.java
Purpose:
Description:
History:
Wed Apr 20 18:35:21 2005, Created by tomyeh
Copyright (C) 2005 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.xel.fn;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.List;
import java.util.Collection;
import java.util.Map;
import java.lang.reflect.Field;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import org.zkoss.lang.Classes;
import org.zkoss.lang.Objects;
import org.zkoss.mesg.Messages;
import org.zkoss.util.resource.Labels;
import org.zkoss.util.logging.Log;
import org.zkoss.text.MessageFormats;
/**
* Common functions used with EL.
*
* @author tomyeh
*/
public class CommonFns {
private static final Log log = Log.lookup(CommonFns.class);
protected CommonFns() {}
/** Converts the specified object to a boolean.
*/
public static boolean toBoolean(Object val) {
return ((Boolean)Classes.coerce(boolean.class, val)).booleanValue();
}
/** Converts the specified object to a string.
*/
public static String toString(Object val) {
return (String)Classes.coerce(String.class, val);
}
/** Converts the specified object to a number.
*/
public static Number toNumber(Object val) {
return (Number)Classes.coerce(Number.class, val);
}
/** Converts the specified object to an integer.
*/
public static int toInt(Object val) {
return ((Integer)Classes.coerce(int.class, val)).intValue();
}
/** Converts the specified object to a (big) decimal.
*/
public static BigDecimal toDecimal(Object val) {
return (BigDecimal)Classes.coerce(BigDecimal.class, val);
}
/** Converts the specified object to an character.
*/
public static char toChar(Object val) {
return ((Character)Classes.coerce(char.class, val)).charValue();
}
/** Tests whehter an object, o, is an instance of a class, c.
*/
public static boolean isInstance(Object c, Object o) {
if (c instanceof Class) {
return ((Class)c).isInstance(o);
} else if (c instanceof String) {
try {
return Classes.forNameByThread((String)c).isInstance(o);
} catch (ClassNotFoundException ex) {
throw new IllegalArgumentException("Class not found: "+c);
}
} else {
throw new IllegalArgumentException("Unknown class: "+c);
}
}
/** Returns the label or message of the specified key.
* <ul>
* <li>If key is "mesg:class:MMM", Messages.get(class.MMM) is called</li>
* <li>Otherwise, {@link Labels#getLabel(String)} is called.
* </ul>
* @see #getLabel(String, Object[])
*/
public static final String getLabel(String key) {
if (key == null)
return "";
if (key.startsWith("mesg:")) {
final int j = key.lastIndexOf(':');
if (j > 5) {
final String clsnm = key.substring(5, j);
final String fldnm = key.substring(j + 1);
try {
final Class cls = Classes.forNameByThread(clsnm);
final Field fld = cls.getField(fldnm);
return Messages.get(((Integer)fld.get(null)).intValue());
} catch (ClassNotFoundException ex) {
log.warning("Class not found: "+clsnm, ex);
} catch (NoSuchFieldException ex) {
log.warning("Field not found: "+fldnm, ex);
} catch (IllegalAccessException ex) {
log.warning("Field not accessible: "+fldnm, ex);
}
} else if (log.debugable()) {
log.debug("Not a valid format: "+key);
}
}
return Labels.getLabel(key);
}
/** Returns the label of the specified key and formats it
* with the specified argument, or null if not found.
*
* <p>It first uses {@link #getLabel(String)} to load the label.
* Then, it, if not null, invokes {@link MessageFormats#format} to format it.
*
* <p>The current locale is given by {@link org.zkoss.util.Locales#getCurrent}.
* @since 3.0.6
*/
public static final String getLabel(String key, Object[] args) {
final String s = getLabel(key);
return s != null ? MessageFormats.format(s, args, null): null;
}
/** Returns the length of an array, string, collection or map.
*/
public static final int length(Object o) {
if (o instanceof String) {
return ((String)o).length();
} else if (o == null) {
return 0;
} else if (o instanceof Collection) {
return ((Collection)o).size();
} else if (o instanceof Map) {
return ((Map)o).size();
} else if (o.getClass().isArray()) {
return Array.getLength(o);
} else {
throw new IllegalArgumentException("Unknown object for length: "+o.getClass());
}
}
/** Returns the index of the given element.
* @param o the array/collection of objects to examine, or a string.
* If o is a map, then {@link Map#keySet} is assumed.
* @since 5.0.7
*/
public static final int indexOf(Object o, Object element) {
if (o instanceof String) {
return element instanceof String ?
((String)o).indexOf((String)element): -1;
} else if (o instanceof Collection) {
int j = 0;
for (Iterator it = ((Collection)o).iterator(); it.hasNext(); ++j)
if (Objects.equals(it.next(), element))
return j;
} else if (o instanceof Map) {
return indexOf(((Map)o).keySet(), element);
} else if (o instanceof Object[]) {
final Object[] ary = (Object[])o;
for (int j = 0; j < ary.length; j++)
if (Objects.equals(ary[j], element))
return j;
} else if (o instanceof int[]) {
if (element instanceof Number) {
int v = ((Number)element).intValue();
final int[] ary = (int[])o;
for (int j = 0; j < ary.length; j++)
if (ary[j] == v)
return j;
}
} else if (o instanceof long[]) {
if (element instanceof Number) {
long v = ((Number)element).longValue();
final long[] ary = (long[])o;
for (int j = 0; j < ary.length; j++)
if (ary[j] == v)
return j;
}
} else if (o instanceof short[]) {
if (element instanceof Number) {
short v = ((Number)element).shortValue();
final short[] ary = (short[])o;
for (int j = 0; j < ary.length; j++)
if (ary[j] == v)
return j;
}
} else if (o instanceof byte[]) {
if (element instanceof Number) {
byte v = ((Number)element).byteValue();
final byte[] ary = (byte[])o;
for (int j = 0; j < ary.length; j++)
if (ary[j] == v)
return j;
}
} else if (o instanceof double[]) {
if (element instanceof Number) {
double v = ((Number)element).doubleValue();
final double[] ary = (double[])o;
for (int j = 0; j < ary.length; j++)
if (ary[j] == v)
return j;
}
} else if (o instanceof float[]) {
if (element instanceof Number) {
float v = ((Number)element).floatValue();
final float[] ary = (float[])o;
for (int j = 0; j < ary.length; j++)
if (ary[j] == v)
return j;
}
} else if (o instanceof char[]) {
char v;
if (element instanceof Character)
v = ((Character)element).charValue();
else if (element instanceof String && ((String)element).length() > 0)
v = ((String)element).charAt(0);
else
return -1;
final char[] ary = (char[])o;
for (int j = 0; j < ary.length; j++)
if (ary[j] == v)
return j;
} else if (o != null) {
throw new IllegalArgumentException("Unknown object for indexOf: "+o.getClass());
}
return -1;
}
/** Returns the last index of the given element.
* @param o the array/list of objects to examine, or a string.
* @since 5.0.7
*/
public static final int lastIndexOf(Object o, Object element) {
if (o instanceof String) {
return element instanceof String ?
((String)o).lastIndexOf((String)element): -1;
} else if (o instanceof List) {
int j = ((List)o).size();
for (ListIterator it = ((List)o).listIterator(j); it.hasPrevious(); j--)
if (Objects.equals(it.previous(), element))
return j - 1;
} else if (o instanceof Object[]) {
final Object[] ary = (Object[])o;
for (int j = ary.length; --j >= 0;)
if (Objects.equals(ary[j], element))
return j;
} else if (o instanceof int[]) {
if (element instanceof Number) {
int v = ((Number)element).intValue();
final int[] ary = (int[])o;
for (int j = ary.length; --j >= 0;)
if (ary[j] == v)
return j;
}
} else if (o instanceof long[]) {
if (element instanceof Number) {
long v = ((Number)element).longValue();
final long[] ary = (long[])o;
for (int j = ary.length; --j >= 0;)
if (ary[j] == v)
return j;
}
} else if (o instanceof short[]) {
if (element instanceof Number) {
short v = ((Number)element).shortValue();
final short[] ary = (short[])o;
for (int j = ary.length; --j >= 0;)
if (ary[j] == v)
return j;
}
} else if (o instanceof byte[]) {
if (element instanceof Number) {
byte v = ((Number)element).byteValue();
final byte[] ary = (byte[])o;
for (int j = ary.length; --j >= 0;)
if (ary[j] == v)
return j;
}
} else if (o instanceof double[]) {
if (element instanceof Number) {
double v = ((Number)element).doubleValue();
final double[] ary = (double[])o;
for (int j = ary.length; --j >= 0;)
if (ary[j] == v)
return j;
}
} else if (o instanceof float[]) {
if (element instanceof Number) {
float v = ((Number)element).floatValue();
final float[] ary = (float[])o;
for (int j = ary.length; --j >= 0;)
if (ary[j] == v)
return j;
}
} else if (o instanceof char[]) {
char v;
if (element instanceof Character)
v = ((Character)element).charValue();
else if (element instanceof String && ((String)element).length() > 0)
v = ((String)element).charAt(0);
else
return -1;
final char[] ary = (char[])o;
for (int j = ary.length; --j >= 0;)
if (ary[j] == v)
return j;
} else if (o != null) {
throw new IllegalArgumentException("Unknown object for indexOf: "+o.getClass());
}
return -1;
}
/** Instantiates the specified class.
*/
public static final Object new_(Object o) throws Exception {
if (o instanceof String) {
return Classes.newInstanceByThread((String)o);
} else if (o instanceof Class) {
return ((Class)o).newInstance();
} else {
throw new IllegalArgumentException("Unknow object for new: "+o);
}
}
/** Instantiates the specified class, and argument.
* @param o the class name or class
* @param arg the argument
* @since 5.0.5
*/
public static final Object new_(Object o, Object arg) throws Exception {
if (o instanceof String) {
return Classes.newInstance(Classes.forNameByThread((String)o), new Object[] {arg});
} else if (o instanceof Class) {
return Classes.newInstance((Class)o, new Object[] {arg});
} else {
throw new IllegalArgumentException("Unknow object for new: "+o);
}
}
/** Instantiates the specified class, and two arguments.
* @param o the class name or class
* @param arg1 the first argument
* @param arg2 the second argument
* @since 5.0.5
*/
public static final Object new_(Object o, Object arg1, Object arg2) throws Exception {
if (o instanceof String) {
return Classes.newInstance(Classes.forNameByThread((String)o), new Object[] {arg1, arg2});
} else if (o instanceof Class) {
return Classes.newInstance((Class)o, new Object[] {arg1, arg2});
} else {
throw new IllegalArgumentException("Unknow object for new: "+o);
}
}
/** Instantiates the specified class, and two arguments.
* @param o the class name or class
* @param arg1 the first argument
* @param arg2 the second argument
* @since 5.0.5
*/
public static final Object new_(Object o, Object arg1, Object arg2, Object arg3) throws Exception {
if (o instanceof String) {
return Classes.newInstance(Classes.forNameByThread((String)o), new Object[] {arg1, arg2, arg3});
} else if (o instanceof Class) {
return Classes.newInstance((Class)o, new Object[] {arg1, arg2, arg3});
} else {
throw new IllegalArgumentException("Unknow object for new: "+o);
}
}
}
|
Recursion is combined with LinkedList.
class ListNode {
public int value;
public ListNode next;
public ListNode(int value) {
this.value = value;
next = null;
}
}
public class Solution {
public ListNode reverseInPairs(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode newNode = reverseInPairs(head.next.next);
ListNode cur = head.next;
cur.next = head;
head.next = newNode;
return cur;
}
}
|
package com.example.hyunyoungpark.assignment3_1;
public class ListViewItem {
public int icon;
public String name;
public int getIcon() {
return icon;
}
public String getName() {
return name;
}
public ListViewItem(int icon, String name) {
this.icon=icon;
this.name=name;
}
} |
package ch7;
public class Ex_Power {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(power(3,4));
}
public static double power(double x, int n) {
double result = 1;
for(int i = 0; i < n; i++) {
result *= x;
}
return result;
}
}
|
/* Copyright 2015 The jeo project. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jeo.js;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import jline.console.ConsoleReader;
import javax.script.ScriptException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Runnable class for executing a script or starting the repl.
*/
public class Main {
@Parameter(description = "Script to execute")
List<String> script = new ArrayList<>();
@Parameter(names = {"-nr", "--no-require"}, description = "Forgoes loading of require function")
boolean noRequire = false;
@Parameter(names = {"-h", "--help"}, description = "Display command help", help = true)
boolean help = false;
public static void main(String[] args) throws Exception {
Main main = new Main();
new JCommander(main, args);
main.run();
}
public void run() throws Exception {
if (help) {
usage();
System.exit(0);
}
JeoJS rt = new JeoJS().require(!noRequire);
Optional<String> file = script.stream().findFirst();
if (file.isPresent()) {
exec(file.get(), rt);
}
else {
// start in interactive mode
repl(rt);
}
}
void repl(final JeoJS rt) throws Exception {
final ConsoleReader console = new ConsoleReader(System.in, System.out);
console.setHandleUserInterrupt(true);
rt.start(console.getOutput());
new Repl(console) {
@Override
protected void handle(String input) {
Object ret = null;
try {
ret = rt.eval(input);
} catch (ScriptException e) {
e.printStackTrace(new PrintWriter(console.getOutput()));
}
if (ret != null) {
try {
console.getOutput().write(ret.toString() + "\n");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}.start();
}
void exec(String script, JeoJS rt) throws Exception {
rt.start(new OutputStreamWriter(System.out));
try (Reader in = Files.newBufferedReader(Paths.get(script))) {
rt.eval(in);
}
}
void usage() {
new JCommander(new Main()).usage();
}
}
|
package ciphers;
import java.util.ArrayList;
import java.util.List;
import interfaces.Cipherable;
//TODO: reduce code redundancy
public class RotorMachine implements Cipherable {
private ArrayList<Rotor> rotors;
/* Constructors */
public RotorMachine() {
this.rotors = new ArrayList<Rotor>();
}
/* Methods */
public void addRotor(Rotor r) {
rotors.add(r);
}
public void removeRotor(Rotor r) {
rotors.remove(r);
}
/* Cipherable Methods */
@Override
public String encipher(String pt){
StringBuilder ct = new StringBuilder();
char ctChar = 0;
//Save starting positions so each rotor can be reset later
int[] startingPositions = getStartingPositions(rotors);
//For each letter in the plaintext
for (int i = 0; i < pt.length(); i++) {
ctChar = pt.charAt(i);
//Encipher each plaintext character through each rotor
for (Rotor rotor : rotors) {
ctChar = rotor.encipherChar(ctChar);
//Turn the rotor according to its period
if ((i + 1) % rotor.getPeriod() == 0)
rotor.turn();
}
//Append enciphered character to ciphertext message
ct.append(Character.toString(ctChar));
}
resetRotors(startingPositions);
return ct.toString();
}
@Override
public String decipher(String ct) {
StringBuilder pt = new StringBuilder();
char ptChar = 0;
//Save starting positions so each rotor can be reset later
int[] startingPositions = getStartingPositions(rotors);
//For each letter in the ciphertext
for (int i = 0; i < ct.length(); i++) {
ptChar = ct.charAt(i);
//Decipher each ciphertext character in reverse through the rotors
for (int j = rotors.size() - 1; j >= 0; j--) {
Rotor rotor = rotors.get(j);
ptChar = rotor.decipherChar(ptChar);
//Turn the rotor according to its period
if ((i + 1) % rotor.getPeriod() == 0)
rotor.turn();
}
//Append deciphered character to plaintext message
pt.append(Character.toString(ptChar));
}
resetRotors(startingPositions);
return pt.toString();
}
@Override
public char encipherChar(char pt) {
char ct = pt;
for (Rotor rotor : rotors)
ct = rotor.encipherChar(ct);
return ct;
}
@Override
public char decipherChar(char ct) {
char pt = ct;
for (int i = rotors.size() - 1; i >= 0; i--)
pt = rotors.get(i).decipherChar(pt);
return pt;
}
/* Helpers */
/* Return each rotor to its starting position */
private void resetRotors(int[] startingPositions) {
for (int i = 0; i < rotors.size(); i++)
rotors.get(i).setPosition(startingPositions[i]);
}
/* Retrieve the starting positions of all rotors */
private int[] getStartingPositions(List<Rotor> rotors) {
int[] startingPositions = new int[rotors.size()];
for (int i = 0; i < rotors.size(); i++)
startingPositions[i] = rotors.get(i).getPosition();
return startingPositions;
}
} |
package com.torontocodingcollective.oi;
public class TGameController_Logitech extends TGameController {
public TGameController_Logitech(int port) {
super(port);
}
@Override
public double getAxis(TStick stick, TAxis axis) {
switch (stick) {
case LEFT:
switch (axis) {
case X:
return super.getFilteredRawAxis(0);
case Y:
return super.getFilteredRawAxis(1);
default:
break;
}
case RIGHT:
switch (axis) {
case X:
return super.getFilteredRawAxis(4);
case Y:
return super.getFilteredRawAxis(5);
default:
break;
}
default:
return 0.0;
}
}
@Override
public boolean getButton(TButton button) {
switch (button) {
case A:
case X_SYMBOL:
return getRawButton(1);
case B:
case CIRCLE:
return getRawButton(2);
case X:
case SQUARE:
return getRawButton(3);
case Y:
case TRIANGLE:
return getRawButton(4);
case LEFT_BUMPER:
return getRawButton(5);
case RIGHT_BUMPER:
return getRawButton(6);
case BACK:
case SELECT:
case SHARE:
return getRawButton(7);
case START:
case OPTIONS:
return getRawButton(8);
default:
return false;
}
}
@Override
public boolean getButton(TStick stick) {
switch (stick) {
case LEFT:
return getRawButton(9);
case RIGHT:
return getRawButton(10);
default:
return false;
}
}
@Override
protected String getButtonString() {
StringBuilder sb = new StringBuilder();
// Logitech Controllers use the A, B, X, Y buttons
if (getButton(TButton.A)) {
sb.append(" A");
}
if (getButton(TButton.B)) {
sb.append(" B");
}
if (getButton(TButton.X)) {
sb.append(" X");
}
if (getButton(TButton.Y)) {
sb.append(" Y");
}
if (getButton(TButton.LEFT_BUMPER)) {
sb.append(" LB");
}
if (getButton(TButton.RIGHT_BUMPER)) {
sb.append(" RB");
}
if (getButton(TButton.START)) {
sb.append(" Start");
}
if (getButton(TButton.BACK)) {
sb.append(" Back");
}
if (getButton(TStick.LEFT)) {
sb.append(" L-Stick");
}
if (getButton(TStick.RIGHT)) {
sb.append(" R-Stick");
}
return sb.toString().trim();
}
@Override
public double getTrigger(TTrigger trigger) {
switch (trigger) {
case LEFT:
return getFilteredRawAxis(2);
case RIGHT:
return getFilteredRawAxis(3);
default:
return 0.0;
}
}
@Override
protected boolean isUserButtonActive() {
// Logitech controllers use the square, triangle, etc buttons
if (getButton(TButton.A) || getButton(TButton.B) || getButton(TButton.X) || getButton(TButton.Y)
|| getButton(TButton.LEFT_BUMPER) || getButton(TButton.RIGHT_BUMPER) || getButton(TButton.START)
|| getButton(TButton.BACK) || getButton(TStick.LEFT) || getButton(TStick.RIGHT)) {
return true;
}
return false;
}
}
|
package com.company;
public class Main {
public static void main(String[] args) {
//Classroom is extends interface school, sign a course with classroom and then resign a different classroom.
System.out.println("School have total number of "+ School.totalClassRoom + " classroom.");
System.out.println();
Classroom classroom1 = new Classroom();
classroom1.signCourseClassroom(100, "Physics1");
System.out.println("Classroom1 is signed!");
System.out.println(classroom1.getCourseName() + " is teaching in " + classroom1.getClassRoomNum());
classroom1.setClassRoomNum(101);
System.out.println(classroom1.getCourseName() + " changed into classroom " + classroom1.getClassRoomNum());
System.out.println();
Classroom classroom2 = new Classroom();
classroom2.signCourseClassroom(100, "Computer Science");
System.out.println("Classroom2 is signed!");
System.out.println(classroom2.getCourseName() + " will be teaching in " + classroom2.getClassRoomNum());
System.out.println();
//use abstract class teacher to declear different kinds of teacher, then sigh them to different classroom.
Teacher physicsTeacher = new PhysicsTeacher();
physicsTeacher.annouceSubject();
Teacher csTeacher = new CSTeacher();
csTeacher.annouceSubject();
physicsTeacher.signClassRoom(101);
csTeacher.signClassRoom(100);
System.out.println();
//student with subclass studentGrade1, studentGrade2, studentGrade3 examples.
Student student1 = new Student("John");
student1.getName();
student1.choiceCourse();
StudentGrade1 studentGrade1 = new StudentGrade1("John");
student1 = studentGrade1;
((StudentGrade1) student1).announceStudentGrade();
((StudentGrade1) student1).courseCanChoose();
StudentGrade2 studentGrade2 = new StudentGrade2("John");
student1 = studentGrade2;
((StudentGrade2) student1).announceStudentGrade();
((StudentGrade2) student1).courseCanChoose();
StudentGrade3 studentGrade3 = new StudentGrade3("John");
student1 = studentGrade3;
((StudentGrade3) student1).announceStudentGrade();
((StudentGrade3) student1).courseCanChoose();
}
}
|
package com.jerry.racecondition;
import com.jerry.racecondition.face.GeneratorSeq;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;
/**
* Date: 2017/10/3 10:40
*
* @author jerry.R
*/
public class RequestIDGenerator implements GeneratorSeq {
public static final RequestIDGenerator INSTANCE = new RequestIDGenerator();
private static short SEQ_LIMIT = 999;
//private static short ID;
private final AtomicLong ID = new AtomicLong(0L);
private RequestIDGenerator() {
}
@Override
public long nextSequence() throws InterruptedException {
Thread.sleep(5000);
return ID.incrementAndGet();
}
public void getSeq() throws InterruptedException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMddHHmmSS");
String timeStamp = simpleDateFormat.format(new Date());
System.out.println(timeStamp+"--"+nextSequence());
}
public static RequestIDGenerator getInstance() {
return INSTANCE;
}
}
|
package com.chamki.log.test;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.chamki.log.entity.Log4j2Entity;
public class TestLog4j2 {
private static final Logger logger = LogManager.getLogger(TestLog4j2.class);
public static void main(String[] args){
logger.trace("Appliaction is entering the Log4j2Entity...");
if(!Log4j2Entity.printTestString()){
logger.error("Didn`t do it");
}
//打印数据
System.out.println("application is ended!");
logger.trace("Appliaction is exiting the Log4j2Entity...");
}
}
|
package co.com.almundo.callcenter.main;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import co.com.almundo.callcenter.controller.CallCenterController;
import co.com.almundo.callcenter.model.Call;
import co.com.almundo.callcenter.test.util.TestUtil;
public class Main {
private static final Logger logger = LogManager.getLogger("CallCenterController");
public static void main(String[] args) {
logger.info(" ---- Start main thread ---- ");
final CallCenterController callCenterController = new CallCenterController();
TestUtil.getAllEmployees().forEach(callCenterController::addEmployee);
final List<Call> calls = TestUtil.getCalls(11);
calls.forEach(callCenterController::addCall);
callCenterController.treatCalls();
callCenterController.terminateDispatch();
logger.info(" ---- End main thread ---- ");
}
}
|
/**
* Copyright 2013 Simon Curd <simoncurd@gmail.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.headless.cart.model;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Cart
{
private String id;
private List<CartLine> cartLines = new ArrayList<CartLine>();
private Map<TotalType,BigDecimal> totals = new HashMap<TotalType,BigDecimal>();
private int articleCount;
private List<Consignment> consignments = new ArrayList<Consignment>(1);
public List<CartLine> getCartLines()
{
return cartLines;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public void setCartLines(List<CartLine> cartLines)
{
this.cartLines = cartLines;
}
public Map<TotalType, BigDecimal> getTotals()
{
return totals;
}
public void setTotals(Map<TotalType, BigDecimal> totals)
{
this.totals = totals;
}
public int getArticleCount()
{
return articleCount;
}
public void setArticleCount(int articleCount)
{
this.articleCount = articleCount;
}
public List<Consignment> getConsignments()
{
return consignments;
}
public void setConsignments(List<Consignment> consignments)
{
this.consignments = consignments;
}
}
|
package com.example.medicare;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
public class RoktoSolpota extends Activity{
TextView tvRoktoSolpota,tvRoktoSolpota1,tvRoktoSolpota2,tvRoktoSolpota3,tvRoktoSolpota4,tvRoktoSolpota5,tvRoktoSolpota6,tvRoktoSolpota7,tvRoktoSolpota8,tvRoktoSolpota9,tvRoktoSolpota10,tvRoktoSolpota11,tvRoktoSolpota12,tvRoktoSolpota13,tvRoktoSolpota14,tvRoktoSolpota15,tvRoktoSolpota16,tvRoktoSolpota17,tvRoktoSolpota18,tvRoktoSolpota19,tvRoktoSolpota20,tvRoktoSolpota21,tvRoktoSolpota22;
Typeface font;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.rokto_solpota);
tvRoktoSolpota=(TextView)findViewById(R.id.tv_roktoSolpota);
tvRoktoSolpota1=(TextView)findViewById(R.id.tv_roktoSolpota1);
tvRoktoSolpota2=(TextView)findViewById(R.id.tv_roktoSolpota2);
tvRoktoSolpota3=(TextView)findViewById(R.id.tv_roktoSolpota3);
tvRoktoSolpota4=(TextView)findViewById(R.id.tv_roktoSolpota4);
tvRoktoSolpota5=(TextView)findViewById(R.id.tv_roktoSolpota5);
tvRoktoSolpota6=(TextView)findViewById(R.id.tv_roktoSolpota6);
tvRoktoSolpota7=(TextView)findViewById(R.id.tv_roktoSolpota7);
tvRoktoSolpota8=(TextView)findViewById(R.id.tv_roktoSolpota8);
tvRoktoSolpota9=(TextView)findViewById(R.id.tv_roktoSolpota9);
tvRoktoSolpota10=(TextView)findViewById(R.id.tv_roktoSolpota10);
tvRoktoSolpota11=(TextView)findViewById(R.id.tv_roktoSolpota11);
tvRoktoSolpota12=(TextView)findViewById(R.id.tv_roktoSolpota12);
tvRoktoSolpota13=(TextView)findViewById(R.id.tv_roktoSolpota13);
tvRoktoSolpota14=(TextView)findViewById(R.id.tv_roktoSolpota14);
tvRoktoSolpota15=(TextView)findViewById(R.id.tv_roktoSolpota15);
tvRoktoSolpota16=(TextView)findViewById(R.id.tv_roktoSolpota16);
tvRoktoSolpota17=(TextView)findViewById(R.id.tv_roktoSolpota17);
tvRoktoSolpota18=(TextView)findViewById(R.id.tv_roktoSolpota18);
tvRoktoSolpota19=(TextView)findViewById(R.id.tv_roktoSolpota19);
tvRoktoSolpota20=(TextView)findViewById(R.id.tv_roktoSolpota20);
tvRoktoSolpota21=(TextView)findViewById(R.id.tv_roktoSolpota21);
tvRoktoSolpota22=(TextView)findViewById(R.id.tv_roktoSolpota22);
font=Typeface.createFromAsset(getAssets(), "S.TTF");
tvRoktoSolpota.setTypeface(font);
tvRoktoSolpota1.setTypeface(font);
tvRoktoSolpota2.setTypeface(font);
tvRoktoSolpota3.setTypeface(font);
tvRoktoSolpota4.setTypeface(font);
tvRoktoSolpota5.setTypeface(font);
tvRoktoSolpota6.setTypeface(font);
tvRoktoSolpota7.setTypeface(font);
tvRoktoSolpota8.setTypeface(font);
tvRoktoSolpota9.setTypeface(font);
tvRoktoSolpota10.setTypeface(font);
tvRoktoSolpota11.setTypeface(font);
tvRoktoSolpota12.setTypeface(font);
tvRoktoSolpota14.setTypeface(font);
tvRoktoSolpota15.setTypeface(font);
tvRoktoSolpota16.setTypeface(font);
tvRoktoSolpota17.setTypeface(font);
tvRoktoSolpota18.setTypeface(font);
tvRoktoSolpota19.setTypeface(font);
tvRoktoSolpota20.setTypeface(font);
tvRoktoSolpota21.setTypeface(font);
tvRoktoSolpota22.setTypeface(font);
}
}
|
package android.support.v7.widget;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
public class ExpandedRecyclerView extends RecyclerView {
public ExpandedRecyclerView(Context context) {
super(context);
}
public ExpandedRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ExpandedRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected int getAdapterPositionFor(ViewHolder viewHolder) {
return super.getAdapterPositionFor(viewHolder);
}
}
|
package MainPackage;
public class MyInteger
{
private int value;
public MyInteger(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
public boolean isEven()
{
if(this.value % 2 == 0)
{
return true;
}
else
{
return false;
}
}
public static boolean isEven(int value)
{
if(value % 2 == 0)
{
return true;
}
else
{
return false;
}
}
public static boolean isEven(MyInteger myInt)
{
if(myInt.getValue() % 2 == 0)
{
return true;
}
else
{
return false;
}
}
public boolean isOdd()
{
if(this.value % 2 == 1)
{
return true;
}
else
{
return false;
}
}
public static boolean isOdd(int value)
{
if(value % 2 == 1)
{
return true;
}
else
{
return false;
}
}
public static boolean isOdd(MyInteger myInt)
{
if(myInt.getValue() % 2 == 1)
{
return true;
}
else
{
return false;
}
}
public boolean isPrime()
{
for(int j = 2; 2*j < this.value; j++){
if (this.value % j==0)
return false;
}
return true;
}
public static boolean isPrime(int value)
{
for(int j = 2; 2*j < value; j++){
if (value % j==0)
return false;
}
return true;
}
public static boolean isPrime(MyInteger myInt)
{
for(int j = 2; 2*j < myInt.getValue(); j++){
if (myInt.getValue() % j==0)
return false;
}
return true;
}
public static boolean equals(int value, int a)
{
if(value==a)
{
return true;
}
else
return false;
}
public static boolean equals(MyInteger myInt, int a)
{
if(myInt.getValue() == a)
{
return true;
}
else
return false;
}
public static int parseInt(char[] b)
{
int charToInt = Integer.parseInt(new String(b));
return charToInt;
}
public static int parseInt(String c)
{
int stringToInt = Integer.parseInt(c);
return stringToInt;
}
}
|
package com.datagraph.core.engine.job;
import com.datagraph.common.app.App;
import com.datagraph.common.exception.JobException;
import com.datagraph.common.Context;
import com.datagraph.core.example.SimpleApp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
/**
* Created by Denny Joseph on 5/24/16.
*/
public class Manager implements Runnable{
private List<JobManager> jobList = Collections.synchronizedList(new ArrayList<>());
private ExecutorService executorService;
private Context context;
public Manager(Context context) {
this.context = context;
}
public void loadJobs() throws Exception {
App simpleApp = new SimpleApp();
String appName = simpleApp.getClass().getCanonicalName();
JobManager jobManager = new JobManager(context, appName);
simpleApp.execute(context, jobManager);
jobManager.build();
jobList.add(jobManager);
}
public void start() {
}
public List<JobManager> getJobList() {
return jobList;
}
@Override
public void run() {
System.out.println("Inside Manager. this will check for new jobs");
System.out.println("if new jobs found it will call loadJobs methods");
}
}
|
package com.example.mpdemo;
public class DemoController {
}
|
//Created By THLAVLU18301190
package lab01t12;
import java.util.Scanner;
public class Lab01t12 {
public static void before(int M1, int D1, int M2, int D2) {
if (((M1 < M2) && (D1 < D2)) || ((M2 > M1) && (D1 > D2))) {
System.out.println(true);
} else {
System.out.println(false);
}
}
public static void main(String[] args) {
Scanner thl = new Scanner(System.in);
System.out.println("Enter first month.");
int m1 = thl.nextInt();
System.out.println("Enter first day.");
int d1 = thl.nextInt();
System.out.println("Enter second month.");
int m2 = thl.nextInt();
System.out.println("Enter second day.");
int d2 = thl.nextInt();
before(m1, d1, m2, d2);
}
}
|
package com.zeyad.grability.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.zeyad.grability.R;
public class ResumenActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resumen);
}
}
|
package com.ubuntu4u.ubuntu4u.ubuntu4u_client.activities;
import android.Manifest;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.R;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.models.Contact;
import com.ubuntu4u.ubuntu4u.ubuntu4u_client.services.DataManager;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import org.json.JSONObject;
/**
* Created by Q. Engelbrecht on 2017-06-16.
*/
public class RequestConfirmationActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private TextView icon;
private TextView textView;
private Intent intent;
private LocationManager locationManager;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private String[] latlongs;
private static final int REQUEST_PERMISSIONS_LOCATION = 20;
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSIONS_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
InitialiseGoogleApiClient();
} else {
Toast.makeText(this, "To send a panic you need to allow us to use your location service :-)", Toast.LENGTH_LONG).show();
}
break;
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
try {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
latlongs = new String[2];
latlongs[0] = String.valueOf(mLastLocation.getLatitude());
latlongs[1] = String.valueOf(mLastLocation.getLongitude());
AsyncTaskRunner runnable = new AsyncTaskRunner("Accepted", RequestConfirmationActivity.this);
runnable.execute();
}
}
} finally {
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private void InitialiseGoogleApiClient() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!isLocationEnabled()) {
showAlert();
} else {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mGoogleApiClient.connect();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pairing_confirmation);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Safety4u");
intent = getIntent();
textView = (TextView)findViewById(R.id.textView1);
textView.setText(intent.getStringExtra("Content"));
NotificationManager notification_manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notification_manager.cancel(0);
final Button acceptButton = (Button)findViewById(R.id.btnAccept);
acceptButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(RequestConfirmationActivity.this);
adb.setTitle("Accept?");
adb.setMessage("You are about to accept a request to connect your device with " + intent.getStringExtra("RequestDisplayName") + ". This will enable both you and " + intent.getStringExtra("RequestDisplayName") + " to access each other's device location at any given time.");
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Continue", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if ((ContextCompat.checkSelfPermission(RequestConfirmationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) +
ContextCompat.checkSelfPermission(RequestConfirmationActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(RequestConfirmationActivity.this, new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }, REQUEST_PERMISSIONS_LOCATION);
} else {
SQLiteDatabase db = openOrCreateDatabase("law4sho_db", Context.MODE_PRIVATE, null);
String query = "DELETE FROM Inbox WHERE UserID = " + intent.getStringExtra("UserID") + " AND Type = 'PairRequest'";
db.execSQL(query);
InitialiseGoogleApiClient();
}
}});
adb.show();
}
});
final Button rejectButton = (Button)findViewById(R.id.btnReject);
rejectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(RequestConfirmationActivity.this);
adb.setTitle("Reject?");
adb.setMessage("You are about to reject a request to connect your device with " + intent.getStringExtra("RequestDisplayName") + ".");
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Continue?", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SQLiteDatabase db = openOrCreateDatabase("law4sho_db", Context.MODE_PRIVATE, null);
String query = "DELETE FROM Inbox WHERE UserID = " + intent.getStringExtra("UserID") + " AND Type = 'PairRequest'";
db.execSQL(query);
AsyncTaskRunner runner = new AsyncTaskRunner("Rejected", RequestConfirmationActivity.this);
runner.execute();
}});
adb.show();
}
});
final Button blockButton = (Button)findViewById(R.id.btnBlock);
blockButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(RequestConfirmationActivity.this);
adb.setTitle("Block?");
adb.setMessage("You are about to block " + intent.getStringExtra("RequestDisplayName") + ".");
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Continue?", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SQLiteDatabase db = openOrCreateDatabase("law4sho_db", Context.MODE_PRIVATE, null);
String query = "DELETE FROM Inbox WHERE UserID = " + intent.getStringExtra("UserID") + " AND Type = 'PairRequest'";
db.execSQL(query);
AsyncTaskRunner runner = new AsyncTaskRunner("Blocked", RequestConfirmationActivity.this);
runner.execute();
}});
adb.show();
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private ProgressDialog asyncDialog;
private String action;
private Contact contact;
private Context context;
public AsyncTaskRunner(String action, Context context) {
asyncDialog = new ProgressDialog(RequestConfirmationActivity.this);
asyncDialog.setCanceledOnTouchOutside(false);
this.action = action;
this.context = context;
}
@Override
protected void onPreExecute() {
asyncDialog.setMessage(getString(R.string.response_type));
asyncDialog.show();
}
@Override
protected String doInBackground(String... params) {
try {
DataManager dataManager = new DataManager();
JSONObject jsonObject = new JSONObject();
jsonObject.put("RequestCellNumber", intent.getStringExtra("RequestCellNumber"));
jsonObject.put("TargetCellNumber", new DataManager().getConfiguration(context).MobileNumber);
jsonObject.put("RequestDisplayName", new DataManager().getConfiguration(context).DisplayName);
jsonObject.put("Latitude", latlongs[0]);
jsonObject.put("Longitude", latlongs[1]);
jsonObject.put("UserID", new DataManager().getConfiguration(context).UserID);
jsonObject.put("Action", action);
dataManager.postData(jsonObject, "/ResponseService/SendResponse");
} catch (Exception e) {
return "Unsuccessful";
}
return "Success";
}
@Override
protected void onPostExecute(String result) {
if (result == "Success")
Toast.makeText(RequestConfirmationActivity.this, "Response sent...", Toast.LENGTH_LONG).show();
asyncDialog.dismiss();
finish();
}
}
}
|
package com.xixiwan.platform.sys.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xixiwan.platform.sys.entity.SysUser;
/**
* <p>
* 管理员表 Mapper 接口
* </p>
*
* @author Sente
* @since 2018-09-28
*/
public interface SysUserMapper extends BaseMapper<SysUser> {
}
|
package dk.sidereal.lumm.components.audio;
import com.badlogic.gdx.audio.Music;
import dk.sidereal.lumm.architecture.Lumm;
import dk.sidereal.lumm.architecture.core.Audio.AudioChannel;
public class MusicClip extends AudioClip {
Music clip;
public MusicClip(String filepath, AudioChannel category, AudioSource source) {
super(filepath, category, source);
clip = Lumm.assets.get(filepath, Music.class);
supportsCompletionEvents = true;
}
public MusicClip(String filepath, String customAudioChannelName, AudioSource source) {
super(filepath, customAudioChannelName, source);
clip = Lumm.assets.get(filepath, Music.class);
supportsCompletionEvents = true;
}
@Override
public void onPlay() {
clip.play();
}
@Override
public void onPause() {
clip.pause();
}
@Override
public void onResume() {
if (clip.getPosition() != 0)
clip.play();
}
@Override
public void onStop() {
clip.stop();
}
/**
* Sets whether to loop the clip or not. This will not start playing the
* clip.
*
* @param value
*/
public void setLooping(boolean value) {
clip.setLooping(value);
}
@Override
protected boolean isCompleted() {
return clip.isPlaying();
}
@Override
protected void onInternalVolumeChange(float volume, float pan, float pitch) {
clip.setVolume(volume);
}
@Override
protected void onInternalPanChange(float volume, float pan, float pitch) {
clip.setPan(pan, volume);
}
@Override
protected void onInternalPitchChange(float volume, float pan, float pitch) {
}
@Override
protected void onFilePathChange(String filepath) {
clip = Lumm.assets.get(filepath, Music.class);
}
@Override
protected void onUnload() {
unload(getFilepath());
}
public static void load(String filepath) {
Lumm.assets.load(filepath, Music.class);
}
public static void unload(String filepath) {
Lumm.assets.unload(filepath);
}
}
|
package com.dora.service;
import com.dora.service.dto.ItensPedidoDTO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
/**
* Service Interface for managing ItensPedido.
*/
public interface ItensPedidoService {
/**
* Save a itensPedido.
*
* @param itensPedidoDTO the entity to save
* @return the persisted entity
*/
ItensPedidoDTO save(ItensPedidoDTO itensPedidoDTO);
/**
* Get all the itensPedidos.
*
* @param pageable the pagination information
* @return the list of entities
*/
Page<ItensPedidoDTO> findAll(Pageable pageable);
/**
* Get the "id" itensPedido.
*
* @param id the id of the entity
* @return the entity
*/
ItensPedidoDTO findOne(Long id);
/**
* Delete the "id" itensPedido.
*
* @param id the id of the entity
*/
void delete(Long id);
/**
* Search for the itensPedido corresponding to the query.
*
* @param query the query of the search
*
* @param pageable the pagination information
* @return the list of entities
*/
Page<ItensPedidoDTO> search(String query, Pageable pageable);
}
|
//package com.bnrc.ui.rjz;
//
//import com.bnrc.busapp.R;
//
//import android.app.Activity;
//import android.content.Context;
//import android.graphics.drawable.ColorDrawable;
//import android.view.LayoutInflater;
//import android.view.MotionEvent;
//import android.view.View;
//import android.view.View.OnClickListener;
//import android.view.View.OnTouchListener;
//import android.view.ViewGroup.LayoutParams;
//import android.widget.Button;
//import android.widget.ImageView;
//import android.widget.PopupWindow;
//
//public class PublishSelectPicPopupWindow extends PopupWindow {
//
// private Button mCancelBtn;
// private ImageView mHomeBtn, mWorkBtn, mDelBtn;
// private View mMenuView;
//
// @SuppressWarnings("deprecation")
// public PublishSelectPicPopupWindow(Activity context,
// OnClickListener clickListener) {
// super(context);
// LayoutInflater inflater = (LayoutInflater) context
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// mMenuView = inflater.inflate(R.layout.publish_dialog, null);
//
// mCancelBtn = (Button) mMenuView.findViewById(R.id.btn_cancel);
// mHomeBtn = (ImageView) mMenuView.findViewById(R.id.iv_home);
// mWorkBtn = (ImageView) mMenuView.findViewById(R.id.iv_work);
// mDelBtn = (ImageView) mMenuView.findViewById(R.id.iv_del);
//
// mHomeBtn.setOnClickListener(clickListener);
// mWorkBtn.setOnClickListener(clickListener);
// mDelBtn.setOnClickListener(clickListener);
// mCancelBtn.setOnClickListener(clickListener);
// // 设置SelectPicPopupWindow的View
// this.setContentView(mMenuView);
// // 设置SelectPicPopupWindow弹出窗体的宽
// this.setWidth(LayoutParams.FILL_PARENT);
// // 设置SelectPicPopupWindow弹出窗体的高
// this.setHeight(LayoutParams.WRAP_CONTENT);
// // 设置SelectPicPopupWindow弹出窗体可点击
// this.setFocusable(true);
// // 设置SelectPicPopupWindow弹出窗体动画效果
// this.setAnimationStyle(R.style.AnimBottom);
// // 实例化一个ColorDrawable颜色为半透明
// ColorDrawable dw = new ColorDrawable(0xb0000000);
// // 设置SelectPicPopupWindow弹出窗体的背景
// this.setBackgroundDrawable(dw);
// // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
// mMenuView.setOnTouchListener(new OnTouchListener() {
// public boolean onTouch(View v, MotionEvent event) {
//
// int height = mMenuView.findViewById(R.id.pop_layout).getTop();
// int y = (int) event.getY();
// if (event.getAction() == MotionEvent.ACTION_UP) {
// if (y < height) {
// dismiss();
// }
// }
// return true;
// }
// });
//
// }
//
//}
|
package com.java.project.BackEnd.Service.Balance;
import com.java.project.BackEnd.Mapper.BalanceMapper;
import com.java.project.BackEnd.Mapper.TransactionMapper;
import com.java.project.BackEnd.Model.Customer;
import com.java.project.BackEnd.Model.CustomerBalance;
import com.java.project.BackEnd.Service.Auth.AuthService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.Reader;
public class BalanceService {
BalanceMapper balanceMapper;
SqlSession session;
public BalanceService() {
try {
Reader reader = Resources.getResourceAsReader("SqlConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
session = sqlSessionFactory.openSession();
} catch (Exception e) {
e.printStackTrace();
}
session.getConfiguration().addMapper(BalanceMapper.class);
balanceMapper = session.getMapper(BalanceMapper.class);
}
public String[] cekPulsa(CustomerBalance customerBalance) {
CustomerBalance cs = getBalance(customerBalance);
String pulsa = cs.getBalance();
if (pulsa == null) {
pulsa = "0";
}
int pls = Integer.parseInt(pulsa);
if (pls < 3000) {
return new String[]{"200", "Sisa Pulsa anda saat ini : " + pls,"Disarankan Untuk mengisi pulsa"};
}
return new String[]{"200", "Sisa Pulsa anda saat ini : " + pls};
}
public String[] cekData(CustomerBalance customerBalance) {
CustomerBalance cs = getBalance(customerBalance);
return new String[]{"200", "Sisa Paket anda saat ini : " + cs.getPaket_data() + "GB."};
}
public String[] cekMasaAktiv(CustomerBalance customerBalance) {
CustomerBalance cs = getBalance(customerBalance);
return new String[]{"200", "Masa aktiv anda sampai dengan : " + cs.getActive_period()};
}
public String[] cekStatus(CustomerBalance customerBalance) {
CustomerBalance cs = getBalance(customerBalance);
return new String[]{"200", "{\"No Telp\":\"" + cs.getPhone_number() + "\",\"Pulsa \":\"" + cs.getBalance() + "\",\"Paket Data\":\"" + cs.getPaket_data() + "GB\",\"Masa Aktif\":\"" + cs.getActive_period() + "\"}"};
}
public CustomerBalance getBalance(CustomerBalance customerBalance) {
return balanceMapper.getBalance(customerBalance);
}
}
|
package com.syscxp.biz.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* 登录页面
*
* @author HenryYan
*/
@Controller
public class LoginController {
@RequestMapping(value = "/login")
public String login() {
// ModelAndView mav = new ModelAndView("/login.jsp");
return "login";
}
}
|
package nihil.publicdefender;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* Created by be127osx on 4/17/18.
*/
public class DatePickerFragment extends DialogFragment {
private static final String ARG_DATE = "date";
public static final String EXTRA_DATE = "nihil.publicdefender.date";
private DatePicker mDatePicker;
public static DatePickerFragment newInstance(Date date)
{
Bundle argumentBundle = new Bundle();
argumentBundle.putSerializable(ARG_DATE, date);
DatePickerFragment dpFrag = new DatePickerFragment();
dpFrag.setArguments(argumentBundle);
return dpFrag;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Date date = (Date) getArguments().getSerializable(ARG_DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int crimeYear = calendar.get(Calendar.YEAR);
int crimeMonth = calendar.get(Calendar.MONTH);
int crimeDay = calendar.get(Calendar.DAY_OF_MONTH);
final int crimeHour = calendar.get(Calendar.HOUR_OF_DAY);
final int crimeMinute = calendar.get(Calendar.MINUTE);
View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date_picker, null);
mDatePicker = v.findViewById(R.id.dialog_date_picker_date_picker);
mDatePicker.init(crimeYear, crimeMonth, crimeDay, null);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.date_picker)
.setView(v)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Date retDate = new GregorianCalendar(mDatePicker.getYear(), mDatePicker.getMonth(), mDatePicker.getDayOfMonth(), crimeHour, crimeMinute).getTime();
sendResult(Activity.RESULT_OK, retDate);
}
})
.create();
}
private void sendResult(int resultCode, Date date) {
if(getTargetFragment() == null)
return;
Intent intent = new Intent();
intent.putExtra(EXTRA_DATE, date);
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
}
}
|
package com.liyang.book.service;
import com.liyang.book.entity.Book;
import com.liyang.book.entity.Bookpic;
import com.liyang.book.mapper.BookMapper;
import com.liyang.book.mapper.BookpicMapper;
import com.liyang.commons.Factory;
import org.apache.ibatis.session.SqlSession;
/*
*@author:李洋
*@date:2019/7/29 17:21
*/
public class BookpicService {
}
|
/*
* 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 InternalForms;
import Forms.Login;
import Forms.MainMenu;
import Forms.SalePayment;
import Model.CompletedOrder;
import Model.Computer;
import Model.Customer;
import Model.ProductService;
import Model.Sale;
import com.sun.glass.events.KeyEvent;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
/**
*
* @author HermanCosta
*/
public class NewSale extends javax.swing.JInternalFrame {
ArrayList firstNames = new ArrayList();
ArrayList lastNames = new ArrayList();
Vector vecProducts = new Vector();
Vector vecQty = new Vector();
Vector vecUnitPrice = new Vector();
Vector vecPriceTotal = new Vector();
Connection con;
PreparedStatement ps;
Statement stmt;
Customer customer;
ProductService productService;
Sale sale;
Computer computer;
ResultSet rs;
ResultSetMetaData rsmd;
CompletedOrder completedOrder;
String saleNo, firstName, lastName, contactNo, email,
stringProducts, stringPriceTotal, stringQty, stringUnitPrice, saleDate, status;
double total, cash, card, changeTotal;
boolean isSaleDetails = false;
public NewSale() {
initComponents();
//Remove borders
this.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
BasicInternalFrameUI ui = (BasicInternalFrameUI) this.getUI();
ui.setNorthPane(null);
SwingUtilities.invokeLater(() -> {
txt_first_name.requestFocus();
});
txt_contact.setFocusLostBehavior(JFormattedTextField.PERSIST);//avoid auto old value by focus loosing
tableSettings(table_view_products);
tableSettings(table_view_computers);
autoID();
checkEmailFormat();
accessDbColumn(firstNames, "SELECT * FROM customers", "firstName");
accessDbColumn(lastNames, "SELECT * FROM customers", "lastName");
listProductService();
loadComputerTable();
}
public void tableSettings(JTable table) {
table.setRowHeight(25);
table.getTableHeader().setFont(new Font("Lucida Grande", Font.BOLD, 14));
}
public void dbConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/pcHouse", "root", "hellmans");
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(NewSale.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, ex, "DB Connection", JOptionPane.ERROR_MESSAGE);
}
}
public final void autoID() {
try {
dbConnection();
//check saleNo from saleNo table
String queryCheck = "SELECT saleNo FROM sales";
ps = con.prepareStatement(queryCheck);
rs = ps.executeQuery();
if (rs.next()) {
String queryMax = "SELECT Max(saleNo) FROM sales";
ps = con.prepareStatement(queryMax);
rs = ps.executeQuery();
while (rs.next()) {
long id = Long.parseLong(rs.getString("Max(saleNo)").substring(3, rs.getString("Max(saleNo)").length()));
id++;
lbl_auto_sale_no.setText("SNO" + String.format("%04d", id));
}
} else {
lbl_auto_sale_no.setText("SNO0001");
}
ps.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(Customers.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void autoCompleteFromDb(ArrayList list, String text, JTextField field) {
String complete = "";
int start = text.length();
int last = text.length();
for (int i = 0; i < list.size(); i++) {
if (list.get(i).toString().startsWith(text)) {
complete = list.get(i).toString();
last = complete.length();
break;
}
}
if (last > start) {
field.setText(complete);
field.setCaretPosition(last);
field.moveCaretPosition(start);
}
}
public void listProductService() {
AutoCompleteDecorator.decorate(combo_box_product_service);
try {
dbConnection();
String query = "SELECT productService FROM products";
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
combo_box_product_service.addItem(rs.getString("productService"));
}
con.close();
ps.close();
} catch (SQLException ex) {
Logger.getLogger(NewSale.class.getName()).log(Level.SEVERE, null, ex);
}
}
public final void accessDbColumn(ArrayList list, String query, String columnName) {
try {
dbConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
list.add(rs.getString(columnName));
}
ps.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(NewSale.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void cleanFields(JTable table) {
//Clean all Fields
lbl_auto_sale_no.setText("");
txt_first_name.setText("");
txt_last_name.setText("");
txt_contact.setText("");
txt_email.setText("");
combo_box_product_service.setSelectedIndex(-1);
txt_total.setText("");
txt_first_name.requestFocus();
//Clean table Fields
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
while (dtm.getRowCount() > 0) {
dtm.removeRow(0);
}
}
public final void checkEmailFormat() {
txt_email.setInputVerifier(new InputVerifier() {
Border originalBorder;
String emailFormat = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
String email = txt_email.getText();
@Override
public boolean verify(JComponent input) {
JTextField comp = (JTextField) input;
return comp.getText().matches(emailFormat) | comp.getText().trim().isEmpty();
}
@Override
public boolean shouldYieldFocus(JComponent input) {
boolean isValid = verify(input);
if (!isValid) {
originalBorder = originalBorder == null ? input.getBorder() : originalBorder;
//input.setBorder(BorderFactory.createLineBorder(Color.red, 2));
input.setBorder(new LineBorder(Color.RED));
} else {
if (originalBorder != null) {
input.setBorder(originalBorder);
originalBorder = null;
}
}
return isValid;
}
});
}
public boolean checkEmptyFields() {
if (txt_first_name.getText().trim().isEmpty() | txt_last_name.getText().trim().isEmpty()
| txt_contact.getText().trim().isEmpty() | table_view_products.getRowCount() == 0) {
JOptionPane.showMessageDialog(this, "Please, check Empty fields", "New Sale", JOptionPane.ERROR_MESSAGE);
}
return true;
}
public void getSaleValues() {
if (txt_first_name.getText().trim().isEmpty() || txt_last_name.getText().trim().isEmpty()
|| txt_contact.getText().trim().isEmpty() || table_view_products.getRowCount() == 0) {
JOptionPane.showMessageDialog(this, "Please, check Empty fields", "New Sale", JOptionPane.ERROR_MESSAGE);
} else {
saleNo = lbl_auto_sale_no.getText();
firstName = txt_first_name.getText().toUpperCase();
lastName = txt_last_name.getText().toUpperCase();
contactNo = txt_contact.getText().replace("(", "").replace(")", "").replace("-", "").replace(" ", "");
email = txt_email.getText();
total = Double.parseDouble(txt_total.getText());
Date date = new java.util.Date();
Timestamp currentDate = new Timestamp(date.getTime());
saleDate = new SimpleDateFormat("dd/MM/yyyy").format(currentDate);
//Empty vector before looping to avoid duplicate values on tableView
vecProducts.removeAllElements();
vecQty.removeAllElements();
vecUnitPrice.removeAllElements();
vecPriceTotal.removeAllElements();
//pass table items from faults and products table to vector
for (int j = 0; j < table_view_products.getRowCount(); j++) {
vecProducts.add(table_view_products.getValueAt(j, 0));
vecQty.add(table_view_products.getValueAt(j, 1));
vecUnitPrice.add(table_view_products.getValueAt(j, 2));
vecPriceTotal.add(table_view_products.getValueAt(j, 3));
}
// pass vector elemnets to a String splitted by a comma,
// in sa to save into DB
stringProducts = vecProducts.toString().replace("[", " ").replace("]", "");
stringQty = vecQty.toString().replace("[", " ").replace("]", "");
stringUnitPrice = vecUnitPrice.toString().replace("[", " ").replace("]", "");
stringPriceTotal = vecPriceTotal.toString().replace("[", " ").replace("]", "");
sale = new Sale(saleNo, firstName, lastName, contactNo, email, stringProducts,
stringQty, stringUnitPrice, stringPriceTotal, total, saleDate, cash, card, changeTotal, status, Login.fullName);
}
}
public void getPriceSum() {
double sum = 0;
for (int i = 0; i < table_view_products.getRowCount(); i++) {
sum = sum + Double.parseDouble(table_view_products.getValueAt(i, 3).toString());
}
txt_total.setText(Double.toString(sum));
}
public void searchSale() {
ArrayList<Computer> computerList = new ArrayList<>();
String searchComputer = txt_search_computer.getText();
try {
dbConnection();
String query = "SELECT * FROM computers WHERE brand LIKE '%" + searchComputer + "%'"
+ "OR model LIKE '%" + searchComputer + "%' OR serialNumber LIKE '%" + searchComputer + "%'"
+ " OR processor LIKE '%" + searchComputer + "%'";
ps = con.prepareStatement(query);
rs = ps.executeQuery(query);
while (rs.next()) {
computer = new Computer(rs.getString("brand"), rs.getString("model"), rs.getString("serialNumber"),
rs.getString("processor"), rs.getString("ram"), rs.getString("storage"),
rs.getString("gpu"), rs.getString("screen"), rs.getString("notes"),
rs.getInt("qty"), rs.getDouble("price"));
computerList.add(computer);
computer.setComputerId(rs.getInt("computerId"));
}
DefaultTableModel dtm = (DefaultTableModel) table_view_computers.getModel();
dtm.setRowCount(0);
Object[] row = new Object[9];
for (int i = 0; i < computerList.size(); i++) {
row[0] = computerList.get(i).getComputerId();
row[1] = computerList.get(i).getBrand();
row[2] = computerList.get(i).getModel();
row[3] = computerList.get(i).getSerialNumber();
row[4] = computerList.get(i).getProcessor();
row[5] = computerList.get(i).getRam();
row[6] = computerList.get(i).getStorage();
row[7] = computerList.get(i).getQty();
row[8] = computerList.get(i).getPrice();
dtm.addRow(row);
}
ps.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(Customers.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void loadComputerTable() {
ArrayList<Computer> computerList = new ArrayList<>();
try {
dbConnection();
String query = "SELECT * FROM computers";
ps = con.prepareStatement(query);
rs = ps.executeQuery(query);
while (rs.next()) {
computer = new Computer(rs.getString("brand"), rs.getString("model"), rs.getString("serialNumber"), rs.getString("processor"),
rs.getString("ram"), rs.getString("storage"), rs.getString("gpu"), rs.getString("screen"), rs.getString("notes"),
rs.getInt("qty"), rs.getDouble("price"));
computer.setComputerId(rs.getInt("computerId"));
computerList.add(computer);
}
ps.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(ComputerList.class.getName()).log(Level.SEVERE, null, ex);
}
DefaultTableModel dtm = (DefaultTableModel) table_view_computers.getModel();
dtm.setRowCount(0);
Object[] row = new Object[9];
for (int i = 0; i < computerList.size(); i++) {
row[0] = computerList.get(i).getComputerId();
row[1] = computerList.get(i).getBrand();
row[2] = computerList.get(i).getModel();
row[3] = computerList.get(i).getSerialNumber();
row[4] = computerList.get(i).getProcessor();
row[5] = computerList.get(i).getRam();
row[6] = computerList.get(i).getStorage();
row[7] = computerList.get(i).getQty();
row[8] = computerList.get(i).getPrice();
dtm.addRow(row);
}
}
public boolean saveCustomerIntoDb() {
boolean isContactNo = false;
contactNo = txt_contact.getText().replace("(", "").replace(")", "").replace("-", "").replace(" ", "");
try {
dbConnection();
String query = "SELECT contactNo, firstName, lastName FROM customers WHERE contactNo = ? ";
ps = con.prepareStatement(query);
ps.setString(1, contactNo);
rs = ps.executeQuery();
if (!rs.isBeforeFirst()) {
customer = new Customer(txt_first_name.getText().toUpperCase(), txt_last_name.getText().toUpperCase(), contactNo, txt_email.getText());
String queryInsert = "INSERT INTO customers (firstName, lastName, contactNo, email) VALUES(?, ?, ?, ?)";
ps = con.prepareStatement(queryInsert);
ps.setString(1, customer.getFirstName());
ps.setString(2, customer.getLastName());
ps.setString(3, customer.getContactNo());
ps.setString(4, customer.getEmail());
ps.executeUpdate();
} else {
while (rs.next()) {
firstName = rs.getString("firstName");
lastName = rs.getString("lastName");
}
if (!firstName.equals(txt_first_name.getText())
&& !lastName.equals(txt_last_name.getText())) {
JOptionPane.showMessageDialog(this, "There is another Customer associated with ContactNo " + txt_contact.getText(), "New Customer", JOptionPane.ERROR_MESSAGE);
isContactNo = true;
}
}
} catch (SQLException ex) {
Logger.getLogger(NewSale.class.getName()).log(Level.SEVERE, null, ex);
}
return isContactNo;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
desktop_pane_new_sale = new javax.swing.JDesktopPane();
panel_sale_details = new javax.swing.JPanel();
lbl_sale_no = new javax.swing.JLabel();
lbl_first_name = new javax.swing.JLabel();
lbl_last_name = new javax.swing.JLabel();
lbl_contact = new javax.swing.JLabel();
lbl_email = new javax.swing.JLabel();
lbl_auto_sale_no = new javax.swing.JLabel();
lbl_service_product = new javax.swing.JLabel();
lbl_price = new javax.swing.JLabel();
txt_first_name = new javax.swing.JTextField();
txt_last_name = new javax.swing.JTextField();
txt_email = new javax.swing.JTextField();
txt_contact = new javax.swing.JFormattedTextField();
combo_box_product_service = new javax.swing.JComboBox<>();
btn_save_sale = new javax.swing.JButton();
btn_cancel = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
table_view_computers = new javax.swing.JTable();
jScrollPane4 = new javax.swing.JScrollPane();
table_view_products = new javax.swing.JTable();
txt_search_computer = new javax.swing.JTextField();
lbl_search_icon = new javax.swing.JLabel();
btn_computers = new javax.swing.JButton();
btn_international_number = new javax.swing.JButton();
btn_copy = new javax.swing.JButton();
btn_add_product_service = new javax.swing.JButton();
txt_total = new javax.swing.JTextField();
setMaximumSize(new java.awt.Dimension(1049, 700));
setPreferredSize(new java.awt.Dimension(1049, 700));
setSize(new java.awt.Dimension(1049, 700));
panel_sale_details.setPreferredSize(new java.awt.Dimension(1049, 700));
lbl_sale_no.setFont(new java.awt.Font("Lucida Grande", 1, 16)); // NOI18N
lbl_sale_no.setText("Sale No.");
lbl_first_name.setFont(new java.awt.Font("Lucida Grande", 1, 16)); // NOI18N
lbl_first_name.setText("First Name");
lbl_last_name.setFont(new java.awt.Font("Lucida Grande", 1, 16)); // NOI18N
lbl_last_name.setText("Last Name");
lbl_contact.setFont(new java.awt.Font("Lucida Grande", 1, 16)); // NOI18N
lbl_contact.setText("Contact No.");
lbl_email.setFont(new java.awt.Font("Lucida Grande", 1, 16)); // NOI18N
lbl_email.setText("Email");
lbl_auto_sale_no.setFont(new java.awt.Font("Lucida Grande", 1, 20)); // NOI18N
lbl_auto_sale_no.setText("autoGen");
lbl_service_product.setFont(new java.awt.Font("Lucida Grande", 1, 16)); // NOI18N
lbl_service_product.setText("Service | Product");
lbl_price.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N
lbl_price.setText("Total €");
txt_first_name.setFont(new java.awt.Font("Lucida Grande", 0, 16)); // NOI18N
txt_first_name.setNextFocusableComponent(txt_last_name);
txt_first_name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_first_nameActionPerformed(evt);
}
});
txt_first_name.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_first_nameKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
txt_first_nameKeyReleased(evt);
}
});
txt_last_name.setFont(new java.awt.Font("Lucida Grande", 0, 16)); // NOI18N
txt_last_name.setNextFocusableComponent(txt_contact);
txt_last_name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_last_nameActionPerformed(evt);
}
});
txt_last_name.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_last_nameKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
txt_last_nameKeyReleased(evt);
}
});
txt_email.setFont(new java.awt.Font("Lucida Grande", 0, 16)); // NOI18N
txt_email.setNextFocusableComponent(combo_box_product_service);
txt_email.setPreferredSize(new java.awt.Dimension(63, 20));
txt_email.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_emailActionPerformed(evt);
}
});
txt_email.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_emailKeyPressed(evt);
}
});
try {
txt_contact.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(0##) ###-####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
txt_contact.setFont(new java.awt.Font("Lucida Grande", 0, 16)); // NOI18N
txt_contact.setNextFocusableComponent(txt_email);
txt_contact.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_contactActionPerformed(evt);
}
});
txt_contact.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
txt_contactKeyReleased(evt);
}
});
combo_box_product_service.setEditable(true);
combo_box_product_service.setFont(new java.awt.Font("Lucida Grande", 0, 15)); // NOI18N
combo_box_product_service.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select or Type" }));
combo_box_product_service.setSize(new java.awt.Dimension(96, 30));
combo_box_product_service.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
combo_box_product_serviceActionPerformed(evt);
}
});
combo_box_product_service.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
combo_box_product_serviceKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
combo_box_product_serviceKeyReleased(evt);
}
});
btn_save_sale.setBackground(new java.awt.Color(21, 76, 121));
btn_save_sale.setFont(new java.awt.Font("Lucida Grande", 1, 22)); // NOI18N
btn_save_sale.setForeground(new java.awt.Color(255, 255, 255));
btn_save_sale.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_save.png"))); // NOI18N
btn_save_sale.setText("Save");
btn_save_sale.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_save_saleActionPerformed(evt);
}
});
btn_cancel.setBackground(new java.awt.Color(21, 76, 121));
btn_cancel.setFont(new java.awt.Font("Lucida Grande", 1, 22)); // NOI18N
btn_cancel.setForeground(new java.awt.Color(255, 255, 255));
btn_cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_cancel.png"))); // NOI18N
btn_cancel.setText("Cancel");
btn_cancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_cancelActionPerformed(evt);
}
});
table_view_computers.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
table_view_computers.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Brand", "Model", "Serial Number", "Processor", "RAM", "Storage", "Qty", "Price"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
table_view_computers.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
table_view_computersMouseClicked(evt);
}
});
jScrollPane2.setViewportView(table_view_computers);
if (table_view_computers.getColumnModel().getColumnCount() > 0) {
table_view_computers.getColumnModel().getColumn(0).setPreferredWidth(50);
table_view_computers.getColumnModel().getColumn(0).setMaxWidth(100);
table_view_computers.getColumnModel().getColumn(7).setPreferredWidth(50);
table_view_computers.getColumnModel().getColumn(7).setMaxWidth(80);
table_view_computers.getColumnModel().getColumn(8).setPreferredWidth(100);
table_view_computers.getColumnModel().getColumn(8).setMaxWidth(150);
}
table_view_products.setFont(new java.awt.Font("Lucida Grande", 0, 16)); // NOI18N
table_view_products.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Product | Service", "Qty", "Unit €", "Total €"
}
) {
boolean[] canEdit = new boolean [] {
false, false, true, true
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
table_view_products.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
table_view_productsMouseClicked(evt);
}
});
table_view_products.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
table_view_productsKeyReleased(evt);
}
});
jScrollPane4.setViewportView(table_view_products);
if (table_view_products.getColumnModel().getColumnCount() > 0) {
table_view_products.getColumnModel().getColumn(1).setPreferredWidth(100);
table_view_products.getColumnModel().getColumn(1).setMaxWidth(200);
table_view_products.getColumnModel().getColumn(2).setPreferredWidth(80);
table_view_products.getColumnModel().getColumn(2).setMaxWidth(120);
table_view_products.getColumnModel().getColumn(3).setPreferredWidth(80);
table_view_products.getColumnModel().getColumn(3).setMaxWidth(120);
}
txt_search_computer.setFont(new java.awt.Font("Lucida Grande", 0, 20)); // NOI18N
txt_search_computer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_search_computerActionPerformed(evt);
}
});
txt_search_computer.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
txt_search_computerKeyTyped(evt);
}
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_search_computerKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
txt_search_computerKeyReleased(evt);
}
});
lbl_search_icon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_search_black.png"))); // NOI18N
btn_computers.setBackground(new java.awt.Color(21, 76, 121));
btn_computers.setFont(new java.awt.Font("Lucida Grande", 1, 22)); // NOI18N
btn_computers.setForeground(new java.awt.Color(255, 255, 255));
btn_computers.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_device_list.png"))); // NOI18N
btn_computers.setText("Computers");
btn_computers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_computersActionPerformed(evt);
}
});
btn_international_number.setBackground(new java.awt.Color(0, 0, 0));
btn_international_number.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_international_number.png"))); // NOI18N
btn_international_number.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_international_numberActionPerformed(evt);
}
});
btn_copy.setBackground(new java.awt.Color(0, 0, 0));
btn_copy.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_copy.png"))); // NOI18N
btn_copy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_copyActionPerformed(evt);
}
});
btn_add_product_service.setBackground(new java.awt.Color(0, 0, 0));
btn_add_product_service.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_add_new.png"))); // NOI18N
btn_add_product_service.setNextFocusableComponent(txt_search_computer);
btn_add_product_service.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_add_product_serviceActionPerformed(evt);
}
});
txt_total.setEditable(false);
txt_total.setFont(new java.awt.Font("Lucida Grande", 1, 16)); // NOI18N
txt_total.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_totalActionPerformed(evt);
}
});
javax.swing.GroupLayout panel_sale_detailsLayout = new javax.swing.GroupLayout(panel_sale_details);
panel_sale_details.setLayout(panel_sale_detailsLayout);
panel_sale_detailsLayout.setHorizontalGroup(
panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane2)
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addComponent(lbl_sale_no)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbl_auto_sale_no))
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addComponent(lbl_email)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txt_email, javax.swing.GroupLayout.PREFERRED_SIZE, 348, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_sale_detailsLayout.createSequentialGroup()
.addComponent(lbl_first_name)
.addGap(18, 18, 18)
.addComponent(txt_first_name, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_sale_detailsLayout.createSequentialGroup()
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_sale_detailsLayout.createSequentialGroup()
.addComponent(lbl_last_name)
.addGap(20, 20, 20))
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addComponent(lbl_contact)
.addGap(11, 11, 11)))
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt_last_name, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addComponent(txt_contact)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_international_number, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_copy, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addComponent(lbl_price)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txt_total, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(lbl_service_product)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(combo_box_product_service, javax.swing.GroupLayout.PREFERRED_SIZE, 386, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_add_product_service, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 587, Short.MAX_VALUE)))))
.addGap(0, 18, Short.MAX_VALUE))
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addGap(116, 116, 116)
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addComponent(btn_save_sale, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btn_cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btn_computers, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addComponent(lbl_search_icon, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_search_computer, javax.swing.GroupLayout.PREFERRED_SIZE, 732, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panel_sale_detailsLayout.setVerticalGroup(
panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_auto_sale_no, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_sale_no))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_first_name, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_first_name))
.addGap(15, 15, 15)
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_last_name)
.addComponent(txt_last_name, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(15, 15, 15)
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_contact)
.addComponent(txt_contact, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(15, 15, 15))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_sale_detailsLayout.createSequentialGroup()
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btn_international_number, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_copy, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(17, 17, 17)))
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lbl_email)
.addComponent(txt_email, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10)
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lbl_price)
.addComponent(txt_total, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(panel_sale_detailsLayout.createSequentialGroup()
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btn_add_product_service)
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(combo_box_product_service, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_service_product)))
.addGap(12, 12, 12)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 24, Short.MAX_VALUE)
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_save_sale)
.addComponent(btn_cancel)
.addComponent(btn_computers))
.addGap(18, 18, 18)
.addGroup(panel_sale_detailsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lbl_search_icon, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_search_computer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(48, Short.MAX_VALUE))
);
desktop_pane_new_sale.setLayer(panel_sale_details, javax.swing.JLayeredPane.DEFAULT_LAYER);
javax.swing.GroupLayout desktop_pane_new_saleLayout = new javax.swing.GroupLayout(desktop_pane_new_sale);
desktop_pane_new_sale.setLayout(desktop_pane_new_saleLayout);
desktop_pane_new_saleLayout.setHorizontalGroup(
desktop_pane_new_saleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(desktop_pane_new_saleLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(panel_sale_details, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
desktop_pane_new_saleLayout.setVerticalGroup(
desktop_pane_new_saleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(desktop_pane_new_saleLayout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(panel_sale_details, javax.swing.GroupLayout.DEFAULT_SIZE, 669, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(desktop_pane_new_sale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(desktop_pane_new_sale, javax.swing.GroupLayout.Alignment.TRAILING)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txt_emailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_emailActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_emailActionPerformed
private void txt_last_nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_last_nameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_last_nameActionPerformed
private void txt_first_nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_first_nameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_first_nameActionPerformed
private void btn_save_saleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_save_saleActionPerformed
// TODO add your handling code here:
getSaleValues();
if (!saveCustomerIntoDb()) {
String formatContactNo = txt_contact.getText();
SalePayment salePayment = new SalePayment(sale, table_view_products, formatContactNo);
salePayment.setVisible(true);
}
}//GEN-LAST:event_btn_save_saleActionPerformed
private void btn_cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cancelActionPerformed
int confirmCancelling = JOptionPane.showConfirmDialog(this, "Do you want to cancel this ?", "New Sale",
JOptionPane.YES_NO_OPTION);
if (confirmCancelling == 0) {
new MainMenu().setVisible(true);
}
}//GEN-LAST:event_btn_cancelActionPerformed
private void txt_first_nameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_first_nameKeyPressed
// TODO add your handling code here:
//Sugest autoComplete firstNames from Database
switch (evt.getKeyCode()) {
case KeyEvent.VK_BACKSPACE:
break;
case KeyEvent.VK_ENTER:
txt_first_name.setText(txt_first_name.getText());
break;
default:
EventQueue.invokeLater(() -> {
String text = txt_first_name.getText();
autoCompleteFromDb(firstNames, text, txt_first_name);
});
}
}//GEN-LAST:event_txt_first_nameKeyPressed
private void txt_emailKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_emailKeyPressed
// TODO add your handling code here:
}//GEN-LAST:event_txt_emailKeyPressed
private void txt_first_nameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_first_nameKeyReleased
// TODO add your handling code here:
}//GEN-LAST:event_txt_first_nameKeyReleased
private void txt_last_nameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_last_nameKeyReleased
// TODO add your handling code here:
}//GEN-LAST:event_txt_last_nameKeyReleased
private void table_view_computersMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_table_view_computersMouseClicked
// TODO add your handling code here:
//Delete products|Service item of the selected row (Function is called with 2 clicks)
int row = table_view_computers.getSelectedRow();
DefaultTableModel compTableModel = (DefaultTableModel) table_view_computers.getModel();
DefaultTableModel prodTableModel = (DefaultTableModel) table_view_products.getModel();
Vector vecComputers = new Vector();
boolean valid = false;
String tableProduct = "";
if (evt.getClickCount() == 2) {
int computerId = (int) compTableModel.getValueAt(row, 0);
String brand = compTableModel.getValueAt(row, 1).toString();
String model = compTableModel.getValueAt(row, 2).toString();
String serialNumber = compTableModel.getValueAt(row, 3).toString();
double price = Double.parseDouble(compTableModel.getValueAt(row, 8).toString());
String newProduct = computerId + "| " + brand + " | " + model + " | " + serialNumber;
int qty = 0;
while (!valid) {
try {
qty = Integer.parseInt(JOptionPane.showInputDialog("Enter '" + computer.getBrand() + " | "
+ computer.getModel() + " | " + computer.getSerialNumber() + "' Qty:"));
if (qty > 0) {
valid = true;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "Qty must be an Integer!", "Add Computer", JOptionPane.ERROR_MESSAGE);
}
}
double priceTotal = price * qty;
vecComputers.add(newProduct);
vecComputers.add(qty);
vecComputers.add(price);
vecComputers.add(priceTotal);
for (int i = 0; i < prodTableModel.getRowCount(); i++) {
tableProduct = prodTableModel.getValueAt(i, 0).toString();
}
if (newProduct.equals(tableProduct)) {
JOptionPane.showMessageDialog(this, "Item '" + newProduct + "' already added !", "Add Computer", JOptionPane.ERROR_MESSAGE);
} else {
prodTableModel.addRow(vecComputers);
}
// Sum price column and set into total textField
getPriceSum();
}
}//GEN-LAST:event_table_view_computersMouseClicked
private void txt_last_nameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_last_nameKeyPressed
// TODO add your handling code here:
//Sugest autoComplete firstNames from Database
switch (evt.getKeyCode()) {
case KeyEvent.VK_BACKSPACE:
break;
case KeyEvent.VK_ENTER:
txt_last_name.setText(txt_last_name.getText());
break;
default:
EventQueue.invokeLater(() -> {
String text = txt_last_name.getText();
autoCompleteFromDb(lastNames, text, txt_last_name);
});
}
}//GEN-LAST:event_txt_last_nameKeyPressed
private void txt_contactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_contactActionPerformed
contactNo = txt_contact.getText().replace("(", "").replace(")", "").replace("-", "").replace(" ", "");
try {
dbConnection();
String query = "SELECT * FROM customers WHERE contactNo = ? ";
ps = con.prepareStatement(query);
ps.setString(1, contactNo);
rs = ps.executeQuery();
if (!rs.isBeforeFirst()) {
JOptionPane.showMessageDialog(this, "Customer not found in the Database", "New Customer", JOptionPane.ERROR_MESSAGE);
} else {
while (rs.next()) {
txt_first_name.setText(rs.getString("firstName"));
txt_last_name.setText(rs.getString("lastName"));
txt_contact.setText(rs.getString("contactNo"));
txt_email.setText(rs.getString("email"));
}
}
} catch (SQLException ex) {
Logger.getLogger(NewSale.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_txt_contactActionPerformed
private void txt_contactKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_contactKeyReleased
// TODO add your handling code here:
}//GEN-LAST:event_txt_contactKeyReleased
private void combo_box_product_serviceKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_combo_box_product_serviceKeyReleased
// TODO add your handling code here:
}//GEN-LAST:event_combo_box_product_serviceKeyReleased
private void combo_box_product_serviceKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_combo_box_product_serviceKeyPressed
// TODO add your handling code here:
}//GEN-LAST:event_combo_box_product_serviceKeyPressed
private void combo_box_product_serviceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combo_box_product_serviceActionPerformed
}//GEN-LAST:event_combo_box_product_serviceActionPerformed
private void table_view_productsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_table_view_productsMouseClicked
// TODO add your handling code here:
//Delete products|Service item of the selected row (Function is called with 2 clicks)
DefaultTableModel dtm = (DefaultTableModel) table_view_products.getModel();
if (evt.getClickCount() == 2) {
int confirmDeletion = JOptionPane.showConfirmDialog(null, "Remove This Item ?", "Remove Product|Service", JOptionPane.YES_NO_OPTION);
if (confirmDeletion == 0) {
dtm.removeRow(table_view_products.getSelectedRow());
// Sum price column and set into total textField
getPriceSum();
}
}
}//GEN-LAST:event_table_view_productsMouseClicked
private void txt_search_computerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_search_computerActionPerformed
// TODO add your handling code here:
searchSale();
}//GEN-LAST:event_txt_search_computerActionPerformed
private void txt_search_computerKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_search_computerKeyTyped
// TODO add your handling code here:
}//GEN-LAST:event_txt_search_computerKeyTyped
private void txt_search_computerKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_search_computerKeyPressed
// TODO add your handling code here:
}//GEN-LAST:event_txt_search_computerKeyPressed
private void txt_search_computerKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_search_computerKeyReleased
// TODO add your handling code here:
searchSale();
}//GEN-LAST:event_txt_search_computerKeyReleased
private void btn_computersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_computersActionPerformed
// TODO add your handling code here:
ComputerList computerList = new ComputerList();
desktop_pane_new_sale.add(computerList).setVisible(true);
}//GEN-LAST:event_btn_computersActionPerformed
private void btn_international_numberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_international_numberActionPerformed
// TODO add your handling code here:
txt_contact.setFormatterFactory(null);
txt_contact.setText("");
txt_contact.requestFocus();
}//GEN-LAST:event_btn_international_numberActionPerformed
private void btn_copyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_copyActionPerformed
// TODO add your handling code here:
StringSelection stringSelection = new StringSelection(txt_contact.getText().replace("(", "").replace(")", "").replace("-", "").replace(" ", ""));
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
JOptionPane.showMessageDialog(this, txt_contact.getText() + " Copied to Clipboard");
}//GEN-LAST:event_btn_copyActionPerformed
private void btn_add_product_serviceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_add_product_serviceActionPerformed
// TODO add your handling code here:
// Add selected items to the products table
ArrayList<String> productsList = new ArrayList<>();
DefaultTableModel dtm = (DefaultTableModel) table_view_products.getModel();
String selectedItem = combo_box_product_service.getSelectedItem().toString();
String newProdAdd = "", category = "";
int qty = 0;
double unitPrice = 0;
double totalPrice = 0;
Vector vector = new Vector();
productsList.clear();
for (int i = 0; i < dtm.getRowCount(); i++) {
productsList.add(dtm.getValueAt(i, 0).toString());
}
if (selectedItem.isEmpty() || selectedItem.matches("Select or Type")) {
JOptionPane.showMessageDialog(this, "Please select a Product | Service!", "Service | Product", JOptionPane.ERROR_MESSAGE);
} else if (productsList.contains(selectedItem)) {
JOptionPane.showMessageDialog(this, "Item '" + selectedItem + "' already added !", "Add Computer", JOptionPane.ERROR_MESSAGE);
} else {
try {
dbConnection();
String query = "SELECT * FROM products WHERE productService = ?";
ps = con.prepareStatement(query);
ps.setString(1, selectedItem);
rs = ps.executeQuery();
if (!rs.isBeforeFirst()) {
JOptionPane.showMessageDialog(this, "Item not Found!", "Service | Product", JOptionPane.ERROR_MESSAGE);
} else {
while (rs.next()) {
newProdAdd = rs.getString("productService");
unitPrice = rs.getDouble("price");
category = rs.getString("category");
}
if (category.equals("Product")) {
boolean valid = false;
while (!valid) {
try {
qty = Integer.parseInt(JOptionPane.showInputDialog("Enter '" + selectedItem + "' Qty:"));
if (qty > 0) {
valid = true;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "Qty must be an Integer!", "Product | Service", JOptionPane.ERROR_MESSAGE);
}
totalPrice = unitPrice * qty;
vector.add(newProdAdd);
vector.add(qty);
vector.add(unitPrice);
vector.add(totalPrice);
dtm.addRow(vector);
}
} else {
qty = 1;
totalPrice = unitPrice * qty;
vector.add(newProdAdd);
vector.add(qty);
vector.add(unitPrice);
vector.add(totalPrice);
dtm.addRow(vector);
}
combo_box_product_service.setSelectedIndex(-1);
// Sum price column and set into total textField
getPriceSum();
ps.close();
con.close();
}
} catch (SQLException ex) {
Logger.getLogger(NewOrder.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_btn_add_product_serviceActionPerformed
private void table_view_productsKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_table_view_productsKeyReleased
// TODO add your handling code here:
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
double sum = 0;
for (int i = 0; i < table_view_products.getRowCount(); i++) {
double unitPrice = Double.parseDouble(table_view_products.getValueAt(i, 2).toString());
int qty = Integer.parseInt(table_view_products.getValueAt(i, 1).toString());
table_view_products.setValueAt(unitPrice, i, 2);
double priceTotal = unitPrice * qty;
table_view_products.setValueAt(priceTotal, i, 3);
sum += priceTotal;
}
txt_total.setText(String.valueOf(sum));
}
}//GEN-LAST:event_table_view_productsKeyReleased
private void txt_totalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_totalActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_totalActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_add_product_service;
private javax.swing.JButton btn_cancel;
private javax.swing.JButton btn_computers;
private javax.swing.JButton btn_copy;
private javax.swing.JButton btn_international_number;
private javax.swing.JButton btn_save_sale;
private javax.swing.JComboBox<String> combo_box_product_service;
private javax.swing.JDesktopPane desktop_pane_new_sale;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JLabel lbl_auto_sale_no;
private javax.swing.JLabel lbl_contact;
private javax.swing.JLabel lbl_email;
private javax.swing.JLabel lbl_first_name;
private javax.swing.JLabel lbl_last_name;
private javax.swing.JLabel lbl_price;
private javax.swing.JLabel lbl_sale_no;
private javax.swing.JLabel lbl_search_icon;
private javax.swing.JLabel lbl_service_product;
private javax.swing.JPanel panel_sale_details;
private javax.swing.JTable table_view_computers;
private javax.swing.JTable table_view_products;
private javax.swing.JFormattedTextField txt_contact;
private javax.swing.JTextField txt_email;
private javax.swing.JTextField txt_first_name;
private javax.swing.JTextField txt_last_name;
private javax.swing.JTextField txt_search_computer;
private javax.swing.JTextField txt_total;
// End of variables declaration//GEN-END:variables
}
|
package com.notely.ui.details;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.notely.R;
import com.notely.model.Note;
import com.notely.ui.BaseActivity;
import com.notely.ui.list.ListNotesActivity;
import com.notely.utility.Helper;
import com.notely.utility.TextViewUndoRedo;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;
public class DetailsNoteActivity extends BaseActivity {
private Menu menu;
private EditText editTitle;
private EditText editGist;
private TextView tvDateUpdated;
private Note note;
private TextViewUndoRedo helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_note);
setUpToolBar();
findView();
getIntentDataAndBind();
}
private void getIntentDataAndBind() {
if (getIntent() != null) {
note = getIntent().getParcelableExtra(ListNotesActivity.NOTE_ITEM);
editTitle.setText(note.getTitle());
editGist.setText(note.getGist());
tvDateUpdated.setText(getString(R.string.last_updated) + " " + Helper.INSTANCE.getDate(this, note.getTime_created()));
}
}
private void findView() {
editTitle = findViewById(R.id.etTitle);
editGist = findViewById(R.id.etGist);
tvDateUpdated = findViewById(R.id.tvDateUpdated);
helper = new TextViewUndoRedo(editGist);
}
private void setUpToolBar() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setElevation(0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
getMenuInflater().inflate(R.menu.details_screen_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_undo:
// add undo while editing
helper.undo();
break;
case R.id.action_save:
// Save edited story/poem
if (!TextUtils.isEmpty(editTitle.getText()) && !TextUtils.isEmpty(editGist.getText())) {
note.setTitle(editTitle.getText().toString());
note.setGist(editGist.getText().toString());
compositeDisposable.add(viewModel.insertNote(note)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(Timber::e)
.subscribe(() -> {
setFocusable(false);
}));
} else {
Toast.makeText(this, getString(R.string.aler_info), Toast.LENGTH_SHORT).show();
}
break;
case R.id.action_edit:
setFocusable(true);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
finishWithTransition();
return true;
}
@Override
protected void onDestroy() {
super.onDestroy();
note = null;
}
/*
* Method to manage visibility of menu item and edit fields
* */
void setFocusable(boolean focusable) {
if (focusable) {
editTitle.setFocusable(true);
editTitle.setFocusableInTouchMode(true);
editGist.setFocusable(true);
editGist.setFocusableInTouchMode(true);
menu.findItem(R.id.action_undo).setVisible(true);
menu.findItem(R.id.action_save).setVisible(true);
menu.findItem(R.id.action_edit).setVisible(false);
} else {
editTitle.setFocusable(false);
editTitle.setFocusableInTouchMode(false);
editGist.setFocusable(false);
editGist.setFocusableInTouchMode(false);
menu.findItem(R.id.action_undo).setVisible(false);
menu.findItem(R.id.action_save).setVisible(false);
menu.findItem(R.id.action_edit).setVisible(true);
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
finishWithTransition();
}
}
|
package in.stevemann.tictactoe.services;
import in.stevemann.tictactoe.entities.Game;
import in.stevemann.tictactoe.entities.Move;
import in.stevemann.tictactoe.entities.Player;
import in.stevemann.tictactoe.enums.GridType;
import in.stevemann.tictactoe.enums.PieceType;
import in.stevemann.tictactoe.pojos.Board;
import in.stevemann.tictactoe.utils.AutomatedPlayerUtil;
import in.stevemann.tictactoe.utils.PrintBoardUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Comparator;
import java.util.Scanner;
@Service
@AllArgsConstructor
public class GamePlayService {
private final GameService gameService;
private final MoveService moveService;
public void playGame(Board board){
playGame(board, false);
}
public void playGame(Board board, boolean secondPlayerTurn) {
Scanner userInputReader = new Scanner(System.in);
Player firstPlayer = board.getGame().getFirstPlayer();
Player secondPlayer = board.getGame().getSecondPlayer();
boolean isGameInProgress = true;
while (isGameInProgress) {
PrintBoardUtil.printCurrentBoard(board);
Player turnPlayer = (secondPlayerTurn) ? secondPlayer : firstPlayer;
int position;
if(turnPlayer.isAutomated()) {
position = AutomatedPlayerUtil.findBestMove(board, moveService.getPlayerPieceOnBoard(board, turnPlayer));
} else {
position = getPosition(userInputReader, secondPlayerTurn, board.getGame().getGridType());
}
// pause game if position is -10
if (position == -10) {
gameService.pauseGame(board.getGame());
return;
}
boolean isValidPosition = moveService.makeMove(turnPlayer, board, position);
if (!isValidPosition) {
System.out.println("Position entered is already marked as filled. Please choose another position");
playGame(board, secondPlayerTurn);
return;
}
PieceType playerPieceOnBoard = moveService.getPlayerPieceOnBoard(board, turnPlayer);
isGameInProgress = gameService.isGameInProgress(board, playerPieceOnBoard, position);
secondPlayerTurn = !secondPlayerTurn; // change turn
}
PrintBoardUtil.printCurrentBoard(board);
System.out.println(" GAME OVER!!!");
System.out.println(board.getGame().getStatus());
}
private int getPosition(Scanner userInputReader, Boolean secondPlayerTurn, GridType gridType) throws NumberFormatException {
int position;
System.out.println(((secondPlayerTurn) ? "Second Player. " : "First Player. ") + "Please enter a position or enter -10 to pause:");
try {
position = Integer.parseInt(userInputReader.nextLine());
} catch (NumberFormatException e) {
return retryInput(userInputReader, secondPlayerTurn, gridType);
}
if (position > gridType.getSize() * gridType.getSize()) {
return retryInput(userInputReader, secondPlayerTurn, gridType);
}
return position;
}
private int retryInput(Scanner userInputReader, Boolean secondPlayerTurn, GridType gridType) {
System.out.println("Invalid Input. Try Again.");
return getPosition(userInputReader, secondPlayerTurn, gridType);
}
public boolean isSecondPlayerTurn(Game game) {
Move move = game.getMoves().stream().max(Comparator.comparing(Move::getCreated)).orElse(null); // getting last move made in game
boolean secondPlayerTurn = false;
if (move != null && move.getPlayer().getUsername().equals(game.getFirstPlayer().getUsername())) {
secondPlayerTurn = true;
}
return secondPlayerTurn;
}
}
|
public class LC189 {
static void reverse(int[] nums,int start,int end){
while(start<end){
int tmp=nums[start];
nums[start]=nums[end];
nums[end]=tmp;
start++;
end--;
}
}
static int[] rotate(int[] nums, int k) {
k=k%nums.length;
reverse(nums,0,nums.length-1);
reverse(nums,0,k-1);
reverse(nums,k,nums.length-1);
return nums;
}
public static void main(String[] args) {
int[] nums1= {-1};
int k=2;
int[] nm=rotate(nums1,k);
for(int n:nm){
System.out.print(n+" ");
}
}
}
|
/*
* Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.wellknownurl;
import java.net.URISyntaxException;
import org.apache.http.client.utils.URIBuilder;
/**
* Builds URL to be used for redirection after account association.
* @author K. Benedyczak
*/
public class PostAssociationRedirectURLBuilder
{
public enum Status {success, error, cancelled}
public static final String PARAM_STATUS = "status";
public static final String PARAM_ERROR_CODE = "error_msg";
public static final String PARAM_ASSOCIATION_OF = "association_of";
public static final String PARAM_ASSOCIATION_FROM = "association_from_idp";
public static final String PARAM_ASSOCIATED_WITH = "associated_with";
private URIBuilder uriBuilder;
public PostAssociationRedirectURLBuilder(String baseURL, Status status)
{
try
{
uriBuilder = new URIBuilder(baseURL);
} catch (URISyntaxException e)
{
throw new IllegalStateException("Illegal redirect URI, shouldn't happen", e);
}
uriBuilder.addParameter(PARAM_STATUS, status.toString());
}
public PostAssociationRedirectURLBuilder setErrorCode(String error)
{
uriBuilder.addParameter(PARAM_ERROR_CODE, error);
return this;
}
public PostAssociationRedirectURLBuilder setAssociatedInto(long associatedIntoEntity)
{
uriBuilder.addParameter(PARAM_ASSOCIATED_WITH, String.valueOf(associatedIntoEntity));
return this;
}
public PostAssociationRedirectURLBuilder setAssociatedInfo(String associatedIdentity, String idp)
{
if (idp != null)
uriBuilder.addParameter(PARAM_ASSOCIATION_FROM, idp);
uriBuilder.addParameter(PARAM_ASSOCIATION_OF, associatedIdentity);
return this;
}
@Override
public String toString()
{
return uriBuilder.toString();
}
}
|
package Arrays;
import java.util.Scanner;
public class Biggest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of elements");
int n = in.nextInt();
int[] a = new int[n];
System.out.println("Enter the "+n+" elements");
for(int i=0; i<n; i++){
a[i] = in.nextInt();
}
int biggest = a[0];
System.out.println("Entered array element are: ");
for(int i=0; i<a.length; i++){
System.out.print(a[i]+" ");
if(biggest<a[i])
biggest=a[i];
}
System.out.println();
System.out.println("Biggest element in the array: "+biggest);
in.close();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.