text
stringlengths
10
2.72M
/** * @Title:AppSysKpiVo.java * @Package:com.git.cloud.appmgt.model.vo * @Description:TODO * @author sunhailong * @date 2014-11-12 下午3:01:43 * @version V1.0 */ package com.git.cloud.appmgt.model.vo; import com.git.cloud.common.model.base.BaseBO; /** * 关于应用系统的指标 * @ClassName:AppSysKpiVo * @Description:TODO * @author sunhailong * @date 2014-11-12 下午3:01:43 */ public class AppSysKpiVo extends BaseBO { private static final long serialVersionUID = 1L; private String appId; // 应用系统Id private String appCName; // 应用系统中文名 private String appEName; // 应用系统英文名 private String deviceNums; // 应用系统虚机数量 private String requestNums; // 应用系统月申请数 public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getAppCName() { return appCName; } public void setAppCName(String appCName) { this.appCName = appCName; } public String getAppEName() { return appEName; } public void setAppEName(String appEName) { this.appEName = appEName; } public String getDeviceNums() { return deviceNums; } public void setDeviceNums(String deviceNums) { this.deviceNums = deviceNums == null ? "0" : deviceNums; } public String getRequestNums() { return requestNums; } public void setRequestNums(String requestNums) { this.requestNums = requestNums == null ? "0" : requestNums; } @Override public String getBizId() { return null; } }
package bip.utilities; public enum ImageSizes { ORIGINAL, SQUARE_SMALL, SQUARE_MEDIUM, LARGE }
package com.project.board.web.User.dto; import java.util.Date; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; @Getter @Setter @RequiredArgsConstructor public class UserDto { // 회원 아이디 private String USER_ID; // 회원 비밀번호 private String PASSWORD; // 회원 이름 private String NAME; // 회원 닉네임 private String NICKNAME; // 회원 가입 일자 private Date CREATE_TIME; // 회원 정보 수정 일자 private Date MODIFY_TIME; }
package com.example.vehiclehirebookingsystem; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class VehicleHireBookingSystemApplication { public static void main(String[] args) { SpringApplication.run(VehicleHireBookingSystemApplication.class, args); } }
package jp.co.comster.batch.mail; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; import jp.co.comster.batch.mail.dto.MailSendDto; /** * * メール送信クラス<br> * * <pre> * 【修正履歴】 * 日付 Ver. 担当者 修正内容 * --------------------------------------- * 2017/06/06 1.0 COMSTER Yamaguchi 新規作成 * </pre> * * @author COMSTER * @version 1.0 * */ public class MailSender { /** * メールを送信します。 * * @param mailSendDto メールDTO */ public void sendMail(MailSendDto mailSendDto) { try { SimpleEmail email = new SimpleEmail(); email.setHostName(mailSendDto.emailSetHostName); for (String mailaddress : mailSendDto.emailTo.split(",")) if (mailaddress.indexOf("|") > -1) email.addTo(mailaddress.split("\\|")[0],mailaddress.split("\\|")[1]); else email.addTo(mailaddress); if (mailSendDto.emailFrom.indexOf("|") > -1) email.setFrom(mailSendDto.emailFrom.split("\\|")[0], mailSendDto.emailFrom.split("\\|")[1]); else email.setFrom(mailSendDto.emailFrom); if (mailSendDto.isEmailSetSSL) { email.setSSLOnConnect(true); email.setSslSmtpPort(mailSendDto.emailSSLPort); email.setAuthentication(mailSendDto.emailSSLUser, mailSendDto.emailSSLPass); } email.setSubject(mailSendDto.subject); email.setContent(mailSendDto.body, "text/plain; charset=ISO-2022-JP"); email.setCharset("ISO-2022-JP"); email.send(); } catch (EmailException e) { throw new RuntimeException(e); } } }
package com.emg.projectsmanage.dao.process; import com.emg.projectsmanage.pojo.ConfigDefaultModel; import com.emg.projectsmanage.pojo.ConfigDefaultModelExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface ConfigDefaultModelDao { int countByExample(ConfigDefaultModelExample example); int deleteByExample(ConfigDefaultModelExample example); int deleteByPrimaryKey(Integer id); int insert(ConfigDefaultModel record); int insertSelective(ConfigDefaultModel record); List<ConfigDefaultModel> selectByExample(ConfigDefaultModelExample example); ConfigDefaultModel selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") ConfigDefaultModel record, @Param("example") ConfigDefaultModelExample example); int updateByExample(@Param("record") ConfigDefaultModel record, @Param("example") ConfigDefaultModelExample example); int updateByPrimaryKeySelective(ConfigDefaultModel record); int updateByPrimaryKey(ConfigDefaultModel record); }
Given an array of integers, find the sum of its elements. For example, if the array , , so return . Function Description Complete the simpleArraySum function in the editor below. It must return the sum of the array elements as an integer. simpleArraySum has the following parameter(s): ar: an array of integers Input Format The first line contains an integer, , denoting the size of the array. The second line contains space-separated integers representing the array's elements. Constraints Output Format Print the sum of the array's elements as a single integer. Sample Input 6 1 2 3 4 10 11 Sample Output 31 Explanation We print the sum of the array's elements: . Solution: import java.util.Scanner; public class SimpleArraySum { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int noOfElements = sc.nextInt(); int sum = 0; for (int i = 0; i < noOfElements; i++) { sum = sum + sc.nextInt(); } System.out.println(sum); sc.close(); } }
package org.celllife.stock.domain; import junit.framework.Assert; import org.celllife.stock.domain.drug.Drug; import org.celllife.stock.domain.drug.DrugRepository; import org.celllife.stock.test.TestConfiguration; 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; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TestConfiguration.class) public class DrugRepositoryTest { @Autowired private DrugRepository drugRepository; @Test public void testCreateOne() throws Exception { String barcode = "0762837491"; Drug drug = null; try { drug = new Drug(barcode, "Disprin"); drugRepository.save(drug); Drug savedDrug = drugRepository.findOneByBarcode(barcode); Assert.assertNotNull(savedDrug); } finally { if (drug != null) drugRepository.delete(drug); } } }
package dominio.evento; import java.util.List; import dominio.participantes.Participante; import dominio.produto.ItemProduto; public class RateioProduto extends Rateio { private List<ItemProduto> produtos; private Participante participante; private Evento evento; public List<ItemProduto> getProdutos() { return produtos; } public void setProdutos(List<ItemProduto> produtos) { this.produtos = produtos; } public Participante getParticipante() { return participante; } public void setParticipante(Participante participante) { this.participante = participante; } public Evento getEvento() { return evento; } public void setEvento(Evento evento) { this.evento = evento; } }
package com.dragonforest.demo.app_java.http; import retrofit2.Call; import retrofit2.http.GET; /** * create by DragonForest at 2020/7/7 */ public interface Api { @GET("article/top/json") Call<String> getData(); }
/** * SlideShow is an Android Custom View that displays a set of slides. * * Copyright (C) 2008-2009 Free Beachler * <http://code.google.com/p/android-slide-show/> * * SlideShow is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * SlideShow is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SlideShow. If not, see <http://www.gnu.org/licenses/>. */ package com.freebeachler.android.component.slideshow; import java.util.LinkedList; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Handler; import android.os.Looper; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.TranslateAnimation; import com.freebeachler.android.demos.component.slideshow.R; /** * Cutom SlideShow component. * This component supports loading {@link com.freebeachler.android.component.slideshow.DrawableSlide}s which can be either * {@link android.drawable.Drawable}s or {@link java.net.URL}s. Known supported {@link android.drawable.Drawable}s * are Drawable and BitmapDrawable. * * @author freebeachler * */ public class SlideShow extends View { public static final int SLIDESHOW_DEFAULT_WIDTH = 281; public static final int SLIDESHOW_DEFAULT_HEIGHT = 150; public static final int DEFAULT_CURRENT_SLIDE_INDEX_START = 0; /** * Use this listener interface to catch slide show events. * * @author freebeachler * */ public static interface SlideShowListener { /** * Called when slides begin loading. */ public void onLoadSlidesStart(SlideShow slideshow); /** * Called when slides are finished loading. */ public void onLoadSlidesEnd(SlideShow slideshow); } /** * Use this listener interface to catch slide show events. * * @author freebeachler * */ public static interface SlideShowAnimationListener { /** * Called when slide animation starts. */ public void onSlideAnimationStart(Animation animation); /** * Called when slide animation ends. */ public void onSlideAnimationEnd(Animation animation); /** * Called when slide animation repeats. */ public void onSlideAnimationRepeat(Animation animation); } /** * * @author freebeachler * */ private class SlideAnimationListener implements Animation.AnimationListener { public SlideAnimationListener() { } /* (non-Javadoc) * @see android.view.animation.Animation.AnimationListener#onAnimationEnd(android.view.animation.Animation) */ public void onAnimationEnd(Animation animation) { if (slideShowAnimationListener != null) { slideShowAnimationListener.onSlideAnimationEnd(animation); } } /* (non-Javadoc) * @see android.view.animation.Animation.AnimationListener#onAnimationRepeat(android.view.animation.Animation) */ public void onAnimationRepeat(Animation animation) { if (slideShowAnimationListener != null) { slideShowAnimationListener.onSlideAnimationRepeat(animation); } } /* (non-Javadoc) * @see android.view.animation.Animation.AnimationListener#onAnimationStart(android.view.animation.Animation) */ public void onAnimationStart(Animation animation) { if (slideShowAnimationListener != null) { slideShowAnimationListener.onSlideAnimationStart(animation); } } } /** * image display height */ private int mDispHeight; /** * cache current slide */ private DrawableSlide mCurrentSlide; /** * linked list of slides */ private LinkedList<DrawableSlide> mSlides; /** * index of current slide being displayed */ private int mCurrentSlideIndex; /** * first animation to apply to slide drawable * when hiding current slide in * slide list */ private AlphaAnimation mHideCurrentAnimation; /** * animation set to apply to slide drawable * when hiding current slide in * slide list */ private AnimationSet mHideCurrentAnimationSet; /** * first animation to apply to slide drawable * when traversing 'forward' through * slide list */ private TranslateAnimation mNextAnimation; /** * animation set to apply to slide drawable * when traversing 'forward' through * slide list */ private AnimationSet mNextAnimationSet; /** * animation to apply to slide drawable * when traversing 'backward' through * slide list */ private TranslateAnimation mPrevAnimation; /** * animation set to apply to slide drawable * when traversing 'backward' through * slide list */ private AnimationSet mPrevAnimationSet; /** * Default callback for slideshow. */ private SlideShowListener slideShowListener; /** * Default callback for slideshow. */ private SlideShowAnimationListener slideShowAnimationListener; /** * Handler for thread that handles loading slides in slideshow. */ private Handler slideShowFinishedLoadingHandler; /** * True if all slides are loaded. */ private boolean slideShowLoaded; public SlideShow(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlideShow); mCurrentSlideIndex = a.getInt(R.styleable.SlideShow_startIndex, DEFAULT_CURRENT_SLIDE_INDEX_START); mSlides = new LinkedList<DrawableSlide>(); setFocusable(true); setFocusableInTouchMode(true); slideShowFinishedLoadingHandler = new Handler(); slideShowListener = null; slideShowAnimationListener = null; mCurrentSlide = null; mDispHeight = SLIDESHOW_DEFAULT_HEIGHT; initAnimationSets(); } /** * @return the Slides to display */ @SuppressWarnings("unused") private LinkedList<DrawableSlide> getSlides() { return mSlides; } /** * Set the {@link com.freebeachler.android.component.slideshow.DrawableSlide}s used by this {@link com.freebeachler.android.component.slideshow.SlideShow}. * Also sets/resets the state of the SlideShow, such as whether slides are * loaded. * * @param set Slides to display */ public void setSlides(LinkedList<DrawableSlide> slides) { this.mSlides = slides; checkSlidesLoaded(); } /** * @return the currentSlideIndex */ public int getCurrentSlideIndex() { return mCurrentSlideIndex; } /** * @param currentSlideIndex the currentSlideIndex to set */ public void setCurrentSlideIndex(int currentSlideIndex) { this.mCurrentSlideIndex = currentSlideIndex; } /** * @return the mHideCurrentAnimation */ public Animation getHideCurrentAnimation() { return mHideCurrentAnimation; } /** * @param hideCurrentAnimation the mHideCurrentAnimation to set */ public void setHideCurrentAnimation(AlphaAnimation hideCurrentAnimation) { this.mHideCurrentAnimation = hideCurrentAnimation; } /** * @return the mNextAnimation */ public Animation getNextAnimation() { return mNextAnimation; } /** * @param nextAnimation the mNextAnimation to set */ public void setNextAnimation(TranslateAnimation nextAnimation) { this.mNextAnimation = nextAnimation; } /** * @return the mPrevAnimation */ public Animation getPrevAnimation() { return mPrevAnimation; } /** * @param prevAnimation the mPrevAnimation to set */ public void setPrevAnimation(TranslateAnimation prevAnimation) { this.mPrevAnimation = prevAnimation; } /** * @param slideShowAnimationListener the slideShowAnimationListener to set */ public void setSlideShowAnimationListener( SlideShowAnimationListener slideShowAnimationListener) { this.slideShowAnimationListener = slideShowAnimationListener; } /** * @param slideShowListenerCallback the slideShowListenerCallback to set */ public void setSlideShowListener( SlideShowListener slideShowListener) { this.slideShowListener = slideShowListener; } /** * @see android.view.View#measure(int, int) */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); } /** * render the slide * * @param Canvas canvas to render slideshow on * @todo {@see ISlideAsset.getSlideAsset} */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Rect slideBounds = null; if (this.getBackground() == null) { canvas.drawColor(android.R.color.background_light); } if (mCurrentSlide != null && mCurrentSlide.isSlideLoaded()) { slideBounds = new Rect(0, 0, getCurrentSlideScaledImageWidth(), mDispHeight); //size it and preserve aspect mCurrentSlide.getSlideAsset().setBounds(slideBounds); mCurrentSlide.draw(canvas); } invalidate(); } /** * Initialize default animation sets. */ private void initAnimationSets() { mHideCurrentAnimation = new AlphaAnimation(0.0f, 1.0f); mHideCurrentAnimation.setRepeatCount(Animation.INFINITE); mHideCurrentAnimation.setRepeatMode(Animation.RESTART); mHideCurrentAnimation.initialize(SLIDESHOW_DEFAULT_WIDTH, SLIDESHOW_DEFAULT_HEIGHT, SLIDESHOW_DEFAULT_WIDTH, SLIDESHOW_DEFAULT_HEIGHT); mHideCurrentAnimation.setDuration(280); mPrevAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f); mPrevAnimation.setDuration(400); mPrevAnimation.initialize(SLIDESHOW_DEFAULT_WIDTH, SLIDESHOW_DEFAULT_HEIGHT, SLIDESHOW_DEFAULT_WIDTH, SLIDESHOW_DEFAULT_HEIGHT); mNextAnimation = new TranslateAnimation(281, 0, 0, 0); mNextAnimation.setDuration(400); mNextAnimation.setRepeatCount(0); mNextAnimation.initialize(SLIDESHOW_DEFAULT_WIDTH, SLIDESHOW_DEFAULT_HEIGHT, SLIDESHOW_DEFAULT_WIDTH, SLIDESHOW_DEFAULT_HEIGHT); mNextAnimation.setAnimationListener(new SlideShow.SlideAnimationListener()); mHideCurrentAnimationSet = new AnimationSet(true); mHideCurrentAnimationSet.addAnimation(mHideCurrentAnimation); mNextAnimationSet = new AnimationSet(true); mNextAnimationSet.addAnimation(mNextAnimation); mPrevAnimationSet = new AnimationSet(true); mPrevAnimationSet.addAnimation(mPrevAnimation); //thread safe to set listeners here? mNextAnimationSet.setAnimationListener(new SlideShow.SlideAnimationListener()); mPrevAnimationSet.setAnimationListener(new SlideShow.SlideAnimationListener()); } /** * Load or re-load any slides that are not yet loaded. */ public void loadSlides() { this.slideShowLoaded = false; this.onLoadSlidesStart(); } /** * If all slides loaded then slideshow flag to loaded. */ private boolean checkSlidesLoaded() { //assume not loaded this.slideShowLoaded = false; for (DrawableSlide slide : this.mSlides) { if (!slide.isSlideLoaded()) { return false; } } this.slideShowLoaded = true; return this.slideShowLoaded; } /** * Determines the width of this view * @param measureSpec A measureSpec packed into an int * @return The width of the view, honoring constraints from measureSpec */ private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { //we were told how big to be result = specSize; } else { if (mCurrentSlide != null) { //measure the slide result = getCurrentSlideScaledImageWidth(); } else { result = SLIDESHOW_DEFAULT_WIDTH; } } return result; } /** * Determines the height of this view * @param measureSpec A measureSpec packed into an int * @return The height of the view, honoring constraints from measureSpec */ private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { //we were told how big to be result = specSize; } else { result = SLIDESHOW_DEFAULT_HEIGHT; } return result; } /** * get scaled width of current slide based on height set for class * @todo {@see ISlideAsset.getSlideAsset} * @return */ private int getCurrentSlideScaledImageWidth() { //load image from list DrawableSlide dr = mSlides.get(mCurrentSlideIndex); //size it and preserve aspect int dispWidth = dr.getSlideAsset().getIntrinsicWidth(); if (dr.getSlideAsset().getIntrinsicHeight() > SLIDESHOW_DEFAULT_HEIGHT) { //preserve aspect ratio 1:1 dispWidth = (int) ((float) dr.getSlideAsset().getIntrinsicWidth() * ((float) SLIDESHOW_DEFAULT_HEIGHT / (float) dr.getSlideAsset().getIntrinsicHeight())); } return dispWidth; } /** * @param slideIndex the currentSlideIndex to set for drawing */ public DrawableSlide getSlideAtIndex(int slideIndex) { //load image from list DrawableSlide dr = mSlides.get(slideIndex); return dr; } public DrawableSlide getCurrentSlide() { mCurrentSlide = getSlideAtIndex(mCurrentSlideIndex); return mCurrentSlide; } /** * garbage collection for current slide */ public void clearCurrentSlide() { if(mCurrentSlide == null) { return; } mCurrentSlide.clearSlide(); mCurrentSlide = null; } /** * draws the current slide using animation defined by one of * @param direction {@link com.freebeachler.android.component.slideshow.Slide#SLIDE_DIRECTION_FORWARD} draws slide with next animation {@link com.freebeachler.android.component.slideshow.Slide#SLIDE_DIRECTION_BACKWARD} draws slide with previous animation * @throws Exception */ public void drawCurrentSlide(int direction) throws Exception { if (mSlides == null) { StringBuffer msg = new StringBuffer(); msg.append("Cannot initialize an empty slideshow. Try calling setSlides() first."); throw new Exception(msg.toString()); } if (!this.checkSlidesLoaded()) { StringBuffer msg = new StringBuffer(); msg.append("Slideshow still loading. Defer loading the current slide and use a SlideShowListener to avoid this error."); throw new Exception(msg.toString()); } if (mCurrentSlideIndex >= mSlides.size()) { StringBuffer msg = new StringBuffer(); msg.append("Cannot initialize slideshow at index " + Integer.toString(mCurrentSlideIndex) + ". SlideShow size is " + Integer.toString(mSlides.size()) + "."); throw new Exception(msg.toString()); } getCurrentSlide(); //get animation AnimationSet an; switch(direction) { case DrawableSlide.SLIDE_DIRECTION_BACKWARD: an = mPrevAnimationSet; break; default: //default to next animation an = mNextAnimationSet; } mCurrentSlide.setShowAnimation(an); mCurrentSlide.getShowAnimation().start(); } /** * increment current slide index * loop to beginning of list if at end * * @param direction * @throws Exception */ public void drawNextSlide() throws Exception { if (!this.checkSlidesLoaded()) { return; } //increment slide index, get next slide, set animation mCurrentSlideIndex++; if(mCurrentSlideIndex >= mSlides.size()) { mCurrentSlideIndex = 0; } drawCurrentSlide(DrawableSlide.SLIDE_DIRECTION_FORWARD); } /** * increment current slide index * loop to beginning of list if at end * * @param direction * @throws Exception */ public void drawPrevSlide() throws Exception { if (!this.checkSlidesLoaded()) { return; } mCurrentSlideIndex--; if(mCurrentSlideIndex < 0) { mCurrentSlideIndex = mSlides.size() - 1; } drawCurrentSlide(DrawableSlide.SLIDE_DIRECTION_BACKWARD); } /** * Calls {@link com.freebeachler.android.component.Slide.loadSlide()} for each {@link com.freebeachler.android.component.slideshow.DrawableSlide} * in slideshow in a seperate thread. */ private void onLoadSlidesStart() { //do nothing if slides already loaded or no slides set if (this.mSlides.size() < 1) { return; } if (checkSlidesLoaded()) { //slides are already loaded - display and trigger event onLoadSlidesEnd(null, null); } new Thread(new Runnable() { public void run() { Looper.prepare(); Object result = null; Exception error = null; try { for (DrawableSlide slide : mSlides) { //load slide form uri or do nothing slide.load(); } } catch (Exception e) { Log.e("ERROR", e.getMessage()); error = e; } final Object finalResult = result; final Exception finalError = error; slideShowFinishedLoadingHandler.post(new Runnable() { public void run() { onLoadSlidesEnd(finalResult, finalError); } }); } }).start(); if (slideShowListener != null) { slideShowListener.onLoadSlidesStart(this); } } private void onLoadSlidesEnd(Object finalResult, Exception finalError) { this.checkSlidesLoaded(); if (finalError != null && finalError.getStackTrace() != null) { finalError.printStackTrace(); return; } try { drawCurrentSlide(DrawableSlide.SLIDE_DIRECTION_FORWARD); } catch (Exception e) { e.printStackTrace(); } if (slideShowListener != null) { slideShowListener.onLoadSlidesEnd(this); } } }
package br.com.transactions.domain.utils; import java.util.Arrays; import br.com.transactions.domain.utils.exception.BankNotFoundException; public enum AgencyBanking { NUBANK, SOROCRED; public static AgencyBanking getAgencyBanking(String agencyBank) throws BankNotFoundException { return Arrays.asList(AgencyBanking.values()).stream() .filter(banking -> banking.name().equals(agencyBank.toUpperCase())).findFirst() .orElseThrow(() -> new BankNotFoundException("Bank branch not found!")); } }
package com.javabanktech; import java.util.*; import java.text.SimpleDateFormat; class AccountStatement { private ArrayList<Transaction> listOfTransactions = new ArrayList<>(); private String pattern = "MM-dd-yyyy"; private SimpleDateFormat format = new SimpleDateFormat(pattern); void printStatement() { System.out.println("date || credit || debit || balance"); Collections.reverse(listOfTransactions); for(Transaction t:listOfTransactions) { String date = format.format(t.getDate()); System.out.println(date + "||" + checkValues(t.getCredit()) + "||" + checkValues(t.getDebit()) + "||" + checkValues(t.getBalance())); } } void addTransaction(double credit, double debit, double balance) { Transaction transaction = new Transaction(credit, debit, balance); listOfTransactions.add(transaction); } String checkValues(String value) { if (value.equals("0.0")) { return " "; } else { return value; } } }
package com.miaoqi.authen.web.controller; import com.fasterxml.jackson.annotation.JsonView; import com.miaoqi.authen.dto.User; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/user") public class UserController { @PutMapping("/{id:\\d+}") public User update(@Valid @RequestBody User user, BindingResult errors) { System.out.println(user.getId()); System.out.println(user.getUsername()); System.out.println(user.getPassword()); System.out.println(user.getBirthday()); user.setId("1"); return user; } @DeleteMapping("/{id:\\d+}") public void delete(@PathVariable String id) { System.out.println(id); } @PostMapping public User create(@Valid @RequestBody User user, BindingResult errors) { if (errors.hasErrors()) { errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage())); } System.out.println(user.getId()); System.out.println(user.getUsername()); System.out.println(user.getPassword()); System.out.println(user.getBirthday()); user.setId("1"); return user; } @GetMapping @JsonView(User.UserSimpleView.class) public List<User> query(@RequestParam(name = "username", required = false) String username) { ArrayList<User> users = new ArrayList<>(); users.add(new User()); users.add(new User()); users.add(new User()); return users; } @JsonView(User.UserDetailView.class) @GetMapping("/{id:\\d+}") public User getInfo(@PathVariable("id") String id) { User user = new User(); user.setId("1"); user.setUsername("tom"); return user; } }
package com.smartsampa.olhovivoapi; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.builder.ToStringBuilder; /** * Created by ruan0408 on 13/02/2016. */ public class ForecastWithTrip { @JsonProperty("hr") public String currentTime; @JsonProperty("ps") public StopNow[] stopsNow; public StopNow[] getStopsNow() { return stopsNow; } @Override public String toString() { return new ToStringBuilder(this) .append("currentTime", currentTime) .append("stopsNow", stopsNow) .toString(); } }
package com.lynch.search.binarytree; import edu.princeton.cs.algs4.Queue; import edu.princeton.cs.algs4.StdOut; import java.util.Scanner; /** * Created by lynch on 2018/9/26. <br> **/ public class BST<Key extends Comparable<Key>, Value> { private Node root; //二叉查找树的根结点 private class Node { private Key key; //键 private Value value; //值 private Node left, right; //指向子树的链接 private int N; //以该结点为根的子树中的结点总数 public Node(Key key, Value value, int N) { this.key = key; this.value = value; this.N = N; } } public int size() { return size(root); } private int size(Node x) { if (x == null) return 0; else return x.N; } //查找与排序 public Value get(Key key) { return get(root, key); } private Value get(Node x, Key key) { //如果x结点为根结点的子树中查找并返回key所对应的值; //如果查不到则返回null if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) return get(x.left, key); else if (cmp > 0) return get(x.right, key); else return x.value; } public void put(Key key, Value value) { //查找key,找到则更新它的值,否则为它创建一个新结点 root = put(root, key, value); } private Node put(Node x, Key key, Value value) { //如果key存在于以x为根结点的子树中则更新它的值 //否则将以key和value为键值对的新结点插入到该子树中 if (x == null) return new Node(key, value, 1); int cmp = key.compareTo(x.key); if (cmp < 0) x.left = put(x.left, key, value); else if (cmp > 0) x.right = put(x.right, key, value); else x.value = value; x.N = size(x.left) + size(x.right) + 1; return x; } //最小键 public Key min() { return min(root).key; } private Node min(Node x) { if (x.left == null) return x; return min(x.left); } //小于或等于key的最大键 public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; return x.key; } private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } //最大键 public Key max() { return max(root).key; } private Node max(Node x) { if (x.right == null) return x; return max(x.right); } //大于或等于key的最小键 public Key ceiling(Key key) { Node x = ceiling(root, key); if (x == null) return null; return x.key; } private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp > 0) return ceiling(x.right, key); Node t = ceiling(x.left, key); if (t != null) return t; else return x; } //排名 public Key select(int k) { return select(root, k).key; } private Node select(Node x, int k) { //返回排名为k的结点 if (x == null) return null; int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k - t - 1); else return x; } public int rank(Key key) { return rank(key, root); } private int rank(Key key, Node x) { //返回以x为结点的子树中小于x.key的键的数量 if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } //删除最小键 public void deleteMin() { root = deleteMin(root); } private Node deleteMin(Node x) { if (x.left == null) return x.right; x.left = deleteMin(x.left); x.N = size(x.left) + size(x.right) + 1; return x; } //删除最大键 public void deleteMax() { root = deleteMax(root); } private Node deleteMax(Node x) { if (x.right == null) return x.left; x.right = deleteMin(x.right); x.N = size(x.left) + size(x.right) + 1; return x; } //删除 public void delete(Key key) { root = delete(root, key); } private Node delete(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) x.left = delete(x.left, key); else if (cmp > 0) x.right = delete(x.right, key); //删除结点有左右两个结点 else { if (x.right == null) return x.left; if (x.left == null) return x.right; Node t = x; //将要被删除的结点用t代替 x = min(t.right); //此时x更新为t的最小右结点 x.right = deleteMin(t.right); //新的x右结点为将要删除的t的右最小结点 x.left = t.left; //新的x左结点就是t的左结点 } x.N = size(x.left) + size(x.right) + 1; return x; } //范围查找 public Queue<Key> keys() { return keys(min(), max()); } public Queue<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); keys(root, queue, lo, hi); return queue; } private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } //按级别顺序返回BST中的键 public Iterable<Key> levelOrder() { Queue<Key> keys = new Queue<Key>(); Queue<Node> queue = new Queue<Node>(); queue.enqueue(root); while (!queue.isEmpty()) { Node x = queue.dequeue(); if (x == null) continue; keys.enqueue(x.key); queue.enqueue(x.left); queue.enqueue(x.right); } return keys; } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input n:");//数组长 int n = in.nextInt(); String[] a = new String[n]; System.out.println("Please input " + n + " letters:"); BST<String, Integer> st = new BST<String, Integer>(); for (int i = 0; i < a.length; i++) { String input = in.next(); a[i] = input; st.put(a[i], i);//关联型数组,意味着每个键的值取决于最近一次put()方法的调用 //如 q a z w a x ...会显示a的值是4 } //级别排序 for (String s : st.levelOrder()) StdOut.println(s + " " + st.get(s)); StdOut.println(); //键排序 for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
package user.services; import java.sql.SQLException; import java.util.List; import userdao.AuthDAO; import userdao.RolesDAO; import userdao.UserDAO; import userdaoimp.AuthDaoImpl; import userdaoimp.RoleDaoImpl; import userdaoimp.UserDaoImpl; import admin.dao.BookDAO; import admin.dao.impl.BookDaoImpl; import bean.bookbean.BookBean; import bean.users.AuthBean; import bean.users.RolesBean; import bean.users.UserBean; public class AdminServices { private UserDAO userDAO = new UserDaoImpl(); private AuthDAO authDAO = new AuthDaoImpl(); private RolesDAO roleDAO = new RoleDaoImpl(); private BookDAO bookDAO = new BookDaoImpl(); public int insert(UserBean c) throws ClassNotFoundException, SQLException { return userDAO.insert(c); } public int update(int id, UserBean c) throws ClassNotFoundException, SQLException { return userDAO.update(id, c); } public int delete(int id) throws ClassNotFoundException, SQLException { return userDAO.delete(id); } public int softDelete(int id) throws ClassNotFoundException, SQLException { return userDAO.softDelete(id); } public List<UserBean> getAll() throws ClassNotFoundException, SQLException { return userDAO.getAll(); } public UserBean getById(int id) throws ClassNotFoundException, SQLException { return userDAO.getById(id); } public AuthBean getByEmail(String email) throws ClassNotFoundException, SQLException { return authDAO.getByEmail(email); } public RolesBean getByRoleId(int id) throws ClassNotFoundException, SQLException { return roleDAO.getById(id); } public AuthBean getByEmailAndPass(String email, String password) throws ClassNotFoundException, SQLException { return authDAO.getByEmailAndPass(email,password); } public int insertBook(BookBean c) throws ClassNotFoundException, SQLException { return bookDAO.insert(c); } public int update(int id, BookBean c) throws ClassNotFoundException, SQLException { return bookDAO.update(id, c); } public int deleteBook(int id) throws ClassNotFoundException, SQLException { return bookDAO.delete(id); } public int softDeleteBook(int id) throws ClassNotFoundException, SQLException { return bookDAO.softDelete(id); } public List<BookBean> getAllBooks() throws ClassNotFoundException, SQLException { return bookDAO.getAll(); } public BookBean getBookById(int id) throws ClassNotFoundException, SQLException { return bookDAO.getById(id); } public int enableBook(int id) throws ClassNotFoundException, SQLException { return bookDAO.enableBook(id); } public List<BookBean> getBookByKeyWord(String keyWord) throws ClassNotFoundException, SQLException { return bookDAO.searchBookByKeyWord(keyWord); } }
package com.gxtc.huchuan.ui.mine.setting.accountSafe; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import com.gxtc.commlibrary.base.BaseTitleActivity; import com.gxtc.commlibrary.utils.GotoUtil; import com.gxtc.commlibrary.utils.ToastUtil; import com.gxtc.huchuan.R; import com.gxtc.huchuan.data.ChangePwsRepository; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.http.ApiCallBack; import com.gxtc.huchuan.ui.im.redPacket.PayPwdSettingActivity; import com.gxtc.huchuan.ui.mine.loginandregister.changepsw.ChangePswContract; import com.gxtc.huchuan.utils.DialogUtil; import com.gxtc.huchuan.utils.GoToActivityIfLoginUtil; import butterknife.BindView; import butterknife.OnClick; /** * 账号与安全 * Created by zzg on 2017/7/3. */ //privacy public class AccountSafeActivity extends BaseTitleActivity { @BindView(R.id.rl_account_id) RelativeLayout rlAccountId; @BindView(R.id.account_id) TextView tvAccountId; @BindView(R.id.rl_bind_phone) RelativeLayout rlBindPhone; @BindView(R.id.phone_number) TextView tvPhoneNumber; @BindView(R.id.rl_cind_wei_xin) RelativeLayout rlWeiXin; @BindView(R.id.weixin_account) TextView tvWeiXin; @BindView(R.id.rl_edit_pwd) RelativeLayout rlEditPwd; @BindView(R.id.tv_edit_pwd) TextView tvEditPwd; @BindView(R.id.ed_pay_pwd) TextView tvEditPayPwd; private EditText editPassword; private ChangePswContract.Source mData; private AlertDialog mDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_account_safe); } @Override public void initView() { getBaseHeadView().showTitle(getString(R.string.title_account_safe)); getBaseHeadView().showBackButton(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); tvAccountId.setText(UserManager.getInstance().getUserCode()); tvPhoneNumber.setText(UserManager.getInstance().getPhone()); //是否有支付密码。 0:否;1:有 if (UserManager.getInstance().getUser().getHasPayPwd() == 0) { tvEditPayPwd.setText("设置支付密码"); } else if (UserManager.getInstance().getUser().getHasPayPwd() == 1) { tvEditPayPwd.setText("修改支付密码"); } } @Override public void initData() { mData = new ChangePwsRepository(); } @OnClick({R.id.rl_bind_phone, R.id.rl_cind_wei_xin, R.id.rl_edit_pwd, R.id.ed_pay_pwd}) public void onClick(View view) { switch (view.getId()) { //绑定手机 case R.id.rl_bind_phone: //需改变 GoToActivityIfLoginUtil.goToActivity(this, BindPhoneActivity.class); break; //绑定微信 case R.id.rl_cind_wei_xin: GotoUtil.goToActivity(this, BindWXActivity.class); break; // GotoUtil.goToActivity(this, PayPwdSettingActivity.class); //修改登录密码 case R.id.rl_edit_pwd: View dialogView = View.inflate(this, R.layout.dialog_ed_pwd_layout, null); editPassword = (EditText) dialogView.findViewById(R.id.edit_password); mDialog = DialogUtil.showEditPwdDialog(AccountSafeActivity.this, dialogView, new View.OnClickListener() { @Override public void onClick(View v) { verifyPassword(); } }); break; //修改(设置)支付密码 case R.id.ed_pay_pwd: switch (UserManager.getInstance().getUser().getHasPayPwd()) { case 0://设置支付密码 GotoUtil.goToActivity(this, PayPwdSettingActivity.class); break; case 1://修改支付密码 GotoUtil.goToActivity(this, EditPayPwdActivity.class); break; } break; } } private void verifyPassword() { final String password = editPassword.getText().toString(); if (TextUtils.isEmpty(password)) { ToastUtil.showShort(this, "请输入密码"); return; } getBaseLoadingView().showLoading(true); String token = UserManager.getInstance().getToken(); mData.verifyPassword(token, password.trim(), new ApiCallBack<Object>() { @Override public void onSuccess(Object data) { getBaseLoadingView().hideLoading(); Intent intent = new Intent(AccountSafeActivity.this, EdPwdActivity.class); intent.putExtra("password", password); startActivity(intent); mDialog.dismiss(); } @Override public void onError(String errorCode, String message) { getBaseLoadingView().hideLoading(); ToastUtil.showShort(AccountSafeActivity.this, message); editPassword.setText(""); } }); } @Override protected void onDestroy() { super.onDestroy(); mData.destroy(); } }
package com.tu.springsession.controller; import com.tu.common.MyException; import com.tu.common.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * @Auther: tuyongjian * @Date: 2020/7/21 09:35 * @Description: */ @RestController @RequestMapping(value = "api/user") public class SpringSessionAction { @RequestMapping("/login") public Result login(HttpServletRequest request) { String userId ="123"; HttpSession session = request.getSession(); session.setAttribute("loginUserId", userId); return new Result(true, "登录成功!"); } @RequestMapping(value = "/getUserInfo") public Result get() { return new Result(true, "查询成功!"); } }
package pers.mine.scratchpad.base.generics; /** * @author mine * @description TODO * @create 2020-06-23 17:40 */ public class CheckConstructor { public static void main1(String[] args) { String empty = ""; char[] chars = empty.toCharArray(); System.out.println(chars); String[] a = {}; String[] b = new String[0]; System.out.println(a.length); System.out.println(b.length); System.out.println("test()--------"); test(); System.out.println("test(null)--------"); test(null); System.out.println("test((Object[]) null)--------"); test((Object[]) null); System.out.println("test((Object[][]) null)----------"); test((Object[][]) null); } public static void test(Object[]... args) { System.out.println(args); try { System.out.println(args.getClass()); System.out.println(args.length); for (Object arg : args) { System.out.println(arg); } } catch (Exception e) { System.out.println(e.getMessage()); } } public static <T> void test(T... s) { System.out.println(s.length); for (T t : s) { System.out.println(t); } } // public static <T> void test(T s1) { // System.out.println(s1); // } // // public static <T> void test(T s1, T s2) { // System.out.println(s1); // System.out.println(s2); // // } public static void main(String[] args) { int[] x = {1}; test(x,x); } static class C extends B { @Override public void look() { System.out.println(name); } C() { super(); } } static abstract class B implements A { String name; B() { System.out.println("B()"); } } interface A { void look(); } }
package co.sblock.events; import static org.bukkit.Material.ACTIVATOR_RAIL; import static org.bukkit.Material.BARRIER; import static org.bukkit.Material.BEACON; import static org.bukkit.Material.BEDROCK; import static org.bukkit.Material.BED_BLOCK; import static org.bukkit.Material.BEETROOT_BLOCK; import static org.bukkit.Material.BURNING_FURNACE; import static org.bukkit.Material.CAKE_BLOCK; import static org.bukkit.Material.CARROT; import static org.bukkit.Material.COCOA; import static org.bukkit.Material.COMMAND; import static org.bukkit.Material.COMMAND_CHAIN; import static org.bukkit.Material.COMMAND_MINECART; import static org.bukkit.Material.COMMAND_REPEATING; import static org.bukkit.Material.CROPS; import static org.bukkit.Material.DAYLIGHT_DETECTOR_INVERTED; import static org.bukkit.Material.DETECTOR_RAIL; import static org.bukkit.Material.DIODE_BLOCK_OFF; import static org.bukkit.Material.DIODE_BLOCK_ON; import static org.bukkit.Material.DOUBLE_STEP; import static org.bukkit.Material.DOUBLE_STONE_SLAB2; import static org.bukkit.Material.ENDER_PORTAL; import static org.bukkit.Material.ENDER_PORTAL_FRAME; import static org.bukkit.Material.END_CRYSTAL; import static org.bukkit.Material.END_GATEWAY; import static org.bukkit.Material.EXPLOSIVE_MINECART; import static org.bukkit.Material.FIRE; import static org.bukkit.Material.FLOWER_POT; import static org.bukkit.Material.HOPPER_MINECART; import static org.bukkit.Material.IRON_DOOR_BLOCK; import static org.bukkit.Material.JUKEBOX; import static org.bukkit.Material.LAVA; import static org.bukkit.Material.MELON_STEM; import static org.bukkit.Material.MINECART; import static org.bukkit.Material.MOB_SPAWNER; import static org.bukkit.Material.MONSTER_EGG; import static org.bukkit.Material.MONSTER_EGGS; import static org.bukkit.Material.NETHER_WARTS; import static org.bukkit.Material.PISTON_EXTENSION; import static org.bukkit.Material.PISTON_MOVING_PIECE; import static org.bukkit.Material.PORTAL; import static org.bukkit.Material.POTATO; import static org.bukkit.Material.POWERED_MINECART; import static org.bukkit.Material.POWERED_RAIL; import static org.bukkit.Material.PUMPKIN_STEM; import static org.bukkit.Material.PURPUR_DOUBLE_SLAB; import static org.bukkit.Material.RAILS; import static org.bukkit.Material.REDSTONE_COMPARATOR_OFF; import static org.bukkit.Material.REDSTONE_COMPARATOR_ON; import static org.bukkit.Material.REDSTONE_LAMP_ON; import static org.bukkit.Material.REDSTONE_TORCH_OFF; import static org.bukkit.Material.SIGN_POST; import static org.bukkit.Material.SKULL; import static org.bukkit.Material.SOIL; import static org.bukkit.Material.STANDING_BANNER; import static org.bukkit.Material.STATIONARY_LAVA; import static org.bukkit.Material.STATIONARY_WATER; import static org.bukkit.Material.STORAGE_MINECART; import static org.bukkit.Material.STRUCTURE_BLOCK; import static org.bukkit.Material.STRUCTURE_VOID; import static org.bukkit.Material.SUGAR_CANE_BLOCK; import static org.bukkit.Material.TNT; import static org.bukkit.Material.TRIPWIRE; import static org.bukkit.Material.WALL_BANNER; import static org.bukkit.Material.WALL_SIGN; import static org.bukkit.Material.WATER; import static org.bukkit.Material.WOODEN_DOOR; import static org.bukkit.Material.WOOD_DOUBLE_STEP; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; import co.sblock.Sblock; import co.sblock.chat.Chat; import co.sblock.chat.Language; import co.sblock.events.listeners.SblockListener; import co.sblock.events.packets.SyncPacketAdapter; import co.sblock.events.session.Status; import co.sblock.events.session.StatusCheck; import co.sblock.module.Module; import co.sblock.utilities.TextUtils; import com.comphenix.protocol.ProtocolLibrary; import com.google.common.collect.ImmutableList; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.scheduler.BukkitTask; import org.reflections.Reflections; /** * The main Module for all events handled by the plugin. * * @author Jikoo */ public class Events extends Module { private final LinkedHashMap<String, String> ipcache; private final HashMap<UUID, BukkitTask> pvp; private final InvisibilityManager invisibilityManager; private final BlockUpdateManager blockUpdateManager; private final List<String> spamhausWhitelist; private final EnumSet<Material> creativeBlacklist; private Chat chat; private Status status; private int statusResample = 0; public Events(Sblock plugin) { super(plugin); this.pvp = new HashMap<>(); this.ipcache = new LinkedHashMap<>(); this.invisibilityManager = new InvisibilityManager(plugin); this.blockUpdateManager = new BlockUpdateManager(plugin); this.spamhausWhitelist = new CopyOnWriteArrayList<>(this.getConfig().getStringList("spamWhitelist")); creativeBlacklist = EnumSet.of(ACTIVATOR_RAIL, BARRIER, BEACON, BED_BLOCK, BEDROCK, BEETROOT_BLOCK, BURNING_FURNACE, CAKE_BLOCK, CARROT, COCOA, COMMAND, COMMAND_CHAIN, COMMAND_MINECART, COMMAND_REPEATING, CROPS, DAYLIGHT_DETECTOR_INVERTED, DETECTOR_RAIL, DIODE_BLOCK_OFF, DIODE_BLOCK_ON, DOUBLE_STEP, DOUBLE_STONE_SLAB2, PURPUR_DOUBLE_SLAB, END_CRYSTAL, END_GATEWAY, ENDER_PORTAL, ENDER_PORTAL_FRAME, EXPLOSIVE_MINECART, FIRE, FLOWER_POT, HOPPER_MINECART, IRON_DOOR_BLOCK, JUKEBOX, LAVA, MELON_STEM, MINECART, MOB_SPAWNER, MONSTER_EGG, MONSTER_EGGS, NETHER_WARTS, PISTON_EXTENSION, PISTON_MOVING_PIECE, PORTAL, POTATO, POWERED_MINECART, POWERED_RAIL, PUMPKIN_STEM, RAILS, REDSTONE_COMPARATOR_OFF, REDSTONE_COMPARATOR_ON, REDSTONE_LAMP_ON, REDSTONE_TORCH_OFF, SIGN_POST, SKULL, SOIL, STANDING_BANNER, STATIONARY_LAVA, STATIONARY_WATER, STORAGE_MINECART, STRUCTURE_BLOCK, STRUCTURE_VOID, SUGAR_CANE_BLOCK, TNT, TRIPWIRE, WALL_BANNER, WALL_SIGN, WATER, WOOD_DOUBLE_STEP, WOODEN_DOOR); } @Override protected void onEnable() { this.chat = this.getPlugin().getModule(Chat.class); File file = new File(getPlugin().getDataFolder(), "ipcache.yml"); if (file.exists()) { YamlConfiguration yaml = YamlConfiguration.loadConfiguration(file); for (String ip : yaml.getKeys(false)) { ipcache.put(ip.replace("_", "."), yaml.getString(ip)); } } status = Status.NEITHER; new StatusCheck().runTaskTimerAsynchronously(getPlugin(), 100L, 1200L); Reflections reflections = new Reflections("co.sblock.events.listeners"); Set<Class<? extends SblockListener>> listeners = reflections.getSubTypesOf(SblockListener.class); for (Class<? extends SblockListener> listener : listeners) { if (!Sblock.areDependenciesPresent(listener)) { getLogger().info(listener.getSimpleName() + " dependencies not found."); continue; } try { Constructor<? extends SblockListener> constructor = listener.getConstructor(getPlugin().getClass()); Bukkit.getPluginManager().registerEvents(constructor.newInstance(getPlugin()), getPlugin()); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) { getLogger().severe("Unable to register events for " + listener.getName() + "!"); e.printStackTrace(); } } ProtocolLibrary.getProtocolManager().addPacketListener(new SyncPacketAdapter(getPlugin())); } @Override protected void onDisable() { this.getConfig().set("spamWhitelist", spamhausWhitelist); try { File file = new File(getPlugin().getDataFolder(), "ipcache.yml"); if (!file.exists()) { file.createNewFile(); } YamlConfiguration yaml = new YamlConfiguration(); for (Entry<String, String> entry : ipcache.entrySet()) { yaml.set(entry.getKey().replace(".", "_"), entry.getValue()); } yaml.save(file); } catch (IOException e) { getLogger().warning("Failed to save IP cache!"); getLogger().warning(TextUtils.getTrace(e)); } } /** * Gets the HashMap PVP ending scheduled for players by UUID. */ public HashMap<UUID, BukkitTask> getPVPTasks() { return pvp; } /** * Gets the creative material blacklist. */ public Set<Material> getCreativeBlacklist() { return this.creativeBlacklist; } /** * Gets the player name stored for an IP. */ public String getIPName(String ip) { synchronized (ipcache) { if (ipcache.containsKey(ip)) { return ipcache.get(ip); } return "Player"; } } /** * Cache a player name for an IP. Resets cache position for existing IPs. */ public void addCachedIP(String ip, String name) { synchronized (ipcache) { if (ipcache.containsKey(ip)) { // LinkedHashMaps replace the existing element, preserving order. We want latest logins last. ipcache.remove(ip); } ipcache.put(ip, name); // Clear oldest cached IPs int surplus = ipcache.size() - 1500; if (surplus < 1) { return; } for (Object entry : ipcache.entrySet().toArray()) { if (surplus <= 0) { break; } --surplus; ipcache.remove(((Entry<?, ?>) entry).getKey()); } } } /** * Get all cached IPs for a UUID. * * @param uuid the UUID * * @return a Collection of all matching IPs. */ public Collection<String> getIPsFor(UUID uuid) { OfflinePlayer offline = Bukkit.getOfflinePlayer(uuid); if (!offline.hasPlayedBefore()) { return ImmutableList.of(); } return getIPsFor(offline.getName()); } /** * Get all cached IPs for a name. * * @param name the name * * @return a Collection of all matching IPs. */ public Collection<String> getIPsFor(String name) { synchronized (ipcache) { ArrayList<String> list = new ArrayList<>(); for (Map.Entry<String, String> entry : ipcache.entrySet()) { if (entry.getValue().equals(name)) { list.add(entry.getKey()); } } return list; } } /** * Change the Status of Minecraft's servers. * <p> * If a service is down, this will announce the issue to all players and set * a relevant MOTD. * * @param status the Status */ public void changeStatus(Status status) { if (status == this.status) { statusResample = 0; return; } if (statusResample < 5) { // less spam - must have status change 5 times in a row to announce. statusResample++; new StatusCheck().runTaskLaterAsynchronously(getPlugin(), 50L); return; } String announcement = null; if (status.hasAnnouncement()) { announcement = status.getAnnouncement(); } else { announcement = this.status.getAllClear(); } if (announcement != null) { this.chat.getHalBase().setMessage(Language.getColor("bot_text") + announcement) .toMessage().send(Bukkit.getOnlinePlayers(), true, false); this.statusResample = 0; } this.status = status; } /** * Gets the current Status. */ public Status getStatus() { return status; } public InvisibilityManager getInvisibilityManager() { return invisibilityManager; } public BlockUpdateManager getBlockUpdateManager() { return blockUpdateManager; } public List<String> getSpamhausWhitelist() { return spamhausWhitelist; } @Override public boolean isRequired() { return true; } @Override public String getName() { return "Events"; } }
/** * 项目名称 :信智互联 * 类一览: * Commonutil 共通类 */ package com.fbse.recommentmobilesystem.common; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Properties; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; /** * <dl> * <dd>功能名:共通工具包 * <dd>功能说明:完成对字符的校验。 * @version V1.0 2014/05/15 * @author 张宁 */ public class Commonutil { /** * 读取res/raw/message文件 * @param context 上下文 * @return 返回Properties文件对象 */ public static Properties loadProperties(Context context) { // 创建Properties对象 Properties props = new Properties(); try { // 获得资源id int id = context.getResources().getIdentifier(CommonConst.MESSAGE, CommonConst.RAW, context.getPackageName()); // 加载资源文件 props.load(context.getResources().openRawResource(id)); } catch (Exception e) { e.printStackTrace(); return props; } return props; } /** * 读取res/raw/androidpn文件 * @param context 上下文 * @return 返回Properties文件对象 */ public static Properties loadIPProperties(Context context) { // 创建Properties对象 Properties props = new Properties(); try { int id = context.getResources().getIdentifier(CommonConst.ANDROIDPN, CommonConst.RAW, context.getPackageName()); // 加载资源文件 props.load(context.getResources().openRawResource(id)); } catch (Exception e) { e.printStackTrace(); return props; } return props; } /** * 检测网络环境是否良好 * @param context 上下文 * @return false */ public static boolean isNetworkAvailable(Context context) { // 获得系统连接管理者 ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (null != info) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { // 如果网络状态正常则返回true return true; } } } } // NETERROR Properties properties = Commonutil.loadProperties(context); // 提示是否网络状态异常 MessageUtil.commonToast(context, properties.getProperty(Msg.E0008, CommonConst.SPACE), Toast.LENGTH_SHORT); return false; } /** * 加载网络图片,生成没有缓存的额图片 * @param imageURL 图片url地址 * @return bitmap */ public static synchronized Bitmap loadBitmapWithOutCash(String imageURL) { // 转换地址为输入流 InputStream bitmapIs = getStreamFromURL(imageURL); // 转换为Bitmap类型 Bitmap bitmap = BitmapFactory.decodeStream(bitmapIs); return bitmap; } /** * 将图片地址转换为流 * @param imageURL 图片url地址 * @return 图片流 */ public static synchronized InputStream getStreamFromURL(String imageURL) { InputStream in = null; try { URL url = new URL(imageURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(10000); in = connection.getInputStream(); } catch (Exception e) { e.printStackTrace(); } return in; } }
/** * This simple class generates the rules (patterns) for 2 of the connect 4 variants. * * @author Jesper Kristensen */ public class GeneratePatterns { public final int MAX_LINE_LENGTH = 80; private int count; private int lineLength; private long b(int column, int row) { return 1L << (7*row + column); } private long b(int x, int y, int z) { return 1L << (x + 4*y + 16*z); } private void init() { System.out.println("private static final long[] PATTERNS = {"); count = 0; lineLength = 0; } private void finish() { System.out.println("};"); System.out.println("// PATTERNS.length == " + count); System.out.flush(); } private void put(long l) { if (count++ > 0) System.out.print(", "); int w; if (l > 0) { w = (int)(Math.log(1.0*l)/Math.log(10.0)) + 4; } else { w = (int)(Math.log(l + Math.pow(2, 64))/Math.log(10.0)) + 4; } if (lineLength + w > MAX_LINE_LENGTH) { System.out.println(); lineLength = 0; } System.out.print("" + l + "L"); lineLength += w; } /** * Generates the rules for the normal connect 4 game. * The output is sent to <code>System.out</code> as a java definition of a long array - * one entry for each pattern (representing a winning combination). */ public void connectFour() { init(); // Check vertical lines. for (int column=0; column<7; column++) for (int row=5; row>=3; row--) put(b(column,row) | b(column,row-1) | b(column,row-2) | b(column,row-3)); // Check horizontal lines. for (int column=0; column<=3; column++) for (int row=0; row<6; row++) put(b(column,row) | b(column+1,row) | b(column+2,row) | b(column+3,row)); // Check both kind of diagonal lines. for (int column=0; column<=3; column++) for (int row=5; row>=3; row--) { put(b(column,row) | b(column+1,row-1) | b(column+2,row-2) | b(column+3,row-3)); put(b(column+3,row) | b(column+2,row-1) | b(column+1,row-2) | b(column,row-3)); } finish(); } /** * Generates the rules for the square version. * The output is sent to <code>System.out</code> as a java definition of a long array - * one entry for each pattern (representing a winning combination). */ public void connectSquare() { init(); for (int column=0; column<7; column++) for (int row=0; row<6; row++) for (int x=0; x<6; x++) for (int y=0; y<6; y++) if ((x!=0 || y!=0) && (0<=column+x && column+x<7 && 0<=row+y && row+y<6) && (0<=column+x+y && column+x+y<7 && 0<=row+y-x && row+y-x<6) && (0<=column+y && column+y<7 && 0<=row-x && row-x<6)) put(b(column,row) | b(column+x,row+y) | b(column+x+y,row+y-x) | b(column+y,row-x)); finish(); } /** * Generates the rules for the 3D version. * The output is sent to <code>System.out</code> as a java definition of a long array - * one entry for each pattern (representing a winning combination). */ public void connect3D() { init(); for (int x=0; x<4; x++) { for (int y=0; y<4; y++) put(b(x,y,0) | b(x,y,1) | b(x,y,2) | b(x,y,3)); for (int z=0; z<4; z++) put(b(x,0,z) | b(x,1,z) | b(x,2,z) | b(x,3,z)); put(b(x,0,0) | b(x,1,1) | b(x,2,2) | b(x,3,3)); put(b(x,0,3) | b(x,1,2) | b(x,2,1) | b(x,3,0)); } for (int y=0; y<4; y++) { for (int z=0; z<4; z++) put(b(0,y,z) | b(1,y,z) | b(2,y,z) | b(3,y,z)); put(b(0,y,0) | b(1,y,1) | b(2,y,2) | b(3,y,3)); put(b(0,y,3) | b(1,y,2) | b(2,y,1) | b(3,y,0)); } for (int z=0; z<4; z++) { put(b(0,0,z) | b(1,1,z) | b(2,2,z) | b(3,3,z)); put(b(0,3,z) | b(1,2,z) | b(2,1,z) | b(3,0,z)); } // The 4 diagonals put(b(0,0,0) | b(1,1,1) | b(2,2,2) | b(3,3,3)); put(b(0,0,3) | b(1,1,2) | b(2,2,1) | b(3,3,0)); put(b(0,3,0) | b(1,2,1) | b(2,1,2) | b(3,0,3)); put(b(0,3,3) | b(1,2,2) | b(2,1,1) | b(3,0,0)); finish(); } }
package entity; import java.io.Serializable; /** * @author zhanglj * Óû§ÊµÌå * */ public class User implements Serializable { private int userid; private String name; private String identity_number; private String account; private String password; private int blance; public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIdentity_number() { return identity_number; } public void setIdentity_number(String identity_number) { this.identity_number = identity_number; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getBlance() { return blance; } public void setBlance(int blance) { this.blance = blance; } @Override public String toString() { return "User [userid=" + userid + ", name=" + name + ", identity_number=" + identity_number + ", account=" + account + ", password=" + password + "]"; } public User(int userid, String name, String identity_number, String account, String password) { super(); this.userid = userid; this.name = name; this.identity_number = identity_number; this.account = account; this.password = password; } }
package com.t2c.Concessionaire.model; import java.util.Date; public class Transaction { private Date buyDate; private Date saleDate; private double buyPrice; private Double salePrice; public Date getBuyDate() { return buyDate; } public Date getSaleDate() { return saleDate; } public double getBuyPrice() { return buyPrice; } public Double getSalePrice() { return salePrice; } public Transaction(Date buyDate, Date saleDate, double buyPrice, Double salePrice) { this.buyDate = buyDate; this.saleDate = saleDate; this.buyPrice = buyPrice; this.salePrice = salePrice; } public double computeTransactionBenefit() { double benefits = 0; if(this.saleDate != null && this.salePrice != null) benefits = this.salePrice; return benefits - this.buyPrice; } }
package thread; class Calculo { static Integer token = 1; synchronized void executa(char caracter) { // synchronized (this) { for (int x = 0; x < 10000; x++) { System.out.print(caracter); if (x % 1000 == 0) { System.out.print('\n'); } } // } } } class MinhaThread1 implements Runnable { Calculo calculo; public MinhaThread1(Calculo calculo) { this.calculo = calculo; } public void run() { // Igual a ideia do main(..) // Inicio // Meio // Fim calculo.executa('x'); } } class MinhaThread2 extends Thread { Calculo calculo; public MinhaThread2(Calculo calculo) { this.calculo = calculo; } @Override public void run() { // Inicio // Meio // Fim calculo.executa('y'); } } public class Test_Thread { public static void main(String[] args) throws Exception { // THIS Calculo calculo = new Calculo(); // T1 = estado NEW MinhaThread1 runnable = new MinhaThread1(calculo); Thread t1 = new Thread(runnable); // T2 = estado NEW MinhaThread2 t2 = new MinhaThread2(calculo); // T1 = estado RUNNABLE (running - ready) t1.start(); // T2 = estado RUNNABLE (running - ready) t2.start(); calculo.executa('m'); } }
package com.wangzhu.utils; import org.openjdk.jol.info.ClassLayout; /** * Created by wang.zhu on 2021-04-26 18:21. **/ public class TestStringNew { public static void main(String[] args) { String s1 = "hello"; //final String s1 = "hello"; String s2 = "world"; //final String s2 = "world"; final String s3 = s1 + s2; System.out.println(s3); System.out.println(ClassLayout.parseInstance(s3).toPrintable()); final Person person = new Person(); person.print(); } int method(int a,int b, int c){ return 0; } String method(int c,int d){ return ""; } }
package com.ngocdt.tttn.dto; import com.ngocdt.tttn.entity.Ingredient; import javax.persistence.Column; public class IngredientDTO { private int id; private String description; public static IngredientDTO toDTO(Ingredient ingredient){ if(ingredient == null) return null; IngredientDTO dto = new IngredientDTO(); dto.setId(ingredient.getId()); dto.setDescription(ingredient.getDescription()); return dto; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
package com.nepshop.controller; import com.nepshop.dao.UserDAO; import com.nepshop.model.User; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; 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 javax.servlet.http.Part; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @WebServlet(urlPatterns = "/userservlet", loadOnStartup = 1) @MultipartConfig(maxFileSize = 16177215) public class UserServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String action = req.getParameter("action"); if (action.equals("list")) { setUsers(req); RequestDispatcher rd = req.getRequestDispatcher("/includes/dashboard/user.jsp"); rd.forward(req, res); } else if (action.equals("delete")) { int id = Integer.parseInt(req.getParameter("id")); boolean rs = UserDAO.deleteUser(id); RequestDispatcher rd = null; if (rs) { HttpSession session = req.getSession(); User user = (User) session.getAttribute("user"); int userId = user.getId(); if (userId == id) { session.removeAttribute("user"); // session.invalidate(); setToastMessage(req, "Your account is successfully deleted.", "success"); rd = req.getRequestDispatcher("/includes/ecommerce/login.jsp"); } else { setUsers(req); setToastMessage(req, "User is successfully deleted.", "success"); rd = req.getRequestDispatcher("/includes/dashboard/user.jsp"); } } else { setUsers(req); setToastMessage(req, "User cannot be deleted right now. Please try again later.", "error"); rd = req.getRequestDispatcher("/includes/dashboard/user.jsp"); } rd.forward(req, res); } else if (action.equals("populate")) { int id = Integer.parseInt(req.getParameter("id")); User user = UserDAO.getUser(id); req.setAttribute("user", user); req.setAttribute("flag", true); setUsers(req); RequestDispatcher rd = req.getRequestDispatcher("/includes/dashboard/user.jsp"); rd.forward(req, res); } } @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String action = req.getParameter("action"); if (action.equals("create")) { String name = req.getParameter("name"); String email = req.getParameter("email"); String password = req.getParameter("password"); String gender = req.getParameter("gender"); Part filePart = req.getPart("photo"); boolean rs = false; if (filePart.getSize() > 0) { InputStream inputStream = filePart.getInputStream(); rs = UserDAO.createUser(name, email, password, gender, inputStream); } else { rs = UserDAO.createUser(name, email, password, gender); } if (rs) { setToastMessage(req, "User is successfully created.", "success"); } else { setToastMessage(req, "User cannot be created right now. Please try again later.", "error"); } setUsers(req); RequestDispatcher rd = req.getRequestDispatcher("/includes/dashboard/user.jsp"); rd.forward(req, res); } else if (action.equals("update")) { int id = Integer.parseInt(req.getParameter("id")); String name = req.getParameter("name"); String email = req.getParameter("email"); String password = req.getParameter("password"); String gender = req.getParameter("gender"); Part filePart = req.getPart("photo"); boolean rs = false; if (filePart.getSize() > 0) { InputStream inputStream = filePart.getInputStream(); rs = UserDAO.updateUser(id, name, email, password, gender, inputStream); } else { rs = UserDAO.updateUser(id, name, email, password, gender); } if (rs) { setToastMessage(req, "User is successfully updated.", "success"); } else { setToastMessage(req, "User cannot be updated right now. Please try again later.", "error"); } HttpSession session = req.getSession(); User sessionUser = (User) session.getAttribute("user"); if (sessionUser.getId() == id) { String photo = UserDAO.getPhoto(id); User user = new User(id, name, email, password, gender, photo); session.setAttribute("user", user); } setUsers(req); RequestDispatcher rd = req.getRequestDispatcher("/includes/dashboard/user.jsp"); rd.forward(req, res); } else if (action.equals("update_ac_info")) { int id = Integer.parseInt(req.getParameter("id")); String name = req.getParameter("name"); String email = req.getParameter("email"); String gender = req.getParameter("gender"); Part filePart = req.getPart("photo"); boolean rs = false; if (filePart.getSize() > 0) { InputStream inputStream = filePart.getInputStream(); rs = UserDAO.updateAcInfo(id, name, email, gender, inputStream); } else { rs = UserDAO.updateAcInfo(id, name, email, gender); } if (rs) { HttpSession session = req.getSession(); String password = UserDAO.getPassword(id); String photo = UserDAO.getPhoto(id); User user = new User(id, name, email, password, gender, photo); session.setAttribute("user", user); setToastMessage(req, "Your account information is successfully updated.", "success"); } else { setToastMessage(req, "Your account information cannot be updated right now. Please try again later.", "error"); } res.sendRedirect("/includes/dashboard/accountsettings.jsp"); } else if (action.equals("update_ac_password")) { int id = Integer.parseInt(req.getParameter("id")); String oldPassword = req.getParameter("old-password"); String newPassword = req.getParameter("new-password"); boolean rs = UserDAO.updateAcPassword(id, oldPassword, newPassword); if (rs) { setToastMessage(req, "Your account password is successfully changed.", "success"); } else { setToastMessage(req, "The current password you have entered is incorrect.", "error"); } RequestDispatcher rd = req.getRequestDispatcher("/includes/dashboard/accountsettings.jsp"); rd.forward(req, res); } else if (action.equals("delete_ac")) { int id = Integer.parseInt(req.getParameter("id")); String password = req.getParameter("password"); boolean rs = UserDAO.deleteAc(id, password); RequestDispatcher rd = null; PrintWriter out = res.getWriter(); out.println(rs); HttpSession session = req.getSession(); if (rs) { session.removeAttribute("user"); // session.invalidate(); setToastMessage(req, "Your account is successfully deleted.", "success"); rd = req.getRequestDispatcher("/includes/ecommerce/login.jsp"); } else { setToastMessage(req, "The current password you have entered is incorrect.", "error"); rd = req.getRequestDispatcher("/includes/dashboard/accountsettings.jsp"); } rd.forward(req, res); } } void setUsers(HttpServletRequest req) { List<User> users = UserDAO.getUsers(); req.setAttribute("users", users); } void setToastMessage(HttpServletRequest req, String message, String type) { HttpSession session = req.getSession(); List<String> toast = new ArrayList<String>(Arrays.asList(message, type)); session.setAttribute("toast", toast); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.annotation; import java.lang.reflect.Method; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Predicate; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.AutowireCandidateQualifier; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Convenience methods performing bean lookups related to Spring-specific annotations, * for example Spring's {@link Qualifier @Qualifier} annotation. * * @author Juergen Hoeller * @author Chris Beams * @since 3.1.2 * @see BeanFactoryUtils */ public abstract class BeanFactoryAnnotationUtils { /** * Retrieve all beans of type {@code T} from the given {@code BeanFactory} declaring a * qualifier (e.g. via {@code <qualifier>} or {@code @Qualifier}) matching the given * qualifier, or having a bean name matching the given qualifier. * @param beanFactory the factory to get the target beans from (also searching ancestors) * @param beanType the type of beans to retrieve * @param qualifier the qualifier for selecting among all type matches * @return the matching beans of type {@code T} * @throws BeansException if any of the matching beans could not be created * @since 5.1.1 * @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class) */ public static <T> Map<String, T> qualifiedBeansOfType( ListableBeanFactory beanFactory, Class<T> beanType, String qualifier) throws BeansException { String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, beanType); Map<String, T> result = new LinkedHashMap<>(4); for (String beanName : candidateBeans) { if (isQualifierMatch(qualifier::equals, beanName, beanFactory)) { result.put(beanName, beanFactory.getBean(beanName, beanType)); } } return result; } /** * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a * qualifier (e.g. via {@code <qualifier>} or {@code @Qualifier}) matching the given * qualifier, or having a bean name matching the given qualifier. * @param beanFactory the factory to get the target bean from (also searching ancestors) * @param beanType the type of bean to retrieve * @param qualifier the qualifier for selecting between multiple bean matches * @return the matching bean of type {@code T} (never {@code null}) * @throws NoUniqueBeanDefinitionException if multiple matching beans of type {@code T} found * @throws NoSuchBeanDefinitionException if no matching bean of type {@code T} found * @throws BeansException if the bean could not be created * @see BeanFactoryUtils#beanOfTypeIncludingAncestors(ListableBeanFactory, Class) */ public static <T> T qualifiedBeanOfType(BeanFactory beanFactory, Class<T> beanType, String qualifier) throws BeansException { Assert.notNull(beanFactory, "BeanFactory must not be null"); if (beanFactory instanceof ListableBeanFactory lbf) { // Full qualifier matching supported. return qualifiedBeanOfType(lbf, beanType, qualifier); } else if (beanFactory.containsBean(qualifier)) { // Fallback: target bean at least found by bean name. return beanFactory.getBean(qualifier, beanType); } else { throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() + " bean found for bean name '" + qualifier + "'! (Note: Qualifier matching not supported because given " + "BeanFactory does not implement ConfigurableListableBeanFactory.)"); } } /** * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier * (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier). * @param bf the factory to get the target bean from * @param beanType the type of bean to retrieve * @param qualifier the qualifier for selecting between multiple bean matches * @return the matching bean of type {@code T} (never {@code null}) */ private static <T> T qualifiedBeanOfType(ListableBeanFactory bf, Class<T> beanType, String qualifier) { String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType); String matchingBean = null; for (String beanName : candidateBeans) { if (isQualifierMatch(qualifier::equals, beanName, bf)) { if (matchingBean != null) { throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName); } matchingBean = beanName; } } if (matchingBean != null) { return bf.getBean(matchingBean, beanType); } else if (bf.containsBean(qualifier)) { // Fallback: target bean at least found by bean name - probably a manually registered singleton. return bf.getBean(qualifier, beanType); } else { throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() + " bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!"); } } /** * Check whether the named bean declares a qualifier of the given name. * @param qualifier the qualifier to match * @param beanName the name of the candidate bean * @param beanFactory the factory from which to retrieve the named bean * @return {@code true} if either the bean definition (in the XML case) * or the bean's factory method (in the {@code @Bean} case) defines a matching * qualifier value (through {@code <qualifier>} or {@code @Qualifier}) * @since 5.0 */ public static boolean isQualifierMatch( Predicate<String> qualifier, String beanName, @Nullable BeanFactory beanFactory) { // Try quick bean name or alias match first... if (qualifier.test(beanName)) { return true; } if (beanFactory != null) { for (String alias : beanFactory.getAliases(beanName)) { if (qualifier.test(alias)) { return true; } } try { Class<?> beanType = beanFactory.getType(beanName); if (beanFactory instanceof ConfigurableBeanFactory cbf) { BeanDefinition bd = cbf.getMergedBeanDefinition(beanName); // Explicit qualifier metadata on bean definition? (typically in XML definition) if (bd instanceof AbstractBeanDefinition abd) { AutowireCandidateQualifier candidate = abd.getQualifier(Qualifier.class.getName()); if (candidate != null) { Object value = candidate.getAttribute(AutowireCandidateQualifier.VALUE_KEY); if (value != null && qualifier.test(value.toString())) { return true; } } } // Corresponding qualifier on factory method? (typically in configuration class) if (bd instanceof RootBeanDefinition rbd) { Method factoryMethod = rbd.getResolvedFactoryMethod(); if (factoryMethod != null) { Qualifier targetAnnotation = AnnotationUtils.getAnnotation(factoryMethod, Qualifier.class); if (targetAnnotation != null) { return qualifier.test(targetAnnotation.value()); } } } } // Corresponding qualifier on bean implementation class? (for custom user types) if (beanType != null) { Qualifier targetAnnotation = AnnotationUtils.getAnnotation(beanType, Qualifier.class); if (targetAnnotation != null) { return qualifier.test(targetAnnotation.value()); } } } catch (NoSuchBeanDefinitionException ex) { // Ignore - can't compare qualifiers for a manually registered singleton object } } return false; } }
package com.pointinside.android.app.util; import android.os.Bundle; import android.os.Handler; import android.os.ResultReceiver; import android.util.Log; public class DetachableResultReceiver extends ResultReceiver { private static final String TAG = "DetachableResultReceiver"; private Receiver mReceiver; public DetachableResultReceiver(Handler paramHandler) { super(paramHandler); } public void clearReceiver() { this.mReceiver = null; } protected void onReceiveResult(int paramInt, Bundle paramBundle) { if (this.mReceiver != null) { this.mReceiver.onReceiveResult(paramInt, paramBundle); return; } Log.w("DetachableResultReceiver", "Dropping result on floor for code " + paramInt + ": " + paramBundle.toString()); } public void setReceiver(Receiver paramReceiver) { this.mReceiver = paramReceiver; } public static abstract interface Receiver { public abstract void onReceiveResult(int paramInt, Bundle paramBundle); } } /* Location: D:\xinghai\dex2jar\classes-dex2jar.jar * Qualified Name: com.pointinside.android.app.util.DetachableResultReceiver * JD-Core Version: 0.7.0.1 */
package video.api.android.sdk.domain; public class Term { private String startAt; private String endAt; public Term(String startAt, String endAt) { this.startAt = startAt; this.endAt = endAt; } public Term() { } public String getStartAt() { return startAt; } public void setStartAt(String startAt) { this.startAt = startAt; } public String getEndAt() { return endAt; } public void setEndAt(String endAt) { this.endAt = endAt; } }
package ru.shikhovtsev.core; public class UsingMultipleIdException extends RuntimeException { public UsingMultipleIdException(String message) { super(message); } }
import java.util.*; public class Algorithms { public static void main(String[] args) { Vertex a = new Vertex(0, false); Vertex b = new Vertex(1, false); Vertex c = new Vertex(2, false); Vertex d = new Vertex(3, false); Vertex[] vertices = {a, b, c, d}; Edge[][] edges = { {new Edge(0, 1, 5), new Edge(0, 2, 6), new Edge(0, 3, 8)}, {new Edge(1, 0, 5), new Edge(1, 2, 10), new Edge(1, 3, 3)}, {new Edge(2, 0, 6), new Edge(2, 1, 10), new Edge(2, 3, 2)}, {new Edge(3, 0, 8), new Edge(3, 1, 3), new Edge(3, 2, 2)}, }; Graph graph = new Graph(vertices, edges); int[] randomPath = new int[4]; randomPath = graph.random().clone(); System.out.println("The path generated by random method is: " + Arrays.toString(randomPath)); graph.reset(); System.out.println("The best path generated by iterative method is: " + Arrays.toString(graph.iterative()) + "\n"); graph.reset(); System.out.println("The path generated by greedy algorithm is: " + Arrays.toString(graph.greedy())); System.out.println("The path generated by greedy optimization algorithm is: " + Arrays.toString(graph.greedyOptimization(randomPath))); System.out.println("The path generated by greedy optimization algorithm is: " + Arrays.toString(graph.greedyRandomOptimization(randomPath))); Graph graph1000 = new Graph(new Vertex[1000], new Edge[1000][999]); Graph graph2000 = new Graph(new Vertex[2000], new Edge[2000][1999]); Graph graph5000 = new Graph(new Vertex[5000], new Edge[5000][4999]); Graph graph10000 = new Graph(new Vertex[10000], new Edge[10000][9999]); graph1000 = graph1000.graphGenerator(1000); graph2000 = graph2000.graphGenerator(2000); graph5000 = graph5000.graphGenerator(5000); graph10000 = graph10000.graphGenerator(10000); System.out.println("\n\n\nGraph with a 1000 cities has been generated. \nNow diffrent algorithms will be run with it:"); System.out.println("Ok? (1 for yes)"); Scanner input = new Scanner(System.in); int s = input.nextInt(); int[] randomPath1000 = new int[1000]; randomPath1000 = graph1000.random().clone(); if(s == 1) { System.out.println("The path generated by random method is: " + Arrays.toString(randomPath1000)); graph1000.reset(); } System.out.println("\nRandom method has been executed. Continue to Iterative? (1 for yes)"); s = input.nextInt(); if(s == 1) { System.out.println("The best path generated by iterative method is: " + Arrays.toString(graph1000.iterative()) + "\n"); graph1000.reset(); } System.out.println("\nIterative method has been executed. Continue to Greedy? (1 for yes)"); s = input.nextInt(); if(s == 1) { System.out.println("The path generated by greedy algorithm is: " + Arrays.toString(graph1000.greedy())); } System.out.println("\nGreedy method has been executed. Continue to Greedy Optimization? (1 for yes)"); s = input.nextInt(); if(s == 1) { System.out.println("The path generated by greedy optimization algorithm is: " + Arrays.toString(graph1000.greedyOptimization(randomPath1000))); } System.out.println("\nGreedy optimization method has been executed. Continue to Greedy random optimization? (1 for yes)"); s = input.nextInt(); if(s == 1) { System.out.println("The path generated by greedy optimization algorithm is: " + Arrays.toString(graph1000.greedyRandomOptimization(randomPath1000))); } System.out.println("The program has finished running successfully."); } } class Vertex { int index; boolean visited; Vertex (int index, boolean visited) { this.index = index; this.visited = visited; } } class Edge { int startIndex; int endIndex; int value; Edge (int startIndex, int endIndex, int value) { this.startIndex = startIndex; this.endIndex = endIndex; this.value = value; } } class Graph { Vertex[] vertices; Edge[][] edges; Graph ( Vertex[] vertices, Edge[][] edges) { this.vertices = vertices; this.edges = edges; } public int[] random() { int[] randomPath = new int[vertices.length]; int visited = 0; int randomVertexToGoTo = (int)(Math.random() * vertices.length); int cost = 0; Vertex current = vertices[randomVertexToGoTo]; current.visited = true; randomPath[visited] = current.index; while(visited < vertices.length - 1) { randomVertexToGoTo = (int)(Math.random() * vertices.length); if(vertices[randomVertexToGoTo].index != current.index && vertices[randomVertexToGoTo].visited == false) { int i = 0; Edge theEdge = edges[current.index][i]; while (edges[current.index][i].endIndex != randomVertexToGoTo) { i++; theEdge = edges[current.index][i]; } vertices[randomVertexToGoTo].visited = true; cost += theEdge.value; visited++; current = vertices[randomVertexToGoTo]; randomPath[visited] = randomVertexToGoTo; } } System.out.println("RANDOM METHOD"); return randomPath; } public void reset() { for(int i = 0; i < vertices.length; i++) { vertices[i].visited = false; } } public int[] iterative() { Scanner input = new Scanner(System.in); int count = 0; int svar = 1; int[] bestResult = new int[vertices.length]; int minCost = 0; while(count < 10) { count++; int[] randomPath = new int[vertices.length]; int visited = 0; int randomVertexToGoTo = (int)(Math.random() * vertices.length); int cost = 0; Vertex current = vertices[randomVertexToGoTo]; current.visited = true; randomPath[visited] = current.index; while(visited < vertices.length - 1) { randomVertexToGoTo = (int)(Math.random() * vertices.length); if(vertices[randomVertexToGoTo].index != current.index && vertices[randomVertexToGoTo].visited == false) { int i = 0; Edge theEdge = edges[current.index][i]; while (edges[current.index][i].endIndex != randomVertexToGoTo) { i++; theEdge = edges[current.index][i]; } vertices[randomVertexToGoTo].visited = true; cost += theEdge.value; visited++; current = vertices[randomVertexToGoTo]; randomPath[visited] = randomVertexToGoTo; } } if(count == 1) { System.out.println("\nITERATIVE METHOD"); bestResult = randomPath; minCost = cost; } else if(cost < minCost && count != 1) { bestResult = randomPath; minCost = cost; } System.out.println("The best result found after " + count + " iteretions is: " + Arrays.toString(bestResult) + " and its cost is: " + minCost); reset(); } return bestResult; } public int[] greedy() { int[] randomPath = new int[vertices.length]; int visited = 0; int randomVertexToGoTo = (int)(Math.random() * vertices.length); int cost = 0; Vertex current = vertices[randomVertexToGoTo]; current.visited = true; randomPath[visited] = current.index; while(visited < vertices.length - 1) { Edge theEdge = edges[current.index][0]; Edge minEdge = theEdge; for(int k = 0; k < vertices.length - 1; k++) { theEdge = edges[current.index][k]; if (vertices[theEdge.endIndex].visited != true) { minEdge = theEdge; } } for(int k = 0; k < vertices.length - 1; k++) { theEdge = edges[current.index][k]; if (minEdge.value > theEdge.value && vertices[theEdge.endIndex].visited != true) { minEdge = theEdge; } } vertices[minEdge.endIndex].visited = true; cost += minEdge.value; visited++; current = vertices[minEdge.endIndex]; randomPath[visited] = minEdge.endIndex; } System.out.println("GREEDY ALGORITHM \nCost of the path generated by greedy algorithm is: " + cost); return randomPath; } public int[] greedyOptimization(int[] x) { System.out.println("\nGREEDY OPTIMIZATION \nInitial path: " + Arrays.toString(x)); int[] optimizedPath = x.clone(); for(int k = 0; k < 10; k++) { int[] holder = optimizedPath.clone(); int cost = 0; for(int j = 0; j < optimizedPath.length - 1; j++) { int i = 0; Edge theEdge = edges[optimizedPath[j]][i]; while (edges[optimizedPath[j]][i].endIndex != optimizedPath[j+1]) { i++; theEdge = edges[optimizedPath[j]][i]; } cost += theEdge.value; } if(k == 0) { System.out.println("Initial path cost: " + cost); } int c1, c2; do{ c1 = (int)(Math.random() * x.length); c2 = (int)(Math.random() * x.length); }while (c1 == c2); int temp = x[c1]; x[c1] = x[c2]; x[c2] = temp; int newCost = 0; for(int j = 0; j < x.length - 1; j++) { int i = 0; Edge theEdge = edges[x[j]][i]; while (edges[x[j]][i].endIndex != x[j+1]) { i++; theEdge = edges[x[j]][i]; } newCost += theEdge.value; } if(newCost < cost) { optimizedPath = x.clone(); } else { optimizedPath = holder.clone(); } if(k == 9) { System.out.println("Final path cost: " + cost); } } return optimizedPath; } public int[] greedyRandomOptimization(int[] x) { System.out.println("\nGREEDY RANDOM OPTIMIZATION \nInitial path: " + Arrays.toString(x)); int[] optimizedPath = x.clone(); int[] bestPath = x.clone(); int bestCost = 0; double PA = 0.9; int cost = 0; for(int j = 0; j < optimizedPath.length - 1; j++) { int i = 0; Edge theEdge = edges[optimizedPath[j]][i]; while (edges[optimizedPath[j]][i].endIndex != optimizedPath[j+1]) { i++; theEdge = edges[optimizedPath[j]][i]; } cost += theEdge.value; } System.out.println("Initial path cost: " + cost); int counter = 0; do { counter++; for(int k = 0; k < 10; k++) { int[] holder = optimizedPath.clone(); cost = 0; for(int j = 0; j < optimizedPath.length - 1; j++) { int i = 0; Edge theEdge = edges[optimizedPath[j]][i]; while (edges[optimizedPath[j]][i].endIndex != optimizedPath[j+1]) { i++; theEdge = edges[optimizedPath[j]][i]; } cost += theEdge.value; } bestCost = 0; for(int j = 0; j < bestPath.length - 1; j++) { int i = 0; Edge theEdge = edges[bestPath[j]][i]; while (edges[bestPath[j]][i].endIndex != bestPath[j+1]) { i++; theEdge = edges[bestPath[j]][i]; } bestCost += theEdge.value; } int c1, c2; do{ c1 = (int)(Math.random() * x.length); c2 = (int)(Math.random() * x.length); }while (c1 == c2); int temp = x[c1]; x[c1] = x[c2]; x[c2] = temp; int newCost = 0; for(int j = 0; j < x.length - 1; j++) { int i = 0; Edge theEdge = edges[x[j]][i]; while (edges[x[j]][i].endIndex != x[j+1]) { i++; theEdge = edges[x[j]][i]; } newCost += theEdge.value; } if(newCost < cost) { optimizedPath = x.clone(); if (newCost < bestCost) { bestPath = optimizedPath.clone(); } } else { optimizedPath = holder.clone(); double rnd = (double)(Math.random() * 100 / 100); if(rnd < PA) { optimizedPath = x.clone(); } } } PA = PA * 0.9; }while(PA > 0.0000001); System.out.println("Probability of acceptance after " + counter + " iterations is: " + PA); System.out.println("Best path cost: " + bestCost); return bestPath; } public Graph graphGenerator(int x) { Vertex[] vertices = new Vertex[x]; for(int i = 0; i < x; i++) { vertices[i] = new Vertex(i, false); } Edge[][] edges = new Edge[x][x-1]; for(int i = 0; i < x; i++) { int[] v = new int[x-1]; int f = 0; int g = 0; while(g < x-1) { if (f != i) { v[g] = f; g++; } f++; } for(int k = 0; k < x-1; k++) { int r = (int)(Math.random() * 10 + 1); edges[i][k] = new Edge(i, v[k], r); } } Graph graph = new Graph(vertices, edges); return graph; } }
package jp.ac.it_college.std.s14011.pdp; /** * Created by s14011 on 15/06/02. */ public interface Iterator { public abstract boolean hasNext(); }
package cj.oshopping.ec.user.batch.config; import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.support.ApplicationContextFactory; import org.springframework.batch.core.configuration.support.GenericApplicationContextFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import cj.oshopping.ec.user.batch.jobs.storedprocedure.StoredProcedureJob; import cj.oshopping.ec.user.batch.jobs.useraccountdump.UserAccountDumpJob; @Configuration @EnableBatchProcessing(modular = true) //@ComponentScan(basePackages={"cj.oshopping.ec.user.batch.jobs.storedprocedure"}) public class SpringBatchConfig extends DefaultBatchConfigurer { // TODO [gookeun.lim] Batch 의 DataSource 설정을 줄수 있어야 함. // @Bean(name="batchDataSource") // public DataSource dataSource() { // EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); // return builder // .setName("batchDb") // .setType(EmbeddedDatabaseType.H2) // .addScript("org/springframework/batch/core/schema-h2.sql") // .build(); // } @Bean(name="cj.oshopping.ec.user.batch.jobs.storedprocedure.StoredProcedureJob") public ApplicationContextFactory storedProcedureJob() { return new GenericApplicationContextFactory(StoredProcedureJob.class); } @Bean(name="cj.oshopping.ec.user.batch.jobs.useraccountdump.UserAccountDumpJob") public ApplicationContextFactory userAccountDumpJob() { return new GenericApplicationContextFactory(UserAccountDumpJob.class); } }
class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { HashMap<Integer,Integer> nextGreater=new HashMap<>(); Stack<Integer> stack=new Stack<>(); for(int i=nums2.length-1;i>=0;i--){ while(stack.size()>0 && stack.peek()<nums2[i]){ stack.pop(); } nextGreater.put(nums2[i],stack.size()==0?-1:stack.peek()); stack.push(nums2[i]); } for(int i=0;i<nums1.length;i++){ nums1[i]=nextGreater.get(nums1[i]); } return nums1; } }
package se.kth.eh2745.moritzv.assigment1.objects; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import org.w3c.dom.Element; import com.wphooper.number.Complex; import se.kth.eh2745.moritzv.assigment1.RdfLibary; import se.kth.eh2745.moritzv.assigment1.XmlParser; import se.kth.eh2745.moritzv.assigment1.db.MysqlField; import se.kth.eh2745.moritzv.assigment1.db.MysqlFieldTypes; import se.kth.eh2745.moritzv.assigment1.exception.VoltageLevelNotFoundException; import se.kth.eh2745.moritzv.assigment1.exception.XmlStructureNotAsAssumedException; public abstract class Equipment extends IdentifiedObject { protected RdfLink<EquipmentContainer> equipmentContainer; @SuppressWarnings("unchecked") public Equipment(Element element) throws XmlStructureNotAsAssumedException { super(element); this.equipmentContainer = (RdfLink<EquipmentContainer>) XmlParser.ParseRdfLink(element, "cim:Equipment.EquipmentContainer", this); } protected Equipment() { super(); } public static ArrayList<MysqlField> getTabelFields() { ArrayList<MysqlField> list = IdentifiedObject.getTabelFields(); list.add(new MysqlField("equipmentContainer_rdf:ID", MysqlFieldTypes.VARCHAR, 50)); return list; } @Override public int insertData(PreparedStatement statment) throws SQLException { int index = super.insertData(statment); statment.setString(index + 1, getEquipmentContainerRdfId()); return index + 1; } public Complex getAdmittanz(double sbase) throws VoltageLevelNotFoundException { return new Complex(0); } public Complex getShunt(double sbase) throws VoltageLevelNotFoundException { return new Complex(0); } public Collection<Terminal> getTerminals() { Collection<Terminal> allTerminals = RdfLibary.getAllofType(Terminal.class); Collection<Terminal> terminalsAtThis = new ArrayList<Terminal>(); for (Terminal terminal : allTerminals) { if (this.equals(terminal.getConductingEquipment())) { terminalsAtThis.add(terminal); } } return terminalsAtThis; } public Collection<Equipment> getConnectedEquipment() { return getConnectedEquipment(new ArrayList<Equipment>(), false); } public Collection<Equipment> getConnectedEquipment(Equipment ignore) { Collection<Equipment> list = new ArrayList<Equipment>(); list.add(ignore); return getConnectedEquipment(list, false); } public Collection<Equipment> getConnectedEquipment(boolean skipBreaker) { return getConnectedEquipment(new ArrayList<Equipment>(), true); } public Collection<Equipment> getConnectedEquipment(Equipment ignore, boolean skipBreaker) { Collection<Equipment> list = new ArrayList<Equipment>(); list.add(ignore); return getConnectedEquipment(list, skipBreaker); } public Collection<Equipment> getConnectedEquipment(Collection<Equipment> ignore, boolean skipBreaker) { Collection<Equipment> equipment = new LinkedHashSet<>(); // To have // unique // values for (Terminal terminal_here : this.getTerminals()) { Collection<Equipment> connected = getEquipmentBehandTerminal(ignore, terminal_here, skipBreaker); // returns null if ignore is connected to this Terminal (=> we // are going back) if (connected != null) { equipment.addAll(connected); } } return equipment; } private Collection<Equipment> getEquipmentBehandTerminal(Collection<Equipment> ignore, Terminal terminal_start, boolean skipBreaker) { Collection<Equipment> tempList = new ArrayList<Equipment>(); for (Terminal terminal_afterConNode : terminal_start.getConnectedTerminals()) { Equipment currentObj = terminal_afterConNode.getConductingEquipment(); if (ignore.contains(currentObj)) { return null; // We are going back, return // nothing } if (skipBreaker && currentObj instanceof Breaker) { if (!((Breaker) currentObj).isOpen()) { ignore.add(this); Collection<Equipment> connected = currentObj.getConnectedEquipment(ignore, true); if (!connected.isEmpty()) { tempList.addAll(connected); } else { return null; // Going back via breaker, skipping } } } else { if (currentObj != null) { tempList.add(currentObj); } } } return tempList; } public double getNominalVoltage() throws VoltageLevelNotFoundException { if (getEquipmentContainer() instanceof VoltageLevel) { return ((VoltageLevel) getEquipmentContainer()).getBaseVoltage().getNominalVoltage(); } Collection<Equipment> connectedEq = getConnectedEquipment(true); for (Equipment equipment : connectedEq) { if (equipment.getEquipmentContainer() instanceof VoltageLevel) { return ((VoltageLevel) equipment.getEquipmentContainer()).getBaseVoltage().getNominalVoltage(); } } throw new VoltageLevelNotFoundException(this.toString()); } public double getZBase(double sBase) throws VoltageLevelNotFoundException { double vBase = getNominalVoltage(); return vBase * vBase / sBase; } public EquipmentContainer getEquipmentContainer() { return equipmentContainer.getObj(); } public String getEquipmentContainerRdfId() { return equipmentContainer.getRdfId(); } }
package org.giddap.dreamfactory.leetcode.onlinejudge; import java.util.List; /** * <a href="http://oj.leetcode.com/problems/pascals-triangle/">Pascal's Triangle</a> * <p/> * Copyright 2013 LeetCode * <p/> * Given numRows, generate the first numRows of Pascal's triangle. * <p/> * For example, given numRows = 5, * Return * <p/> * [ * [1], * [1,1], * [1,2,1], * [1,3,3,1], * [1,4,6,4,1] * ] * <p/> * * @see <a href="http://discuss.leetcode.com/questions/283/pascals-triangle">Leetcode discussion</a> */ public interface PascalsTriangle { List<List<Integer>> generate(int numRows); }
package info.tasks5.sum10; import java.util.logging.Logger; public class Sum10 { private static Logger logger = Logger.getLogger(Sum10.class.getName()); public static void main(String[] args) { logger.info(" " + sumValue()); } public static int sumValue() { int n = 12345; int sum = 0; while (n != 0) { sum += (n % 10); n /= 10; } return sum; } }
package com.citibank.ods.modules.client.relationprvt.functionality; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.functionality.ODSListFnc; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO; import com.citibank.ods.modules.client.relationprvt.functionality.valueobject.RelationPrvtListFncVO; import com.citibank.ods.persistence.pl.dao.BaseTplRelationPrvtDAO; import com.citibank.ods.persistence.pl.dao.TplRelationPrvtDAO; import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory; // //©2002-2007 Accenture. All rights reserved. // /** * [Class description] * * @see package com.citibank.ods.modules.client.relationprvt.functionality; * @version 1.0 * @author gerson.a.rodrigues,Mar 29, 2007 * * <PRE> * * <U>Updated by: </U> <U>Description: </U> * * </PRE> */ public class RelationPrvtListFnc extends BaseRelationPrvtListFnc implements ODSListFnc { public static final String C_BOOLEAN_IND_SIM = "S"; public static final String C_BOOLEAN_IND_NAO = "N"; /* * (non-Javadoc) * @see com.citibank.ods.common.functionality.ODSListFnc#list(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void list( BaseFncVO fncVO_ ) { RelationPrvtListFncVO relationPrvtListFncVO = ( RelationPrvtListFncVO ) fncVO_; if ( !fncVO_.hasErrors() ) { // Obtém a instância da Factory ODSDAOFactory factory = ODSDAOFactory.getInstance(); TplRelationPrvtDAO relationPrvtDAO = factory.getTplRelationPrvtDAO(); DataSet result = relationPrvtDAO.list( relationPrvtListFncVO.getReltnNbrSrc(), relationPrvtListFncVO.getCustNbrSrc(), relationPrvtListFncVO.getCustFullNameTextSrc(), relationPrvtListFncVO.getOwnerCustNbrInd(), relationPrvtListFncVO.getAcctNbrSrc(), relationPrvtListFncVO.getCustCpfCnpjNbrSrc() ); relationPrvtListFncVO.setResults( result ); if ( result.size() > 0 ) { relationPrvtListFncVO.addMessage( BaseODSFncVO.C_MESSAGE_SUCESS ); } else { relationPrvtListFncVO.addMessage( BaseODSFncVO.C_NO_REGISTER_FOUND ); } } } /* * (non-Javadoc) * @see com.citibank.ods.common.functionality.ODSListFnc#load(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void load( BaseFncVO fncVO_ ) { RelationPrvtListFncVO relationPrvtListFncVO = ( RelationPrvtListFncVO ) fncVO_; if ( relationPrvtListFncVO.isFromSearch() ) { loadNameText( relationPrvtListFncVO ); relationPrvtListFncVO.setFromSearch( false ); } else { relationPrvtListFncVO.setResults( null ); relationPrvtListFncVO.setAcctNbrSrc( null ); relationPrvtListFncVO.setReltnNbrSrc( null ); } } /* * (non-Javadoc) * @see com.citibank.ods.common.functionality.ODSListFnc#validateList(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void validateList( BaseFncVO fncVO_ ) { } /* * (non-Javadoc) * @see com.citibank.ods.modules.client.relationprvt.functionality.BaseRelationPrvtListFnc#getDAO() */ protected BaseTplRelationPrvtDAO getDAO() { return null; } /* * (non-Javadoc) * @see com.citibank.ods.common.functionality.BaseFnc#createFncVO() */ public BaseFncVO createFncVO() { return new RelationPrvtListFncVO(); } public void clearPage( BaseFncVO fncVO_ ) { RelationPrvtListFncVO relationPrvtListFncVO = ( RelationPrvtListFncVO ) fncVO_; relationPrvtListFncVO.clearErrors(); relationPrvtListFncVO.clearMessages(); relationPrvtListFncVO.setResults( null ); relationPrvtListFncVO.setAcctNbrSrc( null ); relationPrvtListFncVO.setReltnNbrSrc( null ); relationPrvtListFncVO.setCustNbrSrc( null ); relationPrvtListFncVO.setCustFullNameTextSrc( null ); relationPrvtListFncVO.setOwnerCustNbrInd( null ); relationPrvtListFncVO.setCustCpfCnpjNbrSrc( null ); relationPrvtListFncVO.setSelectedReltnNbr(null); } }
package oop.assignment; public class StudentDemo { public static void main(String[] args) { // Tests the functionality of Student class Student stud1 = new Student(40059267, "Vivek Chatrola", 89, 76, 95); stud1.calculateTotal(); stud1.displayStudDetails(); } }
package uk.co.monkeypower.openchurch.core.web.utils; public class JNDINames { public static String USER_MANAGER = "java:global/openchurch-core-ear/openchurch-core-logic-0.1/UserManagerBean"; public static String LAYOUT_MANAGER = "java:global/openchurch-core-ear/openchurch-core-logic-0.1/LayoutManagerBean"; }
package com.karya.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="paymententry001mb") public class PaymentEntry001MB implements Serializable{ private static final long serialVersionUID = -723583058586873479L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "payentId") private int payentId; @Column(name="entrySeries") private String entrySeries; @Column(name="postingDate") private String postingDate; @Column(name="paymentType") private String paymentType; @Column(name="paymentMode") private String paymentMode; @Column(name="partyType") private String partyType; @Column(name="partyName") private String partyName; @Column(name="accpaidTo") private String accpaidTo; public int getPayentId() { return payentId; } public void setPayentId(int payentId) { this.payentId = payentId; } public String getEntrySeries() { return entrySeries; } public void setEntrySeries(String entrySeries) { this.entrySeries = entrySeries; } public String getPostingDate() { return postingDate; } public void setPostingDate(String postingDate) { this.postingDate = postingDate; } public String getPaymentType() { return paymentType; } public void setPaymentType(String paymentType) { this.paymentType = paymentType; } public String getPaymentMode() { return paymentMode; } public void setPaymentMode(String paymentMode) { this.paymentMode = paymentMode; } public String getPartyType() { return partyType; } public void setPartyType(String partyType) { this.partyType = partyType; } public String getPartyName() { return partyName; } public void setPartyName(String partyName) { this.partyName = partyName; } public String getAccpaidTo() { return accpaidTo; } public void setAccpaidTo(String accpaidTo) { this.accpaidTo = accpaidTo; } public static long getSerialversionuid() { return serialVersionUID; } }
package com.karya.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="userrole001mb") public class UserRole001MB implements Serializable{ private static final long serialVersionUID = -723583058586873479L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "userroleid") private int id; @ManyToOne @JoinColumn(name="loginid") private Login001MB login001MB; @Column(name = "role") private String role; @Column(name = "username") private String username; public int getId() { return id; } public void setId(int id) { this.id = id; } public Login001MB getLogin001MB() { return login001MB; } public void setLogin001MB(Login001MB login001mb) { login001MB = login001mb; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
package com.hint; import java.io.File; public class MainClass { public static File file = new File("/home/valuelabs/workspace/Threads/src/com/hint/hint.txt"); //public static int readers = 0; //public static int writers = 0; public static void main(String[] args) { new RW(file,"read").start(); new RW(file,"read").start(); new RW(file,"write").start(); new RW(file,"read").start(); } }
package com.liuhe.utils; import android.support.annotation.Nullable; import android.util.Log; import com.example.lib_clever.BuildConfig; /** * 打印log工具类 * * @author liuhea * @created 16-11-24 */ public class LogUtils { private LogUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } public static boolean isDebug = BuildConfig.DEBUG; private static final String TAG = "Clever--Log--"; // 下面四个是默认tag的函数 public static void i(String msg) { i(null, msg); } public static void d(String msg) { d(null, msg); } public static void e(String msg) { e(null, msg); } public static void v(String msg) { v(null, msg); } // 下面是传入自定义tag的函数 public static void i(@Nullable String tag, String msg) { if (isDebug) { StackTraceElement stackTraceElement = java.lang.Thread.currentThread().getStackTrace()[3]; if (tag == null) { Log.i(TAG, rebuildMsg(stackTraceElement, msg)); } else { Log.i(TAG + tag, rebuildMsg(stackTraceElement, msg)); } } } public static void d(@Nullable String tag, String msg) { if (isDebug) { StackTraceElement stackTraceElement = java.lang.Thread.currentThread().getStackTrace()[3]; if (tag == null) { Log.d(TAG, rebuildMsg(stackTraceElement, msg)); } else { Log.d(TAG + tag, rebuildMsg(stackTraceElement, msg)); } } } public static void e(@Nullable String tag, String msg) { if (isDebug) { StackTraceElement stackTraceElement = java.lang.Thread.currentThread().getStackTrace()[3]; if (tag == null) { Log.e(TAG, rebuildMsg(stackTraceElement, msg)); } else { Log.e(TAG + tag, rebuildMsg(stackTraceElement, msg)); } } } public static void v(@Nullable String tag, String msg) { if (isDebug) { StackTraceElement stackTraceElement = java.lang.Thread.currentThread().getStackTrace()[3]; if (tag == null) { Log.v(TAG, rebuildMsg(stackTraceElement, msg)); } else { Log.v(TAG + tag, rebuildMsg(stackTraceElement, msg)); } } } /* * 重新组装log信息,加上类名,行数,方法名 * */ private static String rebuildMsg(StackTraceElement element, String msg) { StringBuilder sb = new StringBuilder(); sb.append(element.getFileName()); sb.append("("); sb.append(element.getLineNumber()); sb.append(")"); sb.append(element.getMethodName()); sb.append(":"); sb.append(msg); return sb.toString(); } }
package com.example.fklubben; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import java.util.ArrayList; public class DrinksActivity extends AppCompatActivity { private RecyclerView recyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager layoutManager; private ArrayList<Drink> drinks; public void onClickAboutUs(View view){ Intent intent = new Intent(this, AboutUs.class); startActivity(intent); } public void onClickDrinks(View view){ Intent intent = new Intent(this, DrinksActivity.class); startActivity(intent); } public void onClickContact(View view){ Intent intent = new Intent(this, contact.class); startActivity(intent); } public void onClickMap(View view){ Intent intent = new Intent(this, map.class); startActivity(intent); } public void onClickTest(View view){ Intent intent = new Intent(this, test.class); startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drinks); Log.i("test","hertil2"); this.drinks = new ArrayList<Drink>(); createModel(); this.recyclerView = (RecyclerView) findViewById(R.id.drinks_recycler_view); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView this.recyclerView.setHasFixedSize(true); // adding things to the recycleview RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL); this.recyclerView.addItemDecoration(itemDecoration); // use a linear layout manager this.layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); this.recyclerView.setLayoutManager(layoutManager); // specify an adapter this.mAdapter = new DrinkAdapter(drinks); this.recyclerView.setAdapter(mAdapter); } private void createModel() { Drink drink1 = new Drink("Coca-cola", 12); Drink drink2 = new Drink("Kinley", 6); Drink drink3 = new Drink("Sportscola", 7); } }
package ru.mcfr.oxygen.util.ui.treetable; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.Vector; /** * Created by IntelliJ IDEA. * User: ws * Date: 04.05.11 * Time: 18:15 * To change this template use File | Settings | File Templates. */ public class SchemaInfoModel extends AbstractTreeTableModel implements TreeTableModel { // Names of the columns. static protected String[] cNames = {"Name", "Id", "URL"}; // Types of the columns. static protected Class[] cTypes = {TreeTableModel.class, String.class, String.class}; public SchemaInfoModel(Document doc) { super(doc.getDocumentElement()); } public int getColumnCount() { return cNames.length; } public String getColumnName(int column) { return cNames[column]; } public Object getValueAt(Object node, int column) { if (node instanceof Node) { //MainNode n = (MainNode) node; Node n = (Node) node; if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) n; switch (column) { case 0: return e.getAttribute("title"); case 1: return e.getAttribute("id"); case 2: return e.getAttribute("noNamespaceSchemaLocation"); } } } return null; } private Object[] getChildren(Object node) { Element e = (Element) node; NodeList chlds = e.getChildNodes(); Vector<Element> res = new Vector<Element>(); for (int i = 0; i < chlds.getLength(); i++) if (chlds.item(i).getNodeType() == Node.ELEMENT_NODE) res.add((Element) chlds.item(i)); Object[] ores = new Object[res.size()]; res.copyInto(ores); return ores; } public Object getChild(Object o, int i) { String title = ((Element) o).getAttribute("title"); Object newObj = getChildren(o)[i]; String other_title = ((Element) newObj).getAttribute("title"); return newObj; } public int getChildCount(Object o) { String title = ((Element) o).getAttribute("title"); int len = getChildren(o).length; return len; } }
package com.xys.car.entity; import java.math.BigDecimal; import com.baomidou.mybatisplus.annotation.TableName; import java.time.LocalDate; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import net.bytebuddy.implementation.bind.annotation.Super; /** * <p> * * </p> * * @author zxm * @since 2020-12-04 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("xys_car") public class Car extends RootEntity implements Serializable{ private static final long serialVersionUID=1L; private String id; /** * 名字 */ private String name; /** * 价格 */ private BigDecimal price; /** * 年款 */ private String caryear; /** * 品牌 */ private String brand; /** * 颜色 */ private String color; /** * 型号 */ private String entity; /** * 类型 */ private String type; /** * 行驶里程 */ private Double uselong; /** * 有无事故 */ private Integer accident; /** * 使用几年 */ private Integer useyear; /** * 是否喷漆 */ private Integer paint; /** * 入库时间 */ private LocalDate createtime; /** * 热度 */ private Integer hot; /** * 推荐 */ private Integer recommend; /** * 删除 */ private Integer del; }
package com.cems.activities; import android.app.DatePickerDialog; import android.app.ProgressDialog; import android.app.TimePickerDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.ListView; import android.widget.TimePicker; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.databinding.DataBindingUtil; import com.cems.BaseParentActivity; import com.cems.CEMSDataStore; import com.cems.R; import com.cems.databinding.ActivityAddEventBinding; import com.cems.model.Event; import com.cems.model.EventType; import com.cems.model.ServerResponse; import com.cems.network.ApiInstance; import com.google.gson.Gson; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Map; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class AddEventActivity extends BaseParentActivity { ActivityAddEventBinding binding; Event event = new Event(); ProgressDialog progress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_add_event); progress = new ProgressDialog(this); binding.eventTypeDrop.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, EventType.values())); binding.eventTypeDrop.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { event.setEventType(EventType.values()[position]); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); binding.eventDateBtn.setOnClickListener(v -> { Calendar c = Calendar.getInstance(); DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, month, dayOfMonth) -> { Calendar selDate = Calendar.getInstance(); selDate.set(year, month, dayOfMonth); String date = new SimpleDateFormat("dd MMM yyyy").format(selDate.getTime()); event.setEventDate(date); binding.eventDateBtn.setText(date); }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)); datePickerDialog.show(); }); binding.eventStartTimeBtn.setOnClickListener(v -> { Calendar c = Calendar.getInstance(); TimePickerDialog timePickerDialog = new TimePickerDialog(this, (view, hourOfDay, minute) -> { Calendar selTime = Calendar.getInstance(); selTime.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), hourOfDay, minute); String time = new SimpleDateFormat("hh:mm a").format(selTime.getTime()); event.setEventStartTime(time); binding.eventStartTimeBtn.setText(time); }, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), false); timePickerDialog.show(); }); binding.eventEndTimeBtn.setOnClickListener(v -> { Calendar c = Calendar.getInstance(); TimePickerDialog timePickerDialog = new TimePickerDialog(this, (view, hourOfDay, minute) -> { Calendar selTime = Calendar.getInstance(); selTime.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), hourOfDay, minute); String time = new SimpleDateFormat("hh:mm a").format(selTime.getTime()); event.setEventEndTime(time); binding.eventEndTimeBtn.setText(time); }, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), false); timePickerDialog.show(); }); binding.eventSelYearsBtn.setOnClickListener(v -> { showArrayListSelectionAlert("Select Applicable Years", new YearAdapter(AddEventActivity.this, CEMSDataStore.getYears())); }); binding.eventSelBranchesBtn.setOnClickListener(v -> { showArrayListSelectionAlert("Select Applicable Branches", new BranchAdapter(AddEventActivity.this, CEMSDataStore.getBranches())); }); binding.addEventBtn.setOnClickListener(v -> { String name = binding.eventNameInput.getText().toString().trim(); String venue = binding.eventVenueInput.getText().toString().trim(); String cost = binding.eventCostInput.getText().toString().trim(); if(TextUtils.isEmpty(name) || TextUtils.isEmpty(venue) || TextUtils.isEmpty(cost) || event.getEventType() == null || event.getEventDate() == null || event.getEventStartTime() == null || event.getEventEndTime() == null || !event.getEventDate().matches(".*\\d.*") || !event.getEventStartTime().matches(".*\\d.*") || !event.getEventEndTime().matches(".*\\d.*") || event.getYears().isEmpty() || event.getBranches().isEmpty()) { showAlert(null, "All fields are necessary"); return; } event.setEventName(name); event.setEventVenue(venue); event.setEventCost(cost); progress.setMessage("Adding event..."); progress.setCancelable(false); progress.show(); Call<ServerResponse> data = ApiInstance.getClient().postEvent((String) CEMSDataStore.getUserData().getApiKey(), event); data.enqueue(new Callback<ServerResponse>() { @Override public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) { if (response.isSuccessful()) { ServerResponse serverResponse = response.body(); if (serverResponse != null) { if (serverResponse.getStatusCode() == 0) { if (progress.isShowing()) { progress.dismiss(); } Toast.makeText(AddEventActivity.this, "Success", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(AddEventActivity.this, MainActivity.class); startActivity(intent); finish(); } else { if (progress.isShowing()) { progress.dismiss(); } showAlert("Cannot add event", "Invalid Request\n" + serverResponse.getMessage()); } } else { if (progress.isShowing()) { progress.dismiss(); } showAlert("Cannot add event", "Server error occured\nResponse null"); } } else { if (progress.isShowing()) { progress.dismiss(); } showAlert("Cannot add event", "Server error occured\nResponse failed"); } } @Override public void onFailure(Call<ServerResponse> call, Throwable t) { if (progress.isShowing()) { progress.dismiss(); } t.printStackTrace(); showAlert("Cannot add event", "Server error occured"); } }); }); } private void showArrayListSelectionAlert(String title, ArrayAdapter<String> adapter) { final AlertDialog.Builder builder = new AlertDialog.Builder(AddEventActivity.this); builder.setTitle(title); final View customLayout = getLayoutInflater().inflate(R.layout.layout_listview_alert, null); ListView listView = customLayout.findViewById(R.id.alertListView); listView.setAdapter(adapter); builder.setPositiveButton("OK", (dialog, which) -> { if(!event.getYears().isEmpty()) { binding.eventSelYearsBtn.setText(new Gson().toJson(event.getYears()).replaceAll("[\\[\\]\"]", "").replaceAll("[,]", ", ")); } else { binding.eventSelYearsBtn.setText("SELECT YEARS"); } if(!event.getBranches().isEmpty()) { binding.eventSelBranchesBtn.setText(new Gson().toJson(event.getBranches()).replaceAll("[\\[\\]\"]", "").replaceAll("[,]", ", ")); } else { binding.eventSelBranchesBtn.setText("SELECT BRANCHES"); } builder.create().dismiss(); }); builder.setView(customLayout); final AlertDialog dialog = builder.create(); dialog.show(); } private class YearAdapter extends ArrayAdapter<String> { public YearAdapter(@NonNull Context context, ArrayList<String> data) { super(context, 0, data); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { String value = getItem(position); if (convertView == null) { convertView = getLayoutInflater().inflate(R.layout.layout_checkbox_item, parent, false); } CheckBox checkBox = convertView.findViewById(R.id.lvChkItem); checkBox.setText(value); checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { if (!event.getYears().contains(value)) { event.getYears().add(value); } } else { event.getYears().remove(value); } }); if (event.getYears().contains(value)) { checkBox.setChecked(true); } else { checkBox.setChecked(false); } return convertView; } } private class BranchAdapter extends ArrayAdapter<String> { public BranchAdapter(@NonNull Context context, ArrayList<String> data) { super(context, 0, data); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { String value = getItem(position); if (convertView == null) { convertView = getLayoutInflater().inflate(R.layout.layout_checkbox_item, parent, false); } CheckBox checkBox = convertView.findViewById(R.id.lvChkItem); checkBox.setText(value); checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> { if (isChecked) { if (!event.getBranches().contains(value)) { event.getBranches().add(value); } } else { event.getBranches().remove(value); } }); if (event.getBranches().contains(value)) { checkBox.setChecked(true); } else { checkBox.setChecked(false); } return convertView; } } private void showAlert(final String title, final String msg) { final AlertDialog.Builder alert = new AlertDialog.Builder(AddEventActivity.this); if (title != null) alert.setTitle(title); alert.setMessage(msg); alert.setPositiveButton("Back", (arg0, arg1) -> alert.create().dismiss()); alert.create().show(); } @Override public void onBackPressed() { Intent intent = new Intent(AddEventActivity.this, MainActivity.class); startActivity(intent); finish(); } }
package com.platform.domain; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.platform.domain.util.CustomDateTimeDeserializer; import com.platform.domain.util.CustomDateTimeSerializer; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Type; import org.joda.time.DateTime; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; /** * A Graphicalreadout. */ @Entity @Table(name = "graphicalreadout") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Graphicalreadout implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Lob @Column(name = "image") private byte[] image; @Column(name = "image_content_type") private String imageContentType; @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") @JsonSerialize(using = CustomDateTimeSerializer.class) @JsonDeserialize(using = CustomDateTimeDeserializer.class) @Column(name = "readout_time") private DateTime readoutTime; @ManyToOne private Sensor graphicalreadout_sensor; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } public String getImageContentType() { return imageContentType; } public void setImageContentType(String imageContentType) { this.imageContentType = imageContentType; } public DateTime getReadoutTime() { return readoutTime; } public void setReadoutTime(DateTime readoutTime) { this.readoutTime = readoutTime; } public Sensor getGraphicalreadout_sensor() { return graphicalreadout_sensor; } public void setGraphicalreadout_sensor(Sensor sensor) { this.graphicalreadout_sensor = sensor; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Graphicalreadout graphicalreadout = (Graphicalreadout) o; if ( ! Objects.equals(id, graphicalreadout.id)) return false; return true; } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "Graphicalreadout{" + "id=" + id + ", image='" + image + "'" + ", imageContentType='" + imageContentType + "'" + ", readoutTime='" + readoutTime + "'" + '}'; } public Graphicalreadout(){} public Graphicalreadout(byte[] image, String imageContentType, DateTime readoutTime, Sensor graphicalreadout_sensor) { this.image = image; this.imageContentType = imageContentType; this.readoutTime = readoutTime; this.graphicalreadout_sensor = graphicalreadout_sensor; } }
package com.zd.christopher.action; public interface IAdministratorAction { }
package com.proyectogrado.alternativahorario.entidades; import java.io.Serializable; import java.math.BigDecimal; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import lombok.Getter; import lombok.Setter; /** * * @author Steven */ @Entity @Table(name = "clases") @SequenceGenerator(name = "SecuenciaClases", sequenceName = "SEC_IDCLASES") @NamedQueries({ @NamedQuery(name = "Clase.findByMateria", query = "SELECT c FROM Clase c WHERE c.materia = :materia")}) public class Clase implements Serializable { private static final long serialVersionUID = 1L; @Getter @Setter @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SecuenciaClases") @Basic(optional = false) @Column(name = "id") private BigDecimal id; @Getter @Setter @Column(name = "grupo") private String grupo; @Getter @Setter @OneToMany(mappedBy = "clases", fetch = FetchType.LAZY) private List<Horario> horarioList; @Getter @Setter @JoinColumn(name = "materia", referencedColumnName = "id") @ManyToOne(fetch = FetchType.LAZY) private Materia materia; @Getter @Setter @Column(name = "profesor") private String profesor; public Clase() { } public Clase(BigDecimal id) { this.id = id; } }
package ex1.src; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Objects; /** *The class WGraph_DS represents an unidirectional weighted graph. * each graph has Hashmap that contains all vertices in the graph. * each graph has Hashmap that contains another HashMap that presents for each node key it represent Hash map that contain the key of the neibor and the weight of the edge. * each graph has _edgeCount that presents the number of edge in the graph. * and also _modeCount that that presents the number of change that made in the graph.. * */ public class WGraph_DS implements weighted_graph, java.io.Serializable { private int _modeCount=0; private HashMap<Integer, node_info> _vertex; private HashMap<Integer, HashMap<Integer,Double>> _edgeMap; private static int _edgeCount=0; /** * WGraph_DS has private class NodeInfo that represents an node in an unadjusted and weighted graph. * * Each node has its own key so it appears as FINAL. * Each node has a Tag value that is used by us when we want to find the shortest path. * Each node has info that you can write comments on each vertex. */ private static class NodeInfo implements node_info , java.io.Serializable { private final int _key; private double _tag = -1.0; private String _info=""; /** * Creates an empty node with unique key. */ public NodeInfo(int key){ _key=key; } /** * copy Constructors * Used to make a deep copy of graph. * this constructors copy only the key number. * * @param node - key node */ public NodeInfo(node_info node) { _key = node.getKey(); } /** * @return the key (id) associated with this node. */ @Override public int getKey() { return _key; } /** * This method return the remark (meta data) associated with this node. * * @return -the info include the node. */ @Override public String getInfo() { return _info; } /** * Allows changing the remark (meta data) associated with this node. * * @param s - Represents the new Info */ @Override public void setInfo(String s) { _info = s; } /** * This method return the tag value of this node. * * @return - the tag value of this node. */ @Override public double getTag() { return _tag; } /** * Allow setting the "tag" value for temporal marking an node. * * @param t - the new value of the tag */ @Override public void setTag(double t) { _tag = t; } //////////////////////////////////////////////////////// /** * i choose to override equals for the test class to check my project. * @param o * @return */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NodeInfo nodeInfo = (NodeInfo) o; return _key == nodeInfo._key && Double.compare(nodeInfo._tag, _tag) == 0 && Objects.equals(_info, nodeInfo._info); } } /** Constructor * Creates an empty graph. */ public WGraph_DS() { _vertex = new HashMap<Integer, node_info>(); _edgeMap = new HashMap<Integer, HashMap<Integer, Double>>(); _edgeCount = 0; // _modeCount=0; } /** * copy Constructors * this constructor copy all the node in the graph.with the help of copy Constructor of NodeInfo. * and after that the Constructor connect all the edge with they weight just like the original graph. * the _modeCount count one after one and can be diffrent from the original graph. * @param g - the graph we want to copy */ public WGraph_DS(weighted_graph g) { _vertex = new HashMap<Integer, node_info>(); _edgeMap=new HashMap<Integer, HashMap<Integer, Double>>(); _edgeCount = 0; for (node_info i: g.getV()) { addNode(i.getKey()); } for (node_info i : g.getV()) { int iKey = i.getKey(); for (node_info j: g.getV(iKey)){ int jKey = j.getKey(); connect(iKey, jKey,getEdge(iKey,jKey)); } } } /** *The method receive key and return the pointer of the relevant node by the receive key. * @param key - the node_id * @return pointer of the relevant node */ @Override public node_info getNode(int key) { return _vertex.get(key); } /** * The method receive 2 key and check if they connect. * @param node1 - first key of node * @param node2 - second key of node * @return true if them connect and false if doesn't. */ @Override public boolean hasEdge(int node1, int node2) { if (!_vertex.containsKey((node1)) || !(_vertex.containsKey(node2))|| (!_edgeMap.containsKey(node1))) return false; return _edgeMap.get(node1).containsKey(node2); } /** * * The method receive 2 key check if they connect and return the weight of the edge. * @param node1 - first key of node * @param node2 - second key of node * @return the weight of the edge. */ @Override public double getEdge(int node1, int node2) { if(!hasEdge(node1,node2)) return -1; return _edgeMap.get(node1).get(node2); } /** * The method add the the key node to the _vertex. * At the same time it also inserts it into _edgeMap even though no other node is connected to it yet. * @param key - the node that we want to add. */ @Override public void addNode(int key) { if(!_vertex.containsKey(key)) { _vertex.put(key, new NodeInfo(key)); _edgeMap.put(key,new HashMap<Integer, Double>()); _modeCount++; } } /** * The method receive 2 key and the weight between them and connect them each other. * if the edge already exsist the method replace the weight. * if the edge exsist Just like the original edge (including the weight) so the method will do nothing. * @param node1 * @param node2 * @param w */ @Override public void connect(int node1, int node2, double w) { if((_vertex.containsKey(node1)) && (_vertex.containsKey(node2)) && (node1 != node2)){ boolean tmp =hasEdge(node1,node2); if (tmp && _edgeMap.get(node1).get(node2) == w) { return; } if (!tmp) { _edgeCount++; } _edgeMap.get(node1).put(node2,w); _edgeMap.get(node2).put(node1,w); _modeCount++; } } /** * The method return collection of all the vertices in ths graph. * i used The method values() of HashMap because it cost O(1). * @return collection that represents all the vertices in the graph */ @Override public Collection<node_info> getV() { return _vertex.values(); } /** * The method return collection that represent all the neighbor of the node 'key' in ths graph. * * i used The method of HashMap * @param node_id - the node that i want to get is neighbors * @return - collection that represent the neighbor of the node 'key' */ @Override public Collection<node_info> getV(int node_id) { LinkedList<node_info> ansList = new LinkedList<node_info>(); if(_edgeMap.containsKey(node_id)) { for (Integer i : _edgeMap.get(node_id).keySet()) { ansList.add(_vertex.get(i)); } return ansList; } return ansList; } /** * The method remove the node 'key' from the graph. * and also remove all the edge that was connect to 'key' node. * @param key - the id of the node we want to remove * @return the node_data that was remove */ @Override public node_info removeNode(int key) { if(!_vertex.containsKey(key)) { return null; } for (Integer i : _edgeMap.get(key).keySet()) { _edgeMap.get(i).remove(key); _edgeCount--; } _modeCount++; _edgeMap.remove(key); return _vertex.remove(key); } /** * the method get 2 node check if both node are contain and if they are connect. * and if all true remove the edge between the node; * @param node1 first node * @param node2 second node */ @Override public void removeEdge(int node1, int node2) { if(hasEdge(node1,node2)) { _edgeMap.get(node1).remove(node2); _edgeMap.get(node2).remove(node1); _edgeCount--; _modeCount++; } } /** * * @return the number of vertices (nodes) in the graph. */ @Override public int nodeSize() { return _vertex.size(); } /** * * @return the number of edges (unidirectional graph). */ @Override public int edgeSize() { return _edgeCount; } /** * * @return the Mode Count - for testing changes in the graph. */ @Override public int getMC() { return _modeCount; } /** * i override equals for the test class to check my project. * @param o * @return true if they equals and false if doesnt. */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WGraph_DS wGraph_ds = (WGraph_DS) o; return Objects.equals(_vertex, wGraph_ds._vertex) && Objects.equals(_edgeMap, wGraph_ds._edgeMap); } }
package com.zzping.fix.service; import com.aliyuncs.exceptions.ClientException; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.google.common.collect.Lists; import com.zzping.fix.entity.*; import com.zzping.fix.mapper.FixLabelApplyMapper; import com.zzping.fix.mapper.FixRecordMapper; import com.zzping.fix.mapper.FixUploadMapper; import com.zzping.fix.mapper.FixUserMapper; import com.zzping.fix.model.*; import com.zzping.fix.util.*; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ResourceUtils; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URLEncoder; import java.util.Arrays; import java.util.Date; import java.util.List; @Service public class FixAdminService { public static List<String> EXPORT_HEADER = Lists.newArrayList("UserNo" , "UserName", "Campus", "CampusPalce", "BuildingNo","DormNo", "createTime","FixType", "Label", "Title", "FixerUserNo" , "FixerUserName", "Score" ); @Autowired private FixRecordMapper fixRecordMapper; @Autowired private FixUserMapper fixUserMapper; @Autowired private FixRecordChangeService fixRecordChangeService; @Autowired private FixLabelApplyMapper fixLabelApplyMapper; @Autowired private FixUploadMapper fixUploadMapper; @Autowired private FixSmsService fixSmsService; public LayUIGrid waitFixingGrid(FixFormModel fixFormModel) { LayUIGrid layUIGrid = new LayUIGrid(); PageHelper.startPage(fixFormModel.getPage(), fixFormModel.getLimit()); List<FixRecord> fixRecordList = fixRecordMapper.selectPlatFormRecord(fixFormModel); LayUIUtil.pageInfoToLayGrid(new PageInfo(fixRecordList), layUIGrid); return layUIGrid; } @Transactional public ServerResponse order(String fixId, String userId) { FixRecord fixRecord = fixRecordMapper.selectByPrimaryKey(fixId); FixUser user = fixUserMapper.selectByPrimaryKey(userId); fixRecord.setFixerUserId(user.getUserId()); fixRecord.setFixerUserName(user.getUserName()); fixRecord.setFixerUserType(user.getUserType()); fixRecord.setFixerUserNo(user.getUserNo()); fixRecord.setFixStatus(FixStatusConstant.PLATFORM_SENDED); fixRecordMapper.updateByPrimaryKey(fixRecord); fixRecordChangeService.insertPlatFormOrder(fixRecord, user); String phone = fixUserMapper.selectByPrimaryKey(fixRecord.getUserId()).getPhone(); try { fixSmsService.send(new FixMsgModel(fixRecord.getUserName()+MsgConstant.PLAT_SEND),phone); fixSmsService.send(new FixMsgModel(user.getUserName()+MsgConstant.FIXER_ORDER),user.getPhone()); } catch (ClientException e) { e.printStackTrace(); } return ServerResponse.buildSuccessMsg("派单成功"); } public LayUIGrid fixingGrid(FixFormModel model) { LayUIGrid layUIGrid = new LayUIGrid(); PageHelper.startPage(model.getPage(), model.getLimit()); List<FixRecord> fixRecordList = fixRecordMapper.selectFixingRecord(model); LayUIUtil.pageInfoToLayGrid(new PageInfo(fixRecordList), layUIGrid); return layUIGrid; } public LayUIGrid fixHistoryGrid(FixFormModel model) { LayUIGrid layUIGrid = new LayUIGrid(); PageHelper.startPage(model.getPage(), model.getLimit()); List<FixRecord> fixRecordList = fixRecordMapper.selectHistoryRecord1(model); LayUIUtil.pageInfoToLayGrid(new PageInfo(fixRecordList), layUIGrid); return layUIGrid; } public LayUIGrid labelApplyGrid(FixFormModel model) { LayUIGrid layUIGrid = new LayUIGrid(); PageHelper.startPage(model.getPage(), model.getLimit()); List<FixLabelApply> fixRecordList = fixLabelApplyMapper.selectLabelApplyList(model); LayUIUtil.pageInfoToLayGrid(new PageInfo(fixRecordList), layUIGrid); return layUIGrid; } @Transactional public ServerResponse applyLabelApprove(String id) { FixLabelApply fixLabelApply = fixLabelApplyMapper.selectByPrimaryKey(id); fixLabelApply.setRejectReason("0"); String userId = fixLabelApply.getUserId(); FixUser user = fixUserMapper.selectByPrimaryKey(userId); user.setLabel(fixLabelApply.getApplyLabel()); user.setLabelDetail(fixLabelApply.getApplyLabelDetail()); user.setIsFixer(Constant.STR_SUCCESS); fixLabelApplyMapper.updateByPrimaryKey(fixLabelApply); fixUserMapper.updateByPrimaryKey(user); return ServerResponse.buildSuccessMsg("同意申请成功"); } @Transactional public ServerResponse applyLabelReject(String id) { FixLabelApply fixLabelApply = fixLabelApplyMapper.selectByPrimaryKey(id); fixLabelApply.setRejectReason("0"); fixLabelApplyMapper.updateByPrimaryKey(fixLabelApply); return ServerResponse.buildSuccessMsg("拒绝申请成功"); } public LayUIGrid fixerGrid(FixerModel model) { LayUIGrid layUIGrid = new LayUIGrid(); PageHelper.startPage(model.getPage(), model.getLimit()); List<FixerModel> fixerModelList = fixUserMapper.selectFixerList(model); LayUIUtil.pageInfoToLayGrid(new PageInfo(fixerModelList), layUIGrid); return layUIGrid; } @Transactional public ServerResponse invalidFixer(String userNo) { List<FixUser> fixUsers = fixUserMapper.selectByUserNo(userNo); FixUser user = fixUsers.get(0); user.setIsFixer(Constant.STR_FAIL); user.setLabelDetail(null); user.setLabel(null); fixUserMapper.updateByPrimaryKey(user); return ServerResponse.buildSuccessMsg("取消资格成功"); } public LayUIGrid fixerHisGrid(String userId, int page, int limit) { LayUIGrid layUIGrid = new LayUIGrid(); PageHelper.startPage(page, limit); List<FixRecord> recordList = fixRecordMapper.selectFixerHisRecord(userId); LayUIUtil.pageInfoToLayGrid(new PageInfo(recordList), layUIGrid); return layUIGrid; } public LayUIGrid uploadGrid(String batchNo, int page, int limit) { LayUIGrid layUIGrid = new LayUIGrid(); PageHelper.startPage(page, limit); FixUploadCriteria criteria = new FixUploadCriteria(); criteria.createCriteria().andBatchNoEqualTo(batchNo); criteria.setOrderByClause("success ASC"); List<FixUpload> fixUploadList = fixUploadMapper.selectByExample(criteria); LayUIUtil.pageInfoToLayGrid(new PageInfo(fixUploadList), layUIGrid); return layUIGrid; } @Transactional public ServerResponse upload(String uploadIds) { String[] idArray = uploadIds.split(";"); for (int i = 0; i < idArray.length; i++) { FixUpload fixUpload = fixUploadMapper.selectByPrimaryKey(idArray[i]); FixRecord fixRecord = new FixRecord(); BeanUtils.copyProperties(fixUpload, fixRecord); fixRecord.setFixId(UUIDUtil.getUUIDString()); fixRecord.setFixType(Constant.FIX_TYPE_DORM); fixRecord.setFixStatus(FixStatusConstant.SUBMIT); fixRecord.setOrderType(Constant.ORDER_TYPE_PLATFORM); fixRecord.setCreateTime(new Date()); fixUploadMapper.deleteByPrimaryKey(fixUpload.getUploadId()); fixRecordMapper.insert(fixRecord); fixRecordChangeService.insertUploadInfo(fixRecord); } return ServerResponse.buildSuccessMsg("生成维修单成功"); } public void export(FixFormModel model, HttpServletResponse response) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { List<FixFormModel> recordList = fixRecordMapper.selectHistoryRecord2(model); Resource resource = new ClassPathResource("报表导出.xlsx"); XSSFWorkbook workbook = new XSSFWorkbook(resource.getInputStream()); XSSFSheet sheet = workbook.getSheetAt(0); for (int i = 0; i < recordList.size(); i++) { sheet.createRow(i + 1); XSSFRow row = sheet.getRow(i + 1); FixFormModel fixRecord = recordList.get(i); for (int j = 0; j < EXPORT_HEADER.size(); j++) { row.createCell(j); Method[] m = fixRecord.getClass().getDeclaredMethods(); for (int k = 0; k < m.length; k++) { if (("get" + EXPORT_HEADER.get(j)).toLowerCase().equals(m[k].getName().toLowerCase())) { Object invoke = m[k].invoke(fixRecord); if (invoke == null) { break; } row.getCell(j).setCellValue(invoke.toString()); break; } } } } response.setCharacterEncoding("utf-8"); response.setContentType("application/vnd.ms-excel"); //改成输出excel文件 response.setHeader("Content-disposition", "attachment; filename= " + URLEncoder.encode("报表导出.xlsx", "UTF-8")); ServletOutputStream outputStream = response.getOutputStream(); workbook.write(outputStream); } public List getAllLabel() { List list =fixUserMapper.getAllLabelStr(); return list; } }
/** * */ package solo; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import cern.colt.list.DoubleArrayList; import com.graphbuilder.geom.Geom; /** * @author kokichi3000 * */ public final class Edge { // public final static double ANGLEACCURACY =100.0d; public final static int NUM_POINTS=150; public final static double DELTA = 0.005; ObjectArrayList<Vector2D> allPoints = null; DoubleArrayList x = null; DoubleArrayList y = null; DoubleArrayList allLengths = null; Object2IntMap<Vector2D> p2l = null; double straightDist = 0; double dmin = Double.MAX_VALUE; int size =0; double totalLength =0; Vector2D center = null; double radius = Double.MAX_VALUE; Vector2D nextCenter = null; double nextRadius = 0; int index = 0; int nIndex = -1; public Edge(){ } public double calculateRadius(){ if (index<size && index>=-1) return calculateRadius(index); return -1; } public double calculateRadius(double[] initialGuess){ // int index = y.binarySearch(straightDist); // if (index<0) index = -index; if (index<size && index>=-1) return calculateRadius(index,initialGuess); return -1; } public boolean isStraightLine(Vector2D p1,Vector2D p2,Vector2D p3){ double[] r = new double[3]; boolean isCirle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, r); if (!isCirle || r[2]>=100000) return true; return false; } public boolean isPointOnEdge(Vector2D hh){ double d = 0; if (dmin==Double.MAX_VALUE){ d = calculateRadius(); if (d==-1) return false; } else d = dmin; Vector2D p1 = allPoints.get(size-1); Vector2D p2 = allPoints.get(size-2); Vector2D p3 = allPoints.get(size-3); if (d<=0.0001){//exactly correct guess double dd = (radius!=Double.MAX_VALUE) ? center.distance(hh)-radius : Geom.ptLineDistSq(p1.x, p1.y, p2.x, p2.y, hh.x, hh.y, null); if (radius!=Double.MAX_VALUE) dd*=dd; if (dd<=0.01) return true; } if (isStraightLine(p1, p2, hh)) return true; double[] r = new double[3]; boolean isCircle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, r); if (isCircle){ double dd = hh.distance(new Vector2D(r[0],r[1]))-Math.sqrt(r[2]); if (dd>=-1) return true; } return false;//false means UNKNOWN } public double radiusNextSeg(double[] r){ if (r!=null && r.length>=3 && nextCenter!=null){ r[0] = nextCenter.x; r[1] = nextCenter.y; r[2] = nextRadius*nextRadius; } return nextRadius; } public double calculateRadius(int index,double[] initialGuess){ if (size<index+2) return -1; double x0 = allPoints.get(0).x; if (index+4==size){ Vector2D p1 = allPoints.get(index+1); Vector2D p2 = allPoints.get(index+2); Vector2D p3 = allPoints.get(index+3); double[] r = new double[3]; boolean isCircle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, r); if (isCircle){ r[2] = Math.sqrt(r[2]); // Geom.getCircle2(p1, p2, new Vector2D(x0,0), new Vector2D(x0,1), r); // r[2] = Math.sqrt(r[2]); double lx = r[0]-r[2]-x0; double rx = r[0]+r[2]-x0; if (lx>0.5 || rx<-0.5 || (lx*rx<0 && (lx<-0.5 && rx>0.5))){ Geom.getCircle2(p1, p3, new Vector2D(x0,0), new Vector2D(x0,1), r); r[2] = Math.sqrt(r[2]); } dmin = 0; radius = r[2]; center = new Vector2D(r[0],r[1]); } return dmin; } if (index+4>size){ dmin = 0; center = new Vector2D(initialGuess[0],initialGuess[1]); radius = initialGuess[2]; int n = 0; for (int i=index+1;i<size;++i){ n++; Vector2D p = allPoints.get(i); double tmp = p.distance(center)-radius; dmin += tmp*tmp; } dmin /= n; return dmin; } CircleFitter cf = new CircleFitter(initialGuess.clone(),allPoints.elements(),index+1,index+3); try{ cf.fit(); double r = cf.getEstimatedRadius(); // double d = 0; int n = 0; Vector2D o = cf.getEstimatedCenter(); this.center = o; this.radius = r; for (int i=index+3;i<size;++i){ n++; Vector2D p = allPoints.get(i); double tmp = p.distance(o)-r; if (tmp>=1e-4){ nIndex = i; break; } } if (nIndex!=-1){ // if (nIndex>index+3 && nIndex<size){ // cf = new CircleFitter(initialGuess.clone(),allPoints.elements(),index+1,nIndex-1); // cf.fit(); // this.center = cf.getEstimatedCenter(); // this.radius = cf.getEstimatedRadius(); // } else { // this.center = new Vector2D(initialGuess[0],initialGuess[1]); // this.radius = initialGuess[2]; // } if (nIndex<size-2){ cf = new CircleFitter(initialGuess,allPoints.elements(),nIndex,size-1); cf.fit(); this.nextCenter = cf.getEstimatedCenter(); this.nextRadius = cf.getEstimatedRadius(); } } } catch (Exception e){ e.printStackTrace(); dmin = Double.MAX_VALUE; } if (dmin<Double.MAX_VALUE) return dmin; return -1; } /*public void calculateRadiusWhileInTurn(Segment seg,double tW,double toMiddle,double dist){ double r = seg.radius; double rad = 0; int i=0; for (i=0;i<size;++i) if (allPoints.get(i).y>=0) break; Vector2D p1 = allPoints.get(i); Vector2D p2 = allPoints.get(i+1); Vector2D p3 = allPoints.get(i+2); double[] rr = new double[3]; boolean isCircle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, rr); if (isCircle){ rr[2] = Math.sqrt(rr[2]); } CircleFitter cf = new CircleFitter(rr.clone(),allPoints.elements(),i,i+3); try{ cf.fit(); radius = (int)Math.round(cf.getEstimatedRadius()); rad = (int)Math.round(cf.getEstimatedRadius()+tW); double sign = (cf.getEstimatedCenterX()<0) ? -1 : 1; if (rad != seg.radius){ int nr = seg.map.get(rad); if (nr==seg.map.defaultReturnValue()) nr = 0; nr++; seg.map.put(rad, nr); if (nr<=seg.map.get(r)) rad = r; } center = new Vector2D(sign*r+toMiddle,0); } catch (Exception e) { // TODO: handle exception } Vector2D end = null; for (i=0;i<size;++i){ // System.out.println(allPoints.get(i).distance(center)+tW-rad); if (Math.abs(allPoints.get(i).distance(center)+tW-rad)>=0.0001d) break; } if (i==0){ index=-1; nIndex = -1; return; } end = allPoints.get(i-1); end = center.plus(end.minus(center).normalised().times(rad)); TrackSegment ts = TrackSegment.createTurnSeg(dist, center.x, center.y, rad, 0, 0, end.x, end.y, center.x, center.y); seg.combine(ts); index = -1; nIndex = i; if (nIndex<size-2){ p1 = allPoints.get(size-3); p2 = allPoints.get(size-2); p3 = allPoints.get(size-1); isCircle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, rr); if (isCircle){ rr[2] = Math.sqrt(rr[2]); } cf = new CircleFitter(rr.clone(),allPoints.elements(),nIndex,size-1); cf.fit(); this.nextCenter = cf.getEstimatedCenter(); this.nextRadius = cf.getEstimatedRadius(); } } public Segment calculateRadiusWhileNotInTurn(Segment seg,double tW,double toMiddle,double dist){ double r = (seg!=null) ? seg.radius : -1; int rad = 0; int i=0; double x0 = allPoints.get(0).x; double[] rr = new double[3]; if (index+2>=size) return null; Vector2D p1 = allPoints.get(index+1); Vector2D p2 = allPoints.get(index+2); Vector2D p = null; if (index+3==size){ p = allPoints.get(size-1); Geom.getCircle2(p1, p2, new Vector2D(x0,0), new Vector2D(x0,1), rr); rr[2] = Math.sqrt(rr[2]); rad = (int)Math.round(rr[2]+tW); radius = (int)Math.round(rr[2]); center = new Vector2D(rr[0],rr[1]); } else { Vector2D p3 = allPoints.get(index+3); if (index+4==size){ p = allPoints.get(size-1); boolean isCircle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, rr); if (isCircle){ rr[2] = Math.sqrt(rr[2]); double lx = rr[0]-rr[2]-x0; double rx = rr[0]+rr[2]-x0; if (lx>0.5 || rx<-0.5 || (lx*rx<0 && (lx<-0.5 && rx>0.5))){ Geom.getCircle2(p1, p3, new Vector2D(x0,0), new Vector2D(x0,1), rr); rr[2] = Math.sqrt(rr[2]); } rad = (int)Math.round(rr[2]+tW); radius = (int)Math.round(rr[2]); center = new Vector2D(rr[0],rr[1]); } } else { boolean isCircle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, rr); if (isCircle){ rr[2] = Math.sqrt(rr[2]); } CircleFitter cf = new CircleFitter(rr,allPoints.elements(),index+1,index+4); try{ cf.fit(); rad = (int)Math.round(cf.getEstimatedRadius()+tW); double xx = cf.getEstimatedCenterX(); double r0 = cf.getEstimatedRadius(); double lx = xx-r0-x0; double rx = xx+r0-x0; if (lx>0.5 || rx<-0.5 || (lx*rx<0 && (lx<-0.5 && rx>0.5))){ Geom.getCircle2(p1, p3, new Vector2D(x0,0), new Vector2D(x0,1), rr); rr[2] = Math.sqrt(rr[2]); rad = (int)Math.round(rr[2]+tW); xx = rr[0]; } } catch (Exception e) { // TODO: handle exception } center = new Vector2D(rr[0],rr[1]); radius = rr[2]; for (i=index+4;i<size;++i){ if (Math.abs(allPoints.get(i).distance(center)-radius)>=0.0001d) break; } p = allPoints.get(i-1); nIndex = i; if (nIndex<size-3){ p1 = allPoints.get(size-3); p2 = allPoints.get(size-2); p3 = allPoints.get(size-1); isCircle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, rr); if (isCircle){ rr[2] = Math.sqrt(rr[2]); } cf = new CircleFitter(rr.clone(),allPoints.elements(),nIndex,size-1); cf.fit(); this.nextCenter = cf.getEstimatedCenter(); this.nextRadius = cf.getEstimatedRadius(); } } } if (p!=null) p = center.plus(p.minus(center).normalised().times(rad)); double l = center.y; Vector2D start = allPoints.get(index+1); double angle =0; if (start!=null){ start = center.plus(start.minus(center).normalised().times(rad)); double xx = (center.x==0) ? 0 : -center.x; angle= Math.abs(Vector2D.angle(start.minus(center),new Vector2D(xx,0))); l += rad*angle; } if (p!=null && start!=null){ TrackSegment ts = TrackSegment.createTurnSeg(dist+l, center.x, center.y, rad, start.x, start.y, p.x, p.y, center.x, center.y); if (rad>0 && seg!=null) seg.combine(ts); else return new Segment(ts); } return seg; }//*/ public double reCalculateRadius(){ double[] r = new double[3]; r[0] = center.x; r[1] = center.y; r[2] = radius; int sz = (nIndex>=4) ? nIndex : size; if (center!=null){ CircleFitter cf = new CircleFitter(r,allPoints.elements(),index+1,sz-1); if (sz-index<=4) return -1; try{ cf.fit(); dmin = cf.getLMAObject().chi2Goodness(); center.x = r[0]; center.y = r[1]; radius = r[2]; int n = 0; double d = 0; for (int i=index+1;i<size;++i){ n++; Vector2D p = allPoints.get(i); double tmp = p.distance(center)-radius; if (n>3 && (d+tmp*tmp)/(n-3)>=1e-6){ nIndex = i; n--; break; } d += tmp*tmp; } dmin = d/(n-3); if (nIndex!=-1 && nIndex<=size-3){ Vector2D p1 = allPoints.get(nIndex); Vector2D p2 = allPoints.get((nIndex+size-1)/2); Vector2D p3 = allPoints.get(size-1); boolean isCircle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, r); if (isCircle){ r[2] = Math.sqrt(r[2]); nextRadius = r[2]; nextCenter = new Vector2D(r[0],r[1]); } } } catch (Exception e) { // TODO: handle exception } return dmin; } return -1; } public double calculateRadius(int index){ double[] r = new double[3]; if (center!=null){ int n = 0; double d = 0; for (int i=index+1;i<size;++i){ n++; Vector2D p = allPoints.get(i); double tmp = p.distance(center)-radius; if (n>3 && (d+tmp*tmp)/(n-3)>=1e-6){ nIndex = i; n--; break; } d += tmp*tmp; } dmin = d/(n-3); if (nIndex!=-1 && nIndex<=size-3){ Vector2D p1 = allPoints.get(nIndex); Vector2D p2 = allPoints.get((nIndex+size-1)/2); Vector2D p3 = allPoints.get(size-1); boolean isCircle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, r); if (isCircle){ r[2] = Math.sqrt(r[2]); nextRadius = r[2]; nextCenter = new Vector2D(r[0],r[1]); } } return dmin; } if (straightDist<allPoints.get(size-1).y){ double x0 = allPoints.get(0).x; if (size>index+3){ Vector2D p1 = allPoints.get(index+1); Vector2D p2 = allPoints.get(index+2); Vector2D p3 = allPoints.get(index+3); boolean isCircle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, r); if (isCircle){ r[2] = Math.sqrt(r[2]); double lx = r[0]-r[2]-x0; double rx = r[0]+r[2]-x0; if (lx>0.5 || rx<-0.5 || (lx*rx<0 && (lx<-0.5 && rx>0.5))){ Geom.getCircle2(p1, p3, new Vector2D(x0,0), new Vector2D(x0,1), r); r[2] = Math.sqrt(r[2]); } int n = 0; double d = 0; Vector2D o = new Vector2D(r[0],r[1]); for (int i=index+1;i<size;++i){ n++; Vector2D p = allPoints.get(i); double tmp = p.distance(o)-r[2]; if (n>3 && (d+tmp*tmp)/(n-3)>=1e-6){ nIndex = i; n--; break; } d += tmp*tmp; } dmin = d/(n-3); center = new Vector2D(r[0],r[1]); radius = r[2]; if (nIndex!=-1 && nIndex<=size-3){ p1 = allPoints.get(size-2); p2 = allPoints.get(size-3); p3 = allPoints.get(size-1); isCircle = Geom.getCircle(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, r); if (isCircle){ r[2] = Math.sqrt(r[2]); nextRadius = r[2]; nextCenter = new Vector2D(r[0],r[1]); } } return dmin; } } else if (size>index+2){ Vector2D p1 = allPoints.get(index+1); Vector2D p2 = allPoints.get(size-1); Geom.getCircle2(p1, p2, new Vector2D(x0,0), new Vector2D(x0,1), r); r[2] = Math.sqrt(r[2]); dmin = 0; center = new Vector2D(r[0],r[1]); radius = r[2]; return dmin; } } return -1; } public Edge(double[] xx,double[] yy){ x = new DoubleArrayList(xx); y = new DoubleArrayList(yy); size = xx.length; int sz = Math.max(size, NUM_POINTS); double[] aL = new double[sz]; Vector2D[] aP = new Vector2D[sz]; p2l = new Object2IntOpenHashMap<Vector2D>(sz); straightDist = 0; Vector2D prev = new Vector2D(xx[0],yy[0]); double x0 = xx[0]; double len = 0; int j = 0; for (int i=0;i<size;++i){ double x = xx[i]; double y = yy[i]; if (i>0 && y<yy[i-1]) continue; Vector2D p =new Vector2D(x,y); aP[j] = p; len += p.distance(prev); aL[j] = len; p2l.put(p, j); prev = p; if (x<=x0+DELTA && x>=x0-DELTA) { if (straightDist<y) straightDist = y; index = j; } j++; } this.size = j; allPoints = ObjectArrayList.wrap(aP); allLengths = new DoubleArrayList(aL); totalLength = len; allLengths.setSize(size); allPoints.size(size); x.setSize(size); y.setSize(size); if (index==0) index = -1; // calculateRadius(index); } public Edge(double[] xx,double[] yy,int size){ x = new DoubleArrayList(xx); y = new DoubleArrayList(yy); int sz = Math.max(size, NUM_POINTS); double[] aL = new double[sz]; Vector2D[] aP = new Vector2D[sz]; p2l = new Object2IntOpenHashMap<Vector2D>(sz); straightDist = 0; Vector2D prev = new Vector2D(xx[0],yy[0]); double len = 0; double x0 = xx[0]; int j = 0; for (int i=0;i<size;++i){ double x = xx[i]; double y = yy[i]; if (j>0 && y<prev.y) continue; Vector2D p =new Vector2D(x,y); aP[j] = p; len += p.distance(prev); aL[j] = len; p2l.put(p, j); prev = p; if (x<=x0+DELTA && x>=x0-DELTA) { if (straightDist<y) straightDist = y; index = j; } j++; } size = j; this.size = size; totalLength = len; allPoints = ObjectArrayList.wrap(aP,size); allLengths = new DoubleArrayList(aL); x.setSize(size); y.setSize(size); allLengths.setSize(size); if (index==0) index = -1; // calculateRadius(index); } public Edge(Vector2D[] v,int size){ int sz = Math.max(size, NUM_POINTS); double[] xx = new double[sz]; double[] yy = new double[sz]; double[] aL = new double[sz]; p2l = new Object2IntOpenHashMap<Vector2D>(sz); allPoints = ObjectArrayList.wrap(v,size); Vector2D prev = v[0]; double x0 = prev.x; double len = 0; straightDist = 0; int j = 0; for (int i=0;i<size;++i){ Vector2D p = v[i]; double x = p.x; double y = p.y; xx[i] = x; yy[i] = y; if (j>0 && y<prev.y) continue; len += p.distance(prev); aL[j] = len; p2l.put(p, j); prev = p; if (x<=x0+DELTA && x>=x0-DELTA) { if (straightDist<y) straightDist = y; index = j; } j++; } size = j; this.size = size; x = new DoubleArrayList(xx); y = new DoubleArrayList(yy); allLengths = new DoubleArrayList(aL); totalLength = len; x.setSize(size); y.setSize(size); allLengths.setSize(size); allPoints.size(size); if (index==0) index = -1; // calculateRadius(index); } public Edge(Vector2D[] v){ size = v.length; int sz = Math.max(size, NUM_POINTS); double[] xx = new double[sz]; double[] yy = new double[sz]; double[] aL = new double[sz]; p2l = new Object2IntOpenHashMap<Vector2D>(sz); allPoints = ObjectArrayList.wrap(v,size); straightDist = 0; Vector2D prev = v[0]; double len = 0; double x0 = prev.x; int j = 0; for (int i=0;i<size;++i){ Vector2D p = v[i]; double x = p.x; double y = p.y; xx[i] = x; yy[i] = y; if (j>0 && y<prev.y) continue; len += p.distance(prev); aL[j] = len; p2l.put(p, j); prev = p; if (x<=x0+DELTA && x>=x0-DELTA) { if (straightDist<y) straightDist = y; index = j; } j++; } this.size =j; x = new DoubleArrayList(xx); y = new DoubleArrayList(yy); allLengths = new DoubleArrayList(aL); totalLength = len; x.setSize(size); y.setSize(size); allLengths.setSize(size); if (index==0) index = -1; // calculateRadius(index); } public final Vector2D getHighestPoint(){ return allPoints.get(size-1); } public final Vector2D getLowestPoint(){ return allPoints.get(0); } public final Vector2D locatePointAtLength(double length){ if (allPoints==null || allLengths==null || size<2 || length<0) return null; int index = allLengths.binarySearch(length); Vector2D[] allPoints = this.allPoints.elements(); if (index>=0) return new Vector2D(allPoints[index]); if (index<0) index = -index+1; Vector2D t = null; Vector2D p = null; if (index>=size){ t = allPoints[size-1].minus(allPoints[size-2]).normalized(); p = allPoints[size-1]; return p.plus(t.times(length-totalLength)); } else { t = allPoints[index].minus(allPoints[index-1]).normalized(); p = allPoints[index-1]; } return p.plus(t.times(length-allLengths.getQuick(index-1))); } public final Vector2D estimatePointOnEdge(double length,Vector2D hP){ if (size<2) return null; Vector2D lastPoint = allPoints.get(size-1); if (length<totalLength || hP==null || hP.equals(lastPoint)) return locatePointAtLength(length); double d = length-totalLength; Vector2D t = hP.minus(lastPoint).normalized(); return lastPoint.plus(t.times(d)); } public boolean isStraight(Vector2D[] points){ if (points==null || points.length<2) return false; int len = points.length; if (len==2) return true; Vector2D v0 = points[0]; double min = Double.MAX_VALUE; double max = Double.MIN_VALUE; for (int i=1;i<len;++i){ Vector2D v = points[i]; double a = v.minus(v0).angle(); if (a<min) min = a; if (a>max) max = a; } return (Math.abs(max-min) < 0.1); } public final int turn(){ double sumx = 0; double[] xx = x.elements(); for (int i=0;i<size;++i) sumx +=xx[i]; double mean = sumx/size; double highestx = xx[size-1]; if (highestx>mean+DELTA) return MyDriver.TURNRIGHT; if (highestx<mean-DELTA) return MyDriver.TURNLEFT; return MyDriver.STRAIGHT; } public final void removeLastPoint(){ size--; Vector2D lastPoint = allPoints.get(size); if (straightDist==lastPoint.y ) straightDist=(size>=1) ? allPoints.get(size-1).y : 0; p2l.remove(lastPoint); allPoints.remove(size); x.remove(size); y.remove(size); allLengths.remove(size); } public final void append(Vector2D p){ Vector2D lastPoint = allPoints.get(size-1); size++; this.x.add(p.x); this.y.add(p.y); this.allPoints.add(p); totalLength += p.distance(lastPoint); this.allLengths.add(totalLength); this.p2l.put(p, size-1); double x0 = x.getQuick(0); if (straightDist==lastPoint.y && straightDist<p.y && p.x<=x0+DELTA && p.x>=x0-DELTA) { straightDist=p.y; index++; } // if (index<size) calculateRadius(index); } public final Vector2D get(int index){ if (index<0 || index>=size) return null; return allPoints.get(index); } public final static void drawEdge(Edge edge,final String title){ XYSeries series = new XYSeries("Curve"); for (int i=0;i<edge.size;++i){ Vector2D v = edge.get(i); series.add(v.x,v.y); } if (edge.center!=null){ // if (edge.radius<550) TrackSegment.circle(edge.center.x, edge.center.y, edge.radius, series); series.add(edge.center.x, edge.center.y); } XYDataset xyDataset = new XYSeriesCollection(series); // Create plot and show it final JFreeChart chart = ChartFactory.createScatterPlot(title, "x", "Membership", xyDataset, PlotOrientation.VERTICAL, false, true, false ); chart.getXYPlot().getDomainAxis().setRange(-50.0,50.0); chart.getXYPlot().getRangeAxis().setRange(-20.0,100.0); Thread p = new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try{ BufferedImage image = chart.createBufferedImage(600, 400); ImageIO.write(image, "png", new File(title+".png")); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }); p.start(); } public final static void drawEdge(Edge edge,XYSeries series){ for (int i=0;i<edge.size;++i){ Vector2D v = edge.get(i); series.add(v.x,v.y); } if (edge.center!=null){ TrackSegment.circle(edge.center.x, edge.center.y, edge.radius, series); } series.add(edge.center.x, edge.center.y); } }
package test; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class PrintTest { public static void main(String[] args) throws IOException, InterruptedException { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); ChromeDriver driver1=new ChromeDriver(); driver1.manage().window().maximize(); driver1.get("http://leaftaps.com/opentaps/"); driver1.findElementById("username").sendKeys("DemoSalesManager"); driver1.findElementById("password").sendKeys("crmsfa"); driver1.findElementByClassName("decorativeSubmit").click(); //Thread.sleep(3000); driver1.findElementByLinkText("CRM/SFA").click(); driver1.findElementByXPath("//a[contains(text(),'Leads')]").click(); driver1.findElementByXPath("//a[contains(text(),'Find Leads')]").click(); WebElement localvar = driver1.findElementByXPath("(//span[@class='x-tab-strip-text '])[2]"); localvar.click(); driver1.findElementByXPath("//input[@name='phoneCountryCode']").clear(); driver1.findElementByXPath("//input[@name='phoneCountryCode']").sendKeys("91"); driver1.findElementByXPath("//input[@name='phoneAreaCode']").sendKeys("044"); driver1.findElementByXPath("//input[@name='phoneNumber']").sendKeys("9840440863"); driver1.findElementByXPath("//button[text()='Find Leads']").click(); File src1 = driver1.getScreenshotAs(OutputType.FILE); File desc1 = new File("./snaps/CapLeadID1stRes.png"); FileUtils.copyFile(src1, desc1); Thread.sleep(20); String text = driver1.findElementByXPath("(//a[contains(text(),'12125')])[1]").getText(); System.out.println(text); Thread.sleep(20); } }
package com.myvodafone.android.front.fixed; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import com.myvodafone.android.R; import com.myvodafone.android.business.Errors; import com.myvodafone.android.business.managers.FixedLineServiceManager; import com.myvodafone.android.business.managers.MemoryCacheManager; import com.myvodafone.android.front.VFGRFragment; import com.myvodafone.android.front.auth.ActConnectAccount; import com.myvodafone.android.front.helpers.Dialogs; import com.myvodafone.android.front.soasta.OmnitureHelper; import com.myvodafone.android.model.service.fixed.FxlProduct; import com.myvodafone.android.model.service.fixed.FxlProductList; import com.myvodafone.android.model.service.fixed.GetWifiSettingsResponse; import com.myvodafone.android.model.service.fixed.SetWifiSettingsResponse; import com.myvodafone.android.utils.GlobalData; import com.myvodafone.android.utils.StaticTools; import java.lang.ref.WeakReference; import java.util.ArrayList; /** * Created by kakaso on 2/8/2016. */ public class FragmentFXLWiFiSettings extends VFGRFragment implements FixedLineServiceManager.FixedLineWiFiListener, FixedLineServiceManager.FixedLineProductListListener{ TextView txtWifiEquipment, txtWifiState, txtWifiName, txtWifiPassword, txtWifiChannel, txtWifiEncryption, wifiSetupHyperlink; EditText editWifiName, editWifiPassword; Spinner spinnerWifiChannel, spinnerEncryption, spinnerConnections; LinearLayout settingsContainer, errorContainer; Button btnEdit; public boolean isEditMode; String[] spinnerItems1 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"}; String[][] spinnerItems2 = {{"WPA","wpa"}, {"WPA-2","wpa2"}, {"WEP-128","wep128"} }; int currentSelection = 0; GetWifiSettingsResponse currentSettingsResponse; GetWifiSettingsResponse currentEditValues; public static FragmentFXLWiFiSettings newInstance() { return new FragmentFXLWiFiSettings(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_fxl_wifisettings, container, false); initElements(v); setDetailsMode(); return v; } @Override public void onResume() { super.onResume(); getWifiSettings(); activity.sideMenuHelper.setToggle(getView().findViewById(R.id.toggleDrawer)); activity.sideMenuHelper.setBackButton(getView().findViewById(R.id.back), activity); wifiSetupHyperlink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { activity.showWebView(GlobalData.strFixedWifiSettingsUrl, getFragmentTitle()); } }); //BG StaticTools.setAppBackground(getContext(),StaticTools.BACKGROUND_TYPE_INSIDE,(ImageView)getView().findViewById(R.id.insideBG),null); } private void getWifiSettings() { if(MemoryCacheManager.getFxlProductList()==null || MemoryCacheManager.getFxlProductList().getProductList()==null){ btnEdit.setEnabled(false); Dialogs.showProgress(getActivity()); FixedLineServiceManager.getProductList(getActivity(), new WeakReference<FixedLineServiceManager.FixedLineProductListListener>(this)); } else { Dialogs.showProgress(getActivity()); boolean connectionsAvailable = spinnerConnections.getAdapter() != null && spinnerConnections.getAdapter().getCount() > 0; String pId = connectionsAvailable ? getProductId((String) spinnerConnections.getItemAtPosition(currentSelection)) : ""; if (!pId.equals("")) { btnEdit.setEnabled(false); FixedLineServiceManager.getWifiSettings(pId, getActivity(), new WeakReference<FixedLineServiceManager.FixedLineWiFiListener>(FragmentFXLWiFiSettings.this)); } else{ Dialogs.closeProgress(); btnEdit.setEnabled(false); settingsContainer.setVisibility(View.GONE); errorContainer.setVisibility(View.VISIBLE); } } } private void initElements(View v){ txtWifiEquipment = (TextView) v.findViewById(R.id.txtWiFiEquipment); txtWifiState = (TextView) v.findViewById(R.id.txtWiFiStatus); txtWifiName = (TextView) v.findViewById(R.id.txtWiFiName); txtWifiPassword = (TextView) v.findViewById(R.id.txtWiFiPassword); txtWifiChannel = (TextView) v.findViewById(R.id.txtWiFiChannel); txtWifiEncryption = (TextView) v.findViewById(R.id.txtWiFiEncrypt); wifiSetupHyperlink = (TextView) v.findViewById(R.id.wifiSetupHyperlink); editWifiName = (EditText) v.findViewById(R.id.editWifiName); editWifiPassword = (EditText) v.findViewById(R.id.editWifiPassword); spinnerWifiChannel = (Spinner) v.findViewById(R.id.spinnerWiFiChannel); spinnerEncryption = (Spinner) v.findViewById(R.id.spinnerWifiEncrypt); spinnerConnections = (Spinner) v.findViewById(R.id.spinnerConnections); settingsContainer = (LinearLayout) v.findViewById(R.id.settingsContainer); errorContainer = (LinearLayout) v.findViewById(R.id.errorContainer); btnEdit = (Button) v.findViewById(R.id.btnWifiEdit); btnEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Omniture ** Wifi settings fixed submit ** OmnitureHelper.trackEvent("Wifi settings fixed submit"); onClickBtnEdit(); } }); header = (TextView) v.findViewById(R.id.headerTitle); setFragmentTitle(); ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getActivity(), R.layout.item_spinner_simple, spinnerItems1); adapter1.setDropDownViewResource(R.layout.item_spinner_simple); spinnerWifiChannel.setAdapter(adapter1); String[] encTypeItems = new String[3]; for(int i=0;i<3;i++){ encTypeItems[i] = spinnerItems2[i][0]; } ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, encTypeItems); adapter2.setDropDownViewResource(R.layout.item_spinner_simple); spinnerEncryption.setAdapter(adapter2); spinnerConnections = filterFXLConnectionsSpinner(spinnerConnections, this.getContext(), true); spinnerConnections.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if (spinnerConnections.getSelectedItem() != null && spinnerConnections.getSelectedItem().toString().length() > 0) { if (currentSelection != i) { currentSelection = i; String pId = getProductId((String) spinnerConnections.getSelectedItem()); if (!pId.equals("")) { Dialogs.showProgress(getActivity()); if (FixedLineServiceManager.getRunningTasksCounter() == 0) { btnEdit.setEnabled(false); FixedLineServiceManager.getWifiSettings(pId, getActivity(), new WeakReference<FixedLineServiceManager.FixedLineWiFiListener>(FragmentFXLWiFiSettings.this)); } } } } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); editWifiName.addTextChangedListener(textWatcher); editWifiPassword.addTextChangedListener(textWatcher); editWifiPassword.setText(""); } TextWatcher textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (isEditMode) { if (editWifiName.length() > 0 && editWifiPassword.length() > 0) { enableBtnEdit(); } else { disableBtnEdit(); } } } @Override public void afterTextChanged(Editable editable) { } }; private void enableBtnEdit(){ btnEdit.setTextColor(ContextCompat.getColor(activity, R.color.white)); btnEdit.setEnabled(true); } private void disableBtnEdit(){ btnEdit.setTextColor(ContextCompat.getColor(activity, R.color.btn_gray_light)); btnEdit.setEnabled(false); } private void setEditMode(){ isEditMode = true; txtWifiName.setVisibility(View.GONE); txtWifiPassword.setVisibility(View.GONE); txtWifiChannel.setVisibility(View.GONE); txtWifiEncryption.setVisibility(View.GONE); editWifiName.setVisibility(View.VISIBLE); editWifiPassword.setVisibility(View.VISIBLE); spinnerWifiChannel.setVisibility(View.VISIBLE); spinnerEncryption.setVisibility(View.VISIBLE); btnEdit.setActivated(true); btnEdit.setTextColor(ContextCompat.getColor(activity, R.color.btn_gray_light)); btnEdit.setEnabled(false); btnEdit.setText(R.string.wifi_settings_confirm_button); editWifiPassword.setText(""); spinnerConnections.setEnabled(false); } public void setDetailsMode(){ isEditMode = false; txtWifiName.setVisibility(View.VISIBLE); txtWifiPassword.setVisibility(View.VISIBLE); txtWifiChannel.setVisibility(View.VISIBLE); txtWifiEncryption.setVisibility(View.VISIBLE); editWifiName.setVisibility(View.GONE); editWifiPassword.setVisibility(View.GONE); spinnerWifiChannel.setVisibility(View.GONE); spinnerEncryption.setVisibility(View.GONE); btnEdit.setActivated(true); btnEdit.setTextColor(ContextCompat.getColor(activity, R.color.white)); enableBtnEdit(); btnEdit.setText(R.string.wifi_settings_edit_button); if (multipleConnectionsExist()) { spinnerConnections.setEnabled(true); } else { spinnerConnections.setEnabled(false); } } private void onClickBtnEdit(){ if(isEditMode){ //setDetailsMode(); //isEditMode = false; onSubmitSettings(); } else{ setEditMode(); } } @Override public BackFragment getPreviousFragment() { return BackFragment.FragmentHome; } @Override public String getFragmentTitle() { return getString(R.string.wifi_settings_label); } @Override public void onSuccessGetWiFiSettings(final GetWifiSettingsResponse response) { runOnUiThread(new Runnable() { @Override public void run() { currentSettingsResponse = response; settingsContainer.setVisibility(View.VISIBLE); errorContainer.setVisibility(View.GONE); Dialogs.closeProgress(); bindWifiSettings(response); } }); } @Override public void onSuccessSubmitWiFiSettings(final SetWifiSettingsResponse response) { runOnUiThread(new Runnable() { @Override public void run() { Dialogs.closeProgress(); if (currentEditValues != null) { bindWifiSettings(currentEditValues); if(response!=null && response.getWifiSettingsSaved()){ Dialogs.showDialog(activity, getString(R.string.wifi_settings_verification_message)); } else{ Dialogs.showErrorDialog(activity, getString(R.string.vf_generic_error)); } } setDetailsMode(); } }); } @Override public void onErrorGetWiFiSettings(int errorCode) { runOnUiThread(new Runnable() { @Override public void run() { Dialogs.closeProgress(); } }); } @Override public void onErrorSubmitWiFiSettings(int errorCode) { runOnUiThread(new Runnable() { @Override public void run() { Dialogs.closeProgress(); } }); } @Override public void onGenericErrorFixedLineWiFi(final int errorCode) { runOnUiThread(new Runnable() { @Override public void run() { Dialogs.closeProgress(); if (errorCode == Errors.ERROR_FXL_WIFI_SETTINGS_GET) { settingsContainer.setVisibility(View.GONE); errorContainer.setVisibility(View.VISIBLE); } else { Dialogs.showErrorDialog(activity, getString(R.string.vf_generic_error)); } } }); } @Override public void onSuccessProductList(FxlProductList productList) { runOnUiThread(new Runnable() { @Override public void run() { filterFXLConnectionsSpinner(spinnerConnections, getActivity(), true); boolean connectionsAvailable = spinnerConnections.getAdapter() != null && spinnerConnections.getAdapter().getCount() > 0; String pId = connectionsAvailable ? getProductId((String) spinnerConnections.getItemAtPosition(currentSelection)) : ""; if (!pId.equals("")) { btnEdit.setEnabled(false); FixedLineServiceManager.getWifiSettings(pId, getActivity(), new WeakReference<FixedLineServiceManager.FixedLineWiFiListener>(FragmentFXLWiFiSettings.this)); } else { Dialogs.closeProgress(); btnEdit.setEnabled(false); settingsContainer.setVisibility(View.GONE); errorContainer.setVisibility(View.VISIBLE); } } }); } @Override public void onErrorProductList(int errorCode) { runOnUiThread(new Runnable() { @Override public void run() { Dialogs.closeProgress(); } }); } @Override public void onGenericErrorProductList() { runOnUiThread(new Runnable() { @Override public void run() { Dialogs.closeProgress(); Dialogs.showErrorDialog(getActivity(), getString(R.string.vf_generic_error)); } }); } private void bindWifiSettings(GetWifiSettingsResponse response){ if(response!=null && response.getSsID()!=null && !response.getSsID().equals("")) { enableBtnEdit(); txtWifiName.setText(response.getSsID()); editWifiName.setText(response.getSsID()); txtWifiState.setText(response.getStatus()); txtWifiEquipment.setText(response.getFirmwareName()); txtWifiPassword.setText("**********"); try { int channel = Integer.parseInt(response.getChannel()); if (response.getIeee11iEncryptionModes() != null) { if (response.getIeee11iEncryptionModes().equalsIgnoreCase("wpa")) { spinnerEncryption.setSelection(0); txtWifiEncryption.setText(spinnerItems2[0][0]); } else if (response.getIeee11iEncryptionModes().equalsIgnoreCase("wpa2")) { spinnerEncryption.setSelection(1); txtWifiEncryption.setText(spinnerItems2[1][0]); } else if (response.getIeee11iEncryptionModes().equalsIgnoreCase("wep128")) { spinnerEncryption.setSelection(2); txtWifiEncryption.setText(spinnerItems2[2][0]); } } if (channel > 0) { spinnerWifiChannel.setSelection(channel - 1); txtWifiChannel.setText(spinnerItems1[channel - 1]); } else { spinnerWifiChannel.setSelection(0); txtWifiChannel.setText(spinnerItems1[0]); } settingsContainer.setVisibility(View.VISIBLE); errorContainer.setVisibility(View.GONE); } catch (Exception e) { StaticTools.Log(e); settingsContainer.setVisibility(View.GONE); errorContainer.setVisibility(View.VISIBLE); } } else{ settingsContainer.setVisibility(View.GONE); errorContainer.setVisibility(View.VISIBLE); btnEdit.setEnabled(false); } } enum WiFiSettingsValidation{ SUCCESS, EMPTY_NAME, INVALID_PASSWORD } private WiFiSettingsValidation validateFields() { WiFiSettingsValidation validationResult = WiFiSettingsValidation.SUCCESS; if(editWifiName.getText().length()==0){ validationResult = WiFiSettingsValidation.EMPTY_NAME; return validationResult; } if (spinnerEncryption.getSelectedItemPosition() == 2) { if(!regularExpressionMatcher("^[a-zA-Z0-9\\s]{13}$", editWifiPassword.getText().toString())){ validationResult = WiFiSettingsValidation.INVALID_PASSWORD; } } else { if(!regularExpressionMatcher("^[a-zA-Z0-9\\s]{8,63}$", editWifiPassword.getText().toString())){ validationResult = WiFiSettingsValidation.INVALID_PASSWORD; } } return validationResult; } private String getEncryptionModeValue(String selection){ String result = ""; for(int i=0;i<spinnerItems2.length;i++){ if(spinnerItems2[i][0].equals(selection)){ result = spinnerItems2[i][1]; } } return result; } private GetWifiSettingsResponse setEditValues(){ GetWifiSettingsResponse editValues = new GetWifiSettingsResponse(); try { editValues.setFirmwareName(currentSettingsResponse.getFirmwareName()); editValues.setSsID(editWifiName.getText().toString()); editValues.setChannel((String) spinnerWifiChannel.getSelectedItem()); editValues.setIeee11iEncryptionModes(getEncryptionModeValue(spinnerEncryption.getSelectedItem().toString())); editValues.setCid(currentSettingsResponse.getCid()); editValues.setStatus(currentSettingsResponse.getStatus()); } catch (Exception e){ StaticTools.Log(e); } return editValues; } private void onSubmitSettings() { WiFiSettingsValidation validationResult = validateFields(); switch (validationResult) { case SUCCESS: Dialogs.showProgress(getContext()); currentEditValues = setEditValues(); FixedLineServiceManager.setWifiSettings(currentSettingsResponse.getCid(), currentEditValues, editWifiPassword.getText().toString(), getActivity(), new WeakReference<FixedLineServiceManager.FixedLineWiFiListener>(this)); break; case EMPTY_NAME: Dialogs.showErrorDialog(this.getContext(), getString(R.string.wifi_settings_no_username_message)); break; case INVALID_PASSWORD: Dialogs.showErrorDialog(this.getContext(), getString(R.string.wifi_settings_wrong_credentials_message)); break; } } private boolean multipleConnectionsExist() { ArrayList<String> connections = new ArrayList<String>(); if (MemoryCacheManager.getFxlProductList() != null && MemoryCacheManager.getFxlProductList().getProductList() != null) { for (FxlProduct product : MemoryCacheManager.getFxlProductList().getProductList()) { if (product.getProductType().equalsIgnoreCase(PRODUCT_TYPE_TO_BE_USED)) { connections.add(product.getCli()); } } } return connections.size() > 1; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.StringTokenizer; /* URL https://www.acmicpc.net/problem/3190 */ public class Main3190_뱀 { static int n, k, l, resCnt, map[][], move[][]; static HashMap<Integer, Boolean> turns; public static void main(String[] args) throws IOException { input(); dummy(); print(); } private static void input() throws IOException { move = new int[][]{ {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); n = Integer.parseInt(br.readLine().trim()); k = Integer.parseInt(br.readLine().trim()); map = new int[n+2][n+2]; for (int i = 0; i < n+2; i++) for (int j = 0; j < n+2; j++) if (i == 0 || i == n+1 || j == 0 || j == n+1) map[i][j] = -1; StringTokenizer st; for (int i = 0; i < k; i++ ) { st = new StringTokenizer(br.readLine().trim()); map[Integer.parseInt(st.nextToken())][Integer.parseInt(st.nextToken())] = -2; } turns = new HashMap<>(); l= Integer.parseInt(br.readLine().trim()); for (int i = 0; i < l; i++) { st = new StringTokenizer(br.readLine().trim()); turns.put(Integer.parseInt(st.nextToken()), st.nextToken().equals("L")); } } private static void dummy() { int row = 1, col = 1, len = 1, dir = 3, tailR = 1, tailC = 1, tailRtemp, tailCtemp; resCnt = 1; map[row][col] = resCnt; while (true) { row = row + move[dir][0]; col = col + move[dir][1]; resCnt++; if (map[row][col] == -1 || map[row][col] > 0) break; if (map[row][col] != -2) { if (len == 1) { map[tailR][tailC] = 0; tailR = row; tailC = col; } else { for (int i = 0; i < 4; i++) { tailRtemp = tailR + move[i][0]; tailCtemp = tailC + move[i][1]; if (map[tailRtemp][tailCtemp] - map[tailR][tailC] == 1) { map[tailR][tailC] = 0; tailR = tailRtemp; tailC = tailCtemp; break; } } } } else len++; map[row][col] = resCnt; if (turns.containsKey(resCnt-1)) { if (turns.get(resCnt-1)) dir = (dir < 2)? 5-(3-dir):3-dir; else dir = (dir < 2)? 3-dir:1-(3-dir); } } } private static void print() { System.out.println(resCnt-1); } }
package dubstep; //@Author - Apoorva Biseria import java.util.List; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.select.FromItem; import net.sf.jsqlparser.statement.select.Join; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.SubSelect; public class SubSelectHandler { public static void excecute(PlainSelect plain) { //List<SelectItem> subSelectItems = plain.getSelectItems(); PlainSelect ps =(PlainSelect)((SubSelect) plain.getFromItem()).getSelectBody(); //System.out.println(ps); FromItem subFromItem = ps.getFromItem(); if(subFromItem instanceof SubSelect) {if (ps.getWhere()!=null) { //System.out.println("java"); Expression expression = ps.getWhere(); ConfigureVariables.whereArrayList.add(expression); } excecute(ps); } //System.out.println(subFromItem); else { Table nameTable= (Table)subFromItem; String tnameString = nameTable.getName(); ConfigureVariables.tableStrings.add(tnameString); if(ps.getJoins()!=null) { List<Join> subJoins = ps.getJoins(); if (subJoins.contains("JOIN")) { //System.out.println(joins.size()); //Configuration.conditionsArrayList.add(true); ConfigureVariables.JOIN = 1; for(Join i:subJoins) { System.out.println(i.getRightItem()); String rightString =i.getRightItem().toString(); ConfigureVariables.tableStrings.add(rightString); if(i.getOnExpression()!=null) { Expression onExpression = i.getOnExpression(); ConfigureVariables.OnList.add(onExpression); } }}else { ConfigureVariables.JOIN = -1; for(Join i:subJoins) { System.out.println(i); //Table nameTable = ConfigureVariables.tableStrings.add(i.toString()); } } System.out.println(subJoins.size()); System.out.println(subJoins); } //PlainSelect plainSelect = (PlainSelect)subSelect.getSelectBody() ; if (ps.getWhere()!=null) { Expression expression = ps.getWhere(); ConfigureVariables.whereArrayList.add(expression); //System.out.println("java"); } } //System.out.println(subFromItem); }} //Configuration.coList.add(colNameStrings); //Configuration.coList.add(tableList);
/* * @lc app=leetcode.cn id=136 lang=java * * [136] 只出现一次的数字 * * https://leetcode-cn.com/problems/single-number/description/ * * algorithms * Easy (58.07%) * Total Accepted: 41.7K * Total Submissions: 71.8K * Testcase Example: '[2,2,1]' * * 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 * * 说明: * * 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? * * 示例 1: * * 输入: [2,2,1] * 输出: 1 * * * 示例 2: * * 输入: [4,1,2,1,2] * 输出: 4 * */ class Solution { public int singleNumber(int[] nums) { //^ 位运算, 相同为0,不同为1 int ans = 0; for (int num : nums) { ans ^= num; } return ans; } }
package org.qamation.charities.worker; import org.openqa.selenium.WebDriver; import org.qamation.charities.extractor.Extract; import org.qamation.charities.extractor.FinInfoExtractor; import org.qamation.charities.info.CharityInfo; import org.qamation.charities.info.Storage; import org.qamation.webdriver.utils.WebDriverFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; public class Worker implements Runnable { private static Logger log = LoggerFactory.getLogger(Worker.class); private WebDriver driver; private ConcurrentLinkedQueue<String> queue; public Worker(ConcurrentLinkedQueue<String> queue ) { this.driver = WebDriverFactory.createChromeWebDriver(Extract.getWebDriverPath()); this.queue = queue; } @Override public void run() { while(!queue.isEmpty()) { String url=""; try { url = queue.poll(); FinInfoExtractor extractor = new FinInfoExtractor(driver, url); CharityInfo charity = new CharityInfo(extractor); Storage.addCharity(charity); } catch (Exception ex) { ex.printStackTrace(); log.error("Problem parsing info for <"+url+">"); run(); } } if (driver != null) { driver.quit(); driver = null; } } }
package com.example.gtraderprototype.views; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProviders; import com.example.gtraderprototype.R; import com.example.gtraderprototype.entity.Difficulty; import com.example.gtraderprototype.entity.Item; import com.example.gtraderprototype.entity.Player; import com.example.gtraderprototype.entity.Ship; import com.example.gtraderprototype.model.Model; import com.example.gtraderprototype.viewmodels.EncounterViewModel; import java.util.ArrayList; import java.util.List; import java.util.Random; public class EncounterTraderActivity extends AppCompatActivity { private Button trade; private Button attack; private Button flee; private TextView text; private Player player; private Ship ship; private Difficulty difficulty; private List<Item> cargo; private List<Item> offeredItems; double total; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.encounter_trader_trade); trade=findViewById(R.id.button_trade); attack=findViewById(R.id.button_attack); flee=findViewById(R.id.button_flee); text=findViewById(R.id.text_trader); EncounterViewModel viewModel = ViewModelProviders.of(this).get(EncounterViewModel.class); player=viewModel.getPlayer(); ship=player.getSpaceShip(); difficulty= Model.getInstance().getGameInstanceInteractor().getGameDifficulty(); cargo=ship.getCargo(); offeredItems=new ArrayList<>(); total=0; trade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { trade(); } }); attack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { attack(); } }); flee.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } private void trade() { trade.setText("Deal"); attack.setText("Attack"); flee.setText("Refuse and end Trade"); trade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { initializeTradeList(); text.setText("The trader offers " + offeredItems.toString() + " for " + (int)total); trade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deal(); finish(); } }); } }); } private void initializeTradeList() { offeredItems.clear(); total = 0; Random rand = new Random(); int numOfferedItems = rand.nextInt(4) + 1; for (int i = 0; i < numOfferedItems; i++) { int randomIndex = rand.nextInt((ship.getNumberOfUsedCargoBays()) ); Item offered = cargo.get(randomIndex); total += offered.getBasePrice(); offeredItems.add(offered); } double variance = rand.nextDouble() * (2) - 1; total = total*(1 + variance); } private void deal() { if (player.getMoney() >= total) { for (Item i: offeredItems) { ship.addCargo(i); } player.setMoney(player.getMoney() - (int)total); } else { text.setText("Not enough money"); } } private void attack() { attack.setText("Attack Again"); trade.setText("Deal abd end Trade"); attack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { double winChance = 1.0 - ((difficulty.difficultyIndex() + 1) / (double) 10); if (Math.random() < winChance) { initializeTradeList(); total = total * 0.8; text.setText("The trader offers " + offeredItems.toString() + " for " + (int)total); } else { text.setText("you failed the attack"); flee(); } trade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deal(); finish(); } }); } }); } private void flee() { trade.setEnabled(false); trade.setVisibility(View.GONE); attack.setEnabled(false); attack.setVisibility(View.GONE); flee.setText("Back"); flee.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { double percent = (difficulty.difficultyIndex() + 1) * 2 / (double) 50; int numDroppedItems = (int)(ship.getNumberOfUsedCargoBays() * percent); List<Item> droppedItems = new ArrayList<>(); for (int i = 0; i < numDroppedItems; i++) { int randomIndex = (int)Math.random() * (ship.getNumberOfUsedCargoBays() + 1); Item dropped = cargo.remove(randomIndex); droppedItems.add(dropped); ship.dropCargo(dropped); } text.setText("You dropped " + droppedItems.toString() + " during fleeing"); finish(); } }); } }
package ar.edu.unlam.scaw.dao; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import ar.edu.unlam.scaw.modelo.Usuario; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.inject.Inject; // implelemtacion del DAO de usuarios, la anotacion @Repository indica a Spring que esta clase es un componente que debe // ser manejado por el framework, debe indicarse en applicationContext que busque en el paquete ar.edu.unlam.tallerweb1.dao // para encontrar esta clase. @Repository("UsuarioDao") public class UsuarioDaoImpl implements UsuarioDao { // Como todo dao maneja acciones de persistencia, normalmente estará inyectado el session factory de hibernate // el mismo está difinido en el archivo hibernateContext.xml @Inject private SessionFactory sessionFactory; @Override public Usuario consultarUsuario(Usuario usuario) { // Se obtiene la sesion asociada a la transaccion iniciada en el servicio que invoca a este metodo y se crea un criterio // de busqueda de Usuario donde el email y password sean iguales a los del objeto recibido como parametro // uniqueResult da error si se encuentran más de un resultado en la busqueda. final Session session = sessionFactory.getCurrentSession(); return (Usuario) session.createCriteria(Usuario.class) .add(Restrictions.eq("nickname", usuario.getNickname())) .add(Restrictions.eq("password", usuario.getPassword())) .uniqueResult(); } @Override public void insertUsuario(Usuario usuario) { sessionFactory.getCurrentSession().save(usuario); } @Override public Usuario consultarUsuarioPorNickname(String nickname) { // Se obtiene la sesion asociada a la transaccion iniciada en el servicio que invoca a este metodo y se crea un criterio // de busqueda de Usuario donde el email y password sean iguales a los del objeto recibido como parametro // uniqueResult da error si se encuentran más de un resultado en la busqueda. final Session session = sessionFactory.getCurrentSession(); return (Usuario) session.createCriteria(Usuario.class) .add(Restrictions.eq("nickname", nickname)) .uniqueResult(); } @Override public List<Usuario> consultarUsuariosInactivos() { final Session session = sessionFactory.getCurrentSession(); List<Usuario> usuarios = (List<Usuario>) session.createCriteria(Usuario.class) .add(Restrictions.isNotNull("fecha_inactivo")) .list(); return usuarios; } @SuppressWarnings("unchecked") @Override public Usuario buscarUsuarioPorEmail(String email) { final Session session = sessionFactory.getCurrentSession(); return (Usuario) session.createCriteria(Usuario.class) .add(Restrictions.eq("email", email)) .uniqueResult(); } @Override public Usuario consultarUsuarioPorEmailYPassword(Usuario usuario) { // Se obtiene la sesion asociada a la transaccion iniciada en el servicio que invoca a este metodo y se crea un criterio // de busqueda de Usuario donde el email y password sean iguales a los del objeto recibido como parametro // uniqueResult da error si se encuentran más de un resultado en la busqueda. final Session session = sessionFactory.getCurrentSession(); return (Usuario) session.createCriteria(Usuario.class) .add(Restrictions.eq("email", usuario.getEmail())) .add(Restrictions.eq("password", usuario.getPassword())) .uniqueResult(); } @Override @SuppressWarnings("unchecked") public List<Usuario> consultarUsuarios() { // Se obtiene la sesion asociada a la transaccion iniciada en el servicio que invoca a este metodo y se crea un criterio // de busqueda de Usuario para traer los que tengan rol user final Session session = sessionFactory.getCurrentSession(); List<Usuario> usuarios = (List<Usuario>) session.createCriteria(Usuario.class) .add(Restrictions.eq("rol", "usuario")) .list(); return usuarios; } @Override public void habilitarUsuario(int idUsuario) { final Session session = sessionFactory.getCurrentSession(); Query q = session.createQuery("from Usuario u where u.id = :idUsuario "); q.setParameter("idUsuario", idUsuario); Usuario user = (Usuario)q.list().get(0); user.setEstado("habilitado"); user.setFechaInactivo(null); session.update(user); } @Override public void deshabilitarUsuario(int idUsuario) { final Session session = sessionFactory.getCurrentSession(); Query q = session.createQuery("from Usuario u where u.id = :idUsuario "); q.setParameter("idUsuario", idUsuario); Usuario user = (Usuario)q.list().get(0); user.setEstado("deshabilitado"); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String fecha = dateFormat.format(new Date()); try { Date date1 = dateFormat.parse(fecha); user.setFechaInactivo(date1); } catch (ParseException e) { e.printStackTrace(); } session.update(user); } @Override public void updateUsuario(Usuario usuario) { sessionFactory.getCurrentSession().update(usuario); } @Override public void deleteUsuario(Usuario usuario) { sessionFactory.getCurrentSession().delete(usuario); } @Override public Usuario buscarUsuarioXId(int id) { Session session = sessionFactory.getCurrentSession(); return session.get(Usuario.class, id); } @Override public boolean existeUsername(Usuario usuario) { final Session session = sessionFactory.getCurrentSession(); Usuario usuarioEncontrado = (Usuario) session.createCriteria(Usuario.class) .add(Restrictions.eq("nickname", usuario.getNickname())) .uniqueResult(); return (usuarioEncontrado != null); } }
package se.rtz.bindings.view.table; import java.math.BigDecimal; import se.rtz.bindings.model.ListModel; import se.rtz.bindings.model.TableModelAdapter; final class ItemTableAdapter extends TableModelAdapter<Item> { ItemTableAdapter(ListModel<Item> list) { super( // new String[] { "name", "shoe size", "salary", "is consultant" }, // new Class[] { String.class, Integer.class, BigDecimal.class, Boolean.class }, // list); } @Override protected void set(Item item, int columnIndex, Object aValue) { switch (columnIndex) { case 0: item.setName(aValue.toString()); break; case 1: item.setShoeSize(Integer.parseInt(aValue.toString())); break; case 2: item.setSalary(new BigDecimal(aValue.toString())); break; case 3: item.setConsultant(new Boolean(aValue.toString())); break; default: throw new RuntimeException("unknown column: " + columnIndex); } } @Override protected Object get(Item item, int columnIndex) { switch (columnIndex) { case 0: return item.getName(); case 1: return item.getShoeSize(); case 2: return item.getSalary(); case 3: return item.isConsultant(); default: throw new RuntimeException("unknown column: " + columnIndex); } } }
package com.wangzhu.utils; import org.apache.commons.lang3.StringUtils; /** * Created by wang.zhu on 2021-05-27 15:49. **/ public class Test { //单向链表 //反转链表 public static void main(String[] args) { // int[] nums = {1, 2, 3, 4}; // ListNode listNode = create(nums); // print(listNode); // ListNode reverseListNode = reverse(listNode); // System.out.println("反转后---"); // print(reverseListNode); String strA = "255.255.1.255"; int ret = transferInt(strA); System.out.println("ret=" + ret); String strB = transferStr(ret); System.out.println("strA=" + strA); System.out.println("strB=" + strB); } static void print(ListNode listNode) { while (listNode != null) { System.out.print(listNode.val + "->"); listNode = listNode.next; } System.out.println(); } static ListNode create(int[] nums) { ListNode head = new ListNode(); ListNode tail = head; for (int i = 0, len = nums.length; i < len; i++) { tail.next = new ListNode(nums[i]); tail = tail.next; } return head.next; } static ListNode reverse(ListNode listNode) { ListNode head = null; while (listNode != null) { ListNode next = listNode.next; listNode.next = head; head = listNode; listNode = next; } return head; } static class ListNode { int val; ListNode next; public ListNode() { } public ListNode(int val) { this.val = val; } public ListNode(int val, ListNode next) { this.val = val; this.next = next; } } static int transferInt(String str){ if(str == null || str.length() == 0){ // } String[] arr = StringUtils.split(str, "\\."); if(arr.length != 4){ // } int ret = 0; int i = 0; for(String item : arr){ int num = Integer.parseInt(item); ret += num<<i; i+=8; } return ret; } static String transferStr(int num){ StringBuilder stringBuilder = new StringBuilder(); boolean flag = false; while(num != 0){ if(flag){ stringBuilder.append("."); } stringBuilder.append(num &(0xff)); num >>>= 8; flag = true; } return stringBuilder.toString(); } }
package fr.iutinfo.skeleton.api; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; @Path("/formation") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class FormationResource { private static FormationDao dao = BDDFactory.getDbi().open(FormationDao.class); final static Logger logger = LoggerFactory.getLogger(SecureResource.class); Gson gson = new Gson(); @GET public Response getFormetabl(@QueryParam("lib") String lib) { List res; logger.debug(lib); if (lib != null) { res = dao.getFormetablByDiplome(lib); } else { res = dao.getFormetabl(); } return Response.status(200).entity(gson.toJson(res)).build(); } @PUT public Response addFormEtabl(@QueryParam("fno") int fno, @QueryParam("eno") int eno) { dao.addFormEtabl(fno, eno); return Response.status(200).entity("OK").build(); } @GET @Path("/diplome") public Response getDiplomes() { List<Diplome> reponse = dao.getDiplomes(); return Response.status(200).entity(gson.toJson(reponse)).build(); } @GET @Path("/domaine") public Response getDomaineByDiplome(@QueryParam("lib") String lib) { List<Formation> res = dao.getDomaineByDiplome(lib); return Response.status(200).entity(gson.toJson(res)).build(); } @PUT @Path("/domaine") public Response addDomaineByDiplome(@QueryParam("lib") String lib, @QueryParam("domaine") String domaine) { dao.addDomaineByDiplome(lib, domaine); return Response.status(200).entity("Ok").build(); } @DELETE public Response removeVoeuTo(@QueryParam("feno") int feno) { dao.removeFormEtabl(feno); return Response.status(200).entity("Ok").build(); } }
package com.tdr.registrationv3.service.presenter; import com.tdr.registrationv3.http.utils.DdcResult; import com.tdr.registrationv3.service.BaseView; import okhttp3.RequestBody; public interface CarChangePresenter { interface View extends BaseView<DdcResult> { } interface Presenter { void carChange(RequestBody route); } }
package de.uni_hamburg.informatik.swt.se2.mediathek.materialien; import java.util.List; import de.uni_hamburg.informatik.swt.se2.mediathek.materialien.medien.Medium; public class Vormerkkarte { private List<Kunde> _vormerker; private final Medium _medium; public Vormerkkarte(Medium medium) { _medium = medium; _vormerker = new ArrayList<Kunde>(3); } public Kunde getErstenVormerker() { return _vormerker.get(0); } public boolean istVormerkenMöglich(Kunde kunde) { if ((_vormerker.size()<3)&&(!istVerliehenAn(kunde, _medium) { return true; } else { return false; } } public List<Kunde> getAlleVormerker() { return _vormerker; } public void merkeVor(Kunde kunde) { } public String getFormatiertenString() { return _medium.getFormatiertenString() + "vorgemerkt von" + _vormerker.toString(); } public Medium getMedium() { return _medium; } }
package javaCode; import java.util.*; /* Binary Search Tree Implementation in Java*/ class BinarySearchTree{ class BNode{ private int key; private BNode leftNode, rightNode; public BNode(int item){ this.key = item; this.leftNode=this.rightNode=null; } } public static BNode root; public BinarySearchTree(int item){ root = insertNode(item, null); //Inserting root element } //BST Insert New Node into Tree public BNode insertNode(int key,BNode root){ if(root == null){ return root = new BNode(key); } if(key < root.key){ root.leftNode = insertNode(key,root.leftNode); //Key value Smaller to parent node }else{ root.rightNode = insertNode(key,root.rightNode); //Key value Greater or Equal to parent node } return root; } //BST In-Order Traversals (Prints Sorted Elements) public void inorderTraversal(BNode root){ if(root != null){ inorderTraversal(root.leftNode); System.out.println(root.key); inorderTraversal(root.rightNode); } } //BST Pre-Order Traversals public void preorderTraversal(BNode root){ if(root != null){ System.out.println(root.key); preorderTraversal(root.leftNode); preorderTraversal(root.rightNode); } } //BST Post-Order Traversals public void postorderTraversal(BNode root){ if(root != null){ postorderTraversal(root.leftNode); postorderTraversal(root.rightNode); System.out.println(root.key); } } //BST Searching Key public void searchBST(BNode root, int search){ if(root == null){ System.out.println(search+"-key is NOT present in BST"); }else if(root.key == search){ System.out.println(search+"-key is present in BST"); }else if(search < root.key){ searchBST(root.leftNode, search); }else{ searchBST(root.rightNode, search); } } public static void main(String[] args){ Scanner scan = new Scanner(System.in); System.out.println("Enter Root Key Of The Tree: "); BinarySearchTree bsTree = new BinarySearchTree(scan.nextInt()); while(true){ System.out.println("Select Operations to be performed:"); System.out.println("0-Exit, 1:Insert, 2:In-Order, 3:Pre-Order, 4:Post-Order, 5:Search"); int operation = scan.nextInt(); switch(operation){ case 1: System.out.println("Enter Next-Key to be inserted into tree: "); int key = scan.nextInt(); bsTree.insertNode(key, root); break; case 2: System.out.println("In-Order Traversal of Tree is: "); bsTree.inorderTraversal(root); break; case 3: System.out.println("Pre-Order Traversal of Tree is: "); bsTree.preorderTraversal(root); break; case 4: System.out.println("Post-Order Traversal of Tree is: "); bsTree.postorderTraversal(root); break; case 5: System.out.println("Enter Key to be searched in BSTree: "); bsTree.searchBST(root,scan.nextInt()); break; default: System.out.println("BST says Bye.,"); break; } if(operation == 0){ break; } } } }
package com.util; import java.sql.*; public class JDBCUtil { static { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } String URL = "jdbc:mysql://localhost:3306/java_Test?serverTimezone=UTC"; String USERNAME = "root"; String PASSWORD = "121314"; private Connection con = null; private PreparedStatement ps = null; public Connection getCon() { try { con = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return con; } public PreparedStatement createStatement(String sql) { try { ps = getCon().prepareStatement(sql); } catch (SQLException e) { e.printStackTrace(); } return ps; } public void close() { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } public void close(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } close(); } }
package com.hamatus.domain.enumeration; /** * The MapMarkerType enumeration. */ public enum MapMarkerType { AREA,SECTOR,PARKING_PLACE,PUBLIC_TRANSPORT,POI }
package com.example.university.service; import com.example.university.dto.DegreeCount; import com.example.university.model.Department; import com.example.university.model.Lector; import java.util.List; public interface LectorService { Lector getDepartmentHeadByDepartment(Department department); List<DegreeCount> getStatisticCountsDegree(Department department); Double getAvgSalaryByDepartment(Department department); Long getCountEmployeesByDepartment(Department department); List<Lector> globalSearch(String template); }
/* * This Java source file was generated by the Gradle 'init' task. */ package com.pankaj.hive; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.io.Text; public class Strip extends UDF{ private Text text =new Text(); public Text evaluate(Text text, String str) { if(text==null)return null; this.text.set(StringUtils.strip(text.toString(),str)); return this.text; } public Text evaluate(Text text) { if(text==null)return null; this.text.set(StringUtils.strip(text.toString())); return this.text; } }
package by.htp.cratemynewpc.domain; public class MBBean { private Integer idMb; private Integer mbName; private Integer mbCpuSocket; private Integer mbChipset; private Integer mbMemoryType; private Integer mbMemorySlots; private Integer mbMemoryMaxGb; private Integer mbVgaSyp; public Integer getIdMb() { return idMb; } public void setIdMb(Integer idMb) { this.idMb = idMb; } public Integer getMbName() { return mbName; } public void setMbName(Integer mbName) { this.mbName = mbName; } public Integer getMbCpuSocket() { return mbCpuSocket; } public void setMbCpuSocket(Integer mbCpuSocket) { this.mbCpuSocket = mbCpuSocket; } public Integer getMbChipset() { return mbChipset; } public void setMbChipset(Integer mbChipset) { this.mbChipset = mbChipset; } public Integer getMbMemoryType() { return mbMemoryType; } public void setMbMemoryType(Integer mbMemoryType) { this.mbMemoryType = mbMemoryType; } public Integer getMbMemorySlots() { return mbMemorySlots; } public void setMbMemorySlots(Integer mbMemorySlots) { this.mbMemorySlots = mbMemorySlots; } public Integer getMbMemoryMaxGb() { return mbMemoryMaxGb; } public void setMbMemoryMaxGb(Integer mbMemoryMaxGb) { this.mbMemoryMaxGb = mbMemoryMaxGb; } public Integer getMbVgaSyp() { return mbVgaSyp; } public void setMbVgaSyp(Integer mbVgaSyp) { this.mbVgaSyp = mbVgaSyp; } public Integer getMbFabricator() { return mbFabricator; } public void setMbFabricator(Integer mbFabricator) { this.mbFabricator = mbFabricator; } private Integer mbFabricator; }
package com.javatutorial.leapyearcalculator; public class Main { public static void main(String[] args) { System.out.println(LeapYear.isLeapYear(-1600)); System.out.println(LeapYear.isLeapYear(1600)); System.out.println(LeapYear.isLeapYear(2017)); System.out.println(LeapYear.isLeapYear(2000)); // The following years are not leap years: // 1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600 // This is because they are evenly divisible by 100 but not by 400 System.out.println("The following years are not leap years:"); System.out.println(LeapYear.isLeapYear(1700)); System.out.println(LeapYear.isLeapYear(1900)); System.out.println(LeapYear.isLeapYear(2100)); System.out.println(LeapYear.isLeapYear(2200)); System.out.println(LeapYear.isLeapYear(2300)); System.out.println(LeapYear.isLeapYear(2500)); System.out.println(LeapYear.isLeapYear(2600)); /* The following years are leap years: 1600, 2000, 2400 This is because they are evenly divisible by both 100 and 400. */ System.out.println("The following years are leap years:"); System.out.println(LeapYear.isLeapYear(1924)); System.out.println(LeapYear.isLeapYear(2000)); System.out.println(LeapYear.isLeapYear(2400)); System.out.println(LeapYear.isLeapYear(2020)); System.out.println(LeapYear.isLeapYear(1800)); } }
package com.springapp.repositories; import org.springframework.stereotype.Component; import javax.persistence.*; /** * Created by michal.matlosz on 28.09.2014. */ @Component @Entity @Table(name = "SSC") public class StartStopContinue { @Id @GeneratedValue private Long id; private String start; private String stop; private String continuee; @Transient private String register; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStart() { return start; } public void setStart(String start) { this.start = start; } public String getStop() { return stop; } public void setStop(String stop) { this.stop = stop; } public String getContinuee() { return continuee; } public void setContinuee(String continuee) { this.continuee = continuee; } public String getRegister() { return register; } public void setRegister(String register) { this.register = register; } }
/* * 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 onlineBillingSystem; import java.awt.Color; /** * * @author Abd_2 */ public class OnlineBillingSystem extends javax.swing.JFrame { boolean dotCount = false; double firstnum; double secondnum; double result; String operation = "+"; String answer; double labour = 40; double travel = 3; double plastic = 5.5; double copper = 8.5; double chrome = 10; double iron = 220; double steal = 90; /** * Creates new form OnlineBillingSystem */ public OnlineBillingSystem() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); TAcalculator = new javax.swing.JTextField(); B7 = new javax.swing.JButton(); B0 = new javax.swing.JButton(); B4 = new javax.swing.JButton(); B1 = new javax.swing.JButton(); B8 = new javax.swing.JButton(); B9 = new javax.swing.JButton(); Bmult = new javax.swing.JButton(); Bsub = new javax.swing.JButton(); B6 = new javax.swing.JButton(); B5 = new javax.swing.JButton(); B2 = new javax.swing.JButton(); Bdot = new javax.swing.JButton(); B3 = new javax.swing.JButton(); Badd = new javax.swing.JButton(); Bequal = new javax.swing.JButton(); Bcls = new javax.swing.JButton(); Bmod = new javax.swing.JButton(); Bdiv = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); TAplastic = new javax.swing.JTextField(); TAcopper = new javax.swing.JTextField(); TAchrome = new javax.swing.JTextField(); ChBlabour = new javax.swing.JCheckBox(); ChBtravel = new javax.swing.JCheckBox(); ChBplastic = new javax.swing.JCheckBox(); ChBcopper = new javax.swing.JCheckBox(); ChBchrome = new javax.swing.JCheckBox(); TAlabour = new javax.swing.JTextField(); TAtravel = new javax.swing.JTextField(); ChBiron = new javax.swing.JCheckBox(); ChBstreal = new javax.swing.JCheckBox(); TAiron = new javax.swing.JTextField(); TAsteal = new javax.swing.JTextField(); jPanel4 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); CHBTax = new javax.swing.JCheckBox(); ChBVAT = new javax.swing.JCheckBox(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); TAitems = new javax.swing.JTextField(); TAdelivery = new javax.swing.JTextField(); TAmileage = new javax.swing.JTextField(); TATaxcheckBox = new javax.swing.JTextField(); TAVAT = new javax.swing.JTextField(); jPanel5 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); TASubTotal = new javax.swing.JTextField(); TATAX = new javax.swing.JTextField(); TATotalAmount = new javax.swing.JTextField(); Bclear = new javax.swing.JButton(); Breset = new javax.swing.JButton(); Bcaculate = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Online Billing System", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 2, 36), new java.awt.Color(0, 51, 51))); // NOI18N jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("")); TAcalculator.setEditable(false); TAcalculator.setForeground(new java.awt.Color(204, 204, 204)); TAcalculator.setText("0"); B7.setText("7"); B7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B7ActionPerformed(evt); } }); B0.setText("0"); B0.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B0ActionPerformed(evt); } }); B4.setText("4"); B4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B4ActionPerformed(evt); } }); B1.setText("1"); B1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B1ActionPerformed(evt); } }); B8.setText("8"); B8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B8ActionPerformed(evt); } }); B9.setText("9"); B9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B9ActionPerformed(evt); } }); Bmult.setText("*"); Bmult.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BmultActionPerformed(evt); } }); Bsub.setText("-"); Bsub.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BsubActionPerformed(evt); } }); B6.setText("6"); B6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B6ActionPerformed(evt); } }); B5.setText("5"); B5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B5ActionPerformed(evt); } }); B2.setText("2"); B2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B2ActionPerformed(evt); } }); Bdot.setText("."); Bdot.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BdotActionPerformed(evt); } }); B3.setText("3"); B3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { B3ActionPerformed(evt); } }); Badd.setText("+"); Badd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BaddActionPerformed(evt); } }); Bequal.setText("="); Bequal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BequalActionPerformed(evt); } }); Bcls.setText("C"); Bcls.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BclsActionPerformed(evt); } }); Bmod.setText("%"); Bmod.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BmodActionPerformed(evt); } }); Bdiv.setText("/"); Bdiv.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BdivActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(TAcalculator) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Bcls, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(B7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B0, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Bmod, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Bdot, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(B6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Badd, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(Bdiv, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Bmult, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(B9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Bsub, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(Bequal, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(TAcalculator, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Bcls, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Bmod, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Bdiv, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Bmult, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(B7, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Bsub, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B9, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B8, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(B4, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B5, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B6, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(B1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(B3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(B0, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Bdot, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Bequal, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(Badd, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("")); ChBlabour.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N ChBlabour.setText("Labour"); ChBtravel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N ChBtravel.setText("Travel"); ChBplastic.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N ChBplastic.setText("Plastic"); ChBcopper.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N ChBcopper.setText("Copper"); ChBchrome.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N ChBchrome.setText("Chrome"); ChBiron.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N ChBiron.setText("Iron"); ChBstreal.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N ChBstreal.setText("Steal"); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setText("Total Cost of Mileage"); CHBTax.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N CHBTax.setText("Tax"); ChBVAT.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N ChBVAT.setText("VAT"); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setText("Total Cost of Items"); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setText("Total Cost of Delivery"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(CHBTax, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ChBVAT, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TATaxcheckBox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAVAT, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(49, 49, 49) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TAdelivery, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAitems, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAmileage, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(TAitems, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(TAdelivery, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAmileage, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(CHBTax, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TATaxcheckBox, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChBVAT, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAVAT, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(ChBchrome, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ChBiron, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ChBstreal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ChBtravel, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ChBlabour, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ChBcopper, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(ChBplastic, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(36, 36, 36) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TAtravel, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAlabour, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAplastic, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAcopper, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAchrome, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAiron, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAsteal, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(84, 84, 84)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChBlabour, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TAlabour, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChBtravel) .addComponent(TAtravel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChBplastic) .addComponent(TAplastic, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChBcopper) .addComponent(TAcopper, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChBchrome) .addComponent(TAchrome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChBiron) .addComponent(TAiron, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChBstreal) .addComponent(TAsteal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Calculations", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 18), new java.awt.Color(204, 204, 204))); // NOI18N jLabel4.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel4.setText("Sub Total"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel5.setText("Total Amount"); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel6.setText("TAX"); Bclear.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Bclear.setText("Clear"); Bclear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BclearActionPerformed(evt); } }); Breset.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Breset.setText("Reaset"); Breset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BresetActionPerformed(evt); } }); Bcaculate.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Bcaculate.setText("Calculate"); Bcaculate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BcaculateActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(117, 117, 117) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(TASubTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TATAX, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(TATotalAmount, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(71, 71, 71) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Breset, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Bclear, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Bcaculate, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(5, 5, 5) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(TASubTotal) .addComponent(Bclear)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(5, 5, 5) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(TATAX) .addComponent(Breset)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(5, 5, 5) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(TATotalAmount) .addComponent(Bcaculate)))) .addContainerGap()) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 559, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(13, 13, 13) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void B1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B1ActionPerformed TAcalculator.setForeground(Color.black); if (TAcalculator.getText().equals("0")) { TAcalculator.setText(""); } String enterValue = TAcalculator.getText() + B1.getText(); TAcalculator.setText(enterValue); }//GEN-LAST:event_B1ActionPerformed private void B2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B2ActionPerformed TAcalculator.setForeground(Color.black); if (TAcalculator.getText().equals("0")) { TAcalculator.setText(""); } String enterValue = TAcalculator.getText() + B2.getText(); TAcalculator.setText(enterValue); }//GEN-LAST:event_B2ActionPerformed private void B3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B3ActionPerformed TAcalculator.setForeground(Color.black); if (TAcalculator.getText().equals("0")) { TAcalculator.setText(""); } String enterValue = TAcalculator.getText() + B3.getText(); TAcalculator.setText(enterValue); }//GEN-LAST:event_B3ActionPerformed private void B4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B4ActionPerformed TAcalculator.setForeground(Color.black); if (TAcalculator.getText().equals("0")) { TAcalculator.setText(""); } String enterValue = TAcalculator.getText() + B4.getText(); TAcalculator.setText(enterValue); }//GEN-LAST:event_B4ActionPerformed private void B5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B5ActionPerformed TAcalculator.setForeground(Color.black); if (TAcalculator.getText().equals("0")) { TAcalculator.setText(""); } String enterValue = TAcalculator.getText() + B5.getText(); TAcalculator.setText(enterValue); }//GEN-LAST:event_B5ActionPerformed private void B6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B6ActionPerformed TAcalculator.setForeground(Color.black); if(TAcalculator.getText().equals("0")){ TAcalculator.setText(""); } String enterValue = TAcalculator.getText() + B6.getText(); TAcalculator.setText(enterValue); }//GEN-LAST:event_B6ActionPerformed private void B7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B7ActionPerformed TAcalculator.setForeground(Color.black); if(TAcalculator.getText().equals("0")){ TAcalculator.setText(""); } String enterValue = TAcalculator.getText() + B7.getText(); TAcalculator.setText(enterValue); }//GEN-LAST:event_B7ActionPerformed private void B8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B8ActionPerformed TAcalculator.setForeground(Color.black); if(TAcalculator.getText().equals("0")){ TAcalculator.setText(""); } String enterValue = TAcalculator.getText() + B8.getText(); TAcalculator.setText(enterValue); }//GEN-LAST:event_B8ActionPerformed private void B9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B9ActionPerformed TAcalculator.setForeground(Color.black); if(TAcalculator.getText().equals("0")){ TAcalculator.setText(""); } String enterValue = TAcalculator.getText() + B9.getText(); TAcalculator.setText(enterValue); }//GEN-LAST:event_B9ActionPerformed private void B0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B0ActionPerformed TAcalculator.setForeground(Color.black); if (TAcalculator.getText().equals("") || TAcalculator.getText().equals("0")) { TAcalculator.setText("0"); } else { String enterValue = TAcalculator.getText() + B0.getText(); TAcalculator.setText(enterValue); } }//GEN-LAST:event_B0ActionPerformed private void BdotActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BdotActionPerformed TAcalculator.setForeground(Color.black); if (!dotCount) { if (TAcalculator.getText().equals("")) { TAcalculator.setText("0"); } String enterValue = TAcalculator.getText() + Bdot.getText(); TAcalculator.setText(enterValue); dotCount = true; } }//GEN-LAST:event_BdotActionPerformed private void BclsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BclsActionPerformed TAcalculator.setText("0"); TAcalculator.setForeground(Color.GRAY); dotCount = false; }//GEN-LAST:event_BclsActionPerformed private void BmodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BmodActionPerformed firstnum = Double.parseDouble(TAcalculator.getText()); operation = "%"; TAcalculator.setText(""); }//GEN-LAST:event_BmodActionPerformed private void BdivActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BdivActionPerformed firstnum = Double.parseDouble(TAcalculator.getText()); operation = "/"; TAcalculator.setText(""); }//GEN-LAST:event_BdivActionPerformed private void BmultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BmultActionPerformed firstnum = Double.parseDouble(TAcalculator.getText()); operation = "*"; TAcalculator.setText(""); }//GEN-LAST:event_BmultActionPerformed private void BsubActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BsubActionPerformed firstnum = Double.parseDouble(TAcalculator.getText()); operation = "-"; TAcalculator.setText(""); }//GEN-LAST:event_BsubActionPerformed private void BaddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BaddActionPerformed firstnum = Double.parseDouble(TAcalculator.getText()); operation = "+"; TAcalculator.setText(""); }//GEN-LAST:event_BaddActionPerformed private void BequalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BequalActionPerformed if (TAcalculator.getText().equals("")) { } else { secondnum = Double.parseDouble(TAcalculator.getText()); switch (operation) { case "%": result = firstnum % secondnum; break; case "/": result = firstnum / secondnum; break; case "*": result = firstnum * secondnum; break; case "-": result = firstnum - secondnum; break; case "+": result = firstnum + secondnum; break; default: result = firstnum; } firstnum = result; answer = String.format("%.0f", result); TAcalculator.setText(answer); dotCount = false; } }//GEN-LAST:event_BequalActionPerformed private void BclearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BclearActionPerformed TASubTotal.setText(""); TATAX.setText(""); TATaxcheckBox.setText(""); TATotalAmount.setText(""); TAVAT.setText(""); TAcalculator.setText(""); TAchrome.setText(""); TAcopper.setText(""); TAlabour.setText(""); TAdelivery.setText(""); TAitems.setText(""); TAmileage.setText(""); TAplastic.setText(""); TAiron.setText(""); TAsteal.setText(""); TAtravel.setText(""); }//GEN-LAST:event_BclearActionPerformed private void BcaculateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BcaculateActionPerformed try { double l; double t; double p = Double.parseDouble(TAplastic.getText()); double c = Double.parseDouble(TAcopper.getText()); double ch = Double.parseDouble(TAcopper.getText()); double ir = Double.parseDouble(TAiron.getText()); double st = Double.parseDouble(TAsteal.getText()); double r, v, i, m, x, total; r = v = i = m = x = total = 0.0; if (!CHBTax.isSelected() && !ChBVAT.isSelected()) { TASubTotal.setText(""); TATAX.setText(""); TATaxcheckBox.setText(""); TATotalAmount.setText(""); TAVAT.setText(""); TAcalculator.setText(""); TAchrome.setText(""); TAcopper.setText(""); TAlabour.setText(""); TAdelivery.setText(""); TAitems.setText(""); TAmileage.setText(""); TAplastic.setText(""); TAiron.setText(""); TAsteal.setText(""); TAtravel.setText(""); } if (ChBlabour.isSelected()) { if (!TAlabour.getText().isEmpty()) { l = Double.parseDouble(TAlabour.getText()); r += (l * labour); v += r * 0.05; x += r * 0.15; m += r * 0.10; i += r * 0.01; total += l; } } if (ChBtravel.isSelected()) { if (!TAtravel.getText().isEmpty()) { t = Double.parseDouble(TAtravel.getText()); r += (t * travel); v += r * 0.05; x += r * 0.15; m += r * 0.10; i += r * 0.01; total += t; } } if (ChBplastic.isSelected()) { if (!TAplastic.getText().isEmpty()) { p = Double.parseDouble(TAplastic.getText()); r += (p * plastic); v += r * 0.05; x += r * 0.15; m += r * 0.10; i += r * 0.01; total += p; } } if (ChBcopper.isSelected()) { if (!TAcopper.getText().isEmpty()) { c = Double.parseDouble(TAcopper.getText()); r += (c * copper); v += r * 0.05; x += r * 0.15; m += r * 0.10; i += r * 0.01; total += c; } } if (ChBchrome.isSelected()) { if (!TAchrome.getText().isEmpty()) { ch = Double.parseDouble(TAchrome.getText()); r += (ch * chrome); v += r * 0.05; x += r * 0.15; m += r * 0.10; i += r * 0.01; total += ch; } } if (ChBiron.isSelected()) { if (!TAiron.getText().isEmpty()) { ir = Double.parseDouble(TAiron.getText()); r += (ir * iron); v += r * 0.05; x += r * 0.15; m += r * 0.10; i += r * 0.01; total += ir; } } if (ChBstreal.isSelected()) { if (!TAsteal.getText().isEmpty()) { st = Double.parseDouble(TAsteal.getText()); r += (st * steal); v += r * 0.05; x += r * 0.15; m += r * 0.10; i += r * 0.01; total += st; } } if (total != 0.0) { String temp = String.format("%.0f", r); TAitems.setText(temp); temp = String.format("%.0f", i); TAdelivery.setText(temp); temp = String.format("%.0f", m); TAmileage.setText(temp); temp = String.format("%.0f", x); TATaxcheckBox.setText(temp); temp = String.format("%.0f", v); TAVAT.setText(temp); double subT = r + i + m; double taxT = v + x; temp = String.format("%.0f", subT); TASubTotal.setText(temp); temp = String.format("%.0f", taxT); TATAX.setText(temp); temp = String.format("%.0f", total); TATotalAmount.setText(temp); } else { } } catch (Exception e) { } }//GEN-LAST:event_BcaculateActionPerformed private void BresetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BresetActionPerformed TASubTotal.setText(""); TATAX.setText(""); TATaxcheckBox.setText(""); TATotalAmount.setText(""); TAVAT.setText(""); TAcalculator.setText(""); TAchrome.setText(""); TAcopper.setText(""); TAlabour.setText(""); TAdelivery.setText(""); TAitems.setText(""); TAmileage.setText(""); TAplastic.setText(""); TAiron.setText(""); TAsteal.setText(""); TAtravel.setText(""); }//GEN-LAST:event_BresetActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(OnlineBillingSystem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(OnlineBillingSystem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(OnlineBillingSystem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(OnlineBillingSystem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new OnlineBillingSystem().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton B0; private javax.swing.JButton B1; private javax.swing.JButton B2; private javax.swing.JButton B3; private javax.swing.JButton B4; private javax.swing.JButton B5; private javax.swing.JButton B6; private javax.swing.JButton B7; private javax.swing.JButton B8; private javax.swing.JButton B9; private javax.swing.JButton Badd; private javax.swing.JButton Bcaculate; private javax.swing.JButton Bclear; private javax.swing.JButton Bcls; private javax.swing.JButton Bdiv; private javax.swing.JButton Bdot; private javax.swing.JButton Bequal; private javax.swing.JButton Bmod; private javax.swing.JButton Bmult; private javax.swing.JButton Breset; private javax.swing.JButton Bsub; private javax.swing.JCheckBox CHBTax; private javax.swing.JCheckBox ChBVAT; private javax.swing.JCheckBox ChBchrome; private javax.swing.JCheckBox ChBcopper; private javax.swing.JCheckBox ChBiron; private javax.swing.JCheckBox ChBlabour; private javax.swing.JCheckBox ChBplastic; private javax.swing.JCheckBox ChBstreal; private javax.swing.JCheckBox ChBtravel; private javax.swing.JTextField TASubTotal; private javax.swing.JTextField TATAX; private javax.swing.JTextField TATaxcheckBox; private javax.swing.JTextField TATotalAmount; private javax.swing.JTextField TAVAT; private javax.swing.JTextField TAcalculator; private javax.swing.JTextField TAchrome; private javax.swing.JTextField TAcopper; private javax.swing.JTextField TAdelivery; private javax.swing.JTextField TAiron; private javax.swing.JTextField TAitems; private javax.swing.JTextField TAlabour; private javax.swing.JTextField TAmileage; private javax.swing.JTextField TAplastic; private javax.swing.JTextField TAsteal; private javax.swing.JTextField TAtravel; private javax.swing.JLabel jLabel1; 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.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; // End of variables declaration//GEN-END:variables }
/** * Created by qiaoruixiang on 15/05/2017. */ public interface PreroutingStrategy { }
package com.gxtc.huchuan.ui.mine.deal.fastList; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.view.View; import android.widget.LinearLayout; import com.gxtc.commlibrary.base.BaseRecyclerAdapter; import com.gxtc.commlibrary.base.BaseTitleActivity; import com.gxtc.commlibrary.recyclerview.RecyclerView; import com.gxtc.commlibrary.recyclerview.wrapper.LoadMoreWrapper; import com.gxtc.commlibrary.utils.EventBusUtil; import com.gxtc.commlibrary.utils.GotoUtil; import com.gxtc.commlibrary.utils.ToastUtil; import com.gxtc.huchuan.Constant; import com.gxtc.huchuan.R; import com.gxtc.huchuan.adapter.FastListAdapter; import com.gxtc.huchuan.bean.PurchaseListBean; import com.gxtc.huchuan.bean.event.EventClickBean; import com.gxtc.huchuan.dialog.VertifanceFlowDialog; import com.gxtc.huchuan.ui.deal.guarantee.GuaranteeDetailedActivity; import com.gxtc.huchuan.ui.mine.deal.issueList.IssueListContract; import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity; import com.gxtc.huchuan.utils.CheaekUtil; import com.gxtc.huchuan.utils.DialogUtil; import org.greenrobot.eventbus.Subscribe; import java.util.List; import butterknife.BindView; /** * 快速交易页面 * 苏修伟 */ public class FastListActivity extends BaseTitleActivity implements IssueListContract.View, View.OnClickListener { @BindView(R.id.swipelayout) SwipeRefreshLayout refreshLayout; @BindView(R.id.recyclerView) RecyclerView listView; private IssueListContract.Presenter mPresenter; private FastListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_purchase_list); EventBusUtil.register(this); } @Override public void initView() { getBaseHeadView().showTitle(getString(R.string.title_fast_list)); getBaseHeadView().showBackButton(this); // getBaseHeadView().showHeadRightImageButton(R.drawable.person_release_dynamic_icon_add,this); refreshLayout.setColorSchemeResources(Constant.REFRESH_COLOR); listView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL,false)); listView.setLoadMoreView(R.layout.model_footview_loadmore); } @Override public void initListener() { refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { listView.reLoadFinish(); mPresenter.getData(true); } }); listView.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() { @Override public void onLoadMoreRequested() { mPresenter.loadMrore(); } }); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.headBackButton: finish(); break; // case R.id.HeadRightImageButton: // Intent intent = new Intent(this, ApplyGuaranteeActivity.class); // startActivity(intent); // break; } } @Subscribe public void onEvent(EventClickBean bean){ } @Override public void initData() { new FastListPresenter(this); mPresenter.getData(false); } @Override public void tokenOverdue() { GotoUtil.goToActivity(this, LoginAndRegisteActivity.class); } @Override public void showData(List<PurchaseListBean> datas) { adapter = new FastListAdapter(this,datas,R.layout.item_list_fast); listView.setAdapter(adapter); adapter.setOnReItemOnClickListener(new BaseRecyclerAdapter.OnReItemOnClickListener() { @Override public void onItemClick(View v, int position) { GuaranteeDetailedActivity.startActivity(FastListActivity.this, adapter.getList().get(position).getId() + ""); } }); adapter.setOnReItemOnLongClickListener(new BaseRecyclerAdapter.OnReItemOnLongClickListener() { @Override public void onItemLongClick(View v, int position) { showDeletDialog(position); } }); } VertifanceFlowDialog mVertifanceFlowDialog; //删除 private int position; private AlertDialog deleteDialog; private void showDeletDialog(final int position) { this.position = position; if(deleteDialog == null){ deleteDialog = DialogUtil.showInputDialog(this, false, "", "确认删除这条交易记录?", new View.OnClickListener() { @Override public void onClick(View v) { mPresenter.deleteDeal(adapter.getList().get(FastListActivity.this.position).getId()); deleteDialog.dismiss(); } }); }else{ deleteDialog.show(); } } @Override public void showRefreshFinish(List<PurchaseListBean> datas) { if(adapter != null){ listView.notifyChangeData(datas,adapter); } } @Override public void showLoadMore(List<PurchaseListBean> datas) { listView.changeData(datas,adapter); } @Override public void showNoMore() { listView.loadFinish(); } @Override public void showDeleteSuccess(int id) { for (int i = 0; i < adapter.getList().size(); i++) { if(id == adapter.getList().get(i).getId()){ listView.removeData(adapter,i); } } } @Override public void showLoad() { getBaseLoadingView().showLoading(); } @Override public void showLoadFinish() { refreshLayout.setRefreshing(false); getBaseLoadingView().hideLoading(); } @Override public void showEmpty() { if(adapter == null){ getBaseEmptyView().showEmptyContent(); } } @Override public void showReLoad() {} @Override public void showError(String info) { if(adapter == null){ getBaseEmptyView().showEmptyContent(info); }else{ ToastUtil.showShort(this,info); } } @Override public void showNetError() { getBaseEmptyView().showNetWorkView(new View.OnClickListener() { @Override public void onClick(View v) { mPresenter.getData(false); getBaseEmptyView().hideEmptyView(); } }); } @Override public void setPresenter(IssueListContract.Presenter presenter) { mPresenter = presenter; } @Override protected void onDestroy() { super.onDestroy(); EventBusUtil.unregister(this); if(mVertifanceFlowDialog != null){ CheaekUtil.getInstance().cancelTask(this); mVertifanceFlowDialog = null; } mPresenter.destroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } }
package view; import controller.ControllerUsuarios; import controller.ControllerVendasProdutos; import java.awt.Image; import java.awt.Toolkit; import java.net.URL; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.RowFilter; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import model.ModelUsuarios; public class ViewUsuarioFormListaUsuarios extends javax.swing.JFrame { ViewUsuarioFormCadastro viewUsuarioFormCadastro = new ViewUsuarioFormCadastro(); ControllerUsuarios controllerUsuarios = new ControllerUsuarios(); ModelUsuarios modelUsuarios = new ModelUsuarios(); ArrayList<ModelUsuarios> listaModelUsuarios = new ArrayList<>(); ControllerVendasProdutos controllerVendasProdutos = new ControllerVendasProdutos(); public ViewUsuarioFormListaUsuarios() { initComponents(); carregarUsuarios(); setLocationRelativeTo(null); // Seta o ícone da aplicação URL url = this.getClass().getResource("/imagens/marca/appicon.png"); Image imagemTitulo = Toolkit.getDefaultToolkit().getImage(url); this.setIconImage(imagemTitulo); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jtfPesquisar = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jtUsuarios = new javax.swing.JTable(); jPanel3 = new javax.swing.JPanel(); jbAlterar = new javax.swing.JButton(); jbExcluir = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jbCadastroUsuario = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Usuários"); jPanel1.setBackground(new java.awt.Color(251, 245, 95)); jLabel4.setBackground(new java.awt.Color(255, 255, 255)); jLabel4.setFont(new java.awt.Font("Consolas", 0, 18)); // NOI18N jLabel4.setText("Lista de Usuários"); jLabel5.setFont(new java.awt.Font("Consolas", 0, 14)); // NOI18N jLabel5.setText("Pesquisa"); jtfPesquisar.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jtfPesquisar.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jtfPesquisarKeyTyped(evt); } }); jtUsuarios.getTableHeader().setFont(new java.awt.Font("Consolas", 0, 14)); jtUsuarios.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N jtUsuarios.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Código", "Nome", "Email" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jtUsuarios.setSelectionBackground(new java.awt.Color(251, 245, 95)); jtUsuarios.setSelectionForeground(new java.awt.Color(0, 0, 0)); jScrollPane1.setViewportView(jtUsuarios); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtfPesquisar) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5)) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 524, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(32, 32, 32) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtfPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(30, Short.MAX_VALUE)) ); jPanel3.setBackground(new java.awt.Color(0, 0, 0)); jbAlterar.setBackground(new java.awt.Color(255, 255, 255)); jbAlterar.setFont(new java.awt.Font("Consolas", 1, 12)); // NOI18N jbAlterar.setForeground(new java.awt.Color(251, 245, 95)); jbAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/ícones/edit.png"))); // NOI18N jbAlterar.setText("ALTERAR"); jbAlterar.setBorder(null); jbAlterar.setContentAreaFilled(false); jbAlterar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jbAlterar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jbAlterarMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jbAlterarMouseExited(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { jbAlterarMouseReleased(evt); } }); jbAlterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAlterarActionPerformed(evt); } }); jbExcluir.setFont(new java.awt.Font("Consolas", 1, 12)); // NOI18N jbExcluir.setForeground(new java.awt.Color(251, 245, 95)); jbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/ícones/delete.png"))); // NOI18N jbExcluir.setText("EXCLUIR"); jbExcluir.setBorder(null); jbExcluir.setContentAreaFilled(false); jbExcluir.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jbExcluir.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jbExcluirMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jbExcluirMouseExited(evt); } }); jbExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbExcluirActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(251, 245, 95)); jLabel3.setText("|"); jbCadastroUsuario.setFont(new java.awt.Font("Consolas", 1, 12)); // NOI18N jbCadastroUsuario.setForeground(new java.awt.Color(251, 245, 95)); jbCadastroUsuario.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/ícones/cad.png"))); // NOI18N jbCadastroUsuario.setText("CADASTRO DE USUÁRIOS"); jbCadastroUsuario.setBorder(null); jbCadastroUsuario.setContentAreaFilled(false); jbCadastroUsuario.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jbCadastroUsuario.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jbCadastroUsuarioMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jbCadastroUsuarioMouseExited(evt); } }); jbCadastroUsuario.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbCadastroUsuarioActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jbCadastroUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addComponent(jbAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jbExcluir, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbCadastroUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbAlterar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 43, 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) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jbAlterarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbAlterarMouseEntered jbAlterar.setFont(new java.awt.Font("Consolas", 0, 14)); }//GEN-LAST:event_jbAlterarMouseEntered private void jbAlterarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbAlterarMouseExited jbAlterar.setFont(new java.awt.Font("Consolas", 0, 12)); }//GEN-LAST:event_jbAlterarMouseExited private void jbAlterarMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbAlterarMouseReleased }//GEN-LAST:event_jbAlterarMouseReleased private void jbAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAlterarActionPerformed try { viewUsuarioFormCadastro = new ViewUsuarioFormCadastro(); // Pega a linha int linha = jtUsuarios.getSelectedRow(); // Pega a coluna (códgio) int codigoUsuario = (int) jtUsuarios.getValueAt(linha, 0); // Recupera dados do banco a partir do código modelUsuarios = controllerUsuarios.getUsuariosController(codigoUsuario); // Fecha esta tela this.dispose(); viewUsuarioFormCadastro.habilitarBotaoSalvar(); viewUsuarioFormCadastro.setVisible(true); viewUsuarioFormCadastro.habilitarCampos(true); viewUsuarioFormCadastro.setState(ViewUsuarioFormCadastro.NORMAL); // Preenche os campos viewUsuarioFormCadastro.setCampos(modelUsuarios); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Código inválido ou nenhum registro selecionado"); } }//GEN-LAST:event_jbAlterarActionPerformed private void jbExcluirMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbExcluirMouseEntered jbExcluir.setFont(new java.awt.Font("Consolas", 0, 14)); }//GEN-LAST:event_jbExcluirMouseEntered private void jbExcluirMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbExcluirMouseExited jbExcluir.setFont(new java.awt.Font("Consolas", 0, 12)); }//GEN-LAST:event_jbExcluirMouseExited private void jbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbExcluirActionPerformed // Pega a linha int linha = jtUsuarios.getSelectedRow(); // Pega a coluna (códgio) int codigoUsuario = (int) jtUsuarios.getValueAt(linha, 0); // Exclui o usuário if (controllerUsuarios.excluirUsuariosController(codigoUsuario)) { JOptionPane.showMessageDialog(this, "Usuario excluído com sucesso", "Pronto!", JOptionPane.WARNING_MESSAGE); this.carregarUsuarios(); } else { JOptionPane.showMessageDialog(this, "Não foi possível excluir o cliente", "Erro", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jbExcluirActionPerformed private void jbCadastroUsuarioMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbCadastroUsuarioMouseEntered jbCadastroUsuario.setFont(new java.awt.Font("Consolas", 0, 14)); }//GEN-LAST:event_jbCadastroUsuarioMouseEntered private void jbCadastroUsuarioMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jbCadastroUsuarioMouseExited jbCadastroUsuario.setFont(new java.awt.Font("Consolas", 0, 12)); }//GEN-LAST:event_jbCadastroUsuarioMouseExited private void jbCadastroUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCadastroUsuarioActionPerformed new ViewUsuarioFormCadastro().setVisible(true); this.dispose(); }//GEN-LAST:event_jbCadastroUsuarioActionPerformed private void jtfPesquisarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfPesquisarKeyTyped DefaultTableModel modelo = (DefaultTableModel) this.jtUsuarios.getModel(); final TableRowSorter<TableModel> classificador = new TableRowSorter<>(modelo); this.jtUsuarios.setRowSorter(classificador); String texto = jtfPesquisar.getText().toUpperCase();; classificador.setRowFilter(RowFilter.regexFilter(texto, 1)); }//GEN-LAST:event_jtfPesquisarKeyTyped /** * Carregar usuários na tabela */ private void carregarUsuarios() { listaModelUsuarios = controllerUsuarios.getListaUsuariosController(); DefaultTableModel modelo = (DefaultTableModel) jtUsuarios.getModel(); modelo.setNumRows(0); int cont = listaModelUsuarios.size(); for (int i = 0; i < cont; i++) { modelo.addRow(new Object[]{ listaModelUsuarios.get(i).getUsuarioId(), listaModelUsuarios.get(i).getUsuarioNome(), listaModelUsuarios.get(i).getUsuarioEmail() }); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewUsuarioFormListaUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewUsuarioFormListaUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewUsuarioFormListaUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewUsuarioFormListaUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewUsuarioFormListaUsuarios().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton jbAlterar; private javax.swing.JButton jbCadastroUsuario; private javax.swing.JButton jbExcluir; private javax.swing.JTable jtUsuarios; private javax.swing.JTextField jtfPesquisar; // End of variables declaration//GEN-END:variables }
package me.anmt.demo4j.netty; public class Demo1 { }
package com.j1902.shopping.controller; import com.j1902.shopping.pojo.User; import com.j1902.shopping.service.UserService; import com.j1902.shopping.utils.JsonUtils; 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.ResponseBody; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller public class LoginController { @Autowired private UserService userService; //前端登录 @RequestMapping("/frontLogin") public String login(HttpServletRequest request, Map<String, Object> map, HttpServletResponse response) throws UnsupportedEncodingException { Cookie[] cookies = request.getCookies(); User cookUser = null; if (cookies != null && cookies.length > 0) { for (Cookie c : cookies) { if ("REMEMBER_PASSWORD".equals(c.getName())) { String userJson = c.getValue(); userJson = URLDecoder.decode(userJson, "UTF-8"); cookUser = JsonUtils.jsonToPojo(userJson, User.class); map.put("phone", cookUser.getUserPhone()); map.put("password", cookUser.getUserPwd()); } if ("addCookie".equals(c.getName())) { userService.deleteCookie(request, response); return "front/login"; } } } return "front/login"; } //记住密码勾选框 @RequestMapping("/log") @ResponseBody public Map<String, Object> log(HttpServletRequest request) { Map<String, Object> map = new HashMap<>(); Cookie[] cookies = request.getCookies(); User cookUser = null; if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if ("REMEMBER_PASSWORD".equals(cookie.getName())) { map.put("is", 1); return map; } else if ("addCookie".equals(cookie.getName())) { map.put("is", 1); return map; } } } return null; } @RequestMapping("/logins") public String login(User user, HttpServletRequest request, HttpServletResponse response, Map<String, Object> map, HttpSession session) throws UnsupportedEncodingException { String userphone = request.getParameter("userphone"); String rememberPassword = request.getParameter("rememberPassword"); System.out.println("rememberPassword = " + rememberPassword); System.out.println("user = " + user.toString()); if (userService.login(user)) { if ("true".equals(rememberPassword)) { userService.rememberPwd(user, response); } else { userService.deleteCookie(request, response); } List<User> users = userService.getByPhone(user); if (users.get(0).getUserRealname()!=null){ session.setAttribute("USER_LOGIN",users.get(0)); return "front/member_index"; } session.setAttribute("USER_LOGIN",users.get(0)); return "front/member_info"; } else if ("true".equals(rememberPassword)) { userService.addCookie(user.getUserPhone(), response); map.put("phone", user.getUserPhone()); map.put("loginFail", "用户名与密码不匹配!"); return "front/login"; } map.put("phone", user.getUserPhone()); map.put("loginFail", "用户名与密码不匹配!"); return "front/login"; } }
/******************************************************************************* * Copyright (c) 2012, Eka Heksanov Lie * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the organization nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package com.ehxnv.pvm.io.json; import com.ehxnv.pvm.api.ProcessMetadata; import com.ehxnv.pvm.api.data.DataDefinition; import com.ehxnv.pvm.api.data.DataModel; import com.ehxnv.pvm.api.data.DataType; import org.junit.Test; import java.io.InputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; /** * Unit test for {@link JSONProcessDataModelPopulator}. * * @author Eka Lie */ public class JSONProcessDataModelPopulatorTest { /** * Test of populateProcessInputDataModel method, of class JSONProcessDataModelPopulator. */ @Test public void testPopulateProcessInputDataModel() throws Exception { InputStream inputStream = getClass().getResourceAsStream("model_input.json"); JSONProcess process = new JSONProcess(new ProcessMetadata("test_basic", "1.0")); JSONProcessDataModelPopulator.populateProcessInputDataModel(inputStream, process); DataModel dataModel = process.getInputDataModel(); final Object[][] dataDefDetails = new Object[][] { { "first_name", DataType.STRING }, { "last_name", DataType.STRING }, { "age", DataType.INTEGER }, { "married", DataType.BOOLEAN }, { "salary", DataType.DECIMAL }}; assertEquals(dataDefDetails.length, dataModel.getDataDefinitions().size()); for (Object[] dataDefDetail : dataDefDetails) { boolean matched = false; for (DataDefinition dataDef : dataModel.getDataDefinitions()) { if (dataDef.getDataName().equals(dataDefDetail[0]) && dataDef.getDataType().equals(dataDefDetail[1])) { matched = true; } } if (!matched) { fail(); } } } /** * Test of populateProcessOutputDataModel method, of class JSONProcessDataModelPopulator. */ @Test public void testPopulateProcessOutputDataModel() throws Exception { InputStream inputStream = getClass().getResourceAsStream("model_output.json"); JSONProcess process = new JSONProcess(new ProcessMetadata("test_basic", "1.0")); JSONProcessDataModelPopulator.populateProcessOutputDataModel(inputStream, process); DataModel dataModel = process.getOutputDataModel(); final Object[][] dataDefDetails = new Object[][] { { "first_name", DataType.STRING }, { "last_name", DataType.STRING }, { "age", DataType.INTEGER }, { "married", DataType.BOOLEAN }, { "salary", DataType.DECIMAL }}; assertEquals(dataDefDetails.length, dataModel.getDataDefinitions().size()); for (Object[] dataDefDetail : dataDefDetails) { boolean matched = false; for (DataDefinition dataDef : dataModel.getDataDefinitions()) { if (dataDef.getDataName().equals(dataDefDetail[0]) && dataDef.getDataType().equals(dataDefDetail[1])) { matched = true; } } if (!matched) { fail(); } } } }
package ServerConfig; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class ServerConfigReader { private InputStream inputStream; private int Port; private String FileName; private String DocFolder; private String Folder; private String LogFolder; private String LogPattern; private String LogOutFormat; public ServerConfigReader() throws IOException { try { Properties prop = new Properties(); String propFileName = "config.properties"; inputStream = getClass().getClassLoader().getResourceAsStream(propFileName); if (inputStream != null) { prop.load(inputStream); } else { throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); } String portTemp = prop.getProperty("port"); Port = Integer.parseInt(portTemp); FileName = prop.getProperty("fileName"); DocFolder = prop.getProperty("docFolder"); Folder = prop.getProperty("Folder"); LogFolder = prop.getProperty("logFolder"); LogPattern = prop.getProperty("logPattern"); LogOutFormat = prop.getProperty("logOutFormat"); checkExists(getLogFolder()); } catch (Exception e) { System.out.println("Exception: " + e); } finally { assert inputStream != null; inputStream.close(); } } private void checkExists(File logFolder) { if (!(logFolder.exists())) { if (!(new File(logFolder.getParent()).exists())) if ((new File(logFolder.getParent())).mkdir()) System.out.println("Doc Directory Created"); if (logFolder.mkdir()) System.out.println("Log Directory Created"); } } public File getFile() { return new File(DocFolder + File.separator + getFolder() + File.separator + FileName); } public int getPort() { return Port; } public String getFileName() { return FileName; } public String getFolder() { return Folder; } public File getLogFolder() { return new File(DocFolder + File.separator + LogFolder); } public String getLogPattern() { return LogPattern; } public String getLogOutFormat() { return LogOutFormat; } }
package com.krjani.listener; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import com.krjani.module.GuiceModule; public class GuiceListener extends GuiceServletContextListener { @Override protected Injector getInjector() { return Guice.createInjector(new GuiceModule()); } }
/* * 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 app.action; import com.opensymphony.xwork2.ActionSupport; /** * * @author bruceoutdoors */ public class GenerateAction extends ActionSupport { public String index() { return SUCCESS; } }
package com.infohold.el.base.service.impl; import java.util.Map; import com.infohold.core.exception.BaseException; import com.infohold.core.utils.StringUtils; import com.infohold.el.base.model.Notice; import com.infohold.el.base.service.NoticeService; import com.infohold.el.base.utils.message.MessageUtils; import com.infohold.el.base.utils.notice.NoticeUtils; public class NoticeServiceImpl implements NoticeService { @Override public boolean send(Notice notice){ try { if(null == notice){ throw new BaseException("发送消息失败,notice实例为空!"); } if(StringUtils.isBlank(notice.getMode())){ notice.setMode("1"); //方式,默认为应用提醒 } if(StringUtils.isBlank(notice.getType())){ notice.setType("00"); //业务类型,默认为系统公告 } switch (notice.getMode()) { case "0": sendNotice(notice); sendMessage(notice); break; case "1": sendNotice(notice); case "2": break; case "3": sendMessage(notice); break; case "4": break; case "5": break; case "6": break; case "9": break; default: break; } } catch (Exception e) { e.printStackTrace(); return false; } return true; } private void sendNotice(Notice notice) throws BaseException{ Map<String, String> extraParams = notice.getExtraParams(); String apps = notice.getApps(); String receiverType = notice.getReceiverType(); String receiverValue = notice.getReceiverValue(); String platform = objectToString(extraParams.get("platform")); String notification = objectToString(extraParams.get("notification")); String message = objectToString(extraParams.get("message")); String production = objectToString(extraParams.get("production")); if(StringUtils.isBlank(apps)){ throw new BaseException("发送应用通知错误!未指定APP。"); } if(StringUtils.isBlank(platform)){ platform = "all"; } if(StringUtils.isBlank(notification)){ notification = "all"; } if(StringUtils.isBlank(production)){ production = "true"; } if(StringUtils.isBlank(receiverType) || (!receiverType.equals("0") && !receiverType.equals("1") && !receiverType.equals("2") && !receiverType.equals("3"))){ receiverType = "0"; } extraParams.put("id", notice.getId()); extraParams.put("type", notice.getType()); extraParams.put("target", notice.getTarget()); NoticeUtils.sendNotice(apps, platform, receiverType, receiverValue, notification, message, notice.getTitle(), notice.getContent(), StringUtils.equals("true", production), extraParams); } private void sendMessage(Notice notice){ Map<String, String> extraParams = notice.getExtraParams(); String mobiles = extraParams.get("mobiles"); String type = notice.getType(); if(StringUtils.isBlank(mobiles)){ throw new BaseException("发送短信错误!未指定手机号。"); } MessageUtils.sendMessage(mobiles, type, extraParams); } private static String objectToString(Object obj){ if(obj==null) return ""; return obj.toString(); } }
package edu.zc.oj.entity.response; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author coderplus-tr * @date 2021/3/5 20:33:52 */ @Data @NoArgsConstructor @AllArgsConstructor public class Response { private Integer code; private String message; private Object data; public Response(ResponseCode responseCode){ code = responseCode.getCode(); message = responseCode.getMessage(); } public Response(ResponseCode responseCode, Object data){ code = responseCode.getCode(); message = responseCode.getMessage(); this.data = data; } }
package io.hankki.material.domain.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.querydsl.QueryDslPredicateExecutor; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import com.querydsl.core.types.Predicate; import io.hankki.material.domain.model.Material; import io.hankki.material.domain.model.MaterialCategory; @RepositoryRestResource public interface MaterialRepository extends JpaRepository<Material, Long>, QueryDslPredicateExecutor<Material>{ List<Material> findAll(Predicate predicate); List<Material> findByMaterialCategory(@Param("materialCategory") MaterialCategory materialCategory); List<Material> findByMaterialIdIn(@Param("materialIdList") List<Long> materialIdList); }
/** * Created with IntelliJ IDEA. * User: dogeyes * Date: 13-1-6 * Time: 下午4:22 * To change this template use File | Settings | File Templates. */ public class UniqueSubString { public static void main(String[] args) { String s = StdIn.readString(); MyTST<Object> tst = new MyTST<Object>(); Object mark = new Object(); for(int l = 1; l <= s.length(); ++l) for(int i = 0; i <= s.length() - l; ++i) { tst.put(s.substring(i, i + l), mark); } StdOut.println(tst.keys()); } }
package com.useready.test; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.when; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.useready.code.*; class OurServletTest { @Mock HttpServletRequest request; @Mock HttpServletResponse response; @BeforeEach void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @AfterEach void tearDown() throws Exception { } @Test void testOurServlet() { OurServlet servlet =new OurServlet(); assertTrue(servlet instanceof HttpServlet); } @Test void testDoGetHttpServletRequestHttpServletResponse() throws ServletException, IOException { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); when(response.getWriter()).thenReturn(pw); OurServlet servlet =new OurServlet(); servlet.doGet(request, response); String result = sw.getBuffer().toString().trim(); assertEquals(result, new String("Served always fresh")); } @Test void testDoPostHttpServletRequestHttpServletResponse()throws ServletException, IOException { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); when(response.getWriter()).thenReturn(pw); OurServlet servlet =new OurServlet(); servlet.doPost(request, response); String result = sw.getBuffer().toString().trim(); assertEquals(result, new String("Served always fresh")); } }
package main; import models.ModelMayor3Num; import views.ViewMayor3Num; import controllers.ControllerMayor3Nun; import models.ModelOperaciones; import views.ViewOperaciones; import controllers.ControllerOperaciones; import models.ModelOrdenarAscyProm; import views.ViewOrdenarAscyProm; import controllers.ControllerOrdenarAscyProm; import models.ModelBlocNotas; import views.ViewBlocNotas; import controllers.ControllerBlocNotas; import models.ModelMain; import views.ViewMain; import controllers.ControllerMain; /** * * @author lupita */ public class Main { public static void main(String[] args) { ModelMayor3Num model_mayor3num = new ModelMayor3Num(); ViewMayor3Num view_mayor3num = new ViewMayor3Num(); ControllerMayor3Nun controller_mayor3num = new ControllerMayor3Nun(model_mayor3num,view_mayor3num); ModelOperaciones model_operaciones = new ModelOperaciones(); ViewOperaciones view_operaciones = new ViewOperaciones(); ControllerOperaciones controller_operaciones = new ControllerOperaciones(model_operaciones ,view_operaciones); ModelOrdenarAscyProm model_ordenarascyprom = new ModelOrdenarAscyProm(); ViewOrdenarAscyProm view_ordenarascyprom = new ViewOrdenarAscyProm(); ControllerOrdenarAscyProm controller_ordenarascyprom = new ControllerOrdenarAscyProm(model_ordenarascyprom,view_ordenarascyprom); ModelBlocNotas model_blocnotas = new ModelBlocNotas(); ViewBlocNotas view_blocnotas = new ViewBlocNotas(); ControllerBlocNotas controller_blocnotas= new ControllerBlocNotas(model_blocnotas,view_blocnotas); ModelMain model_main = new ModelMain(); ViewMain view_main = new ViewMain(); Object views[] =new Object [5]; views[0] = view_mayor3num; views[1] = view_operaciones; views[2] = view_ordenarascyprom; views[3] = view_blocnotas; views[4] = view_main; ControllerMain controller_main = new ControllerMain(model_main,views); } }
package com.alex.chess.enums; public enum Color { WHITE, BLACK; public Color opposite() { return this == WHITE ? BLACK : WHITE; } }
package ru.job4j.ui; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.sql.SQLException; import java.text.ParseException; import java.util.GregorianCalendar; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.xml.XmlConfigurationFactory; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; /** * Класс Create реализует функционал создания пользователя. * * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2 * @since 2017-11-09 */ public class Create extends HttpServlet { /** * Логгер. */ private Logger logger; /** * Путь до файла. */ private String path; /** * UserService. */ private UserService us; /** * Инициализатор. */ @Override public void init() throws ServletException { try { // /var/lib/tomcat8/webapps/ch3_ui-1.0/WEB-INF/classes this.path = new File(Create.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath() + "/"; this.path = this.path.replaceFirst("^/(.:/)", "$1"); XmlConfigurationFactory xcf = new XmlConfigurationFactory(); ConfigurationSource source = new ConfigurationSource(new FileInputStream(new File(this.path + "log4j2.xml"))); Configuration conf = xcf.getConfiguration(new LoggerContext("JobsParserTestContext"), source); LoggerContext ctx = (LoggerContext) LogManager.getContext(true); ctx.stop(); ctx.start(conf); this.logger = LogManager.getLogger("Create"); this.us = new UserService(); } catch (URISyntaxException | IOException ex) { this.logger.error("ERROR", ex); } } /** * Обрабатывает GET-запросы. * curl http://bot.net:8080/ch3_ui-1.0/create/ */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); String enc = Charset.defaultCharset().toString(); resp.setCharacterEncoding(enc); PrintWriter writer = new PrintWriter(resp.getOutputStream()); StringBuilder sb = new StringBuilder(); sb.append("<!DOCTYPE html>\n"); sb.append("<html lang='ru' xmlns='http://www.w3.org/1999/xhtml'>\n"); sb.append("<head>\n"); sb.append(" <meta http-equiv='Content-Type' content='text/html; charset=" + enc + "' />\n"); sb.append(" <title>Создание пользователя</title>\n"); sb.append("</head>\n"); sb.append("<body>\n"); sb.append(" <h1>Создание пользователя</h1>\n"); sb.append(" <form method='POST' action='"); sb.append(String.format("%s://%s:%s%s/create/", req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath())); sb.append("'>\n"); sb.append(" <table>\n"); sb.append(" <tr>\n"); sb.append(" <td>\n"); sb.append(" <label>Иия:<br />\n"); sb.append(" <input type='text' name='name' required='required'>\n"); sb.append(" </label>\n"); sb.append(" </td>\n"); sb.append(" </tr>\n"); sb.append(" <tr>\n"); sb.append(" <td>\n"); sb.append(" <label>Логин:<br />\n"); sb.append(" <input type='text' name='login' required='required'>\n"); sb.append(" </label>\n"); sb.append(" </td>\n"); sb.append(" </tr>\n"); sb.append(" <tr>\n"); sb.append(" <td>\n"); sb.append(" <label>Емэил:<br />\n"); sb.append(" <input type='email' name='email' required='required'>\n"); sb.append(" </label>\n"); sb.append(" </td>\n"); sb.append(" </tr>\n"); sb.append(" <tr>\n"); sb.append(" <td>\n"); sb.append(" <input type='submit' value='Создать'>\n"); sb.append(" </td>\n"); sb.append(" </tr>\n"); sb.append(" </table>\n"); sb.append(" <form>\n"); sb.append(String.format("<a href='%s://%s:%s%s/'>Вернуться назад</a>\n", req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath())); sb.append("</body>\n"); writer.append(sb.toString()); writer.flush(); } /** * Обрабатывает POST-запросы. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { resp.setContentType("text/html"); String enc = Charset.defaultCharset().toString(); resp.setCharacterEncoding(enc); PrintWriter writer = new PrintWriter(resp.getOutputStream()); String name = new String(req.getParameter("name").getBytes("ISO-8859-1"), enc); String login = new String(req.getParameter("login").getBytes("ISO-8859-1"), enc); String email = req.getParameter("email"); User user = new User(0, name, login, email, new GregorianCalendar()); StringBuilder sb = new StringBuilder(); sb.append("<!DOCTYPE html>\n"); sb.append("<html lang='ru' xmlns='http://www.w3.org/1999/xhtml'>\n"); sb.append("<head>\n"); sb.append(" <meta http-equiv='Content-Type' content='text/html; charset=" + enc + "' />\n"); sb.append(" <title>Создание пользователя</title>\n"); sb.append("</head>\n"); sb.append("<body>\n"); sb.append(" <h1>Создание пользователя</h1>\n"); if (this.us.addUser(user)) { sb.append(String.format("<p>Пользователь %s добавлен. ID: %s</p><br />\n", name, user.getId())); } else { sb.append(String.format("<p>Ошибка при добавлении пользователя %s.</p><br />\n", name)); } sb.append(String.format("<a href='%s://%s:%s%s/'>Вернуться назад</a>\n", req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath())); sb.append("</body>\n"); writer.append(sb.toString()); writer.flush(); } catch (SQLException | ParseException ex) { this.logger.error("ERROR", ex); } } }
package org.apache.hadoop.hdfs.server.namenode; import java.io.EOFException; import java.io.IOException; import java.net.ConnectException; import java.util.List; import java.util.concurrent.TimeoutException; import org.apache.commons.logging.Log; import org.apache.hadoop.hdfs.server.namenode.persistance.PersistanceException; import org.apache.log4j.Level; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.impl.Log4JLogger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.AppendTestUtil; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSTestUtil; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.server.namenode.persistance.EntityManager; import org.apache.hadoop.io.IOUtils; import org.junit.Test; /** * * @author Jude * Tests the failover during load (read/write operations) when: * 1. Failover from Leader to namenode with next lowest Id * 2. When any other non-leader namenode crashes * 3. When datanodes crash * * In each of the test case, the following should be ensured * 1. The load should continue to run during failover * 2. No corrupt blocks are detected during load * 3. Failovers should perform successfully from the Leader namenode to the namenode with the next lowest id */ public class TestHAFailoverUnderLoad extends junit.framework.TestCase { public static final Log LOG = LogFactory.getLog(TestHAFailoverUnderLoad.class); { ((Log4JLogger) NameNode.stateChangeLog).getLogger().setLevel(Level.ALL); ((Log4JLogger) LeaseManager.LOG).getLogger().setLevel(Level.ALL); ((Log4JLogger) LogFactory.getLog(FSNamesystem.class)).getLogger().setLevel(Level.ALL); } Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = null; FileSystem fs = null; int NN1 = 0, NN2 = 1; static int NUM_NAMENODES = 2; static int NUM_DATANODES = 6; // 10 seconds timeout default long timeout = 10000; Path dir = new Path("/testsLoad"); //Writer[] writers = new Writer[10]; Writer[] writers = new Writer[5]; // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- private void setUp(int replicationFactor) throws IOException { // initialize the cluster with minimum 2 namenodes and minimum 6 datanodes if (NUM_NAMENODES < 2) { NUM_NAMENODES = 2; } if (NUM_DATANODES < 6) { NUM_DATANODES = 6; } this.conf = new Configuration(); conf.setInt(DFSConfigKeys.DFS_REPLICATION_KEY, replicationFactor); conf.setInt(DFSConfigKeys.DFS_DATANODE_HANDLER_COUNT_KEY, 1); //conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10 * 1000); // 10 sec //conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_INTERVAL_KEY, 3); // 3 sec cluster = new MiniDFSCluster.Builder(conf).numNameNodes(NUM_NAMENODES).numDataNodes(NUM_DATANODES).build(); cluster.waitActive(); fs = cluster.getNewFileSystemInstance(NN1); timeout = conf.getInt(DFSConfigKeys.DFS_LEADER_CHECK_INTERVAL_KEY, DFSConfigKeys.DFS_LEADER_CHECK_INTERVAL_DEFAULT) + conf.getLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_DEFAULT) * 1000L; // create the directory namespace assertTrue(fs.mkdirs(dir)); // create writers for (int i = 0; i < writers.length; i++) { writers[i] = new Writer(fs, new Path(dir, "file" + i)); } } private void shutdown() { if (cluster != null) { cluster.shutdown(); } } // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- private void startWriters() { for (int i = 0; i < writers.length; i++) { writers[i].start(); } } private void stopWriters() throws InterruptedException { for (int i = 0; i < writers.length; i++) { if (writers[i] != null) { writers[i].running = false; writers[i].interrupt(); } } for (int i = 0; i < writers.length; i++) { if (writers[i] != null) { writers[i].join(); } } } // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- private void verifyFile() throws IOException { LOG.info("Verify the file"); for (int i = 0; i < writers.length; i++) { LOG.info(writers[i].filepath + ": length=" + fs.getFileStatus(writers[i].filepath).getLen()); FSDataInputStream in = null; try { in = fs.open(writers[i].filepath); //for (int j = 0, x; (x = in.readInt()) != -1; j++) { boolean eof = false; int j = 0, x = 0; while (!eof) { try { x = in.readInt(); assertEquals(j, x); j++; } catch (EOFException ex) { eof = true; // finished reading file } } } finally { IOUtils.closeStream(in); } } } // //@Test // public void testDeadlock() { // try { // setUp((short)3); // String storageId = cluster.getDataNodeByIndex(0).getDatanodeId().getStorageID(); // Thread t1 = new DeadlockTester(NN1, storageId); // t1.start(); // Thread t2 = new DeadlockTester(NN2, storageId); // t2.start(); // // Thread.sleep(50000); // t1.interrupt(); // t2.interrupt(); // } // catch(Exception ex) // { // ex.printStackTrace(); // fail(ex.getMessage()); // } // finally { // shutdown(); // } // // } // // public class DeadlockTester extends Thread{ // // int nnIndex = 0; // String storageId; // public DeadlockTester(int nnIndex, String storageId) { // this.nnIndex = nnIndex; // this.storageId = storageId; // } // @Override // public void run() { // try { // for(;true;) { // cluster.getNamesystem(nnIndex).testDeadlock(storageId); // } // } // catch(Exception ex) { // // } // } // } // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- /** * Under load perform failover by killing leader NN1 * NN2 will be active and loads are now processed by NN2 * Load should still continue * No corrupt blocks should be reported */ @Test public void testFailoverWhenLeaderNNCrashes() { // Testing with replication factor of 3 short repFactor = 3; LOG.info("Running test [testFailoverWhenLeaderNNCrashes()] with replication factor " + repFactor); testFailoverWhenLeaderNNCrashes(repFactor); // Testing with replication factor of 6 repFactor = 6; LOG.info("Running test [testFailoverWhenLeaderNNCrashes()] with replication factor " + repFactor); testFailoverWhenLeaderNNCrashes(repFactor); } private void testFailoverWhenLeaderNNCrashes(short replicationFactor) { try { // setup the cluster with required replication factor setUp(replicationFactor); // save leader namenode port to restart with the same port int nnport = cluster.getNameNodePort(NN1); try { // writers start writing to their files startWriters(); // Give all the threads a chance to create their files and write something to it Thread.sleep(10000); // 10 sec // kill leader NN1 cluster.shutdownNameNode(NN1); TestHABasicFailover.waitLeaderElection(cluster.getDataNodes(), cluster.getNameNode(NN2), timeout); // Check NN2 is the leader and failover is detected assertTrue("NN2 is expected to be the leader, but is not", cluster.getNameNode(NN2).isLeader()); assertTrue("Not all datanodes detected the new leader", TestHABasicFailover.doesDataNodesRecognizeLeader(cluster.getDataNodes(), cluster.getNameNode(NN2))); // the load should still continue without any IO Exception thrown LOG.info("Wait a few seconds. Let them write some more"); Thread.sleep(2000); } finally { stopWriters(); } // the block report intervals would inform the namenode of under replicated blocks // hflush() and close() would guarantee replication at all datanodes. This is a confirmation waitReplication(fs, dir, replicationFactor, timeout); // restart the cluster without formatting using same ports and same configurations cluster.shutdown(); cluster = new MiniDFSCluster.Builder(conf).nameNodePort(nnport).format(false).numNameNodes(NUM_NAMENODES).numDataNodes(NUM_DATANODES).build(); cluster.waitActive(); // update the client so that it has the fresh list of namenodes. Black listed namenodes will be removed fs = cluster.getNewFileSystemInstance(NN1); verifyFile(); // throws IOException. Should be caught by parent } catch (Exception ex) { LOG.error("Received exception: " + ex.getMessage(), ex); ex.printStackTrace(); fail("Exception: " + ex.getMessage()); } finally { shutdown(); } } // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- /** * Under load kill Non-leader NN2 and restart. * Loads should still continue * No corrupt blocks should be reported */ @Test public void testFailoverWhenNonLeaderNNCrashes() { // Testing with replication factor of 3 short repFactor = 3; LOG.info("Running test [testFailoverWhenNonLeaderNNCrashes()] with replication factor " + repFactor); testFailoverWhenNonLeaderNNCrashes(repFactor); // Testing with replication factor of 6 repFactor = 6; LOG.info("Running test [testFailoverWhenNonLeaderNNCrashes()] with replication factor " + repFactor); testFailoverWhenNonLeaderNNCrashes(repFactor); } private void testFailoverWhenNonLeaderNNCrashes(short replicationFactor) { try { // setup the cluster with required replication factor setUp(replicationFactor); // save leader namenode port to restart with the same port int nnport = cluster.getNameNodePort(NN1); try { // writers start writing to their files startWriters(); // Give all the threads a chance to create their files and write something to it Thread.sleep(10000); // 10 sec // kill non-leader namenode NN2 cluster.shutdownNameNode(NN2); // Check NN1 is still the leader assertTrue("NN1 is expected to be the leader, but is not", cluster.getNameNode(NN1).isLeader()); assertTrue("Not all datanodes detect NN1 is the leader", TestHABasicFailover.doesDataNodesRecognizeLeader(cluster.getDataNodes(), cluster.getNameNode(NN1))); // the load should still continue without any IO Exception thrown LOG.info("Wait a few seconds. Let them write some more"); Thread.sleep(100); } finally { stopWriters(); } // the block report intervals would inform the namenode of under replicated blocks // hflush() and close() would guarantee replication at all datanodes. This is a confirmation waitReplication(fs, dir, replicationFactor, timeout); // restart the cluster without formatting using same ports and same configurations cluster.shutdown(); cluster = new MiniDFSCluster.Builder(conf).nameNodePort(nnport).format(false).numNameNodes(NUM_NAMENODES).numDataNodes(NUM_DATANODES).build(); cluster.waitActive(); // update the client so that it has the fresh list of namenodes. Black listed namenodes will be removed fs = cluster.getNewFileSystemInstance(NN1); verifyFile(); // throws IOException. Should be caught by parent } catch (Exception ex) { LOG.error("Received exception: " + ex.getMessage(), ex); ex.printStackTrace(); fail("Exception: " + ex.getMessage()); } finally { shutdown(); } } // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- /** * Under load kill random datanodes after 15 seconds interval * Loads should still continue * No corrupt blocks should be reported * Also tests for successful pipeline recovery when a Datanode crashes */ @Test // Problem with this test case is that, although the new pipeline is setup correctly // when it creates the next pipeline and starts to stream, another datanode crashes!! and then another.. etc. // it only retries when it detects an error while streaming to the datanodes in the pipeline // but not when adding a new datanode to the pipeline //[https://issues.apache.org/jira/browse/HDFS-3436] public void testFailoverWhenDNCrashes() { // Testing with replication factor of 3 short repFactor = 3; LOG.info("Running test [testFailoverWhenDNCrashes()] with replication factor " + repFactor); testFailoverWhenDNCrashes(repFactor); // Testing with replication factor of 6 repFactor = 6; LOG.info("Running test [testFailoverWhenDNCrashes()] with replication factor " + repFactor); testFailoverWhenDNCrashes(repFactor); } public void testFailoverWhenDNCrashes(short replicationFactor) { StringBuffer sb = new StringBuffer(); try { // reset this value NUM_DATANODES = 10; // setup the cluster with required replication factor setUp(replicationFactor); // save leader namenode port to restart with the same port int nnport = cluster.getNameNodePort(NN1); try { // writers start writing to their files startWriters(); // Give all the threads a chance to create their files and write something to it Thread.sleep(10000); // 10 sec // kill some datanodes (but make sure that we have atleast 6+) // The pipleline should be broken and setup again by the client int numDatanodesToKill = 0; if (replicationFactor == 3) { numDatanodesToKill = 5; } else if (replicationFactor == 6) { numDatanodesToKill = 2; } sb.append("Killing datanodes "); for (int i = 0; i < numDatanodesToKill; i++) { // we need a way to ensure that atleast one valid replica is available int dnIndex = AppendTestUtil.nextInt(numDatanodesToKill); sb.append(cluster.getDataNodeByIndex(dnIndex).getSelfAddr()).append("\t"); cluster.stopDataNode(dnIndex); // wait for 15 seconds then kill the next datanode // New pipeline recovery takes place try { Thread.sleep(15000); } catch (InterruptedException ex) { } } LOG.info(sb); // the load should still continue without any IO Exception thrown LOG.info("Wait a few seconds. Let them write some more"); Thread.sleep(2000); } finally { // closing files - finalize all the files UC stopWriters(); } // the block report intervals would inform the namenode of under replicated blocks // hflush() and close() would guarantee replication at all datanodes. This is a confirmation waitReplication(fs, dir, replicationFactor, timeout); // restart cluster - If DNs come up with different host:port, it will be replaced in [ReplicaUC] cluster.shutdown(); cluster = new MiniDFSCluster.Builder(conf).nameNodePort(nnport).format(false).numNameNodes(NUM_NAMENODES).numDataNodes(NUM_DATANODES).build(); cluster.waitActive(); // update the client so that it has the fresh list of namenodes. Black listed namenodes will be removed fs = cluster.getNewFileSystemInstance(NN1); // make sure that DNs that were killed are not part of the "expected block locations" or "triplets" // the blocks associated to the killed DNs should have been replicated verifyFile(); // throws IOException. Should be caught by parent } catch (Exception ex) { LOG.error("Received exception: " + ex.getMessage() + ". DNs killed [" + sb + "]", ex); ex.printStackTrace(); fail("Exception: " + ex.getMessage()); } finally { shutdown(); } } // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- public static void waitReplication(FileSystem fs, Path rootDir, short replicationFactor, long timeout) throws IOException, TimeoutException { FileStatus[] files = fs.listStatus(rootDir); for (int i = 0; i < files.length;) { try { // increasing timeout to take into consideration 'ping' time with failed namenodes // if the client fetches for block locations from a dead NN, it would need to retry many times and eventually this time would cause a timeout // to avoid this, we set a larger timeout long expectedRetyTime = 20000; // 20seconds timeout = timeout + expectedRetyTime; DFSTestUtil.waitReplicationWithTimeout(fs, files[i].getPath(), replicationFactor, timeout); i++; } catch (ConnectException ex) { // ignore LOG.warn("Received Connect Exception (expected due to failure of NN)"); } } } // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- private static void waitTillFilesClose(FileSystem fs, Path rootDir, long timeout) throws IOException, TimeoutException, PersistanceException { long initTime = System.currentTimeMillis(); //getting parent directory INode parent = EntityManager.find(INode.Finder.ByNameAndParentId, rootDir.getName(), 0); // INode parent = INodeHelper.getINode(rootDir.getName(), 0); // List<INode> files = INodeHelper.getChildren(parent.id); List<INode> files = (List<INode>) EntityManager.findList(INode.Finder.ByParentId, parent.getId()); // loop through all files and check if they are closed. Expected to be closed by now for (int i = 0; i < files.size();) { if (!files.get(i).isUnderConstruction()) { i++; } if (System.currentTimeMillis() - initTime > timeout) { throw new TimeoutException("File [" + files.get(i).getFullPathName() + "] has not been closed. Still under construction"); } } } // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- static class Writer extends Thread { FileSystem fs; final Path filepath; boolean running = true; FSDataOutputStream out = null; Writer(FileSystem fs, Path filepath) { super(Writer.class.getSimpleName() + ":" + filepath); this.fs = fs; this.filepath = filepath; // creating the file here try { out = this.fs.create(filepath); } catch (Exception ex) { LOG.info(getName() + " unable to create file [" + filepath + "]" + ex, ex); if (out != null) { IOUtils.closeStream(out); out = null; } } } public void run() { int i = 0; if (out != null) { try { for (; running; i++) { out.writeInt(i); out.hflush(); sleep(100); } } catch (Exception e) { LOG.info(getName() + " dies: e=" + e, e); } finally { LOG.info(getName() + ": i=" + i); IOUtils.closeStream(out); //IOUtils.cleanup(LOG, out); //try { //out.close(); //} //catch(IOException ex) { // LOG.error("*unable to close file. Exception: "+ex.getMessage(), ex); //} }//end-finally }// end-outcheck else { LOG.info(getName() + " outstream was null for file [" + filepath + "]"); } }//end-run }//end-method }
package entity; import Excecoes.UsuarioJaExistenteException; import java.util.HashMap; import java.util.Map; public class Pessoa { private String nome; private String CPF; private String endereco; private int telefone; private String login; private String senha; /** * Método construtor da classe pessoa * * @param nome * @param CPF * @param endereco * @param login * @param senha */ public Pessoa(String nome, String CPF, String endereco, String login, String senha, int telefone) { this.nome = nome; this.CPF = CPF; this.endereco = endereco; this.login = login; this.senha = senha; this.telefone=telefone; }//fim do metodo construtor public String getNome(){ return nome; } public String getCPF(){ return CPF; } public String getEndereco(){ return endereco; } public String getLogin(){ return login; } public String getSenha(){ return senha; } public int getTelefone(){ return telefone; } public void setEndereco(String novoEndereco){ this.endereco=novoEndereco; } public void setTelefone(int novoTelefone){ this.telefone=novoTelefone; } public void setSenha(String novaSenha){ this.senha=novaSenha; } public void setNome(String nome) { this.nome = nome; } }//fim da classe Pessoa
import javax.swing.*; /*********************************************** *@author Timothy Lanfranco* *@version 2.2* *@since 12/05/19* ***********************************************/ public class Converter { public static void main(String[] args) { PROGRAM(); } private static void ReDo() { int reply = JOptionPane.showConfirmDialog(null, "Would you like to Convert again?", "Go again?", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { PROGRAM(); } else { System.exit(0); } } private static void PROGRAM() { int chooseConverter = Integer.parseInt(JOptionPane.showInputDialog(null, "Which converter do you need? \n\n1. Weight\n2. Distance\n3. Temperature\n4. Time")); switch (chooseConverter) { case 1: convertWeight(); break; case 2: convertDistance(); break; case 3: convertTemperature(); break; case 4: convertTime(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } private static void convertWeight() { final double conversionValue = 2.205; int choice = Integer.parseInt(JOptionPane.showInputDialog(null, "1. KG to pounds\n2. Pounds to KG")); double enterValue = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter a Value")); double res; switch (choice) { case 1: res = enterValue * conversionValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue / conversionValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } private static void convertDistance() { int choice1 = Integer.parseInt(JOptionPane.showInputDialog(null, "1.Centimeters to...\n2.Inches to...\n3.Meters to...\n4.Feet to...\n5. Miles to...")); int choice2 = Integer.parseInt(JOptionPane.showInputDialog(null, "1. Centimeters\n2. Inches\n3. Meters\n4. Feet\n5. Miles")); double enterValue = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter a Value")); double res; if (choice1 == 1) { //centimeters switch (choice2) { case 1: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue / 2.54; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue / 100; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue / 30.48; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue / 160934.4; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } else if (choice1 == 2) { // inches switch (choice2) { case 1: res = enterValue * 2.54; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue / 39.37; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue / 12; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue / 63360; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } else if (choice1 == 3) { //meters switch (choice2) { case 1: res = enterValue * 30.48; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue * 39.37; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue * 3.281; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue / 1609.344; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } else if (choice1 == 4) { //feet switch (choice2) { case 1: res = enterValue * 30.48; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue * 12; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue / 3.281; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue / 5280; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } else if (choice1 == 5) { //miles switch (choice2) { case 1: res = enterValue * 160934.4; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue * 63360; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue * 1609.344; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue * 5280; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; } } else { JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); } } private static void convertTemperature() { int choice = Integer.parseInt(JOptionPane.showInputDialog(null, "1. Celsius to Fahrenheit\n2. Fahrenheit to Celsius")); double enterValue = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter a Value")); double CtF = (enterValue * 9/5) + 32; double FtC = (enterValue - 32) * 5/9; switch (choice) { case 1: JOptionPane.showMessageDialog(null, String.format("Result is %.3f", CtF)); ReDo(); break; case 2: JOptionPane.showMessageDialog(null, String.format("Result is %.3f", FtC)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } private static void convertTime() { int choice1 = Integer.parseInt(JOptionPane.showInputDialog(null, "1. Seconds to...\n2. Minutes to...\n3. Hours to...\n4. Days to...\n5. Weeks to...\n6. Months to...\n7. Years to...")); int choice2 = Integer.parseInt(JOptionPane.showInputDialog(null, "1. Seconds\n2. Minutes\n3. Hours\n4. Days\n5. Weeks\n6. Months\n7. Years")); double enterValue = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter a Value")); double res; if (choice1 == 1) { switch (choice2) { case 1: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue / 60; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue / 3600; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue / 86400; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue / 604800; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 6: res = enterValue / 2.628e+6; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 7: res = enterValue / 3.154e+7; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } else if (choice1 == 2) { switch (choice2) { case 1: res = enterValue * 60; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue / 60; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue / 1440; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue / 10080; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 6: res = enterValue / 43800.048; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 7: res = enterValue / 525600; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } else if (choice1 == 3) { switch (choice2) { case 1: res = enterValue * 3600; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue * 60; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue / 24; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue / 168; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 6: res = enterValue / 730.001; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 7: res = enterValue / 8760; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } else if (choice1 == 4) { switch (choice2) { case 1: res = enterValue * 86400; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue * 1440; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue * 24; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue / 7; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 6: res = enterValue / 30.417; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 7: res = enterValue / 365; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } else if (choice1 == 5) { switch (choice2) { case 1: res = enterValue * 604800; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue * 10080; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue * 168; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue * 7; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 6: res = enterValue / 4.345; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 7: res = enterValue / 52.143; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } else if (choice1 == 6) { switch (choice2) { case 1: res = enterValue * 2.628e+6; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue * 43800.048; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue * 730.001; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue * 30.417; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue * 4.345; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 6: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 7: res = enterValue / 12; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } else if (choice1 == 7) { switch (choice2) { case 1: res = enterValue * 3.154e+7; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 2: res = enterValue * 525600; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 3: res = enterValue * 8760; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 4: res = enterValue * 365; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 5: res = enterValue * 52.143; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 6: res = enterValue * 12; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; case 7: res = enterValue; JOptionPane.showMessageDialog(null, String.format("Result is %.3f", res)); ReDo(); break; default: JOptionPane.showMessageDialog(null, "Invalid Option"); ReDo(); break; } } else { JOptionPane.showMessageDialog(null, "Invalid Option"); } } }
package com.finalyearproject.spring.web.entity; import java.util.List; import com.fullcontact.api.libs.fullcontact4j.http.person.model.Organization; import com.fullcontact.api.libs.fullcontact4j.http.person.model.Photo; import com.fullcontact.api.libs.fullcontact4j.http.person.model.SocialProfile; import com.pipl.api.data.containers.Relationship; public class Catfish { private String firstName; private String lastName; private String age; private String gender; private String location; private String facebook; private String phone; private Object metadataDate; private double metadataLat; private double metadataLong; // reverse image search private List<String> reverseImagePics; private List<String> reverseImageWebsites; public Catfish() { } public Catfish(String firstName, String lastName, String age, String gender, String location, String facebook, String phone, Object metadataDate, double metadataLat, double metadataLong, List<String> reverseImagePics, List<String> reverseImageWebsites) { super(); this.firstName = firstName; this.lastName = lastName; this.age = age; this.gender = gender; this.location = location; this.facebook = facebook; this.phone = phone; this.metadataDate = metadataDate; this.metadataLat = metadataLat; this.metadataLong = metadataLong; this.reverseImagePics = reverseImagePics; this.reverseImageWebsites = reverseImageWebsites; } public List<String> getReverseImagePics() { return reverseImagePics; } public void setReverseImagePics(List<String> reverseImagePics) { this.reverseImagePics = reverseImagePics; } public List<String> getReverseImageWebsites() { return reverseImageWebsites; } public void setReverseImageWebsites(List<String> reverseImageWebsites) { this.reverseImageWebsites = reverseImageWebsites; } public Object getMetadataDate() { return metadataDate; } public void setMetadataDate(Object metadataDate) { this.metadataDate = metadataDate; } public double getMetadataLat() { return metadataLat; } public void setMetadataLat(double metadataLat) { this.metadataLat = metadataLat; } public double getMetadataLong() { return metadataLong; } public void setMetadataLong(double metadataLong) { this.metadataLong = metadataLong; } public String getFacebook() { return facebook; } public void setFacebook(String facebook) { this.facebook = facebook; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }