text stringlengths 10 2.72M |
|---|
package gui;
public class Item {
protected String itemName;
protected int itemPrice;
protected int productPrice;
protected String mainUrl;
Item(String itemName){
switch(itemName) {
case "Turnip" : itemPrice = 50; productPrice = 100; mainUrl = "/res/CropItem/turnip.png"; break; // 3 days product
case "Carrot" : itemPrice = 80; productPrice = 160; mainUrl = "/res/CropItem/carrot.png"; break; // 4 days product
case "Potato" : itemPrice = 100; productPrice = 200; mainUrl = "/res/CropItem/potato.png";break; // 4 days product
case "Tomato" : itemPrice = 120; productPrice = 200; mainUrl = "/res/CropItem/tomato.png";break; // 5 days product 2 time
case "Corn" : itemPrice = 150; productPrice = 220;mainUrl = "/res/CropItem/corn.png"; break;// 5 day 3 time
case "Strawberry" : itemPrice = 250; productPrice = 220; mainUrl = "/res/CropItem/strawberry.png"; break;//5 day 3 time
case "Grape" : itemPrice = 300; productPrice = 250; mainUrl = "/res/CropItem/Grape.png"; break;//5 day 3 time
case "Watermelon" : itemPrice = 400 ; productPrice = 300;mainUrl = "/res/CropItem/Watermelon.png"; break;//5 day 4 time
case "Fertilizer" : itemPrice = 20 ; productPrice = 0;mainUrl = "/res/Tools/fertilizer.png"; break;
case "Pesticide" : itemPrice = 20 ; productPrice = 0; mainUrl = "/res/Tools/pesticide.png";break;
case "Chicken" : itemPrice = 500 ; productPrice = 50; mainUrl = "/res/AnimalItem/chicken.png"; break;
case "Sheep" : itemPrice = 800; productPrice = 80;mainUrl = "/res/AnimalItem/sheep.png"; break;
case "Goat" : itemPrice = 1000; productPrice = 100;mainUrl = "/res/AnimalItem/goat.png"; break;
case "Cow" : itemPrice = 1500; productPrice = 150;mainUrl = "/res/AnimalItem/cow.png"; break;
case "Grain" : itemPrice = 20; productPrice = 0;mainUrl = "/res/AnimalItem/grain.png"; break;
case "Straw" : itemPrice = 30; productPrice = 0;mainUrl = "/res/AnimalItem/straw.png"; break;
case "Shovel" : itemPrice = 0; productPrice = 0;mainUrl = "/res/Tools/shovel.png"; break;
case "Watering Can" : itemPrice = 0; productPrice = 0;mainUrl = "/res/Tools/wateringcan.png"; break;
case "Sickle" : itemPrice = 0; productPrice = 0;mainUrl = "/res/Tools/sickle.png"; break;
case "Basket" : itemPrice = 0; productPrice = 0;mainUrl = "/res/Tools/basket.png"; break;
}
this.itemName = itemName;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getItemPrice() {
return itemPrice;
}
public void setItemPrice(int itemPrice) {
this.itemPrice = itemPrice;
}
public int getProductPrice() {
return productPrice;
}
public void setProductPrice(int productPrice) {
this.productPrice = productPrice;
}
public String getPriceText() {
if(itemPrice > 0 ) {
return "\nPrice: "+ itemPrice;
}
return "";
}
public String getIncomeText() {
if(productPrice > 0) {
return "\nIncome: "+ productPrice;
}
return "";
}
}
|
package com.kwik.repositories.client.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import br.com.caelum.vraptor.ioc.Component;
import com.kwik.models.Client;
import com.kwik.repositories.client.ClientRepository;
@Component
public class ClientDao implements ClientRepository {
private EntityManager entityManager;
public ClientDao(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public Client add(Client client) {
Client result = client;
entityManager.persist(result);
return result;
}
@Override
public List<Client> listAll() {
Query query = entityManager.createQuery("FROM " + Client.class.getName());
@SuppressWarnings("unchecked")
List<Client> resultList = query.getResultList();
return resultList;
}
}
|
package GUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Radio extends JFrame {
private JTextField txt;
private Font plainF;
private Font boldF;
private Font italicF;
private Font bolditalicF;
private JRadioButton plainbutton;
private JRadioButton boldbutton;
private JRadioButton italicbutton;
private JRadioButton bolditalicbutton;
private ButtonGroup group;
public Radio(){
super("Radio Title");
setLayout(new FlowLayout());
txt = new JTextField ("Gustavo Ž foda", 18);
add(txt);
plainbutton = new JRadioButton("plain", true);
boldbutton = new JRadioButton("bold", false);
italicbutton = new JRadioButton("italic", false);
bolditalicbutton = new JRadioButton("bold and italic", false);
add(plainbutton);
add(boldbutton);
add(italicbutton);
add(bolditalicbutton);
group = new ButtonGroup();
group.add(plainbutton);
group.add(boldbutton);
group.add(italicbutton);
group.add(bolditalicbutton);
plainF = new Font ("Serif", Font.PLAIN, 18);
boldF = new Font ("Serif", Font.BOLD, 18);
italicF = new Font ("Serif", Font.ITALIC, 18);
bolditalicF = new Font ("Serif", Font.BOLD + Font.ITALIC, 18);
txt.setFont(plainF);
plainbutton.addItemListener(new HandlerClass(plainF));
boldbutton.addItemListener(new HandlerClass(boldF));
italicbutton.addItemListener(new HandlerClass(italicF));
bolditalicbutton.addItemListener(new HandlerClass(bolditalicF));
}
public class HandlerClass implements ItemListener {
private Font font;
public HandlerClass(Font f) {
font = f;
}
public void itemStateChanged (ItemEvent event) {
txt.setFont(font);
}
}
}
|
package CPS261Generics;
public class MyArrayList<E> {
Object[] container;
int numElements =0;
public MyArrayList(int initialSize)
{
container = new Object[initialSize];
}
public MyArrayList()
{
this(10);
}
public int size()
{
return numElements;
}
public void add(E ob)
{
if (numElements >= container.length)
{
resize();
}
container[numElements++] = ob;
}
public E get(int index)
{
if (index < 0 || index >= numElements)
throw new IndexOutOfBoundsException("Index out of bounds");
return (E)container[index];
}
private void resize()
{
int currSize = container.length;
Object[] nextContainer = new Object[currSize*2];
for (int i=0; i < numElements; i++)
nextContainer[i] = container[i];
container = nextContainer;
}
public E set(int index, E ob)
{
if (index < 0 || index >= numElements)
throw new IndexOutOfBoundsException("Index out of bounds: "+ index);
E replacedObject = (E)container[index];
container[index] = ob;
return replacedObject;
}
// Inserts object at desired location
public void add(int index, E ob)
{
if (index < 0 || index > numElements)
throw new IndexOutOfBoundsException("Index out of bounds: "+ index);
add(ob); // This will increase our size by 1
// Shift objects to make room for the new addition
for (int i= numElements-1; i > index; i--)
{
container[i] = container[i-1];
}
container[index] = ob;
}
// For this to work, the objects need to implement equals
public int indexOf(E ob)
{
for (int i=0; i < numElements; i++)
{
if (ob.equals(container[i]))
return i;
}
return -1;
}
public E remove(int index)
{
if (index < 0 || index >= numElements)
throw new IndexOutOfBoundsException("Index out of bounds: "+ index);
// Shift everything down
E removedObject = (E)container[index];
for (int i= index; i < numElements-1; i++)
{
container[i] = container[i+1];
}
numElements -= 1;
return removedObject;
}
// for this to work, the objects need to implement equals
public boolean remove (E ob)
{
int index = indexOf(ob);
if (index < 0)
return false;
remove(index);
return true;
}
public String toString()
{
StringBuilder sb= new StringBuilder();
sb.append("[ ");
for (int i=0; i < numElements; i++)
{
sb.append(container[i].toString());
if (i < numElements-1)
sb.append(",");
}
sb.append(" ]");
return sb.toString();
}
} |
package ru.client.view;
import javax.swing.*;
public class ClientFrame extends JFrame {
private static final String FRAME_TITLE = "Система автомобилестроительного предприятия";
private static final int DEFAULT_WIDTH = 1200;
private static final int DEFAULT_HEIGHT = 600;
private JPanel container;
public ClientFrame() {
initUI();
}
private void initUI() {
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle(FRAME_TITLE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new MainPanel(this);
add(container);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
ClientFrame clientFrame = new ClientFrame();
clientFrame.setVisible(true);
});
}
}
|
package common.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IndexController extends AbstractController {
@Override
public void execute(HttpServletRequest req, HttpServletResponse res) throws Exception {
//메인홈페이지구현
req.setAttribute("msg", "WELCOME TO <span style='color:orange;'>GYURI'S WORLD</span> :D ");
req.setAttribute("mymsg", "CARPE DIEM♬ ");
super.setRedirect(false);
super.setViewPage("/WEB-INF/index.jsp");
}
}
|
import java.util.*;
public class empWage implements employeeInterface
{
static final int isFullTime=2;
static final int isPartTime=1;
static int noOfComp=0;
ArrayList<companyEmpWage> employee;
Map<String, companyEmpWage> employeeMap;
empWage(int n)
{
employee = new ArrayList<>();
employeeMap = new LinkedHashMap<>();
noOfComp=n;
}
public void addCompany(String name, int rate, int workingHrs, int workingDays)
{
companyEmpWage comp = new companyEmpWage(name,rate,workingHrs,workingDays);
employee.add(comp);
employeeMap.put(name,comp);
}
public int getWorkingHours(int check)
{
int workHours;
switch(check)
{
case isFullTime:
workHours=8;
break;
case isPartTime:
workHours=4;
break;
default:
workHours=0;
break;
}
return workHours;
}
public int isPresent()
{
Random rd = new Random();
int randomCheck=rd.nextInt()%3;
return randomCheck;
}
public void computeWage()
{
for(int i=0;i<noOfComp;i++)
{
employee.get(i).setTotalEmpWage(calcWage(employee.get(i)));
System.out.println("Company Name: "+employee.get(i).companyName);
System.out.println("Day\t Daily Hours\t Total Hours\t Daily Wage\t Total Wage");
employee.get(i).printDailyWage();
System.out.println(employee.get(i));
}
}
public int calcWage(companyEmpWage employee)
{
int attendance=0,workHours=0,dailySalary=0,totalSalary=0,totalWorkingDays=0,totalEmpHours=0;
while((totalEmpHours< employee.MAX_HRS_IN_MONTH) && (totalWorkingDays < employee.numWorkingdays))
{
ArrayList<Integer> daily = new ArrayList<>();
totalWorkingDays++;
attendance=isPresent();
workHours=getWorkingHours(attendance);
totalEmpHours+=workHours;
dailySalary=workHours*employee.empRatePerHour;
totalSalary=totalEmpHours*employee.empRatePerHour;
daily.add(totalWorkingDays);
daily.add(workHours);
daily.add(totalEmpHours);
daily.add(dailySalary);
daily.add(totalSalary);
employee.dailyWage.add(daily);
//System.out.println(totalWorkingDays+"\t\t"+workHours+"\t\t"+totalEmpHours+"\t\t"+dailySalary+"\t\t"+totalSalary);
}
return totalSalary;
}
public void getTotalWageByCompanyName(String companyName)
{
System.out.println("Total Wage of Company "+companyName+" is "+employeeMap.get(companyName).totalWage);
}
public static void main(String args[])
{
System.out.println("Welcome to Employee Wage Computation");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of companies:");
int n = sc.nextInt();
empWage emp = new empWage(n);
for(int i=0;i<n;i++)
{
System.out.println("Enter the name of the company:");
String name=sc.next();
System.out.println("Enter employee rate per hour: ");
int rate=sc.nextInt();
System.out.println("Enter total working days: ");
int workingDays=sc.nextInt();
System.out.println("Enter total working hours: ");
int workingHours=sc.nextInt();
//empWage company = new empWage(name,rate,workingDays,workingHours);
//company.calcWage();
emp.addCompany(name,rate,workingDays,workingHours);
//System.out.println(company);
}
emp.computeWage();
String option="yes";
while(option.equals("yes"))
{
System.out.println("Enter the name of the company to find total Wage:");
String name=sc.next();
if(emp.employeeMap.containsKey(name))
emp.getTotalWageByCompanyName(name);
else
System.out.println("Company doesnt exist");
System.out.println("Do you want to continue yes/no?");
option=sc.next();
}
}
}
|
package Problem_1012;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static int[][] arr;
public static int[] dx = { 0, 1, -1, 0 };
public static int[] dy = { 1, 0, 0, -1 };
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int M, N, K;
for (int t = 1; t <= T; t++) {
M = sc.nextInt();
N = sc.nextInt();
K = sc.nextInt();
arr = new int[M][N];
for (int i = 0; i < K; i++) {
arr[sc.nextInt()][sc.nextInt()] = 1;
}
Queue<int[]> q = new LinkedList<>();
int cnt = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (arr[i][j] == 1) {
q.offer(new int[] { i, j });
arr[i][j] = 0;
cnt++;
}
while (!q.isEmpty()) {
int x_ = q.peek()[0];
int y_ = q.poll()[1];
for(int k = 0; k < 4; k++) {
if(0>x_+dx[k] || x_+dx[k] >= M || y_ + dy[k] < 0 || y_ + dy[k] >= N) continue;
if(arr[x_+dx[k]][y_+dy[k]] == 1) {
q.offer(new int[] { x_+dx[k], y_+dy[k]});
arr[x_+dx[k]][y_+dy[k]] = 0;
}
}
}
}
}
System.out.printf("%d\n",cnt);
}
}
}
|
/*
* Copyright (C) 2016 Yong Zhu.
*
* 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.github.drinkjava2.jtransactions.springtx;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import com.github.drinkjava2.jtransactions.ConnectionManager;
/**
* SpringTxConnectionManager is the implementation of ConnectionManager, get
* connection and release connection by using Spring's DataSourceUtils methods
*
* @author Yong Zhu
* @since 1.0.0
*/
public class SpringTxConnectionManager implements ConnectionManager {
private static SpringTxConnectionManager instance = new SpringTxConnectionManager();
public static SpringTxConnectionManager instance() {
return instance;
}
@Override
public Connection getConnection(DataSource ds) throws SQLException {
return DataSourceUtils.getConnection(ds);
}
@Override
public void releaseConnection(Connection conn, DataSource ds) throws SQLException {
DataSourceUtils.releaseConnection(conn, ds);
}
}
|
package com.intel.realsense.librealsense;
public enum CameraInfo {
NAME(0),
SERIAL_NUMBER(1),
FIRMWARE_VERSION(2),
RECOMMENDED_FIRMWARE_VERSION(3),
PHYSICAL_PORT(4),
DEBUG_OP_CODE(5),
ADVANCED_MODE(6),
PRODUCT_ID(7),
CAMERA_LOCKED(8),
USB_TYPE_DESCRIPTOR(9),
PRODUCT_LINE(10),
ASIC_SERIAL_NUMBER(11);
private final int mValue;
private CameraInfo(int value) { mValue = value; }
public int value() { return mValue; }
} |
package com.tsuro.action;
import com.tsuro.board.IBoard;
import com.tsuro.board.Token;
import com.tsuro.rulechecker.IRuleChecker;
import com.tsuro.tile.ITile;
import java.util.Collection;
import java.util.Optional;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
/**
* Represents an Action during the course of a game.
*/
@AllArgsConstructor
@EqualsAndHashCode
public class IntermediateAction implements IAction {
@NonNull
private final ITile tile;
@Override
public Optional<IBoard> doActionIfValid(IRuleChecker rules, IBoard board, Token player,
Collection<ITile> tiles) {
if (rules.isValidIntermediateMove(board, tile, player, tiles)) {
return Optional.of(board.placeTileOnBehalfOfPlayer(tile, player));
}
return Optional.empty();
}
}
|
package com.sushenbiswas.javacode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class ReturnValueInt extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_return_value_int);
goToMain();
}
// this is for Display if Else statement
public void submitOrder(View view) {
display(" // I Defune Number Return Value function here\n" +
" public double makeChange(double itemCost, double dollarsProvided){\n" +
" double change = dollarsProvided-itemCost;\n" +
" return change;\n" +
" };" +
" // I Call The Number Return Value Function\n" +
" double backMoney = makeChange(50,110);\n" +
" System.out.println(backMoney);");
// I Call The Number Return Value Function
double backMoney = makeChange(50,110);
System.out.println(backMoney);
}
// I Defune Number Return Value function here
public double makeChange(double itemCost, double dollarsProvided){
double change = dollarsProvided-itemCost;
return change;
}
private void display(String text) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + text);
}
// this for Button to go main Activety
private void goToMain() {
Button btn = (Button) findViewById(R.id.goToMainBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
Toast.makeText(getApplicationContext(),"I am Going to main activety",Toast.LENGTH_LONG)
.show();
}
});
}
} |
package Controllers.ProductsParts;
import java.util.ArrayList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import MVC.MasterFrame;
import MVC.Product;
import Models.ProductTemplateModel;
import Views.ProductParts.AddProductPartView;
import Views.Products.AddTemplateView;
public class AddProductPartController implements ListSelectionListener {
private ProductTemplateModel model;
private AddProductPartView view;
private MasterFrame master;
private ArrayList arrayList = new ArrayList();
private Product product;
public AddProductPartController(ProductTemplateModel model, AddProductPartView view, MasterFrame m){
this.model = model;
this.view = view;
master = m;
arrayList = model.getProductPartList();
product = model.getCurrentProductObject();
}
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()){
String command = view.getSelectedValue();
view.setFlag(0);
for(int i = 0; i < arrayList.size(); i++){
if(arrayList.get(i).equals(command)){
view.setFlag(1);
master.displayChildMessage("Part already added");
}
}
//if(getNameText().equals(nullString) || getNameText().equals(emptyString)){
//master.displayChildMessage("Part already added");
//}
//arrayList.setListData(view.getSelectedValues());
//Object[] command = view.getSelectedValues();
//System.out.println(command[1].toString());
//product = model.getCurrentProductObject();
}
}
}
|
package com.bestseller.controller.front;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.bestseller.common.Constant;
import com.bestseller.common.session.SessionProvider;
import com.bestseller.pojo.BuyCart;
import com.bestseller.pojo.Buyer;
import com.bestseller.pojo.ItemCart;
import com.bestseller.pojo.Order;
import com.bestseller.pojo.Sku;
import com.bestseller.service.OrderService;
import com.bestseller.service.SkuService;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
public class FrontOrderController {
@Autowired
private OrderService orderService;
@Autowired
private SkuService skuService;
@Autowired
private SessionProvider sessionProvider;
@RequestMapping(value="/buyer/confirmOrder.shtml",method=RequestMethod.POST)
public String addOrder(Order order,HttpServletRequest request,HttpServletResponse response){
ObjectMapper om=new ObjectMapper();
om.setSerializationInclusion(Include.NON_NULL);
BuyCart buyCart=null;
Cookie[] cookies = request.getCookies();
if(cookies!=null&&cookies.length>0){
for(Cookie cookie:cookies){
if(cookie.getName().equals(Constant.COOKIE_CART_NAME)){
try {
buyCart=om.readValue(cookie.getValue(), BuyCart.class);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}else{
return "redirect:/shopping/cart.shtml";
}
//补全sku数据
List<ItemCart> itemCarts = buyCart.getItemCarts();
for(ItemCart itemCart:itemCarts){
Sku sku = skuService.getSkuByKey(itemCart.getSku().getId());
itemCart.setSku(sku);
}
//填充订单用户
Buyer buyer=(Buyer) sessionProvider.getAttribute(response,request, Constant.SESSION_USER_NAME);
order.setBuyerId(buyer.getUsername());
orderService.addOrder(order,buyCart);
//情空购物车
Cookie cookie=new Cookie(Constant.COOKIE_CART_NAME,null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
return "product/confirmOrder";
}
}
|
// Kathryn Brusewitz
// Bellevue College CS211
// Instructor - Bill Iverson
// Chapter 9 - Octagon
import java.awt.Graphics;
public class DrawShapes {
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(300, 300);
Graphics graphics = panel.getGraphics();
Octagon octagon = new Octagon(40);
octagon.drawingPanel(40, 40, graphics);
System.out.println("Perimeter: " + octagon.getPerimeter());
System.out.println("Area: " + octagon.getArea());
}
}
|
package cn.itcast.spring.BeanSimpleIntroduction;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
public class SpringTest {
@Test
public void demo01() {
HelloService helloService = new HelloServiceImpl();
helloService.sayHello();
}
/**
* Java的多态:在Java语言中,多态主要有两种实现形式:一种是继承,另一种是接口,基于接口实现的多态比基于继承实现的多态更加的灵活方便。
* (1)基于继承的多态:在Java中基于继承的多态是指对象方法的调用是通过父类的引用来进行的,也就是说通过父类的引用来指向子类的对象,这样调用父类中定义的方法实际是调用子类中重写的方法。
* (2)基于接口的多态:在Java中基于接口的多态是指对象方法的调用是通过接口的引用来进行的,也就是说通过接口的引用来指向实现类的对象,这样调用接口中定义的方法实际上就是调用实现类中实现的接口的方法
*/
@Test
public void demo02() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"cn/itcast/spring/BeanSimpleIntroduction/beans.xml");
HelloService helloService = (HelloService) applicationContext.getBean("helloServiceImpl");
helloService.sayHello();
}
public void demo03(){
ApplicationContext ac = new FileSystemXmlApplicationContext("WebRoot/beans.xml");
HelloService helloService = (HelloService) ac.getBean("helloServiceImpl");
helloService.sayHello();
}
public void demo04(){
//BeanFactory bf = new ClassPathXmlApplicationContext("beans.xml");
//BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml"));
BeanFactory bf = new FileSystemXmlApplicationContext("WebRoot/beans.xml");
//BeanFactory bf = new XmlBeanFactory(new FileSystemResource("WebRoot/beans.xml"));
HelloService helloService = (HelloService) bf.getBean("helloServiceImpl");
helloService.sayHello();
}
}
|
package utils;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.v7.app.NotificationCompat;
import android.support.v7.widget.ThemedSpinnerAdapter;
import android.util.Log;
import android.widget.Toast;
import com.activeandroid.Model;
import com.activeandroid.query.Select;
import com.it.nhozip.docbao.MainActivity;
import com.it.nhozip.docbao.R;
import org.jsoup.Jsoup;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Handler;
import model.ItemRSS;
import model.ItemTT;
import rss.ReadRSS;
import rss.XMLDOMParser;
/**
* Created by Nhozip on 6/17/2016.
*/
public class Notify extends BroadcastReceiver {
public static final int GET_DATA = 1;
private static final int NO_DATA =2 ;
private ArrayList<ItemRSS> dataNew = new ArrayList<>();
private ReadRSS readRSS = new ReadRSS();
private Context context;
// android.os.Handler handler=new android.os.Handler(){
// @Override
// public void handleMessage(Message msg) {
// if(msg.arg1==GET_DATA){
// // Toast.makeText(context,"CÓ tin mới",Toast.LENGTH_LONG).show();
// new GetDataVnXpress(context,handler).execute();
// }else if (msg.arg1==NO_DATA){
// //Toast.makeText(context,"no data",Toast.LENGTH_LONG).show();
// }
//
// super.handleMessage(msg);
// }
// };
@Override
public void onReceive(final Context context, Intent intent) {
//this.context=context;
if(isOnline(context)){
new GetDataVnXpress(context).execute();
}
}
private Boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
return true;
}
return false;
}
class GetDataVnXpress extends AsyncTask<ArrayList<ItemRSS>, Integer, ArrayList<ItemRSS>> {
Context context;
//android.os.Handler handler;
public GetDataVnXpress(Context context) {
this.context = context;
// this.handler=handler;
}
@Override
protected ArrayList<ItemRSS> doInBackground(ArrayList<ItemRSS>... params) {
dataNew = readRSS.getData("http://vnexpress.net/rss/tin-moi-nhat.rss");
return dataNew;
}
@Override
protected void onPostExecute(ArrayList<ItemRSS> itemRSSes) {
super.onPostExecute(itemRSSes);
List<ItemTT> ls = new Select().from(ItemTT.class).execute();
ArrayList<ItemTT> dataOld = new ArrayList<>();
dataOld.clear();
dataOld.addAll(ls);
Log.e("dataOld", dataOld.toString());
Log.e("dataNew", dataNew.toString());
// if (!itemRSSes.isEmpty()){
// Message ms=new Message();
// ms.obj=dataNew.toString();
// ms.arg1=GET_DATA;
// handler.sendMessage(ms);
// }else{
// Message ms=new Message();
// ms.obj="";
// ms.arg1=NO_DATA;
// handler.sendMessage(ms);
// }
if (dataNew.get(0).get_link().compareTo(dataOld.get(0).getLink()) != 0) {
NotificationManager notificationService = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notBuilder = new NotificationCompat.Builder(context);
notBuilder.setSmallIcon(R.mipmap.ic_launcher);
notBuilder.setContentTitle("Có Tin mới");
notBuilder.setContentText("Có tin mới từ vnXpress ....");
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
notBuilder.setContentIntent(pendingIntent);
notBuilder.setAutoCancel(true);
Notification notification = notBuilder.build();
notificationService.notify(1, notification);
}
}
}
}
|
class Apattern28
{
public static void main(String [] args)
{
for(int i=5;i>=1;i--)
{
for(int j=5;j>i;j--)
{
System.out.print(" ");
}
int k=1;
while(k<=5)
{
System.out.print("*");
k++;
}
System.out.println();
}
}
} |
package classes;
public class Firsttry {
public static void main(String[] args){
System.out.println("hello git!");
System.out.println("push this");
Car porshe = new Car();
porshe.setDoors(4);
System.out.println(porshe.getDoors());
porshe.setColour("matte black");
System.out.println(porshe.getColour());
BankAccount Brunos = new BankAccount(500,500,"Bruno","email","9053342972");
BankAccount vivas = new BankAccount(5230,2323,"viva","email","9053qwer42972");
System.out.println(Brunos.getBalance());
System.out.println(vivas.getBalance());
AnimalInher animal= new AnimalInher("Animal",1,1,5,5);
Dog dog = new Dog("Yorkie",8,20,2,4,1,20,"long silky");
dog.eat();
}
}
|
package com.csc.capturetool.myapplication.base;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import com.csc.capturetool.myapplication.http.listener.LifeCycleObserver;
import com.csc.capturetool.myapplication.utils.DialogUtils;
import com.csc.capturetool.myapplication.utils.SystemBarTintUtils;
public abstract class BaseActivity<V, T extends BasePresenter<V>> extends AppCompatActivity {
protected T mPresenter;
private static final int STATUS_BAR_COLOR = Color.parseColor("#f8f8f8");
private boolean isShowing;
private LifeCycleObserver observer;
private Dialog mProgressBar;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(getContentView());
mPresenter = createPresenter();
if (mPresenter != null) {
mPresenter.attachView((V) this);
}
int mode = getStatusBarLightMode();
switch (mode) {
case 1:
case 2:
case 3:
SystemBarTintUtils.setStatusBarColor(this, STATUS_BAR_COLOR);
break;
case 0:
SystemBarTintUtils.setStatusBarColor(this, Color.parseColor("#000000"));
break;
default:
}
initView();
initData();
}
protected int getStatusBarLightMode() {
return SystemBarTintUtils.getStatusBarLightMode(this);
}
protected abstract int getContentView();
protected abstract void initView();
protected abstract void initData();
// @Override
// public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// }
protected abstract T createPresenter();
public void showProgressBar() {
if (!isShowing) {
mProgressBar = DialogUtils.showIosLoading(this, new DialogUtils.OnKeyBackListener() {
@Override
public void onKeyBack() {
onBackPressed();
}
});
isShowing = true;
}
}
public void setActivityLifeCycleObserver(LifeCycleObserver observer) {
this.observer = observer;
}
@Override
protected void onPause() {
super.onPause();
dismissProgressBar();
}
public void dismissProgressBar() {
if (isShowing) {
if (mProgressBar != null) {
mProgressBar.dismiss();
mProgressBar = null;
}
isShowing = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (observer != null) {
observer.onDestroy();
}
}
@Override
public void onBackPressed() {
dismissProgressBar();
super.onBackPressed();
}
}
|
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ServerMain{
static List<ChatService> ar = new ArrayList<>();
public static void main(String[] args) throws IOException {
MyServer server = new MyServer();
ChatDirectory chatDirectory = new ChatDirectory();
System.out.println("Waiting for clients to connect...");
while(true){
Socket s = server.ss.accept();
System.out.println("Client connected");
//create streams for server side - connections to client a
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
dos.writeUTF("Login: ");
dos.flush();
String str = (String) dis.readUTF();
User user = chatDirectory.findUser(str);
if(user == null){
chatDirectory.newUser(str);
user = chatDirectory.findUser(str);
}
dos.writeUTF("Welcome, " + str);
ChatService service = new ChatService(s, user, chatDirectory, dis, dos);
Thread t = new Thread(service);
ar.add(service);
t.start();
}
}
}
|
package View;
import Controller.LoginControl;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;
public class RegisterView extends javax.swing.JFrame {
public RegisterView() {
super("Register");
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jSeparator2 = new javax.swing.JSeparator();
jSeparator3 = new javax.swing.JSeparator();
jSeparator4 = new javax.swing.JSeparator();
txt_username = new javax.swing.JTextField();
txt_answer = new javax.swing.JTextField();
txt_password = new javax.swing.JPasswordField();
btn_register = new javax.swing.JButton();
jSeparator5 = new javax.swing.JSeparator();
txt_sq = new javax.swing.JComboBox();
txt_email = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jSeparator6 = new javax.swing.JSeparator();
txt_age = new javax.swing.JTextField();
btn_other = new javax.swing.JRadioButton();
btn_male = new javax.swing.JRadioButton();
btn_female = new javax.swing.JRadioButton();
jLabel8 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel1.setBackground(new java.awt.Color(97, 212, 195));
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel2.setBackground(new java.awt.Color(139, 0, 139));
jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel3.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Register");
jPanel2.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 10, 80, 40));
jLabel4.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Username");
jPanel2.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 60, 100, 30));
jLabel5.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Email ");
jPanel2.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 100, 90, 30));
jLabel6.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("Password");
jPanel2.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 230, 80, 30));
jLabel7.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("Security Query");
jPanel2.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 270, 100, 30));
jSeparator2.setBackground(new java.awt.Color(255, 255, 255));
jSeparator2.setForeground(new java.awt.Color(255, 255, 255));
jPanel2.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 90, 250, 20));
jSeparator3.setBackground(new java.awt.Color(255, 255, 255));
jSeparator3.setForeground(new java.awt.Color(255, 255, 255));
jPanel2.add(jSeparator3, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 220, 70, 20));
jSeparator4.setBackground(new java.awt.Color(255, 255, 255));
jSeparator4.setForeground(new java.awt.Color(255, 255, 255));
jPanel2.add(jSeparator4, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 260, 250, 20));
txt_username.setBackground(new java.awt.Color(139, 0, 139));
txt_username.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
txt_username.setForeground(new java.awt.Color(255, 255, 255));
txt_username.setBorder(null);
jPanel2.add(txt_username, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 60, 250, 30));
txt_answer.setBackground(new java.awt.Color(139, 0, 139));
txt_answer.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
txt_answer.setForeground(new java.awt.Color(255, 255, 255));
txt_answer.setBorder(null);
jPanel2.add(txt_answer, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 300, 210, 30));
txt_password.setBackground(new java.awt.Color(139, 0, 139));
txt_password.setForeground(new java.awt.Color(255, 255, 255));
txt_password.setBorder(null);
jPanel2.add(txt_password, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 230, 250, 30));
btn_register.setBackground(new java.awt.Color(97, 212, 195));
btn_register.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N
btn_register.setForeground(new java.awt.Color(255, 255, 255));
btn_register.setText("Register");
btn_register.setBorder(null);
btn_register.setPreferredSize(new java.awt.Dimension(36, 19));
btn_register.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_registerActionPerformed(evt);
}
});
jPanel2.add(btn_register, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 390, 107, 44));
jSeparator5.setBackground(new java.awt.Color(255, 255, 255));
jSeparator5.setForeground(new java.awt.Color(255, 255, 255));
jPanel2.add(jSeparator5, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 330, 210, 20));
txt_sq.setBackground(new java.awt.Color(139, 0, 139));
txt_sq.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N
txt_sq.setForeground(new java.awt.Color(255, 255, 255));
txt_sq.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "What's your nick name ?", "your best friend Name?", "your best number ?", "your best teacher name ?" }));
txt_sq.setBorder(null);
jPanel2.add(txt_sq, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 270, 230, 30));
txt_email.setBackground(new java.awt.Color(139, 0, 139));
txt_email.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
txt_email.setForeground(new java.awt.Color(255, 255, 255));
txt_email.setBorder(null);
jPanel2.add(txt_email, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 100, 250, 30));
jLabel9.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("Age");
jPanel2.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 200, -1, -1));
jLabel10.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("Gender");
jPanel2.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 150, -1, 20));
jSeparator6.setBackground(new java.awt.Color(255, 255, 255));
jSeparator6.setForeground(new java.awt.Color(255, 255, 255));
jPanel2.add(jSeparator6, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 130, 250, 20));
txt_age.setBackground(new java.awt.Color(139, 0, 139));
txt_age.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
txt_age.setForeground(new java.awt.Color(255, 255, 255));
txt_age.setBorder(null);
jPanel2.add(txt_age, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 190, 70, 30));
btn_other.setBackground(new java.awt.Color(139, 0, 139));
buttonGroup1.add(btn_other);
btn_other.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
btn_other.setForeground(new java.awt.Color(255, 255, 255));
btn_other.setText("Other");
btn_other.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_otherActionPerformed(evt);
}
});
jPanel2.add(btn_other, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 150, -1, -1));
btn_male.setBackground(new java.awt.Color(139, 0, 139));
buttonGroup1.add(btn_male);
btn_male.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
btn_male.setForeground(new java.awt.Color(255, 255, 255));
btn_male.setText("Male");
btn_male.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_maleActionPerformed(evt);
}
});
jPanel2.add(btn_male, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 150, -1, -1));
btn_female.setBackground(new java.awt.Color(139, 0, 139));
buttonGroup1.add(btn_female);
btn_female.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N
btn_female.setForeground(new java.awt.Color(255, 255, 255));
btn_female.setText("Female");
btn_female.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_femaleActionPerformed(evt);
}
});
jPanel2.add(btn_female, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 150, -1, -1));
jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 60, 460, 480));
jLabel8.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("Please Fill up then Submit the form....");
jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 30, 370, 40));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/View/Back To_48px.png"))); // NOI18N
jLabel2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel2MouseClicked(evt);
}
});
jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 540, 590));
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
public String getUsername(){
return txt_username.getText();
}
public String getEmail(){
return txt_email.getText();
}
public String getGender(){
return gender;
}
public String getAge(){
return txt_age.getText();
}
public String getPassword(){
return txt_password.getText();
}
public Object getQuest(){
return txt_sq.getSelectedItem();
}
public String getAnswer(){
return txt_answer.getText();
}
public void RegisterActionPerformed(ActionListener al){
btn_register.addActionListener(al);
}
private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel2MouseClicked
// TODO add your handling code here:
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
dispose();
new LoginControl();
}
});
}//GEN-LAST:event_jLabel2MouseClicked
private void btn_registerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_registerActionPerformed
if(txt_username.getText().isEmpty()){
getToolkit().beep();
JOptionPane.showMessageDialog(null, "please Enter valid username");
txt_username.requestFocus();
}
else if(txt_email.getText().isEmpty()){
getToolkit().beep();
JOptionPane.showMessageDialog(null, "please Enter valid email");
txt_username.requestFocus();
}
else if(txt_age.getText().isEmpty()){
getToolkit().beep();
JOptionPane.showMessageDialog(null, "please Enter valid age");
txt_username.requestFocus();
}
else if(txt_password.getText().isEmpty()){
getToolkit().beep();
JOptionPane.showMessageDialog(null, "please Enter valid password");
txt_username.requestFocus();
}
else if(txt_answer.getText().isEmpty()){
getToolkit().beep();
JOptionPane.showMessageDialog(null, "please Enter valid Answer");
txt_username.requestFocus();
}
else
{
}
}//GEN-LAST:event_btn_registerActionPerformed
private void btn_maleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_maleActionPerformed
gender = "m";
}//GEN-LAST:event_btn_maleActionPerformed
private void btn_femaleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_femaleActionPerformed
gender = "f";
}//GEN-LAST:event_btn_femaleActionPerformed
private void btn_otherActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_otherActionPerformed
gender = "o";
}//GEN-LAST:event_btn_otherActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JRadioButton btn_female;
private javax.swing.JRadioButton btn_male;
private javax.swing.JRadioButton btn_other;
private javax.swing.JButton btn_register;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JSeparator jSeparator6;
private javax.swing.JTextField txt_age;
private javax.swing.JTextField txt_answer;
private javax.swing.JTextField txt_email;
private javax.swing.JPasswordField txt_password;
private javax.swing.JComboBox txt_sq;
private javax.swing.JTextField txt_username;
// End of variables declaration//GEN-END:variables
private String gender;
}
|
/*
* MIT License
* (c) 2013 bernd@snowhow.info
*
*/
package info.snowhow.plugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import android.content.Intent;
public class GPSTrack extends CordovaPlugin {
private static final String LOG_TAG = "GPSTrack";
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("record")) {
final String trackFile = args.getString(0);
final float precision = (float) args.getDouble(1);
final boolean adaptiveRecording = (boolean) args.getBoolean(2);
final String trackName = args.getString(3);
if (trackFile.indexOf("file:///") > -1) {
record(trackFile.substring(7), precision, adaptiveRecording, trackName);
} else {
record(trackFile, precision, adaptiveRecording, trackName);
}
JSONObject obj = new JSONObject();
obj.put("test", 1);
PluginResult res = new PluginResult(PluginResult.Status.OK, obj);
res.setKeepCallback(true);
callbackContext.sendPluginResult(res);
Log.d(LOG_TAG, "done sending to webapp");
// cordova.getActivity().runOnUiThread(new Runnable() {
// @Override
// public void run() {
// GPSTrack.this.record(trackFile);
// // callbackContext.success();
// }
// });
} else if (action.equals("listen")) {
JSONObject obj = new JSONObject();
obj.put("test", 1);
PluginResult res = new PluginResult(PluginResult.Status.OK, obj);
res.setKeepCallback(true);
callbackContext.sendPluginResult(res);
Log.d(LOG_TAG, "done sending to webapp");
} else {
return false;
}
return true;
}
public void record(final String trackFile, final float precision, final boolean adaptiveRecording,
String trackName) {
Context context = cordova.getActivity().getApplicationContext();
Intent intent = new Intent(context, RecorderService.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("fileName", trackFile);
intent.putExtra("precision", precision);
intent.putExtra("adaptiveRecording", adaptiveRecording);
intent.putExtra("trackName", trackName);
Log.d(LOG_TAG, "in record ... should start intent now");
context.startService(intent);
}
}
|
package orm.integ.dao.sql;
public class TabQuery extends QueryRequest {
private Where where = new Where();
private TabQuery joinQuery;
private String joinByField;
public TabQuery() {
}
public TabQuery(TableInfo tab) {
this.setTableInfo(tab);
}
public Where getWhere() {
return where;
}
public void setWhere(Where where) {
this.where = where;
}
@Override
public Object[] getValues() {
return where.getValues();
}
public void addWhereItem(String whereStmt, Object...values) {
where.addItem(whereStmt, values);
}
@Override
public TabQuery clone() {
TabQuery q = new TabQuery();
q.copyFrom(this);
q.getWhere().copyFrom(this.getWhere());
return q;
}
@Override
public int getCountQueryHashCode() {
int code = tableName.hashCode();
code = code*31 + where.hashCode();
code = code*31 + order.hashCode();
return code;
}
public void setJoinQuery(TabQuery joinQuery, String joinByField) {
this.joinByField = joinByField;
this.joinQuery = joinQuery;
}
public TabQuery getJoinQuery() {
return joinQuery;
}
public String getJoinByField() {
return joinByField;
}
}
|
package Factory;
public class Cassandra extends DB {
@Override
public int Connect() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int Disconnect() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int Query(String s) {
// TODO Auto-generated method stub
return 0;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.navegador.recreio.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
/**
*
* @author snnangolaPC
*/
@Embeddable
public class MergulhadoresPK implements Serializable {
@Basic(optional = false)
@Column(name = "id_mergulhadores")
private int idMergulhadores;
@Basic(optional = false)
@NotNull
@Column(name = "tipo_licenca_mergulhador_id_tipo_licenca_mergulhador")
private int tipoLicencaMergulhadorIdTipoLicencaMergulhador;
public MergulhadoresPK() {
}
public MergulhadoresPK(int idMergulhadores, int tipoLicencaMergulhadorIdTipoLicencaMergulhador) {
this.idMergulhadores = idMergulhadores;
this.tipoLicencaMergulhadorIdTipoLicencaMergulhador = tipoLicencaMergulhadorIdTipoLicencaMergulhador;
}
public int getIdMergulhadores() {
return idMergulhadores;
}
public void setIdMergulhadores(int idMergulhadores) {
this.idMergulhadores = idMergulhadores;
}
public int getTipoLicencaMergulhadorIdTipoLicencaMergulhador() {
return tipoLicencaMergulhadorIdTipoLicencaMergulhador;
}
public void setTipoLicencaMergulhadorIdTipoLicencaMergulhador(int tipoLicencaMergulhadorIdTipoLicencaMergulhador) {
this.tipoLicencaMergulhadorIdTipoLicencaMergulhador = tipoLicencaMergulhadorIdTipoLicencaMergulhador;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) idMergulhadores;
hash += (int) tipoLicencaMergulhadorIdTipoLicencaMergulhador;
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 MergulhadoresPK)) {
return false;
}
MergulhadoresPK other = (MergulhadoresPK) object;
if (this.idMergulhadores != other.idMergulhadores) {
return false;
}
if (this.tipoLicencaMergulhadorIdTipoLicencaMergulhador != other.tipoLicencaMergulhadorIdTipoLicencaMergulhador) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.navegador.recreio.entity.MergulhadoresPK[ idMergulhadores=" + idMergulhadores + ", tipoLicencaMergulhadorIdTipoLicencaMergulhador=" + tipoLicencaMergulhadorIdTipoLicencaMergulhador + " ]";
}
}
|
package com.lenovohit.hwe.treat.web.rest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.lenovohit.core.dao.Page;
import com.lenovohit.core.exception.BaseException;
import com.lenovohit.core.manager.GenericManager;
import com.lenovohit.core.utils.JSONUtils;
import com.lenovohit.core.utils.StringUtils;
import com.lenovohit.core.web.MediaTypes;
import com.lenovohit.core.web.utils.Result;
import com.lenovohit.core.web.utils.ResultUtils;
import com.lenovohit.hwe.org.web.rest.OrgBaseRestController;
import com.lenovohit.hwe.treat.model.Foregift;
import com.lenovohit.hwe.treat.model.Trade;
@RestController
@RequestMapping("/hwe/treat/foregift")
public class ForegiftRestController extends OrgBaseRestController {
@Autowired
private GenericManager<Foregift, String> foregiftManager;
@Value("${his.baseUrl}")
private String baseUrl;
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result getInfo(@PathVariable("id") String id){
Foregift model = this.foregiftManager.get(id);
return ResultUtils.renderPageResult(model);
}
@RequestMapping(value = "/page/{start}/{limit}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forPage(@PathVariable("start") String start, @PathVariable("limit") String limit,
@RequestParam(value = "data", defaultValue = "") String data){
Foregift query = JSONUtils.deserialize(data, Foregift.class);
StringBuilder jql = new StringBuilder( " from Foregift where 1=1 ");
List<Object> values = new ArrayList<Object>();
if(!StringUtils.isEmpty(query.getProId())){
jql.append(" and proId = ? ");
values.add(query.getProId());
}
if(!StringUtils.isEmpty(query.getProNo())){
jql.append(" and proNo = ? ");
values.add(query.getProNo());
}
if(!StringUtils.isEmpty(query.getUserId())){
jql.append(" and userId = ? ");
values.add(query.getUserId());
}
if(!StringUtils.isEmpty(query.getTradeChannel())){
jql.append(" and tradeChannel = ? ");
values.add(query.getTradeChannel());
}
if(!StringUtils.isEmpty(query.getTradeNo())){
jql.append(" and tradeNo = ? ");
values.add(query.getTradeNo());
}
if(!StringUtils.isEmpty(query.getStatus())){
jql.append(" and status = ? ");
values.add(query.getStatus());
}
jql.append("order by createdAt");
Page page = new Page();
page.setStart(start);
page.setPageSize(limit);
page.setQuery(jql.toString());
page.setValues(values.toArray());
this.foregiftManager.findPage(page);
return ResultUtils.renderPageResult(page);
}
@RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forList(@RequestParam(value = "data", defaultValue = "") String data) {
Foregift query = JSONUtils.deserialize(data, Foregift.class);
StringBuilder jql = new StringBuilder( " from Foregift where 1=1 ");
List<Object> values = new ArrayList<Object>();
if(!StringUtils.isEmpty(query.getProId())){
jql.append(" and proId = ? ");
values.add(query.getProId());
}
if(!StringUtils.isEmpty(query.getProNo())){
jql.append(" and proNo = ? ");
values.add(query.getProNo());
}
if(!StringUtils.isEmpty(query.getUserId())){
jql.append(" and userId = ? ");
values.add(query.getUserId());
}
if(!StringUtils.isEmpty(query.getTradeChannel())){
jql.append(" and tradeChannel = ? ");
values.add(query.getTradeChannel());
}
if(!StringUtils.isEmpty(query.getTradeNo())){
jql.append(" and tradeNo = ? ");
values.add(query.getTradeNo());
}
if(!StringUtils.isEmpty(query.getStatus())){
jql.append(" and status = ? ");
values.add(query.getStatus());
}
jql.append("order by createdAt");
List<Foregift> foregifts = this.foregiftManager.find(jql.toString(),values.toArray());
return ResultUtils.renderSuccessResult(foregifts);
}
@RequestMapping(value="",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8/*TEXT_PLAIN_UTF_8*/)
public Result forCreate(@RequestBody String data){
Foregift foregift = JSONUtils.deserialize(data, Foregift.class);
foregift.setForegiftTime(new Date());
Foregift saved = this.foregiftManager.save(foregift);
return ResultUtils.renderSuccessResult(saved);
}
@RequestMapping(value = "/{id}",method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
public Result forRemove(@PathVariable("id") String id){
try {
this.foregiftManager.delete(id);
} catch (Exception e) {
throw new BaseException("删除失败");
}
return ResultUtils.renderSuccessResult();
}
@SuppressWarnings("rawtypes")
@RequestMapping(value = "/removeAll",method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
public Result forRemoveAll(@RequestBody String data){
List ids = JSONUtils.deserialize(data, List.class);
StringBuilder idSql = new StringBuilder();
List<String> idvalues = new ArrayList<String>();
try {
idSql.append("DELETE FROM TREAT_FOREGIFT WHERE ID IN (");
for(int i = 0 ; i < ids.size() ; i++) {
idSql.append("?");
idvalues.add(ids.get(i).toString());
if(i != ids.size() - 1) idSql.append(",");
}
idSql.append(")");
this.foregiftManager.executeSql(idSql.toString(), idvalues.toArray());
} catch (Exception e) {
e.printStackTrace();
throw new BaseException("删除失败");
}
return ResultUtils.renderSuccessResult();
}
@RequestMapping(value="/callback",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result foregiftCallback(@RequestBody String data){
Trade trade = JSONUtils.deserialize(data, Trade.class);
if (StringUtils.isEmpty(trade.getBizNo())) {
ResultUtils.renderFailureResult();
}
// 1.回写运存表
Foregift foregiftModel = this.foregiftManager.get(trade.getBizNo());
if (trade.getPayChannleCode().equals("wxpay")) {
foregiftModel.setTradeChannel("W");
} else if (trade.getPayChannleCode().equals("aliPay")) {
foregiftModel.setTradeChannelCode("9998");
} else if (trade.getPayChannleCode().equals("alipay")) {
foregiftModel.setTradeChannel("Z");
foregiftModel.setTradeChannelCode("9999");
}
foregiftModel.setTradeNo(trade.getTradeNo());
foregiftModel.setTradeTime(trade.getTradeTime());
foregiftModel.setStatus(trade.getStatus());
this.foregiftManager.save(foregiftModel);
// wuxs will delete begin
// 此为测试数据,用于区分hcp中deposit表的数据是门诊还是住院(当前的模拟数据都存储在了deposit表中了)
foregiftModel.setTradeTerminalCode("04");
// wuxs will delete end
RestTemplate restTemplate = new RestTemplate();
// his端暂时用deposit来模拟foregift
ResponseEntity<Foregift> response = restTemplate.postForEntity(baseUrl + "hcp/app/test/foregift/recharge", foregiftModel, Foregift.class);
if(response.getStatusCode() == HttpStatus.OK){
Foregift resultForegift = response.getBody();
foregiftModel.setNo(resultForegift.getNo());
foregiftModel.setBalance(resultForegift.getBalance());
this.foregiftManager.save(foregiftModel);
}
return ResultUtils.renderSuccessResult();
}
}
|
package com.mindtree.spring.daoImpl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import com.mindtree.spring.dao.EmployeeDAO;
public class EmployeeDAOImpl implements EmployeeDAO {
public List<Object[]> getProjectEmployeeName(int id) {
Session session = null;
Transaction txn = null;
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
txn = session.beginTransaction();
String hql = "from Employee join Project on project_id=id where id=:id";
Query query = session.createQuery(hql);
query.setParameter("id",id);
List<Object[]> list = query.list();
txn.commit();
session.close();
return list;
}
}
|
package oops;
public class Model extends Audi {
public void model() {
// TODO Auto-generated method stub
System.out.println("2020 model");
}
public void about() {
System.out.println("AC car");
}
}
|
package com.spreadtrum.android.eng;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
public class psverinfo extends Activity {
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 44) {
psverinfo.this.mTextView01.setText(msg.obj);
}
}
};
private engfetch mEf;
private TextView mTextView01;
Runnable runnable = new Runnable() {
public void run() {
Log.e("psverinfo", "run is Runnable~~~");
Message msg = psverinfo.this.handler.obtainMessage();
msg.what = 44;
msg.obj = psverinfo.this.writeAndReadDateFromServer(msg.what);
Log.e("psverinfo", "msg.obj = <" + msg.obj + ">");
psverinfo.this.handler.sendMessage(msg);
}
};
private int sockid = 0;
private String str;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.psverinfo);
this.mTextView01 = (TextView) findViewById(R.id.ps01_view);
this.mTextView01.setText("Wait...");
initialpara();
Thread myThread = new Thread(this.runnable);
myThread.setName("new thread");
myThread.start();
Log.e("psverinfo", "thread name =" + myThread.getName() + " id =" + myThread.getId());
}
private void initialpara() {
this.mEf = new engfetch();
this.sockid = this.mEf.engopen();
}
private String writeAndReadDateFromServer(int what) {
ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
DataOutputStream outputBufferStream = new DataOutputStream(outputBuffer);
Log.e("psverinfo", "engopen sockid=" + this.sockid);
this.str = what + "," + 1 + "," + 0;
try {
outputBufferStream.writeBytes(this.str);
this.mEf.engwrite(this.sockid, outputBuffer.toByteArray(), outputBuffer.toByteArray().length);
byte[] inputBytes = new byte[128];
String str123 = new String(inputBytes, 0, this.mEf.engread(this.sockid, inputBytes, 128), Charset.defaultCharset());
Log.e("psverinfo", "str123" + str123);
return str123;
} catch (IOException e) {
Log.e("psverinfo", "writebytes error");
return "error";
}
}
}
|
/*
* 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 Controlador;
import Modelo.Empleado;
import Modelo.HistorialCaja;
import Modelo.dbconecction.CRUD;
import Vista.DialogAbrirCaja;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.util.Date;
import javax.swing.ImageIcon;
/**
*
* @author Percy
*/
public class ControladorAbrirCaja {
Empleado activo;
DialogAbrirCaja vistaAbrirCaja;
CRUD consulta=CRUD.getInstance();
ControladorMenuPrincipal coMenuPrincipal;
HistorialCaja cajaEmpleado;
public ControladorAbrirCaja(DialogAbrirCaja vistaAbrirCaja,Empleado activo) {
this.vistaAbrirCaja = vistaAbrirCaja;
this.activo= activo;
this.coMenuPrincipal=coMenuPrincipal;
this.cajaEmpleado=cajaEmpleado;
//Eventos de Botones
insertarElementos();
insertarEventos1();
vistaAbrirCaja.setVisible(true);
}
public ControladorAbrirCaja(DialogAbrirCaja vistaAbrirCaja,Empleado activo,ControladorMenuPrincipal coMenuPrincipal) {
this.vistaAbrirCaja = vistaAbrirCaja;
this.activo= activo;
this.coMenuPrincipal=coMenuPrincipal;
this.cajaEmpleado=cajaEmpleado;
//Eventos de Botones
insertarElementos();
insertarEventos();
vistaAbrirCaja.setVisible(true);
}
public void insertarElementos(){
//Insertar los elementos del comboBox
ResultSet rs = consulta.select("SELECT * FROM caja");
try{
while(rs.next()){
this.vistaAbrirCaja.cbcaja.addItem( rs.getString(2));
}
}catch(Exception ex){
}
}
public void insertarEventos(){
ActionListener evAbrirC = new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
activo.OpenCashier(vistaAbrirCaja.cbcaja.getSelectedIndex()+1,Float.parseFloat( vistaAbrirCaja.txtMontoInicial.getText()));
coMenuPrincipal.rutaImagenAmostrar = new ImageIcon("src/IMAGENES/cash-register-green.png");
Image Imagen = coMenuPrincipal.rutaImagenAmostrar.getImage();
//Remidencionamos
Image ImagenModificada= Imagen.getScaledInstance(coMenuPrincipal.vistaMenuPrincipal.btncaja.getWidth(), coMenuPrincipal.vistaMenuPrincipal.btncaja.getHeight(), java.awt.Image.SCALE_SMOOTH);
//Mostramos
ImageIcon rutaImagenAmostrar= new ImageIcon(ImagenModificada);
coMenuPrincipal.vistaMenuPrincipal.btncaja.setIcon(rutaImagenAmostrar);
vistaAbrirCaja.dispose();
}
};
this.vistaAbrirCaja.btnaceptar.addActionListener(evAbrirC);
}
private void insertarEventos1() {
ActionListener evAbrirC = new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
activo.OpenCashier(vistaAbrirCaja.cbcaja.getSelectedIndex()+1,Float.parseFloat( vistaAbrirCaja.txtMontoInicial.getText()));
vistaAbrirCaja.dispose();
}
};
this.vistaAbrirCaja.btnaceptar.addActionListener(evAbrirC);
}
}
|
package fr.aresrpg.tofumanchou.domain.data;
import fr.aresrpg.commons.domain.log.Logger;
import fr.aresrpg.tofumanchou.domain.data.entity.player.Perso;
import fr.aresrpg.tofumanchou.domain.data.inventory.Inventory;
import fr.aresrpg.tofumanchou.domain.io.Proxy;
import java.net.SocketAddress;
/**
*
* @since
*/
public interface Account {
int getId();
SocketAddress getAdress();
String getAccountName();
String getPassword();
Perso getPerso();
Logger getLogger();
Inventory getBank();
Proxy getProxy();
}
|
package com.baopinghui.bin.service;
import java.util.List;
import java.util.Map;
import com.baopinghui.bin.dto.ResultDto;
import com.baopinghui.bin.entity.CourseEntity;
import com.baopinghui.bin.entity.DianMianEntity;
public interface CourseService {
Integer insertCourse(CourseEntity c);
Integer updateCourse(CourseEntity c);
Integer deleteCourse(int id);
List<Map<String,Object>>selectCourse();
}
|
package ex01_user_type;
/*
* 클래스
* 1. 필드
* 클래스에 선언한 변수값
* 2. 메소드
* 클래스에 정의(만든)한 함수
*
* */
public class Person { //클래스, 클래스에서 선언한 것은 필드
String name; // null
int age; // 0
double height; // 0,0
char gender; // '\0' (널 문자)
boolean isKorean; // false
public static void main(String[] args) { // 메소드, 메소드에서 선언한것은 일반 변수
// 필드를 선언합니다. (변수를 선언합니다.)
// 일반 변수와 다르게 필드는 자동으로 초기화가 됩니다.( 0, null)
}
}
|
package group29;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import genius.core.AgentID;
import genius.core.Bid;
import genius.core.actions.Accept;
import genius.core.actions.Action;
import genius.core.actions.Offer;
import genius.core.parties.AbstractNegotiationParty;
import genius.core.parties.NegotiationInfo;
import genius.core.uncertainty.BidRanking;
import genius.core.uncertainty.ExperimentalUserModel;
import genius.core.utility.AbstractUtilitySpace;
import genius.core.utility.AdditiveUtilitySpace;
import genius.core.utility.UncertainAdditiveUtilitySpace;
/**
* ExampleAgent returns the bid that maximizes its own utility for half of the negotiation session.
* In the second half, it offers a random bid. It only accepts the bid on the table in this phase,
* if the utility of the bid is higher than Example Agent's last bid.
**/
public class Agent29 extends AbstractNegotiationParty {
private final String description = "Group 29 Agent Learning";
private Bid lastReceivedOffer; // offer received from opponent
private Bid maxBidForme;
private IaMap iaMap;
private AbstractUtilitySpace predictAbstractSpace;
private AdditiveUtilitySpace predictAddtiveSpace;
private BidRanking bidRanking;
private double concessionValue;
@Override
public void init(NegotiationInfo info) {
super.init(info);
this.iaMap=new IaMap(userModel);
// GeneticAlgorithm geneticAlgorithm = new GeneticAlgorithm(userModel);
// this.predictAbstractSpace = geneticAlgorithm.geneticAlgorithm();
UserPrefElicit userPref = new UserPrefElicit(userModel);
predictAbstractSpace = userPref.geneticAlgorithm();
this.predictAddtiveSpace = (AdditiveUtilitySpace)predictAbstractSpace;
this.bidRanking = userModel.getBidRanking();
this.maxBidForme = bidRanking.getMaximalBid();
this.concessionValue = 0.8;
// for (int i = 0; i < 10; i ++) {
// Bid testBid = bidRanking.getRandomBid();
// utilityError(testBid);
// }
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
}
private double utilityError(Bid bid) {
ExperimentalUserModel e = (ExperimentalUserModel) userModel;
UncertainAdditiveUtilitySpace realUSpace = e.getRealUtilitySpace();
double ret = Math.abs(this.predictAddtiveSpace.getUtility(bid) - realUSpace.getUtility(bid));
System.out.println("Utility Error: " + ret);
return ret;
}
private double disagreeUtility(double disagreePercent) {
List<Bid> bidList = userModel.getBidRanking().getBidOrder();
int bidListSize = bidList.size();
int disagreeIndex = (int)Math.ceil(bidListSize * disagreePercent);
double ret = this.predictAddtiveSpace.getUtility(bidList.get(disagreeIndex));
return ret;
}
/**
* When this function is called, it is expected that the Party chooses one of the actions from the possible
* action list and returns an instance of the chosen action.
*
* @param list
* @return
*/
@Override
public Action chooseAction(List<Class<? extends Action>> list) {
double time = getTimeLine().getTime();
if (lastReceivedOffer!=null) {
if (time < 0.3) {
if (predictAddtiveSpace.getUtility(lastReceivedOffer) > concessionValue ||
predictAddtiveSpace.getUtility(lastReceivedOffer) > 0.88) {
return new Accept(getPartyId(), lastReceivedOffer);
}
} else if (time < 0.5) {
if (predictAddtiveSpace.getUtility(lastReceivedOffer) > concessionValue ||
predictAddtiveSpace.getUtility(lastReceivedOffer) > 0.87) {
return new Accept(getPartyId(), lastReceivedOffer);
}
} else if (time < 0.7){
if (predictAddtiveSpace.getUtility(lastReceivedOffer) > concessionValue ||
predictAddtiveSpace.getUtility(lastReceivedOffer) > 0.85) {
return new Accept(getPartyId(), lastReceivedOffer);
}
} else if (time < 0.8) {
if (predictAddtiveSpace.getUtility(lastReceivedOffer) > concessionValue ||
predictAddtiveSpace.getUtility(lastReceivedOffer) > 0.83) {
return new Accept(getPartyId(), lastReceivedOffer);
}
} else if (time < 0.85) {
if (predictAddtiveSpace.getUtility(lastReceivedOffer) > concessionValue ||
predictAddtiveSpace.getUtility(lastReceivedOffer) > 0.8) {
return new Accept(getPartyId(), lastReceivedOffer);
}
} else if (time < 0.9) {
if (predictAddtiveSpace.getUtility(lastReceivedOffer) > concessionValue ||
predictAddtiveSpace.getUtility(lastReceivedOffer) > 0.7) {
return new Accept(getPartyId(), lastReceivedOffer);
}
} else if (time < 0.93) {
if (predictAddtiveSpace.getUtility(lastReceivedOffer) > concessionValue ||
predictAddtiveSpace.getUtility(lastReceivedOffer) > iaMap.JBpredict(lastReceivedOffer)) {
return new Accept(getPartyId(), lastReceivedOffer);
}
} else if (time < 0.98) {
if (predictAddtiveSpace.getUtility(lastReceivedOffer) > concessionValue ||
predictAddtiveSpace.getUtility(lastReceivedOffer) > iaMap.JBpredict(lastReceivedOffer)) {
return new Accept(getPartyId(), lastReceivedOffer);
}
} else {
return new Accept(getPartyId(), lastReceivedOffer);
}
}
return new Offer(getPartyId(), generateRandomBidAboveTarget());
}
/**
* This method is called to inform the party that another NegotiationParty chose an Action.
* @param sender
* @param action
*/
@Override
public void receiveMessage(AgentID sender, Action action) {
if (action instanceof Offer) {
lastReceivedOffer = ((Offer) action).getBid();
iaMap.JonnyBlack(lastReceivedOffer);
}
}
/**
* A human-readable description for this party.
* @return
*/
@Override
public String getDescription() {
return description;
}
private Bid getMaxUtilityBid() {
try {
return this.utilitySpace.getMaxUtilityBid();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private Bid generateRandomBidAboveTarget() {
long numberofPossibleBids = this.getDomain().getNumberOfPossibleBids();
double time = getTimeLine().getTime();
Bid randomBid;
double util;
double opponentUtility;
List<Bid> randomBidList = new ArrayList<>();
List<Double> utilList = new ArrayList<>();
List<Double> opponentUtiList = new ArrayList<>();
if(time < 0.5) {
return maxBidForme;
} else if (time < 0.4){
for (int k = 0; k < 2*numberofPossibleBids; k ++) {
randomBid = generateRandomBid();
util = predictAddtiveSpace.getUtility(randomBid);
if (util > concessionValue - 0.1 && util < concessionValue + 0.05) {
utilList.add(util);
opponentUtiList.add(iaMap.JBpredict(randomBid));
randomBidList.add(randomBid);
}
}
// If we can not find a suitable one, just generate the max one
if (utilList.size() == 0) {
for (int t = 0; t < 2*numberofPossibleBids; t ++) {
randomBid = generateRandomBid();
randomBidList.add(randomBid);
utilList.add(predictAddtiveSpace.getUtility(randomBid));
}
}
double maxUtility = Collections.max(utilList);
int indexRandBid = utilList.indexOf(maxUtility);
Bid suitableBid = randomBidList.get(indexRandBid);
return suitableBid;
} else {
for (int k = 0; k < 3 * numberofPossibleBids; k++) {
randomBid = generateRandomBid();
util = predictAddtiveSpace.getUtility(randomBid);
if (util > concessionValue - 0.05 && util < concessionValue + 0.05) {
utilList.add(util);
opponentUtiList.add(iaMap.JBpredict(randomBid));
randomBidList.add(randomBid);
}
}
// If we can not find a suitable one, just generate the max one
if (utilList.size() == 0) {
for (int t = 0; t < 2 * numberofPossibleBids; t++) {
randomBid = generateRandomBid();
randomBidList.add(randomBid);
utilList.add(predictAddtiveSpace.getUtility(randomBid));
}
}
double maxUtility = Collections.max(utilList);
int indexRandBid = utilList.indexOf(maxUtility);
Bid suitableBid = randomBidList.get(indexRandBid);
return suitableBid;
}
}
} |
package com.crmiguez.aixinainventory.apirest;
import com.crmiguez.aixinainventory.entities.Employee;
import com.crmiguez.aixinainventory.exception.ResourceNotFoundException;
import com.crmiguez.aixinainventory.service.employee.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
//@RequestMapping("/api_aixina/v1")
@RequestMapping("/api_aixina/v1/employeemanage")
@CrossOrigin(origins = "*", methods= {RequestMethod.GET,RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
public class EmployeeController {
@Autowired
@Qualifier("employeeService")
private IEmployeeService employeeService;
@PreAuthorize("hasAuthority('PERM_READ_ALL_EMPLOYEES')")
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeService.findAllEmployees();
}
@PreAuthorize("hasAuthority('PERM_READ_EMPLOYEE')")
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(
@PathVariable(value = "id") Long employeeId) throws ResourceNotFoundException {
Employee employee = employeeService.findEmployeeById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found on :: "+ employeeId));
return ResponseEntity.ok().body(employee);
}
@PreAuthorize("hasAuthority('PERM_CREATE_EMPLOYEE')")
@PostMapping("/employee")
public Employee createEmployee(@Valid @RequestBody Employee employee) { return employeeService.addEmployee(employee); }
@PreAuthorize("hasAuthority('PERM_UPDATE_EMPLOYEE')")
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(
@PathVariable(value = "id") Long employeeId,
@Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
Employee employee = employeeService.findEmployeeById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found on :: "+ employeeId));
final Employee updatedEmployee = employeeService.updateEmployee(employeeDetails, employee);
if (updatedEmployee == null){
return new ResponseEntity<Employee>(HttpStatus.EXPECTATION_FAILED);
} else {
return ResponseEntity.ok(updatedEmployee);
}
}
@PreAuthorize("hasAuthority('PERM_DELETE_EMPLOYEE')")
@DeleteMapping("/employee/{id}")
public Map<String, Boolean> deleteEmployee(
@PathVariable(value = "id") Long employeeId) throws Exception {
Employee employee = employeeService.findEmployeeById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found on :: "+ employeeId));
employeeService.deleteEmployee(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
|
package com.capgemini.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.capgemini.entity.User;
@Repository("userRepository")
public interface UserRepository extends JpaRepository<User, Integer> {
@Query(value = "Select u from User u Where u.username =:username AND u.userPassword =:userPassword ")
public User readByUsernameAndpassword(@Param("username") String name, @Param("userPassword") String Password);
User findByUsername(String username);
}
|
package co.sblock.commands.admin;
import org.bukkit.command.CommandSender;
import co.sblock.Sblock;
import co.sblock.commands.SblockCommand;
import co.sblock.module.Module;
/**
* SblockCommand for reloading configurations.
*
* @author Jikoo
*/
public class ConfigReloadCommand extends SblockCommand {
public ConfigReloadCommand(Sblock plugin) {
super(plugin, "sreload");
this.setDescription("Reload a configuration.");
this.setPermissionLevel("horrorterror");
this.setUsage("/sreload [module class]");
}
@Override
protected boolean onCommand(CommandSender sender, String label, String[] args) {
if (args.length < 1) {
getPlugin().reloadConfig();
sender.sendMessage("Reloaded main configuration.");
return true;
}
if (args[0].equalsIgnoreCase("rpack")) {
((Sblock) getPlugin()).reloadResourceHashes();
sender.sendMessage("Reloaded resource pack hashes.");
return true;
}
try {
Class<?> clazz = Class.forName(args[0]);
if (Module.class.isAssignableFrom(clazz)) {
((Module) ((Sblock) getPlugin()).getModule(clazz)).loadConfig();
sender.sendMessage("Reloaded module configuration.");
return true;
}
sender.sendMessage("Specified class is not assignable from Module.");
return true;
} catch (ClassNotFoundException e) {
sender.sendMessage("Specified string is not a full class name. Package is required.");
return false;
}
}
}
|
package artronics.gsdwn.packet;
import artronics.gsdwn.log.Log;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@Table(name = "packets")
public class SdwnBasePacket implements Packet
{
private static long sequence = 0;
protected List<Integer> content;
protected Integer srcShortAddress;
protected Integer dstShortAddress;
protected Integer netId;
protected Integer ttl;
protected Integer nextHop;
private Long id;
private Timestamp receivedAt;
private Long sessionId;
private String controllerIp;
/**
* Never call this constructor. It is for Jpa entity.
*/
public SdwnBasePacket()
{
}
public SdwnBasePacket(List<Integer> content)
{
this.content = content;
this.srcShortAddress = SdwnPacketHelper.getSourceAddress(content);
this.dstShortAddress = SdwnPacketHelper.getDestinationAddress(content);
this.netId = content.get(SdwnPacket.ByteMeaning.NET_ID.getValue());
this.ttl = content.get(SdwnPacket.ByteMeaning.TTL.getValue());
this.nextHop = SdwnPacketHelper.joinAddresses(
content.get(SdwnPacket.ByteMeaning.NEXT_HOP_H.getValue()),
content.get(SdwnPacket.ByteMeaning.NEXT_HOP_L.getValue())
);
sequence++;
this.receivedAt = new Timestamp(new Date().getTime());
Log.PACKET.debug(toString());
}
@Column(name = "sequence", nullable = false)
public static Long getSequence()
{
return sequence;
}
public static void setSequence(Long sequence)
{
SdwnBasePacket.sequence = sequence;
}
@Id
@GeneratedValue
@Column(nullable = false, unique = true)
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
@Column(name = "controller_ip", nullable = false)
public String getControllerIp()
{
return controllerIp;
}
public void setControllerIp(String controllerIp)
{
this.controllerIp = controllerIp;
}
@Column(name = "session_id", nullable = false)
public Long getSessionId()
{
return sessionId;
}
public void setSessionId(Long session_id)
{
this.sessionId = session_id;
}
@Override
@Column(name = "src_short_add")
public Integer getSrcShortAddress()
{
return srcShortAddress;
}
@Column(name = "dst_short_add")
public Integer getDstShortAddress()
{
return dstShortAddress;
}
@Override
@ElementCollection
// @CollectionType(type = "java.util.ArrayList")
@CollectionTable(name = "packet_content", joinColumns = @JoinColumn(name = "id"))
@Column(name = "content")
public List<Integer> getContent()
{
return content;
}
public void setContent(List<Integer> content)
{
this.content = content;
}
public void setSrcShortAddress(Integer srcShortAddress)
{
this.srcShortAddress = srcShortAddress;
}
public void setDstShortAddress(Integer dstShortAddress)
{
this.dstShortAddress = dstShortAddress;
}
@Column(name = "received_at", nullable = false)
public Timestamp getReceivedAt()
{
return receivedAt;
}
public void setReceivedAt(Timestamp receivedAt)
{
this.receivedAt = receivedAt;
}
@Column(name = "net_id")
public Integer getNetId()
{
return netId;
}
public void setNetId(Integer netId)
{
this.netId = netId;
}
@Column(name = "ttl")
public Integer getTtl()
{
return ttl;
}
public void setTtl(Integer ttl)
{
this.ttl = ttl;
}
@Column(name = "next_hop")
public Integer getNextHop()
{
return nextHop;
}
public void setNextHop(Integer nextHop)
{
this.nextHop = nextHop;
}
@Override
@Transient
public SdwnPacketType getType()
{
return SdwnPacketHelper.getType(content);
}
@Override
public String toString()
{
String s = "";
s += String.format("%-6s", getType().toString());
s += printContent(getContent());
return s;
}
private String printContent(List<Integer> content)
{
String s = "";
for (Integer i : content) {
s += String.format("%-3d", i);
s += " ,";
}
return s;
}
}
|
package com.zhong.baidumusicplay;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.zhong.baidumusicplay.adapter.BaseAdapter;
import com.zhong.baidumusicplay.fragment.first;
import com.zhong.baidumusicplay.fragment.fourth;
import com.zhong.baidumusicplay.fragment.second;
import com.zhong.baidumusicplay.fragment.third;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
private static final String[] titleArray = new String[]{"个性推荐", "歌单", "主播电台", "排行榜"};
private int increateY;
private TextView mTextView_indicator;
private RadioGroup mRadioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.main_view_pager);
mRadioGroup = (RadioGroup) findViewById(R.id.ViewPager_item);
mTextView_indicator = (TextView) findViewById(R.id.indicator_line);
List<Fragment> setPicture = new ArrayList<>();
setPicture.add(new first());
setPicture.add(new second());
setPicture.add(new third());
setPicture.add(new fourth());
FragmentManager manager = getSupportFragmentManager();
BaseAdapter adapter = new BaseAdapter(manager, setPicture);
pager.setAdapter(adapter);
LayoutInflater inflater = LayoutInflater.from(this);
for (int i = 0; i < setPicture.size(); i++) {
RadioButton view = ((RadioButton) inflater.inflate(R.layout.viewpager_indicator, mRadioGroup, false));
view.setId(i);
view.setText(titleArray[i]);
mRadioGroup.addView(view);
}
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
increateY = width / 4;
mTextView_indicator.setWidth(increateY);
pager.setOnPageChangeListener(this);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
RadioButton childAt = ((RadioButton) mRadioGroup.getChildAt(position));
float x = ViewCompat.getX(childAt);
x = x + (childAt.getWidth() * positionOffset);
ViewCompat.setX(mTextView_indicator, x);
childAt.setTextColor(0xffec2626);
int count = mRadioGroup.getChildCount();
for (int i = 0; i < count; i++) {
if (i != position) {
RadioButton otherButton = (RadioButton) mRadioGroup.getChildAt(i);
otherButton.setTextColor(0xff4e4c4c);
}
}
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
|
/*
* Copyright (c) 2020. The Kathra Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* IRT SystemX (https://www.kathra.org/)
*
*/
package org.kathra.resourcemanager.keypair.dao;
import org.kathra.core.model.KeyPair;
import org.kathra.resourcemanager.resource.dao.ResourceDbMapper;
import fr.xebia.extras.selma.Field;
import fr.xebia.extras.selma.Mapper;
import fr.xebia.extras.selma.IgnoreMissing;
@Mapper(
withCyclicMapping = true,
withIgnoreMissing = IgnoreMissing.ALL,
withCustomFields = {
@Field( value = "createdAt", withCustom = ResourceDbMapper.CustomCreatedAt.class),
@Field( value = "updatedAt", withCustom = ResourceDbMapper.CustomUpdatedAt.class),
@Field( value = "metadata", withCustom = ResourceDbMapper.CustomMetadata.class)
})
public interface KeyPairMapper extends ResourceDbMapper {
KeyPairDb asKeyPairDb(KeyPair in);
KeyPair asKeyPair(KeyPairDb in);
}
|
package com.robin.springbootlearn.common.pojo;
import com.robin.springbootlearn.common.enums.RequestOptTypeEnum;
import java.io.Serializable;
import java.util.Date;
/**
* @author robin
* @version v0.0.1
* @depiction 用户操作日志
* @create 2019-11-28 0:04
**/
public class OptLogDTO implements Serializable {
/**
* 记录 id
*/
private Long id;
/**
* 操作类型
*/
private RequestOptTypeEnum optType;
/**
* 操作名
*/
private String optName;
/**
* 模块名
*/
private String moduleName;
/**
* 用户ID
*/
private String userId;
/**
* 用户名
*/
private String userName;
/**
* 明细
*/
private String detail;
/**
* 操作结果 true 成功、false 失败
*/
private Boolean result;
/**
* 操作时间
*/
private Date createDate;
}
|
package ru.ifmo.diploma.synchronizer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.ifmo.diploma.synchronizer.discovery.CurrentConnections;
import ru.ifmo.diploma.synchronizer.discovery.Discovery;
import ru.ifmo.diploma.synchronizer.exchange.TWriter;
import ru.ifmo.diploma.synchronizer.exchange.Worker;
import ru.ifmo.diploma.synchronizer.listeners.CopyFileListener;
import ru.ifmo.diploma.synchronizer.listeners.DeleteFileListener;
import ru.ifmo.diploma.synchronizer.listeners.FileListener;
import ru.ifmo.diploma.synchronizer.listeners.Listener;
import ru.ifmo.diploma.synchronizer.listeners.RenameFileListener;
import ru.ifmo.diploma.synchronizer.listeners.ResultListener;
import ru.ifmo.diploma.synchronizer.listeners.SendFileRequestListener;
import ru.ifmo.diploma.synchronizer.listeners.ListFilesListener;
import ru.ifmo.diploma.synchronizer.listeners.SendListFilesCommandListener;
import ru.ifmo.diploma.synchronizer.listeners.TransferFileListener;
import ru.ifmo.diploma.synchronizer.messages.AbstractMsg;
import ru.ifmo.diploma.synchronizer.protocol.handshake.Credentials;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Created by ksenia on 20.05.2017.
*/
public class Synchronizer extends Thread {
private static final Logger LOG = LogManager.getLogger(Synchronizer.class);
private Map<String, Credentials> authorizationTable;
private String startPath;
private String localIP;
private int localPort;
private List<FileInfo> filesInfo = new ArrayList<>();
private BlockingQueue<AbstractMsg> readerTasks = new LinkedBlockingQueue<>();
private BlockingQueue<AbstractMsg> writerTasks = new LinkedBlockingQueue<>();
private List<Listener<AbstractMsg>> listeners = new ArrayList<>();
private Map<String, CurrentConnections> connections = new ConcurrentHashMap<>();
private String localAddr;
private DirectoriesComparison dc;
private List<Thread> threadList = new ArrayList<>();
private Discovery discovery;
private BlockingQueue<FileOperation> fileOperations = new LinkedBlockingQueue<>();
private Thread viewer;
private String localLogin;
private String localPassword;
public Synchronizer(String localIP, int localPort, Map<String, Credentials> authorizationTable, String startPath,
String localLogin, String localPassword) {
localAddr = localIP + ":" + localPort;
this.localPort = localPort;
this.authorizationTable = authorizationTable;
this.startPath = startPath;
this.localLogin = localLogin;
this.localPassword = localPassword;
}
public String getLocalAddr() {
return localAddr;
}
public Map<String, CurrentConnections> getConnections() {
return connections;
}
public BlockingQueue<FileOperation> getFileOperations() {
return fileOperations;
}
public int getLocalPort() {
return localPort;
}
public Map<String, Credentials> getAuthorizationTable() {
return authorizationTable;
}
public String getStartPath() {
return startPath;
}
public List<FileInfo> getFilesInfo() {
return filesInfo;
}
public BlockingQueue<AbstractMsg> getReaderTasks() {
return readerTasks;
}
public BlockingQueue<AbstractMsg> getWriterTasks() {
return writerTasks;
}
public DirectoriesComparison getDc() {
return dc;
}
public List<Thread> getThreadList() {
return threadList;
}
public ServerSocket getServerSocket() {
return discovery.getServerSocket();
}
public Thread getViewer() {
return viewer;
}
private void addListeners() {
listeners.add(new CopyFileListener(localAddr, writerTasks, dc, fileOperations));
listeners.add(new DeleteFileListener(localAddr, writerTasks, dc, fileOperations));
listeners.add(new FileListener(localAddr, writerTasks, dc, fileOperations));
listeners.add(new ListFilesListener(localAddr, writerTasks, dc));
listeners.add(new RenameFileListener(localAddr, writerTasks, dc, fileOperations));
listeners.add(new ResultListener(localAddr, writerTasks, dc));
listeners.add(new SendFileRequestListener(localAddr, writerTasks, dc));
listeners.add(new SendListFilesCommandListener(localAddr, writerTasks, dc));
listeners.add(new TransferFileListener(localAddr, writerTasks, dc, fileOperations));
}
public void startSynchronizer() {
threadList.add(this);
dc = new DirectoriesComparison(startPath, localAddr, writerTasks);
new Exit(this).start();
//поток для отслеживания изменения директории в режиме реального времени
try {
viewer = new Thread(new DirectoryChangesViewer(Paths.get(startPath), localAddr, fileOperations, writerTasks, threadList));
viewer.start();
} catch (IOException e) {
//
}
addListeners();
Thread worker = new Worker(this, readerTasks, listeners);
worker.start(); //поток-обработчик входящих сообщений
threadList.add(worker);
Thread tWriter = new TWriter(this, writerTasks);
tWriter.start(); //поток для отправки сообщений (в т.ч. broadcast)
threadList.add(tWriter);
discovery = new Discovery(this, localLogin, localPassword);
discovery.startDiscovery();
}
public static void main(String[] args) {
String startPath = null;
Properties properties = new Properties();
Map<String, Credentials> authorizationTable = new HashMap<>();
int localPort;
String localLogin;
String localPassword;
String localIP = null;
try {
FileInputStream fileIn = new FileInputStream("routes.properties");
properties.load(fileIn);
if (args == null || args.length == 0) {
startPath = properties.getProperty("pc_0.startPath");
} else {
startPath = args[0];
}
if (startPath == null) {
System.out.println("Please, specify the path of directory need to be synchronized");
System.out.println("Use 'java -jar synchronizer.jar startpath' or specify it in file 'routes.properties'");
return;
}
// startPath = startPath.replaceAll("\\\\", "/").trim();
String lastChar = startPath.substring(startPath.length() - 1, startPath.length());
if (lastChar.equals("\\") || lastChar.equals("/")) {
startPath = startPath.substring(0, startPath.length() - 1); //удаляем последний сепаратор, если он есть
}
String[] addresses = properties.getProperty("address").split(";");
String[] logins = properties.getProperty("login").split(";");
String[] passwords = properties.getProperty("password").split(";");
localPort = Integer.parseInt(properties.getProperty("pc_0.localPort"));
localLogin = properties.getProperty("pc_0.login");
localPassword = properties.getProperty("pc_0.password");
localIP = properties.getProperty("pc_0.localIP");
for (int i = 0; i < addresses.length; i++) {
authorizationTable.put(addresses[i], new Credentials("", logins[i], passwords[i]));
}
} catch (FileNotFoundException e) {
System.out.println("File 'routes.properties' not found in current directory");
return;
} catch (IOException e) {
System.out.println("Can't load properties from file 'routes.properties'");
return;
}
if (localIP == null || localIP.isEmpty()) {
try {
localIP = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
LOG.error("Synchronizer can't identify local IP");
}
}
LOG.debug("Local IP: " + localIP);
new Synchronizer(localIP, localPort, authorizationTable, startPath, localLogin, localPassword).startSynchronizer();
}
}
|
package com.example.welcome.myregistration;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class RegistrationActivity extends AppCompatActivity{
EditText mname;
EditText mphoneNumber;
EditText memail;
EditText mpassword;
Button mregister;
Button mnext;
Button login;
public static final String MyPREFERENCES="MyPreferences";
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
mname = (EditText)findViewById(R.id.etName);
mphoneNumber = (EditText)findViewById(R.id.etPhone);
memail = (EditText)findViewById(R.id.etEmail);
mpassword = (EditText)findViewById(R.id.etPassword);
mregister = (Button)findViewById(R.id.etRegister);
mnext = (Button)findViewById(R.id.etNext);
login = (Button)findViewById(R.id.etlogin);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
mregister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = mname.getText().toString();
String ph = mphoneNumber.getText().toString();
String e = memail.getText().toString();
String pas = mpassword.getText().toString();
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("Name", n);
editor.putString("PhoneNumber", ph);
editor.putString("Email", e);
editor.putString("Password", pas);
editor.commit();
Toast.makeText(RegistrationActivity.this, "Thanks", Toast.LENGTH_LONG).show();
}
});
mnext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RegistrationActivity.this, NextActivity.class);
startActivity(intent);
}
});
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in = new Intent(RegistrationActivity.this, LoginActivity.class);
startActivity(in);
}
});
}
}
|
package cloudninegui;
import filterpictures.ExtractPictureMetaData;
import javafx.application.HostServices;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseEvent;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class FileBrowserDialogController implements Initializable {
@FXML
private Label label;
@FXML
private ListView directoriesList = new ListView();
@FXML
private CheckBox removeChecked = new CheckBox();
@FXML
private Button closeButton;
FileChooser fileChooser = new FileChooser();
DirectoryChooser directoryChooser = new DirectoryChooser();
ObservableList dataDirectories =
FXCollections.observableArrayList();
Favorites favorites = new Favorites();
String myFavoriteDirectories = "/Users/Shared/favoriteDirectoriesFile";
public String getMyFavoriteDirectories() {
return myFavoriteDirectories;
}
public void setMyFavoriteDirectories(String myFavoriteDirectories) {
this.myFavoriteDirectories = myFavoriteDirectories;
}
@FXML
private void handleButtonDirectoryChooserAction(ActionEvent event) {
System.out.println("Directory Chooser activated");
// label.setText("Directory Chooser");
configuringFileChooser(fileChooser);
configuringDirectoryChooser(directoryChooser);
File choosedDirectory = directoryChooser.showDialog(new Stage());
String myChoosenDirectory = choosedDirectory.toPath().toString();
System.out.println("choosedDirectory: " + myChoosenDirectory);
dataDirectories.addAll(myChoosenDirectory);
favorites.addDirectory(myChoosenDirectory);
favorites.writeFavoriteDirectoriesToFile(myFavoriteDirectories);
//System.out.println("choosen directory: " + directoryChooser.showDialog(new Stage()));
directoriesList.setItems(dataDirectories);
String csvFile = myChoosenDirectory + "/MyLightroom.csv";
ExtractPictureMetaData extractPictureMetaData;
extractPictureMetaData = new ExtractPictureMetaData(myChoosenDirectory, csvFile);
try {
extractPictureMetaData.createCSVFileWalker(myChoosenDirectory, csvFile);
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
private void handleClose(){
System.out.println("Cancelled clicked");
Stage stage = (Stage) closeButton.getScene().getWindow();
stage.close();
}
@FXML
private void handleDirectoriesListAction(MouseEvent event) {
String myDirectory = directoriesList.getSelectionModel().getSelectedItem().toString();
System.out.println("clicked on " + myDirectory);
if (removeChecked.isSelected() == true) {
System.out.println("Remove file from Directory");
favorites.removeDirectory(myDirectory);
favorites.writeFavoriteDirectoriesToFile(myFavoriteDirectories);
dataDirectories.remove(myDirectory);
directoriesList.setItems(dataDirectories);
} else {
fileChooser.setTitle("Select file to open");
fileChooser.setInitialDirectory(new File(myDirectory));
File choosedFile = fileChooser.showOpenDialog(new Stage());
System.out.println("choosedFile: " + choosedFile);
if (choosedFile != null) {
// TODO https://stackoverflow.com/questions/33094981/javafx-8-open-a-link-in-a-browser-without-reference-to-application
// HostServices hs = new HostServices();
// hs.showDocument(choosedFile.toURI().toString());
System.out.println("before showDocument: " + choosedFile.toString());
try {
this.getHostServices().showDocument(choosedFile.toURI().toURL().toExternalForm());
} catch (Exception e) {
System.out.println("Exception: " + e);
}
System.out.println("after showDocument: " + choosedFile.toString());
}
}
}
private void configuringFileChooser(FileChooser fileChooser) {
// Set title for FileChooser
fileChooser.setTitle("Select Some Files");
// Set Initial Directory
fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
}
private void configuringDirectoryChooser(DirectoryChooser directoryChooser) {
// Set title for FileChooser
directoryChooser.setTitle("Select Directory");
// Set Initial Directory
directoryChooser.setInitialDirectory(new File(System.getProperty("user.home")));
}
private HostServices hostServices;
public HostServices getHostServices() {
return hostServices;
}
public void setHostServices(HostServices hostServices) {
this.hostServices = hostServices;
}
@Override
public void initialize(URL url, ResourceBundle rb) {
dataDirectories.clear();
favorites.setDirectoriesFromFile(myFavoriteDirectories);
dataDirectories.addAll(favorites.getDirectories());
directoriesList.setItems(dataDirectories);
}
}
|
package com.baiwang.custom.web.service;
import java.util.List;
import java.util.Map;
import com.baiwang.custom.common.model.MGQueryInvModel;
import com.baiwang.custom.common.model.QueryInvModel;
import com.baiwang.custom.common.model.QueryInvRequest;
import com.baiwang.custom.common.model.QueryInvRequestModel;
import com.baiwang.platform.custom.common.result.CrRpcResult;
import com.github.pagehelper.PageInfo;
public interface MGInvoiceCheckService {
//分页查询已入库发票
PageInfo<MGQueryInvModel> getQueryInvModelListPage(QueryInvRequestModel queryInvRequestModel, int pageNum, int pageSize);
//分页查询已入库发票全票面信息 20180910版新增
PageInfo<MGQueryInvModel> getQueryInvModelFullListPage(QueryInvRequestModel queryInvRequestModel, int pageNum, int pageSize);
//格式化返回列表(已入库)(Excel)
List<Map<String,Object>> getFormartVatList(List<MGQueryInvModel> results);
//根据id获取发票主表实体
} |
package prosjektoppgave.gui;
import prosjektoppgave.controller.Controller;
import prosjektoppgave.models.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TreeSet;
/**
* A panel for managing persons.
*/
public class PersonListContainerPanel extends JPanel{
private JButton showAll, savePerson, createNew, editPerson, showSelectedPerson, back, deletePerson;
private JButton[] showListButtons, showPersonButtons, editPersonButtons;
private static enum State {SHOW_LIST, SHOW_PERSON, EDIT_PERSON}
private PersonListPanel personListPanel;
private PersonContainerPanel personContainerPanel;
private Controller controller;
private Person selectedPerson;
public PersonListContainerPanel(Controller controller) {
this.controller = controller;
personListPanel = new PersonListPanel(new TreeSet<>(controller.getPersons()));
showAll = new JButton("Vis alle personer");
savePerson = new JButton("Lagre person");
createNew = new JButton("Opprett ny person");
editPerson = new JButton("Rediger");
showSelectedPerson = new JButton("Vis valgt person");
back = new JButton("Gå tilbake uten å lagre");
deletePerson = new JButton("Slett person");
showListButtons = new JButton[] {createNew, showSelectedPerson};
showPersonButtons = new JButton[] {back, editPerson, deletePerson};
editPersonButtons = new JButton[] {back, savePerson, deletePerson};
Listener listener = new Listener();
showAll.addActionListener(listener);
savePerson.addActionListener(listener);
createNew.addActionListener(listener);
showSelectedPerson.addActionListener(listener);
editPerson.addActionListener(listener);
back.addActionListener(listener);
deletePerson.addActionListener(listener);
setLayout(new BorderLayout());
setToState(State.SHOW_LIST);
revalidate();
repaint();
}
/**
* Sets the view to show the panels and buttons specified by the state-parameter.
* @param state the enum representing the new state for the panel
*/
public void setToState(State state){
removeAll();
ButtonPanel activeButtons;
JPanel activePanel;
switch (state){
case SHOW_LIST:
ButtonPanel showListButtonPanel = new ButtonPanel(showListButtons);
activeButtons = showListButtonPanel;
activePanel = personListPanel;
break;
case SHOW_PERSON:
ButtonPanel showPersonButtonPanel = new ButtonPanel(showPersonButtons);
activeButtons = showPersonButtonPanel;
activePanel = personContainerPanel;
break;
case EDIT_PERSON:
ButtonPanel editPersonButtonPanel = new ButtonPanel(editPersonButtons);
activeButtons = editPersonButtonPanel;
activePanel = personContainerPanel;
break;
default: throw new IllegalArgumentException(state.toString());
}
add(activeButtons,BorderLayout.PAGE_START);
add(activePanel, BorderLayout.CENTER);
revalidate();
repaint();
}
/**
* Adds the selected person-object to the controller.
*/
public void savePerson(){
try{
if(selectedPerson == null){
Person person = personContainerPanel.create();
controller.add(person);
}
else{
personContainerPanel.update();
}
personListPanel = new PersonListPanel(controller.getPersons());
setToState(State.SHOW_LIST);
}
catch (IllegalArgumentException i){
JOptionPane.showMessageDialog(this, InvalidUserInputException.describe(i), "Feil", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Gets the selected person from the personListPanel, and creates a new PersonContainerPanel to show it.
*/
public void showSelectedPerson(){
selectedPerson = personListPanel.getSelectedPerson();
personContainerPanel = new PersonContainerPanel(selectedPerson);
personContainerPanel.setEditable(false);
setToState(State.SHOW_PERSON);
}
/**
* Eneables the user to edit the input-fields of the visible panel.
* Should only be called when state is set to show an existing person.
*/
public void editPerson(){
personContainerPanel.setEditable(true);
setToState(State.EDIT_PERSON);
revalidate();
repaint();
}
/**
* Checks if the selected person is a landlord that has housings registered.
* If not, the selected person is deleted after prompting the user with a confirmation message.
* Should only be called state is set to show an existing person.
*/
public void deletePerson(){
if(selectedPerson instanceof Landlord){
if(!((Landlord) selectedPerson).getHousings().isEmpty()){
JOptionPane.showMessageDialog(this, "Denne personen er en utleier som fortsatt har boliger knyttet til seg, og kan derfor ikke slettes.");
return;
}
}
int option = JOptionPane.showConfirmDialog(this, "Er du sikker på at du vil slette denne personen?", "Slett person", JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.NO_OPTION){
return;
}
controller.remove(selectedPerson);
selectedPerson = null;
personListPanel = new PersonListPanel(controller.getPersons());
setToState(State.SHOW_LIST);
}
private class Listener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource() == showAll){
personListPanel = new PersonListPanel(controller.getPersons());
setToState(State.SHOW_LIST);
}else if(e.getSource() == createNew){
selectedPerson = null;
personContainerPanel = new PersonContainerPanel();
setToState(State.EDIT_PERSON);
}else if(e.getSource() == savePerson){
savePerson();
}else if(e.getSource() == showSelectedPerson){
showSelectedPerson();
}else if(e.getSource() == back){
setToState(State.SHOW_LIST);
}else if(e.getSource() == editPerson){
editPerson();
}else if(e.getSource() == deletePerson){
deletePerson();
}
}
}
}
|
package com.stk123.common.printobj;
import java.beans.PropertyDescriptor;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.Vector;
public class ObjectPrint {
public static String outputFile = "d:/log/bean_" + System.currentTimeMillis() + ".txt";
public static PrintWriter pw = null;
static {
try {
// 准备输出文件
// pw = new PrintWriter(outputFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void println(String s) {
System.out.println(s);
// pw.println(s);
}
public static void main(String[] args) {
// TreeNode node = new TreeNode();
// node.setName("dddd");
// TreeNode node1 = new TreeNode();
// node1.setName("xxxxxxx");
// node1.setParent(node1);
// node.getChildren().add(node1);
// ObjectPrint.dump(node,null);
}
/**
* 调试, 打印出给定 Bean 的所有属性的取值.
*
* @param bean
* @param proArray
* 需要打印的对象
*/
public static void dump(Object bean, String[] proArray) {
if (bean instanceof Collection) {
@SuppressWarnings("unchecked")
Collection<Object> collection = (Collection<Object>) bean;
println("print Collection begein!");
for (Object o : collection) {
dump(o, proArray);
}
println("print Collection end!");
} else if (bean instanceof Map) {
println("print Map begein!");
@SuppressWarnings("unchecked")
Map<Object, Object> map = (Map<Object, Object>) bean;
for (Object o : map.keySet()) {
Object value = map.get(o);
if (isImmutableObjects(value)) {
println("[" + o.toString() + "]=" + value.toString());
} else {
println("[" + o.toString() + "] begin");
dump(value, proArray);
println("[" + o.toString() + "] end!");
}
}
println("print Map end!");
} else {
if (isImmutableObjects(bean)) {
// 不可变类
println("[" + bean.getClass().getName() + "]="
+ bean.toString());
} else {
printObject(bean, proArray);
}
}
}
/**
* 判断是否是不可变类
*
* @param bean
* @return
*/
private static boolean isImmutableObjects(Object bean) {
if (bean instanceof Integer || bean instanceof Long
|| bean instanceof String || bean instanceof Short
|| bean instanceof Boolean || bean instanceof Byte
|| bean instanceof Character || bean instanceof Double
|| bean instanceof Float || bean instanceof Number) {
return true;
}
return false;
}
/**
* 从 bean 中读取有效的属性描述符. NOTE: 名称为 class 的 PropertyDescriptor 被排除在外.
*
* @param bean Object - 需要读取的 Bean
* @return PropertyDescriptor[] - 属性列表
*/
public static java.beans.PropertyDescriptor[] getAvailablePropertyDescriptors(
Object bean) {
try {
// 从 Bean 中解析属性信息并查找相关的 write 方法
java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean.getClass());
if (info != null) {
java.beans.PropertyDescriptor pd[] = info
.getPropertyDescriptors();
Vector<PropertyDescriptor> columns = new Vector<PropertyDescriptor>();
for (int i = 0; i < pd.length; i++) {
String fieldName = pd[i].getName();
if (fieldName != null && !fieldName.equals("class")) {
columns.add(pd[i]);
}
}
PropertyDescriptor[] arrays = new PropertyDescriptor[columns
.size()];
for (int j = 0; j < columns.size(); j++) {
arrays[j] = (PropertyDescriptor) columns.get(j);
}
return arrays;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
return null;
}
public static void dump(Object bean) {
dump(bean, null);
}
private static void printObject(Object bean, String[] proArray) {
PropertyDescriptor[] descriptors = getAvailablePropertyDescriptors(bean);
for (int i = 0; descriptors != null && i < descriptors.length; i++) {
Method readMethod = descriptors[i].getReadMethod();
try {
String proName = descriptors[i].getName();
if (proArray == null
|| (proArray != null && inArray(proName, proArray))) {
Object value = readMethod.invoke(bean, new Object[] {});
println("[" + bean.getClass().getName() + "]." + proName
+ "(" + descriptors[i].getPropertyType().getName()
+ ") = " + value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 判断proName是否在proArray里面
*
* @param proName
* @param proArray
* @return
*/
private static boolean inArray(String proName, String[] proArray) {
if (proArray == null)
return false;
boolean in = false;
for (String s : proArray) {
if (proName.equals(s)) {
in = true;
break;
}
}
return in;
}
}
|
package week06d02;
import java.util.ArrayList;
import java.util.List;
public class Store {
private List<Product> products;
public Store(List<Product> products) {
if (products == null) {
throw new IllegalArgumentException("Products can't be null");
}
this.products = products;
}
private StoredProduct getStoredProductByCategory(List<StoredProduct> products, ProductCategory productCategory) {
for (StoredProduct item : products) {
if (item.getCategory() == productCategory) {
return item;
}
}
return null;
}
public List<StoredProduct> getProductsByCategory() {
List<StoredProduct> productsByCategories = new ArrayList<>();
for (Product item : products) {
StoredProduct foundedProductCategory = getStoredProductByCategory(productsByCategories, item.getCategory());
if (foundedProductCategory == null) {
productsByCategories.add(new StoredProduct(item.getCategory(), 1));
} else {
foundedProductCategory.incrementCounts();
}
}
return productsByCategories;
}
}
|
package com.example.a.photogallery2_0;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.a.photogallery2_0.model.Photo;
import com.squareup.picasso.Picasso;
import java.util.List;
public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.ViewHolder> {
private final List<Photo> values;
private OnLongClickPhotoListener onLongClickPhotoListener;
public PhotoAdapter(List<Photo> items) {
values = items;
}
@Override
@NonNull
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Photo photo = values.get(position);
Picasso.get().load(photo.getUrlS()).into(holder.image);
holder.itemView.setTag(photo);
}
@Override
public int getItemCount() {
return values.size();
}
public void setOnLongClickPhotoListener(OnLongClickPhotoListener listener) {
this.onLongClickPhotoListener = listener;
}
public class ViewHolder extends RecyclerView.ViewHolder {
final ImageView image;
ViewHolder(View view) {
super(view);
image = view.findViewById(R.id.image);
image.setOnLongClickListener(v -> {
onLongClickPhotoListener.onLongClick(values.get(this.getAdapterPosition()));
return true;
});
}
}
}
|
package com.tide.demo09;
public class InterfaceDefaultB implements InterfaceDefault{
@Override
public void MethodAbs(){
System.out.println("BBB0");
}
@Override
public void MethodDefault(){
System.out.println("改写方法");
}
}
|
package pl.basistam.soa.parkometr;
import com.fasterxml.jackson.core.JsonProcessingException;
public class Main {
public static void main(String[] args) throws JsonProcessingException {
ParkingMeter parkingMeter = new ParkingMeter();
while(true) {
if (parkingMeter.buyTicket()) {
System.out.println("Bilet poprawny");
} else {
System.out.println("Nie udało się przeprowadzić transakcji. Sprawdź poprawność wprowadzonych danych.");
}
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modelo;
/**
*
* @author alex
*/
public class FinPartida {
private byte tipo;
private byte ganador;
private int puntos;
public FinPartida(byte tipo, byte ganador){
this.tipo=tipo;
this.ganador=ganador;
}
public FinPartida(byte tipo, byte ganador, int puntos){
this.tipo=tipo;
this.ganador=ganador;
this.puntos=puntos;
}
public byte get_tipo(){
return this.tipo;
}
public byte get_ganador(){
return this.ganador;
}
public int get_puntos(){
return this.puntos;
}
}
|
package controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
import dao.userDAO;
import model.UserDTO;
@WebServlet("/login")
public class LoginController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession hs = request.getSession();
String loginUser = (String) hs.getAttribute("loginUser");
if(loginUser != null) {//로그인을 한 경우
response.sendRedirect("/main");
return;
}
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/views/login.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String pw = request.getParameter("pw");
System.out.println("id : "+id);
System.out.println("pw : "+pw);
UserDTO param = new UserDTO();
param.setUserID(id);
param.setUserPW(pw);
int result = userDAO.dologin(param);
String msg = "로그인에 성공했습니다.";
String url = "/main";
switch(result) {
case 1:
HttpSession hs = request.getSession();
hs.setAttribute("loginUser", id);
break;
case -1:
msg = "아이디 또는 패스워드가 일치하지 않습니다.";
url = "/login";
break;
default:
msg = "데이터베이스 오류발생 관리자에게 문의해주세요.";
url = "login";
break;
}
request.setAttribute("url", url);
request.setAttribute("msg", msg);
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/views/common/commonMsg.jsp");
rd.forward(request, response);
}
}
|
package Service;
import Dao.model.CollectGoods;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml","file:src/main/webapp/WEB-INF/spring-mybatis.xml"})
public class CollectSearchResultServiceTest extends TestCase {
@Autowired
CollectGoodsService collectGoodsService;
@Test
public void testSaveCollectGoods() throws Exception {
System.out.println(collectGoodsService.saveCollectGoods(1,2));
}
@Test
public void testJudgeCollectGoods() throws Exception {
//System.out.println(collectGoodsService.judgeCollectGoods(1,3));
}
@Test
public void testShowCollection() throws Exception{
//collectGoodsService.showCollection(2);
}
@Test
public void testDeleteCollection() throws Exception{
//System.out.print(collectGoodsService.deleteCollection(3,1));
}
} |
package com.example.itemcatalogservice;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
class ItemInitializer implements CommandLineRunner {
@Autowired
private final ItemRepository itemRepository;
ItemInitializer(ItemRepository itemRepository) {
this.itemRepository = itemRepository;
}
@Override
public void run(String... args) throws Exception {
Stream.of("Pen", "Book", "Yoga", "Speaker", "Light", "Candel")
.forEach(beer -> itemRepository.save(new Item(beer)));
itemRepository.findAll().forEach(System.out::println);
}
} |
package com.stackroute;
import org.junit.Test;
import java.lang.String.*;
import static org.junit.Assert.*;
public class StringVowelTest {
@Test
public void stringChecker()
{
StringVowel check = new StringVowel();
String result =check.stringChecker("a");
assertEquals("vowel",result);
}
@Test
public void CheckTest1()
{
StringVowel check = new StringVowel();
String result =check.stringChecker("@");
assertEquals("consonant",result);
}
}
|
package com.hr.schedule.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.hr.login.model.LoginModel;
import com.hr.schedule.model.EmpBean;
import com.hr.schedule.model.FactSchedule;
import com.hr.schedule.service.ScheduleService;
@Controller
@SessionAttributes("loginModel")
public class ScheduleController {
@Autowired
private ScheduleService service;
//去我的班表頁面
@GetMapping(value="/schedule/MySchedule")
public String queryAllSchedule(Model model, @ModelAttribute("loginModel") LoginModel loginModel) {
// List<FactSchedule> schedule = service.findAllSchedule();
// model.addAttribute("allSchedule",schedule);
// return "schedule/MySchedule";
// <!-- 以下兩個是一組的 --!>
model.addAttribute("body", "schedule/MySchedule.jsp");
return "layout/Template";
}
//看全部班表
@GetMapping(value="/schedule/findAllScheduleAjax")
public @ResponseBody List<FactSchedule> findAllSchedule(){
return service.findAllSchedule();
}
// 看該部門班表
@GetMapping("/schedule/findScheduleByDeptNo")
public @ResponseBody List<FactSchedule> findScheduleByDeptNo(@RequestParam("deptNo") Integer deptNo){
return service.findScheduleByDeptNo(deptNo);
}
//去fullCalendar排班頁面,似乎沒用到
@GetMapping("/schedule/getEmp")
public String queryAllEmp(Model model) {
List<EmpBean> Emps = service.findAllEmps();
model.addAttribute("allEmps", Emps);
return "schedule/TimelineScheduling";
}
//找所有員工,似乎沒用到
@GetMapping("/schedule/findAllEmps")
public @ResponseBody List<EmpBean> findAll(){
return service.findAllEmps();
}
// 新增一個月
@PostMapping("/schedule/addScheduleMonthly")
public @ResponseBody Map<String, String> addScheduleMonthly(@RequestBody FactSchedule schedule) {
Map<String, String> map = new HashMap<>();
int n = 0;
try {
n = service.addScheduleMonthly(schedule);
if (n == 1) {
map.put("success", "新增多筆成功");
} else if (n == -1) {
map.put("fail", "新增多筆失敗");
}
} catch (Exception e) {
map.put("fail", e.getMessage());
e.printStackTrace();
}
return map;
}
// 新增單筆
@PostMapping("/schedule/addSchedule")
public @ResponseBody Map<String, String> saveSchedule(@RequestBody FactSchedule schedule) {
Map<String, String> map = new HashMap<>();
int n = 0;
try {
n = service.saveSchedule(schedule);
if (n == 1) {
map.put("success", "新增1筆成功");
} else if (n == -1) {
map.put("fail", "新增失敗");
}
} catch (Exception e) {
map.put("fail", e.getMessage());
e.printStackTrace();
}
return map;
}
// 刪除單筆
@DeleteMapping("/schedule/{keySchedule}")
public @ResponseBody Map<String, String> deleteScheduleByKey(@PathVariable(required = true) Integer keySchedule) {
Map<String, String> map = new HashMap<>();
try {
service.deleteScheduleByKey(keySchedule);
map.put("success","刪除成功");
}catch (Exception e) {
e.printStackTrace();
map.put("fail", "刪除失敗");
System.out.println("刪除失敗");
}
return map;
}
// 讀取並傳回單筆會員資料
@GetMapping("/schedule/{keySchedule}")
public @ResponseBody FactSchedule showEditSchedule(@PathVariable Integer keySchedule) {
FactSchedule schedule = service.findSchedByPK(keySchedule);
return schedule;
}
// 修改單筆會員資料
@PutMapping(value = "/schedule/{keySchedule}", consumes = { "application/json" }, produces = { "application/json" })
public @ResponseBody Map<String, String> updateSchedule(@RequestBody FactSchedule schedule,
@PathVariable Integer keySchedule) {
FactSchedule sched = null;
if (keySchedule != null) {
sched = service.findSchedByPK(keySchedule);
if (sched == null) {
throw new RuntimeException("鍵值不存在, key=" + keySchedule);
}
// service.evictSchedule(sched);
} else {
throw new RuntimeException("鍵值不存在, key=" + keySchedule);
}
// copyUnupdateField(sched, schedule);
Map<String, String> map = new HashMap<>();
try {
service.updateSchedule(schedule);
map.put("success", "更新成功");
} catch (Exception e) {
e.printStackTrace();
map.put("fail", "更新失敗");
}
return map;
}
//去fullCalendar排班頁面
@GetMapping("/schedule/TimelineScheduling")
public String toSchedule(Model model) {
model.addAttribute("body", "schedule/TimelineScheduling.jsp");
return "layout/Template";
}
//去表格排班葉面
@GetMapping("/schedule/TableScheduling")
public String TableScheduling(Model model) {
model.addAttribute("body", "schedule/TableScheduling.jsp");
return "layout/Template";
}
@GetMapping("/module")
public String module() {
return "module";
}
@GetMapping("/module-1")
public String module_1() {
return "module-1";
}
@GetMapping("/Template")
public String template() {
return "layout/Template";
}
}//end of class
|
package cn.zhanghao90.demo25;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button1;
private TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
textView1 = (TextView) findViewById(R.id.textView1);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
sendRequest();
break;
}
}
private void sendRequest(){
new Thread(new Runnable() {
@Override
public void run() {
try{
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url("https://www.baidu.com").build();
Response response = okHttpClient.newCall(request).execute();
String resStr = response.body().string();
showText(resStr);
}
catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
private void showText(final String text){
runOnUiThread(new Runnable() {
@Override
public void run() {
textView1.setText(text);
}
});
}
}
|
package com.nofatclips.sieve;
public class TestSieve {
public static void main (String args[]) {
int n=2000000;
Sieve s = new Sieve(n);
long count=0;
for (int i=0; i<=n; i++) if (s.isPrime(i)) count+=i;
System.out.println(count);
}
} |
package cn.test.demo01;
import java.util.Random;
import java.util.Scanner;
public class toStringTest {
public static void main(String[] args) {
Person p = new Person("张数",22);
String s = p.toString();
//重点:输出语句中,如果写的是对象P,默认调用对象的toString 方法
System.out.println(p);//p=p.toString()
System.out.println(s);
Random ran = new Random();
System.out.println(ran);//未重写toString
Scanner sc = new Scanner(System.in);
System.out.println(sc);//重写了toString
}
}
|
package com.qst.chapter04.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.Toast;
import java.lang.reflect.Method;
public class SubMenuDemoActivity extends AppCompatActivity {
protected void xonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// 初始化菜单
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// 添加子菜单
SubMenu subMenu = menu.addSubMenu(0, 2, Menu.NONE, "基础操作");
subMenu.setIcon(android.R.drawable.ic_menu_manage);
setIconEnable(menu);
// 添加子菜单项
//重命名菜单项
MenuItem renameItem = subMenu.add(2, 201, 1, "重命名");
renameItem.setIcon(android.R.drawable.ic_menu_edit);
//分享菜单项
MenuItem shareItem = subMenu.add(2, 202, 2, "分享");
shareItem.setIcon(android.R.drawable.ic_menu_share);
//删除菜单项
MenuItem delItem = subMenu.add(2, 203, 3, "删除");
delItem.setIcon(android.R.drawable.ic_menu_delete);
return true;
}
//根据菜单执行相应内容
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 201:
Toast.makeText(getApplicationContext(), "重命名...",
Toast.LENGTH_SHORT).show();
break;
case 202:
Toast.makeText(getApplicationContext(), "分享...", Toast.LENGTH_SHORT)
.show();
break;
case 203:
Toast.makeText(getApplicationContext(), "删除...", Toast.LENGTH_SHORT)
.show();
break;
}
return true;
}
private void setIconEnable(Menu menu) {
try {
Class<?> clazz = Class.forName("com.android.internal.view.menu.MenuBuilder");
Method m = clazz.getDeclaredMethod("setOptionalIconsVisible", boolean.class);
m.setAccessible(true);
// 下面传入参数
m.invoke(menu);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
/*
* 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 EvaluacionDesempeñoSupervisores;
import BD.BD;
import Clases.EvaluacionSupervisores.BDEvaluacionSupervisores;
import Clases.EvaluacionOperativo.ClassEvaluacionOperativo;
import Clases.EvaluacionSupervisores.ClassEvaluacionSupervisores;
import EvaluacionDesempeñoOperativo.ImpresionEvaluaciones;
import static Formuarios.Inicio.Pane1;
import java.awt.Dimension;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.TableColumn;
/**
*
* @author jluis
*/
public class BuscarCodigoSuper extends javax.swing.JInternalFrame {
int id_evaluacion;
int codigo;
int id;
int idevaluacion;
int depto = 10;
int deptousuario = 0;
int evalua = 1;
/**
* Creates new form BuscarCodigo
*/
public BuscarCodigoSuper() {
initComponents();
selectusuario();
if (depto == 8) {
DEPAR.setEnabled(true);
deptousuario = 8;
}
}
public void selectusuario() {
/* 1,'INSPECCION',
2,'TESTING',
3,'CHIPS',
4,'STRIP Y POTTING',
5,'TRANSFORMADORES',
6,'TALLER',
7,'BODEGA',
8,'ADMINISTRACION'
9,'GERENCIA'*/
String a = System.getProperty("user.name");//usar usuario de windows
if (a.equals("jluis")) {
evalua = 367;
depto = 8;
deptousuario = 8;
} //INFORMATICA
else if (a.equals("Inspeccion")) {
evalua = 302;
}// INSPECCION
else if (a.equals("testing")) {
evalua = 822;
} // TESTING
else if (a.equals("deptochips")) {
evalua = 748;
}//CHIPS
else if (a.equals("potting")) {
evalua = 781;
} //STRIP & POTTING
else if (a.equals("ehernandez")) {
evalua = 533;
} //TRANSFORMADORES
else if (a.equals("taller")) {
evalua = 348;
}//TALLE
else if (a.equals("bodega")) {
evalua = 465;
}//BODEGA
else if (a.equals("amonroy")) {
evalua = 920;
depto = 8;
deptousuario = 8;
} //INFORMATICA
else if (a.equals("ingenieria2")) {
evalua = 876;
} // CALIDAD
else if (a.equals("glemus")) {
evalua = 755;
}//SOTANO
else if (a.equals("oecheverria")) {
evalua = 847;
}//SOTANO
else if (a.equals("apacheco")) {
evalua = 833;
}//SOTANO
else if (a.equals("emely")) {
evalua = 833;
}//SOTANO
else if (a.equals("calidad")) {
depto = 8;
}//SOTANO
ListarCodigosPendientesEvalua();
}
public boolean EliminarFace(int a, int b) {
try {
//int id = (Integer.parseInt(String.valueOf(Imprime.getModel().getValueAt(Imprime.getSelectedRow(), 0))));
Connection cnn = BD.getConnection();
PreparedStatement ps = null;
ps = cnn.prepareStatement("update bevaluacion_desempeno set estado = 5 where id_listaempleados = (select id_listaempleados from alistaempleados where codigo = " + a + ") and evaluacion =" + b);
System.out.println("Evaluacion = " + id);
int rowsUpdated = ps.executeUpdate();
cnn.close();
ps.close();
} catch (SQLException ex) {
Logger.getLogger(ImpresionEvaluaciones.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
private void next() {
id_evaluacion = (Integer.parseInt(String.valueOf(Evaluaciones.getModel().getValueAt(Evaluaciones.getSelectedRow(), 0))));
UpdateFechaSuper tra = new UpdateFechaSuper(id_evaluacion);
Pane1.add(tra);
Dimension desktopSize = Pane1.getSize();
Dimension FrameSize = tra.getSize();
tra.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2);
tra.show();
try {
this.dispose();
} catch (Exception e) {
System.out.println("F" + e);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
Evaluaciones = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
Codigotxt = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
DEPAR = new javax.swing.JComboBox<>();
Eliminar = new javax.swing.JButton();
setClosable(true);
addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
}
public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
}
public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
formInternalFrameClosing(evt);
}
public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
}
public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
}
public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
}
public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
}
});
jPanel1.setBackground(new java.awt.Color(153, 204, 255));
Evaluaciones.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"No.", "CODIGO", "NOMBRE", "PUESTO", "DEPARTAMENTO", "FECHA EVALUACION", "FASE"
}
));
Evaluaciones.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EvaluacionesMouseClicked(evt);
}
});
Evaluaciones.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
EvaluacionesKeyReleased(evt);
}
});
jScrollPane1.setViewportView(Evaluaciones);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel1.setText("EVALUACIONES PENDIENTES");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel2.setText("CODIGO");
Codigotxt.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
Codigotxt.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
CodigotxtKeyReleased(evt);
}
});
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel3.setText("DEPARTAMENTO");
DEPAR.setEditable(true);
DEPAR.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
DEPAR.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "SELECCIONAR...", "INSPECCION", "TESTING", "CHIPS", "SOLDER DIP, STRIP & POTTING", "TRANSFORMADORES", "TALLER", "BODEGA", "ADMINISTRACION", "GERENCIA", "TECNOLOGIA DE LA INFORMACION/MANTENIMIENTO", "MOLDING" }));
DEPAR.setEnabled(false);
DEPAR.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DEPARActionPerformed(evt);
}
});
Eliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
Eliminar.setText("Eliminar Face");
Eliminar.setEnabled(false);
Eliminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EliminarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(320, 320, 320)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 899, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Codigotxt, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(DEPAR, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Eliminar)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jLabel1)
.addGap(46, 46, 46)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Codigotxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(DEPAR, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 321, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Eliminar)
.addContainerGap(14, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void ListarCodigosPendientes() {
ArrayList<ClassEvaluacionSupervisores> result1 = BDEvaluacionSupervisores.ListarEvaluacionesPendientesSuper(Codigotxt.getText(), depto);
Listar(result1);
}
private void ListarCodigosPendientesEvalua() {
ArrayList<ClassEvaluacionSupervisores> result2 = BDEvaluacionSupervisores.ListarEvaluacionesPendientesEvalua(Codigotxt.getText(), evalua);
Listar(result2);
}
private void Listar(ArrayList<ClassEvaluacionSupervisores> list1) {
Object[][] datos = new Object[list1.size()][8];
int i = 0;
for (ClassEvaluacionSupervisores t : list1) {
datos[i][0] = t.getId_evaluacion();
datos[i][1] = t.getCodigo();
datos[i][2] = t.getNombres();//+' '+t.getApellidos();
datos[i][3] = t.getPuesto();
datos[i][4] = t.getDepto();
datos[i][5] = t.getFechaS();
datos[i][6] = t.getNoEvaluacion();
datos[i][7] = t.getFaceS();
i++;
}
Evaluaciones.setModel(new javax.swing.table.DefaultTableModel(
datos,
new String[]{
"No.", "CODIGO", "NOMBRE", "PUESTO", "DEPARTAMENTO", "FECHA EVALUACION", "#EVALUACION", "FASE"
}) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
});
TableColumn columna1 = Evaluaciones.getColumn("No.");
columna1.setPreferredWidth(0);
TableColumn columna2 = Evaluaciones.getColumn("CODIGO");
columna2.setPreferredWidth(0);
TableColumn columna3 = Evaluaciones.getColumn("NOMBRE");
columna3.setPreferredWidth(150);
TableColumn columna4 = Evaluaciones.getColumn("PUESTO");
columna4.setPreferredWidth(150);
TableColumn columna5 = Evaluaciones.getColumn("DEPARTAMENTO");
columna5.setPreferredWidth(100);
TableColumn columna6 = Evaluaciones.getColumn("FECHA EVALUACION");
columna6.setPreferredWidth(75);
TableColumn columna7 = Evaluaciones.getColumn("#EVALUACION");
columna7.setPreferredWidth(35);
TableColumn columna8 = Evaluaciones.getColumn("FASE");
columna8.setPreferredWidth(35);
}
private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
InicioEvaluacioSupervisores tra = new InicioEvaluacioSupervisores();
Pane1.add(tra);
Dimension desktopSize = Pane1.getSize();
Dimension FrameSize = tra.getSize();
tra.setLocation((desktopSize.width - FrameSize.width) / 2, (desktopSize.height - FrameSize.height) / 2);
tra.show();
}//GEN-LAST:event_formInternalFrameClosing
private void EvaluacionesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EvaluacionesMouseClicked
if (deptousuario == 8) {
Eliminar.setEnabled(true);
}
if (evt.getClickCount() > 1) {
next();
}
}//GEN-LAST:event_EvaluacionesMouseClicked
private void CodigotxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_CodigotxtKeyReleased
ListarCodigosPendientes();
}//GEN-LAST:event_CodigotxtKeyReleased
private void DEPARActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DEPARActionPerformed
if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("INSPECCION")) {
depto = 1;
} else if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("TESTING")) {
depto = 2;
} else if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("CHIPS")) {
depto = 3;
} else if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("SOLDER DIP, STRIP & POTTING")) {
depto = 4;
} else if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("TRANSFORMADORES")) {
depto = 5;
} else if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("TALLER")) {
depto = 6;
} else if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("BODEGA")) {
depto = 7;
} else if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("ADMINISTRACION")) {
depto = 8;
} else if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("GERENCIA")) {
depto = 9;
} else if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("TECNOLOGIA DE LA INFORMACION/MANTENIMIENTO")) {
depto = 10;
}else if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("MOLDING")){
depto = 11;
}
else if (DEPAR.getSelectedItem().toString().equalsIgnoreCase("SELECCIONAR...")) {
depto = 0;
}
System.out.println(depto);
ListarCodigosPendientes();
}//GEN-LAST:event_DEPARActionPerformed
private void EvaluacionesKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_EvaluacionesKeyReleased
ListarCodigosPendientes();
}//GEN-LAST:event_EvaluacionesKeyReleased
private void EliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EliminarActionPerformed
String Nom;
Nom = (String) (Evaluaciones.getModel().getValueAt(Evaluaciones.getSelectedRow(), 2));
int resp = JOptionPane.showConfirmDialog(null, "Desea Eliminar Evaluacion de " + Nom);
if (JOptionPane.OK_OPTION == resp) {
int cod = 0;
int eva = 0;
cod = (Integer.parseInt(String.valueOf(Evaluaciones.getModel().getValueAt(Evaluaciones.getSelectedRow(), 1))));
eva = (Integer.parseInt(String.valueOf(Evaluaciones.getModel().getValueAt(Evaluaciones.getSelectedRow(), 6))));
if (cod > 0 && eva > 0) {
EliminarFace(cod, eva);
JOptionPane.showMessageDialog(null, "EL EVALUACION ELIMINADA...");
ListarCodigosPendientes();
}
}
}//GEN-LAST:event_EliminarActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField Codigotxt;
private javax.swing.JComboBox<String> DEPAR;
private javax.swing.JButton Eliminar;
private javax.swing.JTable Evaluaciones;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
|
package L1_EstruturaSequencial;
import java.util.Scanner;
public class Ex13_L1 {
public static void main(String[] args) {float altura = 0;
char sexo;
System.out.println("Qual sua altura?");
Scanner myObj = new Scanner(System.in);
altura = myObj.nextFloat();
while (true) {
System.out.println("Qual é seu sexo?");
sexo = myObj.next().charAt(0);
if (sexo == 'f') {
System.out.printf("Seu peso ideal é: %.2f Kg", ((62.1 * altura) - 44.7));
break;
} else if (sexo == 'm') {
System.out.printf("Seu peso ideal é: %.2f Kg", ((72.7 * altura) - 58));
break;
} else {
System.err.println("Alguma informação digitada é invalida.");
}
}
}
}
|
package Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 困难
*
* 给你一个数组 target ,包含若干 互不相同 的整数,以及另一个整数数组 arr ,arr 可能 包含重复元素。
*
* 每一次操作中,你可以在 arr 的任意位置插入任一整数。比方说,如果 arr = [1,4,1,2] ,那么你可以在中间添加 3 得到 [1,4,3,1,2] 。你可以在数组最开始或最后面添加整数。
*
* 请你返回 最少 操作次数,使得 target 成为 arr 的一个子序列。
*
* 一个数组的 子序列 指的是删除原数组的某些元素(可能一个元素都不删除),同时不改变其余元素的相对顺序得到的数组。比方说,[2,7,4] 是 [4,2,3,7,2,1,4] 的子序列(加粗元素),但 [2,4,2] 不是子序列。
*
*/
public class leet1713 {
public static int minOperations(int[] target, int[] arr) {
// 数组 若干互不相同整数,以及另一个整数数组arr,arr有重复元素
// 每次操作中可以在arr任意位置插证书,
// 请返回最少操作次数,使得target成为arr的一个子序列
// 动态规划?
int n = target.length;
Map<Integer, Integer> pos = new HashMap<Integer,Integer>();
// 把target的值按下标存进哈希表
for(int i=0;i<n;i++){
pos.put(target[i],i);
}
List<Integer> d = new ArrayList<Integer>();
for(int val : arr){
// 判断数组中出现的数字在pos中有无出现
if(pos.containsKey(val)) {
// 若有出现,取出值所对应的下标
int idx = pos.get(val);
// 找出idx在d中的位置,通过二分查找
int it = binarySearch(d, idx);
if(it != d.size()){
// 若it!= d.size() 则替换it的映射
d.set(it, idx);
}else{
// 否则将下标加入d
d.add(idx);
}
}
}
return n - d.size();
}
public static int binarySearch(List<Integer> d, int target){
int size = d.size();
if( size==0 || d.get(size-1) < target){
return size;
}
int low = 0, high = size - 1;
while(low<high){
int mid = (high - low) / 2 + low;
if(d.get(mid) < target){
low = mid+1;
}else{
high = mid;
}
}
return low;
}
public static void main(String[] args) {
int[] target = {6,4,8,1,2,3};
int[] arr = {4,7,6,2,3,8,6,1};
System.out.println(minOperations(target,arr));
}
}
|
package utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import edu.stanford.nlp.ie.machinereading.domains.ace.reader.RobustTokenizer.AbbreviationMap;
public class AbbreviationChecker {
public final static String[] ABBREVIATIONS = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Adj", "Adm", "Adv", "Asst", "Bart", "Bldg",
"Brig", "Bros", "Capt", "Cmdr", "Col", "Comdr", "Con", "Corp", "Cpl", "DR", "Dr", "Drs", "Ens", "Gen",
"Gov", "Hon", "Hr", "Hosp", "Insp", "Lt", "MM", "MR", "MRS", "MS", "Maj", "Messrs", "Mlle", "Mme", "Mr",
"Mrs", "Ms", "Msgr", "Op", "Ord", "Pfc", "Ph", "Prof", "Pvt", "Rep", "Reps", "Res", "Rev", "Rt", "Sen",
"Sens", "Sfc", "Sgt", "Sr", "St", "Supt", "Surg", "v", "vs", "i.e", "rev", "e.g", "No", "Nos", "Art", "Nr",
"pp" };
private AbbreviationMap am = new AbbreviationMap(true); //case-insensitive;
private Set<String> abbrSet = new HashSet<String>();
private static AbbreviationChecker instance;
public AbbreviationChecker() {
abbrSet.addAll(toLowerCase(Arrays.asList(ABBREVIATIONS)));
}
public boolean isAbbr(String word) {
if (word.endsWith(".")) {
word = word.substring(0, word.length() - 1);
}
return abbrSet.contains(word) || am.contains(word + ".");
}
private static List<String> toLowerCase(List<String> words) {
List<String> normWords = new ArrayList<>();
for(String word: words) normWords.add(word.toLowerCase());
return normWords;
}
public static AbbreviationChecker getInstance() {
if (AbbreviationChecker.instance == null) {
AbbreviationChecker.instance = new AbbreviationChecker();
}
return AbbreviationChecker.instance;
}
}
|
package net.mv.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class Advisor {
@Before("execution(* net.mv.aop.*.method1(..))")
public void beforeAdvice(){
System.out.println("Before Advice");
}
@After("execution(* net.mv.aop.*.method1(..))")
public void afterAdvice(){
System.out.println("After Advice!");
}
@Around("execution(* net.mv.aop.*.method2(..))")
public void moreAdvice(ProceedingJoinPoint jp) throws Throwable{
System.out.println("Begin around advice");
jp.proceed();
System.out.println("Finish around advice!");
}
}
|
package com.santos.android.evenlychallenge.API;
/**
* Created by Abel Cruz dos Santos on 16.08.2017.
*/
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSetter;
@JsonIgnoreProperties(ignoreUnknown=true)
public class Venue {
private String mId;
private String mName;
private Location mLocation;
private boolean mLike;
private boolean mDislike;
private Categories[] mCategories;
private Contact mContact;
private double mRating;
public String getId() {
return mId;
}
@JsonSetter("id")
public void setId(String id) {
mId = id;
}
public String getName() {
return mName;
}
@JsonSetter("name")
public void setName(String name) {
mName = name;
}
public Location getLocation() {
return mLocation;
}
public void setLocation(Location location) {
mLocation = location;
}
public boolean isLike() {
return mLike;
}
@JsonSetter("like")
public void setLike(boolean like) {
mLike = like;
}
public boolean isDislike() {
return mDislike;
}
@JsonSetter("dislike")
public void setDislike(boolean dislike) {
mDislike = dislike;
}
public Categories[] getCategories() {
return mCategories;
}
@JsonSetter("categories")
public void setCategories(Categories[] categories) {
mCategories = categories;
}
public Contact getContact() {
return mContact;
}
@JsonSetter("contact")
public void setContact(Contact contact) {
mContact = contact;
}
public double getRating() {
return mRating;
}
@JsonSetter("rating")
public void setRating(double rating) {
mRating = rating;
}
}
|
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.HashSet;
import java.util.Stack;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by Anna Bonaldo on 31/08/2017.
*/
public interface Scheduler {
public void spawn(Tasklet t);
// Add tasklet to t.master and to queue of server t.serverIndex
public void waitForAll(HashSet<Tasklet> master);
// Wait for all
public void printStats();
}
class WorkStealingScheduler implements Scheduler {
private static AtomicBoolean shutdownNow = new AtomicBoolean(false);
private static ThreadLocal<Integer> serverIndex = new ThreadLocal<Integer>();
private ServerThread[] servers;
public schedulerStatistics wSchedulerStats = new schedulerStatistics();
private class ServerThread implements Runnable {
private ThreadMXBean threadmxbean = ManagementFactory.getThreadMXBean();
private Stack<Tasklet> stack = new Stack<>();
private int myIndex = 0;
public ConcurrentLinkedDeque<Tasklet> deque = new ConcurrentLinkedDeque<>();
public final serverStatistics stats = new serverStatistics();
public void run() {
shutdownNow.set(false);
serverIndex.set(myIndex);
long startCpuTimer = threadmxbean.getCurrentThreadCpuTime();
long startClockTimer = System.nanoTime();
while (!shutdownNow.get())
{
if(deque.isEmpty())
steal();
while (!deque.isEmpty()) {
Tasklet t = deque.pollLast();
if (t != null)
{
stack.push(t);
t.invoke();
stack.pop();
// servers[myIndex].stats.numTaskletInitiations++;
}
}
shutdownNow.set(checkServers());
}
this.stats.CPUtime = threadmxbean.getCurrentThreadCpuTime() - startCpuTimer;
this.stats.ClockTime = System.nanoTime()-startClockTimer;
;
} // end run
private boolean checkServers()
{
for (int i=0; i<servers.length; i++ ) {
if (!servers[i].deque.isEmpty()||!servers[i].stack.isEmpty())
return false;
}
return true;
}
public boolean steal()
{
boolean stolen = false;
for (int i=0; i<servers.length && (!stolen); i++ ) {
if (i != myIndex && !servers[i].deque.isEmpty()) {
Tasklet t = servers[i].deque.pollFirst();
if (t != null) {
servers[myIndex].deque.addLast(t);
servers[myIndex].stats.numTaskletSteals++;
stolen = true;
}
}
}
return stolen;
}
public ServerThread(int myIndex) {
this.myIndex = myIndex;
}
} // end class ServerThread
public WorkStealingScheduler(int numServers) {
this.servers = new ServerThread[numServers];
for (int i = 0; i < numServers; i++) {
servers[i] = new ServerThread(i);
}
this.wSchedulerStats.numServers = numServers;
}
public void spawn(Tasklet t) {
if (servers[0].deque == null) {
servers[0].deque = new ConcurrentLinkedDeque<>();
}
t.addDeque(servers[0].deque);
servers[0].deque.addLast(t);
Thread[] pool=new Thread[servers.length];
for (int i = 0; i < servers.length; i++) {
pool[i] = new Thread(servers[i]);
pool[i].start();
}
try {
for (int i = 0; i < servers.length; i++) {
pool[i].join();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public void waitForAll(HashSet<Tasklet> master) {
if (master.isEmpty())
this.shutdown();
}
public void shutdown() {
shutdownNow.set(true);
}
public void executeSequential(int[] arrayToSort) {
QuickSort.sequentialSortArray(arrayToSort, 0, arrayToSort.length-1);
}
public void printStats() {
System.out.println("server\tsteals\tinits");
int totalSteals = 0;
int totalInitiations = 0;
for (int i = 0; i < servers.length; i++) {
int numSteals = servers[i].stats.numTaskletSteals;
int numInitiations = servers[i].stats.numTaskletInitiations;
totalSteals += numSteals;
totalInitiations += numInitiations;
System.out.println(Integer.toString(i) + "\t" +
numSteals + "\t" + numInitiations);
}
System.out.println("total\t" + totalSteals + "\t" + totalInitiations);
System.out.println("-----------------------------------------------");
}
public void computeStats() {
int totalSteals = 0;
long totalCPUTime = 0;
long totalClockTime = 0;
for (int i = 0; i < servers.length; i++) {
int numSteals = servers[i].stats.numTaskletSteals;
totalSteals += numSteals;
totalCPUTime += servers[i].stats.CPUtime;
totalClockTime+= servers[i].stats.ClockTime;
}
this.wSchedulerStats.totalSteals = totalSteals;
this.wSchedulerStats.totalCPUTime = totalCPUTime / (this.wSchedulerStats.numServers*Runtime.getRuntime().availableProcessors());
this.wSchedulerStats.totalClockTime = totalClockTime / (this.wSchedulerStats.numServers*Runtime.getRuntime().availableProcessors());
}
} // end class WorkStealingScheduler
|
package com.fjiang.exmaples;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import org.junit.Test;
//http://www.baeldung.com/java-optional
public class OptionalTest {
@Test
public void testCreation() {
Optional<String> empty = Optional.empty();
assertFalse(empty.isPresent());
String name = "fjiang";
Optional<String> opt = Optional.of(name);
assertEquals("Optional[fjiang]", opt.toString());
}
@Test(expected = NullPointerException.class)
public void testCreationWithNPE() {
String name = null;
Optional<String> opt = Optional.of(name);
}
@Test
public void testCreationNullable() {
String name = null;
Optional<String> opt = Optional.ofNullable(name);
assertEquals("Optional.empty", opt.toString());
name = "fjiang";
opt = Optional.ofNullable(name);
assertEquals("Optional[fjiang]", opt.toString());
}
@Test
public void testIsPresent() {
Optional<String> opt = Optional.of("fjiang");
assertTrue(opt.isPresent());
opt.ifPresent(name -> System.out.println(name.length()));
opt = Optional.ofNullable(null);
assertFalse(opt.isPresent());
}
public String getMyDefault() {
System.out.println("Getting Default Value");
return "Default Value";
}
@Test
public void testElse() {
String text = null;
System.out.println("Using orElseGet:");
// The orElseGet API is similar to orElse. However, instead of taking a value to
// return if the Optional value is not present, it takes a supplier functional
// interface which is invoked and returns the value of the invocation:
String defaultText = Optional.ofNullable(text).orElseGet(this::getMyDefault);
assertEquals("Default Value", defaultText);
System.out.println("Using orElse:");
// The orElse API is used to retrieve the value wrapped inside an Optional
// instance. It takes one parameter which acts as a default value. With orElse,
// the wrapped value is returned if it is present and the argument given to
// orElse is returned if the wrapped value is absent:
defaultText = Optional.ofNullable(text).orElse(getMyDefault());
assertEquals("Default Value", defaultText);
}
@Test
public void testGet() {
Optional<String> opt = Optional.of("fjiang");
String name = opt.get();
assertEquals("fjiang", name);
}
@Test(expected = NoSuchElementException.class)
public void testGetWithException() {
Optional<String> opt = Optional.ofNullable(null);
String name = opt.get();
}
@Test
public void testFilter() {
Integer year = 2016;
Optional<Integer> yearOptional = Optional.of(year);
boolean is2016 = yearOptional.filter(y -> y == 2016).isPresent();
assertTrue(is2016);
boolean is2017 = yearOptional.filter(y -> y == 2017).isPresent();
assertFalse(is2017);
}
@Test
public void testMap() {
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
Optional<List<String>> listOptional = Optional.of(companyNames);
int size = listOptional.map(List::size).orElse(0);
assertEquals(6, size);
}
}
|
import java.util.List;
public class Categoria {
//atributos
String nombre;
List<Titulo> titulos;
Categoria supercategoria;
//metodo constructor
public Categoria() {
}
//sobrecargar de constructor
public Categoria(String nombre) {
this.nombre = nombre;
}
}
|
package com.romitus;
import java.util.Scanner;
public class Ejercicio5 {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
System.out.println("Introduce la hora");
int horas = teclado.nextInt();
System.out.println("Introduce los minutos");
int minutos = teclado.nextInt();
System.out.println("Introduce los segundos");
int segundos = teclado.nextInt();
System.out.println("Introduce los segundos a aumentar");
int segundosAumentar = teclado.nextInt();
System.out.println("Aumentando la hora...");
for (int i = 0; i < segundosAumentar; i++) {
segundos = segundos + 1;
if (segundos > 59){
segundos = 0;
minutos = minutos + 1;
}
if (minutos > 59){
minutos = 0;
horas = horas + 1;
}
if (horas > 23){
horas = 0;
minutos = 0;
segundos = 0;
}
System.out.println(horas+":"+minutos+":"+segundos);
}
}
}
|
package table;
import javax.persistence.*;
@Entity
@Table(name = "group")
public class Group {
@Id
@Column(name = "group_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer groupId;
@Column(name = "name")
private String name;
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Group() { }
public Group(String name) {
this.name = name;
}
}
|
package blog.dreamland.com.service.impl;
import blog.dreamland.com.dao.UserMapper;
import blog.dreamland.com.entity.User;
import blog.dreamland.com.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @auther SyntacticSugar
* @data 2019/3/1 0001下午 3:57
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
/**
* 注册
*/
@Transactional
@Override
public int register(User user) {
//先查询用户
// List<User> userList = userMapper.select(user);
// if (userList.isEmpty()) {
// int insert = userMapper.insert(user);
// // 插入数据库
// return insert;
// }
// return 0;
return userMapper.insert(user);
}
/**
* 登录
*/
@Override
public User login(String email, String password) {
// 查询数据库
User user = new User();
user.setPassword(password);
user.setEmail(email);
List<User> users = userMapper.select(user);
if (users.size() == 1) {
//存在
return users.get(0);
}
return null;
}
/**
* 通过email 查找user
*/
@Override
public User findUserByEmail(String email) {
User user = new User();
user.setEmail(email);
List<User> users = userMapper.select(user);
if (users.size() == 1) {
//存在
return users.get(0);
}
return null;
}
/**
* 通过手机号查找user
*/
@Override
public User findUserByPhone(String phone) {
User user = new User();
user.setPhone(phone);
List<User> users = userMapper.select(user);
if (users.size() == 1) {
//存在
return users.get(0);
}
return null;
}
/**
* 通过id 查找user
*/
@Override
public User findUserById(String id) {
User user = userMapper.selectByPrimaryKey(id);
if (user != null) {
return user;
}
return null;
}
/**
* 删除用户通过email
*/
@Transactional
@Override
public void deleteByEmail(String email) {
User user = new User();
int delete = userMapper.delete(user);
if (delete != 1) {
// 删除失败
}
}
/**
* 更新账户信息
*/
@Override
public void update(User user) {
int i = userMapper.updateByPrimaryKeySelective(user);
}
}
|
package comWeb;
import comDao.certificate;
import comUtil.SqlOperate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
public class QueryServlet extends HttpServlet {
String content = null;
private static final long serialVersionUID=1L;
Logger logger = LogManager.getLogger("myLog");//记录日志
//public void destroy(){
// super.destroy();
//}
public QueryServlet(){
super();
}
public void doGet(HttpServletRequest request , HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String organization = request.getParameter("organization");
SqlOperate sqlOperate=new SqlOperate();
if(organization==null){
String serial_NUmber = request.getParameter("serial_NUmber");
try {
certificate cer = sqlOperate.queryCertificate(serial_NUmber);
request.getSession().setAttribute("cer_Owner",false);
request.getSession().setAttribute("certificate",cer);
request.getRequestDispatcher("certificate_info.jsp").forward(request,response);
} catch (SQLException e) {
e.printStackTrace();
}
}
else{
try {
certificate cer = sqlOperate.queryCerByName(organization);
request.getSession().setAttribute("cer_Owner",false);
request.getSession().setAttribute("certificate",cer);
request.getRequestDispatcher("certificate_info.jsp").forward(request,response);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
|
package com.example.myretrofit.api;
import okhttp3.Call;
import okhttp3.HttpUrl;
import retrofit2.http.Field;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
public interface WeatherApi {
String baseUrl = "https://restapi.amap.com/v3/weather/weatherInfo";
@POST("/v3/weather/weatherInfo")
Call postWeather(@Field("city") String city, @Field("key") String key);
@GET("/v3/weather/weatherInfo")
Call getWeather(@Query("city") String city, @Query("key") String key);
}
|
package com.pce.BookMeTutor.Config;
public class Constants {
public static final String SECRET = "secretToEncrypt";
public static final String TOKEN_PREFIX = "Bearer ";
public static final String HEADER_FIELD_STRING = "Authorization";
public static final long EXPIRATION_TIME = 1000 * 60 * 60 * 8;
public static final String BACKEND_URL = "http://bookmetutor-backend.ap-southeast-1.elasticbeanstalk.com/";
public static final String USER_NOT_FOUND = "user not found";
public static final String TUTOR_NOT_FOUND = "tutor not found";
public static final String BOOKING_NOT_FOUND = "booking not found";
public static final String ADDRESS_NOT_FOUND = "addresss id invalid";
public static final String USER_EXISTS = "email id taken";
public static final String SUBJECT_NOT_FOUND = "subject not found";
public static final String INVALID_TOKEN = "invalid token or token expired";
public static final String INVALID_REQUEST = "role is mandatory";
}
|
/*
* Generics doesn't support subtyping. Map accepts Map in constructor
*
*
*/
package Map;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author YNZ
*/
public class CopyOfMap {
public static void main(String[] args) {
Map<String, Double> salaryMap = new HashMap<>();
salaryMap.put("Tom", 12334.33);
salaryMap.put("Mike", 433542.84);
Map<String, Double> copySalaryMap = new HashMap<>(salaryMap);
System.out.println("" + copySalaryMap);
}
}
|
package com.ravi.travel.budget_travel.handler;
import com.ravi.travel.budget_travel.domain.Article;
import com.ravi.travel.budget_travel.exception.ResourceNotFoundException;
import com.ravi.travel.budget_travel.service.ArticleService;
import com.ravi.travel.budget_travel.utilities.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Component(value = "ASYNC")
public class AsyncRequestHandler {
private static Logger log = LoggerFactory.getLogger(AsyncRequestHandler.class);
@Autowired
private ArticleService articleService ;
public ApiResponse executeReq(String type, Map<String, String> params) {
log.info("Thread executeReq {}",Thread.currentThread());
ApiResponse response = new ApiResponse();
try {
log.info("Sleeping for 30sec");
Thread.sleep(1000*30);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<Article> authorList = articleService.article(params.get("name")) ;
if(CollectionUtils.isEmpty(authorList)){
throw new ResourceNotFoundException(" No Article Found of Author :"+params.get("name")) ;
}
/*Map<String,String> res = authorList.stream().collect(Collectors.toMap(Article::getAuthor ,
Article::getDescription));*/
response.setStatus("SUCCESS FROM ASYNC");
//response.setResponseParams(res);
response.setErrorDesc("NA");
return response;
}
}
|
package edu.lewis.ap.tran.don;
import edu.jenks.dist.lewis.ap.*;
import edu.jenks.dist.lewis.ap.Student;
import java.util.*;
public class HighSchoolClass extends AbstractHighSchoolClass {
public Student[] allStudents;
public static void main(String[] args) {
//System.out.println(HONORS_GPA);
ArrayList<Student> doo = new ArrayList();
doo.add(new Student("dan", "tran", 4.0, true));
doo.add(new Student("Griff", "nad", 3.8, false));
Student[] stud = new Student[doo.size()];
for (int i = 0; i < stud.length; i++) {
stud[i] = doo.get(i);
}
HighSchoolClass what = new HighSchoolClass(stud);
System.out.println(what.getValedictorian()[0].getFirstName());
System.out.println(what.getValedictorian().length);
System.out.println(what.getHonorsStudents()[0].getFirstName());
System.out.println(what.getHonorsStudents().length);
System.out.println(what.getHonorsPercent());
System.out.println(what.graduateWithHighestHonorsPercent());
}
public HighSchoolClass(Student[] students) {
super(students);
allStudents = students;
}
public double getHonorsPercent() {
//System.out.println(getHonorsStudents().length + " dad " + allStudents.length);
//System.out.println(((double)getHonorsStudents().length / (double)allStudents.length) * 100.0);
return ((double)getHonorsStudents().length / (double)allStudents.length) * 100.0;
}
public Student[] getHonorsStudents() {
ArrayList<Student> honorStuds = new ArrayList();
for(int i = 0; i < allStudents.length; i++) {
if(allStudents[i].isHonors()) {
honorStuds.add(allStudents[i]);
}
}
Student[] stud = new Student[honorStuds.size()];
for (int i = 0; i < stud.length; i++) {
stud[i] = honorStuds.get(i);
}
return stud;
}
public Student[] getValedictorian() {
ArrayList<Student> valedStuds = new ArrayList();
if (allStudents.length == 0) {
return (Student[]) valedStuds.toArray();
}
double maxGPA = allStudents[0].getGpa();
for (int i = 0; i < allStudents.length; i++) {
if (allStudents[i].getGpa() > maxGPA) {
maxGPA = allStudents[i].getGpa();
}
}
for (int i = 0; i < allStudents.length; i++) {
if (allStudents[i].getGpa() == maxGPA) {
valedStuds.add(allStudents[i]);
}
}
Student[] stud = new Student[valedStuds.size()];
for (int i = 0; i < stud.length; i++) {
stud[i] = valedStuds.get(i);
}
return stud;
}
public double graduateWithHighestHonorsPercent() {
int highHonStuds = 0;
for(int i = 0; i < allStudents.length; i++) {
if(allStudents[i].getGpa() >= HIGHEST_HONORS_GPA) {
highHonStuds++;
}
}
return ((double) highHonStuds / (double) allStudents.length) * 100.0;
}
public double graduateWithHonorsPercent() {
int highHonStuds = 0;
for(int i = 0; i < allStudents.length; i++) {
if(allStudents[i].getGpa() >= HONORS_GPA) {
highHonStuds++;
}
}
return ((double) highHonStuds / (double) allStudents.length) * 100.0;
}
}
|
package com.pabi.miwokmediaplayer;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Admin on 7/7/2017.
*/
public class SongsAdapter extends ArrayAdapter<Songs> {
public SongsAdapter(Context context, ArrayList<Songs> songs) {
super(context, 0, songs);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.song_list, parent, false);
}
Songs currentSong = getItem(position);
TextView txt = (TextView) listItemView.findViewById(R.id.textView);
txt.setText(currentSong.getSongName());
ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);
if (currentSong.hasImage()) {
imageView.setImageResource(currentSong.getImageResourceId());
imageView.setVisibility(View.VISIBLE);
} else {
imageView.setVisibility(View.GONE);
}
return listItemView;
}
}
|
package PSU.Grad.Flight.Search;
/**
Class for storing API Key--added to separate file that is not stored in personal git repo for security
*/
public class Secret {
/**
@return API Key for Skyscanner API
*/
public static String getKey() {
return "e4dabae40emsh90f58866c571a5cp1e5090jsn121b08c88723";
}
}
|
package com.imagsky.v81j.domain;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;
import com.imagsky.util.CommonUtil;
import com.imagsky.v81j.domain.App;
import java.util.*;
@Entity
@Table(name = "tb_member")
@Inheritance(strategy = InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name = "SYS_GUID", referencedColumnName = "SYS_GUID")
public class Member extends SysObject {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final Integer FULLNAME_DISP_FIRSTLAST = 0;
public static final Integer FULLNAME_DISP_FIRSTLAST_COMMA = 1;
public static final Integer FULLNAME_DISP_LASTFIRST = 2;
public static final Integer FULLNAME_DISP_LASTFIRST_COMMA = 3;
public static String getFullName(Member thisMember) {
if (thisMember == null) {
return null;
}
if (thisMember.getMem_fullname_display_type() == FULLNAME_DISP_FIRSTLAST) {
return thisMember.getMem_firstname() + " " + thisMember.getMem_lastname();
} else if (thisMember.getMem_fullname_display_type() == FULLNAME_DISP_FIRSTLAST_COMMA) {
return thisMember.getMem_firstname() + ", " + thisMember.getMem_lastname();
} else if (thisMember.getMem_fullname_display_type() == FULLNAME_DISP_LASTFIRST) {
return thisMember.getMem_lastname() + " " + thisMember.getMem_firstname();
} else if (thisMember.getMem_fullname_display_type() == FULLNAME_DISP_LASTFIRST_COMMA) {
return thisMember.getMem_lastname() + ", " + thisMember.getMem_firstname();
} else {
return thisMember.getMem_firstname() + " " + thisMember.getMem_lastname();
}
}
@Column(length = 50)
private String mem_login_email;
@Column(length = 50)
private String mem_passwd;
@Column(length = 70)
private String mem_firstname;
@Column(length = 70)
private String mem_lastname;
@Column(length = 25)
private String mem_shopurl;
@Column(length = 50)
private String mem_shopname;
@Temporal(TemporalType.TIMESTAMP)
private Date mem_lastlogindate;
@Column
private Integer mem_salutation;
@Column(length = 80)
private String mem_shopbanner;
@Column(length = 50)
private String mem_shop_hp_arti;
@Column
private Integer mem_max_sellitem_count;
@Column
private Integer mem_fullname_display_type;
@Column(length = 30)
private String mem_display_name;
@Column
private Integer mem_feedback;
@Column
private Double mem_cash_balance;
@Column
private Boolean fb_mail_verified;
@Column
private String fb_id;
@Column
private Integer mem_meatpoint;
@Column
private String package_type;
@ManyToMany
@JoinTable(name="tb8_app_user_xref",
joinColumns = { @JoinColumn(name="MEMBER_GUID") },
inverseJoinColumns = { @JoinColumn(name="APP_GUID") } )
private Set<App> apps;
/***
@ManyToMany
@JoinTable(name = "tb_member_service_xref",
joinColumns = {
@JoinColumn(name = "MEM_SYS_GUID")},
inverseJoinColumns = {
@JoinColumn(name = "SERVICE_ID")})
private Collection<Service> services;
***/
public String getMem_shopbanner() {
return mem_shopbanner;
}
public void setMem_shopbanner(String memShopbanner) {
mem_shopbanner = memShopbanner;
}
public String getMem_shop_hp_arti() {
return mem_shop_hp_arti;
}
public void setMem_shop_hp_arti(String memShopHpArti) {
mem_shop_hp_arti = memShopHpArti;
}
public String getMem_login_email() {
return mem_login_email;
}
public void setMem_login_email(String memLoginEmail) {
mem_login_email = memLoginEmail;
}
public String getMem_passwd() {
return mem_passwd;
}
public void setMem_passwd(String memPasswd) {
mem_passwd = memPasswd;
}
public String getMem_firstname() {
return mem_firstname;
}
public void setMem_firstname(String memFirstname) {
mem_firstname = memFirstname;
}
public String getMem_lastname() {
return mem_lastname;
}
public void setMem_lastname(String memLastname) {
mem_lastname = memLastname;
}
public String getMem_shopurl() {
return mem_shopurl;
}
public void setMem_shopurl(String memShopurl) {
mem_shopurl = memShopurl;
}
public String getMem_shopname() {
return mem_shopname;
}
public void setMem_shopname(String memShopname) {
mem_shopname = memShopname;
}
public Date getMem_lastlogindate() {
return mem_lastlogindate;
}
public void setMem_lastlogindate(Date memLastlogindate) {
mem_lastlogindate = memLastlogindate;
}
public Integer getMem_salutation() {
return mem_salutation;
}
public void setMem_salutation(Integer memSalutation) {
mem_salutation = memSalutation;
}
public Integer getMem_max_sellitem_count() {
return mem_max_sellitem_count;
}
public void setMem_max_sellitem_count(Integer memMaxSellitemCount) {
mem_max_sellitem_count = memMaxSellitemCount;
}
public Integer getMem_fullname_display_type() {
return mem_fullname_display_type;
}
public void setMem_fullname_display_type(Integer memFullnameDisplayType) {
mem_fullname_display_type = memFullnameDisplayType;
}
public String getMem_display_name() {
return mem_display_name;
}
public void setMem_display_name(String memDisplayName) {
mem_display_name = memDisplayName;
}
public String getNickName() {
if (CommonUtil.isNullOrEmpty(mem_display_name)) {
return CommonUtil.stringTokenize(mem_login_email, "@")[0];
} else {
return mem_display_name;
}
}
public Integer getMem_meatpoint() {
return mem_meatpoint;
}
public void setMem_meatpoint(Integer memMeatpoint) {
mem_meatpoint = memMeatpoint;
}
public Integer getMem_feedback() {
return mem_feedback;
}
public void setMem_feedback(Integer memFeedback) {
mem_feedback = memFeedback;
}
/*** V6
public Collection<Service> getServices() {
return services;
}
public void setRoles(Collection<Service> services) {
this.services = services;
} ***/
public Double getMem_cash_balance() {
return mem_cash_balance;
}
public void setMem_cash_balance(Double memCashBalance) {
mem_cash_balance = memCashBalance;
}
public Boolean getFb_mail_verified() {
return fb_mail_verified;
}
public void setFb_mail_verified(Boolean fbMailVerified) {
fb_mail_verified = fbMailVerified;
}
public String getFb_id() {
return fb_id;
}
public void setFb_id(String fbId) {
fb_id = fbId;
}
public String getPackage_type() {
return package_type;
}
public void setPackage_type(String package_type) {
this.package_type = package_type;
}
public Set<App> getApps() {
return apps;
}
public void setApps(Set<App> apps) {
this.apps = apps;
}
public static TreeMap<String, Object> getFields(Member obj) {
TreeMap<String, Object> aHt = new TreeMap<String, Object>();
aHt.put("mem_login_email", obj.mem_login_email);
aHt.put("mem_passwd", obj.mem_passwd);
aHt.put("mem_firstname", obj.mem_firstname);
aHt.put("mem_lastname", obj.mem_lastname);
aHt.put("mem_shopurl", obj.mem_shopurl);
aHt.put("mem_shopname", obj.mem_shopname);
aHt.put("mem_lastlogindate", obj.mem_lastlogindate);
aHt.put("mem_salutation", obj.mem_salutation);
aHt.put("mem_shopbanner", obj.mem_shopbanner);
aHt.put("mem_max_sellitem_count", obj.mem_max_sellitem_count);
aHt.put("mem_display_name", obj.getMem_display_name());
aHt.put("mem_fullname_display_type", obj.getMem_fullname_display_type());
aHt.put("mem_feedback", obj.getMem_feedback());
aHt.put("mem_cash_balance", obj.getMem_cash_balance());
aHt.put("fb_id", obj.getFb_id());
aHt.put("fb_mail_verified", obj.getFb_mail_verified());
aHt.put("package_type",obj.getPackage_type());
///aHt.put("mem_address",obj.mem_address);
aHt.putAll(SysObject.getSysFields(obj));
return aHt;
}
public static List getWildFields() {
List returnList = new ArrayList();
// returnList.add("mem_shopname");
return returnList;
}
}
|
package com.xwj.designIntercept;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @Description 将代理类的invoke放进来
* @Author yuki
* @Date 2018/11/29 14:54
* @Version 1.0
**/
public class Invocation {
private Object target;
private Method method;
private Object[] args;
public Invocation(Object target, Method method, Object[] args) {
this.target = target;
this.method = method;
this.args = args;
}
public Object proceed() throws InvocationTargetException, IllegalAccessException {
return method.invoke(target,args);
}
}
|
/*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* 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.alibaba.druid.sql.dialect.hive.stmt;
import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLObject;
import com.alibaba.druid.sql.ast.statement.SQLAssignItem;
import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement;
import com.alibaba.druid.sql.visitor.SQLASTVisitor;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class HiveCreateTableStatement extends SQLCreateTableStatement {
protected List<SQLExpr> skewedBy = new ArrayList<SQLExpr>();
protected List<SQLExpr> skewedByOn = new ArrayList<SQLExpr>();
protected Map<String, SQLObject> serdeProperties = new LinkedHashMap<String, SQLObject>();
protected SQLExpr metaLifeCycle;
protected boolean likeQuery; // for DLA
protected List<SQLAssignItem> mappedBy = new ArrayList<SQLAssignItem>(1);
protected SQLExpr intoBuckets;
protected SQLExpr using;
public HiveCreateTableStatement() {
this.dbType = DbType.hive;
}
public HiveCreateTableStatement(DbType dbType) {
this.dbType = dbType;
}
protected void accept0(SQLASTVisitor v) {
if (v.visit(this)) {
acceptChild(v);
}
v.endVisit(this);
}
protected void acceptChild(SQLASTVisitor v) {
super.acceptChild(v);
acceptChild(v, skewedBy);
acceptChild(v, skewedByOn);
for (SQLObject item : serdeProperties.values()) {
acceptChild(v, item);
}
acceptChild(v, metaLifeCycle);
acceptChild(v, intoBuckets);
}
public void cloneTo(HiveCreateTableStatement x) {
super.cloneTo(x);
for (SQLExpr item : skewedBy) {
x.addSkewedBy(item.clone());
}
for (SQLExpr item : skewedByOn) {
x.addSkewedByOn(item.clone());
}
for (Map.Entry<String, SQLObject> entry : serdeProperties.entrySet()) {
SQLObject entryValue = entry.getValue().clone();
entryValue.setParent(x);
x.serdeProperties.put(entry.getKey(), entryValue);
}
if (metaLifeCycle != null) {
x.setMetaLifeCycle(metaLifeCycle.clone());
}
x.setLikeQuery(this.likeQuery);
if (mappedBy != null) {
for (SQLAssignItem item : mappedBy) {
SQLAssignItem item2 = item.clone();
item2.setParent(this);
x.mappedBy.add(item2);
}
}
if (intoBuckets != null) {
x.intoBuckets = intoBuckets.clone();
}
if (using != null) {
x.setUsing(using.clone());
}
}
public HiveCreateTableStatement clone() {
HiveCreateTableStatement x = new HiveCreateTableStatement();
cloneTo(x);
return x;
}
public List<SQLExpr> getSkewedBy() {
return skewedBy;
}
public void addSkewedBy(SQLExpr item) {
item.setParent(this);
this.skewedBy.add(item);
}
public List<SQLExpr> getSkewedByOn() {
return skewedByOn;
}
public void addSkewedByOn(SQLExpr item) {
item.setParent(this);
this.skewedByOn.add(item);
}
public Map<String, SQLObject> getSerdeProperties() {
return serdeProperties;
}
public SQLExpr getMetaLifeCycle() {
return metaLifeCycle;
}
public void setMetaLifeCycle(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.metaLifeCycle = x;
}
public boolean isLikeQuery() {
return likeQuery;
}
public void setLikeQuery(boolean likeQuery) {
this.likeQuery = likeQuery;
}
public List<SQLAssignItem> getMappedBy() {
return mappedBy;
}
public SQLExpr getIntoBuckets() {
return intoBuckets;
}
public void setIntoBuckets(SQLExpr intoBuckets) {
this.intoBuckets = intoBuckets;
}
public SQLExpr getUsing() {
return using;
}
public void setUsing(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.using = x;
}
}
|
/*
* Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.db.generic.reg;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.types.registration.UserRequestState;
public interface RequestsSupplier
{
List<? extends UserRequestState<?>> getRequests(SqlSession sql) throws EngineException;
} |
package com.beike.wap.service;
import com.beike.wap.entity.MMerchantEvaluation;
public interface MMerchantEvaluationService {
public MMerchantEvaluation findByTrxorderId(Long trxorderId);
}
|
/* Strings.java
Purpose: String utilities and constants
Description:
History:
2001/4/17, Tom M. Yeh: Created.
Copyright (C) 2001 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.lang;
import org.zkoss.mesg.MCommon;
import org.zkoss.util.IllegalSyntaxException;
/**
* String utilties and constants
*
* @author tomyeh
*/
public class Strings {
/** Used with {@link #escape} to escape a string in
* JavaScript. It assumes the string will be enclosed with a single quote.
*/
public static final String ESCAPE_JAVASCRIPT = "'\n\r\t\f\\/!";
/**
* Returns true if the string is null or empty.
*/
public static final boolean isEmpty(String s) {
return s == null || s.length() == 0;
}
/**
* Returns true if the string is null or empty or pure blank.
*/
public static final boolean isBlank(String s) {
return s == null || s.trim().length() == 0;
}
/** Trims the string buffer by removing the leading and trailing
* whitespaces.
* Note: unlike String.trim(), you can specify the index of
* the first character to start trimming.
*
* <p>Like String.trim(), a whitespace is a character that has
* a code not great than <code>'\u0020'</code> (the space character)
*
* @param buf the string buffer to trim the leading and trailing.
* @param index the index of the first character to trim
* (i.e., consider as the leading character).
* If 0, it starts from the beginning.
* @return the same string buffer
* @since 3.0.4
*/
public static final StringBuffer trim(StringBuffer buf,
final int index) {
for (int j = index, len = buf.length();; ++j) {
if (j >= len) {
buf.delete(index, len);
break; //done
}
char cc = buf.charAt(j);
if (cc > ' ') { //same as String.trim()
buf.delete(index, j);
for (len = j = buf.length(); --j >= index;) {
cc = buf.charAt(j);
if (cc > ' ') { //same as String.trim()
buf.delete(j + 1, len);
break;
}
}
break; //done
}
}
return buf;
}
/** Returns an encoded string buffer, faster and shorter than
* Integer.toHexString. It uses numbers and lower-case leters only.
* Thus it is a valid variable name if prefix with an alphabet.
* At least one character is generated.
*
* <p>It works even in system that is case-insensitive, such as IE.
*
* <p>It is useful to generate a string to represent a number.
*/
public static final StringBuffer encode(StringBuffer sb, int val) {
if (val < 0) {
sb.append('z');
val = -val;
}
do {
int v = val & 31;
if (v < 10) {
sb.append((char)('0' + v));
} else {
sb.append((char)(v + ((int)'a' - 10)));
}
} while ((val >>>= 5) != 0);
return sb;
}
/** Returns an encoded string buffer, faster and shorter than
* Long.toHexString. It uses numbers and lower-case letters only.
* Thus it is a valid variable name if prefix with an alphabet.
* At least one character is generated.
*
* <p>It works even in system that is case-insensitive, such as IE.
*
* <p>It is useful to generate a string to represent a number.
*/
public static final StringBuffer encode(StringBuffer sb, long val) {
if (val < 0) {
sb.append('z');
val = -val;
}
do {
int v = ((int)val) & 31;
if (v < 10) {
sb.append((char)('0' + v));
} else {
sb.append((char)(v + ((int)'a' - 10)));
}
} while ((val >>>= 5) != 0);
return sb;
}
/** Returns an encoded string, faster and shorter than
* Long.toHexString.
*/
public static final String encode(int val) {
return encode(new StringBuffer(12), val).toString();
}
/** Returns an encoded string, faster and shorter than
* Long.toHexString.
*/
public static final String encode(long val) {
return encode(new StringBuffer(20), val).toString();
}
/** Returns the index of the give character in the given string buffer,
* or -1 if not found.
* It is equivalent to <code>sb.indexOf(""+cc, j);</code>, but faster.
* @since 5.0.3
*/
public static final int indexOf(StringBuffer sb, char cc, int j) {
for (int len = sb.length(); j < len; ++j)
if (sb.charAt(j) == cc)
return j;
return -1;
}
/** Returns the last index of the give character in the given string buffer,
* or -1 if not found.
* It is equivalent to <code>sb.lastIndexOf(""+cc, j);</code>, but faster.
* @since 5.0.3
*/
public static final int lastIndexOf(StringBuffer sb, char cc, int j) {
if (j >= sb.length())
j = sb.length() - 1;
for (; j >= 0; --j)
if (sb.charAt(j) == cc)
return j;
return -1;
}
/**
* Returns the index that is one of delimiters, or the length if none
* of delimiter is found.
*
* <p>Unlike String.indexOf(String, int), this method returns the first
* occurrence of <i>any</i> character in the delimiters.
*
* <p>This method is optimized to use String.indexOf(char, int)
* if it found the length of dilimiter is 1.
*
* @param src the source string to search
* @param from the index to start the search from
* @param delimiters the set of characters to search for
*
* @return the index that is one of delimiters.
* If return >= src.length(), it means no such delimiters
* @see #lastAnyOf
*/
public static final int anyOf(String src, String delimiters, int from) {
switch (delimiters.length()) {
case 0:
return src.length();
case 1:
final int j = src.indexOf(delimiters.charAt(0), from);
return j >= 0 ? j: src.length();
}
for (int len = src.length();
from < len && delimiters.indexOf(src.charAt(from)) < 0; ++from)
;
return from;
}
/**
* The backward version of {@link #anyOf}.
*
* <p>This method is optimized to use String.indexOf(char, int)
* if it found the length of dilimiter is 1.
*
* @return the previous index that is one of delimiter.
* If it is negative, it means no delimiter in front of
* <code>from</code>
* @see #anyOf
*/
public static final int lastAnyOf(String src, String delimiters, int from) {
switch (delimiters.length()) {
case 0:
return -1;
case 1:
return src.lastIndexOf(delimiters.charAt(0), from);
}
int len = src.length();
if (from >= len)
from = len - 1;
for (; from >= 0 && delimiters.indexOf(src.charAt(from)) < 0; --from)
;
return from;
}
/**
* Returns the next index after skipping whitespaces.
*/
public static final int skipWhitespaces(CharSequence src, int from) {
for (final int len = src.length();
from < len && Character.isWhitespace(src.charAt(from)); ++from)
;
return from;
}
/**
* The backward version of {@link #skipWhitespaces}.
*
* @return the next index that is not a whitespace.
* If it is negative, it means no whitespace in front of it.
*/
public static final int skipWhitespacesBackward(CharSequence src, int from) {
final int len = src.length();
if (from >= len)
from = len - 1;
for (; from >= 0 && Character.isWhitespace(src.charAt(from)); --from)
;
return from;
}
/** Returns the next whitespace.
*/
public static final int nextWhitespace(CharSequence src, int from) {
for (final int len = src.length();
from < len && !Character.isWhitespace(src.charAt(from)); ++from)
;
return from;
}
/** Escapes (aka, quote) the special characters with backslash.
* It prefix a backslash to any characters specfied in the specials
* argument.
*
* <p>Note: specials usually contains '\\'.
*
* <p>For example, {@link org.zkoss.util.Maps#parse} will un-quote
* backspace. Thus, if you want to preserve backslash, you have
* invoke escape(s, "\\") before calling Maps.parse().
*
* @param src the string to process. If null, null is returned.
* @param specials a string of characters that shall be escaped/quoted
* To escape a string in JavaScript code snippet, you can use {@link #ESCAPE_JAVASCRIPT}.
* @see #unescape
*/
public static final String escape(String src, String specials) {
if (src == null)
return null;
StringBuffer sb = null;
int j = 0;
l_out:
for (int j2 = 0, len = src.length();;) {
String enc = null;
char cc;
int k = j2;
for (;; ++k) {
if (k >= len)
break l_out;
cc = src.charAt(k);
if (shallEncodeUnicode(cc, specials)) {
enc = encodeUnicode(cc);
break;
}
if (specials.indexOf(cc) >= 0)
break;
}
if (enc == null
&& (cc = escapeSpecial(src, cc, k, specials)) == (char)0) {
j2 = k + 1;
continue;
}
if (sb == null)
sb = new StringBuffer(len + 4);
sb.append(src.substring(j, k)).append('\\');
if (enc != null) sb.append(enc);
else sb.append(cc);
j2 = j = k + 1;
}
if (sb == null)
return src; //nothing changed
return sb.append(src.substring(j)).toString();
}
private static char escapeSpecial(CharSequence src,
char cc, int k, String specials) {
switch (cc) {
case '\n': return 'n';
case '\t': return 't';
case '\r': return 'r';
case '\f': return 'f';
case '/':
//escape </script>
if (specials == ESCAPE_JAVASCRIPT //handle it specially
&& (k <= 0 || src.charAt(k - 1) != '<' || k + 8 > src.length()
|| !"script>".equalsIgnoreCase(src.subSequence(k+1, k+8).toString()))) {
return (char)0; //don't escape
}
break;
case '!':
//escape <!-- (ZK-676: it causes problem if used with <script>)
if (specials == ESCAPE_JAVASCRIPT //handle it specially
&& (k <= 0 || src.charAt(k - 1) != '<' || k + 3 > src.length()
|| !"--".equals(src.subSequence(k+1, k+3)))) {
return (char)0; //don't escape
}
break;
}
return cc;
}
/** @deprecated As of release 5.0.0, use {@link #escape(StringBuffer,CharSequence,String)}
* instead.
*/
public static final StringBuffer
appendEscape(StringBuffer sb, String src, String specials) {
return escape(sb, (CharSequence)src, specials);
}
/** Escapes (aka. quote) the special characters with backslash
* and appends it the specified string buffer.
*
* @param dst the destination buffer to append to.
* @param src the source to escape from.
* @param specials a string of characters that shall be escaped/quoted
* To escape a string in JavaScript code snippet, you can use {@link #ESCAPE_JAVASCRIPT}.
* @since 5.0.0
*/
public static final
StringBuffer escape(StringBuffer dst, CharSequence src, String specials) {
if (src == null)
return dst;
for (int j = 0, j2 = 0, len = src.length();;) {
String enc = null;
char cc;
int k = j2;
for (;; ++k) {
if (k >= len)
return dst.append((Object)src.subSequence(j, src.length()));
cc = src.charAt(k);
if (shallEncodeUnicode(cc, specials)) {
enc = encodeUnicode(cc);
break;
}
if (specials.indexOf(cc) >= 0)
break;
}
if (enc == null
&& (cc = escapeSpecial(src, cc, k, specials)) == (char)0) {
j2 = k + 1;
continue;
}
dst.append((Object)src.subSequence(j, k)).append('\\');
if (enc != null) dst.append(enc);
else dst.append(cc);
j2 = j = k + 1;
}
}
private static final boolean shallEncodeUnicode(char cc, String specials) {
return specials == ESCAPE_JAVASCRIPT && cc > (char)255
&& !Character.isLetterOrDigit(cc);
//don't check isSpaceChar since \u2028 will return true and it
//is not recoginized by firefox
}
/** Return "u????". */
private static final String encodeUnicode(int cc) {
final StringBuffer sb = new StringBuffer(6)
.append('u').append(Integer.toHexString(cc));
while (sb.length() < 5)
sb.insert(1, '0');
return sb.toString();
}
/** Un-escape the quoted string.
* @see #escape
*/
public static final String unescape(String s) {
if (s == null)
return null;
StringBuffer sb = null;
int j = 0;
for (int k; (k = s.indexOf('\\', j)) >= 0;) {
if (sb == null)
sb = new StringBuffer(s.length());
char cc = s.charAt(k + 1);
switch (cc) {
case 'n': cc = '\n'; break;
case 't': cc = '\t'; break;
case 'r': cc = '\r'; break;
case 'f': cc = '\f'; break;
}
sb.append(s.substring(j, k)).append(cc);
j = k + 2;
}
if (sb == null)
return s; //nothing changed
return sb.append(s.substring(j)).toString();
}
/**
* Returns the substring from the <code>from</code> index up to the
* <code>until</code> character or end-of-string.
* Unlike String.subsring, it converts \f, \n, \t and \r. It doesn't
* handle u and x yet.
*
* @return the result (never null). Result.next is the position of
* the <code>until</code> character if found, or
* a number larger than length() if no such character.
*/
public static final Result substring(String src, int from, char until) {
return substring(src, from, until, true);
}
/**
* Returns the substring from the <code>from</code> index up to the
* <code>until</code> character or end-of-string.
*
* @param escBackslash whether to treat '\\' specially (as escape char)
* It doesn't handle u and x yet.
* @return the result (never null). Result.next is the position of
* the <code>until</code> character if found, or
* a number larger than length() if no such character.
* You can tell which case it is by examining {@link Result#separator}.
*/
public static final
Result substring(String src, int from, char until, boolean escBackslash) {
final int len = src.length();
final StringBuffer sb = new StringBuffer(len);
for (boolean quoted = false; from < len; ++from) {
char cc = src.charAt(from);
if (quoted) {
quoted = false;
switch (cc) {
case 'f': cc = '\f'; break;
case 'n': cc = '\n'; break;
case 'r': cc = '\r'; break;
case 't': cc = '\t'; break;
}
} else if (cc == until) {
break;
} else if (escBackslash && cc == '\\') {
quoted = true;
continue; //skip it
}
sb.append(cc);
}
return new Result(from, sb.toString(), from < len ? until: (char)0);
}
/** Returns the next token with unescape.
* <ul>
* <li>It trims whitespaces before and after the token.</li>
* <li>It handles both '\'' and '"'. All characters between them are
* considered as a token.</li>
* <li>If nothing found before end-of-string, null is returned</li>
* </ul>
*
* If a separator is found, it is returned in
* {@link Strings.Result#separator}.
*
* @exception IllegalSyntaxException if the quoted string is unclosed.
*/
public static final
Result nextToken(String src, int from, char[] separators)
throws IllegalSyntaxException {
return nextToken(src, from, separators, true, true, false);
}
/** Returns the next token with additional options.
* It is the same as nextToken(src, from, separators, escBackslash, quotAsToken, false);
* Refer to {@link #nextToken(String, int, char[], boolean, boolean, boolean)}
* for more infomation.
*
* @exception IllegalSyntaxException if the quoted string is unclosed.
* @see #nextToken(String, int, char[], boolean, boolean, boolean)
*/
public static final Result nextToken(String src, int from,
char[] separators, boolean escBackslash, boolean quotAsToken)
throws IllegalSyntaxException {
return nextToken(src, from, separators, escBackslash, quotAsToken, false);
}
/** Returns the next token with additional options.
*
* <ul>
* <li>It trims whitespaces before and after the token.</li>
* <li>If quotAsToken is true, all characters between quotations
* ('\'' or '"') are considered as a token.</li>
* <li>If parenthesis is true, the separators and quots inside
* a pair of parenthesis won't be treated specially.
* It is useful if EL expressions might be contained.</li>
* <li>Consider '\\' as the escape char if escBackslash is true.</li>
* <li>If nothing found before end-of-string, null is returned</li>
* </ul>
*
* If a separator is found, it is returned in
* {@link Strings.Result#separator}.
*
* @param escBackslash whether to treat '\\' specially (as escape char)
* It doesn't handle u and x yet.
* @param quotAsToken whether to treat characters inside '\'' or '"'
* as a token. Note: the quots are excluded from the token.
* @param parenthesis whether to ignore separators and quots in side
* a pair of parenthesises. Recognized parentheseses include
* {}, [] or ().
* @exception IllegalSyntaxException if the quoted string is unclosed.
* @since 3.0.6
*/
public static final Result nextToken(String src, int from,
char[] separators, boolean escBackslash, boolean quotAsToken,
boolean parenthesis)
throws IllegalSyntaxException {
final int len = src.length();
from = skipWhitespaces(src, from);
if (from >= len)
return null; //end-of-string
//1. handle quoted
final char cc = src.charAt(from);
if (quotAsToken && (cc == '\'' || cc == '"')) {
final Result res = substring(src, from + 1, cc, escBackslash);
if (res.separator != cc)
throw new IllegalSyntaxException(MCommon.QUOTE_UNMATCHED, src);
res.next = skipWhitespaces(src, res.next + 1);
if (res.next < len && isSeparator(src.charAt(res.next), separators))
++res.next;
return res;
}
//2. handle not-quoted
final int j = nextSeparator(src, from, separators,
escBackslash, false, quotAsToken, parenthesis);
int next = j;
if (j < len) {
if (quotAsToken) {
final char c = src.charAt(j);
if (c != '\'' && c != '"')
++next;
} else {
++next;
}
}
if (j == from) //nothing but separator
return new Result(next, "", src.charAt(j));
int k = 1 + skipWhitespacesBackward(src, j - 1);
return new Result(next,
k > from ? escBackslash ?
unescape(src.substring(from, k)) : src.substring(from, k): "",
j < len ? src.charAt(j): (char)0);
//if the token is nothing but spaces, k < from
}
/** Returns the next seperator index in the src string.
*
* @param escQuot whether to escape characters inside quotations
* ('\'' or '"'). In other words, ignore separators inside quotations
* @param quotAsSeparator whether to consider quotations as one of
* the separators
* @since 2.4.0
*/
public static int nextSeparator(String src, int from, char[] separators,
boolean escBackslash, boolean escQuot, boolean quotAsSeparator) {
return nextSeparator(src, from, separators, escBackslash, escQuot,
quotAsSeparator, false);
}
/** Returns the next seperator index in the src string.
*
* @param escQuot whether to escape characters inside quotations
* ('\'' or '"'). In other words, it specifies whether to ignore
* separators inside quotations
* @param quotAsSeparator whether to consider quotations as one of
* the separators.
* If escQuot is true, quotAsSeparator is ignored.
* @param parenthesis whether to ignore separators and quots in side
* a pair of parenthesises. Recognized parentheseses include
* {}, [] or ().
* @since 3.0.6
*/
public static int nextSeparator(String src, int from, char[] separators,
boolean escBackslash, boolean escQuot, boolean quotAsSeparator,
boolean parenthesis) {
boolean esc = false;
char quot = (char)0, endparen;
for (final int len = src.length(); from < len; ++from) {
if (esc) {
esc = false;
continue;
}
final char cc = src.charAt(from);
if (escBackslash && cc == '\\') {
esc = true;
} else if (quot != (char)0) {
if (cc == quot)
quot = (char)0;
} else if (escQuot && (cc == '\'' || cc == '"')) {
quot = cc;
} else if ((quotAsSeparator && (cc == '\'' || cc == '"'))
|| isSeparator(cc, separators)) {
break;
} else if (parenthesis
&& (endparen = getEndingParenthesis(cc)) != (char)0) {
from = skipParenthesis(src, from, cc, endparen);
if (from >= len) break; //don't increase
}
}
return from;
}
/** Returns the ending parenthesis (such as }),
* or (char)0 if cc is not the beginning parenthsis (such as {).
*/
private static final char getEndingParenthesis(char cc) {
return cc == '{' ? '}': cc == '(' ? ')': cc == '[' ? ']': (char)0;
}
/** Skip the string enclosed by a pair of parenthesis and
* return index after the ending parenthesis.
* @param j the index of the starting parenthesis
*/
private static int skipParenthesis(String src, int j, char beg, char end) {
for (int len = src.length(), depth = 0; ++j < len;) {
final char cc = src.charAt(j);
if (cc == '\\') ++j; //skip next
else if (cc == beg) ++depth;
else if (cc == end && --depth < 0)
break;
}
return j;
}
private static final boolean isSeparator(char cc, char[] separators) {
for (int j = 0; j < separators.length; ++j) {
if (cc == separators[j]
|| (separators[j] == ' ' && Character.isWhitespace(cc)))
return true;
}
return false;
}
/** The result of {@link #substring}.
*/
public static class Result {
/** The next index. */
public int next;
/** The converted string. */
public String token;
/** The separator found. If no separator but end-of-line found,
* ((char)0) is returned.
*/
public char separator;
protected Result(int next, String token, char separator) {
this.next = next;
this.token = token;
this.separator = separator;
}
protected Result(int next, char separator) {
this.next = next;
this.separator = separator;
}
//-- Object --//
public String toString() {
return "[next="+next+", token="+token+" separator="+separator+']';
}
}
}
|
package bai1;
public class MyClass {
public static void main(String[] args) {
demo1 demo = new demo1();
demo.input();
demo.output();
demo.getThueNhapKhau();
}
}
|
/*
* 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 controlador;
import Modelo.Programa;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
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 javax.servlet.http.HttpSession;
import persistencia.Avances;
/**
*
* @author gateway1
*/
@WebServlet(name = "formaravance", urlPatterns = {"/formaravance"})
public class formaravance extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
private ArrayList<String> alldepcharge(ArrayList arr) {
arr.add("corte");
arr.add("fechacor");
arr.add("cormaq");
arr.add("precorte");
arr.add("fechaprecor");
arr.add("precormaq");
arr.add("pespunte");
arr.add("fechapes");
arr.add("pesmaq");
arr.add("deshebrado");
arr.add("fechades");
arr.add("desmaq");
arr.add("ojillado");
arr.add("fechaoji");
arr.add("ojimaq");
arr.add("inspeccion");
arr.add("fechainsp");
arr.add("inspmaq");
arr.add("preacabado");
arr.add("fechaprea");
arr.add("preamaq");
arr.add("montado");
arr.add("fechamont");
arr.add("montmaq");
arr.add("prodt");
arr.add("fechapt");
arr.add("ptmaq");
return arr;
}
private ArrayList<String> depaload(ArrayList arr) throws ClassNotFoundException, SQLException {
arr.add("corte");
arr.add("precorte");
arr.add("pespunte");
arr.add("deshebrado");
arr.add("ojillado");
arr.add("inspeccion");
arr.add("preacabado");
arr.add("montado");
arr.add("prodt");
return arr;
}
//Aqui me quede0000
private void Autoupdate_Stoplote(ArrayList<String> arr, int k, int a, String fecha, Avances avan, String banda, String charmaquila) throws SQLException, ClassNotFoundException {
k += 3;
for (int i = k - 3; i < k; i++) {
//System.out.println(arr.get(i)+"-"+a+"-"+k);
if (avan.buscardepa(arr, i, a).equals("0")) {
avan.Autoupdate_lotes(a, fecha, arr, i, banda, charmaquila);
i += 2;
} else {
i += 2;
}
}
avan.modiavancestatus(arr, k - 3, String.valueOf(a), fecha, banda, charmaquila);
}
private void Autoupdate_Stoplote_v2(ArrayList<String> arr, int k, int a, String fecha, Avances avan, String banda, String charmaquila) throws SQLException, ClassNotFoundException {
k += 3;
for (int i = 0; i < k; i++) {
//System.out.println(arr.get(i)+"-"+a+"-"+k);
if (avan.buscardepa(arr, i, a).equals("0")) {
avan.Autoupdate_lotes(a, fecha, arr, i, banda, charmaquila);
i += 2;
} else {
i += 2;
}
}
avan.modiavancestatus(arr, k - 3, String.valueOf(a), fecha, banda, charmaquila);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
try {
HttpSession objSesion = request.getSession(false);
objSesion.invalidate();
response.sendRedirect("index.jsp");
} catch (Exception e) {
response.sendRedirect("index.jsp");
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
HttpSession objSesion = request.getSession(false);
//i_d
boolean estado;
String usuario = (String) objSesion.getAttribute("usuario");
String tipos = (String) objSesion.getAttribute("tipo");
String ids = String.valueOf(objSesion.getAttribute("i_d"));
//out.print(carrito.size());
// out.println("" + tipos+"/"+ids);
if (usuario != null && tipos != null && tipos.equals("BASICO") || tipos.equals("MEDIOBASICO") || tipos.equals("PREINTERMEDIO") || tipos.equals("INTERMEDIO") || tipos.equals("ADMIN")) {
//out.println(carrito.size());
} else {
response.sendRedirect("index.jsp");
}
Calendar fecha = Calendar.getInstance();
int año = fecha.get(Calendar.YEAR);
int mes = fecha.get(Calendar.MONTH) + 1;
int dia = fecha.get(Calendar.DAY_OF_MONTH);
int hora = fecha.get(Calendar.HOUR_OF_DAY);
int minuto = fecha.get(Calendar.MINUTE);
int segundo = fecha.get(Calendar.SECOND);
String fechac = año + "/" + mes + "/" + dia;
String horas = hora + ":" + minuto;
String charmaquila = null;
String maquila = request.getParameter("marcas");
String codigo = request.getParameter("codigo");
String banda = request.getParameter("banda");
String depar = request.getParameter("depar");
int k = 0, k2 = 0;
String a = "";
int b = 0;
//carga de lista con departamento,fecha y maquila
ArrayList<String> array = new ArrayList<>();
ArrayList<String> array2 = new ArrayList<>();
PrintWriter out = response.getWriter();
//System.out.println(maquila + "/" + codigo + "/montado banda: " + banda);
if (maquila.equals("PLANTA") && (tipos.equals("BASICO")) || tipos.equals("MEDIOBASICO")) {//planta
// System.out.println("PLANTA");
boolean respuesta;
try {
ArrayList<String> loadprog = new ArrayList<>();
Avances av = new Avances();
String autofill = av.check_autofill();// autoavance
charmaquila = "PL";
Programa pr = new Programa();
// carga de datos sobre listas
array = alldepcharge(array); // carga en un arreglo las columnas de la bd de avance
array2 = depaload(array2);// carga todos los departamentos disponibles
b = av.searchcod(codigo);// asignar id del programa a una variable
pr = av.getprogcode(b); // asignar programa buscando por el id previamente obtenido
// verifica que nos haya devuelto un id distinto a cero
if (b == 0) {
//registro de lote por desfase o lote inexistente.
av.loglote(codigo, String.valueOf(pr.getPrograma()), fechac, usuario + banda, String.valueOf(b));
out.println("<label style=color:red>Lote inexistente, intentelo de nuevo</label>");
} else {// Inicio de verificacion y actualizacion de avances
a = String.valueOf(b);// asignar id a otra variable
loadprog = av.getprogavances(a);// carga programa mediante id
//inicio es corte
if (array2.get(0).equals(usuario)) {
respuesta = av.avanceprimerdep(a, fechac, charmaquila, array, array2);
if (respuesta) {
av.modiavancestatus(array, k, a, fechac, charmaquila);
out.println("<label style=color:green>Avance Completo Exitosamente:)</label>");
} else {
out.println("<label>Ya existe Avance de este departamento</label>");
}
} else {
// de precorte en adelante esto es lo que prosigue\
//Establecer punto donde se encuentra el departamento en la lista
for (int i = 0; i < array.size(); i++) {
if (array.get(i).equals(usuario)) {
k = i;
i = array.size();
}
}
if (av.verificaraiz(array, k, a)) {// inicio de verificacion del usuario con la lista
if (av.checkback(array, k, a) || usuario.equals("preacabado")) {//verifica el departamento anterior
if (usuario.equals("preacabado")) {//solo si el usuario es preacabado
if (av.checkmontado(array, k, a)) {// verifica avance en montado
av.loglote(String.valueOf(pr.getLote()), String.valueOf(pr.getPrograma()), fechac, usuario + banda, a);//avance en montado
out.println("<label style=color:red>No se puede realizar avance de preacabado si ya se tiene montado, Contacte a un administrador</label>");
} else {
av.avancespreaca(a, fechac, charmaquila, array, k);// avance solo para preacabado solo si montado dio avance
out.println("<label style=color:green>Avance Completo Exitosamente:)</label>");
}
} else if (usuario.equals("montado")) {//entra a usuariomontado
if (av.checkpremontado(array, k, a)) {//verifica inspeccion de calidad
av.avancesmontado(a, fechac, charmaquila, array, k, banda);// actualiza datos de acuerdo a el avance de montado
av.modiavancestatus(array, k, a, fechac, banda, charmaquila);// actualiza registro en el programa
out.println("<label style=color:green>Avance Completo Exitosamente:)</label>");
} else {
av.loglote(String.valueOf(pr.getLote()), String.valueOf(pr.getPrograma()), fechac, (usuario + banda), a);
if (autofill.equals("1")) {
Autoupdate_Stoplote(array, k, Integer.parseInt(a), fechac, av, banda, charmaquila);// solomodifica el departamento quien solicitoel avance
//Autoupdate_Stoplote_v2(array,k,Integer.parseInt(a),fechac,av,banda,charmaquila); este segundo metodo rellena todos los depas anteriores.
}
out.println("<label style=color:red>Falta Captura de Inspeccion de calidad o Preacabado</label>");
}
} else {
av.avances(a, fechac, charmaquila, array, k, (array.size() - 1), fechac);
out.println("<label style=color:green>Avance Completo Exitosamente:)</label>");
if (array.get(k).equals(array.get(array.size() - 3))) {
av.modiavancestatus(a);
} else {
av.modiavancestatus(array, k, a, fechac, charmaquila);
}
}
} else {
av.loglote(String.valueOf(pr.getLote()), String.valueOf(pr.getPrograma()), fechac, usuario + banda, a);
if (autofill.equals("1") || usuario.equals("deshebrado") || usuario.equals("ojillado") || usuario.equals("inspeccion")) {
Autoupdate_Stoplote(array, k, Integer.parseInt(a), fechac, av, banda, charmaquila);
out.println("<label style=color:green>Avance Completo</label>");
} else {
out.println("<label style=color:red>Falta captura del departamento anterior</label>");
}
}
} else {
out.println("<label>Ya existe Avance de este departamento</label>");
}
}
}
if (loadprog.isEmpty()) {
} else {
out.println(" <div class=\"row\" style=\"padding-top: 15px\">\n"
+ " <div class=\"col-sm-4\">\n"
+ " <label class=\"ln\">PROGRAMA:" + loadprog.get(0) + "</label><br>\n"
+ " <label class=\"ln\">LOTE:" + loadprog.get(5) + "</label> \n"
+ " </div>\n"
+ " <div class=\"col-sm-4\">\n"
+ " <label class=\"ln\">ESTILO:" + loadprog.get(1) + "</label><br>\n"
+ " <label class=\"ln\">PARES:" + loadprog.get(2) + "</label> \n"
+ " </div>\n"
+ " <div class=\"col-sm-4\">\n"
+ " <label class=\"ln\">COMBINACION:" + loadprog.get(3) + "</label>\n"
+ " </div> <div class=\"col-sm-4\">\n"
+ " <label class=\"ln\">TERMINO :" + loadprog.get(6) + "</label>\n"
+ " </div>\n"
+ " </div>");
}
} catch (Exception e) {
response.sendRedirect("../index.jsp");
Logger.getLogger(Avances.class.getName()).log(Level.SEVERE, null, e);
}
} else if (tipos.equals("PREINTERMEDIO") || tipos.equals("INTERMEDIO") || tipos.equals("ADMIN")) { // es practicamente lo mismo que en planta solo que aqui se elige el departamento para dar avance
String maquilas = request.getParameter("maquila");
String depmaquila = request.getParameter("depmaquila");
boolean respuesta;
try {
ArrayList<String> loadprog = new ArrayList<>();
Avances av = new Avances();
String autofill = av.check_autofill_m();
System.out.println(maquilas+"-"+depmaquila);
charmaquila = String.valueOf(maquilas.charAt(0)+String.valueOf(maquilas.charAt(1)));
System.out.println(charmaquila);
// carga de datos sobre listas
array = alldepcharge(array);
array2 = depaload(array2);
b = av.searchcod(codigo);
Programa pr = new Programa();
pr = av.getprogcode(b);
// verifica que nos haya devuelto un id distinto a cero
if (b == 0) {
av.loglote(codigo, String.valueOf(pr.getPrograma()), fechac, usuario + banda, String.valueOf(b));
out.println("<label>LOTE NO ENCONTRADO, VUELVA A INTERNTARLO O LLAME A UN ADMINISTRADOR</label>");
} else {
a = String.valueOf(b);
loadprog = av.getprogavances(a);
//inicio es corte
if (array2.get(0).equals(depmaquila)) { // avance solo para corte ya que es el inicio
respuesta = av.avanceprimerdep(a, fechac, charmaquila, array, array2);
if (respuesta) {
av.modiavancestatus(array, k, a, fechac, charmaquila);// si el avance no existe modifica el registro
out.println("<label>Avance Completo Exitosamente :)</label>");
} else {// si ya existe solo manda un mensaje
out.println("<label>Ya existe Avance de este departamento</label>");
}
} else {
// de precorte en adelante esto es lo que prosigue\
//Establecer punto donde se encuentra el departamento en la lista
for (int i = 0; i < array.size(); i++) {
if (array.get(i).equals(depmaquila)) {
k = i;
i = array.size();
}
}
if (av.verificaraiz(array, k, a)) {// inicio de verificacion del usuario con la lista
if (av.checkback(array, k, a) || depmaquila.equals("preacabado")) {//verifica el departamento anterior
if (depmaquila.equals("preacabado")) {//solo si el usuario es preacabado
if (av.checkmontado(array, k, a)) {
av.loglote(String.valueOf(pr.getLote()), String.valueOf(pr.getPrograma()), fechac, usuario + banda, a);
out.println("<label>No se puede realizar avance de preacabado si ya se tiene montado, Contacte a un administrador</label>");
} else {
av.avancespreaca(a, fechac, charmaquila, array, k);
out.println("<label>Avance Completo Exitosamente:)</label>");
}
} else if (depmaquila.equals("montado")) {//entra a usuariomontado
if (av.checkpremontado(array, k, a)) {//verifica inspeccion de calidad
av.avancesmontado(a, fechac, charmaquila, array, k, banda);
av.modiavancestatus(array, k, a, fechac, charmaquila);
out.println("<label>Avance Completo Exitosamente:)</label>");
} else {// si aun no se tiene avance de inspeccion
av.loglote(String.valueOf(pr.getLote()), String.valueOf(pr.getPrograma()), fechac, usuario + banda, a);
out.println("<label>Falta Captura de Inspeccion de calidad</label>");
if (autofill.equals("1")) {
Autoupdate_Stoplote(array, k, Integer.parseInt(a), fechac, av, banda, charmaquila);
}
}
} else {
av.avances(a, fechac, charmaquila, array, k, (array.size() - 1), fechac);
out.println("<label>Avance Completo Exitosamente:)</label>");
if (array.get(k).equals(array.get(array.size() - 3))) {
av.modiavancestatus(a);
} else {
av.modiavancestatus(array, k, a, fechac, charmaquila);
}
}
} else {
av.loglote(String.valueOf(pr.getLote()), String.valueOf(pr.getPrograma()), fechac, usuario + banda, a);// inserta incidencia en bd
if (autofill.equals("1")) {// verifica si esta habilitada la opcion de avance automatico
Autoupdate_Stoplote(array, k, Integer.parseInt(a), fechac, av, banda, charmaquila);// ejecuta funcion de avance automatico
out.println("<label style=color:green>Completo exitosamente :)</label>");
}
}
} else {
out.println("<label>Ya existe Avance de este departamento</label>");
}
}
}
if (loadprog.isEmpty()) {
} else {
out.println(" <div class=\"row\" style=\"padding-top: 15px\">\n"
+ " <div class=\"col-sm-4\">\n"
+ " <label class=\"ln\">PROGRAMA:" + loadprog.get(0) + "</label><br>\n"
+ " <label class=\"ln\">LOTE:" + loadprog.get(5) + "</label> \n"
+ " </div>\n"
+ " <div class=\"col-sm-4\">\n"
+ " <label class=\"ln\">ESTILO:" + loadprog.get(1) + "</label><br>\n"
+ " <label class=\"ln\">PARES:" + loadprog.get(2) + "</label> \n"
+ " </div>\n"
+ " <div class=\"col-sm-4\">\n"
+ " <label class=\"ln\">COMBINACION:" + loadprog.get(3) + "</label>\n"
+ " </div><div class=\"col-sm-4\">\n"
+ " <label class=\"ln\">TERMINO :" + loadprog.get(6) + "</label>\n"
+ " </div> \n"
+ " </div>");
}
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
Logger.getLogger(Avances.class.getName()).log(Level.SEVERE, null, e);
} catch (Exception e) {
response.sendRedirect("index.jsp");
System.out.println(e.getMessage());
Logger.getLogger(Avances.class.getName()).log(Level.SEVERE, null, e);
}
}
}
/**
* Returns a short description of the servlet.
*
*
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.dangel.db;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.uqbarproject.jpa.java8.extras.PerThreadEntityManagers;
public class Main {
private static EntityManager manager;
private static EntityManagerFactory emf;
public static void main(String[] args) {
EntityManager entityManager = PerThreadEntityManagers.getEntityManager();
EntityTransaction transaccion = entityManager.getTransaction();
// emf = Persistence.createEntityManagerFactory("Persistencia");
// manager = emf.createEntityManager();
// List<Entrenador> entrenadores = (List<Entrenador>) manager.createQuery("FROM Entreador").getResultList();
// System.out.println("En esta base de datos hay" + entrenadores.size() + "entrenadores");
// DateTime fecha = new DateTime("1991-09-09");
// Entrenador trainer1 = new Entrenador(1L, "ash", "ket", fecha);
transaccion.begin();
//LocalDate fecha = new LocalDate("1991-09-09");
Entrenador trainer1 = new Entrenador(1L, "ash", "ket");
entityManager.persist(trainer1);
Entrenador trainer2 = new Entrenador();
trainer2.setCodigo(2L);
trainer2.setNombre("dario");
trainer2.setApellido("angel");
entityManager.persist(trainer2);
transaccion.commit();
}
}
|
package com.gaoshin.sorma.browser;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import android.database.Cursor;
public class TableContentCursorInputStream extends InputStream {
private Cursor cursor;
private boolean init = true;
private boolean firstRecord = true;
private boolean done = false;
private int size;
private int offset;
private int currentRow;
private boolean showDetails = false;
private LinkedList<Byte> queue = new LinkedList<Byte>();
public TableContentCursorInputStream(Cursor cursor, int offset, int size, boolean showDetails) throws IOException {
this.cursor = cursor;
this.showDetails = showDetails;
if(offset > 0 && cursor!=null) {
cursor.move(offset);
}
this.size = size;
this.offset = offset;
currentRow = -1;
}
@Override
public int read() throws IOException {
if (queue.size() == 0) {
readMore();
}
if (queue.size() == 0) {
return -1;
}
return queue.removeFirst().intValue();
}
private void readMore() throws IOException {
if(done) {
return;
}
if (init) {
init = false;
String header = "<html><body><table style='border:solid 1px;'>";
putToQueue(header);
return;
}
StringBuilder sb = new StringBuilder();
if (cursor.moveToNext() && size>0) {
currentRow++;
size--;
int count = cursor.getColumnCount();
if (firstRecord) {
firstRecord = false;
sb.append("<tr>");
for (int i = 0; i < count; i++) {
sb.append("<th style='border:solid 1px #ccc;padding:1px;'>");
sb.append(cursor.getColumnName(i));
sb.append("</th>");
}
sb.append("</tr>");
}
sb.append("<tr onClick='window.location=window.location.href+\"&detail=1&size=1&offset=" + (offset + currentRow) + "\"'>");
for (int i = 0; i < count; i++) {
String value;
if (cursor.isNull(i)) {
value = "null";
} else {
try {
value = cursor.getString(i);
if (value.length() == 0)
value = " ";
} catch (Exception e) {
value = "---";
try {
byte[] content = cursor.getBlob(i);
if (content != null) {
value = "blob " + content.length;
}
content = null;
}
catch (Exception e1) {
}
}
int length = value.length();
if(!showDetails && length > 32) {
value = (value.substring(0, 8)) + ("...") + (value.substring(length-24, length));
}
}
String columnName = cursor.getColumnName(i);
sb.append("<td class='" + columnName
+ "' style='border:solid 1px #ccc;padding:1px;'>");
sb.append(value);
sb.append("</td>");
}
sb.append("</tr>");
putToQueue(sb.toString());
} else {
putToQueue("</table></body></html>");
if (cursor != null) {
try {
cursor.close();
} catch (Exception e) {
}
}
done = true;
}
}
private void putToQueue(String s) throws IOException {
for (byte b : s.getBytes()) {
queue.add(b);
}
}
}
|
package com.Nikolovska.spring.HRManagement.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.Nikolovska.spring.HRManagement.model.Employee;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
List<Employee> findByUsernameAndPassword(String username, String password);
Optional<Employee> findById(Long id);
}
|
package com.project.alex.ServiceDiscipline;
import lombok.Data;
import org.springframework.stereotype.Component;
import javax.persistence.*;
@Data
@Entity
public class HoursLPL {
@Id
@GeneratedValue(strategy= GenerationType.AUTO, generator = "hoursL")
private int id;
private int hoursLabs;
private int hoursLecture;
private int hoursPractice;
}
|
package com.yc.education.controller.sale;
import com.github.pagehelper.PageInfo;
import com.yc.education.controller.BaseController;
import com.yc.education.model.DataSetting;
import com.yc.education.model.DepotProperty;
import com.yc.education.model.basic.ProductBasic;
import com.yc.education.model.sale.*;
import com.yc.education.service.DataSettingService;
import com.yc.education.service.sale.ISaleOfferProductService;
import com.yc.education.service.sale.ISaleQuotationService;
import com.yc.education.util.AppConst;
import com.yc.education.util.StageManager;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
/**
* 报价单导入 -- 查询
*/
@Controller
public class QuotationImportController extends BaseController implements Initializable {
@Autowired ISaleQuotationService iSaleQuotationService;
@Autowired ISaleOfferProductService iSaleOfferProductService;
@Autowired DataSettingService iDataSettingService;
@FXML VBox menu_first; // 第一页
@FXML VBox menu_prev; // 上一页
@FXML VBox menu_next; // 下一页
@FXML VBox menu_last; // 最后一页
@FXML CheckBox che_recently; // 最近单据
@FXML CheckBox che_audit; // 已审核
@FXML TextField num; // 数量
@FXML
Button client_sure;
@FXML TableView tab_order;
@FXML TableColumn col_order_id;
@FXML TableColumn col_order_no;
@FXML TableColumn col_order_date;
@FXML TableColumn col_order_valid_until; //有效期至
@FXML TableColumn col_order_customer_no;
@FXML TableColumn col_order_customer_name;
@FXML TableColumn col_order_status;
@FXML TableView tab_product;
@FXML TableColumn tab_product_che;
@FXML TableColumn tab_product_id;
@FXML TableColumn tab_product_no;
@FXML TableColumn tab_product_name;
@FXML TableColumn tab_product_num;
@FXML TableColumn tab_product_unit;
@FXML TableColumn tab_product_price;
@FXML TableColumn tab_product_money;
@FXML TableColumn tab_product_remark;
// 订单编号
private static String orderid = "";
// 查询订单中产品
ObservableList<SaleQuotationImportProductProperty> importData = FXCollections.observableArrayList();
// 导入选中的产品 -- 订货单
ObservableList<SalePurchaseOrderProductProperty> importPurchaseData = FXCollections.observableArrayList();
// 导入选中的产品 -- 销货单
ObservableList<SaleGoodsProductProperty> importSaleGoodsData = FXCollections.observableArrayList();
@Override
public void initialize(URL location, ResourceBundle resources) {
setMenuValue(1);
importData = FXCollections.observableArrayList();
importPurchaseData = FXCollections.observableArrayList();
importSaleGoodsData = FXCollections.observableArrayList();
}
/**
* @Description 模糊查询
* @Author BlueSky
* @Date 12:00 2019/4/11
**/
@FXML
public void textQuery(){
setMenuValue(1);
}
/**
* 给翻页菜单赋值
* @param page
*/
private void setMenuValue(int page){
int rows = pageRows(che_recently,num);
boolean audit = che_audit.isSelected();
List<SaleQuotation> quotationList = iSaleQuotationService.listSaleQuotationAll("",audit?"1":"",page, rows);
if(quotationList != null && quotationList.size() >0){
PageInfo<SaleQuotation> pageInfo = new PageInfo<>(quotationList);
menu_first.setUserData(pageInfo.getFirstPage());
menu_prev.setUserData(pageInfo.getPrePage());
menu_next.setUserData(pageInfo.getNextPage());
menu_last.setUserData(pageInfo.getLastPage());
initData(quotationList);
}else {
tab_order.setItems(null);
}
}
/**
* 分页
* @param event
*/
public void pages(MouseEvent event){
Node node =(Node)event.getSource();
if(node.getUserData() != null){
int page =Integer.parseInt(String.valueOf(node.getUserData()));
setMenuValue(page);
}
}
/**
* 关闭导入窗口
*/
@FXML
public void closeImprotWin(){
Stage stage=(Stage)client_sure.getScene().getWindow();
StageManager.CONTROLLER.remove("PurchaseOrderControllerImport");
StageManager.CONTROLLER.remove("SaleGoodsControllerImportQuotation");
importData.clear();
importPurchaseData.clear();
importSaleGoodsData.clear();
stage.close();
}
/**
* 确认按钮-关闭窗口
*/
@FXML
public void sureCloseImportWin(){
if(orderid != null && !"".equals(orderid)){
int rows = 1;
// 销售 - 订货单
PurchaseOrderController orderController = (PurchaseOrderController) StageManager.CONTROLLER.get("PurchaseOrderControllerImport");
if(orderController != null){
SaleQuotation quotation = iSaleQuotationService.selectByKey(Long.valueOf(orderid));
if(!quotation.getOrderAudit()){
alert_informationDialog("该单据未审核或已作废暂无法进行导出");
return;
}
// 把选中订单数据加载到订货单上
orderController.setBasicImportVal(quotation);
orderController.relation.setBeRelationId(quotation.getId());
orderController.relation.setBeRelationName("报价单");
// 把报价单中的选中产品加载到订货单的订货产品中
for (SaleQuotationImportProductProperty p : importData) {
if(p.isChecked() && p.getId() != null && p.getId()>0){
SaleOfferProduct product = iSaleOfferProductService.selectByKey(p.getId());
DepotProperty depotProperty = new DepotProperty();
ProductBasic productBasic = getProductBasic(p.getProductNo());
if(productBasic != null){
depotProperty = getDepot(productBasic.getInventoryplace());
}
totalCost(p.getNum()==null||"".equals(p.getNum())?0:Integer.valueOf(p.getNum()),p.getMoney()==null||"".equals(p.getMoney())?new BigDecimal("0.00"):new BigDecimal(p.getMoney()),quotation.getTax(), orderController.total_num, orderController.tax_total, orderController.total_loan, orderController.total_money);
importPurchaseData.add(new SalePurchaseOrderProductProperty( rows++, product.getProductNo(), product.getProductName(), product.getCategory(), product.getNum(), product.getUnit(), product.getPricing(), product.getDiscount(), product.getPrice(), product.getMoney(), quotation.getOfferNo(), "报价单", depotProperty.getDepotOrder(),depotProperty.getDepotFloor(),product.getRemark()));
}
}
if(importPurchaseData != null){
orderController.generalProductTab(importPurchaseData);
}
orderController.setControllerUse();
}
// 销售 - 销货单
SaleGoodsController saleGoodsController = (SaleGoodsController) StageManager.CONTROLLER.get("SaleGoodsControllerImportQuotation");
if(saleGoodsController != null){
SaleQuotation quotation = iSaleQuotationService.selectByKey(Long.valueOf(orderid));
if(!quotation.getOrderAudit()){
alert_informationDialog("该单据未审核或已作废暂无法进行导出");
return;
}
// 把选中订单数据加载到销货单上
saleGoodsController.setBasicImportQuotationVal(quotation);
saleGoodsController.relation.setBeRelationId(quotation.getId());
saleGoodsController.relation.setBeRelationName("报价单");
// 把报价单中的选中产品加载到销货单的销货产品中
if(saleGoodsController.product_table.getItems() != null){
importSaleGoodsData = saleGoodsController.product_table.getItems();
}
for (SaleQuotationImportProductProperty p : importData) {
if(p.isChecked() && p.getId() != null && p.getId()>0){
SaleOfferProduct product = iSaleOfferProductService.selectByKey(p.getId());
DepotProperty depotProperty = new DepotProperty();
ProductBasic productBasic = getProductBasic(p.getProductNo());
if(productBasic != null){
depotProperty = getDepot(productBasic.getInventoryplace());
}
totalCost(p.getNum()==null||"".equals(p.getNum())?0:Integer.valueOf(p.getNum()),p.getMoney()==null||"".equals(p.getMoney())?new BigDecimal("0.00"):new BigDecimal(p.getMoney()),quotation.getTax(), saleGoodsController.total_num, saleGoodsController.total_tax, saleGoodsController.total_loan, saleGoodsController.total_money);
importSaleGoodsData.add(new SaleGoodsProductProperty(rows++,"报价单",quotation.getOfferNo(), product.getProductNo(), product.getProductName(), product.getCategory(), product.getNum(), product.getUnit(), product.getPricing(), product.getDiscount(), product.getPrice(), product.getMoney(), depotProperty.getDepotOrder(), depotProperty.getDepotFloor(), product.getRemark()));
}
}
if(importSaleGoodsData != null){
saleGoodsController.generalProductTab(importSaleGoodsData);
}
saleGoodsController.setControllerUse();
}
}
closeImprotWin();
}
/**
* 初始化报价单信息
*/
private void initData(List<SaleQuotation> list){
try {
list.forEach(p->{
p.setCreateDateStr(new SimpleDateFormat("yyyy-MM-dd").format(p.getCreateDate()));
p.setValidUntilStr(new SimpleDateFormat("yyyy-MM-dd").format(p.getValidUntil()));
if(p.getOrderAudit() != null && p.getOrderAudit()){
p.setAuditStatus("已审核");
}else{
p.setAuditStatus("未审核");
}
});
}catch (Exception e){
e.printStackTrace();
}
// 查询客户集合
final ObservableList<SaleQuotation> data = FXCollections.observableArrayList(list);
col_order_id.setCellValueFactory(new PropertyValueFactory("id"));
col_order_no.setCellValueFactory(new PropertyValueFactory("offerNo"));
col_order_date.setCellValueFactory(new PropertyValueFactory("createDateStr"));//映射
col_order_valid_until.setCellValueFactory(new PropertyValueFactory("validUntilStr"));
col_order_customer_no.setCellValueFactory(new PropertyValueFactory("customerNo"));
col_order_customer_name.setCellValueFactory(new PropertyValueFactory("customerNoStr"));
col_order_status.setCellValueFactory(new PropertyValueFactory("auditStatus"));
tab_order.setItems(data);
// 选择行 查询数据
tab_order.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<SaleQuotation>() {
@Override
public void changed(ObservableValue<? extends SaleQuotation> observableValue, SaleQuotation oldItem, SaleQuotation newItem) {
if(newItem.getId() != null && !("".equals(newItem.getId()))){
QuotationImportController.orderid = newItem.getId().toString();
List<SaleOfferProduct> offerProductList = iSaleOfferProductService.listSaleOfferProduct(newItem.getId());
importData.clear();
tab_product.setEditable(true);
tab_product_che.setCellFactory(CheckBoxTableCell.forTableColumn(tab_product_che));
tab_product_che.setCellValueFactory(new PropertyValueFactory("checked"));
tab_product_id.setCellValueFactory(new PropertyValueFactory("id"));
tab_product_no.setCellValueFactory(new PropertyValueFactory("productNo"));
tab_product_name.setCellValueFactory(new PropertyValueFactory("productName"));//映射
tab_product_num.setCellValueFactory(new PropertyValueFactory("num"));
tab_product_unit.setCellValueFactory(new PropertyValueFactory("unit"));
tab_product_price.setCellValueFactory(new PropertyValueFactory("price"));
tab_product_money.setCellValueFactory(new PropertyValueFactory("money"));
tab_product_remark.setCellValueFactory(new PropertyValueFactory("remark"));
for (SaleOfferProduct p : offerProductList) {
importData.add(new SaleQuotationImportProductProperty(p.getId(), p.getProductNo(), p.getProductName(), p.getNum(), p.getUnit(), p.getPrice(),p.getMoney(), p.getRemark(), false));
}
tab_product.setItems(importData);
}
}
});
// 设置选择多行
tab_product.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
}
}
|
package textProcessor;
import org.supercsv.io.CsvListWriter;
import org.supercsv.prefs.CsvPreference;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.supercsv.io.ICsvListWriter;
public class Util {
public static String fileToString(String file) throws IOException{
BufferedReader reader = new BufferedReader( new FileReader(file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
public static void stringToTxtFile(String file,String data){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(data);
System.out.println("Successfully store extracted text to " + file + " !");
writer.close();
} catch (IOException e) {
System.out.println("Fail to store extracted text to file!");
e.printStackTrace();
}
}
public static List<String> getFilelist(File dir){
List<String> fileList = new ArrayList<>();
File[] files = dir.listFiles();
for(File file: files){
fileList.add(file.toString());
System.out.println("One file added to FileList: " + file.toString());
}
return fileList;
}
public static HashMap<String, Integer> countWord(String out1, HashMap<String, Integer> map) {
String trim = out1.replaceAll("\n"," ");
trim = trim.replaceAll("\r"," ");
trim = trim.replaceAll("\\p{Punct}+", "");
trim = trim.toLowerCase();
String[] splitted = trim.split(" ");
int x;
for (int i=0; i<splitted.length ; i++) {
splitted[i].replaceAll(" ", "");
if( !splitted[i].equals("") && !splitted[i].equals(" ")) {
map.put(splitted[i], i);
}
System.out.println("word: " + splitted[i] + "; counts: " + i);
if (map.containsKey(splitted[i])) {
x = map.get(splitted[i]);
map.put(splitted[i], x+1);
}
}
return map;
}
public static void writeHashMapToCsv(HashMap<String, Integer> map) throws Exception {
ICsvListWriter listWriter = null;
try {
listWriter = new CsvListWriter(new FileWriter("D:\\workspace\\WebCrawler1\\counts.csv"),
CsvPreference.STANDARD_PREFERENCE);
System.out.println(listWriter);
for (Map.Entry<String, Integer> entry : map.entrySet()){
listWriter.write(entry.getKey(), entry.getValue());
}
}
finally {
if( listWriter != null ) {
listWriter.close();
}
}
}
}
|
package com.edasaki.rpg.tips;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import com.edasaki.core.options.SakiOption;
import com.edasaki.core.utils.RScheduler;
import com.edasaki.core.utils.RTicks;
import com.edasaki.rpg.AbstractManagerRPG;
import com.edasaki.rpg.SakiRPG;
public class TipManager extends AbstractManagerRPG {
private static final String PREFIX = ChatColor.GRAY + "[0] " + ChatColor.AQUA + ChatColor.BOLD + "Bot " + ChatColor.WHITE + "Rensa: " + ChatColor.GOLD;
private static int last = -1;
private static final String[] TIPS = {
"Be sure to turn on particles in your Minecraft client!",
"Most spells are displayed using particles. Make sure you have particles turned on!",
"Vote every day with &e/vote&6 to earn awesome rewards!",
"Buy awesome stuff from &e/rewards&6 with your Reward Points, earned by voting!",
"Make sure to set up your spells with &e/spell&6!",
"Be sure to check &e/help&6 for a list of all the commands!",
"Check your quest progress with &e/quests&6 and your location with &e/loc&6.",
"Party up! Team up with other players using &e/party&6 for bonus EXP.",
"Danger Levels 3 and 4 allow PvP. Be careful in them!",
"You will only lose items when you die in Danger Level 4.",
"Shards are the main currency of Zentrela, so keep your shards safe!",
"Hover over players' names in chat to see extra information. Click on their names for even more!",
"Be sure to check &e/options&6 to see what information you can hide or show!",
"I can provide convenient clickable links! Just say !help in chat for a list of chat commands!",
"Stuck? Try using the &eJumper Trinket&6 from &e/trinket&6 to get out!",
"Be sure to join the official Discord chat to chill with players and staff! Type &e!discord&6 for more information.",
"Help support the server! store.zentrela.net has all kinds of cool stuff!",
"Use &e!store&6 for a link to the official Zentrela store, where you can buy ranks and more!",
"Check out the Zentrela plug.dj at https://plug.dj/zentrela!",
"Zentrela is a new server, so we're still coming out with content! There will be lots more quests, shops, NPCs, mobs, builds, and dungeons in the future!",
"Too few quests? Not enough dungeons? The Zentrela team is working hard to bring you more fun content!",
"Want to know how much damage you're taking? Turn on Damage Messages in &e/options&6!",
"Check out the Zentrela Wiki for all kinds of help! http://zentrela.wikia.com/",
"Remember to vote every day to earn Reward Points! Type &e/vote&6 for a link to the voting page.",
"Want some awesome rewards from &e/rewards&6? &e/Vote&6 every day to stock up on Reward Points!",
};
private static boolean scheduled = false;
static {
for (int k = 0; k < TIPS.length; k++)
TIPS[k] = PREFIX + ChatColor.translateAlternateColorCodes('&', TIPS[k]);
}
public TipManager(SakiRPG plugin) {
super(plugin);
}
public static void sayTip() {
int rand = (int) (Math.random() * TIPS.length);
for (int k = 0; k < 3; k++) {
if (rand == last)
rand = (int) (Math.random() * TIPS.length);
}
last = rand;
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (plugin.getPD(p) != null) {
if (plugin.getPD(p).getOption(SakiOption.SAKIBOT_TIPS))
p.sendMessage(TIPS[rand]);
}
}
}
public static void schedule() {
if (scheduled)
return;
scheduled = true;
RScheduler.schedule(plugin, new Runnable() {
public void run() {
scheduled = false;
if (plugin.isEnabled()) {
sayTip();
}
}
}, RTicks.seconds((int) (Math.random() * 60 + 30)));
}
@Override
public void initialize() {
schedule();
}
}
|
package orm.integ.dao.dialect;
import orm.integ.dao.sql.QueryRequest;
import orm.integ.dao.sql.SqlBuilder;
import orm.integ.dao.sql.SqlQuery;
import orm.integ.dao.sql.TabQuery;
public class Oracle extends SqlBuilder {
@Override
public String makePageQuerySql(QueryRequest req) {
String orderStmt = req.getOrder().toString();
String sql ;
if (req instanceof TabQuery) {
TabQuery tq = (TabQuery)req;
String whereStmt = tq.getWhere().toString();
sql = " select rownum rn, t.* from ("
+ " select * from "+tq.getTableName()+whereStmt+orderStmt
+ ") t where rownum<= "+ req.getLast();
}
else {
SqlQuery sq = (SqlQuery)req;
sql = "select rownum rn, t.* from (" + sq.getSql() + ") t where rownum<="+req.getLast();
}
if (req.getStart()>1) {
sql = "select * from (" + sql + ") where rn>="+req.getStart();
}
return sql + orderStmt;
}
@Override
public String getTestSql() {
return "select * from dual";
}
}
|
package dataset;
import cluster.PartitionMapper;
import logHandling.PRLogRecord;
import org.apache.tinkerpop.gremlin.process.computer.ComputerResult;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.janusgraph.graphdb.database.StandardJanusGraph;
import java.util.Iterator;
public interface DatasetQueryRunner {
/**
* Runs the queries "benchmark" queries against the dataset.
* @param graph for the queries to be run against
* @param partitionMapper
* @param log true/false to enable/disable logging of the queries to the {@link logHandling.PRLog}
*/
void runQueries(StandardJanusGraph graph, PartitionMapper partitionMapper, boolean log);
/**
* Evaluates the improvement and other metrics of the partitioning algorithm
* @param result the computer result fo the partitioning algorithm
* @param label
* @return the improvement in percents - the difference of before and after cross node communication.
* @throws Exception
*/
double evaluateQueries(ComputerResult result, String label) throws Exception;
/**
* Variant of the {@link DatasetQueryRunner#evaluateQueries(ComputerResult, String)}
*/
double evaluateQueries(Graph graph, String label) throws Exception;
/**
* Variant of the {@link DatasetQueryRunner#evaluateQueries(ComputerResult, String)}
*/
double evaluateQueries(Graph graph, String label, Iterator<PRLogRecord> log) throws Exception;
}
|
import java.util.ArrayList;
import java.util.Collections;
// Caso não se utilize o Banco de Dados, esta classe MonoState pode ser
// utilizada para se armazenar os dados.
public class ListaLampadas {
private ArrayList<Lampada> listaLampadas = null;
// MonoState
public ListaLampadas(){
if(listaLampadas == null){
listaLampadas = new ArrayList<Lampada>();
}
}
public void addLampada(Lampada lampada){
listaLampadas.add(lampada);
Collections.sort(listaLampadas);
}
public ArrayList<Lampada> getListaLampadas(){
return listaLampadas;
}
public void editarLampada(Lampada lampada, Lampada novaLampada){
listaLampadas.remove(lampada);
listaLampadas.add(novaLampada);
Collections.sort(listaLampadas);
}
public void removerLampada(Lampada lampada){
listaLampadas.remove(lampada);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.