text
stringlengths
10
2.72M
package com.mibo.modules.data.model; import com.mibo.modules.data.base.BaseTagProduct; import java.util.List; @SuppressWarnings("serial") public class TagProduct extends BaseTagProduct<TagProduct> { /* 12 */ public static final TagProduct dao = (TagProduct) new TagProduct().dao(); public List<TagProduct> queryTagProductLikeName(String keyword) { /* 21 */ String sql = "SELECT * FROM t_tag_product WHERE product_name LIKE '%" + keyword + "%'"; /* 22 */ return find(sql); } }
package util; /** * Created by yijigao on 2015/10/27. */ public interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }
import java.util.Scanner; /* SOAL Batas Bawah : 1 Batas Atas : 3 Iterasi Maks : 3 Hasil : Akar diantara 1.6666666666666665 dan 2.333333333333333 Akar lebih dekat ke x[2] = 2.333333333333333 */ public class MetodeTabel{ public static double y(float x) { double hasil= Math.pow(x, 2) - 2 * Math.pow(x, 2) - x + 1; return hasil; } public static void main(String args[]){ Scanner input= new Scanner(System.in); System.out.print("Batas bawah(Xbawah) : "); double xBawah= input.nextDouble(); System.out.print("Batas atas(Xatas) : "); double xAtas= input.nextDouble(); System.out.print("Jumlah pembagian(N) : "); int n= input.nextInt(); double h= (xAtas-xBawah)/n; double[] x= new double [n+1]; double[] y= new double [n+1]; for(int i=0; i<=n; i++){ x[i]= i * h + xBawah; y[i]= y(-x[i]); System.out.println("x[" +i+ "] = " +x[i]+ "\ty[" +i+ "] = " +y[i]); } for(int j=0; j<n; j++){ if(y[j]*y[j+1]<0){ System.out.println("Akar diantara " +x[j]+ " dan " +x[j+1]); if(Math.abs(y[j]) < Math.abs(y[j + 1])){ System.out.println("Akar lebih dekat ke x[" +j+ "] = " +x[j]); } else{ System.out.println("Akar lebih dekat ke x[" +(j+1)+ "] = " +x[j+1]); } } } } }
package factory; import enums.Color; import piece.Pawn; import piece.Piece; import piece.Queen; public class PieceFactory { public static Piece getPiece(String input) { char color = input.charAt(0); char pieceType = input.charAt(1); Piece piece=null; switch(pieceType) { case 'Q': piece = new Queen(); break; case 'P': piece = new Pawn(); break; default: System.out.println("Incorrect piece in input"); } if (color == 'W') piece.setColor(Color.WHITE); else piece.setColor(Color.BLACK); return piece; } }
package net.yustinus.crud.web.main; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import org.apache.commons.lang.StringUtils; import org.docx4j.XmlUtils; import org.docx4j.jaxb.Context; import org.docx4j.openpackaging.exceptions.Docx4JException; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.openpackaging.parts.WordprocessingML.NumberingDefinitionsPart; import org.docx4j.wml.ContentAccessor; import org.docx4j.wml.Numbering; import org.docx4j.wml.ObjectFactory; import org.docx4j.wml.P; import org.docx4j.wml.PPrBase.NumPr; import org.docx4j.wml.PPrBase.NumPr.Ilvl; import org.docx4j.wml.PPrBase.NumPr.NumId; import org.docx4j.wml.Text; public class WebMain2 { public static void main(String[] args) throws Docx4JException, JAXBException, IOException { String template = "D:\\yus.docx"; WordprocessingMLPackage mlPackage = getTemplate(template); replaceParagraph("YUS_PARAGRAPH", "aklsdf adaf \n skdjfalksjd fask \n jdlasjdkfahsdkjfahs dfja", mlPackage, mlPackage.getMainDocumentPart()); writeDocxToStream(mlPackage, "D:\\yusgandos.docx"); } public static WordprocessingMLPackage getTemplate(String name) throws Docx4JException, FileNotFoundException { WordprocessingMLPackage template = WordprocessingMLPackage.load(new File(name)); return template; } public static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) { List<Object> result = new ArrayList<Object>(); if (obj instanceof JAXBElement) obj = ((JAXBElement<?>) obj).getValue(); if (obj.getClass().equals(toSearch)) result.add(obj); else if (obj instanceof ContentAccessor) { List<?> children = ((ContentAccessor) obj).getContent(); for (Object child : children) { result.addAll(getAllElementFromObject(child, toSearch)); } } return result; } public void replacePlaceholder(WordprocessingMLPackage template, String name, String placeholder ) { List<Object> texts = getAllElementFromObject(template.getMainDocumentPart(), Text.class); for (Object text : texts) { Text textElement = (Text) text; if (textElement.getValue().equals(placeholder)) { textElement.setValue(name); } } } public static void writeDocxToStream(WordprocessingMLPackage template, String target) throws IOException, Docx4JException { File f = new File(target); template.save(f); } public static void replaceParagraph(String placeholder, String textToAdd, WordprocessingMLPackage template, ContentAccessor addTo) { // 1. get the paragraph List<Object> paragraphs = getAllElementFromObject(template.getMainDocumentPart(), P.class); P toReplace = null; for (Object p : paragraphs) { List<Object> texts = getAllElementFromObject(p, Text.class); for (Object t : texts) { Text content = (Text) t; if (content.getValue().equals(placeholder)) { toReplace = (P) p; break; } } } // we now have the paragraph that contains our placeholder: toReplace // 2. split into seperate lines String as[] = StringUtils.splitPreserveAllTokens(textToAdd, '\n'); for (int i = 0; i < as.length; i++) { String ptext = as[i]; // 3. copy the found paragraph to keep styling correct P copy = (P) XmlUtils.deepCopy(toReplace); // replace the text elements from the copy List<?> texts = getAllElementFromObject(copy, Text.class); if (texts.size() > 0) { Text textToReplace = (Text) texts.get(0); textToReplace.setValue(ptext); } // add the paragraph to the document addTo.getContent().add(copy); } // 4. remove the original one ((ContentAccessor)toReplace.getParent()).getContent().remove(toReplace); } }
/* * 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 bmiserver; import java.io.*; import java.net.*; import java.util.Date; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.control.TextArea; import javafx.scene.control.ScrollPane; import javafx.stage.Stage; /** * * @author emwhfm */ public class BMIServer extends Application { // Constants final double KILOGRAMS_PER_POUND = 0.45359237; final double METERS_PER_INCH = 0.0254; ScrollPane sp; @Override public void start(Stage primaryStage) { // Text area for displaying contents TextArea ta = new TextArea(); sp = new ScrollPane(ta); // Create a scene and place it in the stage Scene scene = new Scene(sp, 450, 200); primaryStage.setTitle("BMI Server"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage new Thread(() -> { try { // Create a server socket ServerSocket serverSocket = new ServerSocket(8000); Platform.runLater(() -> ta.appendText("Server started at " + new Date() + '\n')); Platform.runLater(() -> sp.setHvalue(0)); // Listen for a connection request Socket socket = serverSocket.accept(); Platform.runLater(() -> ta.appendText("Connected to a client at " + new Date() + '\n')); // Create data input and output streams DataInputStream inputFromClient = new DataInputStream( socket.getInputStream()); DataOutputStream outputToClient = new DataOutputStream( socket.getOutputStream()); PrintWriter printWriter = new PrintWriter(outputToClient); while (true) { // Receive weight and height from the client double weight = inputFromClient.readDouble(); double height = inputFromClient.readDouble(); Platform.runLater(() -> { ta.appendText("Weight: " + weight + '\n'); ta.appendText("Height: " + height + '\n'); }); // Compute BMI double weightInKilograms = weight * KILOGRAMS_PER_POUND; double heightInMeters = height * METERS_PER_INCH; double bmi = (weightInKilograms / (heightInMeters * heightInMeters)); double finalBMI = Math.round( bmi * 100.0 ) / 100.0; // Analyze result String descr; if (finalBMI < 18.5) descr = "Underweight"; else if (finalBMI < 25) descr = "Normal"; else if (finalBMI < 30) descr = "Overweight"; else descr = "Obese"; Platform.runLater(() -> { ta.appendText("BMI is " + finalBMI + ". " + descr + '\n'); }); // Send BMI back to the client printWriter.print("BMI is " + finalBMI + ". " + descr + '\n'); printWriter.flush(); } } catch(IOException ex) { ta.appendText(ex.toString() + '\n'); } }).start(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
package com.qx.wechat.tulin; import com.github.dadiyang.httpinvoker.annotation.HttpApi; import com.github.dadiyang.httpinvoker.annotation.HttpReq; import com.github.dadiyang.httpinvoker.annotation.Param; import com.github.dadiyang.httpinvoker.annotation.RetryPolicy; import com.qx.wechat.tulin.request.TuLinRequest; import com.qx.wechat.tulin.response.TuLinResponse; @HttpApi("http://openapi.tuling123.com") @RetryPolicy public interface ITuLin { @HttpReq(value = "/openapi/api/v2", method = "POST") public TuLinResponse send(@Param TuLinRequest request); }
package com.example.cs458project4.dto; import com.example.cs458project4.Models.Suser; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @AllArgsConstructor @NoArgsConstructor @ToString public class SuserDTO { private String tcnumber; private String password; }
import java.awt.*; import java.applet.*; public class m3 extends Applet { Color ci; Font f1; int b; public void paint(Graphics g) { f1=new Font("Arial",Font.BOLD,16); g.setFont(f1); ci=new Color(50,67,70); setBackground(ci); g.setColor(Color.RED); g.drawString(" WELCOME ",40,40); f1=new Font("Regular",Font.BOLD|Font.ITALIC,15); g.setFont(f1); g.setColor(Color.GREEN); g.drawString(" TO ",40,60); f1=new Font("Biondi",Font.ITALIC,15); g.setFont(f1); g.setColor(Color.BLUE); g.drawString(" ADA IT ",40,80); try { g.setColor(Color.RED); for(b=1;b<=30;b++) { g.drawString(" AMRESH ",40,20); Thread.sleep(1000); g.drawString("",40,20); Thread.sleep(1000); } }//close of try catch(Exception e) { } }//close paint() }//close of class
package com.example.buildpc.Model; public class Model_Item { public String ImageItem; public String NameItem; public String Brand; public int Price; public Model_Item(String imageItem, String nameItem, String brand, int price) { ImageItem = imageItem; NameItem = nameItem; Brand = brand; Price = price; } public String getImageItem() { return ImageItem; } public void setImageItem(String imageItem) { ImageItem = imageItem; } public String getNameItem() { return NameItem; } public void setNameItem(String nameItem) { NameItem = nameItem; } public String getBrand() { return Brand; } public void setBrand(String brand) { Brand = brand; } public int getPrice() { return Price; } public void setPrice(int price) { Price = price; } }
package com.madrun.springmongo.model; import org.springframework.data.mongodb.core.mapping.Document; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @Document @NoArgsConstructor public class SocialMediaAccount { String accountType; int noOfFollowers; public SocialMediaAccount(String accountType, int noOfFollowers) { super(); this.accountType = accountType; this.noOfFollowers = noOfFollowers; } public SocialMediaAccount() { super(); } public String getAccountType() { return accountType; } public void setAccountType(String accountType) { this.accountType = accountType; } public int getNoOfFollowers() { return noOfFollowers; } public void setNoOfFollowers(int noOfFollowers) { this.noOfFollowers = noOfFollowers; } }
package com.ifeng.recom.mixrecall.prerank; import com.alibaba.fastjson.JSONObject; import com.ifeng.recom.mixrecall.prerank.constant.CTRConstant; import java.util.ArrayList; import java.util.List; import static com.ifeng.recom.mixrecall.common.model.JsonUtils.writeToJSON; public class AdNatureEntity { //内部类用于存储新闻、视频item的特征和权重 public class AdFeatureAndValue{ //特征id1 long setId; //特征id2 long valueId; //特征对应值 double value; public long getSetId() { return setId; } public void setSetId(long setId) { this.setId = setId; } public long getValueId() { return valueId; } public void setValueId(long valueId) { this.valueId = valueId; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public AdFeatureAndValue(long setId, long valueId, double value) { this.setId = setId; this.valueId = valueId; this.value = value; } } List<AdFeatureAndValue> AdFeatureAndValues = null; private String sId; private String expid; private String itemId; private String trackId; public AdNatureEntity(String sId, String expid, String itemId, String trackId) { this.sId = sId; this.expid = expid; this.itemId = itemId; this.trackId=trackId; AdFeatureAndValues = new ArrayList<AdFeatureAndValue>(); } public void addAd(long setId, long valueId, double value) { AdFeatureAndValues.add(new AdFeatureAndValue(setId, valueId, value)); } private String listToString() { StringBuilder sb = new StringBuilder(); for(AdFeatureAndValue adFeatureAndValue : AdFeatureAndValues) { if (sb.length() > 0) { sb.append(CTRConstant.Symb_Comma); } sb.append(adFeatureAndValue.getSetId()).append(CTRConstant.Symb_Colon) .append(adFeatureAndValue.getValueId()).append(CTRConstant.Symb_Colon) .append(adFeatureAndValue.getValue()); } return sb.toString(); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(sId).append(CTRConstant.Symb_Tab) .append(itemId).append(CTRConstant.Symb_Tab) .append(writeToJSON(AdFeatureAndValues)).append(CTRConstant.Symb_Tab) .append(expid).append(CTRConstant.Symb_Tab) .append(trackId); return sb.toString(); } public JSONObject toJsonObject() { JSONObject jsonObject = new JSONObject(); jsonObject.put("sid", sId); jsonObject.put("itemid", itemId); jsonObject.put("userid", trackId); jsonObject.put("expid", expid); jsonObject.put("data", AdFeatureAndValues); return jsonObject; } // public void pushToQueue() { // if (AdFeatureAndValues.size() > 0) { // Manage.addAdNatureQueue(this); // } // } public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public List<AdFeatureAndValue> getAdFeatureAndValues() { return AdFeatureAndValues; } public void setAdFeatureAndValues(List<AdFeatureAndValue> adFeatureAndValues) { AdFeatureAndValues = adFeatureAndValues; } public String getsId() { return sId; } public void setsId(String sId) { this.sId = sId; } public String getExpid() { return expid; } public void setExpid(String expid) { this.expid = expid; } public String getTrackId() { return trackId; } public void setTrackId(String trackId) { this.trackId = trackId; } public static void main(String[] args) { } }
package ru.itmo.ctlab.sgmwcs; public class TimeLimit { private double tl; private TimeLimit parent; public TimeLimit(double tl) { if (tl < 0) { throw new IllegalArgumentException(); } this.tl = tl; } private TimeLimit(TimeLimit parent, double fraction) { if (fraction < 0.0 || fraction > 1.0) { throw new IllegalArgumentException(); } this.parent = parent; tl = parent.getRemainingTime() * fraction; } public void spend(double time) { tl -= time; if (parent != null) { parent.spend(time); } } public TimeLimit subLimit(double fraction) { return new TimeLimit(this, fraction); } public double getRemainingTime() { return tl; } }
package mihau.eu.githubsearach; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import io.reactivex.observers.TestObserver; import mihau.eu.githubsearch.api.GitHubRepository; import mihau.eu.githubsearch.api.TestAPIService; import mihau.eu.githubsearch.utils.providers.resources.TestResourceProvider; import mihau.eu.githubsearch.utils.providers.scheduler.TestSchedulerProvider; import mihau.eu.githubsearch.viewmodel.SearchEvent; import mihau.eu.githubsearch.viewmodel.UserViewModel; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class UserViewModelTest { private UserViewModel userViewModel; @Before public void before() { TestSchedulerProvider schedulerProvider = new TestSchedulerProvider(); GitHubRepository gitHubRepository = new GitHubRepository(new TestAPIService(), schedulerProvider); TestResourceProvider resourcesProvider = new TestResourceProvider(); userViewModel = new UserViewModel(gitHubRepository, resourcesProvider); } @After public void after() { } @Test public void testInitialization() { assertEquals(userViewModel.isError.get(), true); assertEquals(userViewModel.isLoading.get(), false); } @Test public void testSearch() { ArrayList<SearchEvent> sequence = new ArrayList<>(); TestObserver<SearchEvent> testObserver = userViewModel.searchEventPublishSubject.test(); userViewModel.search("test"); sequence.add(new SearchEvent(SearchEvent.Type.LOADING)); sequence.add(new SearchEvent(SearchEvent.Type.SUCCESS)); testObserver.assertValueSequence(sequence); } @Test public void testGetUser() { ArrayList<SearchEvent> sequence = new ArrayList<>(); TestObserver<SearchEvent> testObserver = userViewModel.searchEventPublishSubject.test(); userViewModel.search("test"); sequence.add(new SearchEvent(SearchEvent.Type.LOADING)); sequence.add(new SearchEvent(SearchEvent.Type.SUCCESS)); testObserver.assertValueSequence(sequence); assertNotNull(userViewModel.getUser()); } @Test public void testSearchWhileLoading() { ArrayList<SearchEvent> sequence = new ArrayList<>(); TestObserver<SearchEvent> testObserver = userViewModel.searchEventPublishSubject.test(); userViewModel.search("test"); userViewModel.isLoading.set(true); userViewModel.search("test"); sequence.add(new SearchEvent(SearchEvent.Type.LOADING)); sequence.add(new SearchEvent(SearchEvent.Type.SUCCESS)); testObserver.assertValueSequence(sequence); } @Test public void testFailedSearch() { ArrayList<SearchEvent> sequence = new ArrayList<>(); TestObserver<SearchEvent> testObserver = userViewModel.searchEventPublishSubject.test(); userViewModel.search(null); sequence.add(new SearchEvent(SearchEvent.Type.LOADING)); sequence.add(new SearchEvent(SearchEvent.Type.ERROR, new Throwable(""))); testObserver.assertValueSequence(sequence); assertEquals(userViewModel.isError.get(), true); } }
package Items; public enum Armour { HEAVY(10), LIGHT(5), SEXY(1); private final int armourValue; Armour(int armourValue) { this.armourValue = armourValue; } public int getArmourValue() { return armourValue; } }
package com.otherhshe.niceread.presenter; import com.otherhshe.niceread.api.GankService; import com.otherhshe.niceread.model.GankItemData; import com.otherhshe.niceread.net.ApiService; import com.otherhshe.niceread.rx.RxManager; import com.otherhshe.niceread.rx.RxSubscriber; import com.otherhshe.niceread.ui.view.GankItemView; import java.util.List; /** * Author: Othershe * Time: 2016/8/12 14:29 */ public class GankItemPresenter extends BasePresenter<GankItemView> { public GankItemPresenter(GankItemView view) { super(view); } public void getGankItemData(String suburl) { mSubscription = RxManager.getInstance() .doSubscribe1(ApiService.getInstance().initService(GankService.class).getGankItemData(suburl), new RxSubscriber<List<GankItemData>>(true) { @Override protected void _onNext(List<GankItemData> gankItemData) { mView.onSuccess(gankItemData); } @Override protected void _onError() { mView.onError(); } }); } }
/* * (C) Copyright 2010 Marvell International Ltd. * All Rights Reserved * * MARVELL CONFIDENTIAL * Copyright 2008 ~ 2010 Marvell International Ltd All Rights Reserved. * The source code contained or described herein and all documents related to * the source code ("Material") are owned by Marvell International Ltd or its * suppliers or licensors. Title to the Material remains with Marvell International Ltd * or its suppliers and licensors. The Material contains trade secrets and * proprietary and confidential information of Marvell or its suppliers and * licensors. The Material is protected by worldwide copyright and trade secret * laws and treaty provisions. No part of the Material may be used, copied, * reproduced, modified, published, uploaded, posted, transmitted, distributed, * or disclosed in any way without Marvell's prior express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or delivery * of the Materials, either expressly, by implication, inducement, estoppel or * otherwise. Any license under such intellectual property rights must be * express and approved by Marvell in writing. * */ package com.marvell.fmradio.list; import java.util.List; import com.marvell.fmradio.R; import com.marvell.fmradio.util.Station; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class RemoveListAdapter extends ArrayAdapter<Station> { private static final String TAG = "RemoveListAdapter"; public class FMHolder { public TextView mFreq; public TextView mName; public ImageView mIcon; public boolean mSelect; } private int mListItemLayoutId = -1; private LayoutInflater mInflater = null; private boolean mRemoveArray[] = null; private static int mSize = -1; public RemoveListAdapter(Context context, int textViewResourceId, List<Station> objects) { super(context, textViewResourceId, objects); mListItemLayoutId = textViewResourceId; mInflater = LayoutInflater.from(context); mSize = objects.size(); mRemoveArray = new boolean[mSize]; for (int i = 0; i < mSize; i++) mRemoveArray[i] = false; } public void setChecked(int position) { mRemoveArray[position] = ! mRemoveArray[position]; notifyDataSetChanged(); } public void selectAll() { for (int i = 0; i < mSize; i++) mRemoveArray[i] = true; notifyDataSetChanged(); } public void cancelAll() { for (int i = 0; i < mSize; i++) mRemoveArray[i] = false; notifyDataSetChanged(); } public boolean getChecked(int position) { return mRemoveArray[position]; } public View getView(int position, View convertView, ViewGroup parent) { View view = null; FMHolder holder = null; if (null == convertView) { view = mInflater.inflate(mListItemLayoutId, parent, false); holder = new FMHolder(); holder.mFreq = (TextView) view.findViewById(R.id.text_view_freq); holder.mName = (TextView) view.findViewById(R.id.text_view_name); holder.mIcon = (ImageView) view.findViewById(R.id.image_view_remove); holder.mSelect = false; view.setTag(holder); } else { view = convertView; holder = (FMHolder) view.getTag(); } Station item = (Station) getItem(position); if (null == item) return null; holder.mFreq.setText(item.mFreq); holder.mName.setText(item.mName); if (mRemoveArray[position]) holder.mIcon.setImageResource(R.drawable.btn_dialog_selected); else holder.mIcon.setImageResource(R.drawable.btn_dialog_normal); return view; } }
package br.com.amaro.demo.strategy; import br.com.amaro.demo.forms.ProductRegisterForm; import br.com.amaro.demo.forms.ProductRegisterListForm; import br.com.amaro.demo.validators.RegisterFormErrors; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.FieldError; import java.util.Collections; import java.util.List; @RunWith(MockitoJUnitRunner.class) @SpringBootTest(classes = IndexOfTagsStrategy.class) public class ElementListToRemoveStrategyTest { @InjectMocks private ElementListToRemoveStrategy elementListToRemoveStrategy; private final ProductRegisterListForm productRegisterListForm = new ProductRegisterListForm(); @Before public void init() { final ProductRegisterForm productRegisterForm1 = new ProductRegisterForm(); final ProductRegisterForm productRegisterForm2 = new ProductRegisterForm(); final ProductRegisterForm productRegisterForm3 = new ProductRegisterForm(); productRegisterListForm.getProducts().add(productRegisterForm1); productRegisterListForm.getProducts().add(productRegisterForm2); productRegisterListForm.getProducts().add(productRegisterForm3); } @Test public void execute_NullInputData() { final List<Integer> response = this.elementListToRemoveStrategy.execute(null); Assert.assertEquals(Collections.emptyList(), response); } @Test public void execute() { final Object[] args = {1}; final String message = "rejection test"; final BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(productRegisterListForm, "productRegisterListForm"); bindingResult.rejectValue(ProductRegisterForm.NAME, RegisterFormErrors.EMPTY_NAME, args, message); final FieldError fieldError = bindingResult.getFieldError(ProductRegisterForm.NAME); final List<Integer> response = this.elementListToRemoveStrategy.execute(fieldError); Assert.assertEquals(1, response.get(0).intValue()); } @Test public void execute_WithoutRejection() { final String message = "rejection test"; final BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(productRegisterListForm, "productRegisterListForm"); bindingResult.rejectValue(ProductRegisterForm.NAME, RegisterFormErrors.EMPTY_NAME, null, message); final FieldError fieldError = bindingResult.getFieldError(ProductRegisterForm.NAME); final List<Integer> response = this.elementListToRemoveStrategy.execute(fieldError); Assert.assertEquals(0, response.size()); } }
package com.company; class Book { String code="000" ; //รหัสหนังสือ String bookname="" ; //ชื่อหนังสือ String status="" ; // สถานะ String date =""; //วันเวลา int group ; // หมวดหมู่ของหนังสือ public Book() { } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getBookname() { return bookname; } public void setBookname(String bookname) { this.bookname = bookname; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public int getGroup() { return group; } public void setGroup(int group) { this.group = group; } public Book(String code, String bookname, String status, String date, int group) { this.code = code; this.bookname = bookname; this.status = status; this.date = date; this.group = group; } public void printBook (){ System.out.println( "รหัสหนังสือ : "+this.code+"\n "+ "ชื่อหนังสือ : "+this.bookname+"\n "+ "สถานะของหนังสือ : "+this.status+"\n "+ "วันที่ทำการยืมหนังสือ : "+this.date+"\n "+ "หมวดหมู่ของหนังสือ : "+this.group); } }
/* https://codeforces.com/problemset/problem/1283/E => min => max => independence => seperate two . => two sub-problems #greedy */ import java.util.Scanner; public class NewYearParties { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; int maxVal = 0; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); if (arr[i] > maxVal) { maxVal = arr[i]; } } // count array int[] cntArr = new int[maxVal + 1]; for (int v : arr) { cntArr[v]++; } // find min int min = 0; int i = 1; while (i < maxVal + 1) { if (cntArr[i] > 0) { /* i : cnt[i] > 0 || cnt[i+1] > 0 || cnt[i+2] > 0 => select pos = i+1 for both i, i+1, i+2. */ i += 3; min++; } else { i++; } } // find max int max = 0; int prev = 0; // number of free's that can move back or forward for (i = 1; i < maxVal + 1; i++) { if (prev > 0) { // use prev only max++; prev = cntArr[i]; cntArr[i] = 1; } else { // need to use at least one at i. if (cntArr[i] > 0 && cntArr[i - 1] == 0) { // move left cntArr[i - 1]++; cntArr[i]--; max++; // count for i - 1 } if (cntArr[i] > 0) { max++; // count for i prev = cntArr[i] - 1; } } } // right bound if (prev > 0) max++; System.out.println(min + " " + max); } }
import java.util.Scanner; public class TextMenu { private void printMenu() { System.out.println("=============================================="); System.out.println("Menu tekstowe dla listy 1"); System.out.println("=============================================="); System.out.println(" Aby wybrać zadanie wpisz odpowiednią liczbę"); System.out.println(" 1 -zdanie 1"); System.out.println(" 2 -zdanie 2"); System.out.println(" 3 -zdanie 3"); System.out.println(" 4 -zdanie 4"); System.out.println(" 5 -zdanie 5"); System.out.println(" 6 -zdanie 6"); System.out.println(" 7 -zdanie 7"); System.out.println(" 8 -zdanie 8"); System.out.println(" 9 -zdanie 9"); System.out.println(" 10 -zdanie 10"); System.out.println(" 11 -wyjscie"); System.out.println("=============================================="); } public void textMenu() { while(true) { printMenu(); Scanner menu = new Scanner(System.in); int choice = menu.nextInt(); switch (choice) { case 1: System.out.println("zdanie 1"); ExerciseI1 ex1 = new ExerciseI1(); ex1.run(); break; case 2: System.out.println("zdanie 2"); ExerciseI2 ex2 = new ExerciseI2(); ex2.run(); break; case 3: System.out.println("zdanie 3"); ExerciseI3 ex3 = new ExerciseI3(); ex3.run(); break; case 4: System.out.println("zdanie 4"); ExerciseI4 ex4 = new ExerciseI4(); ex4.run(); break; case 5: System.out.println("zdanie 5"); ExerciseI5 ex5 = new ExerciseI5(); ex5.run(); break; case 6: System.out.println("zdanie 6"); ExerciseI6 ex6 = new ExerciseI6(); ex6.run(); break; case 7: System.out.println("zdanie 7"); ExerciseI7 ex7 = new ExerciseI7(); ex7.run(); break; case 8: System.out.println("zdanie 8"); ExerciseI8 ex8 = new ExerciseI8(); ex8.run(); break; case 9: System.out.println("zdanie 9"); ExerciseI9 ex9 = new ExerciseI9(); ex9.run(); break; case 10: System.out.println("zdanie 10"); ExerciseI10 ex10 = new ExerciseI10(); ex10.run(); break; case 11: System.exit(0); break; default: System.out.println("nie ma tkiej opcji"); break; } } } }
package StackCalculator; import StackCalculator.Exceptions.*; import org.junit.Test; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import static org.junit.Assert.*; public class CalculatorTest { double actual, expected; double epsilon = 0.01; @Test public void ExecuteCommands() throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, UndefinedVariable, IllegalAccessException, VarNameHasAlreadyExist, WrongAmountOfArguments, ClassNotFoundException, CommandNotFound, WrongConfigFileFormat { Calculator calculator = new Calculator(); calculator.ExecuteCommands("in.txt", "cfg.txt"); actual = calculator.getStackTop(); expected = 2.0; assertTrue(Math.abs(actual - epsilon) < epsilon); calculator.ExecuteCommands("in1.txt", "cfg.txt"); actual = calculator.getStackTop(); expected = 28.4632; assertTrue(Math.abs(actual - epsilon) < epsilon); } }
package project; /************************************************************************************************** * Created by: Robert Darrow * Date: 9/24/18 * Description: Interface which declares methods used by multimedia devices. **************************************************************************************************/ public interface MultimediaControl { void play(); void stop(); void previous(); void next(); }
import java.io.*; import java.lang.*; import java.util.*; // #!/usr/bin/python -O // #include <stdio.h> // #include <stdlib.h> // #include <string.h> // #include<stdbool.h> // #include<limits.h> // #include<iostream> // #include<algorithm> // #include<string> // #include<vector> //using namespace std; /* # Author : @RAJ009F # Topic or Type : GFG/LinkedList # Problem Statement : Rearrange Lonkedlist in L1->Ln->L2->ln-1->l3->ln-2..... # Description : # Complexity : ======================= #sample output ---------------------- ======================= */ class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } class ReArrangeLinkedList { Node head; public void push(int data) { Node node = new Node(data); node.next = head; head= node; } public void printList(Node node) { while(node != null) { System.out.print(node.data+" "); node = node.next; } System.out.println(); } public void reArrange(Node node) { if(node==null || node.next == null) return; // split the list: Node mid = node; Node last = node; Node list1 = node; while(last.next!=null && last.next.next!=null) { mid = mid.next; last = last.next.next; } Node list2 = mid.next; mid.next = null; // reverse 2nd list Node prev = null; Node temp = null; while(list2 !=null){ temp = prev; prev = list2; list2 = list2.next; prev.next = temp; } list2 = prev; // reaarnge or merge Node next1; Node next2; while( list1!=null && list2!=null) { next1 = list1.next; next2 = list2.next; list2.next = next1; list1.next = list2; list1 = next1; list2 = next2; } head = node; } public static void main(String args[]) { ReArrangeLinkedList ll = new ReArrangeLinkedList(); ll.push(1); ll.push(2); ll.push(3); ll.push(4); ll.push(5); ll.push(6); ll.push(7); ll.printList(ll.head); ll.reArrange(ll.head); ll.printList(ll.head); } }
package at.paulcosta.springmavenstarter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringMavenStarterApplication { public static void main(String[] args) { SpringApplication.run(SpringMavenStarterApplication.class, args); } }
package info.finny.msvc.service; import org.springframework.cloud.netflix.feign.FeignClient; @FeignClient ("get-article") public interface ArticleClient extends WordFeignClient { }
package com.lanhuai.study.datastructure.list; import java.util.Arrays; /** * @author lanhuai */ public class ArrayList<E> extends AbstractList<E> implements List<E> { private static final int MAX_SIZE = 20; private Object[] elements = new Object[MAX_SIZE]; private int size; @Override public boolean isEmpty() { return size == 0; } @Override public void clear() { for (int x = 0; x < size; x++) { elements[x] = null; } size = 0; } @Override @SuppressWarnings("unchecked") public E get(int index) { checkIndex(index); return (E) elements[index]; } @Override public void insert(E element, int index) { if (element == null) { throw new NullPointerException(); } if (size == MAX_SIZE) { throw new IllegalStateException("ArrayList is full"); } if (index < 0 || index > size) { // 末端只允许在紧接着最后一个元素的后面插入 throw new IndexOutOfBoundsException("Invalid position for insert"); } if (index <= size - 1) { // 在现有元素的位置插入 for (int k = size - 1; k >= index; k--) { elements[k + 1] = elements[k]; } } elements[index] = element; size++; } private void checkIndex(int index) { if (index < 0 || index > size - 1) { throw new IndexOutOfBoundsException(); } } @Override public int indexOf(Object object) { for (int x = 0; x < size; x++) { if (elements[x].equals(object)) { return x; } } return -1; } @Override @SuppressWarnings("unchecked") public E remove(int index) { checkIndex(index); E oldValue = (E) elements[index]; if (index < size - 1) { for (int x = index; x < size - 1; x++) { elements[x] = elements[x + 1]; } } elements[size - 1] = null;// 帮助 GC size--; return oldValue; } @Override public int size() { return size; } @Override public Object[] toArray() { // 偷懒了,用个现成的 return Arrays.copyOf(elements, size); } @Override @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { // 偷懒了,用个现成的 if (a.length < size) { // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elements, size, a.getClass()); } System.arraycopy(elements, 0, a, 0, size); if (a.length > size) { a[size] = null; } return a; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.fastHotel.modeloTabla; import java.util.ArrayList; import javax.swing.table.AbstractTableModel; /** * * @author rudolf */ public class MT_Huespedes extends AbstractTableModel { private final String[] nombre_cabecera; public Class[] tipoColumnas = {Integer.class, String.class, String.class, Integer.class, String.class, String.class, Boolean.class}; private final ArrayList<F_Huesped> lista = new ArrayList<>(); public MT_Huespedes(String[] nombre_cabecera) { this.nombre_cabecera = nombre_cabecera; } public boolean isVacia() { return lista.isEmpty(); } public void agregar_fila(F_Huesped elemento) { lista.add(elemento); fireTableDataChanged(); } public void eliminar_fila(int rowIndex) { lista.remove(rowIndex); fireTableDataChanged(); } public void limpiar_tabla() { lista.clear(); fireTableDataChanged(); } public F_Huesped getFila(int rowIndex) { return lista.get(rowIndex); } @Override public String getColumnName(int columnIndex) { return nombre_cabecera[columnIndex]; } @Override public int getRowCount() { return lista.size(); } @Override public int getColumnCount() { return nombre_cabecera.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: return rowIndex + 1; case 1: return lista.get(rowIndex).getNombreHuesped(); case 2: return lista.get(rowIndex).getFechaNacimiento(); case 3: return lista.get(rowIndex).getEdad(); case 4: return lista.get(rowIndex).getTipoDocumento(); case 5: return lista.get(rowIndex).getCaducidad(); case 6: return lista.get(rowIndex).isSeleccionado(); default: return null; } } @Override public Class getColumnClass(int columnIndex) { return tipoColumnas[columnIndex]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { if (columnIndex == 6) { return true; } else { return false; } } @Override public void setValueAt(Object value, int rowIndex, int columnIndex) { F_Huesped filaResultado = null; if(rowIndex < lista.size()) if(lista.get(rowIndex) != null){ filaResultado = lista.get(rowIndex); switch (columnIndex) { case 6: filaResultado.setSeleccionado((Boolean) value); fireTableCellUpdated(rowIndex, columnIndex); default: } } } }
package utilities.unused; public class CorrectSensorFile { //holds file to log sonars, not currently in use private static SensorFile file; public static SensorFile getInstance(){ if(file == null){ file = new SensorFile(1, "/home/lvuser/RecordSonar.csv"); System.out.println("Creating file"); } return file; } }
package kr.ac.kopo.day08; public class CarMain { public static void main(String[] args) { Car c = new Car(); Car c2 = new Car("아반떼"); Car c3 = new Car(2223, "쿠페"); // c.Car(); c.car(); c2.car(); c3.car(); } }
package com.lidaye.shopIndex.domain.entity; import lombok.Data; import java.io.Serializable; @Data public class Property implements Serializable { private Integer propertyId; private Integer categoryId; private String propertyName; }
package com.example.covid_19tracker; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; public class AboutActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); themeUtils.onActivityCreateSetTheme(this); setContentView(R.layout.activity_about); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Covid-19 Tracker"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } public void github( View v){ Uri uri = Uri.parse("https://github.com/starboi02"); // missing 'http://' will cause crashed Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } public void facebook( View v){ Uri uri = Uri.parse("https://www.facebook.com/varunbhardwaj.064"); // missing 'http://' will cause crashed Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }
package tm.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import tm.pojo.Tourist; import tm.service.TouristService; @Controller @RequestMapping("/touristRegister") public class TouristRegisterController { private TouristService touristService; private Tourist tourist; @Autowired public void setTourist(Tourist tourist) { this.tourist = tourist; } @Autowired public void setTouristService(TouristService touristService) { this.touristService = touristService; } @RequestMapping(method = RequestMethod.GET) public String touristRegister(Model model){ model.addAttribute("tourist",tourist); return "touristRegister"; } @RequestMapping(value = "/submit",method = RequestMethod.POST) public String submit(Tourist tourist){ touristService.add(tourist); return "redirect:/touristRetrieval"; } }
package com.redhat.service.bridge.executor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.redhat.service.bridge.infra.models.filters.StringBeginsWith; import com.redhat.service.bridge.infra.models.filters.StringContains; import com.redhat.service.bridge.infra.models.filters.StringEquals; public class FilterEvaluatorFactoryFEELTest { private static final FilterEvaluatorFactoryFEEL TEMPLATE_FACTORY_FEEL = new FilterEvaluatorFactoryFEEL(); @Test public void testStringEqualsTemplate() { String expected = "if data.name = \"jrota\" then \"OK\" else \"NOT_OK\""; String template = TEMPLATE_FACTORY_FEEL.getTemplateByFilterType(new StringEquals("data.name", "jrota")); Assertions.assertEquals(expected, template); } @Test public void testStringContainsTemplate() { String expectedSingle = "if (contains (data.name, \"jrota\")) then \"OK\" else \"NOT_OK\""; String templateSingle = TEMPLATE_FACTORY_FEEL.getTemplateByFilterType(new StringContains("data.name", "[\"jrota\"]")); Assertions.assertEquals(expectedSingle, templateSingle); String expectedMulti = "if (contains (data.name, \"jacopo\")) or (contains (data.name, \"rota\")) then \"OK\" else \"NOT_OK\""; String templateMulti = TEMPLATE_FACTORY_FEEL.getTemplateByFilterType(new StringContains("data.name", "[\"jacopo\", \"rota\"]")); Assertions.assertEquals(expectedMulti, templateMulti); } @Test public void testStringBeginsWithTemplate() { String expectedSingle = "if (starts with (data.name, \"jrota\")) then \"OK\" else \"NOT_OK\""; String templateSingle = TEMPLATE_FACTORY_FEEL.getTemplateByFilterType(new StringBeginsWith("data.name", "[\"jrota\"]")); Assertions.assertEquals(expectedSingle, templateSingle); String expectedMulti = "if (starts with (data.name, \"jacopo\")) or (starts with (data.name, \"rota\")) then \"OK\" else \"NOT_OK\""; String templateMulti = TEMPLATE_FACTORY_FEEL.getTemplateByFilterType(new StringBeginsWith("data.name", "[\"jacopo\", \"rota\"]")); Assertions.assertEquals(expectedMulti, templateMulti); } }
/** * Copyright 2014 qixin Inc. All rights reserved. * - Powered by Team GOF. - */ package com.igs.qhrzlc.exception; /** * @ClassName: NoUpdateException * @Description: 用一句话描述该文件做什么 * @author jinsongliu * @date 2014-5-17 下午2:28:28 * */ public class NoUpdateException extends Exception { /** * @Fields serialVersionUID */ private static final long serialVersionUID = 1L; public NoUpdateException() { super(); // TODO Auto-generated constructor stub } public NoUpdateException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); // TODO Auto-generated constructor stub } public NoUpdateException(String detailMessage) { super(detailMessage); // TODO Auto-generated constructor stub } public NoUpdateException(Throwable throwable) { super(throwable); // TODO Auto-generated constructor stub } }
package com.ngocdt.tttn.dto; import com.ngocdt.tttn.entity.ReceiptionDetailKey; import lombok.Getter; import lombok.Setter; @Getter @Setter public class ReceiptionDetailKeyDTO { private int productID; private int receiptionID; public static ReceiptionDetailKey toEntity(ReceiptionDetailKeyDTO dto) { if (dto == null) return null; ReceiptionDetailKey key = new ReceiptionDetailKey(); key.setProductID(dto.getProductID()); key.setReceiptionID(dto.getReceiptionID()); return key; } public int getProductID() { return productID; } public void setProductID(int productID) { this.productID = productID; } public int getReceiptionID() { return receiptionID; } public void setReceiptionID(int receiptionID) { this.receiptionID = receiptionID; } }
import java.util.Scanner; public class TempToFarh { public static void main(String[] args) { Scanner in=new Scanner(System.in); double cels,fahre; System.out.print("Enter the temperature in celsius: "); cels=in.nextDouble(); fahre=((cels*9)/5)+32; System.out.println(cels+" celsius in Fahrenhit is: "+fahre); } }
package com.pykj.annotation.projectdemo.entity; import com.pykj.annotation.projectdemo.annntation.PYController; /** * @description: TODO * @author: zhangpengxiang * @time: 2020/4/13 17:58 */ @PYController public class PyController { }
package com.egova.baselibrary.retrofit; import com.egova.baselibrary.BuildConfig; import com.egova.baselibrary.retrofit.interceptor.BaseInterceptor; import com.egova.baselibrary.retrofit.interceptor.logging.Level; import com.egova.baselibrary.retrofit.interceptor.logging.LoggingInterceptor; import java.util.concurrent.TimeUnit; import okhttp3.ConnectionPool; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.internal.platform.Platform; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RetrofitClient { //超时时间 private static final int DEFAULT_TIMEOUT = 60; private static RetrofitClient instance; private static OkHttpClient okHttpClient; private static Retrofit retrofit; private String baseUrl; private Interceptor tokenInterceptor; private RetrofitClient() { } /** * 建议在自己的application中进行初始化网络配置 * @param baseUrl 基础url * @param tokenInterceptor token失效拦截器 * @return */ public RetrofitClient init(String baseUrl, Interceptor tokenInterceptor) { this.baseUrl = baseUrl; this.tokenInterceptor = tokenInterceptor; return instance; } public static RetrofitClient getInstance() { if (instance == null) { synchronized (RetrofitClient.class) { if (instance == null) { instance = new RetrofitClient(); } } } return instance; } private Interceptor getTokenInterceptor() { if (tokenInterceptor == null) { tokenInterceptor = new BaseInterceptor(null); } return tokenInterceptor; } public <T> T create(final Class<T> service) { if (service == null) { throw new RuntimeException("Api service is null!"); } if (retrofit == null) { buildRetrofit(BuildConfig.DEBUG); } return retrofit.create(service); } public void buildRetrofit(boolean isLogEnable) { HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(); okHttpClient = new OkHttpClient.Builder() .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager) .addInterceptor(getTokenInterceptor())//添加token失效监听 .addInterceptor(new LoggingInterceptor .Builder()//构建者模式 .loggable(isLogEnable) //是否开启日志打印 .setLevel(Level.BASIC) //打印的等级 .log(Platform.INFO) // 打印类型 .request("Request") // request的Tag .response("Response")// Response的Tag .addHeader("log-header", "I am the log request header.") // 添加请求头, 注意 key 和 value 都不能是中文 .build() ) .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS)) // 这里你可以根据自己的机型设置同时连接的个数和时间,我这里8个,和每个保持时间为10s .build(); retrofit = new Retrofit.Builder() .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(baseUrl) .build(); } }
package com.gloomy; import static com.gloomy.fileOperation.writeMessage; /** * return and save the error message * @author liuzhen * @date 2018-4-8 * @version 1.0 */ public class errorOperation { private String errorFile; public errorOperation(String errorFile) { this.errorFile = errorFile; } public void writeErrorMessage(String msg){ writeMessage(errorFile,msg); } }
import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { String separator = "****************************"; ArrayList<String> mylist = new ArrayList<String>() {{ add("A1"); add("B"); add("C"); add("C"); add("C"); add("A2"); }}; mylist.forEach((element)->{ System.out.println("loop"+element); }); System.out.println(separator); System.out.println(); System.out.println(); mylist.stream() .filter(s->s.contains("A")) .map(element->element+"*") .forEach((element)->{ System.out.println("loop"+element); }); System.out.println(separator); System.out.println(); System.out.println(); ArrayList<String> myElements = new ArrayList<String>() {{ add("a"); add("b"); add("c"); add("d"); add("e"); add("f"); }}; IntStream.range(0,myElements.size()) .forEach(idx -> myElements.set(idx,myElements.get(idx)+idx) ); myElements.forEach((element)->{ System.out.println("loop"+element); }); ArrayList<String> names = new ArrayList<String>() {{ add("Marco"); add("Francesco"); add("Claudio"); add("Roberto"); add("Cristina"); add("Franco"); }}; List<Student> students=new ArrayList<Student>(); final String classe="5a"; names.forEach(name-> { Student s=new Student(); s.setName(name); students.add(s); }); System.out.println(separator); System.out.println(); System.out.println(); IntStream.range(0,students.size()) .forEach(idx-> { students.get(idx) .setClas(classe); students.get(idx) .setId(idx); }); students.forEach((element)->{ System.out.println("student:"+element); }); } }
package com.dbs.portal.ui.component.view; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.dbs.portal.ui.component.application.IApplication; import com.dbs.portal.ui.layout.HTMLGridLayout; import com.dbs.portal.ui.util.LanguageChanger; import com.vaadin.data.Container; import com.vaadin.data.Property; import com.vaadin.ui.AbstractComponent; import com.vaadin.ui.AbstractLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Panel; import com.vaadin.ui.VerticalLayout; public class BaseTableGridView extends VerticalLayout implements ITableGridResultView{ private HTMLGridLayout gridLayout; private int noOfColumn = 1; private int noOfRow = 1; private int maxRow = 1; private String dataKey = null; private String id = null; private List<GridHeaderField> headerFieldList = null; private Map<String, GridHeaderField> headerNameMapping = new HashMap<String, GridHeaderField>(); private ArrayList<String> spanList = new ArrayList<String>(); private Map<Integer, Integer> sequenceMap = new HashMap<Integer, Integer>(); public BaseTableGridView(){ super(); gridLayout = new HTMLGridLayout(noOfColumn, noOfRow); } public BaseTableGridView(String caption){ super(); gridLayout = new HTMLGridLayout(caption, noOfColumn, noOfRow); } public void setFieldList(Object a){ this.headerFieldList = (ArrayList<GridHeaderField>)a; } @Override public void packLayout() { this.setSizeFull(); LanguageChanger changer = ((IApplication)this.getApplication()).getLanguageChanger(); gridLayout.setLanguageChanger(changer); this.setSizeFull(); this.addComponent(gridLayout.getMainLayout()); } @Override public AbstractComponent getComponent(String dataId) { GridHeaderField field = headerNameMapping.get(dataId); if (field == null) return null; return field.getComponent(); } @Override public void updateContent(Container container) { gridLayout.removeAllComponents(); noOfRow = 1; noOfColumn = 1; maxRow = 1; spanList.clear(); Collection propertyIds = container.getContainerPropertyIds(); int headerHeight = 1; int xConstant = 0; Map<Integer, GridHeaderField> columnFieldMapping = new HashMap<Integer, GridHeaderField>(); Map<Integer, String> columnNameMapping = new HashMap<Integer, String>(); //draw header first... for (int i = 0 ; i < headerFieldList.size() ; i++){ GridHeaderField field = headerFieldList.get(i); expand(field, headerHeight, xConstant); if (!field.isRepeatable()){ if (!field.isChildSpan()){ gridLayout.addLabel(field.getComponent(), field.getxCordinate() + xConstant, field.getyCordinate(), field.getColumnSpan(), field.getRowSpan(), field.getAlignment(), field.isBold()); columnFieldMapping.put(field.getxCordinate() + xConstant, field); columnNameMapping.put(field.getxCordinate() + xConstant , field.getDataId()); }else{ if (field.isSequence()){ if (sequenceMap.containsKey(field.getxCordinate()+xConstant)){ Integer sequence = sequenceMap.get(field.getxCordinate()+xConstant); sequence ++; if (field.getComponent() instanceof Label){ ((Label)field.getComponent()).setValue(((String)((Label)field.getComponent()).getValue())+sequence); } }else{ Integer sequence = 1; sequenceMap.put(field.getxCordinate()+xConstant, sequence); if (field.getComponent() instanceof Label){ ((Label)field.getComponent()).setValue(((String)((Label)field.getComponent()).getValue())+sequence); } } } gridLayout.addLabel(field.getComponent(), field.getxCordinate() + xConstant, field.getyCordinate(), field.getColumnSpan(), field.getRowSpan(), field.getAlignment(), field.isBold()); columnFieldMapping.put(field.getxCordinate() + xConstant, field); columnNameMapping.put(field.getxCordinate() + xConstant , field.getDataId()); } }else{ int repeatCount = 0; List<GridHeaderField> childList = field.getChild(); boolean haveData = true; while (haveData){ if (childList != null && childList.size() > 0){ //check if necessary to draw this group of child for (int j = 0 ; j < childList.size() ; j++){ GridHeaderField childField = childList.get(j); if (childField.getDataId() != null && !"".equals(childField.getDataId())){ if (!propertyIds.contains(childField.getDataId()+"_"+repeatCount)){ haveData = false; }else{ haveData = true; break; } } } if (haveData){ //then draw header expand(field, headerHeight, xConstant); gridLayout.addLabel(new Label(field.getFieldNameKey()), field.getxCordinate() + xConstant , field.getyCordinate(), field.getColumnSpan(), field.getRowSpan(), field.getAlignment(), field.isBold()); //then children for (int j = 0 ; j < childList.size() ; j++){ GridHeaderField childField = childList.get(j); expand(childField, headerHeight, xConstant); gridLayout.addLabel(new Label(childField.getFieldNameKey()), childField.getxCordinate() + xConstant , childField.getyCordinate(), childField.getColumnSpan(), childField.getRowSpan(), childField.getAlignment(), childField.isBold()); if (childField.getDataId() != null && !"".equals(childField.getDataId())){ columnFieldMapping.put(childField.getxCordinate() + xConstant, childField); columnNameMapping.put(childField.getxCordinate() + xConstant, childField.getDataId()+"_"+repeatCount); } } xConstant += field.getRequiredColumn(); } } repeatCount++; } } } int currentRow = noOfRow; //then draw grid table content Collection itemIds = container.getItemIds(); for (Iterator it = itemIds.iterator(); it.hasNext() ; ){ Object itemId = it.next(); if (currentRow + 1 > maxRow){ gridLayout.setRows(currentRow + 1); maxRow = currentRow + 1; } for (Iterator<Integer> itColumn = columnNameMapping.keySet().iterator() ; itColumn.hasNext(); ){ Integer column = itColumn.next(); GridHeaderField headerField = columnFieldMapping.get(column); String dataId = columnNameMapping.get(column); Property property = container.getContainerProperty(itemId, dataId); String value = (String)property.getValue(); Label label = new Label(value); //gridLayout.addField(label, column, currentRow , headerField.getColumnSpan(), headerField.getRowSpan(), headerField.getAlignment(), headerField.isBold()); if (!(spanList.contains((column)+"."+currentRow))){ if (!headerField.isChildSpan()){ gridLayout.addField(label, column, currentRow , headerField.getColumnSpan(), 1, headerField.getAlignment(), headerField.isBold()); }else{ expandChild(headerField, headerHeight, xConstant, currentRow); gridLayout.addField(label, column, currentRow , headerField.getChildColSpan() , headerField.getChildRowSpan() , headerField.getAlignment(), headerField.isBold()); } } if (headerField.isChildSpan() && !(spanList.contains((column)+"."+currentRow))){ if (headerField.getChildColSpan() > 0 && headerField.getChildRowSpan() > 0){ spanList.add((headerField.getxCordinate() + xConstant)+"."+headerField.getyCordinate()); for (int x = headerField.getxCordinate() + xConstant ; x < headerField.getxCordinate() + xConstant + headerField.getChildColSpan() ; x++){ for (int y = currentRow ; y < currentRow + headerField.getChildRowSpan(); y++){ spanList.add(x+"."+y); } } }else if (headerField.getChildColSpan() > 0){ for (int x = headerField.getxCordinate() + xConstant ; x < headerField.getxCordinate() + xConstant + headerField.getChildColSpan() ; x++){ spanList.add(x+"."+headerField.getyCordinate()); } }else if (headerField.getChildRowSpan() > 0){ for (int y = currentRow ; y < currentRow + headerField.getChildRowSpan(); y++){ spanList.add(headerField.getxCordinate() + xConstant+"."+y); } } } } currentRow++; } this.removeAllComponents(); this.addComponent(gridLayout.getMainLayout()); } private void expand(GridHeaderField field, int headerHeight, int xConstant){ if (field.getyCordinate() + field.getRowSpan() > (headerHeight - 1)){ headerHeight = field.getyCordinate() + (field.getRowSpan() == 0 ? 1 : field.getRowSpan()); if (headerHeight > (noOfRow - 1)){ gridLayout.setRows(headerHeight); noOfRow = headerHeight; } } if (xConstant + field.getxCordinate() + field.getColumnSpan() > (noOfColumn-1)){ noOfColumn = xConstant + field.getxCordinate() + (field.getColumnSpan() == 0 ? 1 : field.getColumnSpan()); gridLayout.setColumns(noOfColumn); } } private void expandChild(GridHeaderField field, int headerHeight, int xConstant, int currentRow){ if (field.getyCordinate() + Math.max(field.getRowSpan(), field.getChildRowSpan()) > (headerHeight - 1)){ headerHeight = currentRow + (Math.max(field.getRowSpan(), field.getChildRowSpan()) <=1 ? 1 : Math.max(field.getRowSpan(), field.getChildRowSpan())); if (headerHeight > (noOfRow - 1)){ gridLayout.setRows(headerHeight); maxRow = headerHeight; // noOfRow = headerHeight; } } if (xConstant + field.getxCordinate() + Math.max(field.getColumnSpan(), field.getChildColSpan()) > (noOfColumn-1)){ noOfColumn = xConstant + field.getxCordinate() + (Math.max(field.getColumnSpan(), field.getChildColSpan()) <= 1 ? 1 : Math.max(field.getColumnSpan(),field.getChildColSpan())); gridLayout.setColumns(noOfColumn); } } public String getDataKey(){ return this.dataKey; } public void setDataKey(String dataKey){ this.dataKey = dataKey; } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public List<GridHeaderField> getHeaderFieldList() { return this.headerFieldList; } }
/* * 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 Cricket_score.input; /** * * @author Pankajan */ public interface Input { public String getInput(); }
package com.datagraph.core; import com.datagraph.common.exception.JobException; import com.datagraph.common.Context; import com.datagraph.core.common.ContextImpl; import com.datagraph.common.cons.DBType; import com.datagraph.core.db.datasource.DBDetail; import com.datagraph.core.db.datasource.DatabaseManager; import com.datagraph.core.engine.job.Manager; import com.datagraph.core.engine.scheduler.Scheduler; import com.datagraph.core.utils.Config; import org.apache.commons.configuration.ConfigurationException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by Denny Joseph on 6/4/16. */ public class Bootstrap { public Bootstrap() { } public void start() { //get all configuration data from properties file try { // load properties file Config config = new Config("datagraph.properties"); DBDetail dbDetail = config.getDBDetail(); DatabaseManager dbManager = DatabaseManager.getInstance(); dbManager.createDataSource("DATAGRAPH",dbDetail); DBDetail toplist = new DBDetail("jdbc:mysql://localhost:3306/helloworld", "root","password", "com.mysql.jdbc.Driver",2,DatabaseManager.DBType.MYSQL); dbManager.createDataSource("TOPLIST", toplist); //Create Context object Context context = new ContextImpl(dbManager, DBType.JDBI); //Start Manager Manager manager = new Manager(context); manager.loadJobs(); manager.start(); // start scheduler as daemon int sleepDelay = 1; //ExecutorService schedulerExec = Executors.newFixedThreadPool(1, new ThreadFactoryBuilder().setDaemon(true).build()); Scheduler scheduler = new Scheduler(manager, sleepDelay); ExecutorService schedulerExec = Executors.newSingleThreadExecutor(); schedulerExec.submit(scheduler); schedulerExec.shutdown(); } catch (Exception e) { System.out.println(e); } // create context object and point to taskmanager //start } public static void main(String[] args) { Bootstrap bootstrap = new Bootstrap(); bootstrap.start(); } }
package sort; public class HeapSort { public static void main(String[] args){ // String[] input = { "s", "o", "r", "t", "e", "x", "a", "m", "p", "l" , "e"}; Integer[] input = new Integer[100]; for(int i=0;i<input.length;i++){ input[i] = (int) (100*Math.random()); } HeapSort.sort(input); Sort.show(input); } public static void sort(Comparable[] a){ int N = a.length; // for(int x=N/2-1;x>=0;x--){ // sink(a,x,N); //make binary heap sing sink operation // } for(int x=1;x<=N-1;x++) swim(a, x); // making binary heap using swim operation assert(isBinaryHeap(a)); while(N>0){ swap(a, 0, --N); sink(a, 0, N); assert(Sort.isSorted(a, N, a.length-1)); } } private static void sink(Comparable[] a, int x, int N){ while(2*x + 1<= N-1){ int y = 2*x+ 1; if((y+1<= N-1) && less(a[y], a[y+1])){ y++; } if(less(a[x], a[y])){ swap(a, x, y); x=y; }else{ break; } } } private static boolean less(Comparable x, Comparable y){ return (x.compareTo(y)<0); } private static void swap(Comparable[] a, int x, int y){ Comparable temp = a[x]; a[x]= a[y]; a[y]= temp; } private static boolean isBinaryHeap(Comparable[] a){ int N = a.length; for(int i=N/2-1; i>=0 ;i--){ int y = 2*i+ 1; if(y+1<=N-1 && less(a[y], a[y+1])){ y++; } if(less(a[i], a[y])){ return false; } } return true; } private static void swim(Comparable[] a, int x){ while((x-1)/2>=0 &&less(a[(x-1)/2], a[x])){ swap(a, (x-1)/2, x); x = (x-1)/2; } } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.stdext.attr; import java.util.Collections; import java.util.List; import pl.edu.icm.unity.types.basic.Attribute; import pl.edu.icm.unity.types.basic.AttributeVisibility; /** * Helper class allowing to create integer attributes easily. * @author K. Benedyczak */ public class IntegerAttribute extends Attribute<Long> { public IntegerAttribute(String name, String groupPath, AttributeVisibility visibility, List<Long> values) { super(name, new IntegerAttributeSyntax(), groupPath, visibility, values); } public IntegerAttribute(String name, String groupPath, AttributeVisibility visibility, long value) { this(name, groupPath, visibility, Collections.singletonList(value)); } public IntegerAttribute() { } }
package com.androidsample.wearableapp; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.wearable.activity.WearableActivity; import android.support.wearable.view.WatchViewStub; import android.util.Log; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextClock; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.wearable.DataApi; import com.google.android.gms.wearable.MessageApi; import com.google.android.gms.wearable.Node; import com.google.android.gms.wearable.NodeApi; import com.google.android.gms.wearable.PutDataMapRequest; import com.google.android.gms.wearable.PutDataRequest; import com.google.android.gms.wearable.Wearable; import wearableapp.androidsample.wearableapp.wearableapp.R; public class TrackActivity extends WearableActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { //Path for the messages and data map objects private static final String STEP_COUNT_MESSAGES_PATH = "/StepCount"; private static final String STEP_TRACKING_STATUS_PATH = "/TrackingStatus"; //Step sensors private SensorManager mSensorManager; private Sensor mStepSensor; private GoogleApiClient mGoogleApiClient; private WatchViewStub mWatchViewStub; private ImageView mHeaderIv; private TextView mStepCountTv; /** * Event listener to get updates of step count sensor updates. */ private SensorEventListener mSensorEventListener = new SensorEventListener() { private float mStepOffset; @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { if (mStepOffset == 0) mStepOffset = event.values[0]; if (mStepCountTv != null) { //get the steps count String stepCount = Float.toString(event.values[0] - mStepOffset); mStepCountTv.setText(stepCount); //send the message to the phone, to update the display. //this will send data using MessageAPI, as we don't require guarantee for the delivery. //If the phone is not connected to the watch, this message will be lost. sendStepCountMessage(stepCount); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_track); //Set this to allow activity to enable the ambient mode setAmbientEnabled(); //Get the watch view stub mWatchViewStub = (WatchViewStub) findViewById(R.id.watch_view_stub); mWatchViewStub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() { @Override public void onLayoutInflated(WatchViewStub watchViewStub) { init(watchViewStub); } }); //Connect Google api client to communicate with phone connectGoogleApiClient(); } private void connectGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Wearable.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mGoogleApiClient.connect(); } private void registerStepSensor() { mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mStepSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER); //send update of the step count tracking sensor status to the phone sendTrackingStatusDataMap(true); } @Override protected void onPause() { super.onPause(); //stop sensing if (mGoogleApiClient.isConnected()) { mSensorManager.unregisterListener(mSensorEventListener); //send update of the step count tracking sensor status to the phone sendTrackingStatusDataMap(false); } } @Override protected void onDestroy() { super.onDestroy(); mGoogleApiClient.disconnect(); } /** * Initialize the UI. */ private void init(WatchViewStub watchViewStub) { mHeaderIv = (ImageView) watchViewStub.findViewById(R.id.header_icon); mHeaderIv.setColorFilter(ContextCompat.getColor(this, R.color.icon_red)); mStepCountTv = (TextView) watchViewStub.findViewById(R.id.step_count_tv); } @Override public void onEnterAmbient(Bundle ambientDetails) { super.onEnterAmbient(ambientDetails); //This method will called whenever the application is entering the //ambient mode. Try to simplify the view and display less number of colors updateDisplay(); } @Override public void onUpdateAmbient() { super.onUpdateAmbient(); //This method will called whenever the ambient mode updates. //This will allow you to update the existing view and the //duration period is almost every 1 min. updateDisplay(); } @Override public void onExitAmbient() { //This method will be called whenever device exists from the ambient mode and entered into //interactive mode. updateDisplay(); super.onExitAmbient(); } /** * Update the display based on if the device is in ambiant mode or not. If the device is in * ambient mode this will try to reduce number of colors on the screen and try to simplify the view. */ private void updateDisplay() { if (isAmbient()) { mWatchViewStub.setBackgroundColor(getResources().getColor(android.R.color.black)); mHeaderIv.setColorFilter(ContextCompat.getColor(this, R.color.white)); } else { mWatchViewStub.setBackgroundColor(getResources().getColor(R.color.green)); mHeaderIv.setColorFilter(ContextCompat.getColor(this, R.color.icon_red)); } } /** * Send the current status of the step count tracking weather it is running or not. This message * is important and we should have guarantee of delivery to maintain the state of tracking status * on the phone. That is why we are using DataMap to communicate. So, if the phone is not connected * the message won't get lost. As soon as the phone connects, this status message will pass to the * phone application. * * @param isTracking true if the tracking is running */ private void sendTrackingStatusDataMap(boolean isTracking) { PutDataMapRequest dataMapRequest = PutDataMapRequest.create(STEP_TRACKING_STATUS_PATH); dataMapRequest.getDataMap().putBoolean("status", isTracking); dataMapRequest.getDataMap().putLong("status-time", System.currentTimeMillis()); PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); Wearable.DataApi.putDataItem(mGoogleApiClient, putDataRequest) .setResultCallback(new ResultCallback<DataApi.DataItemResult>() { @Override public void onResult(@NonNull DataApi.DataItemResult dataItemResult) { //check if the message is delivered? //If the status is failed, that means that the currently device is //not connected. The data will get deliver when phone gets connected to the watch. Log.d("Data saving", dataItemResult.getStatus().isSuccess() ? "Success" : "Failed"); } }); } /** * Send the current step count to the phone. This does not require guarantee of message delivery. As, if * the message is not delivered, the count will get updated when second message gets delivered. * So, we are using messages api for passing the data that are usful at the current moment only. * <p> * <B>Note: </B> Messages will block the UI thread while sending. So, we should send messages in background * thread only. * * @param stepCount current step count. */ private void sendStepCountMessage(final String stepCount) { new Thread(new Runnable() { @Override public void run() { NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await(); for (Node node : nodes.getNodes()) { MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage( mGoogleApiClient, node.getId(), STEP_COUNT_MESSAGES_PATH, stepCount.getBytes()).await(); //check if the message is delivered? Log.d("Messages Api", result.getStatus().isSuccess() ? "Sent successfully" : "Sent failed."); } } }).start(); } @Override public void onConnected(@Nullable Bundle bundle) { //register the step sensors registerStepSensor(); } @Override public void onConnectionSuspended(int i) { Toast.makeText(this, "Cannot init GoogleApiClient.", Toast.LENGTH_SHORT).show(); finish(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Toast.makeText(this, "Cannot init GoogleApiClient.", Toast.LENGTH_SHORT).show(); finish(); } }
package com.example.workstudy.jdk; import java.util.ArrayList; public class MemoryLeak { /** * 内存溢出 * Java 垃圾自动回收机制 * GC Roots 到对象的引用链存在,不进行回收,不存在回收,用图论说法就是不可达 * 1.静态字段内存泄漏,静态字段的生命周期和应用程序的生命周期一致 * 2.equals 和hashmap方法实现不当,或者未实现,进行hashmap.put 操作相同对象不应该新增占用内存 * 3.资源关闭,比如数据库连接,输入输出流,会话对象 * 4.ThreadLocal是使用不当,造成memory leak */ private static ArrayList<String> list = new ArrayList<>(); public void populateList(){ for (int i = 0; i < 1000000; i++) { list.add( "hand"); } } public static void main(String[] args) { System.out.println("12"); new MemoryLeak().populateList(); System.out.println("13"); } }
package Variables_and_DataTypes; public class Constants { public static void main(String[] args) { /* ================ Constants ================ * Для указания константы используется служебное слово `final'. * Имя констант пишется большими буквами. */ final double PI = 3.1415; System.out.println("Значение PI=" + PI); //PI=5; ERROR } }
package com.StepDefinition; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import org.junit.Assert; import com.Base.BaseClass; import com.UsingPojoClasses.PutUsing_PutPojo; import com.Utility.Api_Resources; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.restassured.RestAssured; import io.restassured.filter.log.RequestLoggingFilter; import io.restassured.filter.log.ResponseLoggingFilter; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; public class Put_Steps extends BaseClass{ PutUsing_PutPojo put; Api_Resources method; Response response; // JsonPath json; @Given("Initilise URI for PUT Method") public void initilise_URI_for_PUT_Method() throws IOException { BaseSetup(); RestAssured.baseURI = "https://www.change2testautomation.com"; } @Then("Call The Pojo Class for PUT Method") public void call_the_pojo_class_for_put_method() { put = new PutUsing_PutPojo(); } @Then("Get the Response for PUT method") public void get_the_response_for_put_method() throws FileNotFoundException { method = Api_Resources.valueOf("PutResource"); PrintStream log = new PrintStream(new File("./Log File/PutLog.txt")); response = RestAssured.given() .filters(RequestLoggingFilter.logRequestTo(log)) .filters(ResponseLoggingFilter.logResponseTo(log)) .body(put.PutMethod()) .when().put(method.getresource()) .then().statusCode(200).extract().response(); } @Then("Validate PUT Response") public void validate_put_response() { //checkStatuscode logger.info(" ******************* Checking Staus code ***************************** "); int statuscode=response.getStatusCode(); System.out.println("Status code is: " + statuscode); Assert.assertEquals(statuscode, 200); //Check Responce Body logger.info(" ****************** Checking Respose Body *****************************"); String ResponseBody = response.getBody().asString(); System.out.println("Responce Body is: "+ResponseBody); Assert.assertTrue(ResponseBody!=null); } }
package mb.tianxundai.com.toptoken.base; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.icu.text.DecimalFormat; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.PersistableBundle; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import com.ants.theantsgo.AppManager; import com.ants.theantsgo.util.L; import com.finddreams.languagelib.CommSharedUtil; import com.finddreams.languagelib.LanguageType; import com.finddreams.languagelib.MultiLanguageUtil; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import butterknife.ButterKnife; import io.realm.Realm; import io.realm.RealmResults; import mb.tianxundai.com.toptoken.MyApp; import mb.tianxundai.com.toptoken.R; import mb.tianxundai.com.toptoken.aty.SplashShouAty; import mb.tianxundai.com.toptoken.bean.UserBean; import mb.tianxundai.com.toptoken.realm.UserInfo; import mb.tianxundai.com.toptoken.uitl.PreferencesUtils; import static mb.tianxundai.com.toptoken.MyApp.application; /** * Created by dell-pc on 2018/9/27. */ public abstract class BaseAty extends BaseActivity { public String userWalletId = ""; private Realm mRealm; protected RealmResults<UserInfo> userList; public UserInfo mUserInfo = null; @Override protected void onCreate(Bundle savedInstanceState) { AppManager.getInstance().addActivity(this); if (PreferencesUtils.getString(this, "userWalletId") != null) { userWalletId = PreferencesUtils.getString(this, "userWalletId"); } mRealm = Realm.getDefaultInstance(); userList = mRealm.where(UserInfo.class).findAll(); for (int i = 0; i < userList.size(); i++) { mUserInfo = new UserInfo(); if (userList.get(i).getUserWalletId().equals(userWalletId)) { mUserInfo = userList.get(i); break; } } setLanguage(); super.onCreate(savedInstanceState); } // @RequiresApi(api = Build.VERSION_CODES.N) // public static String doubleToString(double num){ // //使用0.00不足位补0,#.##仅保留有效位 // return new DecimalFormat("0.00").format(num); // } // @RequiresApi(api = Build.VERSION_CODES.N) // public static String doubleToString1(double num){ // //使用0.00不足位补0,#.##仅保留有效位 // return new DecimalFormat("0.0").format(num); // } // // @RequiresApi(api = Build.VERSION_CODES.N) // public static String doubleToString3(double num){ // //使用0.00不足位补0,#.##仅保留有效位 // return new DecimalFormat("0.00").format(num); // } // // @RequiresApi(api = Build.VERSION_CODES.N) // public static String doubleToStringthree(double num){ // //使用0.00不足位补0,#.##仅保留有效位 // return new DecimalFormat("0.000").format(num); // } // @RequiresApi(api = Build.VERSION_CODES.N) // public static String doubleToStringfour(double num){ // //使用0.00不足位补0,#.##仅保留有效位 // return new DecimalFormat("0.0000").format(num); // } // // @RequiresApi(api = Build.VERSION_CODES.N) // public static String doubleToString4(double num){ // //使用0.00不足位补0,#.##仅保留有效位 // return new DecimalFormat("0.00").format(num); // } // // @RequiresApi(api = Build.VERSION_CODES.N) // public static String doubleToString6(double num){ // //使用0.00不足位补0,#.##仅保留有效位 // return new DecimalFormat("0.000000").format(num); // } // // @RequiresApi(api = Build.VERSION_CODES.N) // public static String doubleToString8(double num){ // //使用0.00不足位补0,#.##仅保留有效位 // return new DecimalFormat("0.00000000").format(num); // } @Override protected void onDestroy() { super.onDestroy(); mRealm.close(); } public boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); if (!isNum.matches()) { return false; } return true; } protected void attachBaseContext(Context newBase) { super.attachBaseContext(MultiLanguageUtil.attachBaseContext(newBase)); } public static boolean validatePhonePass(String pass) { String passRegex = "(?=.*[a-zA-Z])(?=.*[^a-zA-Z])^.{6,12}$"; return !TextUtils.isEmpty(pass) && pass.matches(passRegex); } protected static PackageInfo getPackageInfo(Context context) { PackageInfo pi = null; try { PackageManager pm = context.getPackageManager(); pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS); return pi; } catch (Exception e) { e.printStackTrace(); } return pi; } /** * 获取本地软件版本号名称 */ public static String getLocalVersionName(Context ctx) { String localVersion = ""; try { PackageInfo packageInfo = ctx.getApplicationContext() .getPackageManager() .getPackageInfo(ctx.getPackageName(), 0); localVersion = packageInfo.versionName; Log.d("TAG", "本软件的版本号。。" + localVersion); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return localVersion; } public Bitmap SaveBitmapFromView(View view) { int w = view.getWidth(); int h = view.getHeight(); Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bmp); view.layout(0, 0, w, h); view.draw(c); // 缩小图片 Matrix matrix = new Matrix(); matrix.postScale(0.5f, 0.5f); //长和宽放大缩小的比例 bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true); DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); saveBitmap(bmp, "sssssssss" + ".JPEG"); return bmp; } /* * 保存文件,文件名为当前日期 */ public void saveBitmap(Bitmap bitmap, String bitName) { String fileName; File file; if (Build.BRAND.equals("Xiaomi")) { // 小米手机 fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName; } else { // Meizu 、Oppo fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName; } file = new File(fileName); if (file.exists()) { file.delete(); } FileOutputStream out; try { out = new FileOutputStream(file); // 格式为 JPEG,照相机拍出的图片为JPEG格式的,PNG格式的不能显示在相册中 if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) { out.flush(); out.close(); // 插入图库 MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), bitName, null); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 发送广播,通知刷新图库的显示 this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName))); toast(me.getResources().getString(R.string.save_success)); } private void setLanguage() { if (!PreferencesUtils.getString(this, "isLan", "").equals("")) { if (PreferencesUtils.getString(this, "isLan", "").equals("1")) { SplashShouAty.LANGUAGE = "zh-Hans"; settingLanguage1(Locale.SIMPLIFIED_CHINESE); } else if (PreferencesUtils.getString(this, "isLan", "").equals("2")) { SplashShouAty.LANGUAGE = "zh-Hant"; settingLanguage1(Locale.TRADITIONAL_CHINESE); } else if (PreferencesUtils.getString(this, "isLan", "").equals("3")) { SplashShouAty.LANGUAGE = "en"; settingLanguage1(Locale.ENGLISH); } else if (PreferencesUtils.getString(this, "isLan", "").equals("4")) { SplashShouAty.LANGUAGE = "ja"; settingLanguage1(Locale.JAPAN); } else if (PreferencesUtils.getString(this, "isLan", "").equals("5")) { SplashShouAty.LANGUAGE = "ko"; settingLanguage1(Locale.KOREAN); } } else { String locale = getResources().getConfiguration().locale.getCountry(); //繁体 if (locale.equalsIgnoreCase(Locale.TRADITIONAL_CHINESE.getCountry())) { SplashShouAty.LANGUAGE = "zh-Hant"; //简体 } else if (locale.equalsIgnoreCase(Locale.SIMPLIFIED_CHINESE.getCountry())) { SplashShouAty.LANGUAGE = "zh-Hans"; //英文 } else if (locale.equalsIgnoreCase(Locale.ENGLISH.getCountry())) { SplashShouAty.LANGUAGE = "en"; //日文 } else if (locale.equalsIgnoreCase(Locale.JAPAN.getCountry())) { SplashShouAty.LANGUAGE = "ja"; //韩文 } else if (locale.equalsIgnoreCase(Locale.KOREAN.getCountry())) { SplashShouAty.LANGUAGE = "ko"; } else { SplashShouAty.LANGUAGE = "zh-Hans"; } } } private void settingLanguage1(Locale targetLocale) { // Configuration configuration = getResources().getConfiguration(); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 8.0需要使用createConfigurationContext处理 return updateResources(context); // // configuration.setLocale(targetLocale); // createConfigurationContext(configuration); // // } else { // // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // configuration.setLocale(targetLocale); // } else { // configuration.locale = targetLocale; // } // Resources resources = getResources(); // DisplayMetrics dm = resources.getDisplayMetrics(); // resources.updateConfiguration(configuration, dm);//语言更换生效的代码! // } } }
package com.shichuang.mobileworkingticket.adapter; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.shichuang.mobileworkingticket.R; import com.shichuang.mobileworkingticket.entify.Empty; import com.shichuang.mobileworkingticket.entify.ReportProcessList; /** * Created by Administrator on 2018/3/16. */ public class ReportProcessAdapter extends BaseQuickAdapter<ReportProcessList.ReportProcessModel, BaseViewHolder> { public ReportProcessAdapter() { super(R.layout.item_report_process); } @Override protected void convert(BaseViewHolder helper, ReportProcessList.ReportProcessModel item) { helper.setText(R.id.tv_process_name, item.getProcessName()); helper.setText(R.id.tv_sum_complete_count, "完成数:" + item.getSumCompleteCount()); String unfinishedCount = "未完成数:" + item.getSumUnfinishedCount(); SpannableString spannableString = new SpannableString(unfinishedCount); spannableString.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.red)), 5, unfinishedCount.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); helper.setText(R.id.tv_sum_unfinished_count, spannableString); } }
package com.aof.component.prm.expense; import java.io.Serializable; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; /** @author Hibernate CodeGenerator */ public class ProjectCostType implements Serializable { /** identifier field */ private String typeid; /** nullable persistent field */ private String typename; private String typeaccount; /** full constructor */ public ProjectCostType(java.lang.String typename) { this.typename = typename; } /** default constructor */ public ProjectCostType() { } public java.lang.String getTypeid() { return this.typeid; } public void setTypeid(java.lang.String typeid) { this.typeid = typeid; } public java.lang.String getTypename() { return this.typename; } public void setTypename(java.lang.String typename) { this.typename = typename; } public java.lang.String getTypeaccount() { return this.typeaccount; } public void setTypeaccount(java.lang.String typeaccount) { this.typeaccount = typeaccount; } public String toString() { return new ToStringBuilder(this) .append("typeid", getTypeid()) .toString(); } public boolean equals(Object other) { if ( !(other instanceof ProjectCostType) ) return false; ProjectCostType castOther = (ProjectCostType) other; return new EqualsBuilder() .append(this.getTypeid(), castOther.getTypeid()) .isEquals(); } public int hashCode() { return new HashCodeBuilder() .append(getTypeid()) .toHashCode(); } }
package Other; import java.util.HashMap; import java.util.List; import java.util.Map; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import Catalogue.*; import Clients.*; import Middle.*; import Processing.*; /** * A very simple test of the system * @author Michael Alexander Smith * @version 2.2 * */ public class StandAloneTest { private final int ORDER_NUMBER = 7; // Order numbers private Product theProduct = null; // Current product private SoldBasket theBought = null; // Bought items private StockReadWriter theStock = null; // Stock list private OrderProcessing theOrder = null; // Order processing system private MiddleFactory mf = null; // Type of access public static void main( String args[] ) { StandAloneTest sat = new StandAloneTest(); sat.simple(); } /** * Parts tested: * Add order into the system, * Get an order to pick, * Inform order picked, * Customer collects */ public void simple() { // Setup the environment mf = new LocalMiddleFactory(); // Local Stock list ... try // { theStock = mf.makeStockReadWriter(); // DataBase access object theOrder = mf.makeOrderProcessing(); // Process order object } catch ( Exception e ) { System.out.println("Exception: " + e.getMessage() ); System.exit(-1); } // Create a SoldBasket containing 1 item of product #0001 theBought = new SoldBasket( ORDER_NUMBER ); // Items bought Product pr = null; try { pr = theStock.getDetails( "0001" ); } catch ( StockException e ) { System.out.println("Exception: " + e.getMessage() ); System.exit(-1); } System.out.println("Product No = " + pr.getProductNo()); System.out.println("Price = " + pr.getPrice() ); System.out.println("Stock level = " + pr.getQuantity() ); System.out.println("Description = " + pr.getDescription() ); pr.setQuantity(1); // Wish to buy 1 item // Now send it to the order processing system theBought.add( pr ); // Add to basket of sold items try { theOrder.newOrder( theBought ); // Create new order in the system } catch (OrderException e ) { System.out.println("Fail: newOrder" ); System.out.println("Exception: " + e.getMessage() ); System.exit(-1); } // Get details about the next order to pick SoldBasket orderPicked = null; // Order picked try { orderPicked = theOrder.getOrderToPick(); // Should be an order to pick } catch ( OrderException e ) { System.out.println("Exception: " + e.getMessage() ); System.exit(-1); } if ( orderPicked != null ) // Error if no order { System.out.println( orderPicked.getDetails() ); } else { System.out.println("Fail: No order to pick?"); System.exit(-1); } // Say that we have picked product from the shelves int orderNo = orderPicked.getOrderNo(); if (orderNo != ORDER_NUMBER ) { System.out.println("Fail: Wrong order number found"); System.exit(-1); } try { theOrder.informOrderPicked( orderNo ); } catch (OrderException e ) { System.out.println("Fail: informOrderPicked(" ); System.out.println("Exception: " + e.getMessage() ); System.exit(-1); } // Inform order processing that the customer has picked up the order boolean ok = true; try { ok = theOrder.informOrderColected( orderNo ); } catch ( OrderException e ) { System.out.println("Fail: informOrderColected" ); System.out.println("Exception: " + e.getMessage() ); System.exit(-1); } if ( ok ) { System.out.println( "Success: Order collected"); } else { System.out.println("Fail: Order not collected" ); } } }
public class Main { public static void main(String[] args) { double miles = SpeedConversion.toMilesPerHour(10.5); System.out.println(miles + "miles"); } }
/* * 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 asteroidy.challenges; /** * * @author Basic */ public class ChallengeZnicMeteority extends ChallengesZniceneMeteority implements IChallenges { private StavChallenge stavChallenge; /** * Konstruktor metody implementuje interface Challenges. * Nastavuje stav ulohy na NEAKTIVNY. */ public ChallengeZnicMeteority() { super(7); this.stavChallenge = StavChallenge.NEAKTIVNY; } /** * * Zadanie pre hraca aby vedel co ma robit. * Nastavy stav challengeu na AKTIVNY. */ public void zadanie() { System.out.println(""); System.out.println("----------------------------------------------------"); System.out.println("Zdravim ta udatny bojovnik"); System.out.println("Tvoja lod sa dostala do zoskupenia meteoritov."); System.out.println("Pokus sa branit co najdlhsie,"); System.out.println("Stavim sa ze ich nedokazes znicit ani " + "5" + ". Hahahaha"); System.out.println("Znic " + "5" + " meteoritov."); System.out.println("----------------------------------------------------"); System.out.println(""); this.stavChallenge = StavChallenge.AKTIVNY; } /** * * Po splneni ulohy sa objavy oznamenie o ukonceni ulohy. * Nastavi stav na SPLNENY. */ public void ukonciChallenge() { System.out.println(""); System.out.println("----------------------------------------------------"); System.out.println("Coze tak ty si este zivy? Haha."); System.out.println("Velmi sa mi paci tvoj zapal."); System.out.println("Ako odmenu odo mna dostavas bonusovy zivot."); System.out.println("Vyuzi ho s rozumom."); System.out.println("----------------------------------------------------"); System.out.println(""); this.stavChallenge = StavChallenge.SPLNENY; } /** * * * @return vrati v akom stave challenge je. */ public StavChallenge getStavChallenge() { return this.stavChallenge; } public void setStavChallenge(StavChallenge stavChallenge) { this.stavChallenge = stavChallenge; } public void setNeaktivny() { this.stavChallenge = StavChallenge.NEAKTIVNY; } }
package com.show.comm.utils.ext; import java.lang.reflect.Type; import java.util.EventObject; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 事件管理器 * * @author heyuhua * @date 2017年9月7日 */ public class EventManager { /** 唯一实例 */ private static final EventManager INSTANCE = new EventManager(); /** 日志 */ private static final Logger LOG = LoggerFactory.getLogger(EventManager.class); /** 侦听器 */ private ConcurrentHashMap<String, ConcurrentLinkedQueue<EventListener<?>>> listeners = new ConcurrentHashMap<>(); /** 线程池 */ private ExecutorService es = Executors.newCachedThreadPool(); private EventManager() { } /** 获得实例 */ public static EventManager getInstance() { return INSTANCE; } /** * 添加事件侦听器 * * @param listener * 事件侦听器 */ public void addEventListener(EventListener<?> listener) { String type = type(listener); ConcurrentLinkedQueue<EventListener<?>> ls = listeners.get(type); if (null == ls) { ls = new ConcurrentLinkedQueue<EventListener<?>>(); } ls.add(listener); listeners.put(type, ls); } /** * 移除事件侦听器 * * @param listener * 事件侦听器 */ public void removeEventListener(EventListener<?> listener) { String type = type(listener); ConcurrentLinkedQueue<EventListener<?>> ls = listeners.get(type); if (null != ls) { ls.remove(listener); } } /** * 移除事件所有侦听器 * * @param eventType * 事件类型 */ public void removeEventListeners(Class<? extends EventObject> eventType) { listeners.remove(eventType.getName()); } /** 解析事件类型 */ private String type(EventListener<?> listener) { Type type = listener.getClass().getGenericInterfaces()[0]; Pattern p = Pattern.compile("\\$EventListener\\<[0-9A-Za-z\\.\\-\\$]*\\>"); Matcher m = p.matcher(type.toString()); if (m.find()) { String s = m.group(); return s.substring(15, s.length() - 1); } throw new RuntimeException("EventObject's name does not compile $EventListener<[0-9A-Za-z.-$]*>"); } /** * 同步事件处理 * * @param event * 事件 */ public void send(EventObject event) { ConcurrentLinkedQueue<EventListener<?>> ls = listeners.get(event.getClass().getName()); if (null != ls && !ls.isEmpty()) { for (EventListener<?> l : ls) { doEvent(l, event); } } } /** * 异步事件处理 * * @param event * 事件 */ public void post(EventObject event) { ConcurrentLinkedQueue<EventListener<?>> ls = listeners.get(event.getClass().getName()); if (null != ls && !ls.isEmpty()) { for (EventListener<?> l : ls) { es.execute(new Runnable() { @Override public void run() { doEvent(l, event); } }); } } } /** 执行事件 */ @SuppressWarnings("unchecked") private void doEvent(EventListener<?> l, EventObject event) { try { EventListener<EventObject> el = (EventListener<EventObject>) l; el.onEvent(event); } catch (Exception e) { LOG.error("Process event failed .", e); } } /** * 事件侦听器 */ public static interface EventListener<T extends EventObject> { /** * 处理事件 * * @param event * 事件 */ public void onEvent(T event); } }
/** * Copyright (C) 2013 by Raphael Michel under the MIT license: * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package de.geeksfactory.opacclient.apis; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CookieStore; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.ClientContext; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import de.geeksfactory.opacclient.NotReachableException; import de.geeksfactory.opacclient.networking.HTTPClient; import de.geeksfactory.opacclient.objects.DetailledItem; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.storage.MetaDataSource; /** * Abstract Base class for OpacApi implementations providing some helper methods * for HTTP */ public abstract class BaseApi implements OpacApi { protected DefaultHttpClient http_client; /** * Initializes HTTP client */ public void init(MetaDataSource metadata, Library library) { http_client = HTTPClient.getNewHttpClient(library); } /** * Perform a HTTP GET request to a given URL * * @param url * URL to fetch * @param encoding * Expected encoding of the response body * @param ignore_errors * If true, status codes above 400 do not raise an exception * @param cookieStore * If set, the given cookieStore is used instead of the built-in * one. * @return Answer content * @throws NotReachableException * Thrown when server returns a HTTP status code greater or * equal than 400. */ public String httpGet(String url, String encoding, boolean ignore_errors, CookieStore cookieStore) throws ClientProtocolException, IOException { HttpGet httpget = new HttpGet(url.replace(" ", "%20").replace("&amp;", "&")); HttpResponse response; if (cookieStore != null) { // Create local HTTP context HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); response = http_client.execute(httpget, localContext); } else { response = http_client.execute(httpget); } if (!ignore_errors && response.getStatusLine().getStatusCode() >= 400) { throw new NotReachableException(); } String html = convertStreamToString(response.getEntity().getContent(), encoding); response.getEntity().consumeContent(); return html; } public String httpGet(String url, String encoding, boolean ignore_errors) throws ClientProtocolException, IOException { return httpGet(url, encoding, ignore_errors, null); } public String httpGet(String url, String encoding) throws ClientProtocolException, IOException { return httpGet(url, encoding, false, null); } @Deprecated public String httpGet(String url) throws ClientProtocolException, IOException { return httpGet(url, getDefaultEncoding(), false, null); } public void downloadCover(DetailledItem item) { if (item.getCover() == null) return; HttpGet httpget = new HttpGet(item.getCover()); HttpResponse response; try { response = http_client.execute(httpget); if (response.getStatusLine().getStatusCode() >= 400) { return; } HttpEntity entity = response.getEntity(); byte[] bytes = EntityUtils.toByteArray(entity); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); item.setCoverBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); return; } } /** * Perform a HTTP POST request to a given URL * * @param url * URL to fetch * @param data * POST data to send * @param encoding * Expected encoding of the response body * @param ignore_errors * If true, status codes above 400 do not raise an exception * @param cookieStore * If set, the given cookieStore is used instead of the built-in * one. * @return Answer content * @throws NotReachableException * Thrown when server returns a HTTP status code greater or * equal than 400. */ public String httpPost(String url, UrlEncodedFormEntity data, String encoding, boolean ignore_errors, CookieStore cookieStore) throws ClientProtocolException, IOException { HttpPost httppost = new HttpPost(url.replace(" ", "%20").replace( "&amp;", "&")); httppost.setEntity(data); HttpResponse response = null; if (cookieStore != null) { // Create local HTTP context HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); response = http_client.execute(httppost, localContext); } else { response = http_client.execute(httppost); } if (!ignore_errors && response.getStatusLine().getStatusCode() >= 400) { throw new NotReachableException(); } String html = convertStreamToString(response.getEntity().getContent(), encoding); response.getEntity().consumeContent(); return html; } public String httpPost(String url, UrlEncodedFormEntity data, String encoding, boolean ignore_errors) throws ClientProtocolException, IOException { return httpPost(url, data, encoding, ignore_errors, null); } public String httpPost(String url, UrlEncodedFormEntity data, String encoding) throws ClientProtocolException, IOException { return httpPost(url, data, encoding, false, null); } @Deprecated public String httpPost(String url, UrlEncodedFormEntity data) throws ClientProtocolException, IOException { return httpPost(url, data, getDefaultEncoding(), false, null); } /** * Reads content from an InputStream into a string * * @param is * InputStream to read from * @return String content of the InputStream */ protected static String convertStreamToString(InputStream is, String encoding) throws IOException { BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(is, encoding)); } catch (UnsupportedEncodingException e1) { reader = new BufferedReader(new InputStreamReader(is)); } StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append((line + "\n")); } } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } protected static String convertStreamToString(InputStream is) throws IOException { return convertStreamToString(is, "ISO-8859-1"); } protected String getDefaultEncoding() { return "ISO-8859-1"; } }
package entity; public class Animal { private String Dono; private int id; private String nome; private int idade; private static int gerarCodigo=100; static int _id=0; public static enum Categoria { CACHORRO,GATO,REPTIL,ROEDOR; } private Categoria categoria; public Animal(String dono, String nome, int idade, Categoria categoria) { this.Dono = dono; this.nome = nome; this.idade=idade; this.id= gerarCodigo++; this.idade = idade; this.id=_id++; this.categoria = categoria; } public int getId() { return id; } public String getNome() { return nome; } public int getIdade() { return idade; } public String getDono() { return Dono; } }
package sign.com.biz.sign.mapper; import java.util.List; import java.util.Map; import sign.com.biz.sign.dto.SignInfoDto; import sign.com.biz.sign.dto.SignTranctionDto; import sign.com.common.PageDto; import tk.mybatis.mapper.common.Mapper; public interface SignMapper extends Mapper<SignInfoDto>{ SignInfoDto insertIntoSignInfo(SignInfoDto signInfoDto); int batchInsertIntoSignInfo(Map<String, Object> param); List<String> selectByIdCollect(String signCollectId); int batchUpdate(Map<String, Object> params); String getIdGroupByIdTask(Map<String, Object> paramMap); PageDto getTaskListByIdUser(PageDto pageDto); List<String> getRoleList(Map<String, Object> paramMap); List<SignInfoDto> getSignDetailById(String idSignInfo); int insertIntoSignLabelInfo(SignInfoDto signInfoDto); void deleteLabelInfoById(String idLabelInfo); void updateLabelInfoById(SignInfoDto signInfoDto); }
package lol; public class SampleServiceTest2 { // // @Test // public void testLol() { // EnumBuster<SampleEnum> buster = new EnumBuster<SampleEnum>(SampleEnum.class, SampleService.class); // SampleService service = new SampleService(); // // SampleEnum THREE = buster.make("THREE", 2); // buster.addByValue(THREE); // // service.handleFoo(THREE); // } }
/** * Copyright (c) 2012 Vasile Popescu (elisescu@gmail.com) * * This source file CANNOT be distributed and/or modified * without prior written consent of the author. **/ package com.hmc.project.hmc.devices.implementations; import java.util.HashMap; import android.os.RemoteException; import android.util.Log; import com.hmc.project.hmc.aidl.IUserRequestsListener; import com.hmc.project.hmc.devices.interfaces.HMCDeviceItf; import com.hmc.project.hmc.devices.interfaces.HMCMediaDeviceItf; import com.hmc.project.hmc.devices.interfaces.HMCServerItf; import com.hmc.project.hmc.devices.proxy.AsyncCommandReplyListener; import com.hmc.project.hmc.devices.proxy.HMCAnonymousDeviceProxy; import com.hmc.project.hmc.devices.proxy.HMCDeviceProxy; import com.hmc.project.hmc.devices.proxy.HMCMediaDeviceProxy; import com.hmc.project.hmc.devices.proxy.HMCServerProxy; import com.hmc.project.hmc.security.HMCOTRManager; import com.hmc.project.hmc.service.HMCInterconnectionConfirmationListener; import com.hmc.project.hmc.service.HMCManager; import com.hmc.project.hmc.ui.DevicesListAdapter; // TODO: Auto-generated Javadoc /** * The Class HMCServerImplementation. */ public class HMCServerImplementation extends HMCDeviceImplementation implements HMCServerItf { /** The Constant TAG. */ private static final String TAG = "HMCServerImplementation"; /** The m hmc interconnection confirmation listener. */ private HMCInterconnectionConfirmationListener mHMCInterconnectionConfirmationListener; /** The adding success. */ private boolean remoteUserReply = true; /** The interconnection success. */ private RemoteReply intconnUsrReply = null; /** The m local hmc info. */ private HMCDevicesList mLocalHMCInfo; // TODO: make sure this is enough and we don't need a vector of pending // remote info given that we anyway can interconnect with a single external // HMC at a time /** The m pending hmc info. */ private HMCDevicesList mPendingHMCInfo = null; /** * Instantiates a new hMC server implementation. * * @param hmcManager the hmc manager * @param thisDeviceDesc the this device desc */ public HMCServerImplementation(HMCManager hmcManager, DeviceDescriptor thisDeviceDesc) { super(hmcManager, thisDeviceDesc); mLocalHMCInfo = new HMCDevicesList(mHMCManager.getHMCName(), false); mDeviceDescriptor.setFingerprint(HMCOTRManager.getInstance().getLocalFingerprint( mDeviceDescriptor.getFullJID())); mLocalHMCInfo.addDevice(mDeviceDescriptor); } /** * Interconnect to. * * @param externalHMCServerAddress the external hmc server address * @return true, if successful */ public boolean interconnectTo(String externalHMCServerAddress) { Log.d(TAG, "Going to intercoonecto to " + externalHMCServerAddress); boolean userConfirmation = false; // TODO: for now use HMCDevicesList to exchange information about the // two HMCs so the user can accept or reject the interconnection. Later // change this and make it more nice HMCDevicesList remoteHMCInfo = null; DeviceDescriptor remoteHMCServerDesc = null; String remoteHMCName = ""; intconnUsrReply = new RemoteReply(); HMCAnonymousDeviceProxy newDevProxy = mHMCManager .createAnonymousProxy(externalHMCServerAddress); newDevProxy.setLocalImplementation(this); // send a hello message to remote anonymous device to negotiate OTR and // get information about device which will be approved by the user mLocalHMCInfo.getDevice(mDeviceDescriptor.getFullJID()).setFingerprint( HMCOTRManager.getInstance().getLocalFingerprint(mDeviceDescriptor.getFullJID())); remoteHMCInfo = newDevProxy.exchangeHMCInfo(mLocalHMCInfo); if (remoteHMCInfo == null) { Log.e(TAG, "info from remote device is null"); mHMCManager.deleteAnonymousProxy(externalHMCServerAddress); return false; } remoteHMCName = remoteHMCInfo.getHMCName(); // we should have only one device in this "pseudo-list". this will be // changed in future according with the previous TODO remoteHMCServerDesc = remoteHMCInfo.getIterator().next(); // check the descriptor received if (remoteHMCServerDesc == null || remoteHMCServerDesc.getDeviceType() != HMCDeviceItf.TYPE.HMC_SERVER) { mHMCManager.deleteAnonymousProxy(externalHMCServerAddress); return false; } String remoteRealFingerprint = HMCOTRManager.getInstance().getRemoteFingerprint( externalHMCServerAddress); if (!remoteRealFingerprint.equals(remoteHMCServerDesc.getFingerprint())) { Log.e(TAG, "The fingerprint received from remote " + remoteHMCServerDesc.getFingerprint() + " doesn't match the one he uses(" + remoteRealFingerprint + ") !!!!!!!!!! "); // mHMCManager.deleteAnonymousProxy(externalHMCServerAddress); // return false; } newDevProxy.setDeviceDescriptor(remoteHMCServerDesc); Log.d(TAG, "Got remote dev desc: " + remoteHMCServerDesc.toString() + "\n Now send the joining request"); // sending the join request newDevProxy.interconnectionRequest(mHMCManager.getHMCName(), new AsyncCommandReplyListener() { public void onReplyReceived(String reply) { intconnUsrReply.setUserReply(Boolean.parseBoolean(reply)); Log.d(TAG, "Got the reply from media deviec user: " + intconnUsrReply.userReply); } }); // now the user should confirm or deny adding the device with // information present in remoteDevDesc data try { userConfirmation = mUserRequestsListener.confirmHMCInterconnection(remoteHMCServerDesc, remoteHMCName); } catch (RemoteException e) { Log.e(TAG, "Couldn't retrieve the user confirmation"); e.printStackTrace(); } Log.d(TAG, "The user replied with :" + userConfirmation); if (!userConfirmation) { // the user didn't confirm the addition of the device mHMCManager.deleteAnonymousProxy(externalHMCServerAddress); return false; } // if remote device accepted to join HMC, then send it the list of // devices // TODO: wait here for the remote reply! use a different variable that I // can wait for and the notify on in when the reply arrived if (intconnUsrReply.userReply) { try { // TODO:elis: shouldn't I use true so that I notify the rest of // devices as well? HMCServerProxy specificDevPrxy = (HMCServerProxy) mHMCManager .promoteAnonymousProxyToExternal(newDevProxy, remoteHMCName, false); // now that we have the specific proxy, add it also in our list // of devices HMCDevicesList devList = specificDevPrxy .exchangeListsOfLocalDevices(getListOfLocalHMCDevices()); mHMCManager.updateListOfExternalDevices(devList, true); } catch (ClassCastException e) { Log.e(TAG, "Fatal error: the remote device we interconnect with " + "is not a HMC server"); e.printStackTrace(); mHMCManager.deleteAnonymousProxy(externalHMCServerAddress); return false; } } return intconnUsrReply.userReply; } /** * Interconnection request. * * @param requesterName the requester name * @param fromDev the from dev * @return true, if successful */ public boolean interconnectionRequest(String requesterName, HMCDeviceProxy fromDev) { boolean retVal = true; // we have received an interconnection request from an external // HMCServer so we send a notification to the user to confirm using the // HMCInterconnectionConfirmationListener if (mPendingHMCInfo != null && mHMCInterconnectionConfirmationListener != null) { // TODO: improve this bad practice to send the "iterator.next()" as // parameter DeviceDescriptor remoteHMCServer = mPendingHMCInfo.getIterator().next(); if (remoteHMCServer == null) { Log.e(TAG, "remote HMCServer descriptor is null"); return false; } // Log.d(TAG, "Ask the user to confirm joining with HMCServer: " + // remoteHMCServer); retVal = mHMCInterconnectionConfirmationListener.confirmHMCInterconnection( remoteHMCServer, mPendingHMCInfo.getHMCName(), mDeviceDescriptor.getFingerprint()); // if the user accepted addition, then add the remote server to our // list of external devices if (retVal) { try { Log.d(TAG, "The user confirmed addition so add the device to the list"); mHMCManager.promoteAnonymousProxyToExternal((HMCAnonymousDeviceProxy) fromDev, mPendingHMCInfo.getHMCName(), false); Log.d(TAG, "The device was promoted"); } catch (ClassCastException e) { e.printStackTrace(); if (!(fromDev instanceof HMCServerProxy)) retVal = false; // this should never happen Log.e(TAG, "FATAL: Received interconnection request from non-anonymous device"); } } } else { Log.e(TAG, "Cannot ask the user for confirmation"); retVal = false; } return retVal; } /** * Gets the list of local hmc devices. * * @return the list of local hmc devices */ private HMCDevicesList getListOfLocalHMCDevices() { HashMap<String, DeviceDescriptor> ourLocalDevices = mHMCManager .getListOfLocalDevicesDescriptors(); HMCDevicesList locDevsList = new HMCDevicesList(mHMCManager.getHMCName(), true, ourLocalDevices); return locDevsList; } private HMCDevicesList getListOfExternalHMCDevices() { HashMap<String, DeviceDescriptor> ourExternalDevices = mHMCManager .getListOfExternalDevicesDescriptors(); HMCDevicesList locDevsList = new HMCDevicesList("external HMC", true, ourExternalDevices); return locDevsList; } /* (non-Javadoc) * @see com.hmc.project.hmc.devices.interfaces.HMCServerItf#getListOfNewHMCDevices(java.lang.String) */ @Override public void getListOfNewHMCDevices(String hashOfMyListOfDevices) { // TODO Auto-generated method stub } /* (non-Javadoc) * @see com.hmc.project.hmc.devices.interfaces.HMCServerItf#removeHMCDevice() */ @Override public void removeHMCDevice() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see com.hmc.project.hmc.devices.implementations.HMCDeviceImplementation#localExecute(int, java.lang.String, com.hmc.project.hmc.devices.proxy.HMCDeviceProxy) */ @Override public String onCommandReceived(int opCode, String params, HMCDeviceProxy fromDev) { String retVal = null; switch (opCode) { case CMD_INTERCONNECTION_REQUEST: retVal = _interconnectionRequest(params, fromDev); break; case CMD_EXCHANGE_HMC_INFO: retVal = _exchangeHMCInfo(params, fromDev); break; case CMD_EXCHANGE_LISTS_OF_LOCAL_DEVICES: retVal = _exchangeListsOfLocalDevices(params, fromDev); break; default: retVal = super.onCommandReceived(opCode, params, fromDev); break; } return retVal; } /** * _exchange lists of local devices. * * @param params the params * @param fromDev the from dev * @return the string */ private String _exchangeListsOfLocalDevices(String params, HMCDeviceProxy fromDev) { HMCDevicesList devList = HMCDevicesList.fromXMLString(params); // update the HMCManager about the new list of devices if (devList != null) { mHMCManager.updateListOfExternalDevices(devList, true); } // now we have to send the list back as well HashMap<String, DeviceDescriptor> list = mHMCManager.getListOfLocalDevicesDescriptors(); devList = new HMCDevicesList(mHMCManager.getHMCName(), false, list); String strList = devList.toXMLString(); Log.d(TAG, "List of local devs to be sent back: " + strList); return strList; } /** * _exchange hmc info. * * @param params the params * @param fromDev the from dev * @return the string */ private String _exchangeHMCInfo(String params, HMCDeviceProxy fromDev) { String retVal = ""; HMCDevicesList localList = exchangeHMCInfo(HMCDevicesList.fromXMLString(params), fromDev); if (localList != null) { retVal = localList.toXMLString(); } return retVal; } /** * Exchange hmc info. * * @param remoteHMCInfo the remote hmc info * @param fromDev the from dev * @return the hMC devices list */ private HMCDevicesList exchangeHMCInfo(HMCDevicesList remoteHMCInfo, HMCDeviceProxy fromDev) { mPendingHMCInfo = remoteHMCInfo; if (remoteHMCInfo != null) { fromDev.setDeviceDescriptor(remoteHMCInfo.getIterator().next()); } mLocalHMCInfo.getDevice(mDeviceDescriptor.getFullJID()).setFingerprint( HMCOTRManager.getInstance().getLocalFingerprint(mDeviceDescriptor.getFullJID())); return mLocalHMCInfo; } /** * _interconnection request. * * @param params the params * @param fromDev the from dev * @return the string */ private String _interconnectionRequest(String params, HMCDeviceProxy fromDev) { return interconnectionRequest(params, fromDev) + ""; } /** * Adds the new device. * * @param fullJID the full jid * @return true, if successful */ public boolean addNewDevice(String fullJID) { Log.d(TAG, "Have to add new device: !!" + fullJID); boolean userConfirmation = false; DeviceDescriptor remoteDevDesc = null; HMCAnonymousDeviceProxy newDevProxy = mHMCManager.createAnonymousProxy(fullJID); newDevProxy.setLocalImplementation(this); // send a hello message to remote anonymous device to negotiate OTR and // get information about device which will be approved by the user if (!mDeviceDescriptor.getFingerprint().equals( HMCOTRManager.getInstance().getLocalFingerprint( mDeviceDescriptor.getFullJID()))) { Log.w(TAG, "Reset the fingerprint from " + mDeviceDescriptor.getFingerprint() + "to " + HMCOTRManager.getInstance() .getLocalFingerprint( mDeviceDescriptor.getFullJID())); mDeviceDescriptor.setFingerprint(HMCOTRManager.getInstance().getLocalFingerprint( mDeviceDescriptor.getFullJID())); } remoteDevDesc = newDevProxy.hello(mDeviceDescriptor); // check the descriptor received if (remoteDevDesc == null) { mHMCManager.deleteAnonymousProxy(fullJID); return false; } String remoteRealFingerprint = HMCOTRManager.getInstance().getRemoteFingerprint(fullJID); if (!remoteRealFingerprint.equals(remoteDevDesc.getFingerprint())) { Log.e(TAG, "The fingerprint received from remote " + remoteDevDesc.getFingerprint() + " doesn't match the one he uses(" + remoteRealFingerprint + ")"); // mHMCManager.deleteAnonymousProxy(fullJID); // return false; } newDevProxy.setDeviceDescriptor(remoteDevDesc); Log.d(TAG, "Got remote dev desc: " + remoteDevDesc.toString() + "\n Now send the joining request"); // sending the join request newDevProxy.joinHMC(mHMCManager.getHMCName(), new AsyncCommandReplyListener() { public void onReplyReceived(String reply) { remoteUserReply = Boolean.parseBoolean(reply); Log.d(TAG, "Got the reply from media deviec user:" + remoteUserReply); } }); // now the user should confirm or deny adding the device with // information present in remoteDevDesc data try { userConfirmation = mUserRequestsListener.confirmDeviceAddition(remoteDevDesc); } catch (RemoteException e) { Log.e(TAG, "Couldn't retrieve the user confirmation"); e.printStackTrace(); } Log.d(TAG, "The user replied with :" + userConfirmation); if (!userConfirmation) { // the user didn't confirm the addition of the device mHMCManager.deleteAnonymousProxy(fullJID); return false; } // if remote device accepted to join HMC, then send it the list of // devices if (remoteUserReply) { // TODO: maybe do all this in a separate thread HMCMediaDeviceProxy specificDevPrxy = (HMCMediaDeviceProxy)mHMCManager .promoteAnonymousProxyToLocal(newDevProxy, true); // now that we have the specific proxy, added also in our list of // devices specificDevPrxy.sendListOfDevices(getListOfLocalHMCDevices()); HMCDevicesList extDevs = getListOfExternalHMCDevices(); if (extDevs.getNoDevices() > 0) { specificDevPrxy.setExternalDevicesList(extDevs); } } return remoteUserReply; } /** * Register device adition confirmation listener. * * @param listener the listener */ public void registerDeviceAditionConfirmationListener( HMCInterconnectionConfirmationListener listener) { mHMCInterconnectionConfirmationListener = listener; } private class RemoteReply { public boolean userReply; public boolean receivedReply; public RemoteReply() { userReply = false; receivedReply = false; } public void setUserReply(boolean usrRepl) { userReply = usrRepl; receivedReply = true; } } }
package patterns.creational.absFactory; /** * @author:lanmengxi@viomi.com.cn * @createtime : * @description * @since version 初始于版本 */ public class HpKeyboard implements Keyboard { @Override public void enter() { System.out.println(" HpKeyboard enter ! "); } }
package xqj; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import javax.xml.xquery.XQConnection; import javax.xml.xquery.XQDataSource; import javax.xml.xquery.XQException; import javax.xml.xquery.XQPreparedExpression; import javax.xml.xquery.XQResultSequence; import net.xqj.exist.ExistXQDataSource; public class xqj22 { public static void main(String[] args) throws IOException{ String zona = ""; BufferedReader teclat = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Quina zona? "); String zona1 = teclat.readLine(); if (zona1.equals("10") || zona1.equals("20") || zona1.equals("30") || zona1.equals("40")) { zona = "/home/cf17jordi.casali/Documents/zona"+zona1+".xml"; } else { System.out.print("Zona equivocada"); System.exit(0); } try{ XQDataSource server = new ExistXQDataSource(); server.setProperty ("serverName", "192.168.56.102"); server.setProperty ("port","8080"); server.setProperty ("user","admin"); server.setProperty ("password","austria"); XQConnection conn = server.getConnection(); XQPreparedExpression consulta;XQResultSequence resultado; consulta = conn.prepareExpression ("for $zona in doc('nueva/zonas.xml')/zonas/zona[cod_zona='"+zona1+"'] return $zona"); resultado = consulta.executeQuery(); BufferedWriter writer = new BufferedWriter(new FileWriter(zona)); writer.write("<?xml version='1.0' encoding='UTF-8'?>"); writer.newLine(); while (resultado.next()) { String cad = resultado.getItemAsString(null); writer.write(cad); writer.newLine(); } consulta = conn.prepareExpression ("for $prod in doc('nueva/productos.xml')/productos/produc[cod_zona='"+zona1+"'] return $prod"); resultado = consulta.executeQuery(); while (resultado.next()) { String cad = resultado.getItemAsString(null); writer.write(cad); writer.newLine(); } writer.close(); conn.close(); } catch (XQException ex) { System.out.println("Error al operar "+ex.getMessage()); } } }
import java.util.Stack; /* public class SubsetGeneration { public generateSubset(int[] arr, int idx, Stack op){ //Stack<String> stack = new Stack<>(); if(idx == arr.length){ op.print(); return; } } } */
package com.forfinance.service; import com.forfinance.dao.CustomerDAO; import com.forfinance.domain.Customer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.internal.verification.VerificationModeFactory; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertSame; @RunWith(MockitoJUnitRunner.class) public class PersistenceServiceImplTest { @Mock @SuppressWarnings("unused") private CustomerDAO customerDAO; @InjectMocks @SuppressWarnings("unused") private PersistenceServiceImpl service; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @Test public void testGetCustomers() throws Exception { List<Customer> customers = new ArrayList<>(); Mockito.doReturn(customers).when(customerDAO).findAll(); List<Customer> result = service.getCustomers(); assertSame(customers, result); Mockito.verify(customerDAO, VerificationModeFactory.times(1)).findAll(); } @Test public void testGetCustomer() throws Exception { Customer customer = new Customer(); Mockito.doReturn(customer).when(customerDAO).findById(1L); Customer result = service.getCustomer(1L); assertSame(result, customer); Mockito.verify(customerDAO, VerificationModeFactory.times(1)).findById(1L); } @Test public void testCreateCustomer() throws Exception { Customer source = new Customer(); Customer destination = new Customer(); Mockito.doReturn(destination).when(customerDAO).create(source); Customer result = service.createCustomer(source); assertSame(result, destination); Mockito.verify(customerDAO, VerificationModeFactory.times(1)).create(source); } }
package com.kheirallah.inc.goldman; public class UglyNumbers { /* Time complexity: O(n^2) Space complexity: O(1) */ private static int getNthUglyNo(int n) { int i = 1; //ugly number count int count = 1; while (n > count) { i++; if (isUgly(i) == 1) { count++; } } return i; } private static int isUgly(int no) { no = maxDivide(no, 2); no = maxDivide(no, 3); no = maxDivide(no, 5); return (no == 1) ? 1 : 0; } private static int maxDivide(int a, int b) { while (a % b == 0) { a = a / b; } return a; } /* Time complexity: O(n) Space complexity: O(n) */ private static int getNthUglyNoDynamic(int n) { int[] ugly = new int[n]; int i2 = 0, i3 = 0, i5 = 0; int next_multiple_of_2 = 2; int next_multiple_of_3 = 3; int next_multiple_of_5 = 5; int next_ugly_no = 1; ugly[0] = 1; for (int i = 1; i < n; i++) { next_ugly_no = Math.min(next_multiple_of_2, Math.min(next_multiple_of_3, next_multiple_of_5)); ugly[i] = next_ugly_no; if (next_ugly_no == next_multiple_of_2) { i2++; next_multiple_of_2 = ugly[i2] * 2; } if (next_ugly_no == next_multiple_of_3) { i3++; next_multiple_of_3 = ugly[i3] * 2; } if (next_ugly_no == next_multiple_of_5) { i5++; next_multiple_of_5 = ugly[i5] * 2; } } return next_ugly_no; } public static void main(String[] args) { System.out.println(getNthUglyNo(150)); System.out.println(getNthUglyNoDynamic(150)); } }
package com.it306.test; /** * This is the class that contains the information of the player * @author Amith Kini * */ //import com.it306.test.UI.*; import java.util.ArrayList; import javax.swing.JLabel; public class Player { public JLabel lbl; private String name; private int index; private int colour; private int money = 0; private int position = 0; private boolean inJail = false; private boolean isOut = false; private ArrayList<Property> properties = new ArrayList<Property>(); public int lastRollValue = 0; public Player(JLabel x){ this.lbl = x; } /** * @return the name */ public String getName() { return name; } /** * @return the colour */ public int getColour() { return colour; } /** * @return the index */ public int getIndex() { return index; } /** * @param index the index to set */ public void setIndex(int index) { this.index = index; } /** * @param colour the colour to set */ public void setColour(int colour) { this.colour = colour; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the money */ public int getMoney() { return money; } /** * @param money : the money to be added * This method adds the money to the player */ public void addMoney(int add) { this.money = this.money + add; } /** * @param money : the money to be subtracted * This method subtracts the money from the player */ public void subMoney(int sub) { this.money = this.money - sub; } /** * @return the position */ public int getPosition() { return position; } /** * @param position the position to set */ public void setPosition(int position) { this.position = position; } /** * @return the inJail */ public boolean isInJail() { return inJail; } /** * @param inJail the inJail to set */ public void setInJail(boolean inJail) { this.inJail = inJail; } /** * @return the isOut */ public boolean getIsOut() { return isOut; } /** * @param isOut the isOut to set */ public void setOut(boolean isOut) { this.isOut = isOut; } public void addProperty(Property a) { properties.add(a); } public ArrayList<Property> getPropertyList() { return properties; } public void removeProperty(Property e) { properties.remove(e); } public ArrayList<Integer> rollDice() { Dice die = new Dice(); int a = die.roll(); int b = die.roll(); int value = a + b; ArrayList<Integer> dice = new ArrayList<Integer>(); dice.add(a); dice.add(b); dice.add(value); lastRollValue = value; if (a == b) { dice.add(1); } else { dice.add(0); } return dice; } public void destroy() { if (getIsOut()) { lbl.setVisible(false); for (Property x : properties) { x.setPowner(null); x.setOwner("Bank"); } } } }
class ejercicio06 { public static void main (String[] args) { System.out.println("Bienvenido al mundo de Java \nPodrás dar solución a muchos problemas"); } }
/** *게이트시스템의 문의하기 빈 *<p> 제목:CpContactBean.java</p> *<p> 설명:문의하기 빈</p> *<p> Copyright: Copright(c)2004</p> *<p> Company: VLC</p> *@author 이창훈 *@version 1.0 */ package com.ziaan.cp; import java.util.ArrayList; import com.ziaan.library.ConfigSet; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.DataBox; import com.ziaan.library.ErrorManager; import com.ziaan.library.ListSet; import com.ziaan.library.MailSet; import com.ziaan.library.RequestBox; import com.ziaan.library.SQLString; public class CpContactBean { private ConfigSet config; private int row; public CpContactBean() { try { config = new ConfigSet(); row = Integer.parseInt(config.getProperty("page.bulletin.row") ); // 이 모듈의 페이지당 row 수를 셋팅한다 } catch( Exception e ) { e.printStackTrace(); } } /** * 사용자가 로그인했다면 사용자의 이름,메일,사번을 검색한다 * @param s_userid 로그인한 사용자의 id * @return DataBox 사용자의 이름,메일,사번을 리턴 */ public static DataBox selectMail(String s_userid) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = null; String sql = ""; DataBox dbox = null; try { list = new ArrayList(); connMgr = new DBConnectionManager(); sql = " select name, email, cono "; sql += " from TZ_member "; sql += " where userid = " + SQLString.Format(s_userid); ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex); throw new Exception( ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return dbox; } /** * 사용자가 운영자에게 메일을 보낸다 * @param box receive from the form object and session * @return isMailed 메일발송에 성공했다면 TRUE를 리턴한다 */ public boolean sendMail(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; String sql = ""; DataBox dbox = null; boolean isMailed = false; ArrayList list = null; String v_toEmail = ""; String v_name = box.getString("p_name"); String v_email = box.getString("p_email"); String v_toCono = box.getString("p_cono"); String v_mailTitle = box.getString("p_title"); String v_content = box.getString("p_content"); String v_hyuncono = box.getString("p_hyuncono"); String v_kiacono = box.getString("p_kiacono"); MailSet mset = new MailSet(box); // 메일 세팅 및 발송 try { list = new ArrayList(); connMgr = new DBConnectionManager(); // ---------------------- 받는 사람의 이메일을 가져온다 ---------------------------- sql = "select email from tz_member where (cono =" + SQLString.Format(v_hyuncono) + "or cono = " + SQLString.Format(v_kiacono) + ")"; ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); list.add(dbox); } // ------------------------------------------------------------------------------------ String v_mailContent = v_content + "답변메일은 " + v_name + "님의 " +v_email + "로 보내주세요!!"; for ( int i = 0; i < list.size(); i++ ) { dbox = (DataBox)list.get(i); v_toEmail = dbox.getString("d_email"); isMailed = mset.sendMail(v_toCono, v_toEmail, v_mailTitle, v_mailContent, "1", ""); } ls.close(); } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { }} if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isMailed; } }
package com.online.spring.core; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ImpCompany { static ApplicationContext context; static{ context=new ClassPathXmlApplicationContext("company.xml"); } public static void main(String[] args) { Company comp; comp=(Company) context.getBean("cmp"); comp.print(); } }
package com.crackerjack.notificationcenter.webService; /** * Created by pratik on 05/06/16. */ public class QuickstartPreferences { public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer"; public static final String REGISTRATION_COMPLETE = "registrationComplete"; }
// Generated code from Butter Knife. Do not modify! package com.zhicai.byteera.activity.community.dynamic.activity; import android.view.View; import butterknife.ButterKnife.Finder; import butterknife.ButterKnife.ViewBinder; public class AddtionFocusOrganizationFragment$$ViewBinder<T extends com.zhicai.byteera.activity.community.dynamic.activity.AddtionFocusOrganizationFragment> implements ViewBinder<T> { @Override public void bind(final Finder finder, final T target, Object source) { View view; view = finder.findRequiredView(source, 2131427671, "field 'mListView' and method 'onItemCilck'"); target.mListView = finder.castView(view, 2131427671, "field 'mListView'"); ((android.widget.AdapterView<?>) view).setOnItemClickListener( new android.widget.AdapterView.OnItemClickListener() { @Override public void onItemClick( android.widget.AdapterView<?> p0, android.view.View p1, int p2, long p3 ) { target.onItemCilck(p1, p2); } }); view = finder.findRequiredView(source, 2131427668, "field 'tvP2P' and method 'onClick'"); target.tvP2P = finder.castView(view, 2131427668, "field 'tvP2P'"); view.setOnClickListener( new butterknife.internal.DebouncingOnClickListener() { @Override public void doClick( android.view.View p0 ) { target.onClick(p0); } }); view = finder.findRequiredView(source, 2131427670, "field 'tvBank' and method 'onClick'"); target.tvBank = finder.castView(view, 2131427670, "field 'tvBank'"); view.setOnClickListener( new butterknife.internal.DebouncingOnClickListener() { @Override public void doClick( android.view.View p0 ) { target.onClick(p0); } }); view = finder.findRequiredView(source, 2131427669, "field 'tvZhongchou' and method 'onClick'"); target.tvZhongchou = finder.castView(view, 2131427669, "field 'tvZhongchou'"); view.setOnClickListener( new butterknife.internal.DebouncingOnClickListener() { @Override public void doClick( android.view.View p0 ) { target.onClick(p0); } }); } @Override public void unbind(T target) { target.mListView = null; target.tvP2P = null; target.tvBank = null; target.tvZhongchou = null; } }
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.aerospike.helper.model; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class Utils { public static Map<String, String> toMap(String source){ HashMap<String, String> responses = new HashMap<String, String>(); String values[] = source.split(";"); for (String value : values) { String nv[] = value.split("="); if (nv.length >= 2) { responses.put(nv[0], nv[1]); } else if (nv.length == 1) { responses.put(nv[0], null); } } return responses.size() != 0 ? responses : null; } public static List<NameValuePair> toNameValuePair(Object parent, Map<String, String> map){ List<NameValuePair> list = new ArrayList<NameValuePair>(); for (String key : map.keySet()){ NameValuePair nvp = new NameValuePair(parent, key, map.get(key)); list.add(nvp); } return list; } public static <T> T[] concat(T[] first, T[] second) { T[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } }
package com.gateway.client; public class WebhookNotification { long timestamp; String orderId; String transactionId; String orderStatus; String amount; public WebhookNotification() { } public WebhookNotification(String orderId, String transactionId, String orderStatus, String amount) { this.timestamp = System.currentTimeMillis(); this.orderId = orderId; this.transactionId = transactionId; this.orderStatus = orderStatus; this.amount = amount; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public void setOrderId(String orderId) { this.orderId = orderId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public void setOrderStatus(String orderStatus) { this.orderStatus = orderStatus; } public void setAmount(String amount) { this.amount = amount; } public long getTimestamp() { return timestamp; } public String getOrderId() { return orderId; } public String getTransactionId() { return transactionId; } public String getOrderStatus() { return orderStatus; } public String getAmount() { return amount; } }
/** * Copyright 2014 David Pettersson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.dp.test; import java.util.HashMap; import java.util.Map; import se.dp.concurrency.AsyncResponseHandler; /** * Process a response and return dummy data */ public abstract class DummyResponseHandler extends AsyncResponseHandler<String, Map<String, Integer>> { /** * Process the response * * @param response * @return */ @Override public Map<String, Integer> processResponse(String response) { try { //Simulate doing some processing Thread.sleep(1000); } catch (InterruptedException ie) { //NOP } Map<String, Integer> map = new HashMap<String, Integer>(); map.put("Test", new Integer(1000)); return map; } }
package arrival.util; import org.apache.commons.lang.ArrayUtils; import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static arrival.util.TimeUtil.ONE_DAY; import static arrival.util.TimeUtil.ONE_HOUR; import static arrival.util.TimeUtil.getTime; /** * 账户,代表一个用户在某个统计方式下的状态,比如他应该是Arrival?Worker?Normal? * 每个账户会保存三个状态: * 1. 最后一次信令时间:lastTime * 2. 最后一次信令时的状态:lastInside * 3. 最近30天的停留时间:lastRecentDays * <p/> * 每次账户收到一个新的信令,都会记录到EditLog里。当发现新收到的信令比之前的信令早时,从EditLog读取之前的一个同步点, * 从这个同步点开始,后续的记录重新排序后重新计算。 */ public class Accout { public enum Status { Worker, Normal, Arrival } private final String imsi; private final UserGroup.Listener listener; private boolean bootStatus = false; // 开机状态:是否在机场开机 private long bootTime = 0L; private long lastStart; //上次统计开始时间,绝对时间。默认值为1970/01/01的0点 private long lastTime = 0; // 上次信令时间 private boolean lastInside = false; // 上次信令是否在里面 private long[] lastRecentDays = new long[30]; // 最近30天的停留时间 private Status lastStatus = Status.Normal; //上次用户状态,默认为Normal private final EditLog<AccountSnapshot> editLog; private AtomicInteger invokeOrderTime = new AtomicInteger(); public Accout(String imsi, UserGroup.Listener listener, EditLog<AccountSnapshot> editLog) throws IOException { this.imsi = imsi; this.listener = listener; this.lastStart = 0; this.editLog = editLog; System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); } public void onSignal(final long time, String eventType, String lac, String cell) throws IOException { boolean isInside = KbUtils.getInstance().isInAirport(lac, cell); if (isInside && eventType.equals(EventTypeConst.EVENT_TURN_ON)) { bootStatus = true; bootTime = time; } AccountSnapshot accountSnapshot = new AccountSnapshot(imsi, time, isInside, true, lastStart, lastTime, lastInside, lastRecentDays, lastStatus); this.editLog.append(accountSnapshot); if (!(time < lastTime)) {//正序 order(time, isInside); } else {//乱序,很少发生,不需要考虑效率 final List<AccountSnapshot> misOrderSnapshots = new ArrayList<AccountSnapshot>(); misOrderSnapshots.add(accountSnapshot); boolean isFindSync = !editLog.forEachFromTail(new EditLog.RecordProcessor<AccountSnapshot>() { @Override public boolean on(AccountSnapshot record) { misOrderSnapshots.add(record); return !record.isSync() || record.getTime() > time || !imsi.equals(record.getImsi()); //找到同步点就不再找了 } }); Collections.sort(misOrderSnapshots); if (isFindSync) { AccountSnapshot sync = misOrderSnapshots.get(0); this.lastInside = sync.isLastInside(); this.lastTime = sync.getLastTime(); this.lastRecentDays = sync.getLastRecentDays(); this.lastStart = sync.getLastStart(); this.lastStatus = sync.getLastStatus(); this.editLog.seek(sync.getLogNameIndex(), sync.getStartPosition()); //转到指定位置,并且清空后面的数据 } else { this.lastInside = false; this.lastTime = 0; this.lastRecentDays = new long[30]; // this.lastStart = this.start; this.lastStatus = Status.Normal; } for (AccountSnapshot snapshot : misOrderSnapshots) { if (snapshot.getImsi().equals(imsi)) { this.editLog.append(new AccountSnapshot(imsi, snapshot.getTime(), snapshot.isInside(), true, lastStart, lastTime, lastInside, lastRecentDays, lastStatus)); order(snapshot.getTime(), snapshot.isInside()); } else { this.editLog.append(snapshot); } } } // if (!isInside) { // if (lastStatus == Status.Arrival && bootStatus && time < bootTime + 2 * ONE_HOUR) { // System.out.println("send sms to imsi:" + imsi + " on " + getTime(time) + "/" + time); // } // bootStatus = false; // bootTime = 0L; // } // if (imsi.equals("100001002990698") && time == 1359568614987L){ // System.out.println(); // } // if (imsi.equals("100001002990698") && time == 1359563843303L){ // System.out.println(); // } check(time); } private void order(long time, boolean inside) { do { if (lastInside) { // 上次在景区则添加本次停留时间 long delta = Math.max((Math.min(time, lastStart + 24 * ONE_HOUR) - lastTime), 0); lastRecentDays[29] += delta; System.out.println("add delta:" + delta + " on time:" + time + "/" + getTime(time) + " lastStart:" + getTime(lastStart) + " lastTime:" + getTime(lastTime)); } if (time < lastStart + ONE_DAY) { lastTime = time; } else { lastTime = lastStart + ONE_DAY; for (int i = 0; i < lastRecentDays.length - 1; i++) { lastRecentDays[i] = lastRecentDays[i + 1]; } lastRecentDays[29] = 0; lastStart += ONE_DAY; if (lastInside && time < lastStart + ONE_DAY) { // 上次在景区则添加本次停留时间 long delta = Math.max((Math.min(time, lastStart + 24 * ONE_HOUR) - lastTime), 0); lastRecentDays[29] += delta; System.out.println("add delta:" + delta + " on time:" + time + "/" + getTime(time) + " lastStart:" + getTime(lastStart) + " lastTime:" + getTime(lastTime)); } } } while (time > lastStart + ONE_DAY - 1); lastTime = time; lastInside = inside; System.out.println(imsi + ":" + ArrayUtils.toString(lastRecentDays) + time + "/" + getTime(time)); } public boolean isWorker() { return lastStatus == Status.Worker; } public void updateGlobleTime(Long globalTime) { if (lastInside && globalTime > lastTime) { order(globalTime, lastInside); check(globalTime); } } private void check(long time) { if (!lastInside) { if (lastStatus == Status.Arrival && bootStatus && time < bootTime + 2 * ONE_HOUR) { this.listener.sendSms(time, imsi); System.out.println("send sms to imsi:" + imsi + " on " + getTime(time) + "/" + time); } bootStatus = false; bootTime = 0L; } int i = 0; long timeSum = 0L; for (long o : lastRecentDays) { if (o > 0) { if ((++i > 9) || ((timeSum += o) > (50 * ONE_HOUR - 1))) { if (lastStatus != Status.Worker) { this.listener.onAddWorker(time, imsi, lastStatus); lastStatus = Status.Worker; } } } } if (lastInside) { if (lastStatus != Status.Worker) { this.listener.onAddArrival(time, imsi, lastStatus); lastStatus = Status.Arrival; } } else { if (lastStatus != Status.Worker) { this.listener.onAddNormal(time, imsi, lastStatus); lastStatus = Status.Normal; } } } }
package cn.itcast.bookstore.cart.wev.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.bookstore.book.domain.Book; import cn.itcast.bookstore.book.service.BookService; import cn.itcast.bookstore.cart.domain.Cart; import cn.itcast.bookstore.cart.domain.CartItem; import cn.itcast.servlet.BaseServlet; public class CartServlet extends BaseServlet { /** * 往购物车中添加商品 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1.得到车 2.得到条目(得到图书和数量) */ Cart cart = (Cart) request.getSession().getAttribute("cart"); System.out.println(cart); /* * 表单传递的只有bid和数量 2.得到条目 >得到图书和数量 >先得到图书的bid,然后通过bid查询数据库得到Book 数量表单中有 */ String bid = request.getParameter("bid"); Book book = new BookService().load(bid); int count = Integer.parseInt(request.getParameter("count")); CartItem cartItem = new CartItem(); cartItem.setBook(book); cartItem.setCount(count); cart.add(cartItem); return "f:/jsps/cart/list.jsp"; } /** * 清空购物车 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cart cart = (Cart) request.getSession().getAttribute("cart"); cart.clear(); return "f:/jsps/cart/list.jsp"; } /** * 删除购物车的商品 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 得到车 得到要删除的bid */ Cart cart = (Cart) request.getSession().getAttribute("cart"); String bid = request.getParameter("bid"); cart.delete(bid); return "f:/jsps/cart/list.jsp"; } }
package com.team9.spda_team9.forum; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.tabs.TabLayout; import com.team9.spda_team9.R; import java.util.ArrayList; public class allcats extends Fragment { private ArrayList<String> categories = new ArrayList<String>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_categories, container, false); View tabLayout1 = view.findViewById(R.id.tablayout1); tabLayout1.setVisibility(View.INVISIBLE); categories.clear(); categories.add("Dating and Relationship"); categories.add("Teenagers"); categories.add("Parenting"); categories.add("Child Care"); categories.add("Finances"); categories.add("Mental Health Support"); RecyclerView recyclerView = view.findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); recyclerView.setAdapter(new CategoryAdapter(categories, getActivity())); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); return view; } }
package idea.spark.in.vehicleowner; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import com.google.firebase.analytics.FirebaseAnalytics; import org.w3c.dom.Text; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; public class ResultScreen extends AppCompatActivity { HandleXML obj; TextView lblowner, lblclass, lblmodel, lblregno, lblregdate, lblchasis, lblengine, lblfuel, lblrto; InterstitialAd mInterstitialAd; private FirebaseAnalytics mFirebaseAnalytics; Timer timer; MyTimerTask myTimerTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result_screen); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { shareRegistrationDetails(); } }); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mFirebaseAnalytics = FirebaseAnalytics.getInstance(this); // Create the InterstitialAd and set the adUnitId. mInterstitialAd = new InterstitialAd(this); // Defined in res/values/strings.xml mInterstitialAd.setAdUnitId(getString(R.string.interstitial_result_ad_unit_id)); requestNewInterstitial(); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { requestNewInterstitial(); } }); AdView mBottomAdView = (AdView) findViewById(R.id.bottomBanner); AdRequest adBottomRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .build(); mBottomAdView.loadAd(adBottomRequest); lblowner=(TextView)findViewById(R.id.lblownername); lblchasis=(TextView)findViewById(R.id.lblchasisno); lblengine=(TextView)findViewById(R.id.lblengineno); lblfuel=(TextView)findViewById(R.id.lblfueltype); lblmodel=(TextView)findViewById(R.id.lblmodel); lblregdate=(TextView)findViewById(R.id.lblregdate); lblregno=(TextView)findViewById(R.id.lblregno); lblclass=(TextView)findViewById(R.id.lblvehclass); lblrto=(TextView)findViewById(R.id.lblrtoname); Bundle bundle = getIntent().getExtras(); obj = bundle.getParcelable("data"); if(obj!=null) { lblowner.setText(obj.getOwner().toUpperCase()); lblchasis.setText(obj.getChasis().toUpperCase()); lblengine.setText(obj.getengine().toUpperCase()); lblfuel.setText(obj.getFuel().toUpperCase()); lblmodel.setText(obj.getMaker().toUpperCase()); lblregdate.setText(obj.getRegdt().toUpperCase() + " (" + obj.getVehAge().toUpperCase().replace("&AMP;","AND") + ")"); lblregno.setText(obj.getRegno().toUpperCase()); lblclass.setText(obj.getVehClass().toUpperCase()); lblrto.setText(obj.getRto().toUpperCase() + ", " + obj.getState().toUpperCase()); } /*final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if(Utils.internetStatus(ResultScreen.this)){ showInterstitial(); } } }, 6000);*/ if(timer != null){ timer.cancel(); } //re-schedule timer here //otherwise, IllegalStateException of //"TimerTask is scheduled already" //will be thrown timer = new Timer(); myTimerTask = new MyTimerTask(); //delay 1000ms, repeat in 5000ms timer.schedule(myTimerTask, 6000, 18000); Bundle analyticsBundle = new Bundle(); analyticsBundle.putString("email",Utils.getPrimaryEmail(this)); analyticsBundle.putString("ad",Utils.internetStatus(this) ? "yes":"no"); mFirebaseAnalytics.logEvent("resultScreen", bundle); } @Override protected void onDestroy() { super.onDestroy(); if (timer!=null){ timer.cancel(); timer = null; } } private void shareRegistrationDetails(){ StringBuilder sb = new StringBuilder(); sb.append(getString(R.string.regdet)); sb.append("\n"); sb.append(getString(R.string.ownername)); sb.append(": "); sb.append(obj.getOwner().toUpperCase()); sb.append("\n"); sb.append(getString(R.string.vehclass)); sb.append(": "); sb.append(obj.getVehClass().toUpperCase()); sb.append("\n"); sb.append(getString(R.string.model)); sb.append(": "); sb.append(obj.getMaker().toUpperCase()); sb.append("\n"); sb.append(getString(R.string.regno)); sb.append(": "); sb.append(obj.getRegno().toUpperCase()); sb.append("\n"); sb.append(getString(R.string.regdt)); sb.append(": "); sb.append(obj.getRegdt().toUpperCase()); sb.append(" ("); sb.append(obj.getVehAge().toUpperCase().replace("&AMP;","AND")); sb.append(")"); sb.append("\n"); sb.append(getString(R.string.chasisno)); sb.append(": "); sb.append(obj.getChasis().toUpperCase()); sb.append("\n"); sb.append(getString(R.string.engineno)); sb.append(": "); sb.append(obj.getengine().toUpperCase()); sb.append("\n"); sb.append(getString(R.string.fueltype)); sb.append(": "); sb.append(obj.getFuel().toUpperCase()); sb.append("\n"); sb.append(getString(R.string.rtoname)); sb.append(": "); sb.append(obj.getRto().toUpperCase()); sb.append(", "); sb.append(obj.getState().toUpperCase()); sb.append("\n"); sb.append("Shared Via Vehicle Owner App, To install this app click following link"); sb.append("\n"); sb.append("https://play.google.com/store/apps/details?id=" + getPackageName()); Intent intent = new Intent("android.intent.action.SEND"); intent.setType("text/plain"); intent.putExtra("android.intent.extra.TEXT", sb.toString()); startActivity(Intent.createChooser(intent, "Share Via")); } private void requestNewInterstitial() { // Request a new ad if one isn't already loaded, hide the button, and kick off the timer. if (!mInterstitialAd.isLoading() && !mInterstitialAd.isLoaded()) { AdRequest adRequest = new AdRequest.Builder().build(); mInterstitialAd.loadAd(adRequest); } } public void showInterstitial() { // Show the ad if it's ready. Otherwise toast and restart the game. if (mInterstitialAd != null && mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } } class MyTimerTask extends TimerTask { @Override public void run() { runOnUiThread(new Runnable(){ @Override public void run() { showInterstitial(); }}); } } }
package com.company; public class Main { public static void main(String[] args) { // write your code here int[] operand1 = {76, 90, 4, 87, 70, 57, 48, 70, 31, 69, 18, 40, 76}; int[] operand2 = {76, 50, 36, 77, 87, 28, 98, 20, 20, 52, 86, 34, 34}; int[] expectedResults = {152, 140, 40, 164, 157, 85, 146, 90, 51, 121, 104, 74, 110}; boolean isPassed = true; for (int i=0; i<operand1.length; i++) { int sum=operand1[i] + operand2[i]; int expected=expectedResults[i]; if (sum != expected) { System.out.println("Expected: "+ expected +"; Actual: "+sum); isPassed = false; } } if (isPassed == true) { System.out.print("Tests PASSED"); } else{ System.out.print("Tests FAILED"); } } }
package com.epam.cdp.java_testng.tetiana_melnychuk.hw2; import java.util.Scanner; abstract public class Flower implements IFlower{ String name; String size; String color; Integer quantity; public Flower(String name, String size, String color, Integer quantity) { this.name = name; this.size = size; this.color = color; this.quantity = quantity; } abstract public double getPrice(); @Override public String getName() { return name; } @Override public String setSize(String flowerName) { Scanner scannerString = new Scanner(System.in); System.out.println("What is the size of the " + flowerName + "s ?"); String size = scannerString.nextLine(); return size; } @Override public String getSize() { return size; } @Override public String setColor(String flowerName) { Scanner scannerString = new Scanner(System.in); System.out.println("What is the color of the " + flowerName + "s ?"); String color = scannerString.nextLine(); return color; } @Override public String getColor() { return color; } @Override public Integer setQuantity(String flowerName) { Scanner scannerString = new Scanner(System.in); System.out.println("How many " + flowerName + "s do you need?"); Integer quantity = scannerString.nextInt(); return quantity; } @Override public Integer getQuantity() { return quantity; } }
package com.yidatec.weixin.security; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.stereotype.Service; import com.yidatec.weixin.common.ParamsConfig; import com.yidatec.weixin.dao.security.SecurityDao; import com.yidatec.weixin.dao.sysmgr.ResourceDao; import com.yidatec.weixin.entity.ParamEntity; import com.yidatec.weixin.message.WeixinHelper; import com.yidatec.weixin.security.tool.AntUrlPathMatcher; import com.yidatec.weixin.security.tool.UrlMatcher; /** * 朄1�7核心的地方,就是提供某个资源对应的权限定义, * 即getAttributes方法返回的结果�1�7�1�7 此类在初始化时,应该取到扄1�7有资源及其对应角色的定义〄1�7 * */ @Service public class CustomInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource { private static final Logger log = LogManager .getLogger(CustomInvocationSecurityMetadataSourceService.class); @Autowired private SecurityDao securityDao; private ResourceDao resourceDao; private UrlMatcher urlMatcher = new AntUrlPathMatcher(); private static Map<String, Collection<ConfigAttribute>> resourceMap = null; public CustomInvocationSecurityMetadataSourceService() { // loadResourceDefine(); } private void loadResourceDefine() { try { /* * //从ClassPath路径下获取指定文件名的配置文件,返回Resource Resource resource = new * ClassPathResource("applicationContext-service.xml"); * //通过XmlBeanFactory解析该文件,获取BeanFactory BeanFactory factory = new * XmlBeanFactory(resource); //获取指定的bean。这里的jdbcTemplate是bean元素的id * securityDao = (ISecurityDao)factory.getBean("securityDao"); // * 在Web服务器启动时,提取系统中的所有权限�1�7�1�7 */ List<String> authorities = securityDao.loadAuthorities(); /* * 应当是资源为key$1�7 权限为value〄1�7 资源通常为url$1�7 权限就是那些以ROLE_为前缄1�7的角色�1�7�1�7 * 丄1�7个资源可以由多个权限来访问�1�7�1�7 */ resourceMap = new HashMap<String, Collection<ConfigAttribute>>(); // 根据权限获取资源 for (String auth_name : authorities) { ConfigAttribute ca = new SecurityConfig(auth_name); List<String> resources = securityDao .loadResourcesByAuthorityName(auth_name); for (String res : resources) { String url = res; /* * 判断资源文件和权限的对应关系,如果已经存在相关的资源url,则要�1�7�过该url为key提取出权限集合,将权限增加到权限集合丄1�7 * 〄1�7 */ if (resourceMap.containsKey(url)) { Collection<ConfigAttribute> value = resourceMap .get(url); value.add(ca); resourceMap.put(url, value); } else { Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>(); atts.add(ca); resourceMap.put(url, atts); } } } System.out.println("load resource ok!"); } catch (Exception ex) { log.error(ex.getMessage()); } } /** * 加载全局参数 * @throws Exception */ public void loadParams() { try { List<ParamEntity> paramList = resourceDao.loadParams(); Map<String, ParamEntity> params = new HashMap<String, ParamEntity>(); for (ParamEntity param : paramList) { params.put(param.getParam_name(), param); } ParamsConfig.setParams(params); } catch (Exception ex) { log.error(ex.getMessage()); } } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } // 根据URL,找到相关的权限配置〄1�7 @Override public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { if (null == resourceMap) { return null; } // object 是一个URL,被用户请求的url〄1�7 String url = ((FilterInvocation) object).getRequestUrl(); int firstQuestionMarkIndex = url.indexOf("?"); if (firstQuestionMarkIndex != -1) { url = url.substring(0, firstQuestionMarkIndex); } Iterator<String> ite = resourceMap.keySet().iterator(); while (ite.hasNext()) { String resURL = ite.next(); if (urlMatcher.pathMatchesUrl(url, resURL)) { return resourceMap.get(resURL); } } return null; } @Override public boolean supports(Class<?> arg0) { return true; } public SecurityDao getSecurityDao() { return securityDao; } public void setSecurityDao(SecurityDao securityDao) { this.securityDao = securityDao; // 注入后就加载资源 loadResourceDefine(); // 初始化TOKEN //WeixinHelper msgHelper = new WeixinHelper(); //WeixinHelper.ACCESS_TOKEN = msgHelper.getAccessToken(); } public void setResourceDao(ResourceDao resourceDao) { this.resourceDao = resourceDao; // 注入后加载全局参数 try { loadParams(); } catch (Exception e) { log.error(e.getMessage()); } } /** * 获取资源MAP["/index.jsp":AUTH_XXX] * * @return */ public static Map<String, Collection<ConfigAttribute>> getResourceMap() { return resourceMap; } public static void setResourceMap( Map<String, Collection<ConfigAttribute>> resourceMap) { CustomInvocationSecurityMetadataSourceService.resourceMap = resourceMap; } }
package com.crawler.tentacle.html.analyse; public interface IHtmlAnalyse { boolean Analyse(String html); String[] Links(); String[] Contents(); }
package com.example.chordnote.data.network.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; public class CommentsResponse extends CommonResponse { public CommentsResponse() { } @Expose @SerializedName("data") private List<Comment> commentList; public ArrayList<Comment> getCommentList() { return new ArrayList<>(commentList); } public void setCommentList(List<Comment> commentList) { this.commentList = commentList; } }
package com.legaoyi.common.gps.util; import java.io.Serializable; import java.util.Arrays; import java.util.List; public class GeoHash implements Serializable { private static final long serialVersionUID = 7584031649203542603L; public static final int MAX_PRECISION = 52; private static final long FIRST_BIT_FLAGGED = 0x8000000000000L; private long bits = 0; private byte significantBits = 0; private GeoHash() {} public static GeoHash toGeoHash(LngLat lnglat) { return toGeoHash(lnglat, MAX_PRECISION); } public static GeoHash toGeoHash(double lng, double lat) { return toGeoHash(new LngLat(lng, lat), MAX_PRECISION); } public static GeoHash toGeoHash(double lng, double lat, int precision) { return toGeoHash(new LngLat(lng, lat), precision); } public static GeoHash toGeoHash(LngLat lnglat, int precision) { GeoHash geoHash = new GeoHash(); boolean isEvenBit = true; double[] latitudeRange = {-90, 90}; double[] longitudeRange = {-180, 180}; while (geoHash.significantBits < precision) { if (isEvenBit) { divideRangeEncode(geoHash, lnglat.getLng(), longitudeRange); } else { divideRangeEncode(geoHash, lnglat.getLat(), latitudeRange); } isEvenBit = !isEvenBit; } geoHash.bits <<= (MAX_PRECISION - precision); return geoHash; } public static GeoHash toGeoHash(long longValue) { return toGeoHash(longValue, MAX_PRECISION); } public static GeoHash toGeoHash(long longValue, int significantBits) { double[] latitudeRange = {-90.0, 90.0}; double[] longitudeRange = {-180.0, 180.0}; boolean isEvenBit = true; GeoHash geoHash = new GeoHash(); String binaryString = Long.toBinaryString(longValue); while (binaryString.length() < MAX_PRECISION) { binaryString = "0".concat(binaryString); } for (int j = 0; j < significantBits; j++) { if (isEvenBit) { divideRangeDecode(geoHash, longitudeRange, binaryString.charAt(j) != '0'); } else { divideRangeDecode(geoHash, latitudeRange, binaryString.charAt(j) != '0'); } isEvenBit = !isEvenBit; } geoHash.bits <<= (MAX_PRECISION - geoHash.significantBits); return geoHash; } public List<GeoHash> getAdjacent() { GeoHash northern = getNorthernNeighbour(); GeoHash eastern = getEasternNeighbour(); GeoHash southern = getSouthernNeighbour(); GeoHash western = getWesternNeighbour(); return Arrays.asList(northern, northern.getEasternNeighbour(), eastern, southern.getEasternNeighbour(), southern, southern.getWesternNeighbour(), western, northern.getWesternNeighbour(), this); } public long toLong() { return bits; } @Override public String toString() { return Long.toBinaryString(bits); } private GeoHash getNorthernNeighbour() { long[] latitudeBits = getRightAlignedLatitudeBits(); long[] longitudeBits = getRightAlignedLongitudeBits(); latitudeBits[0] += 1; latitudeBits[0] = maskLastNBits(latitudeBits[0], latitudeBits[1]); return recombineLatLonBitsToHash(latitudeBits, longitudeBits); } private GeoHash getSouthernNeighbour() { long[] latitudeBits = getRightAlignedLatitudeBits(); long[] longitudeBits = getRightAlignedLongitudeBits(); latitudeBits[0] -= 1; latitudeBits[0] = maskLastNBits(latitudeBits[0], latitudeBits[1]); return recombineLatLonBitsToHash(latitudeBits, longitudeBits); } private GeoHash getEasternNeighbour() { long[] latitudeBits = getRightAlignedLatitudeBits(); long[] longitudeBits = getRightAlignedLongitudeBits(); longitudeBits[0] += 1; longitudeBits[0] = maskLastNBits(longitudeBits[0], longitudeBits[1]); return recombineLatLonBitsToHash(latitudeBits, longitudeBits); } private GeoHash getWesternNeighbour() { long[] latitudeBits = getRightAlignedLatitudeBits(); long[] longitudeBits = getRightAlignedLongitudeBits(); longitudeBits[0] -= 1; longitudeBits[0] = maskLastNBits(longitudeBits[0], longitudeBits[1]); return recombineLatLonBitsToHash(latitudeBits, longitudeBits); } private GeoHash recombineLatLonBitsToHash(long[] latBits, long[] lonBits) { GeoHash geoHash = new GeoHash(); boolean isEvenBit = false; latBits[0] <<= (MAX_PRECISION - latBits[1]); lonBits[0] <<= (MAX_PRECISION - lonBits[1]); double[] latitudeRange = {-90.0, 90.0}; double[] longitudeRange = {-180.0, 180.0}; for (int i = 0; i < latBits[1] + lonBits[1]; i++) { if (isEvenBit) { divideRangeDecode(geoHash, latitudeRange, (latBits[0] & FIRST_BIT_FLAGGED) == FIRST_BIT_FLAGGED); latBits[0] <<= 1; } else { divideRangeDecode(geoHash, longitudeRange, (lonBits[0] & FIRST_BIT_FLAGGED) == FIRST_BIT_FLAGGED); lonBits[0] <<= 1; } isEvenBit = !isEvenBit; } geoHash.bits <<= (MAX_PRECISION - geoHash.significantBits); return geoHash; } private long[] getRightAlignedLatitudeBits() { long copyOfBits = bits << 1; long value = extractEverySecondBit(copyOfBits, getNumberOfLatLonBits()[0]); return new long[] {value, getNumberOfLatLonBits()[0]}; } private long[] getRightAlignedLongitudeBits() { long copyOfBits = bits; long value = extractEverySecondBit(copyOfBits, getNumberOfLatLonBits()[1]); return new long[] {value, getNumberOfLatLonBits()[1]}; } private long extractEverySecondBit(long copyOfBits, int numberOfBits) { long value = 0; for (int i = 0; i < numberOfBits; i++) { if ((copyOfBits & FIRST_BIT_FLAGGED) == FIRST_BIT_FLAGGED) { value |= 0x1; } value <<= 1; copyOfBits <<= 2; } value >>>= 1; return value; } private int[] getNumberOfLatLonBits() { if (significantBits % 2 == 0) { return new int[] {significantBits / 2, significantBits / 2}; } else { return new int[] {significantBits / 2, significantBits / 2 + 1}; } } private long maskLastNBits(long value, long number) { long mask = 0xffffffffffffffffL; mask >>>= (MAX_PRECISION - number); return value & mask; } private static void divideRangeEncode(GeoHash geoHash, double value, double[] range) { double mid = (range[0] + range[1]) / 2; if (value >= mid) { geoHash.addOnBitToEnd(); range[0] = mid; } else { geoHash.addOffBitToEnd(); range[1] = mid; } } private static void divideRangeDecode(GeoHash geoHash, double[] range, boolean isOnBit) { double mid = (range[0] + range[1]) / 2; if (isOnBit) { geoHash.addOnBitToEnd(); range[0] = mid; } else { geoHash.addOffBitToEnd(); range[1] = mid; } } private void addOnBitToEnd() { significantBits++; bits <<= 1; bits = bits | 0x1; } private void addOffBitToEnd() { significantBits++; bits <<= 1; } }
package application.address.business; import application.address.util.RepositoryUser; public class BusinessTCP { // RepositoryUser }
package com.getkhaki.api.bff.domain.services; import java.time.Instant; import java.time.temporal.ChronoUnit; public class DayTimeBlockGenerator extends BaseTimeBlockGenerator { @Override public Instant addUnit(Instant start) { return start.plus(1, ChronoUnit.DAYS); } @Override public Instant minusUnit(Instant instant) { return instant.minus(1, ChronoUnit.DAYS); } }
package edu.gcccd.csis; public class Organization{ //instance variables private String orgName; private int numberOfEmployees; public Organization(String orgName, int numberOfEmployees){ this.orgName=orgName; this.numberOfEmployees=numberOfEmployees; } public Organization(){ this.orgName=null; this.numberOfEmployees=0; } public String getOrgName() { return orgName; } public void setOrgName(String orgName) { this.orgName = orgName; } public int getNumberOfEmployees() { return numberOfEmployees; } public void setNumberOfEmployees(int numberOfEmployees) { this.numberOfEmployees = numberOfEmployees; } @Override public boolean equals(Object o) { if (o instanceof Organization) { Organization org1 = (Organization) o; if (this.orgName.equals(org1.getOrgName()) && this.numberOfEmployees == org1.getNumberOfEmployees()) { return true; } } return false; } @Override public String toString(){ return String.format("Company: "+orgName+"\n"+"Number of Employees: "+numberOfEmployees); } }
package dk.webbies.tscreate.paser.AST; import com.google.javascript.jscomp.parsing.parser.util.SourceRange; import dk.webbies.tscreate.paser.ExpressionVisitor; import java.util.List; /** * Created by Erik Krogh Kristensen on 04-09-2015. */ public class CallExpression extends Expression { private final Expression function; private final List<Expression> args; public CallExpression(SourceRange location, Expression function, List<Expression> args) { super(location); this.function = function; this.args = args; } public Expression getFunction() { return function; } public List<Expression> getArgs() { return args; } @Override public <T> T accept(ExpressionVisitor<T> visitor) { return visitor.visit(this); } }
package org.child.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.child.entity.URole; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author Walle * @since 2019-01-24 */ @Mapper public interface URoleMapper extends BaseMapper<URole> { public List<String> findRoleByUids(List<Long> uids); }
/* * 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 front; import java.io.File; import javax.swing.filechooser.FileFilter; /** * * @author Szlatyka */ public class MapFileFilter extends FileFilter { @Override public boolean accept(File f) { return (f.isDirectory() || getExtension(f.getName()).equals("map")); } @Override public String getDescription() { return "Corridor térkép"; } private String getExtension(String filename) { int i = filename.toLowerCase().lastIndexOf("."); return i > 0 ? filename.substring(i+1) : ""; } }
class State { void display1() { System.out.println("Language spoken: "); } } class Gujarat extends State { void display2() { System.out.println("Gujarati"); } } class Rajasthan extends State { void display() { System.out.println("Rajasthani"); } public static void main(String[] args) { Gujarat g=new Gujarat(); g.display1(); g.display2(); Rajasthan r=new Rajasthan(); r.display1(); r.display3(); } }
package be.darkshark.parkshark.domain.repository; import be.darkshark.parkshark.domain.entity.parkinglot.ParkingLot; import org.springframework.data.repository.CrudRepository; import java.util.Collection; public interface ParkingLotRepository extends CrudRepository<ParkingLot, Long> { @Override Collection<ParkingLot> findAll(); }
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; public class A6LineNumberReadertest { public static void main(String[] args) { LineNumberReader lineread=null; try { lineread = new LineNumberReader(new FileReader("member.txt")); String content = lineread.readLine(); while((content=lineread.readLine())!=null) { int su = lineread.getLineNumber(); System.out.println(su+"\t"+content); } } catch (FileNotFoundException e) { System.out.println(e); }catch(IOException e) { System.out.println(e); } finally{if(lineread!=null);try{lineread.close();}catch(IOException e){};} } }
package telas; import java.awt.EventQueue; import javax.swing.JFrame; import java.awt.Color; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.Font; import javax.swing.SwingConstants; import projeto.model.bean.Fornecedor; import projeto.model.dao.FornecedorDAO; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class FornecedorTela { JFrame frame; private JTextField nome; private JTextField cnpj; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { FornecedorTela window = new FornecedorTela(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public FornecedorTela() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.getContentPane().setBackground(Color.WHITE); frame.setBounds(100, 100, 556, 427); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblCadastroFornecedor = new JLabel("Cadastrar Fornecedor"); lblCadastroFornecedor.setHorizontalAlignment(SwingConstants.CENTER); lblCadastroFornecedor.setFont(new Font("Sitka Small", Font.BOLD | Font.ITALIC, 30)); lblCadastroFornecedor.setBounds(110, 13, 361, 61); frame.getContentPane().add(lblCadastroFornecedor); nome = new JTextField(); nome.setForeground(Color.LIGHT_GRAY); nome.setBounds(189, 102, 153, 31); frame.getContentPane().add(nome); nome.setColumns(10); cnpj = new JTextField(); cnpj.setForeground(Color.LIGHT_GRAY); cnpj.setBounds(189, 161, 153, 31); frame.getContentPane().add(cnpj); cnpj.setColumns(10); JButton btnFinCadForn = new JButton("Finalizar"); btnFinCadForn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Fornecedor fornecedor = new Fornecedor(); FornecedorDAO dao = new FornecedorDAO(); if(cnpj.getText().isEmpty() || nome.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "É necessário o preenchimento de todos os campos"); } else { fornecedor.setCnpj(Long.parseLong(cnpj.getText())); fornecedor.setNome(nome.getText()); dao.Create(fornecedor); frame.dispose(); } } }); btnFinCadForn.setBackground(Color.DARK_GRAY); btnFinCadForn.setForeground(Color.WHITE); btnFinCadForn.setFont(new Font("Times New Roman", Font.PLAIN, 14)); btnFinCadForn.setBounds(209, 217, 97, 25); frame.getContentPane().add(btnFinCadForn); JButton btnVoltarCadForn = new JButton("Voltar"); btnVoltarCadForn.setBackground(Color.DARK_GRAY); btnVoltarCadForn.setForeground(Color.WHITE); btnVoltarCadForn.setFont(new Font("Times New Roman", Font.PLAIN, 14)); btnVoltarCadForn.setBounds(52, 264, 97, 25); btnVoltarCadForn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent argo0) { frame.dispose(); } }); frame.getContentPane().add(btnVoltarCadForn); JLabel lblNomeDoFornecedor = new JLabel("Nome do Fornecedor"); lblNomeDoFornecedor.setBounds(189, 85, 181, 14); frame.getContentPane().add(lblNomeDoFornecedor); JLabel lblCnpj = new JLabel("CNPJ"); lblCnpj.setBounds(189, 144, 46, 14); frame.getContentPane().add(lblCnpj); } }
package crushstudio.crush_studio.DTO; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import org.springframework.beans.factory.annotation.Autowired; @Getter @Setter @AllArgsConstructor public class AdminDTO { private String name; private Long id; private String email; }
/* * @(#){{ table.nameNoPrefix | pascalcase }}UpdateResponse.java * * Copyright (c) 2014-2017 {{ setting.companyName }} 版权所有 * {{ setting.companyCode}}. All rights reserved. * * This software is the confidential and proprietary * information of {{ setting.companyCode}}. * ("Confidential Information"). You shall not disclose * such Confidential Information and shall use it only * in accordance with the terms of the contract agreement * you entered into with {{ setting.companyCode}}. */ package com.{{ setting.companyCode | lower}}.{{ setting.applicationCode | lower}}.response; import com.{{ setting.companyCode | lower}}.framework.base.BaseUpdateResponse; /** * 修改{{ table.meaning }}的响应. * @author {{ setting.developerName}} */ public class {{ table.nameNoPrefix | pascalcase }}UpdateResponse extends BaseUpdateResponse { /** * 更新的{{ table.meaning }}的数目 */ private Long result; public Long getResult() { return result; } public void setResult(Long result) { this.result = result; } }
package run.entity; public class FestivalDTO { String ID; String name; String genre; String description; public FestivalDTO() { } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getID() { return ID; } public void setID(String iD) { ID = iD; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } @Override public String toString() { return "FestivalObj [ID=" + ID + ", name=" + name + ", genre=" + genre + "]"; } public int hashCode() { return Integer.parseInt(this.ID); } public boolean equals(Object obj) { if(obj!=null && obj instanceof FestivalDTO) { String id=((FestivalDTO) obj).getID(); if(id==this.getID()) { return true; } } return false; } }
package Lesson5; import Lesson5.Bus.Bus; import Lesson5.Passenger.Dog; import Lesson5.Passenger.Human; import Lesson5.Passenger.Passenger; import Lesson5.Route.BusStation; import Lesson5.Route.Route; import java.util.ArrayList; public class Main { Route route = new Route(initStation()); Bus bus = new Bus(route); /** * * Поочередный вызов метода обеспечивающего перемещение между станциями */ public static void main(String[] args) { Main mn = new Main(); mn.bus.dispatch(); routeNext(mn); routeNext(mn); routeNext(mn); routeNext(mn); } /** * * @param mn */ private static void routeNext(Main mn) { System.out.println("_______________________________________________________________________"); Passenger[] passangers = mn.route.getBusStations().getPassengers(); ArrayList<Passenger> busPassenger = mn.bus.getBusPassenger(); /** * Автобус приыл на станцию */ mn.bus.arrival(); /** * Осуществляется высадка пассажиров из автобуса */ if (busPassenger.size() > 0) { for (int i = 0; i < busPassenger.size(); i++) { Passenger bp = busPassenger.get(i); if (bp.getStationDestination().equals(mn.route.getBusStations().getStationName())) { mn.bus.passengersOutput(bp); } } } /** * Осуществляется посадка пассажиров в автобус */ if (passangers.length > 0) { for (Passenger passenger : passangers) { mn.bus.passengersInput(passenger); } } /** * Проверка станции прибытия автобуса и сопоставление с конечной остановкой маршрута */ if (mn.route.getNumberStation() < (mn.route.getBusStationLength() - 1)) { mn.bus.dispatch(); } } /** * * @return возвращает инициализированный объект с маршрутом, станциями и пассажирами, которые находятся на данных станциях */ private BusStation[] initStation() { BusStation[] bs = new BusStation[5]; bs[0] = new BusStation("Финтазия.", new Passenger[]{}); bs[1] = new BusStation("бул. Славы", new Passenger[]{new Human("Коля", "Победа 50", new Dog("Rex"))}); bs[2] = new BusStation("Кодак", new Passenger[]{}); bs[3] = new BusStation("Победа 50", new Passenger[]{ new Human("Марго", "ПриватБанк", null), new Human("Валентин", "ПриватБанк", null), new Human("Лена", "ПриватБанк", null), new Human("Петр", "ПриватБанк", null), }); bs[4] = new BusStation("ПриватБанк", new Passenger[]{}); return bs; } }