text
stringlengths
10
2.72M
public class Cab { private String driverName; private String cabNumberPlate; private String driverPhoneNumber; private Location location; private Account driverAccount; private String password; private boolean isAvailable; private CabTypeDetails cabType; public final static double DRIVER_SHARE_PERCENTAGE = 0.8; public Cab(String driverName, String cabNumberPlate, String driverPhoneNumber, CabTypeDetails cabType, String password, Account newAccount) { this.driverName = driverName; this.cabNumberPlate = cabNumberPlate; this.driverPhoneNumber = driverPhoneNumber; this.cabType = cabType; this.password = password; this.isAvailable = false; this.location = null; this.driverAccount = newAccount; } public String getPassword() { return this.password; } public void setLocation(Location location) { this.location = location; } public Location getLocation() { return this.location; } public void setStatus(boolean status) { this.isAvailable = status; } public boolean getStatus() { return this.isAvailable; } public CabTypeDetails getCabTypeDetails() { return this.cabType; } public Account getAccount() { return this.driverAccount; } public String displayLocation() { return "Cab[\nDriver Name = " + driverName + ",\nPhone Number = " + driverPhoneNumber + "\nLocation = " + location.toString() + "\n]"; } @Override public String toString() { return "Cab[\nDriver Name = " + driverName + ",\nNumber Plate = " + cabNumberPlate + ",\nPhone Number = " + driverPhoneNumber + ",\nCab Type = " + cabType.toString() + ",\nCab Available = " + isAvailable + "\n]"; } }
package Model.Tiles; /** * This class creates a new Mosaic Tile * @author csd4351 */ public class MosaicTile extends FindingTile { private MosaicColor color; /** * <b>Constructor:</b> Constructs a new instance of MosaicTile and via the * parent FindingTile sets with the command super, id='id' and sets the private * color = color * @param id * @param color */ public MosaicTile(int id ,MosaicColor color){ super(id); this.color = color; } /** * <b>Accessor:</b> returns the MosaicTile's color * <b>Postcondition:</b> Tile's color has been returned * @return the tile's color */ public MosaicColor getColour() { return color; } /** * <b>Transformer:</b> set the AmphoraTile's color * <b>Postcondition</b> the AmphoraTile's color has been set * @param colour */ public void setColour(MosaicColor colour) { this.color = colour; } }
package webley; @SuppressWarnings("serial") public class WebleyException extends Exception { private String errorCode; public String getErrorCode() { return errorCode; } public String getErrorMessage() { return errorMessage; } private String errorMessage; WebleyException(String eCode, String eMessage){ super(eMessage); this.errorCode=eCode; this.errorMessage = eMessage; } }
package com.Premium.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; @Entity @Table(name = "workStatusFrom") @Data public class WorkStatusFromEntity { @Id @Column(name = "statusFrom") private String statusFrom; }
class Client { private int sex; //0 -> female, 1 -> male private int height; //in cm private int shiftPattern; //0 -> night, 1 -> day, -1 -> unemployed boolean smokes; //true -> smoker, false -> non-smoker String postalDistrict; int age; public Client(int wsex,int wheight, int wshiftPattern, boolean wsmokes, String wpostalDistrict, int wage) { sex = wsex; height = wheight; shiftPattern = wshiftPattern; smokes = wsmokes; postalDistrict = wpostalDistrict; age = wage; } boolean isCompatible(Client otherPerson){ if(sex == otherPerson.retSex()) return false; Client male, female; //since the logical requirements are rather specific about sex ensure //we know which is male and which is female if(sex == 0){ male = otherPerson; female = this; } else { male = this; female = otherPerson; } //requirement that if the male is under 26 the female is to be no more //than 1 year older than him if((male.retAge() < 26) && (female.retAge() > (male.retAge()+1))) return false; //height requirements if((male.retHeight() < female.retHeight()) || (male.retHeight() > (female.retHeight()+25))) return false; //work shift requirements if((male.retShiftPattern() > -1) && (female.retShiftPattern() > -1)) if(male.retShiftPattern() != female.retShiftPattern()) return false; //smoking requirements if(male.retSmokes() != female.retSmokes()) return false; //Postal district requirements if( (male.retPostalDistrict()).equals(female.retPostalDistrict()) ) return true; else return false; } public int retSex() { return sex; } public int retHeight() { return height; } public int retShiftPattern() { return shiftPattern; } public boolean retSmokes() { return smokes; } public String retPostalDistrict() { return postalDistrict; } public int retAge() { return age; } }
package com.joalib.board.svc; import java.sql.Connection; import com.joalib.DAO.DAO; import com.joalib.DTO.BoardDTO; public class BoardModifyProService { public boolean modifyArticle(BoardDTO article) { boolean suc = false; DAO dao = new DAO(); DAO.getinstance(); int i = dao.board_update(article); if(i > 0 ) { suc = true; } return suc; } }
package br.com.candleanalyser.simulation; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.jfree.chart.JFreeChart; import br.com.candleanalyser.advisors.CandleIndicatorAdvisor; import br.com.candleanalyser.advisors.MACDAdvisor; import br.com.candleanalyser.advisors.RSIAdvisor; import br.com.candleanalyser.advisors.StochRSIAdvisor; import br.com.candleanalyser.advisors.StopGainLossAdvisor; import br.com.candleanalyser.advisors.TrendChannelAdvisor; import br.com.candleanalyser.calculators.RSICalculatorStrategy; import br.com.candleanalyser.engine.CandleAnalyser; import br.com.candleanalyser.engine.CandleAnalyser.ReliabilityFilter; import br.com.candleanalyser.engine.CandleFactory; import br.com.candleanalyser.engine.ChartBuilder; import br.com.candleanalyser.engine.Helper; import br.com.candleanalyser.engine.Result; import br.com.candleanalyser.engine.StockPeriod; import br.com.candleanalyser.genetics.simulation.GeneticAdvisorSimulator; import br.com.candleanalyser.genetics.trainner.AdvisorResult; import br.com.candleanalyser.genetics.trainner.GeneticTrainner; import br.com.candleanalyser.genetics.trainner.GeneticTrainnerListenerConsole; import br.com.candleanalyser.genetics.trainner.GeneticTrainnerRunner; import br.com.candleanalyser.genetics.trainner.NeuralAdvisorFactory; public class SimulatorTest extends TestCase { public void testOperateUsingCandleIndicatorAdvisor() throws NumberFormatException, IOException, ParseException { CandleIndicatorAdvisor advisor = new CandleIndicatorAdvisor(); StockPeriod period = CandleFactory.getStockHistoryFromYahoo("DCO", 180); OperationResult result = Simulator.operateUsingAdvisor(10D, 1000D, period, advisor, advisor, 0.5F, 0.5F, null); System.out.println(result); } public static void main(String[] args) throws NumberFormatException, IOException, ParseException, ClassNotFoundException { // trainUntilSuccessful(); // trainOnMultipleStocksAndOperate(); // executeTrendChannelAdvisor(); // executeCandleIndicatorAdvisor(); // executeMACDAdvisor(); // executeRSIAdvisor(); // executeStopGainLossAdvisor(); // executeStochRSIAdvisor(); executeTestAdvisor(); } private static void executeTestAdvisor() throws NumberFormatException, IOException, ParseException { StopGainLossAdvisor sellAdvisor = new StopGainLossAdvisor(0.1F, 0.1F, true); StochRSIAdvisor buyAdvisor = new StochRSIAdvisor(14, RSICalculatorStrategy.SMA_BASED, false, true); StockPeriod period = CandleFactory.getStockHistoryFromYahoo("PETR4.SA", Helper.createDate(15, 1, 2007), Helper.createDate(15, 1, 2008)); PeriodResult result = Simulator.operateUsingAdvisor(10D, 10000D, period, buyAdvisor, sellAdvisor, 0.5F, 0.5F, null); JFreeChart chart = ChartBuilder.createCandleChart(period); ChartBuilder.addOperations(chart, result); ChartBuilder.showGraph(chart, result.getStockPeriod().getStockName()); System.out.println(result); } private static void executeStopGainLossAdvisor() throws NumberFormatException, IOException, ParseException { StopGainLossAdvisor advisor = new StopGainLossAdvisor(0.05F, 0.05F, true); StockPeriod period = CandleFactory.getStockHistoryFromYahoo("VALE5.SA", Helper.createDate(15, 1, 2007), Helper.createDate(15, 1, 2009)); PeriodResult result = Simulator.operateUsingAdvisor(10D, 10000D, period, advisor, advisor, 0.5F, 0.5F, null); JFreeChart chart = ChartBuilder.createCandleChart(period); ChartBuilder.addOperations(chart, result); ChartBuilder.showGraph(chart, result.getStockPeriod().getStockName()); System.out.println(result); } public static void trainUntilSuccessful() throws NumberFormatException, IOException, ParseException, ClassNotFoundException { // EVOLVE ADVISORS System.out.println("TRAINNING WITH MULTIPLE STOCKS"); List<String> trainningStocks = new ArrayList<String>(); trainningStocks.add("VALE5.SA"); // trainningStocks.add("BBDC4.SA"); // trainningStocks.add("TMAR5.SA"); // prepare trainner boolean found = false; while(!found) { NeuralAdvisorFactory factory = new NeuralAdvisorFactory(0.01F); // GeneticAdvisorFactory factory = new SelectiveAdvisorFactory(0.01F); GeneticTrainner gs = new GeneticTrainner(15, 30, 1, 1F, 0.1F, 10000F, 10F, factory, 0.5F, 0.5F, new GeneticTrainnerListenerConsole()); // execute trainning GeneticTrainnerRunner.performTrainning(gs, trainningStocks, Helper.createDate(1, 1, 2004), Helper.createDate(31, 12, 2005), 0.5F, 30, new File("/advisors.ser")); AdvisorResult bestResult = gs.getBestAdvisorResult(); System.out.println(bestResult.getOperationResult()); // OPERATE WITH BEST ADVISOR AFTER THE DATE OF TRAINNING System.out.println("SIMULATING ON A DATE AFTER TRAINNING"); AdvisorResult result = GeneticAdvisorSimulator.executeSimulation(bestResult.getAdvisor(), 0.5F, 0.5F, "ITAU4.SA", Helper.createDate(1, 1, 2006), Helper.createDate(31, 12, 2006), 10000, 10, null); System.out.println(result.getOperationResult()); found = result.getOperationResult().getYield()>0.28F; } } public static void trainOnMultipleStocksAndOperate() throws NumberFormatException, IOException, ParseException, ClassNotFoundException { // EVOLVE ADVISORS System.out.println("TRAINNING WITH MULTIPLE STOCKS"); List<String> trainningStocks = new ArrayList<String>(); // trainningStocks.add("IBOVESPA.SA"); // trainningStocks.add("DCO"); trainningStocks.add("VALE5.SA"); trainningStocks.add("ITAU4.SA"); // trainningStocks.add("BBDC4.SA"); // trainningStocks.add("BRTO4.SA"); // trainningStocks.add("TNLP4.SA"); trainningStocks.add("TMAR5.SA"); // prepare trainner // GeneticAdvisorFactory factory = new NeuralAdvisorFactory(0.5F, 0.5F, 0.01F); // GeneticAdvisorFactory factory = new SelectiveAdvisorFactory(0.01F); // GeneticTrainner gs = new GeneticTrainner(20, 30, 10, 0.01F, 0.02F, 10000F, 10F, factory, 0.5F, 0.5F, new GeneticTrainnerListenerConsole()); // execute trainning // GeneticTrainnerRunner.performTrainning(gs, trainningStocks, Helper.createDate(1, 1, 2003), Helper.createDate(31, 12, 2006), 0.5F, 30, new File("/advisors.ser")); // System.out.println("Total advisors: " + gs.getAdvisorResults().size()); // AdvisorResult bestResult = gs.getBestAdvisorResult(); // System.out.println(bestResult.getOperationResult()); // OPERATE WITH BEST ADVISOR AFTER THE DATE OF TRAINNING // System.out.println("SIMULATING ON A DATE AFTER TRAINNING"); // GeneticAdvisorSimulator.executeSimulationAndShowResults(bestResult.getAdvisor(), 0.5F, 0.5F, "VALE5.SA", Helper.createDate(1, 1, 2008), Helper.createDate(31, 12, 2008), 10000, 10, null); // GeneticAdvisorSimulator.executeSimulationAndShowResults(bestResult.getAdvisor(), 0.5F, 0.5F, "ITAU4.SA", Helper.createDate(1, 1, 2006), Helper.createDate(31, 12, 2006), 10000, 10, null); // GeneticAdvisorSimulator.executeSimulationAndShowResults(bestResult.getAdvisor(), "PETR4.SA", Helper.createDate(1, 1, 2006), Helper.createDate(31, 12, 2006), 10000, 10, null); // GeneticAdvisorSimulator.executeSimulationAndShowResults(bestResult.getAdvisor(), "POSI3.SA", Helper.createDate(1, 1, 2007), Helper.createDate(31, 12, 2007), 10000, 10, null); // GeneticAdvisorSimulator.executeSimulationAndShowResults(bestResult.getAdvisor(), "IBOVESPA.SA", Helper.createDate(1, 1, 2006), Helper.createDate(31, 12, 2006), 10000, 10, null); } public static void executeMACDAdvisor() throws NumberFormatException, IOException, ParseException { MACDAdvisor advisor = new MACDAdvisor(9, 12, 26, 1, 1, 1); StockPeriod period = CandleFactory.getStockHistoryFromYahoo("VALE5.SA", Helper.createDate(15, 1, 2008), Helper.createDate(15, 1, 2009)); PeriodResult result = Simulator.operateUsingAdvisor(10D, 1000D, period, advisor, advisor, 0.5F, 0.5F, null); JFreeChart chart = ChartBuilder.createCandleChart(period); ChartBuilder.addOperations(chart, result); ChartBuilder.showGraph(chart, result.getStockPeriod().getStockName()); System.out.println(result); } public static void executeRSIAdvisor() throws NumberFormatException, IOException, ParseException { RSIAdvisor advisor = new RSIAdvisor(14, RSICalculatorStrategy.SMA_BASED, false, true); StockPeriod period = CandleFactory.getStockHistoryFromYahoo("VALE5.SA", Helper.createDate(15, 1, 2006), Helper.createDate(15, 1, 2009)); PeriodResult result = Simulator.operateUsingAdvisor(10D, 10000D, period, advisor, advisor, 0.5F, 0.5F, null); JFreeChart chart = ChartBuilder.createCandleChart(period); ChartBuilder.addOperations(chart, result); ChartBuilder.showGraph(chart, result.getStockPeriod().getStockName()); System.out.println(result); } public static void executeStochRSIAdvisor() throws NumberFormatException, IOException, ParseException { StochRSIAdvisor advisor = new StochRSIAdvisor(14, RSICalculatorStrategy.SMA_BASED, false, true); StockPeriod period = CandleFactory.getStockHistoryFromYahoo("VALE5.SA", Helper.createDate(15, 1, 2007), Helper.createDate(15, 1, 2009)); PeriodResult result = Simulator.operateUsingAdvisor(10D, 10000D, period, advisor, advisor, 0.5F, 0.5F, null); JFreeChart chart = ChartBuilder.createCandleChart(period); ChartBuilder.addOperations(chart, result); ChartBuilder.showGraph(chart, result.getStockPeriod().getStockName()); //show stoch rsi graph // StochRSICalculator sc = new StochRSICalculator(14, RSICalculatorStrategy.SMA_BASED, false); // List<Double> rsis = new ArrayList<Double>(); // for (Candle candle : period.getCandles()) { // sc.addSample(candle); // rsis.add(sc.getCurrentValue()); // } // ChartBuilder.showGraphForCandles(period); // JFreeChart chart2 = ChartBuilder.createTimeLineChart("VALE5.SA"); // ChartBuilder.addTimeSeries(chart2, "RSI", rsis); // ChartBuilder.showGraph(chart2, "VALE5.SA"); System.out.println(result); } public static void executeTrendChannelAdvisor() throws NumberFormatException, IOException, ParseException { StockPeriod period = CandleFactory.getStockHistoryFromYahoo("VALE5.SA", Helper.createDate(1, 1, 2005), Helper.createDate(1, 1, 2007)); final TrendChannelAdvisor advisor = new TrendChannelAdvisor(20, 0.95F, 1, 2); final JFreeChart chart = ChartBuilder.createCandleChart(period); PeriodResult result = Simulator.operateUsingAdvisor(10D, 1000D, period, advisor, advisor, 0.5F, 0.5F, new SimulatorListener() { public void onSell(Operation currentOperation) { ChartBuilder.addTrendChannel(chart, advisor.getTrendChannel()); // System.out.println("SELL " + // currentOperation.getSellCandle().getClose()); } public void onBuy(Operation currentOperation) { ChartBuilder.addTrendChannel(chart, advisor.getTrendChannel()); // System.out.println("BUY " + // currentOperation.getBuyCandle().getClose()); } }); ChartBuilder.addOperations(chart, result); ChartBuilder.showGraph(chart, "DCO"); System.out.println(result); } public static void executeCandleIndicatorAdvisor() throws NumberFormatException, IOException, ParseException { CandleIndicatorAdvisor advisor = new CandleIndicatorAdvisor(); StockPeriod period = CandleFactory.getStockHistoryFromYahoo("DCO", 120); PeriodResult result = Simulator.operateUsingAdvisor(10D, 1000D, period, advisor, advisor, 0.5F, 0.5F, null); List<Result> indicatorResults = CandleAnalyser.analysePeriod(period, ReliabilityFilter.MODERATE_HIGH); JFreeChart chart = ChartBuilder.createCandleChart(period); ChartBuilder.addOperations(chart, result); ChartBuilder.addIndicators(chart, indicatorResults); ChartBuilder.showGraph(chart, "DCO"); System.out.println(result); } }
/* * Copyright (c) 2004 Steve Northover and Mike Wilson * * 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 part2; import java.io.InputStream; import java.util.Hashtable; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; /** * @author mcq * * This class is not meant to be executed. It contains all of the code * fragments that show up in the Graphics part of the book. This ensures * that the code is all syntactically correct. */ public class Fragments { Display display; Shell shell; Font textFont; Point pt; ImageData theImageData; Image imageWithTransparency; Color backgroundColor; InputStream imageSource; Image[] images; public void f1() { Hashtable h = new Hashtable(); Point p = new Point(100,100); h.put(p, "get the point?"); p.x = 200; // BAD BAD BAD: changes hashCode of p. } public void f2() { Rectangle rectangle1 = new Rectangle(10, 10, 100, 100); Rectangle rectangle2 = new Rectangle(100, 100, 100, 100); Point p = new Point ( (rectangle1.x + rectangle2.x) / 2, (rectangle1.y + rectangle2.y) / 2); } public void f3() { Rectangle rectangle1 = new Rectangle(10, 10, 100, 100); Rectangle rectangle2 = new Rectangle(100, 100, 100, 100); if (rectangle1.intersects(rectangle2)) { Rectangle intersection = rectangle1.intersection(rectangle2); // overlapping area Rectangle union = rectangle1.union(rectangle2); // smallest area covering both } } public void f4() { RGB rgb = new RGB(19, 255, 100); System.out.println(rgb.red+" "+ rgb.green+" "+rgb.blue); } public void f5() { Text text = new Text(shell, SWT.MULTI); Font textFont = text.getFont(); text.dispose(); } public void f6() { List list = new List(shell, SWT.SINGLE); RGB foreground = list.getBackground().getRGB(); RGB background = list.getForeground().getRGB(); list.dispose(); } public void f7() { RGB[] rgbs = theImageData.getRGBs(); Color[] colors = new Color[rgbs.length]; if (rgbs != null) for (int i=0; i<rgbs.length; ++i) colors[i] = new Color(display, rgbs[i]); } public void f8() { Rectangle r = imageWithTransparency.getBounds(); Image img = new Image(display, r.width, r.height); GC gc = new GC(img); gc.setBackground(backgroundColor); gc.fillRectangle(r); gc.drawImage(imageWithTransparency, 0, 0); gc.copyArea(imageWithTransparency, 0, 0); gc.dispose(); } public void f9() { imageWithTransparency = new Image(display, "something.gif"); Button b = new Button(shell, SWT.PUSH); imageWithTransparency.setBackground(b.getBackground()); b.setImage(imageWithTransparency); } }
package duke; import java.util.ArrayList; import java.util.List; import duke.task.PriorityLevel; import duke.task.Task; /** * Supports actions involving adding, removing and storing tasks in a list. */ public class TaskList { /** * List of tasks. */ private List<Task> tasks; /** * Creates an empty TaskList object. */ public TaskList() { tasks = new ArrayList<>(); } /** * Creates a TaskList object using an existing list of tasks. * @param taskArr List of tasks. */ public TaskList(List<Task> taskArr) { this.tasks = taskArr; } /** * Generates a TaskList object by loading a saved list and generates * an empty TaskList object otherwise. * @param storage Object containing filepath to saved list of tasks. * @return TaskList object. */ public static TaskList generateTaskList(Storage storage) { try { return new TaskList(storage.load()); } catch (Exception e) { System.out.println("Could not load file. Generating blank duke.task.Task List."); return new TaskList(); } } /** * Adds a task to the task list. */ public void addTask(Task task) { tasks.add(task); } /** * Removes a task at a specified index from the task list. * @param i Index of task to be removed. */ public void removeTask(int i) { tasks.remove(i); } /** * Returns the task at a specific index of the task list. * @param i Index of task. * @return Task at specified index. */ public Task getTask(int i) { return tasks.get(i); } /** * Returns the last task on the task list. * @return Task at the end of the task list. */ public Task getMostRecentTask() { return tasks.get(tasks.size() - 1); } /** * Returns the size of the task list. * @return Size of task list. */ public int getTaskListSize() { return tasks.size(); } /** * Checks if the task list is empty or not. * @return Either true or false. */ public boolean isEmpty() { return tasks.isEmpty(); } /** * Sets the priority level of a task. * @param i Index of task. * @param priorityLevel Priority level of task. */ public void setTaskPriorityLevel(int i, PriorityLevel priorityLevel) { tasks.get(i).setPriorityLevel(priorityLevel); } }
package com.example.raimu_000.miscursos; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { public List<Ramo> ramosList; public static class ViewHolder extends RecyclerView.ViewHolder{ private TextView ramoTextView; private TextView notaTextView; public ViewHolder(@NonNull View itemView) { super(itemView); ramoTextView = (TextView) itemView.findViewById(R.id.ramoText); notaTextView = (TextView) itemView.findViewById(R.id.promedioText); } } public RecyclerViewAdapter(List<Ramo> _ramosList){ this.ramosList = _ramosList; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout1, viewGroup, false); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { } @Override public int getItemCount() { return ramosList.size(); } }
package com.esum.web.ims.jms; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.esum.appetizer.AbstractTestCase; import com.esum.web.ims.jms.dao.JmsInfoDao; import com.esum.web.ims.jms.vo.JmsInfo; public class JmsInfoDaoTestCase extends AbstractTestCase { @Autowired private JmsInfoDao baseDao; @Test public void test() { String interfaceId = "TEST"; JmsInfo vo = baseDao.select(interfaceId); System.out.println(vo.getInChannelName()); } }
/** * * Copyright (c) 2017, Yustinus Nugroho * * This software is created to help SIMPEG division in Badan Kepegawaian Daerah * gathering and organizing data from other divisions. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Let me know if you use this code by email yustinus.nugroho@gmail.com * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Hope this make changes. */ package net.yustinus.crud.backend.dto; /** * @author Yustinus Nugroho * */ public class TembusanItemDto { private int tembusanItemId; private String tembusanItem; private int tembusanId; private boolean tembusanItemDisable; public TembusanItemDto() { } public int getTembusanItemId() { return tembusanItemId; } public void setTembusanItemId(int tembusanItemId) { this.tembusanItemId = tembusanItemId; } public String getTembusanItem() { return tembusanItem; } public void setTembusanItem(String tembusanItem) { this.tembusanItem = tembusanItem; } public int getTembusanId() { return tembusanId; } public void setTembusanId(int tembusanId) { this.tembusanId = tembusanId; } public boolean isTembusanItemDisable() { return tembusanItemDisable; } public void setTembusanItemDisable(boolean tembusanItemDisable) { this.tembusanItemDisable = tembusanItemDisable; } }
package com.esum.framework.core.queue.mq; public enum JmsConnectorTypes { CONNECTOR_ALL("all"), /** ALL(MAIN노드에 속한 컴포넌트는 VM모드, 그렇지 않으면 NETTY 모드 사용*/ CONNECTOR_NETTY("netty"), /** 모든 컴포넌트는 NETTY 모드 사용 */ CONNECTOR_VM("invm"); /** 모든 컴포넌트는 VM 모드 사용*/ private String value = ""; private JmsConnectorTypes(String value) { this.value = value; } public String getValue() { return value; } public static JmsConnectorTypes parse(String code) { JmsConnectorTypes c = null; switch(code) { case "all" : c = CONNECTOR_ALL; break; case "netty" : c = CONNECTOR_NETTY; break; case "invm" : c = CONNECTOR_VM; break; default : c = CONNECTOR_ALL; } return c; } }
package com.vti.entity; import java.time.LocalDate; public class Bao extends QLTL { private LocalDate ngayphathanh; public Bao(int matailieu, String tennhasanxuat, String sobanphathanh, LocalDate ngayphathanh) { super(matailieu, tennhasanxuat, sobanphathanh); this.ngayphathanh = ngayphathanh; } @Override public String toString() { return "Bao"+super.getMatailieu()+" Tên nhà sản xuất: "+super.getTennhasanxuat()+" Số bản phát hành: "+super.getSobanphathanh()+ " Ngày phát hành: " + ngayphathanh; } }
package coffeeshop; public class Milk { private double fatProcentage = 3.0; public double getFatProcentage() { return fatProcentage; } public void setFatProcentage(double fatProcentage) { this.fatProcentage = fatProcentage; } }
package window.cardTournament; public interface UpdateDatabaseListener { public void update_database(); }
package dk.nemprogrammering.android.listeapp; import android.arch.lifecycle.LiveData; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Query; import android.arch.persistence.room.Update; @Dao public interface ListElementDao { @Query("SELECT * FROM list_elements") LiveData<java.util.List<ListElementEntity>> getAllListElements(); @Query("SELECT * FROM list_elements WHERE uid = :id") LiveData<ListElementEntity> getListElementById(int id); @Delete void deleteListElements(ListElementEntity... listElementEntities); @Update void updateListElements(ListElementEntity... listElementEntities); @Insert void insertListElements(ListElementEntity... listElementEntities); }
/* * 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 btnhom1; import java.io.IOException; import java.util.Arrays; /** * * @author Linh Liv */ public class QLGiaoVien{ private GiaoVien[] arrGVs; private DocGhiObj dgo; public QLGiaoVien() throws IOException, ClassNotFoundException{ dgo=new DocGhiObj("gv\\dataGV.txt"); arrGVs=(GiaoVien[])dgo.doc(); } public boolean checkLogin(String userID, String pass){ for (GiaoVien arrGV : arrGVs) { if (arrGV.getMaGV().equalsIgnoreCase(userID)) { if (arrGV.getMatKhau().equals(Helper.getMD5(pass))) { return true; } } } return false; } public GiaoVien[] getArrGVs() { return arrGVs; } public void addGiaoVien(GiaoVien sv){ if (arrGVs==null){ arrGVs=new GiaoVien[1]; arrGVs[0]=sv; return ; } arrGVs=(GiaoVien[]) Helper.addArr(arrGVs, sv); } public void editGV(GiaoVien gv, int id) { arrGVs[id-1]=gv; } }
package br.com.estore.web.model; import java.util.Date; public class WishListBean { // ID_LIST INT NOT NULL AUTO_INCREMENT , // DATE_WISH_LIST DATE NOT NULL , // CUSTOMER_ID INT NOT NULL , // ID_BOOK INT NOT NULL , private int id; private Date date; private int customerID; private int bookID; public int getId() { return id; } public void setId(int id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public int getCustomerID() { return customerID; } public void setCustomerID(int customerID) { this.customerID = customerID; } public int getBookID() { return bookID; } public void setBookID(int bookID) { this.bookID = bookID; } }
package com.eegeo.mapapi.services.mapscene; import androidx.annotation.UiThread; import androidx.annotation.WorkerThread; import com.eegeo.mapapi.util.NativeApiObject; import java.util.concurrent.Callable; /** * A handle to an ongoing mapscene request. */ public class MapsceneRequest extends NativeApiObject { private MapsceneApi m_mapsceneApi; private final boolean m_applyOnLoad; private OnMapsceneRequestCompletedListener m_callback = null; @UiThread MapsceneRequest(final MapsceneApi mapsceneApi, final boolean applyOnLoad, OnMapsceneRequestCompletedListener callback, Callable<Integer> beginRequestCallable) { super(mapsceneApi.getNativeRunner(), mapsceneApi.getUiRunner(), beginRequestCallable); m_mapsceneApi = mapsceneApi; m_applyOnLoad = applyOnLoad; m_callback = callback; submit(new Runnable() { @WorkerThread @Override public void run() { m_mapsceneApi.register(MapsceneRequest.this, getNativeHandle()); } }); } public boolean shouldApplyOnLoad() { return m_applyOnLoad; } /** * Cancels the current mapscene request if it has not yet been completed. */ @UiThread public void cancel() { submit(new Runnable() { @WorkerThread public void run() { m_mapsceneApi.cancelRequest(getNativeHandle()); } }); } @UiThread void returnResponse(MapsceneRequestResponse mapsceneResponse) { if (m_callback != null) { m_callback.onMapsceneRequestCompleted(mapsceneResponse); } } }
package edu.upenn.cis455.Indexer.EMRIndexer; import static spark.Spark.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.amazonaws.AmazonClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream; /** * An example TFIDF computation and web interface program **/ public class IndexMain { static final Logger logger = Logger.getLogger(IndexMain.class); static AmazonDynamoDB client; static JSONParser parser = new JSONParser(); static int totalFiles; public static void main(String[] args) { System.out.println("Indexer Main starts!"); if(args.length < 1) { System.err.println("You need to provide the total number of files."); System.exit(1); } totalFiles = Integer.parseInt(args[0]); port(8000); get("/", (request,response) -> { return "<html><body>" + "<form action=\"/tfidf\" method=\"POST\">" + "<label for=\"name\">Search: </label>" + "<input type=\"text\" name=\"query\" required/><br>" + "<input type=\"submit\" value=\"Search\"/>" + "</form></body></html>"; }); post("/tfidf", (request,response) -> { String query = request.queryParams("query"); Pattern pattern = Pattern.compile("[\\p{Alnum}]+"); Matcher matcher = pattern.matcher(query); List<String> keys = new ArrayList<String>(); while(matcher.find()) { String key = matcher.group().toLowerCase(); keys.add(key); } System.out.println("query:"+query); System.out.println("key number:"+keys.size()); Map<String, String> invertedlist = getDataFromDynamo(keys); HashMap<String, Double> ret = comupteTFIDF(invertedlist); return ret.toString(); }); } public static Map<String,String> getDataFromDynamo(List<String> keys) { //load credential ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider(); try { credentialsProvider.getCredentials(); } catch (Exception e) { throw new AmazonClientException( "Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (~/.aws/credentials), and is in valid format.", e); } //create client client = AmazonDynamoDBClientBuilder.standard() .withCredentials(credentialsProvider) .withRegion("us-east-1") .build(); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("InvertedIndex"); //word, {doc:tf, doc:tf} Map<String,String> invertedlist = new HashMap<String,String>(); PorterStemmer s = new PorterStemmer(); for(String key : keys) { //stem search key boolean allLetters = true; for(int i=0; i<key.length(); i++) { char ch = key.charAt(i); if(Character.isLetter(ch)) { s.add(ch); } else { s.reset(); allLetters = false; break; } } if(allLetters){ s.stem(); key = s.toString(); s.reset(); } Item item = table.getItem("word", key); if(item == null) { System.out.println("Item " + key + " does not exsit"); continue; } String json = item.toJSON(); try { Object obj = parser.parse(json); HashMap<String, String> map = (HashMap<String, String>)obj; String info = map.get("info"); //System.out.println(key+" "+info); invertedlist.put(key, info); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // // return invertedlist; } public static HashMap<String, Double> comupteTFIDF( Map<String,String> invertedlist) throws IOException { //docid: scores HashMap<String, Double> scorings = new HashMap<String, Double>(); for(String word: invertedlist.keySet()) { String info = invertedlist.get(word); //read large info from s3 files if(info.startsWith("s3://")) { String bucket_name = "testmyindexer";//this can be changed final AmazonS3 s3 = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); S3Object o = s3.getObject(bucket_name, "storage/"+word); if(o == null) { System.out.println("Cannot find object in s3"); continue; } S3ObjectInputStream s3is = o.getObjectContent(); InputStreamReader streamReader = new InputStreamReader(s3is); BufferedReader reader = new BufferedReader(streamReader); info = ""; String line; if((line=reader.readLine())!=null) { info = line; } } Object obj; try { obj = parser.parse(info); HashMap<String, Double> map = (HashMap<String, Double>)obj; for(String docid: map.keySet()) { double tf = (0.4+(1-0.4)* map.get(docid)); double idf = Math.log((double)totalFiles/(double)map.size()); double score = scorings.getOrDefault(docid, (double) 0); score += tf*idf; scorings.put(docid,score); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return scorings; } }
package com.legaoyi.protocol.down.messagebody; import java.util.List; import java.util.Map; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.legaoyi.protocol.message.MessageBody; /** * 事件设置 * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2015-01-30 */ @Scope("prototype") @Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "8301_2011" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX) public class JTT808_8301_MessageBody extends MessageBody { private static final long serialVersionUID = 6849239253288036284L; public static final String MESSAGE_ID = "8301"; /** 设置类型 **/ @JsonProperty("type") private int type; /** 事项列表,key/val键值对,key包括事件id:eventId和事件内容:content **/ @JsonProperty("eventList") private List<Map<String, Object>> eventList; public final int getType() { return type; } public final void setType(int type) { this.type = type; } public final List<Map<String, Object>> getEventList() { return eventList; } public final void setEventList(List<Map<String, Object>> eventList) { this.eventList = eventList; } }
package gradedGroupProject; import java.util.List; public class DeleteBankAccount { private String confirm; private int accountNum; private int pos; public void deleteBankClient( BankClient loggedInClient,List<BankClient> bankClients ) { provideChoice(loggedInClient); provideVerification(); String error = checkTransactionStructure(loggedInClient) ; if( error != null ) printErrorMessage( error ); else executeDeleteTransaction( loggedInClient,bankClients ); } private void provideChoice(BankClient loggedInClient) { loggedInClient.printAccounts(); KeyInput KeyInput = new KeyInput(); System.out.println("Enter the Account Number of the account you wish to delete?"); accountNum= Integer.parseInt( KeyInput.read( "Account Num" ) ); } private void provideVerification() { KeyInput KeyInput = new KeyInput(); System.out.println("Are you sure you want to delete this account?"); System.out.println("Enter 'Y' or 'N'"); confirm= KeyInput.read("Choice"); } private String checkTransactionStructure(BankClient loggedInClient) { for( pos = 0; pos < loggedInClient.getClientAccounts().size(); ++pos ) if( loggedInClient.getClientAccounts().get( pos ).getAccountNum() == accountNum ) break; if( pos < 0 || pos >= loggedInClient.getClientAccounts().size()) return"Account not found"; if(!confirm.equals("Y") && !confirm.equals("N")) { return "Invalid selection"; } return null; } private void printErrorMessage( String message ) { System.err.println( message ); } private void executeDeleteTransaction(BankClient loggedInClient, List<BankClient> bankClients ) { loggedInClient.getClientAccounts().remove(pos); System.out.println("Bank Account Removed"); } }
import java.util.LinkedList; /** NIfte.java * * Author: Greg Choice c9311718@uon.edu.au * * Created: * Updated: 28/09/2018 * * Description: * STNode sub-class for NIFTE rule * */ public class NIfte extends STNode { public NIfte(LinkedList<Token> tokenList, SymbolTable table) { super(NID.NIFTE); setRight(processStats(tokenList, table)); } }
// Copyright 2016 Yahoo Inc. // Licensed under the terms of the New-BSD license. Please see LICENSE file in the project root for terms. package com.yahoo.test.monitor; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class JMXServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream out = response.getOutputStream(); ShowDataRunnable sdr = new ShowDataRunnable(out); MonitoringTools mt = new MonitoringTools(out); mt.foreachVM(sdr); } }
package undirectedGraphANDdijkstra; /**<pre> * ******************************************************************************************************************** * DijkstraPath.java * ******************************************************************************************************************** * * <strong>Description:</strong> This class allows for the instantiation of an object whose sole purpose is to * use the Dijkstra algorithm to find the vertex farthest away from the source vertex. The class is modified to * reduce the amount of instantiations when finding the farthest vertex from all vertices in a graph. It operated * a few seconds faster on my computer this way instead of using multiple instantiations in the main method. * This class contains only the methods necessary to accomplish the tak for project 3. Many other methods could * be coded for a broader use of the class. * ********************************************************************************************************************* * @author VagnerMachado - QCID 23651127 - Queens College - Spring 2018 ********************************************************************************************************************* * * *<a href="http://www.facebook.com/vagnermachado84"> Do you like this code? Let me know! </a> *</pre> */ public class DijkstraPath { private boolean [] distFound; private double [] distTo; private HeapPQ<Double, Integer> pq; private int vertices; private WeightedUndirectedGraph g; private double max; /** * DijkstraPath constructor - Initiates an object based on undirected weighted graph * passed as parameter * @param g - an undirected weighted graph */ public DijkstraPath(WeightedUndirectedGraph g) { vertices = g.V(); this.g= g; max = 0; } /** * findFar - finds the farthest vertex using longest of shortest path from source * @param source - the source vertex */ public double findFar(int source) { distFound = new boolean [vertices]; distTo = new double [vertices]; pq = new HeapPQ<Double, Integer>(); distTo[source] = 0; pq.enqueue(0,source); int vertex = 0; while(!pq.isEmpty()) { vertex = pq.dequeue().getVertex(); if (!distFound[vertex]) relax(g, vertex); } return max; } /** * distanceTo - gets a distance to a vertex, must be called after findFar(int source) * @param x - the vertex being looked for * @return - the distance from source to vertex. */ public double distanceTo(int x) { return distTo[x]; } /** * relax - private method called by findFar. Sets a distance to found and * enqueues all the adjacent vertices to vertex with distance not found. * @param g - a graph * @param vertex - the vertex being relaxed */ private void relax(WeightedUndirectedGraph g, int vertex) { distFound[vertex] = true; max = distTo[vertex]; for(int x : g.adj(vertex)) { if(distFound[x] == false) { double newDist = distTo[vertex] + g.getWeight(x, vertex); if(distTo[x] == 0 || distTo[x] > newDist) { pq.enqueue(newDist, x); distTo[x] = newDist; } } } } }
package com.xdd.vsuproject; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; public class AssetLoader extends AssetManager { public void loadAll(){ load("skins/uiskin.json", Skin.class); load("MainMenuBg.jpg", Texture.class); load("SecondMenu.png", Texture.class); load("backButton.png", Texture.class); load("CampainBg.png", Texture.class); finishLoading(); // load("blueBlock.png", Texture.class); // load("yellowBlock.png", Texture.class); } public Skin getSkin(){ return get("skins/uiskin.json", Skin.class); } public Texture getMainMenuBg(){ return get("MainMenuBg.jpg"); } public Texture getSecondMenu(){ return get("SecondMenu.png"); } public Texture getIntroScreenBg(){ return get("CampainBg.png"); } public ImageButton.ImageButtonStyle getBackButtonSkin(){ return generateImageButtonSkin(get("backButton.png", Texture.class)); } public ImageButton.ImageButtonStyle generateImageButtonSkin(Texture t){ ImageButton.ImageButtonStyle s = new ImageButton.ImageButtonStyle(); s.up = new TextureRegionDrawable(new TextureRegion(t)); return s; } }
package br.mpac.controller; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.inject.Named; import br.mpac.dados.EstadoCivilDao; import br.mpac.dados.GenericDao; import br.mpac.entidade.EstadoCivil; @Named("estadoController") @SessionScoped public class EstadoCivilController extends AbstractController<EstadoCivil> { private static final long serialVersionUID = 1L; @EJB private EstadoCivilDao dao; @Override public GenericDao<EstadoCivil> getDao() { return dao; } @Override public void prepareCreate() { setSelected(new EstadoCivil()); } }
//------------------------------------------------------------------------------ // Copyright (c) 2012 Microsoft Corporation. All rights reserved. // // Description: See the class level JavaDoc comments. //------------------------------------------------------------------------------ package com.microsoft.live; /** * QueryParameters is a non-instantiable utility class that holds query parameter constants * used by the API service. */ final class QueryParameters { public static final String PRETTY = "pretty"; public static final String CALLBACK = "callback"; public static final String SUPPRESS_REDIRECTS = "suppress_redirects"; public static final String SUPPRESS_RESPONSE_CODES = "suppress_response_codes"; public static final String METHOD = "method"; public static final String OVERWRITE = "overwrite"; public static final String RETURN_SSL_RESOURCES = "return_ssl_resources"; /** Private to present instantiation. */ private QueryParameters() { throw new AssertionError(ErrorMessages.NON_INSTANTIABLE_CLASS); } }
package com.main.parse; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.LinkedList; import com.database.mysql.AppCommit; import com.database.mysql.AppCommitsDB; import com.database.mysql.MigrationRule; import com.database.mysql.MigrationRuleDB; import com.database.mysql.MigrationSegmentsDB; import com.database.mysql.ProjectLibrariesDB; import com.database.mysql.RepositoriesDB; import com.library.source.DownloadLibrary; import com.library.source.MigratedLibraries; import com.project.info.Operation; import com.project.info.Project; import com.segments.build.CleanJavaCode; import com.segments.build.Segment; import com.segments.build.TerminalCommand; import com.subversions.process.GitHubOP; /** * This Client responsible for detect all fragments by cloning the apps from * GitHub */ public class DetectorClient { String LOG_FILE_NAME = "app_commits.txt"; static String pathClone = Paths.get(".").toAbsolutePath().normalize().toString() + "/Clone/Process/"; String pathToSaveJAVALibrary = "/librariesClasses/jar"; TerminalCommand terminalCommand = new TerminalCommand(); CleanJavaCode cleanJavaCode = new CleanJavaCode(); public static void main(String[] args) { // TODO Auto-generated method stub new DetectorClient().start(); System.out.println("process done"); } void start() { // Created needed folder terminalCommand.createFolder("librariesClasses/jar/tfs"); System.out.println("*****Loading all projects libraries (will take some time) *****"); AppCommitsDB appCommitsDB = new AppCommitsDB(); // ArrayList<Repository> listOfRepositories= new // RepositoriesDB().getRepositories(); // HashMap<Integer, LinkedList<AppCommit>> appsCommitsList= // appCommitsDB.getAppCommits(); LinkedList<MigrationRule> migrationRules = new MigrationRuleDB().getMigrationRulesWithoutVersion(0); MigrationSegmentsDB migratedCommitDB = new MigrationSegmentsDB(); ArrayList<Project> listOfProjectLibraries = new ProjectLibrariesDB().getProjectLibraries(); ArrayList<Project> listOfAddedLibraries = new ArrayList<Project>(); ArrayList<Project> listOfRemovedLibraries = new ArrayList<Project>(); // Hold list of project libraries at current commit ArrayList<Project> listOfCurrentProjectLibraries = new ArrayList<Project>(); String oldcommitID = ""; String oldPomPath = ""; String newcommitID = ""; int currentProjectsID = 0; MigrationRulesClient migrationRulesClient = new MigrationRulesClient(); // search in all commits for rule String appLink = ""; // ********************************************************************* // 1- Search for migration using library changes in pom file // ********************************************************************* for (MigrationRule migrationRule : migrationRules) { System.out.println("==> Start search for migration rule " + migrationRule.FromLibrary + "<==> " + migrationRule.ToLibrary); MigratedLibraries.ID = migrationRule.ID; // get one vaild library signature to use it in self-admitted String fromLibraryVaild = null; String toLibraryVaild = null; ; // currentProjectSearch=0; // boolean exitSearch=false; // collect all the segments that found in all the projects for specific rule ArrayList<Segment> segmentList = new ArrayList<Segment>(); for (Project project : listOfProjectLibraries) { // if(currentProjectSearch>15){ // break; //Go check next rule // } newcommitID = project.CommitID; // move to next project to search in // TODO: This code cannot find migration in last commit in every project if (project.ProjectID != currentProjectsID) { currentProjectsID = project.ProjectID; listOfAddedLibraries.clear(); listOfRemovedLibraries.clear(); listOfCurrentProjectLibraries.clear(); oldcommitID = ""; oldPomPath = ""; appLink = new RepositoriesDB().getRepositoriesLink(project.ProjectID); } // Move to next project in one repository if (oldPomPath.equals(project.PomPath) == false) { listOfAddedLibraries.clear(); listOfRemovedLibraries.clear(); listOfCurrentProjectLibraries.clear(); oldcommitID = ""; oldPomPath = project.PomPath; } // ********************************************************************* // if new commit there we need to generate the CP for libraries changed if (oldcommitID.equals(newcommitID) == false) { // he may be only added new library but didnot remove old library if (listOfAddedLibraries.size() > 0 || listOfRemovedLibraries.size() > 0) { if (migrationRulesClient.isCommitsSequence(oldcommitID, newcommitID) == false) { System.err.println("==>This process ingored because uncorrect order commits in between " + oldcommitID + "==> " + newcommitID); return; } else { // make sure is not migrate process // TODO: make sure is not library separate process // it happened when one library divided into multi-libraries // we use ":" to make sure we search for artificate id String isFoundInPrevious = Project.isFound(listOfRemovedLibraries, ":" + migrationRule.ToLibrary); if (isFoundInPrevious.length() > 0) { continue; } String toLibraryFind = Project.isFound(listOfAddedLibraries, ":" + migrationRule.ToLibrary); String fromLibraryFind = Project.isFound(listOfRemovedLibraries, ":" + migrationRule.FromLibrary); // Case: for library that migrate but we didnot remove from the pom.xml String isStillFound = Project.isFound(listOfCurrentProjectLibraries, ":" + migrationRule.FromLibrary); if (toLibraryFind.length() > 0 && fromLibraryFind.length() == 0) { fromLibraryFind = isStillFound; } // Case: use removed old library and he have new library already added in // prevous commits if (toLibraryFind.length() == 0 && fromLibraryFind.length() > 0) { toLibraryFind = Project.isFound(listOfCurrentProjectLibraries, ":" + migrationRule.ToLibrary); } if (toLibraryFind.length() > 0 && fromLibraryFind.length() > 0) { MigratedLibraries.toLibrary = toLibraryFind; MigratedLibraries.fromLibrary = fromLibraryFind; String previousCommitID = appCommitsDB.previousCommitID(project.ProjectID, oldcommitID); if (previousCommitID.length() > 0) { System.out.println("-----------------\n" + currentProjectsID + "- Fing migration\nCommit from :" + previousCommitID + "==> " + oldcommitID + "\nLibrary from: " + MigratedLibraries.fromLibrary + "==> " + MigratedLibraries.toLibrary + "\nAppLink: " + appLink); ArrayList<Segment> listOfblocks = startCloning(appLink, previousCommitID, oldcommitID); // if we find fragments we add them to fragment list if (listOfblocks.size() > 0) { segmentList.addAll(listOfblocks); // get active library signature to use it in self admitted fromLibraryVaild = fromLibraryFind; toLibraryVaild = toLibraryFind; // Save all segments in database System.out.println("==> Start saving all founded segmenst in database"); for (Segment segment : listOfblocks) { // save the commit and project that has the migration migratedCommitDB.add(migrationRule.ID, currentProjectsID, oldcommitID, segment, fromLibraryFind, toLibraryFind); } System.out.println("<== complete saving all founded segmenst in database"); } // currentProjectSearch++; } else { System.err.println("Cannot find prevous commit before :" + oldcommitID); } } } } // if there is migration // clear and update current project libraries listOfCurrentProjectLibraries.addAll(listOfAddedLibraries); listOfAddedLibraries.clear(); // remove object from list of current project library for (Project projectRemoved : listOfRemovedLibraries) { for (int i = 0; i < listOfCurrentProjectLibraries.size(); i++) { if (listOfCurrentProjectLibraries.get(i).LibraryName.equals(projectRemoved.LibraryName)) { listOfCurrentProjectLibraries.remove(i); break; } } } listOfRemovedLibraries.clear(); oldcommitID = project.CommitID; // oldPomPath = project.PomPath; } // ********************************************************************* // added library in list and removed library in list if (project.isAdded == Operation.added) { listOfAddedLibraries.add(project); } else { listOfRemovedLibraries.add(project); } } // end of project search // call self admitted search ArrayList<Segment> listOfblocks = findSelfAdmittedMigration(migrationRule.ID, fromLibraryVaild, toLibraryVaild, migrationRule.FromLibrary, migrationRule.ToLibrary); if (listOfblocks.size() > 0) { segmentList.addAll(listOfblocks); } /* * After find all migration segments start apply Algorithm Run CP and * Substitution Algorithm on cleaned files */ int isVaildMigration = 0; if (segmentList.size() > 0) { isVaildMigration = 1; // Run function mapping mapping // SyntheticTestClient testClient= new SyntheticTestClient(); // testClient.runAlgorithm( segmentList); } else { isVaildMigration = 2; System.out.println("Didnot find any migration segment for this rule"); } // update the migration rule to state of valid=1 or not valid=2 new MigrationRuleDB().updateMigrationRule(migrationRule.ID, isVaildMigration); } // end check all migration rules } // ********************************************************************* // 2- Search for migration that defined using commit text // ********************************************************************* ArrayList<Segment> findSelfAdmittedMigration(int migrationRuleID, String fromLibraryVaild, String toLibraryVaild, String fromLibraryName, String toLibraryName) { ArrayList<Segment> segmentList = new ArrayList<Segment>(); if (fromLibraryVaild == null || toLibraryVaild == null) { System.err.println( "Either fromLibrary=" + fromLibraryVaild + " or toLibrary=" + toLibraryVaild + " is not vaild"); return segmentList; } AppCommitsDB appCommitsDB = new AppCommitsDB(); MigrationSegmentsDB migratedCommitDB = new MigrationSegmentsDB(); ArrayList<AppCommit> listOfAppsCommit = appCommitsDB.getAllCommitsHasMigration(fromLibraryName, toLibraryName, migrationRuleID); System.out.println("Start searching for self-admitted migration between " + fromLibraryVaild + "==>" + toLibraryVaild + " by the developer"); MigratedLibraries.toLibrary = toLibraryVaild; MigratedLibraries.fromLibrary = fromLibraryVaild; for (AppCommit appCommit : listOfAppsCommit) { String appLink = new RepositoriesDB().getRepositoriesLink(appCommit.AppID); String previousCommitID = appCommitsDB.previousCommitID(appCommit.AppID, appCommit.CommitID); if (previousCommitID.length() > 0) { System.out.println( "-----------------\n" + appCommit.AppID + "- Fing migration\nCommit from :" + previousCommitID + "==> " + appCommit.CommitID + "\nLibrary from: " + MigratedLibraries.fromLibrary + "==> " + MigratedLibraries.toLibrary + "\nAppLink: " + appLink); ArrayList<Segment> listOfblocks = startCloning(appLink, previousCommitID, appCommit.CommitID); // if we find fragments we add them to fragment list if (listOfblocks.size() > 0) { segmentList.addAll(listOfblocks); // Save all segments in database System.out.println("==> Start saving all founded segmenst in database"); for (Segment segment : listOfblocks) { // save the commit and project that has the migration migratedCommitDB.add(MigratedLibraries.ID, appCommit.AppID, appCommit.CommitID, segment, fromLibraryVaild, toLibraryVaild); } System.out.println("<== complete saving all founded segmenst in database"); } } } return segmentList; } // This function return list of cleaned segments ArrayList<Segment> startCloning(String appURL, String previousCommitName, String migrateAtCommitName) { ArrayList<Segment> segmentList = new ArrayList<Segment>(); // list of changed files ArrayList<String> listOfChangedFiles = cloneMigratedCommits(appURL, previousCommitName, migrateAtCommitName); if (listOfChangedFiles.size() > 0) { String outputDiffsPath = pathClone + "../Diffs/" + MigratedLibraries.ID + "/" + migrateAtCommitName + "/"; // list of changed cleaned files ArrayList<String> diffsFilePath = generateFragments(listOfChangedFiles, previousCommitName, migrateAtCommitName, outputDiffsPath); if (diffsFilePath.size() > 0) { // clean java code from the data segmentList = cleanJavaCode.getListOfCleanedFiles(outputDiffsPath, diffsFilePath); } } return segmentList; } // This method responsible for clone two commits that has migration to find file // changes between them ArrayList<String> cloneMigratedCommits(String appURL, String previousCommitName, String migrateAtCommitName) { ArrayList<String> listOfChangedFiles = new ArrayList<String>(); // Download The library Jar singatures DownloadLibrary downloadLibrary = new DownloadLibrary(pathToSaveJAVALibrary); downloadLibrary.download(MigratedLibraries.fromLibrary, false); downloadLibrary.buildTFfiles(MigratedLibraries.fromLibrary); downloadLibrary.download(MigratedLibraries.toLibrary, false); downloadLibrary.buildTFfiles(MigratedLibraries.toLibrary); if (downloadLibrary.isLibraryFound(MigratedLibraries.fromLibrary) == false || downloadLibrary.isLibraryFound(MigratedLibraries.toLibrary) == false) { System.err.println( "Cannot download either " + MigratedLibraries.fromLibrary + " or " + MigratedLibraries.toLibrary); return listOfChangedFiles; } // Clone App if isnot cloned already GitHubOP gitHubOP = new GitHubOP(appURL, pathClone); if (gitHubOP.isAppExist(gitHubOP.appFolder) == false) { gitHubOP.deleteFolder(pathClone); // clear folder from prevous project process terminalCommand.createFolder(pathClone); gitHubOP.cloneApp(); gitHubOP.generateLogs(LOG_FILE_NAME); } // get list of change files listOfChangedFiles = gitHubOP.getlistOfChangedFiles(migrateAtCommitName); if (listOfChangedFiles.size() == 0) { System.out.println("\t==>Cannot find any changes in Java files in this commit"); return listOfChangedFiles; } // clone first commit if (gitHubOP.isAppExist(previousCommitName) == false) { gitHubOP.copyApp(previousCommitName); String firstCommitID = GitHubOP.getCommitID(previousCommitName); gitHubOP.gitCheckout(previousCommitName, firstCommitID); } // clone second commit if (gitHubOP.isAppExist(migrateAtCommitName) == false) { gitHubOP.copyApp(migrateAtCommitName); String secondCommitID = GitHubOP.getCommitID(migrateAtCommitName); gitHubOP.gitCheckout(migrateAtCommitName, secondCommitID); } return listOfChangedFiles; } // This function will generate fragments of code changes ArrayList<String> generateFragments(ArrayList<String> listOfChangedFiles, String previousCommitName, String migrateAtCommitName, String outputDiffsPath) { // list of diffs files path ArrayList<String> diffsFilePath = new ArrayList<String>(); boolean isDiffFolderCreated = false; // generate diffs String outputDiffFilePath = ""; for (String changedFilePath : listOfChangedFiles) { String changedFilePathSplit[] = changedFilePath.split("/"); String chnagedFileName = changedFilePathSplit[changedFilePathSplit.length - 1]; System.out.print("Detect change in " + changedFilePath); String newUpdatedFilePath = pathClone + migrateAtCommitName + "/" + changedFilePath; String oldFilePath = pathClone + previousCommitName + "/" + changedFilePath; outputDiffFilePath = outputDiffsPath + "diff_" + chnagedFileName + ".txt"; // Make sure the file has call from old function before update and call from new // library after update if (cleanJavaCode.isUsedNewLibrary(oldFilePath, MigratedLibraries.fromLibrary) && cleanJavaCode.isUsedNewLibrary(newUpdatedFilePath, MigratedLibraries.toLibrary)) { // create folder only for one time if (isDiffFolderCreated == false) { isDiffFolderCreated = true; terminalCommand.createFolder(outputDiffsPath); } terminalCommand.createDiffs(oldFilePath, newUpdatedFilePath, outputDiffFilePath); // Copy real file before and after migration terminalCommand.copyFile(oldFilePath, outputDiffFilePath.replace(".txt", "_before.java")); terminalCommand.copyFile(newUpdatedFilePath, outputDiffFilePath.replace(".txt", "_after.java")); diffsFilePath.add(outputDiffFilePath); } else { System.err.print("|ignored because old or new file NOT used libraries functions \n"); } } return diffsFilePath; } }
package com.icanit.app_v2.common; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Color; import android.widget.TextView; import com.icanit.app_v2.util.AppUtil; public class VeriCodeSender implements Runnable { private TextView tv; private String url, message, veriCode; private VeriCodeTimer timer; private int seconds = 60; public VeriCodeSender(String url, String veriCode, TextView tv) { this.tv = tv; this.url = url; this.veriCode = veriCode; } public void setMessage(String message){ this.message=message; } @Override public void run() { IConstants.MAIN_HANDLER.post(new Runnable(){ public void run(){ tv.setEnabled(false); tv.setText("获取中..."); tv.setTextColor(Color.rgb(0x99, 0x99, 0x99)); } }); JSONObject veriCodeResp = null; try { String jsonResp = AppUtil.getNetUtilInstance() .sendMessageWithHttpPost(url, message); if (jsonResp != null && jsonResp.startsWith("{")) veriCodeResp = new JSONObject(jsonResp); } catch (Exception e) { e.printStackTrace(); } final JSONObject jo = veriCodeResp; IConstants.MAIN_HANDLER.post(new Runnable() { public void run() { try { if (jo != null && jo.getBoolean(IConstants.RESPONSE_SUCCESS)) { AppUtil.toast("验证码:" + jo.getString(veriCode)); startTimer(); } else { String respDesc=null; try{ respDesc=jo.getString(IConstants.RESPONSE_DESC); }catch (Exception e) {} if(respDesc==null||"".equals(respDesc)||"null".equals(respDesc)) respDesc="短信发送失败,稍后重试"; AppUtil.toast(respDesc); tv.setEnabled(true); tv.setTextColor(Color.rgb(0x33, 0x33, 0x33)); tv.setText("获取验证码"); } } catch (JSONException e) { e.printStackTrace(); AppUtil.toast("解析内容异常,稍后重试"); tv.setEnabled(true); tv.setTextColor(Color.rgb(0x33, 0x33, 0x33)); tv.setText("获取验证码"); } } }); } private void startTimer() { if (timer == null) { timer = new VeriCodeTimer(tv); } timer.start(seconds); } }
package br.com.wasys.gfin.cheqfast.cliente.endpoint; import br.com.wasys.gfin.cheqfast.cliente.model.CredencialModel; import br.com.wasys.gfin.cheqfast.cliente.model.DispositivoModel; import br.com.wasys.gfin.cheqfast.cliente.model.RecoveryModel; import br.com.wasys.gfin.cheqfast.cliente.model.ResultModel; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; /** * Created by pascke on 02/08/16. */ public interface DispositivoEndpoint { @POST("dispositivo/recuperar") Call<ResultModel> recuperar(@Body RecoveryModel recoveryModel); @POST("dispositivo/autenticar") Call<DispositivoModel> autenticar(@Body CredencialModel credencialModel); }
package io.zipcoder.fundamentals.day2.lab1; import java.util.Scanner; public class Greeting { public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("What is your name?"); String name = sc.nextLine(); if (name.equals("Bob") || name.equals("Alice")) { System.out.println("Hello " + name); } else{ System.out.println("Bye"); } } }
package home.stanislavpoliakov.meet7_practice; import android.util.Log; import java.util.List; /** * Класс элемента данных. Эта реализация несколько нарушает первый принцип SOLID, так как * внутри себя описывает три разновидности данных. Надо сделать общий интерфейс данных и три * реализации для каждого типа. * Три различных конструктора, каждый из которых вызывается в зависимости от типа данных, описанного * в Enum. К сожалению, реализация не по SOLID дает возможность дотянуться до полей, значение которых * будет инициализировано default (для String = "", для int = 0), в то время как этих полей для определенного * типа данных вообще не должно существовать. Надо переделать. * * Добавил id-элемента данных. Для DiffUtils */ public class DataItem implements Cloneable{ private static final String TAG = "meet7_logs"; private static int count; private String text; private int imageId = 0; private ItemTypes itemType; private List<Integer> imageItems; private int id; //TODO Переделать объекты данных /** * Конструктор для данных типа "Простой текст" * @param itemType тип данных Enum (ItemTypes.SIMPLE_TEXT) * @param text текстовое содержимое для отображения */ DataItem(ItemTypes itemType, String text) { this.itemType = itemType; this.text = text; this.id = ++count; } /** * Конструктор для данных типа "Каскад картинок" * @param itemType тип данных Enum (ItemTypes.SIMPLE_IMAGE) * @param imageItems коллекция изображений (package:drawable/) */ DataItem(ItemTypes itemType, List<Integer> imageItems) { this.itemType = itemType; this.imageItems = imageItems; this.id = ++count; } /** * Конструктор для данных типа "Картинка и текст" * @param itemType тип данных Enum (ItemTypes.IMAGE_AND_TEXT) * @param text текстовое содержимое для отображения * @param imageId идентификатор ресурса (package:drawable/) */ DataItem(ItemTypes itemType, String text, int imageId) { this.itemType = itemType; this.text = text; this.imageId = imageId; this.id = ++count; } public String getText() { return text; } public void setText(String text) { this.text = text; } public int getImageId() { return imageId; } public void setImageId(int imageId) { this.imageId = imageId; } public ItemTypes getItemType() { return itemType; } public int getId() { return id; } public List<Integer> getImageItems() { return imageItems; } public void setImageItems(List<Integer> imageItems) { this.imageItems = imageItems; } /** * Переопределяем метод Clone для того, чтобы сделать дубликат нашего списка элемнтов * для внесения изменений (чтобы изменения регистрировались в DiffCall * @return дубликат * @throws CloneNotSupportedException */ @Override protected Object clone() throws CloneNotSupportedException { DataItem cloneData = (DataItem) super.clone(); cloneData.text = this.text; cloneData.imageId = this.imageId; return cloneData; } }
package hr.ivlahek.financial.app.constants; /** * @author ivlahek */ public enum PropertyConstants { DATABASE_NAME("db.database"), DB_SERVER("db.server"); private String propertyName; PropertyConstants(String propertyName) { this.propertyName = propertyName; } public String getPropertyName() { return propertyName; } }
package spring.di.demo.integration; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import spring.di.demo.dao.EmployeeDaoInMemoryImpl; import spring.di.demo.domain.Employee; import spring.di.demo.service.EmployeeService; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.LongStream; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:config-beans.xml"}) public class FullServiceIntegrationTest { @Autowired private EmployeeService employeeService; @Autowired private EmployeeDaoInMemoryImpl employeeDaoInMemory; @Test public void findAll_Test() throws Exception { //given... Method initialize = employeeDaoInMemory.getClass().getDeclaredMethod("initialize"); initialize.setAccessible(true); initialize.invoke(employeeDaoInMemory); //when... List<Employee> all = employeeService.findAll(); //then... Assert.assertEquals(10, all.size()); int idx = 1; for (Employee employee : all) { Assert.assertEquals("Firstname " + (idx++), employee.getFirstname()); } } @Test public void find_list_long_Test() throws Exception { //given... List<Long> idsToSearchFor = Arrays.asList(1L, 2L); //when... List<Employee> result = employeeService.find(idsToSearchFor); //then... Assert.assertEquals(result.size(), 2); int idx = 1; for (Employee employee : result) { Assert.assertEquals("Firstname " + (idx++), employee.getFirstname()); } } @Test public void find_long_Test() throws Exception { //when... Employee employee = employeeService.find(1L); //then... Assert.assertEquals(employee.getFirstname(), "Firstname 1"); } @Test public void find_boolean_Test() throws Exception { //given... List<Employee> firedEmployees = employeeService.findAll().stream().filter(Employee::getFired).collect(Collectors.toList()); //when... List<Employee> result = employeeService.find(true); //then... Assert.assertEquals(result, firedEmployees); } @Test public void find_string_string_string_Test() throws Exception { //when... List<Employee> result = employeeService.find("Firstname 1", "Initials 1", "Surname 1"); //then... Assert.assertEquals(result.get(0).getFirstname(), "Firstname 1"); } @Test public void insert_Test() throws Exception { //given... Employee employee = Employee.builder().firstname("chri").initials(null).surname("niko").fired(false).build(); //when... employeeService.insert(employee); //then... List<Employee> result = employeeService.find("chri", null, "niko"); Assert.assertEquals(result.get(0), employee); } @Test public void update_Test() throws Exception { //given... Employee employee = Employee.builder().id(1L).firstname("Firstname 1").initials("Initials 1").surname("Surname 1").fired(true).build(); //when... employeeService.update(employee); //then... Employee result = employeeService.find(1L); Assert.assertEquals(result, employee); } @Test public void delete_Test() throws Exception { //when... employeeService.delete(1L); Employee employee = employeeService.find(1L); //then... Assert.assertNull(employee); } @Test public void update_list_employees_Test() throws Exception { //given... List<Employee> employees = LongStream .rangeClosed(1, 2) .boxed() .map(idx -> Employee.builder() .id(idx) .firstname("Firstname " + idx) .initials("Initials " + idx) .surname("Surname " + idx) .fired(true) .build()) .collect(Collectors.toList()); //when... employeeService.update(employees); //then... List<Employee> result = employeeService.find(Arrays.asList(1L, 2L)); Assert.assertEquals(result, employees); } }
package com.app.noan.listener; import com.app.noan.model.BrandModel; import java.util.List; /** * Created by Suleiman on 16/11/16. */ public interface BrandAdapterCallback { void retryBrandId(List<BrandModel> brandList); }
package com.mredrock.freshmanspecial.data; import android.util.Log; import com.mredrock.freshmanspecial.httptools.GetDataFromServer; import java.util.ArrayList; import java.util.List; import rx.Subscriber; /** * Created by 700-15isk on 2017/8/8. */ public class DataFactory { private List<SexRatio>sexRatios; private Subscriber subscriber; public List<SexRatio> getSexRatios() { return sexRatios; } public void setSexRatios(List<SexRatio> sexRatios) { this.sexRatios = sexRatios; } public List<SexRatio> postSexRatio(){ sexRatios=new ArrayList<>(); subscriber=new Subscriber<List<SexRatio>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(List<SexRatio> sexRatio) { sexRatios.addAll(sexRatio); } }; GetDataFromServer.getInstance().getSexRatio(subscriber,"SexRatio"); return sexRatios; } }
/** * project name:saas * file name:SysUserServiceImpl * package name:com.cdkj.system.service.impl * date:2018/2/9 下午2:36 * author:bovine * Copyright (c) CD Technology Co.,Ltd. All rights reserved. */ package com.cdkj.schedule.system.service.impl; import com.cdkj.common.base.service.impl.BaseServiceImpl; import com.cdkj.common.exception.CustException; import com.cdkj.constant.ErrorCode; import com.cdkj.model.system.pojo.SysUser; import com.cdkj.schedule.system.dao.SysUserMapper; import com.cdkj.schedule.system.service.api.SysUserService; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.Resource; /** * description: 系统用户管理 <br> * date: 2018/2/9 下午2:36 * * @author bovine * @version 1.0 * @since JDK 1.8 */ @Service public class SysUserServiceImpl extends BaseServiceImpl<SysUser, String> implements SysUserService { /** * 用户-部门关系表中套账号,暂先用 */ private final String sysAccount = "All"; @Resource private SysUserMapper sysUserMapper; @Override public SysUser selectByUsername(String username) { return sysUserMapper.selectByUsername(username); } /** * 根据用户名及登录源获取用户信息 * * @param username 用户名 * @param sourceLogin 登录源:0:APP登录,1:后端登录 * @return 用户信息 */ @Override public SysUser selectByUsernameAndSourceLogin(String username, int sourceLogin) { if (StringUtils.isEmpty(username)) { throw new CustException(ErrorCode.ERROR_20001, "用户名为空"); } return sysUserMapper.selectByUsernameAndSourceLogin(username, sourceLogin); } /** * 根据用户名及登录源获取用户信息 * * @param mobile 手机号 * @param sourceLogin 登录源:0:APP登录,1:后端登录 * @return 用户信息 */ @Override public SysUser selectByMobileAndSourceLogin(String mobile, int sourceLogin) { if (StringUtils.isEmpty(mobile)) { throw new CustException(ErrorCode.ERROR_20001, "手机号为空"); } return sysUserMapper.selectByMobileAndSourceLogin(mobile, sourceLogin); } }
package web.util; import java.lang.reflect.Field; import java.sql.*; import java.util.*; import javax.sql.DataSource; import org.apache.commons.beanutils.BeanUtils; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import web.moel.Dorm; public class DBUtils { /** * 使用数据库连接池 */ private static DataSource dataSource = null; static { ConfigurableApplicationContext context = null; try { context = new ClassPathXmlApplicationContext("applicationContext.xml"); dataSource = (DataSource) context.getBean("dataSource"); } catch (Exception e) { e.printStackTrace(); } finally { if(context != null) context.close(); } } /** * des 得到数据库的连接 * * @return * @throws Exception */ public static Connection getConnection() throws Exception { return dataSource.getConnection(); } /** * @des 关闭数据库的连接 * @param conn * @param pre * @param rs */ public static void close(Connection conn, Statement sta, ResultSet rs) { try { if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); } try { if (sta != null) sta.close(); } catch (Exception e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } /** * * @param sql语句(增删改) * @param 任意多个参数 * @return 受影响的条数 * @throws Exception */ public static int executeUpdate(String sql, Object... args) { Connection conn = null; PreparedStatement pre = null; int count = 0; try { conn = getConnection(); pre = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { pre.setObject(i + 1, args[i]); } count = pre.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { close(conn, pre, null); } return count; } /** * 将一个对象插入到数据库中 * @param obj * @return */ public static int insertObject( Object obj ) { System.out.println( obj.getClass().getSimpleName() ); String tablename = obj.getClass().getSimpleName(); Class<?> clazz = obj.getClass(); Field[] fields = clazz.getDeclaredFields(); StringBuffer sql = new StringBuffer("insert into " + tablename + "("); for( int i = 0 ; i < fields.length; i ++ ) { sql.append( fields[i].getName() ); if( i != fields.length - 1 ) sql.append(","); } sql.append(") values ( "); for( int i = 0 ; i < fields.length; i ++ ) { try { sql.append( "'" + BeanUtils.getProperty(obj, fields[i].getName()) + "'" ); } catch (Exception e) { e.printStackTrace(); } if( i != fields.length - 1 ) sql.append(","); } sql.append(" )"); System.out.println(sql.toString()); return executeUpdate(sql.toString()); } /** * * @param sql语句(增删改) * @param 任意多个参数 * @return 受影响的条数 * @throws Exception */ public static int executeUpdateSupportTransaction(Connection conn, String sql, Object... args) { PreparedStatement pre = null; int count = 0; try { pre = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { pre.setObject(i + 1, args[i]); } count = pre.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { close(null, pre, null); } return count; } /** * @des 插入数据,返回的是自增长主键的id * @param sql * @param args * @return */ public static int insertAndGetAutoId(String sql, Object... args) { Connection conn = null; PreparedStatement pre = null; ResultSet rs = null; try { conn = getConnection(); pre = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); for (int i = 0; i < args.length; i++) { pre.setObject(i + 1, args[i]); } pre.executeUpdate(); rs = pre.getGeneratedKeys(); if (rs.next()) return rs.getInt(1); } catch (Exception e) { e.printStackTrace(); } finally { close(conn, pre, rs); } return 0; } /** * @require javabean中的属性名必须和数据表中的字段名完全一样 * @param c * @param sql * @param args * @return Object or null */ public static <T> T getOneData(Class<T> c, String sql, Object... args) { Connection conn = null; PreparedStatement pre = null; ResultSet rs = null; T entity = null; try { conn = getConnection(); pre = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { pre.setObject(i + 1, args[i]); } rs = pre.executeQuery(); if (rs.next()) { entity = c.newInstance(); // 获得元数据,包含结果集的列数,属性名,以及别名等信息。 ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String key = md.getColumnName(i); Object value = rs.getObject(key); // Field field = c.getDeclaredField(key); // field.setAccessible(true); // field.set(entity, value); BeanUtils.setProperty(entity, key, value); } } } catch (Exception e) { e.printStackTrace(); } finally { close(conn, pre, rs); } return entity; } /** * @require javabean中的属性名必须和数据表中的字段名完全一样 * @param c * @param sql * @param args * @return list */ public static <T> List<T> getListData(Class<T> c, String sql, Object... args) { Connection conn = null; PreparedStatement pre = null; ResultSet rs = null; List<T> list = new ArrayList<>(); try { conn = getConnection(); pre = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { pre.setObject(i + 1, args[i]); } rs = pre.executeQuery(); ResultSetMetaData md = rs.getMetaData(); while (rs.next()) { T entity = c.newInstance(); // 获得元数据,包含结果集的列数,属性名,以及别名等信息。 int columnCount = md.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String key = md.getColumnName(i); Object value = rs.getObject(key); // Field field = c.getDeclaredField(key); // field.setAccessible(true); // field.set(entity, value); BeanUtils.setProperty(entity, key, value); } list.add(entity); } } catch (Exception e) { e.printStackTrace(); } finally { close(conn, pre, rs); } return list; } /** * * @param sql * @param args * @return 得到某一列的值如count(*),max(),min()之类的 */ public static Object getOneColum(String sql, Object... args) { Connection conn = null; PreparedStatement pre = null; ResultSet rs = null; try { conn = getConnection(); pre = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { pre.setObject(i + 1, args[i]); } rs = pre.executeQuery(); if (rs.next()) { return rs.getObject(1); } } catch (Exception e) { e.printStackTrace(); } finally { close(conn, pre, rs); } return null; } /** * * @param sql * @param args * @return 得到某张图片 */ public static Blob getOnePic(String sql, Object... args) { Connection conn = null; PreparedStatement pre = null; ResultSet rs = null; try { conn = getConnection(); pre = conn.prepareStatement(sql); for (int i = 0; i < args.length; i++) { pre.setObject(i + 1, args[i]); } rs = pre.executeQuery(); if (rs.next()) { return rs.getBlob(1); } } catch (Exception e) { e.printStackTrace(); } finally { close(conn, pre, rs); } return null; } public static void main(String[] args) throws Exception { Dorm dorm = new Dorm(); dorm.setDormid("N10B132"); dorm.setPeoplenum(6); insertObject(dorm); // String sql = "insert into Dorm(dormid,peoplenum) values ( 'N10B131','6' )"; // executeUpdate(sql); // } }
package de.marcoheintze.dartscoreboard.utils; public class DartsConstants { // Bogey-Numbers sind zahlen die zwar im Finish-Bereich liegen, // aber im Modus Double-Out mit 3 Darts nicht auszuwerfen sind. public static final int BOGEY_169 = 169; public static final int BOGEY_168 = 168; public static final int BOGEY_166 = 166; public static final int BOGEY_165 = 165; public static final int BOGEY_163 = 163; public static final int BOGEY_162 = 162; public static final int BOGEY_159 = 159; // Prueft einen geworfenen score, auf Bogey-Number public static boolean isBogeyNumber(int score) { switch(score) { case BOGEY_159 : case BOGEY_162 : case BOGEY_163 : case BOGEY_165 : case BOGEY_166 : case BOGEY_168 : case BOGEY_169 : return true; default :return false; } } // Prueft ob ein geworfener score im Finish-Bereich liegt public static boolean finishPossible(int score) { // score ist kleiner oder gleich 170 UND ist keine Bogey-Number if(score <= 170 && !isBogeyNumber(score)) { return true; } // score ist groesser 170 ODER eine Bogey-Number else return false; } }
package gabriel.luoyer.promonkey.cptslide; import gabriel.luoyer.promonkey.R; import gabriel.luoyer.promonkey.cptslide.ChapterFragment.onChapterPageClickListener; import gabriel.luoyer.promonkey.utils.Utils; import gabriel.luoyer.promonkey.view.ChapterToggleView; import java.util.ArrayList; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; /** * * @author gluoyer@gmail.com * */ public class ChapterSlideActivity extends FragmentActivity implements onChapterPageClickListener { private ChapterToggleView mToggleView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chapter); getViews(); getFlowView(); } private void getViews() { String[] names = getResources().getStringArray(R.array.array_cpt_slide_name); ViewPager vp = (ViewPager) findViewById(R.id.cpt_view_pager); final LinearLayout indexContainer = (LinearLayout) findViewById(R.id.cpt_index_container); // Get names list, and Alloc for page. int len = names.length; final int pn = ChapterAdapter.CHAPTER_PAGE_NUM; final int loop = len / pn + (len % pn == 0 ? 0 : 1); Utils.logh("ChapterSlideActivity", "name length: " + len + " loop: " + loop); ArrayList<ArrayList<String>> arrayLists = new ArrayList<ArrayList<String>>(); for(int i=0; i<loop; i++) { ArrayList<String> list = new ArrayList<String>(); int base = i * pn; int rang = base + pn > len ? len : base + pn; for(int j=base+0; j<rang; j++) { list.add(names[j]); } arrayLists.add(list); } // Set adapter for ViewPager, in order to slide. vp.setAdapter(new ChapterAdapter(getSupportFragmentManager(), arrayLists)); vp.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int position) { mToggleView.hiddenBars(); for(int i=0; i<loop; i++) { indexContainer.getChildAt(i).setSelected(i == position?true:false); } } }); // Bottom page select navigation if(loop > 1) { Utils.setVisible(indexContainer); for(int i=0; i<loop; i++) { ImageView focus; focus = new ImageView(this); focus.setBackgroundResource(R.drawable.shelf_circle_selector); indexContainer.addView(focus); focus.setSelected(i == 0?true:false); } } else { Utils.setInvisible(indexContainer); } } private void getFlowView() { // Add flow buttons layout, and buttons click listener View buttons = View.inflate(this, R.layout.chapter_toggle_buttons, null); addContentView(buttons, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); View more = buttons.findViewById(R.id.cpt_right_more); mToggleView = new ChapterToggleView(buttons, more); more.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mToggleView.hiddenBars(); Toast.makeText(ChapterSlideActivity.this, R.string.str_toast_click_anzai, Toast.LENGTH_SHORT).show(); } }); } @Override public void onChapterItemClick(int position, String name) { Toast.makeText(this, "Click " + (position + 1) + ": " + name, Toast.LENGTH_SHORT).show(); } @Override public void onChapterSpaceClick() { mToggleView.toggleBarView(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { mToggleView.toggleBarView(); return super.onPrepareOptionsMenu(menu); } }
import java.util.Date; import java.util.List; public class ServiceImpl implements Service { @Override @Cache(cacheType = CacheType.FILE, fileNamePrefix = "data", zip = true, identityBy = {String.class, double.class}) public List<String> work(String item) { return null; } @Override @Cache(cacheType = CacheType.IN_MEMORY, listList = 100_000) public List<String> run(String item, double value, Date date) { return null; } }
package com.cninnovatel.ev.conf; import java.text.SimpleDateFormat; import java.util.Locale; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.TextView; import com.cninnovatel.ev.BaseActivity; import com.cninnovatel.ev.HexMeet; import com.cninnovatel.ev.R; import com.cninnovatel.ev.api.model.RestMeeting; import com.cninnovatel.ev.type.HexMeetTab; import com.cninnovatel.ev.utils.CalendarUtil; import com.cninnovatel.ev.utils.ScreenUtil; public class ConferenceSchedulingOK extends BaseActivity { private Button share_wechat; private RestMeeting meeting; public static void actionStart(Activity context, RestMeeting meeting) { Intent intent = new Intent(context, ConferenceSchedulingOK.class); intent.putExtra("meeting", meeting); context.startActivity(intent); } private boolean isSomething(String str) { return str != null && !str.trim().equals(""); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); ScreenUtil.initStatusBar(this); setContentView(R.layout.conference_schedule_ok); meeting = (RestMeeting) getIntent().getSerializableExtra("meeting"); findViewById(R.id.back).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { HexMeet.currentTab = HexMeetTab.CONFERENCE; finish(); } }); TextView confName = (TextView) findViewById(R.id.call_title); confName.setText(" " + meeting.getName()); TextView conf_number = (TextView) findViewById(R.id.conf_number); conf_number.setText(" " + meeting.getNumericId() + ""); TextView conf_password = (TextView) findViewById(R.id.conf_password); conf_password.setText(isSomething(meeting.getConfPassword()) ? " " + meeting.getConfPassword().trim() : " [" + getString(R.string.no) + "]"); TextView conf_starttime = (TextView) findViewById(R.id.conf_starttime); conf_starttime.setText(" " + new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.SIMPLIFIED_CHINESE) .format(meeting.getStartTime())); TextView conf_endtime = (TextView) findViewById(R.id.conf_endtime); conf_endtime.setText(" " + new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.SIMPLIFIED_CHINESE).format(meeting .getStartTime() + meeting.getDuration())); share_wechat = (Button) findViewById(R.id.share_wechat); share_wechat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { WeChat.share(ConferenceSchedulingOK.this, meeting, true); finish(); } }); String sync = getSharedPreferences("settings", 0).getString("sync_calendar", "sync"); if (sync.equals("sync")) { CalendarUtil.addEvent(meeting); } } }
package cn.soulutions.pointJudger; import java.util.Scanner; //只能通过70%,求大佬帮忙看看 public class Main2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int N = input.nextInt(); int[][] p = new int[N][2]; for (int i = 0; i < N; i++) { p[i][0] = input.nextInt(); p[i][1] = input.nextInt(); } input.close(); Solution(N, p); } public static void Solution(int N, int[][] p) { QuickSort(p, 0, N - 1); int[] ymax = new int[N]; ymax[N - 1] = p[N - 1][1]; for (int i = N - 2; i >= 0; i--) { ymax[i] = (p[i][1] > ymax[i + 1]) ? p[i][1] : ymax[i + 1]; } for (int i = 0; i < N; i++) { if (p[i][1] == ymax[i]) { System.out.println(p[i][0] + " " + p[i][1]); } } } public static void QuickSort(int[][] p, int start, int end) { int i = start; int j = end; int k = p[start][0]; int[] t; while (i < j) { t = p[i]; while (i < j && p[j][0] >= k) { j--; } p[i] = p[j]; p[j] = t; while (i < j && p[i][0] <= k) { i++; } p[j] = p[i]; p[i] = t; } if (i - 1 > start) QuickSort(p, start, i - 1); if (i + 1 < end) QuickSort(p, i + 1, end); } }
/* * Copyright 2017 Goldman Sachs. * 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.gs.tablasco; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import java.io.IOException; public class HideMatchedTablesTest { @Rule public final TableVerifier tableVerifier = new TableVerifier() .withFilePerMethod() .withMavenDirectoryStrategy() .withHideMatchedTables(true); @Test public void matchedTablesAreHidden() throws IOException { final VerifiableTable matchTable = new TestTable("Col").withRow("A"); final VerifiableTable outOfOrderTableExpected = new TestTable("Col 1", "Col 2").withRow("A", "B"); final VerifiableTable outOfOrderTableActual = new TestTable("Col 2", "Col 1").withRow("B", "A"); final VerifiableTable breakTableExpected = new TestTable("Col").withRow("A"); final VerifiableTable breakTableActual = new TestTable("Col").withRow("B"); TableTestUtils.assertAssertionError(() -> tableVerifier.verify( TableTestUtils.toNamedTables("match", matchTable, "break", breakTableExpected, "outOfOrder", outOfOrderTableExpected), TableTestUtils.toNamedTables("match", matchTable, "break", breakTableActual, "outOfOrder", outOfOrderTableActual))); Assert.assertEquals( "<body>\n" + "<div class=\"metadata\"/>\n" + "<h1>matchedTablesAreHidden</h1>\n" + "<div id=\"matchedTablesAreHidden.break\">\n" + "<h2>break</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"pass\">Col</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"surplus\">B<p>Surplus</p>\n" + "</td>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"missing\">A<p>Missing</p>\n" + "</td>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "<div id=\"matchedTablesAreHidden.outOfOrder\">\n" + "<h2>outOfOrder</h2>\n" + "<table border=\"1\" cellspacing=\"0\">\n" + "<tr>\n" + "<th class=\"outoforder\">Col 2<p>Out of order</p>\n" + "</th>\n" + "<th class=\"pass\">Col 1</th>\n" + "</tr>\n" + "<tr>\n" + "<td class=\"outoforder\">B<p>Out of order</p>\n" + "</td>\n" + "<td class=\"pass\">A</td>\n" + "</tr>\n" + "</table>\n" + "</div>\n" + "</body>" , TableTestUtils.getHtml(this.tableVerifier, "body")); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.jearl.ejb.model.document; import org.jearl.ejb.model.Entity; /** * * @author bamasyali */ public interface Document<USER> extends Entity<Integer, USER> { Integer getDocId(); void setDocId(Integer id); String getDocTable(); void setDocTable(String table); int getDocRecord(); void setDocRecord(int record); String getDocFilename(); void setDocFilename(String filename); byte[] getDocFile(); void setDocFile(byte[] file); }
package com.yf.accountmanager.sqlite; import java.io.File; import java.util.Set; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import com.yf.accountmanager.sqlite.ISQLite.IPathColumns; public class IPathService { public static String TABLE = ISQLite.TABLE_IPATH, ID = IPathColumns.ID, NAME = IPathColumns.NAME, PATH = IPathColumns.PATH; public static boolean containPath(String path) { SQLiteDatabase db = ISQLite.getInstance(CommonService.context) .getReadableDatabase(); Cursor c = null; try { c = db.rawQuery("select " + ID + " from " + TABLE + " where " + PATH + "=?", new String[] { path }); boolean b = c != null && c.getCount() > 0; return b; } finally { if (c != null) c.close(); } } public static boolean insert(File file) { if (file == null) return false; SQLiteDatabase db = ISQLite.getInstance(CommonService.context) .getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(NAME, file.getName()); cv.put(PATH, file.getAbsolutePath()); return db.insert(TABLE, null, cv) > 0; } public static boolean deleteBYPath(String path) { if (TextUtils.isEmpty(path)) return false; SQLiteDatabase db = ISQLite.getInstance(CommonService.context) .getWritableDatabase(); return db.delete(TABLE, PATH + "=?", new String[] { path }) > 0; } public static boolean deleteById(int id) { if (id == 0) return false; SQLiteDatabase db = ISQLite.getInstance(CommonService.context) .getWritableDatabase(); return db.delete(TABLE, ID + "=?", new String[] { Integer.toString(id) }) > 0; } public static boolean batchDelete(Set<Integer> ids){ if(ids==null||ids.isEmpty()) return false; SQLiteDatabase db = ISQLite.getInstance(CommonService.context).getWritableDatabase(); int count = db.delete(TABLE, ID+" in(" + CommonService.concatenateIds(ids) + ")", null); return count > 0; } public static boolean update(String name, String path, int id) { if (id == 0) return false; SQLiteDatabase db = ISQLite.getInstance(CommonService.context) .getWritableDatabase(); ContentValues cv = new ContentValues(); if (name != null) cv.put(NAME, name); if (!TextUtils.isEmpty(path)) cv.put(PATH, path); return db.update(TABLE, cv, ID +"=?", new String[] { Integer.toString(id) }) > 0; } public static Cursor query() { SQLiteDatabase db = ISQLite.getInstance(CommonService.context) .getReadableDatabase(); Cursor c = null; c = db.rawQuery("select * from " + TABLE ,null); return c; } }
package com.example.android.stock_war; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.example.android.stock_war.adapter.FeedAdapter; import com.example.android.stock_war.model.Feed; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private RecyclerView.LayoutManager mLayoutManager; private FeedAdapter adapter; private List<Feed> feedList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new JsonTask(this).execute("http://almat.almafiesta.com/chirag/predictionf.json", "http://almat.almafiesta.com/chirag/dataf.json"); ArrayList<Integer> booljson= new ArrayList<>(); ArrayList<Float> datajson = new ArrayList<>(); datajson = getIndicators2(); booljson = getIndicators(); setContentView(R.layout.activity_main); feedList = new ArrayList<>(); adapter = new FeedAdapter(this, feedList); mLayoutManager = new LinearLayoutManager(MainActivity.this); recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(adapter); Feed feed = new Feed("BHEL", "Sect: Infrastucture", "O:" + datajson.get(0).toString(), "C: " + datajson.get(3).toString(), "L: " + datajson.get(2).toString(), "H: " + datajson.get(1).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(0), booljson.get(1), booljson.get(2), booljson.get(3), booljson.get(4)); feedList.add(0, feed); feed = new Feed("Sun TV", "Sect: Media", "O:" + datajson.get(4).toString(), "C: " + datajson.get(7).toString(), "L: " + datajson.get(6).toString(), "H: " + datajson.get(5).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(5), booljson.get(6), booljson.get(7), booljson.get(8), booljson.get(9)); feedList.add(0, feed); feed = new Feed("ICICI bank", "Sect: Banking", "O:" + datajson.get(8).toString(), "C: " + datajson.get(11).toString(), "L: " + datajson.get(10).toString(), "H: " + datajson.get(9).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(10), booljson.get(11), booljson.get(12), booljson.get(13), booljson.get(14)); feedList.add(0, feed); feed = new Feed("Bharat Forging", "Sect: Casting", "O:" + datajson.get(12).toString(), "C: " + datajson.get(15).toString(), "L: " + datajson.get(14).toString(), "H: " + datajson.get(13).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(15), booljson.get(16), booljson.get(17), booljson.get(18), booljson.get(19)); feedList.add(0, feed); feed = new Feed("LTFH", "Sect: Finance", "O:" + datajson.get(16).toString(), "C: " + datajson.get(19).toString(), "L: " + datajson.get(18).toString(), "H: " + datajson.get(17).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(20), booljson.get(21), booljson.get(22), booljson.get(23), booljson.get(24)); feedList.add(0, feed); feed = new Feed("Reliance", "Sect: Refineries", "O:" + datajson.get(20).toString(), "C: " + datajson.get(23).toString(), "L: " + datajson.get(22).toString(), "H: " + datajson.get(21).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(25), booljson.get(26), booljson.get(27), booljson.get(28), booljson.get(29)); feedList.add(0, feed); feed = new Feed("Maruti", "Sect: Automobiles", "O:" + datajson.get(24).toString(), "C: " + datajson.get(27).toString(), "L: " + datajson.get(26).toString(), "H: " + datajson.get(25).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(30), booljson.get(31), booljson.get(32), booljson.get(33), booljson.get(34)); feedList.add(0, feed); feed = new Feed("Infosys", "Sect: Software", "O:" + datajson.get(28).toString(), "C: " + datajson.get(31).toString(), "L: " + datajson.get(30).toString(), "H: " + datajson.get(29).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(35), booljson.get(36), booljson.get(37), booljson.get(38), booljson.get(39)); feedList.add(0, feed); feed = new Feed("Asian Paints", "Sect: Paints", "O:" + datajson.get(32).toString(), "C: " + datajson.get(35).toString(), "L: " + datajson.get(34).toString(), "H: " + datajson.get(33).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(40), booljson.get(41), booljson.get(42), booljson.get(43), booljson.get(44)); feedList.add(0, feed); feed = new Feed("BPCL", "Sect: Refineries", "O:" + datajson.get(36).toString(), "C: " + datajson.get(39).toString(), "L: " + datajson.get(38).toString(), "H: " + datajson.get(37).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(45), booljson.get(46), booljson.get(47), booljson.get(48), booljson.get(49)); feedList.add(0, feed); feed = new Feed("Airtel", "Sect: Communications", "O:" + datajson.get(40).toString(), "C: " + datajson.get(43).toString(), "L: " + datajson.get(42).toString(), "H: " + datajson.get(41).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(50), booljson.get(51), booljson.get(52), booljson.get(53), booljson.get(54)); feedList.add(0, feed); feed = new Feed("Tata Steel", "Sect: Steel", "O:" + datajson.get(44).toString(), "C: " + datajson.get(47).toString(), "L: " + datajson.get(46).toString(), "H: " + datajson.get(45).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(55), booljson.get(56), booljson.get(57), booljson.get(58), booljson.get(59)); feedList.add(0, feed); feed = new Feed("ITC", "Sect: FMCG", "O:" + datajson.get(48).toString(), "C: " + datajson.get(51).toString(), "L: " + datajson.get(50).toString(), "H: " + datajson.get(49).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(60), booljson.get(61), booljson.get(62), booljson.get(63), booljson.get(64)); feedList.add(0, feed); feed = new Feed("Lupin", "Sect: Pharmacy", "O:" + datajson.get(52).toString(), "C: " + datajson.get(55).toString(), "L: " + datajson.get(54).toString(), "H: " + datajson.get(53).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(65), booljson.get(66), booljson.get(67), booljson.get(68), booljson.get(69)); feedList.add(0, feed); feed = new Feed("McDowell", "CAT: Breweries", "O:" + datajson.get(56).toString(), "C: " + datajson.get(59).toString(), "L: " + datajson.get(58).toString(), "H: " + datajson.get(57).toString(), "https://s3.amazonaws.com/zaubatrademarks/11941166-0a1f-4ec0-872d-9e604ec9049c.png", booljson.get(70), booljson.get(71), booljson.get(72), booljson.get(73), booljson.get(74)); feedList.add(0, feed); Collections.reverse(feedList); adapter.notifyDataSetChanged(); } private ArrayList<Float> getIndicators2(){ String json = null; InputStream is = null; StringBuilder sb = new StringBuilder(); String path = this.getFilesDir().getAbsolutePath() + "/data.json"; FileInputStream fis = null; try { fis = new FileInputStream(path); InputStreamReader isr = new InputStreamReader(fis); BufferedReader bufferedReader = new BufferedReader(isr); String line; while((line = bufferedReader.readLine())!= null){ sb.append(line + "\n"); } fis.close(); }catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return str2arrdata(sb.toString()); } private ArrayList<Float> str2arrdata(String s) { ArrayList<Float> flarr = new ArrayList<Float>(); int count = 0; StringBuilder num = new StringBuilder(); for(int i = 0; i< s.length(); i++){ if(s.charAt(i) == '"') { count++; i++; Log.d("countrise", String.valueOf(count)); } if(count%20 !=1 && count%20 != 2 && count%20 != 3 && count%20 !=4 && count %4 == 3){ //i++; num.append(s.charAt(i)); } if(count%20 !=1 && count%20 != 2 && count%20 != 3 && count%20 !=4 && count %4 == 0){ DecimalFormat decimalFormat = new DecimalFormat("#0.00"); try { float number = decimalFormat.parse(num.toString()).floatValue(); flarr.add(number); Log.d("numberfinally", String.valueOf(number)); } catch (ParseException e) { Log.d("numberfinally", "not a valid number"+ String.valueOf(num)); } num = new StringBuilder(); } } Log.d("flarrsize", String.valueOf(flarr.size())); return flarr; } private ArrayList<Integer> getIndicators() { String json = null; InputStream is=null; StringBuilder sb = new StringBuilder(); try { String path = this.getFilesDir().getAbsolutePath() + "/" + "prediction.json"; FileInputStream fis = new FileInputStream(path); InputStreamReader isr = new InputStreamReader(fis); BufferedReader bufferedReader = new BufferedReader(isr); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line + "\n"); } fis.close(); Log.d("change", "profile.json was changed here"); }catch(Exception e){ Log.e("errorbigone", e.getMessage()); } Log.d("hereitisfucked", sb.toString()); return(str2arrindicators(sb.toString())); } private ArrayList<Integer> str2arrindicators(String s) { ArrayList<Integer> indiarray = new ArrayList<Integer>(); int cnt = 0; for(int i = 0 ;i <s.length(); i++){ if(s.charAt(i) == ':'){ indiarray.add(Character.getNumericValue(s.charAt(i+3)));Log.d("checkkk", Integer.toString(indiarray.get(cnt))); cnt++; } } return indiarray; } }
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import com.sun.xml.bind.CycleRecoverable; public class Main { public static void main(String[] args) throws JAXBException { // let's create an obvious cycle Person p = new Person(); p.id = 5; p.name = "Joe Chin"; p.parent = p; JAXBContext context = JAXBContext.newInstance(Person.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); m.marshal(p,System.out); } }
package com.codebook.gpa4; import androidx.appcompat.app.AppCompatActivity; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.textfield.TextInputEditText; import xyz.hanks.library.bang.SmallBangView; public class CumulativeGPAFragment extends AppCompatActivity { private double total1 = 0.0, total2 = 0.0, total3 = 0.0, hSum1 = 0.0, totalSemGPA =0.0 ,finalGPA=0.0,cum=0.0,sem=0.0,cumH=0.0,semH=0.0; private TextView semTextView,cumTV; private TextInputEditText cumET,cumHourET,semET,semHourET; LinearLayout semesterLinearLayout; boolean flag=false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cumulative_gpafragment); final SmallBangView like_heart = findViewById(R.id.like); like_heart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (like_heart.isSelected()) { like_heart.setSelected(false); } else { like_heart.setSelected(true); like_heart.likeAnimation(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); Intent intent=new Intent(CumulativeGPAFragment.this,BreakAds.class); startActivity(intent); } }); } } }); Intent intent=getIntent(); semTextView=findViewById(R.id.semtextView); cumTV=findViewById(R.id.cumTV); cumET=(TextInputEditText)findViewById(R.id.cumET); semET=(TextInputEditText)findViewById(R.id.semET); cumHourET=(TextInputEditText)findViewById(R.id.cumHourET); semHourET=(TextInputEditText)findViewById(R.id.semHourET); semesterLinearLayout=(LinearLayout) findViewById(R.id.semesterLinearLayout); total1=Double.parseDouble(intent.getStringExtra(MainActivity.EXTRA_TOTAL1)); hSum1 =Double.parseDouble(intent.getStringExtra(MainActivity.EXTRA_HOURS)); if(hSum1 !=0.0 ) { totalSemGPA = total1 / hSum1; if(totalSemGPA ==0.0) { semesterLinearLayout.setVisibility(View.VISIBLE); semTextView.setVisibility(View.GONE); flag=false; } else { semesterLinearLayout.setVisibility(View.GONE); semTextView.setVisibility(View.VISIBLE); String s= String.format(getText(R.string.semester_gpa) +"= %.5s", totalSemGPA) ; semTextView.setText(s); flag=true; } } } public void calculate(View view) { try { if(flag==false) { cum=Double.parseDouble(cumET.getText().toString()); cumH=Double.parseDouble(cumHourET.getText().toString()); sem=Double.parseDouble(semET.getText().toString()); semH=Double.parseDouble(semHourET.getText().toString()); total2=cum * cumH; total3=sem * semH; double h=cumH + semH; if((cumH+semH)!=0) { double GPA = (total2 + total3)/h; cumTV.setText(String.format(getText(R.string.cumulative_gpa) + "=%.5s", GPA)); } else { //toast } } else { cum=Double.parseDouble(cumET.getText().toString()); cumH=Double.parseDouble(cumHourET.getText().toString()); total2=cum*cumH; if ((cumH + hSum1) != 0) { finalGPA = (total2 + total1) / (cumH + hSum1); cumTV.setText(String.format(getText(R.string.cumulative_gpa) + "=%.5s", finalGPA)); } else { //toast } }} catch (Exception e) { Toast.makeText(getApplicationContext(),R.string.emptyFields,Toast.LENGTH_SHORT).show(); } /* total2 = 0.0; total3 = 0.0; totalSemGPA =0.0 ; finalGPA=0.0; cum=0.0; flag=false; sem=0.0;cumH =0.0; semH=0.0;*/ } public void back(View view) { Intent intent=new Intent(CumulativeGPAFragment.this,MainActivity.class); startActivity(intent); } }
package cn.test.clone.deep.serializable; import java.io.*; /** * Created by xiaoni on 2018/12/19. */ public class Student2 implements Serializable { /** * */ public static final long serialVersionUID = 1L; public String name;// 常量对象。 public int age; public Professor2 p;// 学生1和学生2的引用值都是一样的。 public Student2(String name, int age, Professor2 p) { this.name = name; this.age = age; this.p = p; } public Object deepClone() throws IOException, ClassNotFoundException { // 将对象写到流里 ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(this); // 从流里读出来 ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi = new ObjectInputStream(bi); return (oi.readObject()); } }
package lk.logic; /** *@author Veranga Sooriyabandara *Our Java Class */ public interface UserLoginInterface { public boolean checkUserEnteredPINs(String PIN1,String PIN2); }
package com.worldchip.bbpaw.bootsetting.util; import android.net.Uri; public class Utils { /** 用户注册本地shard保存key **/ public static final String IS_FIRST_START_KEY = "first_start"; public static final String PHOTO_SHARD_KEY = "user_photo"; public static final String USERNAME_SHARD_KEY = "user_name"; public static final String GENDER_SHARD_KEY = "user_gender"; public static final String DOB_SHARD_KEY = "user_dob"; public static final String EMAIL_SHARD_KEY = "user_email"; public static final String PASSWORD_SHARD_KEY = "user_password"; public static final String DEVICEID_SHARD_KEY = "user_device_id"; public static final String TERMS_ENABLE_SHARD_KEY = "terms_enable"; public static final String LANGUAGE_SHARD_KEY = "language"; public static final String UPDATE_SYSTEMUI = "cn.worldchip.www.UPDATE_SYSTEMUI"; /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is Google Photos. */ public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri.getAuthority()); } }
package com.mvc.btc.simulator; /** * Created by lrkin on 2017/6/7. */ public enum LaneType { enLane, exLane; private LaneType() { } }
/* * Copyright (c) 2013-2014, Neuro4j.org * * 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 org.neuro4j.studio.properties.sources; import org.eclipse.ui.views.properties.IPropertyDescriptor; import org.eclipse.ui.views.properties.IPropertySource; import org.eclipse.ui.views.properties.TextPropertyDescriptor; import org.neuro4j.studio.core.KeyValuePair; import org.neuro4j.studio.core.Node; /** */ public class StandardPropertySource implements IPropertySource { Node node = null; KeyValuePair pair = null; public static String SOURCE = "Source"; //$NON-NLS-1$ public static String TARGET = "Target"; //$NON-NLS-1$ protected static IPropertyDescriptor[] descriptors; static { descriptors = new IPropertyDescriptor[] { new TextPropertyDescriptor(SOURCE, "Name"), new TextPropertyDescriptor(TARGET, "Value") }; } public StandardPropertySource(Node node, KeyValuePair pair) { this.node = node; this.pair = pair; } protected void firePropertyChanged(String propName, Object oldValue, Object newValue) { node.notifyPropertyChanged(oldValue, newValue); } public Object getEditableValue() { return this; } public IPropertyDescriptor[] getPropertyDescriptors() { return descriptors; } public Object getPropertyValue(Object propName) { if (SOURCE.equals(propName)) { return pair.getKey(); } if (TARGET.equals(propName)) { return pair.getValue(); } return null; } public KeyValuePair getPair() { return pair; } // public Point getValue(){ // return new Point(point.x, point.y); // } /** * @see org.eclipse.ui.views.properties.IPropertySource#isPropertySet(Object) */ public boolean isPropertySet(Object propName) { if (SOURCE.equals(propName) || TARGET.equals(propName)) return true; return false; } public void resetPropertyValue(Object propName) { } public void setPropertyValue(Object propName, Object value) { if (SOURCE.equals(propName)) { pair.setKey(value.toString()); } if (TARGET.equals(propName)) { pair.setValue(value.toString()); } firePropertyChanged((String) propName, null, value); } public String toString() { return pair.getValue(); } }
package com.hzero.order.app.service; import com.hzero.order.domain.entity.SoHeader; import org.springframework.http.ResponseEntity; import java.security.Principal; /** * 应用服务 * */ public interface SoHeaderService { ResponseEntity<String> updateStatus(String status,SoHeader soHeader, Principal principal); }
import static org.junit.Assert.*; import org.junit.Test; public class tgTest { private Triangle triangle; private Triangle illegalTriangle; private Triangle illegalTriangle2; private Triangle regularTriangle; private Triangle isoscelesTriangle; @Test public void test(){ triangle = new Triangle(3, 4, 5); illegalTriangle = new Triangle(-1, 2, 3); illegalTriangle2 = new Triangle(1, 2, 5); regularTriangle = new Triangle(2, 2, 2); isoscelesTriangle = new Triangle(2, 2, 3); assertEquals(true, triangle.isTriangle(triangle)); assertEquals(false, triangle.isTriangle(illegalTriangle)); assertEquals(false, triangle.isTriangle(illegalTriangle2)); assertEquals("Scalene", triangle.getType(triangle)); assertEquals("Regular", triangle.getType(regularTriangle)); assertEquals("Isosceles", triangle.getType(isoscelesTriangle)); assertEquals("Illegal", triangle.getType(illegalTriangle)); long[] borders = triangle.getBorders(); long[] expected = {(long)3.0, (long)4.0, (long)5.0}; for(int i = 0; i < 3; i++){ assertEquals(expected[i], borders[i], 0.1); } // assertEquals(1, triangle.diffOfBorders(2, 1), 0.0); } }
package co.jijichat.muc; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import tigase.jaxmpp.core.client.BareJID; import tigase.jaxmpp.core.client.JID; import tigase.jaxmpp.core.client.SessionObject; import tigase.jaxmpp.core.client.exceptions.JaxmppException; import tigase.jaxmpp.core.client.observer.Listener; import tigase.jaxmpp.core.client.xml.XMLException; import tigase.jaxmpp.core.client.xmpp.modules.chat.Chat; import tigase.jaxmpp.core.client.xmpp.modules.chat.MessageModule; import tigase.jaxmpp.core.client.xmpp.modules.muc.MucModule; import tigase.jaxmpp.core.client.xmpp.modules.muc.MucModule.MucEvent; import tigase.jaxmpp.core.client.xmpp.modules.muc.Occupant; import tigase.jaxmpp.core.client.xmpp.modules.muc.Room; import tigase.jaxmpp.j2se.Jaxmpp; import android.app.Activity; import android.app.Dialog; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import co.jijichat.Constants; import co.jijichat.MessengerApplication; import co.jijichat.R; import co.jijichat.chat.ChatActivity; import co.jijichat.db.NicknameCacheTableMetaData; import co.jijichat.db.providers.MergeSort; import co.jijichat.db.providers.RosterProvider; import co.jijichat.vcard.VCardViewActivity; public class OccupantsListDialog extends DialogFragment { private class OccupantsAdapter extends BaseAdapter { private static final String TAG = "OccupantsAdapter"; private final LayoutInflater mInflater; private final ArrayList<Occupant> occupants = new ArrayList<Occupant>(); public OccupantsAdapter(Context mContext, Room room) { mInflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); occupants.addAll(room.getPresences().values()); sortList(); notifyDataSetChanged(); } public void add(Occupant occupant) { occupants.add(occupant); sortList(); notifyDataSetChanged(); } @Override public int getCount() { return occupants.size(); } @Override public Object getItem(int arg0) { Occupant o = occupants.get(arg0); return o; } @Override public long getItemId(int position) { return occupants.get(position).hashCode(); } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate(R.layout.muc_occupants_list_item, parent, false); } else { view = convertView; } final Occupant occupant = (Occupant) getItem(position); final TextView nicknameTextView = (TextView) view .findViewById(R.id.occupant_nick); final TextView mentionTextView = (TextView) view .findViewById(R.id.mention_occupant); final TextView messageTextView = (TextView) view .findViewById(R.id.message_occupant); final TextView profileTextView = (TextView) view .findViewById(R.id.profile_occupant); try { final String nickname = occupant.getNickname(); nicknameTextView.setText(nickname); if (nickname.equals(room.getSessionObject().getUserProperty( SessionObject.NICKNAME))) { mentionTextView.setVisibility(View.GONE); messageTextView.setVisibility(View.GONE); profileTextView.setVisibility(View.GONE); nicknameTextView.setTextColor(getResources().getColor( R.color.actionBar_bg)); } else { mentionTextView.setVisibility(View.VISIBLE); messageTextView.setVisibility(View.VISIBLE); profileTextView.setVisibility(View.VISIBLE); nicknameTextView.setTextColor(Color.BLACK); } final BareJID jid = BareJID.bareJIDInstance(occupant .getPresence() .getChildrenNS("x", "http://jabber.org/protocol/muc#user") .getFirstChild().getAttribute("jid")); messageTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { ContentValues values = new ContentValues(); try { values.put( NicknameCacheTableMetaData.FIELD_NICKNAME, occupant.getNickname()); } catch (XMLException e) { e.printStackTrace(); } getActivity().getContentResolver().insert( Uri.parse(RosterProvider.NICKNAME_URI + "/" + Uri.encode(jid.toString())), values); openChatWith(jid); } }); mentionTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(); try { intent.putExtra("nickname", occupant.getNickname()); } catch (XMLException e) { } getTargetFragment().onActivityResult( getTargetRequestCode(), Activity.RESULT_OK, intent); getDialog().dismiss(); } }); profileTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent i = new Intent(getActivity(), VCardViewActivity.class); i.putExtra("jid", jid.toString()); startActivity(i); } }); } catch (Exception e) { Log.e(TAG, "Can't show occupant", e); } return view; } public void remove(Occupant occupant) { occupants.remove(occupant); sortList(); notifyDataSetChanged(); } public void update(Occupant occupant) { occupants.remove(occupant); occupants.add(occupant); sortList(); notifyDataSetChanged(); } private void sortList() { MergeSort.sort(occupants, new Comparator<Occupant>() { @Override public int compare(Occupant object1, Occupant object2) { try { String n1 = object1.getNickname(); String n2 = object2.getNickname(); return n1.compareTo(n2); } catch (Exception e) { return 0; } } }); } } public static OccupantsListDialog newInstance() { Bundle args = new Bundle(); return newInstance(args); } public static OccupantsListDialog newInstance(Bundle args) { OccupantsListDialog frag = new OccupantsListDialog(); frag.setArguments(args); return frag; } private OccupantsAdapter adapter; private final Listener<MucEvent> mucListener; private MucModule mucModule; private ListView occupantsList; private Room room; public OccupantsListDialog() { mucListener = new Listener<MucEvent>() { @Override public void handleEvent(MucEvent be) throws JaxmppException { if (be.getRoom() == room && adapter != null) onRoomEvent(be); } }; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Dialog dialog = new Dialog(getActivity()); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); dialog.setContentView(R.layout.muc_occupants_list); dialog.setTitle(getString(R.string.occupants_title)); Bundle data = getArguments(); long roomId = data.getLong("roomId", -1); room = findRoomById(roomId); mucModule = getJaxmpp().getModule(MucModule.class); mucModule.addListener(mucListener); occupantsList = (ListView) dialog.findViewById(R.id.occupants_list); // occupantsList.setOnItemClickListener(new OnItemClickListener() { // // @Override // public void onItemClick(AdapterView<?> parent, View v, // int position, long id) { // Occupant occupant = (Occupant) parent // .getItemAtPosition(position); // // Intent intent = new Intent(); // // try { // intent.putExtra("nickname", occupant.getNickname()); // } catch (XMLException e) { // } // // getTargetFragment().onActivityResult(getTargetRequestCode(), // Activity.RESULT_OK, intent); // // dialog.dismiss(); // } // }); adapter = new OccupantsAdapter(getActivity(), room); occupantsList.setAdapter(adapter); return dialog; } private Room findRoomById(long roomId) { Collection<Room> rooms = getRooms(); synchronized (rooms) { for (Room r : rooms) { if (r.getId() == roomId) return r; } } return null; } private Jaxmpp getJaxmpp() { return ((MessengerApplication) getActivity().getApplicationContext()) .getJaxmpp(); } private Collection<Room> getRooms() { return getJaxmpp().getModule(MucModule.class).getRooms(); } protected void onRoomEvent(final MucEvent be) { occupantsList.post(new Runnable() { @Override public void run() { if (be.getType() == MucModule.OccupantComes) { adapter.add(be.getOccupant()); } else if (be.getType() == MucModule.OccupantLeaved) { adapter.remove(be.getOccupant()); } else if (be.getType() == MucModule.OccupantChangedPresence) { adapter.update(be.getOccupant()); } else if (be.getType() == MucModule.OccupantChangedNick) { adapter.update(be.getOccupant()); } adapter.notifyDataSetChanged(); } }); } protected void openChatWith(final BareJID bareJID) { new Runnable() { @Override public void run() { try { final Jaxmpp jaxmpp = getJaxmpp(); Chat chat = findChat(bareJID); if (chat == null) { chat = jaxmpp.createChat(JID.jidInstance(bareJID, Constants.RESOURCE)); } Intent i = new Intent(getActivity(), ChatActivity.class); i.putExtra("chatId", chat.getId()); startActivity(i); } catch (JaxmppException e) { throw new RuntimeException(e); } } }.run(); } protected Chat findChat(final BareJID bareJID) { List<Chat> l = getChatList(); for (int i = 0; i < l.size(); i++) { Chat c = l.get(i); if (c.getJid().getBareJid().equals(bareJID)) return c; } return null; } protected List<Chat> getChatList() { return getJaxmpp().getModule(MessageModule.class).getChatManager() .getChats(); } }
package com.grognak.sobuddy.app; public class Main { public static void main(String[] args) { QueryTerminal queryTerminal = new QueryTerminal(); queryTerminal.startLoop(); } }
/* * lcmsCourseOrgDAO.java 1.00 2011-09-05 * * Copyright (c) 2011 ???? Co. All Rights Reserved. * * This software is the confidential and proprietary information * of um2m. You shall not disclose such Confidential Information * and shall use it only in accordance with the terms of the license agreement * you entered into with um2m. */ package egovframework.adm.lcms.cts.dao; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import egovframework.rte.psl.dataaccess.EgovAbstractDAO; /** * <pre> * system : * menu : * source : LcmsMetadataDAO.java * description : * </pre> * @version * <pre> * 1.0 2011-09-05 created by ? * 1.1 * </pre> */ @Repository("lcmsMetadataDAO") public class LcmsMetadataDAO extends EgovAbstractDAO{ public int selectLcmsMetadataSeq( Map<String, Object> commandMap) throws Exception{ return (Integer)getSqlMapClientTemplate().queryForObject("lcmsMetadataDAO.selectLcmsMetadataSeq", commandMap); } public Object insertLcmsMetadata( Map<String, Object> commandMap) throws Exception{ return insert("lcmsMetadataDAO.insertLcmsMetadata", commandMap); } public int selectElementSeq( Map<String, Object> commandMap) throws Exception{ return (Integer)getSqlMapClientTemplate().queryForObject("lcmsMetadataDAO.selectElementSeq", commandMap); } public Object insertMetadataElement( Map<String, Object> commandmap) throws Exception{ return insert("lcmsMetadataDAO.insertMetadataElement", commandmap); } public int deleteLcmsMetadataElement(Map<String, Object> commandMap) throws Exception{ return delete("lcmsMetadataDAO.deleteLcmsMetadataElement", commandMap); } public int deleteLcmsMetadata(Map<String, Object> commandMap) throws Exception{ return delete("lcmsMetadataDAO.deleteLcmsMetadata", commandMap); } public List selectLcmsMetadataElementList(Map<String, Object> commandMap) throws Exception{ return list("lcmsMetadataDAO.selectLcmsMetadataElementList", commandMap); } public int updateLcmsMetadataElement(Map<String, Object> commandMap) throws Exception{ return update("lcmsMetadataDAO.updateLcmsMetadataElement", commandMap); } public int selectLcmsMetadataCount(Map<String, Object> commandMap) throws Exception{ return (Integer)getSqlMapClientTemplate().queryForObject("lcmsMetadataDAO.selectLcmsMetadataCount", commandMap); } public int selectLcmsMetadataElementCount(Map<String, Object> commandMap) throws Exception{ return (Integer)getSqlMapClientTemplate().queryForObject("lcmsMetadataDAO.selectLcmsMetadataElementCount", commandMap); } }
package io.github.stepheniskander.equationsolver; public class Matrix { private RationalNumber[][] numMatrix; public Matrix(RationalNumber[][] constructorMatrix) { numMatrix = constructorMatrix; } public static Matrix matrixMultiply(Matrix m1, Matrix m2) { RationalNumber[][] result = new RationalNumber[m1.getColumns()][m2.getRows()]; for (int i = 0; i < m1.getColumns(); i++) { for (int j = 0; j < m2.getRows(); j++) { result[i][j] = RationalNumber.ZERO; for (int k = 0; k < m1.getRows(); k++) { result[i][j] = result[i][j].add(m1.getMatrix()[i][k].multiply(m2.getMatrix()[k][j])); } } } return new Matrix(result); } public int getColumns() { return numMatrix.length; } public int getRows() { return numMatrix[0].length; } public RationalNumber[][] getMatrix() { return numMatrix; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < getColumns(); i++) { sb.append("["); for (int j = 0; j < getRows(); j++) sb.append(numMatrix[i][j].toString()).append(","); sb.replace(sb.length() - 1, sb.length(), "] "); } sb.replace(sb.length() - 1, sb.length(), "]"); return sb.toString(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Matrix)) return false; Matrix m = (Matrix) obj; if (this.getRows() != m.getRows() || this.getColumns() != m.getColumns()) return false; for (int i = 0; i < this.getColumns(); i++) { for (int j = 0; j < this.getColumns(); j++) { if (!this.getMatrix()[i][j].equals(m.getMatrix()[i][j])) return false; } } return true; } }
import java.util.Random; import java.util.Scanner; public class Main { public int size; public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.println("Размер матрицы: "); int size = input.nextInt(); int matrix[][] = new int[size][size]; Random random = new Random(); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { matrix[i][j] = random.nextInt(500); } } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } MyThread[] thread = new MyThread[size]; for (int i=0;i<thread.length;i++){ thread[i] = new MyThread(matrix[i]); thread[i].start(); } int m = Integer.MIN_VALUE; try { for(int i=0;i<thread.length;i++){ thread[i].join(); m = Math.max(m,thread[i].getMax()); } } catch (InterruptedException e){ System.out.println("Поток прерывался"); } System.out.println("Максимум= "+m); } }
package com.auro.scholr.home.presentation.view.fragment; import android.Manifest; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.MediaStore; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.webkit.JavascriptInterface; import android.webkit.PermissionRequest; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.camera.core.CameraSelector; import androidx.camera.core.CameraX; import androidx.camera.core.ImageCapture; import androidx.camera.core.Preview; import androidx.camera.extensions.HdrImageCaptureExtender; import androidx.camera.lifecycle.ProcessCameraProvider; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.ViewModelProviders; import com.auro.scholr.R; import com.auro.scholr.core.application.AuroApp; import com.auro.scholr.core.application.base_component.BaseFragment; import com.auro.scholr.core.application.di.component.ViewModelFactory; import com.auro.scholr.core.common.AppConstant; import com.auro.scholr.core.database.AppPref; import com.auro.scholr.core.database.PrefModel; import com.auro.scholr.core.network.URLConstant; import com.auro.scholr.databinding.QuizTestLayoutBinding; import com.auro.scholr.home.data.model.AssignmentReqModel; import com.auro.scholr.home.data.model.AssignmentResModel; import com.auro.scholr.home.data.model.DashboardResModel; import com.auro.scholr.home.data.model.QuizResModel; import com.auro.scholr.home.data.model.SaveImageReqModel; import com.auro.scholr.home.presentation.view.activity.newDashboard.StudentMainDashboardActivity; import com.auro.scholr.home.presentation.viewmodel.QuizTestViewModel; import com.auro.scholr.util.AppLogger; import com.auro.scholr.util.AppUtil; import com.auro.scholr.util.TextUtil; import com.auro.scholr.util.ViewUtil; import com.auro.scholr.util.alert_dialog.CustomDialogModel; import com.auro.scholr.util.alert_dialog.CustomProgressDialog; import com.auro.scholr.util.alert_dialog.InstructionDialog; import com.google.common.util.concurrent.ListenableFuture; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Objects; import java.util.concurrent.ExecutionException; import javax.inject.Inject; import javax.inject.Named; import static com.auro.scholr.core.common.Status.ASSIGNMENT_STUDENT_DATA_API; /** * Created by varun */ @SuppressLint("SetJavaScriptEnabled") public class QuizTestFragment extends BaseFragment implements View.OnClickListener { public static final String TAG = "QuizTestFragment"; @Inject @Named("QuizTestFragment") ViewModelFactory viewModelFactory; private static final int INPUT_FILE_REQUEST_CODE = 1; private WebSettings webSettings; private ValueCallback<Uri[]> mUploadMessage; private String mCameraPhotoPath = null; private long size = 0; QuizTestLayoutBinding binding; private WebView webView; DashboardResModel dashboardResModel; QuizTestViewModel quizTestViewModel; QuizResModel quizResModel; AssignmentResModel assignmentResModel; InstructionDialog customDialog; Dialog customProgressDialog; AssignmentReqModel assignmentReqModel; boolean submittingTest = false; // Storage Permissions variables private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA }; /*Camera x code */ Handler handler = new Handler(); /*End of cmera x code*/ @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); ViewUtil.setLanguageonUi(getActivity()); AuroApp.getAppContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); if (binding == null) { binding = DataBindingUtil.inflate(inflater, getLayout(), container, false); AuroApp.getAppComponent().doInjection(this); quizTestViewModel = ViewModelProviders.of(this, viewModelFactory).get(QuizTestViewModel.class); binding.setLifecycleOwner(this); setHasOptionsMenu(true); } AppLogger.e(TAG, "Step 1"); setRetainInstance(true); ViewUtil.setActivityLang(getActivity()); return binding.getRoot(); } @Override public void onStop() { super.onStop(); getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE); } @Override public void onDestroy() { if (webView != null) { webView.destroy(); } if (customDialog != null) { customDialog.cancel(); } handler.removeCallbacksAndMessages(null); ViewUtil.setLanguageonUi(getActivity()); super.onDestroy(); } @Override protected void init() { //setKeyListner(); ((StudentMainDashboardActivity) getActivity()).setDashboardApiCallingInPref(true); setListener(); AppLogger.e(TAG, "Step 2"); if (dashboardResModel != null && quizResModel != null) { AppLogger.e(TAG, "Step 3"); assignmentReqModel = quizTestViewModel.homeUseCase.getAssignmentRequestModel(dashboardResModel, quizResModel); quizTestViewModel.getAssignExamData(assignmentReqModel); } ((StudentMainDashboardActivity) getActivity()).loadPartnerLogo(binding.auroScholarLogo); } private void observeServiceResponse() { quizTestViewModel.serviceLiveData().observeForever(responseApi -> { switch (responseApi.status) { case LOADING: handleProgress(0, ""); break; case SUCCESS: if (responseApi.apiTypeStatus == ASSIGNMENT_STUDENT_DATA_API) { AppLogger.e(TAG, "Step 3"); assignmentResModel = (AssignmentResModel) responseApi.data; if (!assignmentResModel.isError()) { String webUrl = URLConstant.TEST_URL + "StudentID=" + assignmentResModel.getStudentID() + "&ExamAssignmentID=" + assignmentResModel.getExamAssignmentID(); openDialog(); loadWeb(webUrl); checkNativeCameraEnableOrNot(); } else { handleProgress(2, assignmentResModel.getMessage()); } } break; case NO_INTERNET: handleProgress(2, getActivity().getResources().getString(R.string.internet_check)); break; case AUTH_FAIL: case FAIL_400: default: handleProgress(2, getActivity().getResources().getString(R.string.default_error)); break; } }); } @Override protected void setToolbar() { /*Do cod ehere*/ } @Override protected void setListener() { ((StudentMainDashboardActivity)getActivity()).setListingActiveFragment(StudentMainDashboardActivity.QUIZ_TEST_FRAGMENT); binding.backButton.setOnClickListener(this); if (quizTestViewModel != null && quizTestViewModel.serviceLiveData().hasObservers()) { quizTestViewModel.serviceLiveData().removeObservers(this); } else { observeServiceResponse(); } } @Override protected int getLayout() { return R.layout.quiz_test_layout; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); dashboardResModel=AppPref.INSTANCE.getModelInstance().getDashboardResModel(); quizResModel=AppPref.INSTANCE.getModelInstance().getQuizResModel(); /* if (getArguments() != null) { dashboardResModel = getArguments().getParcelable(AppConstant.DASHBOARD_RES_MODEL); quizResModel = getArguments().getParcelable(AppConstant.QUIZ_RES_MODEL); }*/ init(); } public void openQuizHomeFragment() { getActivity().getSupportFragmentManager().popBackStack();//old code//refrence https://stackoverflow.com/questions/53566847/popbackstack-causing-java-lang-illegalstateexception-can-not-perform-this-actio // getActivity().getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } public void openDemographicFragment() { Bundle bundle = new Bundle(); DemographicFragment demographicFragment = new DemographicFragment(); bundle.putParcelable(AppConstant.DASHBOARD_RES_MODEL, dashboardResModel); demographicFragment.setArguments(bundle); openFragment(demographicFragment); } private void openFragment(Fragment fragment) { getActivity().getSupportFragmentManager().popBackStack(); getActivity().getSupportFragmentManager() .beginTransaction() .setReorderingAllowed(true) .replace(AuroApp.getFragmentContainerUiId(), fragment, KYCViewFragment.class .getSimpleName()) .addToBackStack(null) .commitAllowingStateLoss(); } @Override public void onResume() { super.onResume(); getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); setListener(); } @Override public void onDestroyView() { super.onDestroyView(); } @SuppressLint("JavascriptInterface") private void loadWeb(String webUrl) { webView = binding.webView; webSettings = webView.getSettings(); webSettings.setAppCacheEnabled(true); webSettings.setCacheMode(webSettings.LOAD_CACHE_ELSE_NETWORK); webSettings.setJavaScriptEnabled(true); webSettings.setLoadWithOverviewMode(true); webSettings.setDomStorageEnabled(true); webSettings = binding.webView.getSettings(); webSettings.setPluginState(WebSettings.PluginState.ON); webSettings.setMediaPlaybackRequiresUserGesture(false); webSettings.setAllowFileAccess(true); webSettings.setUserAgentString("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36"); webView.setWebViewClient(new PQClient()); webView.setWebChromeClient(new PQChromeClient()); //if SDK version is greater of 19 then activate hardware acceleration otherwise activate software acceleration if (Build.VERSION.SDK_INT >= 19) { webView.setLayerType(View.LAYER_TYPE_HARDWARE, null); } else if (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT < 19) { webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } webView.addJavascriptInterface(new MyJavaScriptInterface(getActivity()), "ButtonRecognizer"); webView.loadUrl(webUrl); } @Override public void onClick(View view) { int viewId = view.getId(); if (viewId == R.id.backButton) { ((StudentMainDashboardActivity) getActivity()).alertDialogForQuitQuiz(); } } public void onBackPressed() { getActivity().getSupportFragmentManager().popBackStack(); AppLogger.v("AUROSCHOLAR","Auroscholar"); } class MyJavaScriptInterface { private Context ctx; MyJavaScriptInterface(Context ctx) { this.ctx = ctx; } @JavascriptInterface public void boundMethod(String html) { // binding.previewView.setVisibility(View.INVISIBLE); openProgressDialog(); AppLogger.e("chhonker bound method", html); /* new Handler().postDelayed(new Runnable() { @Override public void run() { cancelDialogAfterSubmittingTest(); } }, 8000); */ } } private void cancelDialogAfterSubmittingTest() { if (!submittingTest) { submittingTest = true; if (customProgressDialog != null) { customProgressDialog.cancel(); } if (!quizTestViewModel.homeUseCase.checkDemographicStatus(dashboardResModel)) { openDemographicFragment(); } else { openQuizHomeFragment(); } } PrefModel prefModel = AppPref.INSTANCE.getModelInstance(); if (prefModel != null) { assignmentReqModel.setSubjectPos(quizResModel.getSubjectPos()); prefModel.setAssignmentReqModel(assignmentReqModel); AppPref.INSTANCE.setPref(prefModel); } } public class PQClient extends WebViewClient { public boolean shouldOverrideUrlLoading(WebView view, String url) { // If url contains mailto link then open Mail Intent AppLogger.e("chhonker shouldOverrideUrlLoading", url); if (url.contains("mailto:")) { // Could be cleverer and use a regex //Open links in new browser view.getContext().startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } else { //Stay within this webview and load url view.loadUrl(url); return true; } } //Show loader on url load public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); AppLogger.e("chhonker onPageStarted", url); if (!TextUtil.isEmpty(url)) { if (url.equalsIgnoreCase("https://auroscholar.com/index.php") || url.contains("demographics") || url.contains("dashboard")) { // binding.previewView.setVisibility(View.INVISIBLE); cancelDialogAfterSubmittingTest(); } } } // Called when all page resources loaded public void onPageFinished(WebView view, String url) { //webView.loadUrl("<button type=\"button\" value=\"Continue\" onclick=\"Continue.performClick(this.value);\">Continue</button>\n"); AppLogger.e("chhonker Finished", url); loadEvent(clickListener()); if (!TextUtil.isEmpty(url) && url.equalsIgnoreCase("https://assessment.eklavvya.com/Exam/CandidateExam")) { AppLogger.e("chhonker Finished exam", url); closeDialog(); } handleProgress(1, ""); } private void closeDialog() { new Handler().postDelayed(new Runnable() { @Override public void run() { if (customDialog != null) { customDialog.cancel(); } } }, 2000); } private void loadEvent(String javascript) { webView.loadUrl("javascript:" + javascript); } private String clickListener() { return getButtons() + "for(var i = 0; i < buttons.length; i++){\n" + "\tbuttons[i].onclick = function(){ console.log('click worked.'); ButtonRecognizer.boundMethod('button clicked'); };\n" + "}"; } private String getButtons() { // return "var buttons = document.getElementsByClassName('col-sm-12'); console.log(buttons.length + ' buttons');\n"; return "var buttons = document.getElementsByClassName('btn-primary btn btn-style'); console.log(buttons.length + ' buttons');\n"; } } public class PQChromeClient extends WebChromeClient { @Override public void onPermissionRequest(final PermissionRequest request) { String[] requestedResources = request.getResources(); ArrayList<String> permissions = new ArrayList<>(); ArrayList<String> grantedPermissions = new ArrayList<String>(); for (int i = 0; i < requestedResources.length; i++) { if (requestedResources[i].equals(PermissionRequest.RESOURCE_AUDIO_CAPTURE)) { permissions.add(Manifest.permission.RECORD_AUDIO); } else if (requestedResources[i].equals(PermissionRequest.RESOURCE_VIDEO_CAPTURE)) { permissions.add(Manifest.permission.CAMERA); } } for (int i = 0; i < permissions.size(); i++) { if (ContextCompat.checkSelfPermission(getActivity(), permissions.get(i)) != PackageManager.PERMISSION_GRANTED) { continue; } if (permissions.get(i).equals(Manifest.permission.RECORD_AUDIO)) { grantedPermissions.add(PermissionRequest.RESOURCE_AUDIO_CAPTURE); } else if (permissions.get(i).equals(Manifest.permission.CAMERA)) { grantedPermissions.add(PermissionRequest.RESOURCE_VIDEO_CAPTURE); } } if (grantedPermissions.isEmpty()) { request.deny(); } else { String[] grantedPermissionsArray = new String[grantedPermissions.size()]; grantedPermissionsArray = grantedPermissions.toArray(grantedPermissionsArray); request.grant(grantedPermissionsArray); } } @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); // pbPageLoading.setProgress(newProgress); } // For Android 5.0+ public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, FileChooserParams fileChooserParams) { // Double check that we don't have any existing callbacks if (mUploadMessage != null) { mUploadMessage.onReceiveValue(null); } mUploadMessage = filePath; int writePermission = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE); int readPermission = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE); int cameraPermission = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA); if (!(writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED || cameraPermission != PackageManager.PERMISSION_GRANTED)) { try { Intent galleryintent = new Intent(Intent.ACTION_GET_CONTENT, null); galleryintent.setType("image/*"); Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File Log.e("error", "Unable to create Image File", ex); } // Continue only if the File was successfully created if (photoFile != null) { mCameraPhotoPath = "file:" + photoFile.getAbsolutePath(); cameraIntent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile) ); } Intent chooser = new Intent(Intent.ACTION_CHOOSER); chooser.putExtra(Intent.EXTRA_INTENT, galleryintent); chooser.putExtra(Intent.EXTRA_TITLE, "Select from:"); Intent[] intentArray = {cameraIntent}; chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); // startActivityForResult(chooser, REQUEST_PIC); startActivityForResult(chooser, INPUT_FILE_REQUEST_CODE); } catch (Exception e) { // TODO: when open file chooser failed } } return true; } } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); File imageFile = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); return imageFile; } private void handleProgress(int status, String msg) { if (status == 0) { binding.progressBar.setVisibility(View.VISIBLE); binding.webView.setVisibility(View.GONE); binding.errorConstraint.setVisibility(View.GONE); } else if (status == 1) { binding.progressBar.setVisibility(View.GONE); binding.webView.setVisibility(View.VISIBLE); binding.errorConstraint.setVisibility(View.GONE); } else if (status == 2) { binding.progressBar.setVisibility(View.GONE); binding.webView.setVisibility(View.GONE); binding.errorConstraint.setVisibility(View.VISIBLE); binding.errorLayout.textError.setText(msg); binding.errorLayout.btRetry.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (dashboardResModel != null && quizResModel != null) { quizTestViewModel.getAssignExamData(quizTestViewModel.homeUseCase.getAssignmentRequestModel(dashboardResModel, quizResModel)); } } }); } } private void openDialog() { if (getContext() != null) { customDialog = new InstructionDialog(getContext()); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(customDialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; customDialog.getWindow().setAttributes(lp); Objects.requireNonNull(customDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); customDialog.setCancelable(false); customDialog.show(); } } private void openProgressDialog() { CustomDialogModel customDialogModel = new CustomDialogModel(); customDialogModel.setContext(getActivity()); customDialogModel.setTitle("Calculating Your Score"); customDialogModel.setContent(getActivity().getResources().getString(R.string.bullted_list)); customDialogModel.setTwoButtonRequired(false); customProgressDialog = new CustomProgressDialog(customDialogModel); Objects.requireNonNull(customProgressDialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); customProgressDialog.setCancelable(false); customProgressDialog.show(); } private void setKeyListner() { this.getView().setFocusableInTouchMode(true); // binding.toolbarLayout.backArrow.setOnClickListener(this); this.getView().requestFocus(); this.getView().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { return true; } return false; } }); } private void startCamera() { final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(getActivity()); cameraProviderFuture.addListener(new Runnable() { @Override public void run() { try { ProcessCameraProvider cameraProvider = cameraProviderFuture.get(); bindPreview(cameraProvider); } catch (ExecutionException | InterruptedException e) { // No errors need to be handled for this Future. // This should never be reached. } } }, ContextCompat.getMainExecutor(getActivity())); } void bindPreview(@NonNull ProcessCameraProvider cameraProvider) { Preview preview = new Preview.Builder() .build(); CameraSelector cameraSelector = new CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_FRONT) .build(); ImageCapture.Builder builder = new ImageCapture.Builder(); //Vendor-Extensions (The CameraX extensions dependency in build.gradle) HdrImageCaptureExtender hdrImageCaptureExtender = HdrImageCaptureExtender.create(builder); // Query if extension is available (optional). if (hdrImageCaptureExtender.isExtensionAvailable(cameraSelector)) { // Enable the extension if available. hdrImageCaptureExtender.enableExtension(cameraSelector); } final ImageCapture imageCapture = builder .setTargetRotation(getActivity().getWindowManager().getDefaultDisplay().getRotation()) .build(); // preview.setSurfaceProvider(binding.previewView.createSurfaceProvider()); } void captureImage() { handler.postDelayed(new Runnable() { @Override public void run() { Bitmap bitmap ;//= binding.previewView.getBitmap(); /* if (bitmap != null) { processImage(bitmap); }*/ captureImage(); } }, 10000); } void processImage(Bitmap picBitmap) { byte[] bytes = AppUtil.encodeToBase64(picBitmap, 100); long mb = AppUtil.bytesIntoHumanReadable(bytes.length); int file_size = Integer.parseInt(String.valueOf(bytes.length / 1024)); AppLogger.d(TAG, "Image Path Size mb- " + mb + "-bytes-" + file_size); if (file_size >= 500) { assignmentReqModel.setImageBytes(AppUtil.encodeToBase64(picBitmap, 50)); } else { assignmentReqModel.setImageBytes(bytes); } int new_file_size = Integer.parseInt(String.valueOf(assignmentReqModel.getImageBytes().length / 1024)); AppLogger.d(TAG, "Image Path new Size kb- " + mb + "-bytes-" + new_file_size); callSendExamImageApi(); } private void callSendExamImageApi() { if (!TextUtil.isEmpty(assignmentResModel.getExamAssignmentID())) { if (assignmentResModel != null && !TextUtil.isEmpty(assignmentResModel.getExamAssignmentID())) { SaveImageReqModel saveQuestionResModel = new SaveImageReqModel(); saveQuestionResModel.setImageBytes(assignmentReqModel.getImageBytes()); saveQuestionResModel.setExamId(assignmentResModel.getExamAssignmentID()); if (!TextUtil.isEmpty(assignmentResModel.getImgNormalPath())) { saveQuestionResModel.setImgNormalPath(assignmentResModel.getImgNormalPath()); } else { saveQuestionResModel.setImgNormalPath(""); } if (!TextUtil.isEmpty(assignmentResModel.getImgPath())) { saveQuestionResModel.setImgPath(assignmentResModel.getImgPath()); } else { saveQuestionResModel.setImgPath(""); } if (!TextUtil.isEmpty(assignmentResModel.getQuizId())) { saveQuestionResModel.setQuizId(assignmentResModel.getQuizId()); } else { saveQuestionResModel.setQuizId(""); } PrefModel prefModel = AppPref.INSTANCE.getModelInstance(); DashboardResModel dashboardResModel = prefModel.getDashboardResModel(); saveQuestionResModel.setRegistration_id(dashboardResModel.getAuroid()); quizTestViewModel.uploadExamFace(saveQuestionResModel); } } } void checkNativeCameraEnableOrNot() { PrefModel prefModel = AppPref.INSTANCE.getModelInstance(); // prefModel.getDashboardResModel().setIs_native_image_capturing(true); AppLogger.e("checkNativeCameraEnableOrNot--", "" + prefModel.getDashboardResModel().isIs_native_image_capturing()); if (prefModel.getDashboardResModel() != null && prefModel.getDashboardResModel().isIs_native_image_capturing()) { if (assignmentResModel != null && !TextUtil.isEmpty(assignmentResModel.getExamAssignmentID())) { if (handler != null) { handler.removeCallbacksAndMessages(null); } startCamera(); captureImage(); //binding.previewView.setVisibility(View.VISIBLE); } } else { //binding.previewView.setVisibility(View.INVISIBLE); } } }
/* * 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 chapseven; import java.util.Scanner; /** * * @author Frebby */ public class PhoneNumberFormat { public static void main(String[] args){ Scanner input = new Scanner(System.in); String phoneNum = input.nextLine(); char firstBracket = '('; char secondBracket = ')'; char dash = '-'; System.out.println(firstBracket + phoneNum.substring(0, 3) + secondBracket + phoneNum.substring(3, 6) + dash + phoneNum.substring(7, 11)); } }
/** * 用于提供ip。定义了接口规范和一些具体实现,从不同的几个网站获取ip资源, * 这些网站可能失效,导致内置的这些方法无法使用。此时开发者可以在自己的项 * 目中实现Provider接口,在初始化ip池的时候将其加入,可以达到与内置实现 * 相同的效果。 */ package com.oscroll.strawboat.provider;
package com.goldenasia.lottery.db; import android.content.Context; import com.j256.ormlite.android.apptools.OpenHelperManager; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.stmt.DeleteBuilder; import java.sql.SQLException; import java.util.List; /** *11选5秒秒彩 * Created by Gan on 2018/1/29. */ public class MmcElevenSelectFiveWinHistoryDao { private Dao<MmcElevenSelectFiveWinHistory, Integer> dao; public MmcElevenSelectFiveWinHistoryDao(Context context) { DatabaseHelper dbHelper = OpenHelperManager.getHelper(context, DatabaseHelper.class); try { dao = dbHelper.getDao(MmcElevenSelectFiveWinHistory.class); } catch (SQLException e) { e.printStackTrace(); } } public void savaMmcWinHistory(MmcElevenSelectFiveWinHistory bean) { try { // 如果表中没有该MmcWinHistory则保存,根据主键是否相同来标示是否是同一MmcWinHistory dao.createIfNotExists(bean); } catch (SQLException e) { e.printStackTrace(); } } public List<MmcElevenSelectFiveWinHistory> getAllMmcWinHistory() { try { return dao.queryBuilder().orderBy("uid", false).query(); } catch (SQLException e) { e.printStackTrace(); return null; } } public void delete(MmcElevenSelectFiveWinHistory mmcWinHistory) { DeleteBuilder deleteBuilder = dao.deleteBuilder(); try { deleteBuilder.where().eq("uid", mmcWinHistory.getUid()); deleteBuilder.delete(); } catch (SQLException e) { e.printStackTrace(); } } public int deleteAllMmcWinHistory() { List<MmcElevenSelectFiveWinHistory> allMmcWinHistory=getAllMmcWinHistory(); if(allMmcWinHistory==null||allMmcWinHistory.size()==0) return 0; int count=0; for(MmcElevenSelectFiveWinHistory mmcWinHistory:allMmcWinHistory) { delete(mmcWinHistory); count++; } return count; } // 查询记录的总数 select count(*) from database public int getCount() { try { return (int)(dao.queryBuilder().countOf()); } catch (SQLException e) { e.printStackTrace(); return 0; } } /** * 分页查询 * sql = "select * from database limit ?,?" * @param currentPage 当前页 * @param pageSize 每页显示的记录 * @return 当前页的记录 */ public List<MmcElevenSelectFiveWinHistory> getAllItems(int currentPage, int pageSize) { long firstResult = (currentPage - 1) * pageSize; long maxResult = currentPage * pageSize; List<MmcElevenSelectFiveWinHistory> allMmcWinHistory=null; try { allMmcWinHistory=dao.queryBuilder().orderBy("uid", false).offset(firstResult).limit(maxResult).query(); } catch (SQLException e) { e.printStackTrace(); } return allMmcWinHistory; } }
package handler; import com.google.common.collect.Maps; import org.bukkit.entity.Player; import org.bukkit.scoreboard.Scoreboard; import java.util.HashMap; public final class ScoreboardManager { private static final HashMap<String, ScoreboardHandler> handlers = Maps.newHashMap(); private final HashMap<String, Scoreboard> scoreboards = Maps.newHashMap(); public static ScoreboardHandler getScoreboardHandler(Player player) { return handlers.get(player.getName()); } public static void removeScoreboardHandler(Player player) { handlers.remove(player.getName()); } public static void addScoreboardHandler(Player player, ScoreboardHandler handler) { handlers.put(player.getName(), handler); } public Scoreboard getScoreboard(Player player) { return this.scoreboards.get(player.getName()); } public void put(Player player, Scoreboard scoreboard) { this.scoreboards.put(player.getName(), scoreboard); } public void remove(Player player) { this.scoreboards.remove(player.getName()); } public void destroy() { this.scoreboards.clear(); } }
package com.theshoes.jsp.member.controller; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.theshoes.jsp.common.paging.SelectCriteria; import com.theshoes.jsp.member.model.dto.AddressDTO; import com.theshoes.jsp.member.model.dto.MemberDTO; import com.theshoes.jsp.member.model.serivce.AddressService; @WebServlet("/myPage/address") public class AddressServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { AddressService addressService = new AddressService(); /* 배송지 삭제 */ if(request.getParameter("delete") != null) { int result = addressService.deletAddress(request.getParameter("delete")); if (result > 0) { request.setAttribute("deleteRequest", "0"); } else { request.setAttribute("deleteRequest", "1"); } } HttpSession session = request.getSession(); String id = ((MemberDTO)session.getAttribute("entryMember")).getId(); /* 전체 주소록 조회 */ List<AddressDTO> addressList = new AddressService().selectAllAddressList(id); /* 이것도 3번보기 list size + "" addressCT로 넘어간다. */ request.setAttribute("addressCT", addressList.size()+""); SelectCriteria selectCriteria = null; String path = ""; if(addressList != null) { path = "/WEB-INF/views/myPage/myAddress.jsp"; request.setAttribute("addressList", addressList); } else { path = "/WEB-INF/views/common/errorPage.jsp"; } request.getRequestDispatcher(path).forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* address 추가 */ HttpSession session = request.getSession(); String nameMM = ((MemberDTO)session.getAttribute("entryMember")).getId(); String addressNo = request.getParameter("addressNo"); String addressName = request.getParameter("addressNameMM"); String address1MM = request.getParameter("address1"); String address2MM = request.getParameter("address2"); AddressDTO newAddress = new AddressDTO(); newAddress.setNameMM(nameMM); newAddress.setAddressNo(addressNo); newAddress.setAddressName(addressName); newAddress.setAddress1MM(address1MM); newAddress.setAddress2MM(address2MM); System.out.println("memberController newAddress : " + newAddress); AddressService addressService = new AddressService(); int result = addressService.insertAddress(newAddress); if (result > 0) { request.setAttribute("successCode", "updateAddress"); request.getRequestDispatcher("/WEB-INF/views/common/success.jsp").forward(request, response); } else { request.getRequestDispatcher("/WEB-INF/views/common/errorPage.jsp").forward(request, response); } } }
package org.gracejvc.vanrin.service; import java.util.List; import org.gracejvc.vanrin.dao.NationalityADO; import org.gracejvc.vanrin.model.Nationality; import org.springframework.transaction.annotation.Transactional; public class NationalityServiceImpl implements NationalityService { private NationalityADO nationality; public NationalityServiceImpl(NationalityADO nationality) { this.nationality = nationality; } @Override @Transactional public List<Nationality> allNationlity() { return this.nationality.allNationlity(); } @Override @Transactional public Nationality findNationalityById(int id) { return this.nationality.findNationalityById(id); } @Override public void newNationality(Nationality n) { } @Override public void removeNationality(int id) { // TODO Auto-generated method stub } @Override public void updateNationlity(Nationality n) { // TODO Auto-generated method stub } }
package com.egame.app.tasks; import java.util.ArrayList; import java.util.List; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.telephony.SmsManager; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import com.egame.R; import com.egame.beans.ContactsBean; import com.egame.utils.common.PreferenceUtil; import com.egame.utils.ui.ToastUtil; /** * 描述:发送短消息的异步任务 * * @author LiuHan * @version 1.0 create on:2012/1/5 */ public class SendSMSAsyncTask extends AsyncTask<String, Integer, String> { private static final String LOG_TAG = "SenSMSAsyncTask"; private boolean mException = false; /** 要发送短信的联系人数据集合 */ private List<ContactsBean> mCBean; /** 发送状态提示UI */ private ProgressDialog mPDialog; /** 上下文 */ private Context context; private TelephonyManager mTelephonyManager; private String gameId,gameName; public SendSMSAsyncTask(Context context, List<ContactsBean> mContactsBean, String gameId,String gameName) { this.mCBean = mContactsBean; this.context = context; this.mCBean = mContactsBean; this.gameId = gameId; this.gameName = gameName; mTelephonyManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); mPDialog = new ProgressDialog(context); mPDialog.setMessage("分享发送中,请稍后. . . . . "); mPDialog.show(); } public SendSMSAsyncTask(Context context, List<ContactsBean> mContactsBean) { this.mCBean = mContactsBean; this.context = context; this.mCBean = mContactsBean; mTelephonyManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); mPDialog = new ProgressDialog(context); mPDialog.setMessage("分享发送中,请稍后. . . . . "); mPDialog.show(); } @Override protected String doInBackground(String... params) { // 读取运营商的名称 Log.i(LOG_TAG, getOperatorName()); if ("unknown".equals(getOperatorName())) { return "无法读取运营商的信息,请确保手机已正常入网,然后重试。"; } String mStr = readSimState(); Log.i(LOG_TAG, mStr); // 判断SIM卡的状态 if ("Fine".equals(mStr)) { // 如歌手机不欠费 可以正常发送短信 SmsManager sms = SmsManager.getDefault(); for (int i = 0; i < this.mCBean.size(); i++) { try { ContactsBean mBean = this.mCBean.get(i); String num = mBean.getmContactsPhone(); String content; if ("game".equals(PreferenceUtil.fetchType(context))) { content = getPhoneShareWord(this.gameId,this.gameName); } else { content = getClientShareWord(); } if (content.length() > 70) { // 使用短信管理器进行短信内容的分段,返回分成的段 ArrayList<String> contents = sms.divideMessage(content); for (String msg : contents) { // 使用短信管理器发送短信内容 // 参数一为短信接收者 // 参数三为短信内容 // 其他可以设为null sms.sendTextMessage(num, null, msg, null, null); } } else { // 否则一次过发送 sms.sendTextMessage(num, null, content, null, null); } } catch (Exception e) { e.printStackTrace(); mException = true; } } return "分享消息发送成功!"; } else { return mStr; } } private String getClientShareWord() { String imsi = null; try { TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); imsi = telManager.getSubscriberId(); } catch (Exception e) { e.printStackTrace(); } return this.context.getResources().getString( R.string.egame_share_content)+imsi; } private String getPhoneShareWord(String gameId,String gameName) { return "我正在玩《" + gameName + "》,很给力啊!http://wapgame.189.cn/c/game/details/" + gameId ; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); mPDialog.dismiss(); if (mException) { ToastUtil.show(this.context, "分享消息发送失败!"); } else { ToastUtil.show(this.context, result); } } /** * 功能:取得当前手机运营商的名称 * * @return string 运营商的名称 */ public String getOperatorName() { // 取得运营商的信息 String operatorInfo = mTelephonyManager.getSimOperator(); String operatorName = ""; Log.i(LOG_TAG, operatorInfo); if ("46000".equals(operatorInfo) || "46002".equals(operatorInfo) || "46007".equals(operatorInfo)) { // 中国移动 operatorName = "中国移动"; } else if ("46001".equals(operatorInfo)) { // 中国联通 operatorName = "中国联通"; } else if ("46003".equals(operatorInfo)) { // 中国电信 operatorName = "中国电信"; } else { operatorName = "unknown"; } return operatorName; } /** * 功能:读取Sim卡的状态 * * @return Sim卡的状态 */ public String readSimState() { String mString = ""; int simState = mTelephonyManager.getSimState(); switch (simState) { case TelephonyManager.SIM_STATE_ABSENT: mString = "未找到SIM卡,请确认插入了SIM卡,然后重试。"; break; case TelephonyManager.SIM_STATE_NETWORK_LOCKED: mString = "需要NetworkPIN解锁"; break; case TelephonyManager.SIM_STATE_PIN_REQUIRED: mString = "需要PIN解锁"; break; case TelephonyManager.SIM_STATE_PUK_REQUIRED: mString = "需要PUN解锁"; break; case TelephonyManager.SIM_STATE_READY: mString = "Fine"; break; case TelephonyManager.SIM_STATE_UNKNOWN: mString = "未能正确读取SIM卡的信息,请确认SIM卡是否正确放入卡槽内。"; break; } return mString; } }
package by.orion.onlinertasks.presentation.main; import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy; import com.arellomobile.mvp.viewstate.strategy.OneExecutionStateStrategy; import com.arellomobile.mvp.viewstate.strategy.StateStrategyType; import by.orion.onlinertasks.presentation.BaseMvpView; @StateStrategyType(OneExecutionStateStrategy.class) public interface MainView extends BaseMvpView { String TAG_LOGIN_BUTTON = "TAG_LOGIN_BUTTON"; void showAllTasks(); void showAllProfiles(); void goToLoginScreen(); @StateStrategyType(value = AddToEndSingleStrategy.class, tag = TAG_LOGIN_BUTTON) void showLoginButton(); @StateStrategyType(value = AddToEndSingleStrategy.class, tag = TAG_LOGIN_BUTTON) void hideLoginButton(); }
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.context.request; import jakarta.faces.context.FacesContext; import org.springframework.core.NamedInheritableThreadLocal; import org.springframework.core.NamedThreadLocal; import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; /** * Holder class to expose the web request in the form of a thread-bound * {@link RequestAttributes} object. The request will be inherited * by any child threads spawned by the current thread if the * {@code inheritable} flag is set to {@code true}. * * <p>Use {@link RequestContextListener} or * {@link org.springframework.web.filter.RequestContextFilter} to expose * the current web request. Note that * {@link org.springframework.web.servlet.DispatcherServlet} * already exposes the current request by default. * * @author Juergen Hoeller * @author Rod Johnson * @since 2.0 * @see RequestContextListener * @see org.springframework.web.filter.RequestContextFilter * @see org.springframework.web.servlet.DispatcherServlet */ public abstract class RequestContextHolder { private static final boolean jsfPresent = ClassUtils.isPresent("jakarta.faces.context.FacesContext", RequestContextHolder.class.getClassLoader()); private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal<>("Request attributes"); private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder = new NamedInheritableThreadLocal<>("Request context"); /** * Reset the RequestAttributes for the current thread. */ public static void resetRequestAttributes() { requestAttributesHolder.remove(); inheritableRequestAttributesHolder.remove(); } /** * Bind the given RequestAttributes to the current thread, * <i>not</i> exposing it as inheritable for child threads. * @param attributes the RequestAttributes to expose * @see #setRequestAttributes(RequestAttributes, boolean) */ public static void setRequestAttributes(@Nullable RequestAttributes attributes) { setRequestAttributes(attributes, false); } /** * Bind the given RequestAttributes to the current thread. * @param attributes the RequestAttributes to expose, * or {@code null} to reset the thread-bound context * @param inheritable whether to expose the RequestAttributes as inheritable * for child threads (using an {@link InheritableThreadLocal}) */ public static void setRequestAttributes(@Nullable RequestAttributes attributes, boolean inheritable) { if (attributes == null) { resetRequestAttributes(); } else { if (inheritable) { inheritableRequestAttributesHolder.set(attributes); requestAttributesHolder.remove(); } else { requestAttributesHolder.set(attributes); inheritableRequestAttributesHolder.remove(); } } } /** * Return the RequestAttributes currently bound to the thread. * @return the RequestAttributes currently bound to the thread, * or {@code null} if none bound */ @Nullable public static RequestAttributes getRequestAttributes() { RequestAttributes attributes = requestAttributesHolder.get(); if (attributes == null) { attributes = inheritableRequestAttributesHolder.get(); } return attributes; } /** * Return the RequestAttributes currently bound to the thread. * <p>Exposes the previously bound RequestAttributes instance, if any. * Falls back to the current JSF FacesContext, if any. * @return the RequestAttributes currently bound to the thread * @throws IllegalStateException if no RequestAttributes object * is bound to the current thread * @see #setRequestAttributes * @see ServletRequestAttributes * @see FacesRequestAttributes * @see jakarta.faces.context.FacesContext#getCurrentInstance() */ public static RequestAttributes currentRequestAttributes() throws IllegalStateException { RequestAttributes attributes = getRequestAttributes(); if (attributes == null) { if (jsfPresent) { attributes = FacesRequestAttributesFactory.getFacesRequestAttributes(); } if (attributes == null) { throw new IllegalStateException("No thread-bound request found: " + "Are you referring to request attributes outside of an actual web request, " + "or processing a request outside of the originally receiving thread? " + "If you are actually operating within a web request and still receive this message, " + "your code is probably running outside of DispatcherServlet: " + "In this case, use RequestContextListener or RequestContextFilter to expose the current request."); } } return attributes; } /** * Inner class to avoid hard-coded JSF dependency. */ private static class FacesRequestAttributesFactory { @Nullable public static RequestAttributes getFacesRequestAttributes() { try { FacesContext facesContext = FacesContext.getCurrentInstance(); return (facesContext != null ? new FacesRequestAttributes(facesContext) : null); } catch (NoClassDefFoundError err) { // typically for com/sun/faces/util/Util if only the JSF API jar is present return null; } } } }
package com.tide.demo17; public class Demo01Person { public static void main(String[] args) { Person person=new Person(); person.setName("盖伦"); person.setAge(19); //方法一 Weapon weapon=new Weapon("多兰剑"); person.setWeapon(weapon); //方法二 // person.setWeapon(new Weapon("多兰剑")); person.method(); } }
package com.edu.realestate.dao; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.edu.realestate.model.Picture; public class PictureDaoJDBC extends AbstractDaoJDBC implements PictureDao { @Override public void create(Picture p) { // TODO Auto-generated method stub } @Override public Picture read(Integer id) { Picture picture = null; try { Statement st = getConnection().createStatement(); String req = "SELECT * FROM picture WHERE id = " + id; ResultSet rs = st.executeQuery(req); if (rs.next()) { picture = new Picture(); picture.setId(rs.getInt("id")); picture.setData(rs.getBlob("content").getBytes(1, (int)rs.getBlob("content").length())); } } catch (Exception e) { System.out.println("PictureDaoJDBC error : " + e.getLocalizedMessage()); } return picture; } @Override public void update(Picture p) { // TODO Auto-generated method stub } @Override public void delete(Picture p) { // TODO Auto-generated method stub } @Override public List<Picture> getAllPicturesByAd(Integer id) { List<Picture> list = new ArrayList<>(); Picture picture = null; try { Statement st = getConnection().createStatement(); String req = "SELECT p.* FROM picture p JOIN advertisement a ON a.id = p.advertisement_id WHERE a.id = " + id; ResultSet rs = st.executeQuery(req); picture = new Picture(); while (rs.next()) { picture.setId(rs.getInt("id")); picture.setData(rs.getBlob("content").getBytes(1, (int)rs.getBlob("content").length())); list.add(picture); } } catch (Exception e) { System.out.println("PictureDaoJDBC error : " + e.getLocalizedMessage()); } return list; } }
/** * */ package section1.view1; import java.awt.BorderLayout; import java.awt.GridBagLayout; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import main.MainGUI; import section1.controller1.ButtonListener1; import somedatamodel.SomeDataClass; /** * * Class description * * @author Samuel * */ public class Panel1 extends JPanel { private JScrollPane firstPanelScroll; private JList<String> listOfTasks; private JButton newTaskButton; private JLabel label; private JLabel label2; private String titleText; private SomeDataClass someData; private JPanel containsLabels; private ButtonListener1 buttonController; private MainGUI mainGui; /** * Constructor method for Panel1. Sets fields of this class to object references * passed as a parameters. * Finally, sets up Panel1 GUI. * * @param someData, mainGui */ public Panel1(SomeDataClass someData, MainGUI mainGui) { this.someData = someData; this.mainGui = mainGui; titleText = "DASHBOARD<br>"; this.setLayout(new GridLayout(1,1)); this.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JPanel firstPanelCenter = new JPanel(); firstPanelCenter.setLayout(new GridLayout(1,1)); this.add(firstPanelCenter, BorderLayout.CENTER); JPanel containsLabelContainer = new JPanel(); containsLabelContainer.setLayout(new GridBagLayout()); containsLabels = new JPanel(); containsLabels.setLayout(new BoxLayout(containsLabels, BoxLayout.Y_AXIS)); label = new JLabel("<html><div style='text-align: center;'>" + titleText + "</div></html>"); listOfTasks = new JList<String>(someData.getSomeArray()); containsLabels.add(label); newTaskButton = new JButton("Add New Task"); buttonController = new ButtonListener1(this, mainGui); newTaskButton.setName("add new task"); newTaskButton.addActionListener(buttonController); containsLabels.add(listOfTasks); containsLabels.add(newTaskButton); containsLabelContainer.add(containsLabels); // 'firstPanelScroll' contains 'containsLabelContainer'. firstPanelScroll = new JScrollPane(containsLabelContainer); // 'firstPanelCenter' contains 'firstsPanelScroll'. firstPanelCenter.add(firstPanelScroll); label.setHorizontalAlignment(JLabel.CENTER); this.setVisible(true); } }
package com.mkd.adtools.bean; import javax.persistence.Entity; import javax.persistence.Id; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @Data @AllArgsConstructor @NoArgsConstructor @Accessors(chain = true) @Entity(name = "ad_site") public class AdSite { @Id private Integer id ; private Integer userid ; private String sitename ; private String sitekey ; private String note ; private Integer sitetype ; private Integer status ; private Integer createtime ; private Integer pagesize ; private Integer currentpage ; private String price ;//json }
package com.hrrm.infrastructure.web.internal; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ServiceScope; import org.osgi.service.http.context.ServletContextHelper; import org.osgi.service.http.whiteboard.HttpWhiteboardConstants; @Component(service = ServletContextHelper.class, property = { HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=" + WebContentContextHelper.WEB_APP_CONTEXT_NAME, HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH + "=" + WebContentContextHelper.WEB_APP_CONTEXT }, scope = ServiceScope.BUNDLE) public class WebContentContextHelper extends DelegatedServletContextHalper { public static final String WEB_APP_CONTEXT_NAME = "com.hrrm.budget.webapp"; public static final String WEB_APP_CONTEXT = "/"; }
package com.example.test_appman; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.jar.Attributes; public class MainActivity extends AppCompatActivity { private ArrayList<String> namesList = new ArrayList<>(); private ArrayList<String> description = new ArrayList<>(); TextView textView; ListView listView; private PopupWindow mPopupWindow; LinearLayout layout; String Id,Name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); layout = (LinearLayout) findViewById(R.id.LinearLayout1); getNameList(); ActionBar actionBar = getSupportActionBar(); if(actionBar != null) { actionBar.setTitle("Id: "+ Id +" Name: " + Name); } listView = (ListView) findViewById(R.id.listview); final ArrayList<String> arrayList = new ArrayList<>(); for (int i = 0 ; i < namesList.size(); i++ ){ arrayList.add(namesList.get(i)); } ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { LayoutInflater layoutInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View customView = layoutInflater.inflate(R.layout.activity_popup,null); textView = customView.findViewById(R.id.text); textView.setText(description.get(position)); mPopupWindow = new PopupWindow(customView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); mPopupWindow.showAtLocation(layout, Gravity.CENTER, 0, 0); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mPopupWindow.dismiss(); } }, 1000); } }); } private void getNameList() { String myJSONStr = loadJSONFromAsset(); try { JSONObject rootJsonObject = new JSONObject(myJSONStr); Id = rootJsonObject.getString("Id"); Name = rootJsonObject.getString("firstName")+" "+rootJsonObject.getString("lastName"); JSONArray dataJsonArray = rootJsonObject.getJSONArray("data"); for (int i = 0; i < dataJsonArray.length(); i++){ JSONObject jsonObject = dataJsonArray.getJSONObject(i); namesList.add(jsonObject.getString("docType")); JSONObject descriptionJsonObject = new JSONObject(jsonObject.getString("description")); description.add(descriptionJsonObject.getString("th") + " / " + descriptionJsonObject.getString("en")); } } catch (JSONException e) { e.printStackTrace(); } } public String loadJSONFromAsset() { String json = null; try { InputStream is = getAssets().open("intern.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; } }
import java.io.*; import java.net.*; import java.util.*; public class Server { public static void main(String[] args) { ArrayList<ServerThread> threads = new ArrayList<ServerThread>(0); ChatManager chats = new ChatManager(); int i=0; int port = 6868; try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Server is listening on port " + port); while (true) { Socket socket = serverSocket.accept(); System.out.println("New client connected"); threads.add(new ServerThread(socket,chats)); threads.get(i).start(); i++; //for(int x = 0;x<threads.size();x++){ // System.out.println(threads.get(x).getName()); //} } } catch (IOException ex) { System.out.println("Server exception: " + ex.getMessage()); ex.printStackTrace(); } } }
package cdp.participacao; import cdp.projetos.Monitoria; /** * Representa um aluno graduando no sistema. * * @author Yuri Silva * @author Tiberio Gadelha * @author Matheus Henrique * @author Gustavo Victor */ public class AlunoGraduando extends Participacao { private static final double MAXIMO_PONTOS_ATINGIDOS = 0; private static final int MESES_MINIMO = 6; private static final double BONUS_PARTICIPACAO_MONITORIA_SEMESTRAL = 1.5; private static final double BONUS_PARTICIPACAO_PED_SEMESTRAL = 2.0; private static final double LIMITE_PONTOS_PED = 8; private static final double LIMITE_PONTOS_MONITORIA = 6; private static final double DURACAO_INSUFICIENTE = 0.0; public static double controlePontosPED; public static double controlePontosMonitoria; public AlunoGraduando(double valorHora, int qtdHoras) { super(valorHora, qtdHoras); } @Override public double geraPontuacaoParticipacao() { double pontosFeitos; int duracao = super.getProjeto().getDuracao(); if(super.getProjeto() instanceof Monitoria) { if(duracao >= MESES_MINIMO) { pontosFeitos = (duracao / MESES_MINIMO) * BONUS_PARTICIPACAO_MONITORIA_SEMESTRAL; if(AlunoGraduando.controlePontosMonitoria + pontosFeitos > LIMITE_PONTOS_MONITORIA) { double diferenca = LIMITE_PONTOS_MONITORIA - controlePontosMonitoria; if(pontosFeitos <= diferenca) { AlunoGraduando.controlePontosMonitoria += diferenca; return pontosFeitos; } return MAXIMO_PONTOS_ATINGIDOS; } AlunoGraduando.controlePontosMonitoria += pontosFeitos; return pontosFeitos; }else { return DURACAO_INSUFICIENTE; } }else { if(duracao >= MESES_MINIMO) { pontosFeitos = ( duracao / MESES_MINIMO ) * BONUS_PARTICIPACAO_PED_SEMESTRAL; if(AlunoGraduando.controlePontosPED + pontosFeitos > LIMITE_PONTOS_PED) { double diferenca = LIMITE_PONTOS_PED - controlePontosPED; if(pontosFeitos <= diferenca) { AlunoGraduando.controlePontosPED += diferenca; return pontosFeitos; } return MAXIMO_PONTOS_ATINGIDOS; } AlunoGraduando.controlePontosPED += pontosFeitos; return pontosFeitos; } else { return DURACAO_INSUFICIENTE; } } } }
package com.zantong.mobilecttx.car.fragment; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.zantong.mobilecttx.car.adapter.CarChooseXingAdapter; import com.zantong.mobilecttx.api.CallBack; import com.zantong.mobilecttx.api.CarApiClient; import com.jcodecraeer.xrecyclerview.BaseAdapter; import com.zantong.mobilecttx.base.fragment.BaseListFragment; import com.zantong.mobilecttx.car.bean.CarLinkageResult; import com.zantong.mobilecttx.car.bean.CarStyleInfoBean; import com.zantong.mobilecttx.car.dto.CarLinkageDTO; import com.zantong.mobilecttx.car.activity.AddCarActivity; import com.zantong.mobilecttx.car.activity.CarChooseActivity; public class CarChooseXingFragment extends BaseListFragment<CarStyleInfoBean> { public static CarChooseXingFragment newInstance(int typeId, int idB) { CarChooseXingFragment f = new CarChooseXingFragment(); Bundle args = new Bundle(); args.putInt("id", typeId); args.putInt("idB", idB); f.setArguments(args); return f; } private int id; private int idB; @Override public void initData() { super.initData(); Bundle bundle = getArguments(); id = bundle.getInt("id", 0); idB = bundle.getInt("idB", 0); carXingList(); } private void carXingList() { CarLinkageDTO carLinkageDTO = new CarLinkageDTO(); carLinkageDTO.setModelsId(""); carLinkageDTO.setBrandId(String.valueOf(idB)); carLinkageDTO.setSeriesId(String.valueOf(id)); CarApiClient.liYingCarLinkage(getActivity(), carLinkageDTO, new CallBack<CarLinkageResult>() { @Override public void onSuccess(CarLinkageResult result) { if(result.getResponseCode() == 2000){ setDataResult(result.getData().getCarModels()); } } }); } @Override protected void onLoadMoreData() { } @Override protected void onRefreshData() { carXingList(); } @Override protected void onRecyclerItemClick(View view, Object data) { CarStyleInfoBean carStyleBean = (CarStyleInfoBean) data; Intent intent = new Intent(getActivity(), AddCarActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable(CarChooseActivity.CAR_XING_BEAN, carStyleBean); intent.putExtras(bundle); getActivity().setResult(CarChooseActivity.RESULT_X_CODE, intent); getActivity().finish(); } @Override public BaseAdapter<CarStyleInfoBean> createAdapter() { return new CarChooseXingAdapter(); } }
package com.cedo.cat2auth.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.cedo.cat2auth.model.Menu; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; import java.util.List; /** * 菜单类 * * @author chendong * @date 2019-03-02 20:37:43 */ @Component @Mapper public interface MenuMapper extends BaseMapper<Menu> { List<Menu> findMenuByUserId(@Param("userId") long userId); List<Menu> findAll(); }
package com.cdgpacific.sellercatpal; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.Paint; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.telephony.TelephonyManager; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import org.json.JSONObject; import static android.R.attr.button; public class LoginActivity extends AppCompatActivity { private ProgressDialog pDialog; public String URL = ""; //http://138.128.118.2:8090/api/signin/795edd365fd0e371ceaaf1ddd559a85d/"; public EditText txtEmail, txtPassword; public TextView forgot_password; public Button btnLogin; public String email, password; public int ScreenCheckSizeIfUsing10Inches; public int width = 0, height = 370; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); //<< this URL = Helpers.Host + "/api/signin/795edd365fd0e371ceaaf1ddd559a85d/"; setContentView(R.layout.activity_login); ScreenCheckSizeIfUsing10Inches = Helpers.getScreenOfTablet(getApplicationContext()); txtEmail = (EditText) findViewById(R.id.email); txtPassword = (EditText) findViewById(R.id.password); forgot_password = (TextView) findViewById(R.id.forgot_password); txtEmail.setText(""); txtPassword.setText(""); forgot_password.setPaintFlags(forgot_password.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); btnLogin = (Button) findViewById(R.id.btnLogin); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { email = txtEmail.getText().toString(); password = txtPassword.getText().toString(); if(email == "") { return; } if(password == "") { return; } URL = Helpers.Host + "/api/signin/795edd365fd0e371ceaaf1ddd559a85d/" + email + "/" + password; Log.d("Response: ", "> " + URL); new getLogin().execute(); } }); Context context = getApplicationContext(); TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); if(manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE){ Log.d("DEVICE", "TABLET"); if(ScreenCheckSizeIfUsing10Inches == 1) { height = 570; } else if(ScreenCheckSizeIfUsing10Inches == 2) { height = 745; } width = 500; }else{ Log.d("DEVICE", "MOBILE"); width = 1050; height = 1210; } } public class getLogin extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { loaderShow("Please wait..."); super.onPreExecute(); } @Override protected String doInBackground(Void... params) { // TODO: attempt authentication against a network service. String json = null; try { Thread.sleep(100); JSONHelper json_help = new JSONHelper(); json = json_help.makeServiceCall(URL, JSONHelper.GET); Log.d("Response: ", "> " + json); return json; } catch (InterruptedException e) { } // TODO: register the new account here. return null; } @Override protected void onPostExecute(final String json) { loaderHide(); validate_user_account(json); } } private void validate_user_account(String json) { String message_ = "Please connect to the internet in order to log on to your account.\n"; if (json != null) { try { JSONObject job = new JSONObject(json); String Status = job.getString("LoginStatus"); Log.d("Status: ", Status); int LoginStatus = Integer.parseInt(Status); if(LoginStatus == 200) { String UID = job.getString("Id"); String ROLE = job.getString("role"); int user_role = Integer.parseInt(ROLE); if(user_role == 5) { JSONHelper.Seller_UID = UID; Intent i = new Intent(getApplicationContext(), MainActivity.class); startActivity(i); finish(); return; } message_ = "Please use your valid seller account.\n"; } else { message_ = "This Username and/or Password is invalid. Please try again.\n"; } }catch(Exception e) { e.printStackTrace(); } showDialogForDynamicError( LoginActivity.this, "USER LOGIN", message_, width, height, 15); } } public void showDialogForDynamicError(Activity activity, String caption, String message, int width, int height, final int number){ final Dialog dialog = new Dialog(activity); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(false); dialog.setContentView(R.layout.activity_custom_dialog_error); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.height = height; if(width > 0) { lp.width = width; } TextView title_dialog = (TextView) dialog.findViewById(R.id.title_dialog); TextView title_message = (TextView) dialog.findViewById(R.id.title_message); TextView screen_code = (TextView) dialog.findViewById(R.id.screen_code); Button btn_dialog_OK = (Button) dialog.findViewById(R.id.btn_dialog_OK); title_dialog.setText(caption); title_message.setText(message); screen_code.setText("MW-" + number); btn_dialog_OK.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.getWindow().setAttributes(lp); dialog.show(); } private void messageAlert(String message, String title) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message).setTitle(title) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // do nothing } }); AlertDialog alert = builder.create(); alert.show(); } private void loaderShow(String Message) { pDialog = new ProgressDialog(LoginActivity.this); pDialog.setMessage(Message); pDialog.setCancelable(false); pDialog.show(); } private void loaderHide(){ if (pDialog.isShowing()) pDialog.dismiss(); } }
/* * 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 gestionbadr.RDV; import GestionRDV.ConsulterConvontionRDV; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import GestionRDV.RDV; import gestionbadr.Connect; import gestionbadr.HomeAdministrateur; import gestionbadr.HomeDirecteur; import gestionbadr.HomeSecretaire; import java.awt.Color; import java.awt.Component; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.SQLException; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import static java.util.Calendar.APRIL; import static java.util.Calendar.AUGUST; import static java.util.Calendar.DECEMBER; import static java.util.Calendar.FEBRUARY; import static java.util.Calendar.JANUARY; import static java.util.Calendar.JULY; import static java.util.Calendar.JUNE; import static java.util.Calendar.MARCH; import static java.util.Calendar.MAY; import static java.util.Calendar.NOVEMBER; import static java.util.Calendar.OCTOBER; import static java.util.Calendar.SEPTEMBER; import java.util.Date; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import org.apache.log4j.Logger; /** * * @author FAWZI */ public class Quantite extends javax.swing.JFrame { static Logger log = Logger.getLogger(Quantite.class.getName()); Connection con = null; PreparedStatement pst = null; ResultSet rst = null; Statement st = null; ResultSet rs = null; String nom_convontion; String nbr_RDv; String unite_c; protected int id_conv; int id_pp; int id_p; String nom_p; char id; protected String id_m; //protected int id_demande_RDV; boolean t = false; // etat de la date si prise = true "Verifier_date_rdv()" Integer[] tableau_resultat_rdv_mois_par_annee = new Integer[12]; // tableau des rdv restant par mois de l'année Integer[] tableau_Vendredi_mois_par_annee = new Integer[12]; // Tableau du nombres de Vendredi par mois de l'année Integer[] tableau_max_Day_mois_par_annee = new Integer[12]; // Tableau de Maximum de jour par mois de l'année public Quantite() { initComponents(); jTabbedPane1.setEnabledAt(1, false); Remplir_Combo_Type_Convontion(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Cancel(); } }); } public Quantite(char id) { initComponents(); jTabbedPane1.setEnabledAt(1, false); Remplir_Combo_Type_Convontion(); this.id = id; addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Cancel(); } }); } @SuppressWarnings("unchecked") private void Remplir_Combo_Type_Convontion() { log.trace("Debut"); con = Connect.connect(); String requete = "select nom_convontion from convontion"; try { pst = con.prepareStatement(requete); rst = pst.executeQuery(); while (rst.next()) { nom_convontion = rst.getString("nom_convontion"); // id_conv = rst.getString("id_conv"); cConvontion.addItem(nom_convontion); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, e.getMessage()); log.error(e); } finally { /*This block should be added to your code * You need to release the resources like connections */ if (con != null) { try { con.close(); } catch (SQLException ex) { log.error(ex); } } } log.trace("Fin"); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); pChoisirRDV = new javax.swing.JPanel(); jLabel17 = new javax.swing.JLabel(); jYearChooser2 = new com.toedter.calendar.JYearChooser(); jScrollPane1 = new javax.swing.JScrollPane(); tConvontion = new javax.swing.JTable(){ public boolean isCellEditable (int d, int c){ return false; } } ; jLabel15 = new javax.swing.JLabel(); cConvontion = new javax.swing.JComboBox(); bRechercherCotaParAns = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); pChoisirDate = new javax.swing.JPanel(); tDateParConvontion = new javax.swing.JScrollPane(); tRDVchoix1 = new javax.swing.JTable(){ public boolean isCellEditable (int d, int c){ // Rendre les cellule non Editable return false; } public Component prepareRenderer(TableCellRenderer r, int rw,int col) { // // Colorier les ligne du tableau Component c = super.prepareRenderer(r, rw, col); c.setBackground(Color.WHITE); c.setForeground(Color.BLACK); String nomJour = tRDVchoix1.getModel().getValueAt(rw, 0).toString(); if (nomJour.equals("vendredi")) { // Si Jour = Vendredi alors ERREUR c.setBackground(Color.RED); c.setForeground(Color.WHITE); } String date_tester = tRDVchoix1.getModel().getValueAt(rw, 1).toString(); boolean k = Verifier_date_rdv_colorier(date_tester); // con = Connect.connect(); // String sql = "select Etat_RDV,date_rdv from rdv where date_rdv ='" + date_tester + "'"; // try { // pst = con.prepareStatement(sql); // ResultSet rst1 = pst.executeQuery(sql); // while (rst1.next()) { // // Compare la valeur selectioner avec la valeur rechercher dans la BDD // String Etat_rdv_pris = rst1.getString("Etat_RDV"); // Date date_rdv_pris = rst1.getDate("date_rdv"); // DateFormat fd = new SimpleDateFormat("yyyy-MM-dd"); // String dateFormatee = fd.format(date_rdv_pris); // System.out.println(Etat_rdv_pris + " | date bd: "+ dateFormatee + " | date tableau: "+ date_tester); if (k == true) { // // si la date est prise afficher ERREUR t = true; System.out.println("Rouge"); c.setBackground(Color.RED); c.setForeground(Color.WHITE); // // JOptionPane.showMessageDialog(null, "c'est une date prise"); } //else if ((((Etat_rdv_pris.equals("Pris") || Etat_rdv_pris.equals("En Attente"))) // && (Etat_rdv_pris.equals("Annuler") || Etat_rdv_pris.equals("Reporter"))) // && dateFormatee.equals(date_tester)) { // // si la date est prise afficher ERREUR // t = true; // c.setBackground(Color.RED); // c.setForeground(Color.WHITE); // } // } // else { // t = false; // // } // } catch (SQLException | NumberFormatException e) { // JOptionPane.showMessageDialog(null, e.getMessage()); // }finally{ // /*This block should be added to your code // * You need to release the resources like connections // */ // if(con!=null) // try { // con.close(); // } catch (SQLException ex) { // Logger.getLogger(RDV.class.getName()).log(Level.SEVERE, null, ex); // } // } return c; } }; jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jYearChooser1 = new com.toedter.calendar.JYearChooser(); jMonthChooser1 = new com.toedter.calendar.JMonthChooser(); bRechercherCotaParMois = new javax.swing.JButton(); jLabel16 = new javax.swing.JLabel(); txtNomConvontion = new javax.swing.JTextField(); bCancel = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jLabel17.setText("Annee"); tConvontion.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Mois", "Annee", "Quantite" } )); tConvontion.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tConvontionMouseClicked(evt); } }); jScrollPane1.setViewportView(tConvontion); jLabel15.setText("Convontion"); cConvontion.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { cConvontionPopupMenuWillBecomeInvisible(evt); } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { } }); cConvontion.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cConvontionActionPerformed(evt); } }); bRechercherCotaParAns.setText("Rechercher"); bRechercherCotaParAns.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bRechercherCotaParAnsActionPerformed(evt); } }); jButton3.setText("Consulter Convontion"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout pChoisirRDVLayout = new javax.swing.GroupLayout(pChoisirRDV); pChoisirRDV.setLayout(pChoisirRDVLayout); pChoisirRDVLayout.setHorizontalGroup( pChoisirRDVLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pChoisirRDVLayout.createSequentialGroup() .addGroup(pChoisirRDVLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pChoisirRDVLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(pChoisirRDVLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pChoisirRDVLayout.createSequentialGroup() .addGap(58, 58, 58) .addComponent(jLabel15)) .addGroup(pChoisirRDVLayout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(pChoisirRDVLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cConvontion, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(pChoisirRDVLayout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jButton3))))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pChoisirRDVLayout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(jLabel17) .addGap(29, 29, 29) .addComponent(jYearChooser2, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(pChoisirRDVLayout.createSequentialGroup() .addGap(52, 52, 52) .addComponent(bRechercherCotaParAns))) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 548, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pChoisirRDVLayout.setVerticalGroup( pChoisirRDVLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pChoisirRDVLayout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(pChoisirRDVLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pChoisirRDVLayout.createSequentialGroup() .addGroup(pChoisirRDVLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(pChoisirRDVLayout.createSequentialGroup() .addComponent(jLabel15) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cConvontion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jYearChooser2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel17)) .addGap(29, 29, 29) .addComponent(bRechercherCotaParAns) .addGap(18, 18, 18) .addComponent(jButton3)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(180, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Choisir une Convontion", pChoisirRDV); tRDVchoix1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Jour", "Date" } )); tRDVchoix1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tRDVchoix1MouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { tRDVchoix1MouseEntered(evt); } }); tDateParConvontion.setViewportView(tRDVchoix1); jLabel8.setText("Mois"); jLabel9.setText("Annee"); jMonthChooser1.setMonth(5); bRechercherCotaParMois.setText("Rechercher"); bRechercherCotaParMois.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bRechercherCotaParMoisActionPerformed(evt); } }); jLabel16.setText("Nom de la convontion:"); javax.swing.GroupLayout pChoisirDateLayout = new javax.swing.GroupLayout(pChoisirDate); pChoisirDate.setLayout(pChoisirDateLayout); pChoisirDateLayout.setHorizontalGroup( pChoisirDateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pChoisirDateLayout.createSequentialGroup() .addGroup(pChoisirDateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pChoisirDateLayout.createSequentialGroup() .addGap(39, 39, 39) .addComponent(jLabel8)) .addGroup(pChoisirDateLayout.createSequentialGroup() .addGap(29, 29, 29) .addComponent(jLabel16)) .addGroup(pChoisirDateLayout.createSequentialGroup() .addContainerGap() .addComponent(jMonthChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pChoisirDateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addComponent(jYearChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(pChoisirDateLayout.createSequentialGroup() .addGap(76, 76, 76) .addComponent(bRechercherCotaParMois)) .addGroup(pChoisirDateLayout.createSequentialGroup() .addContainerGap() .addComponent(txtNomConvontion, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(tDateParConvontion, javax.swing.GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE) .addGap(28, 28, 28)) ); pChoisirDateLayout.setVerticalGroup( pChoisirDateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pChoisirDateLayout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtNomConvontion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 356, Short.MAX_VALUE) .addGroup(pChoisirDateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pChoisirDateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jYearChooser1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jMonthChooser1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bRechercherCotaParMois) .addGap(48, 48, 48)) .addGroup(pChoisirDateLayout.createSequentialGroup() .addContainerGap() .addComponent(tDateParConvontion, javax.swing.GroupLayout.PREFERRED_SIZE, 539, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Choisir une Date", pChoisirDate); bCancel.setText("Cancel"); bCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bCancelActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jTabbedPane1))) .addGap(36, 36, 36)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 582, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bCancel) .addContainerGap()) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void bRechercherCotaParMoisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRechercherCotaParMoisActionPerformed log.trace("Debut"); try { afficher_la_date_dun_mois(); } catch (ParseException ex) { log.error("Erreure ", ex); } log.trace("Fin"); }//GEN-LAST:event_bRechercherCotaParMoisActionPerformed public void afficher_la_date_dun_mois() throws ParseException { // Afficher les Date + le Nom du Jours d'un mois et d'une annee dans tRDVChoix DecimalFormat myFormatter = new DecimalFormat("00"); String output = myFormatter.format(jMonthChooser1.getMonth() + 1); Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, jMonthChooser1.getMonth()); DefaultTableModel md = new DefaultTableModel(); md.setColumnIdentifiers(new String[]{"Jours", "date"}); cal.set(Calendar.YEAR, jYearChooser1.getYear()); int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); for (int i = 1; i < maxDay + 1; i++) { String output2 = myFormatter.format(i); // Ajouter le Nom du jour SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String n = jYearChooser1.getYear() + "-" + output + "-" + output2; Date dateValidation = formatter.parse(n); md.addRow(new Object[]{new SimpleDateFormat("EEEE").format(dateValidation), jYearChooser1.getYear() + "-" + output + "-" + output2}); } tRDVchoix1.setModel(md); } private void tRDVchoix1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tRDVchoix1MouseEntered // TODO add your handling code here: }//GEN-LAST:event_tRDVchoix1MouseEntered public boolean Verifier_date_rdv() { // Cette methode Verifie si la date de RDv a été Pris ou existe Sur TOute l'année // et affiche un message d'erreur si l'utilisateur choisit une date prise Rechercher_Unite_Convontion(); int row = tRDVchoix1.getSelectedRow(); ArrayList date = new ArrayList(); // tableau de ma date ArrayList etat = new ArrayList(); // tableau des etat des date boolean h = false; // etat des date String date_tester = tRDVchoix1.getModel().getValueAt(row, 1).toString(); con = Connect.connect(); String sql = "select Etat_RDV,date_rdv from rdv where convontion_id_conv='" + id_conv + "'"; try { pst = con.prepareStatement(sql); ResultSet rst1 = pst.executeQuery(sql); while (rst1.next()) { // Remplire ArrayList "Etat" et "Date" String Etat_rdv_pris = rst1.getString("Etat_RDV"); Date date_rdv_pris = rst1.getDate("date_rdv"); DateFormat fd = new SimpleDateFormat("yyyy-MM-dd"); String dateFormatee = fd.format(date_rdv_pris); etat.add(Etat_rdv_pris); date.add(dateFormatee); } } catch (SQLException | NumberFormatException e) { JOptionPane.showMessageDialog(null, e.getMessage()); log.error(e); } finally { /*This block should be added to your code * You need to release the resources like connections */ if (con != null) { try { con.close(); } catch (SQLException ex) { log.error(ex); } } } for (int i = 0; i < etat.size(); i++) { // Parcourt tout le tableau if (date.get(i).equals(date_tester)) { // verifie si la date existe dans la tableau if (etat.get(i).equals("Pris") || etat.get(i).equals("En Attente")) { // verifie l'etat si pris ou en attent puis h = true h = true; } } } return h; } @SuppressWarnings("unchecked") private boolean Verifier_date_rdv_colorier(String date_rdv_tableau) { // Cette methode Verifie si la date de RDv a été Pris ou existe Sur TOute l'année // puis elle colorie le tableau Rechercher_Unite_Convontion(); ArrayList date = new ArrayList(); // tableau des date ArrayList etat = new ArrayList(); // tableau des etat des date boolean h = false; // l'etat du RDV con = Connect.connect(); String sql = "select Etat_RDV,date_rdv from rdv where convontion_id_conv='" + id_conv + "'"; try { pst = con.prepareStatement(sql); ResultSet rst1 = pst.executeQuery(sql); while (rst1.next()) { // Remplire ArrayList "Etat" et "Date" depuis la table RDV String Etat_rdv_pris = rst1.getString("Etat_RDV"); Date date_rdv_pris = rst1.getDate("date_rdv"); DateFormat fd = new SimpleDateFormat("yyyy-MM-dd"); String dateFormatee = fd.format(date_rdv_pris); etat.add(Etat_rdv_pris); date.add(dateFormatee); } } catch (SQLException | NumberFormatException e) { JOptionPane.showMessageDialog(null, e.getMessage()); log.error(e); } finally { /*This block should be added to your code * You need to release the resources like connections */ if (con != null) { try { con.close(); } catch (SQLException ex) { log.error(ex); } } } for (int i = 0; i < etat.size(); i++) { // Parcourt tout le tableau if (date.get(i).equals(date_rdv_tableau)) { // verifie si la date existe dans la tableau if (etat.get(i).equals("Pris") || etat.get(i).equals("En Attente")) { // verifie l'etat si c'est pirs ou en attente h = true h = true; } } } return h; } private void tRDVchoix1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tRDVchoix1MouseClicked // Envoie de la Date du TABLEAU "Choisir une Date" à "Validation RDV" log.trace("Debut"); boolean v; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); int row = tRDVchoix1.getSelectedRow(); String n = tRDVchoix1.getModel().getValueAt(row, 1).toString(); String nomJour = tRDVchoix1.getModel().getValueAt(row, 0).toString(); if (nomJour.equals("vendredi")) { // Si Jour = Vendredi alors ERREUR JOptionPane.showMessageDialog(null, "c'est un week end"); } else { Boolean k = Verifier_date_rdv(); // System.out.println("Table else t =" + t); // if (t == false) { // Si la Date a était prise alos if (k == false) { // Si la Date a était prise alos // System.out.println("Table else if t =" + t); try { Date dateValidation = formatter.parse(n); // foramter la date // jDateValidation.setDate(dateValidation); v = true; } catch (ParseException e) { log.error(e); v = false; } finally { /*This block should be added to your code * You need to release the resources like connections */ if (con != null) { try { con.close(); } catch (SQLException ex) { log.error(ex); } } } // if (v == true) { // // Débloquer les autres anglets et affecter la date prise // // System.out.println("Table if v =" + v); // jTabbedPane1.setEnabledAt(3, true); // jTabbedPane1.setSelectedIndex(3); // // jDateValidation.setEnabled(false); // bAjouterValidation.setEnabled(true); // bModifierValidation.setEnabled(false); // } else { // // System.out.println("Table Erreur"); // JOptionPane.showMessageDialog(null, "Erreur"); // } } else { JOptionPane.showMessageDialog(null, "c'est une date prise"); } } log.trace("Fin"); }//GEN-LAST:event_tRDVchoix1MouseClicked private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed ConsulterConvontionRDV s = new ConsulterConvontionRDV(); s.setVisible(true); }//GEN-LAST:event_jButton3ActionPerformed private void bRechercherCotaParAnsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRechercherCotaParAnsActionPerformed log.trace("Debut"); if (cConvontion.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(null, "La Convontion est vide"); } else { Rechercher_Unite_Convontion(); afficher_le_Mois_dune_anne(); } log.trace("Fin"); }//GEN-LAST:event_bRechercherCotaParAnsActionPerformed public void Rechercher_Unite_Convontion() { log.trace("Debut"); String sql = "select partenaire_id_p,id_conv, nbr_RDv , unite from convontion where nom_convontion ='" + cConvontion.getSelectedItem() + "'"; con = Connect.connect(); try { pst = con.prepareStatement(sql); ResultSet rec2 = pst.executeQuery(sql); rec2.next(); id_p = Integer.parseInt(rec2.getString("partenaire_id_p")); id_conv = Integer.parseInt(rec2.getString("id_conv")); nbr_RDv = rec2.getString("nbr_RDv"); unite_c = rec2.getString("unite"); } catch (SQLException | NumberFormatException e) { JOptionPane.showMessageDialog(null, e.getMessage()); log.error(e); } finally { /*This block should be added to your code * You need to release the resources like connections */ if (con != null) { try { con.close(); } catch (SQLException ex) { log.error(ex); } } } log.trace("Fin"); } public void afficher_le_Mois_dune_anne() { // Cette methode Affiche tout les mois d'une annee dans tConvontion log.trace("Debut"); int quantite_par_unite; // la quantite des RDV restant par Unite String Unite[] = {"Mois", "Semaine", "Jours"}; // Tableau des Nom d'unite DecimalFormat myFormatter = new DecimalFormat("00"); int MoisAnnee[] = {JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER}; DefaultTableModel md = new DefaultTableModel(); md.setColumnIdentifiers(new String[]{"Mois", "Annee", "Quantite"}); if (unite_c.equals(Unite[0])) { // Calcule de la Quantite des RDV restant dans l'unite MOIS Calculer_les_RDv_Pris(); quantite_par_unite = Integer.parseInt(nbr_RDv); for (int i = 0; i < MoisAnnee.length; i++) { String Mois = myFormatter.format(i + 1); // le Mois (formater et +1 pour afficher le mois exacte) int quantite_restante_rdv = quantite_par_unite - tableau_resultat_rdv_mois_par_annee[i]; md.addRow(new Object[]{Mois, jYearChooser2.getYear(), quantite_restante_rdv}); } tConvontion.setModel(md); } else if (unite_c.equals(Unite[1])) { // Calcule de la Quantite des RDV restant dans l'unite Semaine } else if (unite_c.equals(Unite[2])) { // Calcule de la Quantite des RDV restant dans l'unite Jours Calculer_les_RDv_Pris(); Nbr_Vedredie_de_toute_lannee(); quantite_par_unite = Integer.parseInt(nbr_RDv); for (int i = 0; i < MoisAnnee.length; i++) { // calculer le nombre de rdv par mois sans les weekend String Mois = myFormatter.format(i + 1); // int quantite_restante_rdv = quantite_par_unite * tableau_max_Day_mois_par_annee[i] - tableau_Vendredi_mois_par_annee[i]; int quantite_restante_rdv = tableau_max_Day_mois_par_annee[i] - tableau_Vendredi_mois_par_annee[i] - tableau_resultat_rdv_mois_par_annee[i]; md.addRow(new Object[]{Mois, jYearChooser2.getYear(), quantite_restante_rdv}); } tConvontion.setModel(md); } // } log.trace("Fin"); // Remplir la table tConvontion } private void Nbr_Vedredie_de_toute_lannee() { // cette methode Calcule les vendredi de toute l'année par mois log.trace("Debut"); Calendar cal = Calendar.getInstance(); int tableauMois[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; for (int i = 0; i < tableauMois.length; i++) { int Vendredi_par_mois = get_nombre_Vendredi_par_mois(tableauMois[i], jYearChooser1.getYear()); tableau_Vendredi_mois_par_annee[i] = Vendredi_par_mois; cal.set(Calendar.MONTH, tableauMois[i]); cal.set(Calendar.YEAR, jYearChooser2.getYear()); int maxDayPerMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH); tableau_max_Day_mois_par_annee[i] = maxDayPerMonth; } log.trace("Fin"); } public int get_nombre_Vendredi_par_mois(int mois, int annee) { // Cette Methode calcule de nombre de WeekEnd par mois de l'année log.trace("Debut"); Calendar mois_annee = Calendar.getInstance(); mois_annee.set(annee, mois, 1); int nombre_jours_du_mois = mois_annee.getActualMaximum(Calendar.DAY_OF_MONTH); int nombre_week_end = 0; for (int i = 1; i <= nombre_jours_du_mois; i++) { mois_annee.set(annee, mois, i); int dayOfWeek = mois_annee.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == Calendar.FRIDAY) { nombre_week_end++; } } log.trace("Fin"); return nombre_week_end; } private void Calculer_les_RDv_Pris() { // Cette methode Calcule les RDv Pris ou En ATTENTE Sur TOute l'année log.trace("Debut"); Rechercher_Unite_Convontion(); DecimalFormat myFormatter = new DecimalFormat("00"); String sql = "select Etat_RDV,date_rdv from rdv where convontion_id_conv='" + id_conv + "'"; int yearChooser2 = jYearChooser2.getYear(); for (int m = 0; m <= 11; m++) { // calculer les rdv restant sur tout les mois le l'annee int i = 0; con = Connect.connect(); try { pst = con.prepareStatement(sql); ResultSet rst1 = pst.executeQuery(sql); while (rst1.next()) { String Etat_rdv_pris = rst1.getString("Etat_RDV"); Date date_rdv_pris = rst1.getDate("date_rdv"); DateFormat fd = new SimpleDateFormat("yyyy-MM-dd"); String dateFormatee = fd.format(date_rdv_pris); String Mois = dateFormatee.substring(5, 7); String Annee = dateFormatee.substring(0, 4); String Month = myFormatter.format(m + 1); String yearChooser2Formater = myFormatter.format(yearChooser2); if ((Etat_rdv_pris.equals("Pris") || Etat_rdv_pris.equals("En Attente")) && Mois.equals(Month) && Annee.equals(yearChooser2Formater)) { // Si l'etat du RDV = Pris ou En Attente alors +1 i++; } } tableau_resultat_rdv_mois_par_annee[m] = i; } catch (SQLException | NumberFormatException e) { JOptionPane.showMessageDialog(null, e.getMessage()); log.error(e); } finally { /*This block should be added to your code * You need to release the resources like connections */ if (con != null) { try { con.close(); } catch (SQLException ex) { log.error(ex); } } } } log.trace("Fin"); } private void cConvontionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cConvontionActionPerformed log.trace("Debut"); String a = (String) cConvontion.getSelectedItem(); txtNomConvontion.setText(a); txtNomConvontion.setEditable(false); log.trace("Fin"); }//GEN-LAST:event_cConvontionActionPerformed private void cConvontionPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_cConvontionPopupMenuWillBecomeInvisible Rechercher_Unite_Convontion(); }//GEN-LAST:event_cConvontionPopupMenuWillBecomeInvisible private void tConvontionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tConvontionMouseClicked log.trace("Debut"); boolean b = false; int row = tConvontion.getSelectedRow(); String Mois = tConvontion.getModel().getValueAt(row, 0).toString(); String Annee = tConvontion.getModel().getValueAt(row, 1).toString(); String quantite_rdv = tConvontion.getModel().getValueAt(row, 2).toString(); jYearChooser1.setYear(Integer.parseInt(Annee)); int Month = Integer.parseInt(Mois) - 1; jMonthChooser1.setMonth(Month); if (Integer.parseInt(quantite_rdv) == 0) { // Si quantite de RDV = 0 alors ERREUR JOptionPane.showMessageDialog(null, "Erreur: La Quantite est = 0. "); } else { try { afficher_la_date_dun_mois(); } catch (ParseException ex) { log.error(ex); } b = true; /*This block should be added to your code * You need to release the resources like connections */ if (con != null) { try { con.close(); } catch (SQLException ex) { log.error(ex); } } } if (b == true) { // Debloquer les autres anglets log.trace("Debut Debloquer les autres anglets"); jTabbedPane1.setEnabledAt(1, true); jTabbedPane1.setSelectedIndex(1); log.trace("Fin Debloquer les autres anglets"); } log.trace("Fin"); // else { // JOptionPane.showMessageDialog(null, "Erreur"); // } }//GEN-LAST:event_tConvontionMouseClicked private void bCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelActionPerformed Cancel(); }//GEN-LAST:event_bCancelActionPerformed private void Cancel(){ this.dispose(); this.setVisible(false); if (id == 'A') { this.setVisible(false); HomeAdministrateur h = new HomeAdministrateur(id); h.setVisible(true); } else if (id == 'S') { this.setVisible(false); HomeSecretaire h = new HomeSecretaire(id); h.setVisible(true); } else if (id == 'D') { this.setVisible(false); HomeDirecteur h = new HomeDirecteur(id); h.setVisible(true); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Quantite.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Quantite.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Quantite.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Quantite.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Quantite().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bCancel; private javax.swing.JButton bRechercherCotaParAns; private javax.swing.JButton bRechercherCotaParMois; private javax.swing.JComboBox cConvontion; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private com.toedter.calendar.JMonthChooser jMonthChooser1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTabbedPane jTabbedPane1; private com.toedter.calendar.JYearChooser jYearChooser1; private com.toedter.calendar.JYearChooser jYearChooser2; private javax.swing.JPanel pChoisirDate; private javax.swing.JPanel pChoisirRDV; private javax.swing.JTable tConvontion; private javax.swing.JScrollPane tDateParConvontion; private javax.swing.JTable tRDVchoix1; private javax.swing.JTextField txtNomConvontion; // End of variables declaration//GEN-END:variables }
package org.iMage.mosaique.rectangle; import org.junit.*; import org.iMage.mosaique.rectangle.RectangleShape; public class RectangleShapeTest { @Test public void RectangleShapeTest(){ } }
package vo; public class BidItemUserJoinVo { String item_name,item_mode,diff,user_first_name,user_city,user_state,user_country,user_email,user_phone_no,bidding_timestamp,user_id,item_condition,bid_status; public String getDiff() { return diff; } public void setDiff(String diff) { this.diff = diff; } public String getItem_mode() { return item_mode; } public void setItem_mode(String item_mode) { this.item_mode = item_mode; } public String getItem_name() { return item_name; } public void setItem_name(String item_name) { this.item_name = item_name; } int item_id,bidding_bid,item_baseprice,count,max_bid,item_shipping_charge; public int getItem_shipping_charge() { return item_shipping_charge; } public void setItem_shipping_charge(int item_shipping_charge) { this.item_shipping_charge = item_shipping_charge; } public String getBid_status() { return bid_status; } public void setBid_status(String bid_status) { this.bid_status = bid_status; } public String getItem_condition() { return item_condition; } public void setItem_condition(String item_condition) { this.item_condition = item_condition; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getMax_bid() { return max_bid; } public void setMax_bid(int max_bid) { this.max_bid = max_bid; } public String getUser_first_name() { return user_first_name; } public void setUser_first_name(String user_first_name) { this.user_first_name = user_first_name; } public String getUser_city() { return user_city; } public void setUser_city(String user_city) { this.user_city = user_city; } public String getUser_state() { return user_state; } public void setUser_state(String user_state) { this.user_state = user_state; } public String getUser_country() { return user_country; } public void setUser_country(String user_country) { this.user_country = user_country; } public String getUser_email() { return user_email; } public void setUser_email(String user_email) { this.user_email = user_email; } public String getUser_phone_no() { return user_phone_no; } public void setUser_phone_no(String user_phone_no) { this.user_phone_no = user_phone_no; } public String getBidding_timestamp() { return bidding_timestamp; } public void setBidding_timestamp(String bidding_timestamp) { this.bidding_timestamp = bidding_timestamp; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public int getItem_id() { return item_id; } public void setItem_id(int item_id) { this.item_id = item_id; } public int getBidding_bid() { return bidding_bid; } public void setBidding_bid(int bidding_bid) { this.bidding_bid = bidding_bid; } public int getItem_baseprice() { return item_baseprice; } public void setItem_baseprice(int item_baseprice) { this.item_baseprice = item_baseprice; } }
package com.dqm.msg; import com.dqm.annotations.Index; import com.dqm.msg.common.MsgPack; import lombok.Getter; import lombok.Setter; /** * Created by dqm on 2018/9/14. */ @Setter @Getter public class GetHeaders implements MsgPack { @Index(val=0, specialType = Index.SpecialType.VARINT) private int startCount; @Index(val=1, size = 32, hex = true) private String hashStart; @Index(val=2, size = 32, hex = true) private String hashStop; }
package com.solunaire.vectrize; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.IOException; public class PreviewActivity extends AppCompatActivity { String picturePath; Uri pictureUri; byte[] bytes; boolean usesPicPath, usesUriPath; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_preview); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); //Load Image into ImageView to Preview before Running Primitive Intent intent1 = getIntent(); ImageView imageView = (ImageView) findViewById(R.id.image_preview); picturePath = intent1.getExtras().getString("key"); pictureUri = (Uri) intent1.getExtras().get("uriKey"); System.out.println(picturePath); if(picturePath != null) { imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); usesPicPath = true; } else if(pictureUri != null) { ParcelFileDescriptor parcelFD = null; try { parcelFD = getContentResolver().openFileDescriptor(pictureUri, "r"); FileDescriptor imageSource = parcelFD.getFileDescriptor(); // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(imageSource, null, o); // the new size we want to scale to final int REQUIRED_SIZE = 1024; // Find the correct scale value. It should be the power of 2. int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) { break; } width_tmp /= 2; height_tmp /= 2; scale *= 2; } // decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; Bitmap bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2); imageView.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (parcelFD != null) try { parcelFD.close(); } catch (IOException e) { // ignored } } usesUriPath = true; } else { bytes = (byte[]) intent1.getExtras().get("img"); BitmapFactory.Options options = new BitmapFactory.Options(); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options); imageView.setImageBitmap(bitmap); usesPicPath = false; } //Choose Button Initialization FloatingActionButton btn = (FloatingActionButton) findViewById(R.id.usePicBtn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent optionsIntent = new Intent(PreviewActivity.this, OptionsActivity.class); if(usesPicPath) { optionsIntent.putExtra("path", picturePath); } else if (usesUriPath) { optionsIntent.putExtra("uri", pictureUri); } else { optionsIntent.putExtra("img", bytes); } startActivity(optionsIntent); finish(); //Can't press back to load Preview Activity } }); } @Override public boolean onSupportNavigateUp() { finish(); return true; } }
package com.gsn.data.result; import com.gsn.constants.ResultCodeConstants; import java.util.Date; /** * 任何api或者dao方法的执行结果数据结构 * <p /> * 包含执行是否成功的信息、错误提示和一个特定类型的返回值;不需要返回值的请使用{@link com.gsn.data.result.ExecInfo} * * @author GSN */ public class ExecResult<T> { //------------------------------------------------------------------------- // 属性字段 //------------------------------------------------------------------------- private Date createTime = new Date(); private int resultCode; private String message; private T data; //------------------------------------------------------------------------- // 功能方法 //------------------------------------------------------------------------- public static <T> ExecResult<T> success() { return new ExecResult<>(ResultCodeConstants.SUCCESS, "", null); } public static <T> ExecResult<T> success(T value) { return new ExecResult<>(ResultCodeConstants.SUCCESS, "", value); } public static <T> ExecResult<T> fail(String message) { return new ExecResult<>(ResultCodeConstants.SERVER_ERROR, message, null); } public static <T> ExecResult<T> fail(String message, T value) { return new ExecResult<>(ResultCodeConstants.SERVER_ERROR, message, value); } public static <T> ExecResult<T> fail(int errorCode, String message) { return new ExecResult<>(errorCode, message, null); } public static <T> ExecResult<T> fail(int errorCode, String message, T value) { return new ExecResult<>(errorCode, message, value); } public boolean isSuccess() { return this.resultCode == ResultCodeConstants.SUCCESS; } //------------------------------------------------------------------------- // 常规setter/getter及构造方法 //------------------------------------------------------------------------- public ExecResult() {} public ExecResult(int resultCode, String message, T data) { this.resultCode = resultCode; this.message = message; this.data = data; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public T getData() { return data; } public void setData(T data) { this.data = data; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getResultCode() { return resultCode; } public void setResultCode(int resultCode) { this.resultCode = resultCode; } }
package loyer.sqlserver; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * SQLserver2017连接帮助类 * @author Loyer * */ public class DataBase { //数据库连接字符串 private final static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private String url = null; private final static String username = "sa"; private String password = null; private Connection connection = null; private ResultSet res = null; private PreparedStatement pstmt = null; public DataBase(String databaseName, String password) { this.url = "jdbc:sqlserver://localhost:1433;databaseName="+databaseName+""; this.password = password; } /** * 提供数据库连接方法 * @return getConnectionCommon() * @throws Exception */ public Connection getConnection() throws Exception { return getConnectionCommon(); } /** * 定义数据库连接方法 * @return connection * @throws Exception */ private Connection getConnectionCommon() throws Exception { Connection connection = null; //连接对象 try { //加载驱动 Class.forName(driver); connection = DriverManager.getConnection(url, username, password); } catch(ClassNotFoundException e) { throw new Exception("JDBC驱动加载失败"); } catch(SQLException e) { throw new Exception("无法连接到数据库"); } return connection; } /** * 提供数据库查询方法 * @param sql * @param str * @return * @throws Exception */ public ResultSet Search(String sql, String str[]) throws Exception { try { connection = getConnection(); pstmt = connection.prepareStatement(sql); if(str != null) { for(int i = 0; i < str.length; i++) { pstmt.setString(i + 1, str[i]); } } res = pstmt.executeQuery(); } catch(Exception e) { throw new Exception("数据库操作失败:"+e.getMessage()); } return res; } /** * 提供数据库增删修改方法 * @param sql * @param str * @return * @throws Exception */ public int AddU(String sql, String str[]) throws Exception { int getBack = 0; try { connection = getConnection(); pstmt = connection.prepareStatement(sql); if(str != null) { for(int i = 0; i < str.length; i++) { pstmt.setString(i + 1, str[i]); } } getBack = pstmt.executeUpdate(); } catch(Exception e) { throw new Exception("数据库操作失败:"+e.getMessage()); } return getBack; } /** * 数据库关闭连接方法 * @throws SQLException */ public void close() throws SQLException { if(res != null) { try { res.close(); } catch(SQLException e) { throw new SQLException("数据库关闭失败:"+e.getMessage()); } } if(pstmt != null) { try { pstmt.close(); } catch(SQLException e) { throw new SQLException("数据库关闭失败:"+e.getMessage()); } } if(connection != null) { try { connection.close(); } catch(SQLException e) { throw new SQLException("数据库关闭失败:"+e.getMessage()); } } } }
package com.example.tp2j2e_crud.servlets; import com.example.tp2j2e_crud.beans.Produit; import com.example.tp2j2e_crud.dao.IProduitDao; import com.example.tp2j2e_crud.dao.ProduitDaoImpl; import com.example.tp2j2e_crud.model.ProduitModele; import jakarta.servlet.*; import jakarta.servlet.http.*; import jakarta.servlet.annotation.*; import java.io.IOException; import java.util.List; @WebServlet(name = "ProduitServlet", urlPatterns = {"/produits","*.do"}) public class ProduitServlet extends HttpServlet { private IProduitDao produitDao; @Override public void init() throws ServletException { produitDao= new ProduitDaoImpl(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getServletPath(); switch (path){ case "/produits.do": request.getRequestDispatcher("/index.jsp").forward(request,response); break; case "/search.do": ProduitModele produitModele= new ProduitModele(); String keyword= request.getParameter("keyword"); produitModele.setKeyword(keyword); List<Produit> produits= produitDao.produits(keyword); produitModele.setProduits(produits); request.setAttribute("modele",produitModele); request.getRequestDispatcher("/index.jsp").forward(request,response); break; case "/saisie.do": request.getRequestDispatcher("/create.jsp").forward(request,response); break; case "/supprimer.do": int id = Integer.parseInt(request.getParameter("id")); produitDao.deleteProduit(id); response.sendRedirect("search.do?keyword="); break; case "/editer.do": int id_edit = Integer.parseInt(request.getParameter("id")); Produit produit= produitDao.getProduit(id_edit); request.setAttribute("produit",produit); request.getRequestDispatcher("editer.jsp").forward(request,response); default: request.getRequestDispatcher("/index.jsp").forward(request,response); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getServletPath(); if(path.equals("/save.do")){ String nom = request.getParameter("nom"); double prix = Double.parseDouble(request.getParameter("prix")); Produit produit = produitDao.save(new Produit(nom,prix)); request.setAttribute("produit",produit); request.getRequestDispatcher("/confirmation.jsp").forward(request,response); }else if(path.equals("/update.do")){ int id_update=Integer.parseInt(request.getParameter("id")); String nom_update=request.getParameter("nom"); double prix_update= Double.parseDouble(request.getParameter("prix")); Produit produit_update=produitDao.updateProduit(new Produit(id_update,nom_update,prix_update)); request.setAttribute("produit",produit_update); request.getRequestDispatcher("/confirmation.jsp").forward(request,response); } } }
package com.simple.imlib.handler; import com.tencent.mars.wrapper.remote.PushMessage; public abstract class BusinessHandler { public abstract boolean handlerReceivedMessage(PushMessage pushMessage); }
package com.contentstack.sdk.utilities; import android.annotation.SuppressLint; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** * Helper class of utilities. * * * @author contentstack.com, Inc * */ public class ContentstackUtil { /** * Converts the given date to user&#39;s timezone. * * @param date * date in ISO format. * * @return * {@link Calendar} object. * * @throws ParseException * * <br><br><b>Example :</b><br> * <pre class="prettyprint"> * BuiltUtil.parseDate(dateString, TimeZone.getDefault()); * </pre> * */ public static Calendar parseDate(String date, TimeZone timeZone) throws ParseException { ArrayList<String> knownPatterns = new ArrayList<String>(); knownPatterns.add("yyyy-MM-dd'T'HH:mm:ssZ"); knownPatterns.add("yyyy-MM-dd'T'HH:mm:ss'Z'"); knownPatterns.add("yyyy-MM-dd'T'HH:mm.ss'Z'"); knownPatterns.add("yyyy-MM-dd'T'HH:mmZ"); knownPatterns.add("yyyy-MM-dd'T'HH:mm'Z'"); knownPatterns.add("yyyy-MM-dd'T'HH:mm'Z'"); knownPatterns.add("yyyy-MM-dd'T'HH:mm:ss"); knownPatterns.add("yyyy-MM-dd' 'HH:mm:ss"); knownPatterns.add("yyyy-MM-dd"); knownPatterns.add("HH:mm:ssZ"); knownPatterns.add("HH:mm:ss'Z'"); for (String formatString : knownPatterns){ try { return parseDate(date, formatString, timeZone); }catch (ParseException e) {} } return null; } /** * Converts the given date to the user&#39;s timezone. * * @param date * date in string format. * * @param dateFormat * date format. * * @return * {@link Calendar} object. * * @throws ParseException * * <br><br><b>Example :</b><br> * <pre class="prettyprint"> * BuiltUtil.parseDate(dateString, "yyyy-MM-dd'T'HH:mm:ssZ", TimeZone.getTimeZone("GMT")); * </pre> */ @SuppressLint("SimpleDateFormat") public static Calendar parseDate(String date, String dateFormat, TimeZone timeZone) throws ParseException { Date dateObject = null; String month = ""; String day = ""; String year = ""; String hourOfDay = ""; String min = ""; String sec = ""; Calendar cal = Calendar.getInstance(); SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat); dateObject = dateFormatter.parse(date); month = new SimpleDateFormat("MM").format(dateObject); day = new SimpleDateFormat("dd").format(dateObject); year = new SimpleDateFormat("yyyy").format(dateObject); hourOfDay = new SimpleDateFormat("HH").format(dateObject); min = new SimpleDateFormat("mm").format(dateObject); sec = new SimpleDateFormat("ss").format(dateObject); if(timeZone != null){ cal.setTimeZone(timeZone); }else{ cal.setTimeZone(TimeZone.getDefault()); } cal.set(Integer.valueOf(year), Integer.valueOf(month)-1, Integer.valueOf(day), Integer.valueOf(hourOfDay), Integer.valueOf(min), Integer.valueOf(sec)); month = null; day = null; year = null; hourOfDay = null; min = null; sec = null; dateObject = null; return cal; } /** * Type to compare dates. * * @author built.io, Inc * */ public static enum DateComapareType{ WEEK, DAY, HOURS, MINUTES, SECONDS }; }
package com.baby.babygrowthrecord.Growth; /** * Created by Administrator on 2016/11/24. */ public class Growth_Class { private long id; private String year; private String week; private String duration; private String content; private int img_first; private int img_second; public Growth_Class(long id, String year, String week, String duration, String content, int img_first, int img_second) { this.id = id; this.year = year; this.week = week; this.duration = duration; this.content = content; this.img_first = img_first; this.img_second = img_second; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getWeek() { return week; } public void setWeek(String week) { this.week = week; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getImg_first() { return img_first; } public void setImg_first(int img_first) { this.img_first = img_first; } public int getImg_second() { return img_second; } public void setImg_second(int img_second) { this.img_second = img_second; } }
/** */ package iso20022; import java.lang.String; import java.util.Date; import java.util.Map; import org.eclipse.emf.common.util.DiagnosticChain; import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Repository Concept</b></em>'. * <!-- end-user-doc --> * * <!-- begin-model-doc --> * artefact that has been defined during the development of an ISO 20022 MessageDefinition and which is stored in the Repository * <!-- end-model-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link iso20022.RepositoryConcept#getName <em>Name</em>}</li> * <li>{@link iso20022.RepositoryConcept#getDefinition <em>Definition</em>}</li> * <li>{@link iso20022.RepositoryConcept#getSemanticMarkup <em>Semantic Markup</em>}</li> * <li>{@link iso20022.RepositoryConcept#getDoclet <em>Doclet</em>}</li> * <li>{@link iso20022.RepositoryConcept#getExample <em>Example</em>}</li> * <li>{@link iso20022.RepositoryConcept#getConstraint <em>Constraint</em>}</li> * <li>{@link iso20022.RepositoryConcept#getRegistrationStatus <em>Registration Status</em>}</li> * <li>{@link iso20022.RepositoryConcept#getRemovalDate <em>Removal Date</em>}</li> * </ul> * * @see iso20022.Iso20022Package#getRepositoryConcept() * @model abstract="true" * @generated */ public interface RepositoryConcept extends ModelEntity { /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * a word or set of words by which a RepositoryConcept is known, addressed or referred to * <!-- end-model-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see iso20022.Iso20022Package#getRepositoryConcept_Name() * @model required="true" ordered="false" * @generated */ String getName(); /** * Sets the value of the '{@link iso20022.RepositoryConcept#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); /** * Returns the value of the '<em><b>Definition</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * describes the semantic meaning of a RepositoryConcept * <!-- end-model-doc --> * @return the value of the '<em>Definition</em>' attribute. * @see #setDefinition(String) * @see iso20022.Iso20022Package#getRepositoryConcept_Definition() * @model ordered="false" * @generated */ String getDefinition(); /** * Sets the value of the '{@link iso20022.RepositoryConcept#getDefinition <em>Definition</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Definition</em>' attribute. * @see #getDefinition() * @generated */ void setDefinition(String value); /** * Returns the value of the '<em><b>Semantic Markup</b></em>' containment reference list. * The list contents are of type {@link iso20022.SemanticMarkup}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * Enables modelers to markup elements of the Repository with semantic metadata. * <!-- end-model-doc --> * @return the value of the '<em>Semantic Markup</em>' containment reference list. * @see iso20022.Iso20022Package#getRepositoryConcept_SemanticMarkup() * @model containment="true" ordered="false" * annotation="urn:iso:std:iso:20022:2013:ecore:extension basis='IMPLEMENTATION_ENHANCEMENT' description='SemanticMarkup is structured with a MetaClass instead of a Tuple text.This provides more control, structure and validation to the feature and avoids the need for reparsing each time the value of a textual feature.'" * @generated */ EList<SemanticMarkup> getSemanticMarkup(); /** * Returns the value of the '<em><b>Doclet</b></em>' containment reference list. * The list contents are of type {@link iso20022.Doclet}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * Doclets of the entity, used for documentation. * <!-- end-model-doc --> * @return the value of the '<em>Doclet</em>' containment reference list. * @see iso20022.Iso20022Package#getRepositoryConcept_Doclet() * @model containment="true" ordered="false" * annotation="urn:iso:std:iso:20022:2013:ecore:extension basis='RepositoryManagement' description='to store documentation information : scope, usage, ...'" * @generated */ EList<Doclet> getDoclet(); /** * Returns the value of the '<em><b>Example</b></em>' attribute list. * The list contents are of type {@link java.lang.String}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * provides a representative instance of a RepositoryConcept * <!-- end-model-doc --> * @return the value of the '<em>Example</em>' attribute list. * @see iso20022.Iso20022Package#getRepositoryConcept_Example() * @model * @generated */ EList<String> getExample(); /** * Returns the value of the '<em><b>Constraint</b></em>' containment reference list. * The list contents are of type {@link iso20022.Constraint}. * It is bidirectional and its opposite is '{@link iso20022.Constraint#getOwner <em>Owner</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * a property of a RepositoryConcept specifying a semantic condition or restriction expressed in natural language text and potentially in a formal notation * <!-- end-model-doc --> * @return the value of the '<em>Constraint</em>' containment reference list. * @see iso20022.Iso20022Package#getRepositoryConcept_Constraint() * @see iso20022.Constraint#getOwner * @model opposite="owner" containment="true" * @generated */ EList<Constraint> getConstraint(); /** * Returns the value of the '<em><b>Registration Status</b></em>' attribute. * The default value is <code>"Provisionally Registered"</code>. * The literals are from the enumeration {@link iso20022.RegistrationStatus}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * specifies in which stage of the registration lifecycle a RepositoryConcept is in * <!-- end-model-doc --> * @return the value of the '<em>Registration Status</em>' attribute. * @see iso20022.RegistrationStatus * @see #setRegistrationStatus(RegistrationStatus) * @see iso20022.Iso20022Package#getRepositoryConcept_RegistrationStatus() * @model default="Provisionally Registered" required="true" ordered="false" * @generated */ RegistrationStatus getRegistrationStatus(); /** * Sets the value of the '{@link iso20022.RepositoryConcept#getRegistrationStatus <em>Registration Status</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Registration Status</em>' attribute. * @see iso20022.RegistrationStatus * @see #getRegistrationStatus() * @generated */ void setRegistrationStatus(RegistrationStatus value); /** * Returns the value of the '<em><b>Removal Date</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * specifies the date at which a RepositoryConcept will cease or has ceased to be part of the Repository * <!-- end-model-doc --> * @return the value of the '<em>Removal Date</em>' attribute. * @see #setRemovalDate(Date) * @see iso20022.Iso20022Package#getRepositoryConcept_RemovalDate() * @model ordered="false" * @generated */ Date getRemovalDate(); /** * Sets the value of the '{@link iso20022.RepositoryConcept#getRemovalDate <em>Removal Date</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Removal Date</em>' attribute. * @see #getRemovalDate() * @generated */ void setRemovalDate(Date value); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * If a removalDate is specified then the registrationStatus must be OBSOLETE * removalDate->notEmpty( ) implies registrationStatus = RegistrationStatus::OBSOLETE * <!-- end-model-doc --> * @model required="true" ordered="false" contextRequired="true" contextOrdered="false" diagnosticsRequired="true" diagnosticsOrdered="false" * @generated */ boolean RemovalDateRegistrationStatus(Map context, DiagnosticChain diagnostics); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * First letter of name shall be upper case. [A-Z] * Set {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}->exists(x|x=name.substring(1,1)) * <!-- end-model-doc --> * @model required="true" ordered="false" contextRequired="true" contextOrdered="false" diagnosticsRequired="true" diagnosticsOrdered="false" * @generated */ boolean NameFirstLetterUppercase(Map context, DiagnosticChain diagnostics); } // RepositoryConcept
package com.becool.baidu.service; import org.apache.poi.ss.usermodel.Workbook; import com.becool.baidu.pojo.FileBean; public interface DoctorService { FileBean parseData(Workbook wb,String company); }
package com.prep.datastructure.collection; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; public class Set_Example { public static void main(String[] args){ Set setA= new HashSet(); Set setB= new LinkedHashSet(); Set setC =new TreeSet(); setA.add("element 1"); setA.add("element 2"); setA.add("element 3"); Iterator itor1=setA.iterator(); System.out.println("HashSet Print"); while(itor1.hasNext()) System.out.print((String)itor1.next()+ " , "); System.out.println("\r\n"); setB.add("element 1"); setB.add("element 2"); setB.add("element 3"); Iterator itor2=setA.iterator(); System.out.println("LinkedHashSet Print"); while(itor2.hasNext()) System.out.print((String)itor2.next()+ " , "); System.out.println("\r\n"); setC.add("element 1"); setC.add("element 2"); setC.add("element 3"); Iterator itor3=setA.iterator(); System.out.println("TreeSet Print"); while(itor3.hasNext()) System.out.print((String)itor3.next()+ " , "); System.out.println("\r\n"); SortedSet setD=new TreeSet(); setD.add("element 1"); setD.add("element 2"); setD.add("element 3"); Iterator itor4=setA.iterator(); System.out.println("Sorted TreeSet Print"); while(itor4.hasNext()) System.out.print((String)itor4.next()+ " , "); System.out.println("\r\n"); } }
package com.crypto.controller; import java.util.ArrayList; import java.util.List; import javax.websocket.server.PathParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.crypto.document.BTC; import com.crypto.document.DOGE; import com.crypto.document.ETH; import com.crypto.document.LTC; import com.crypto.service.CryptoService; @RestController public class CryptoController { @Autowired CryptoService cryptoService; @GetMapping("/btc") public List<BTC> getAllBTC(@PathParam(value="crypt") String crypt) { Iterable<BTC> btc = cryptoService.getAllBTC(); List<BTC> coins = new ArrayList<>(); btc.forEach(coins::add); return coins; } @GetMapping("/eth") public List<ETH> getAllETH() { Iterable<ETH> btc = cryptoService.getAllETH(); List<ETH> coins = new ArrayList<>(); btc.forEach(coins::add); return coins; } @GetMapping("/ltc") public List<LTC> getAllLTC() { Iterable<LTC> btc = cryptoService.getAllLTC(); List<LTC> coins = new ArrayList<>(); btc.forEach(coins::add); return coins; } @GetMapping("/doge") public List<DOGE> getAllDOGE() { Iterable<DOGE> btc = cryptoService.getAllDOGE(); List<DOGE> coins = new ArrayList<>(); btc.forEach(coins::add); return coins; } }
package com.junzhao.rongyun.activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.view.View; import android.widget.RadioGroup; import android.widget.TextView; import com.junzhao.base.base.APPCache; import com.junzhao.base.base.BaseAct; import com.junzhao.base.http.IHttpResultSuccess; import com.junzhao.base.http.MLHttpRequestMessage; import com.junzhao.base.http.MLHttpType; import com.junzhao.base.http.MLRequestParams; import com.junzhao.base.recycler.ViewHolder; import com.junzhao.base.recycler.recyclerview.CommonAdapter; import com.junzhao.base.widget.refresh.SmartRefreshLayout; import com.junzhao.shanfen.R; import com.junzhao.shanfen.model.LZFaRedBaoData; import com.junzhao.shanfen.model.LZShouRedBaoData; import com.junzhao.shanfen.service.CommService; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.lidroid.xutils.view.annotation.event.OnClick; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by Administrator on 2018/4/2. */ public class LZRedBaoRecordAty extends BaseAct { @ViewInject(R.id.rg_redrecord) RadioGroup rg_redrecord; @ViewInject(R.id.rb_shoudao) RadioGroup rb_shoudao; @ViewInject(R.id.rb_fachu) RadioGroup rb_fachu; @ViewInject(R.id.rcv_redbaolist) RecyclerView rcv_redbaolist; @ViewInject(R.id.tv_numbao) TextView tv_numbao; @ViewInject(R.id.tv_money) TextView tv_money; @ViewInject(R.id.tv_name) TextView tv_name; @ViewInject(R.id.redbao_pill) SmartRefreshLayout redbao_pill; public int pageNo = 1; public String pageSize = "20"; public int fapageNo = 1; public String fapageSize = "20"; CommonAdapter fCommonAdapter; CommonAdapter SCommonAdapter; LZFaRedBaoData lzFaRedBaoData; LZShouRedBaoData lzShouRedBaoData; boolean isshoudao=true; private boolean mIsRefresh=true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aty_lzrecord); ViewUtils.inject(this); initdata(); selectReceiveRedPacket(); selectSendRedPacket(); } private void initdata() { LinearLayoutManager sgm = new LinearLayoutManager(LZRedBaoRecordAty.this); rcv_redbaolist.setLayoutManager(sgm); //解决上下滑动卡顿的问题(主要原因:该RecycleView嵌套在ScrollView中事件冲突的问题) rcv_redbaolist.setHasFixedSize(true); rcv_redbaolist.setNestedScrollingEnabled(false); rg_redrecord.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.rb_shoudao: isshoudao=true; updata(); break; case R.id.rb_fachu: isshoudao=false; updata(); break; } } }); fCommonAdapter= new CommonAdapter<LZFaRedBaoData.RedPacketVos>(LZRedBaoRecordAty.this, R.layout.item_faredbao, new ArrayList<LZFaRedBaoData.RedPacketVos>()) { @Override public void convert(ViewHolder holder, LZFaRedBaoData.RedPacketVos redPacketVos) { holder.setText(R.id.tv_target_user, redPacketVos.redPacketTypeName); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date date = new Date(Long.parseLong(redPacketVos.sendTime)); holder.setText(R.id.tv_time, simpleDateFormat.format(date)); holder.setText(R.id.tv_money, redPacketVos.redPacketMoney+"元"); holder.setText(R.id.tv_state, redPacketVos.redPacketType); } }; SCommonAdapter= new CommonAdapter<LZShouRedBaoData.RedPacketReceives>(LZRedBaoRecordAty.this, R.layout.item_shouredbao, new ArrayList<LZShouRedBaoData.RedPacketReceives>()) { @Override public void convert(ViewHolder holder, LZShouRedBaoData.RedPacketReceives redPacketVos) { holder.setText(R.id.tv_target_user, redPacketVos.fromUserName); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date date = new Date(Long.parseLong(redPacketVos.receiveTime)); holder.setText(R.id.tv_time, simpleDateFormat.format(date)); holder.setText(R.id.tv_money, redPacketVos.receiveMoney+"元"); // holder.setText(R.id.tv_state, redPacketVos.receiveUserName); } }; redbao_pill.setOnRefreshListener(new SmartRefreshLayout.onRefreshListener() { @Override public void onRefresh() { mIsRefresh = true; pageNo=1; fapageNo=1; if (isshoudao){ selectReceiveRedPacket(); }else { selectSendRedPacket(); } } @Override public void onLoadMore() { mIsRefresh = false; pageNo=pageNo+1; fapageNo=fapageNo+1; if (isshoudao){ selectReceiveRedPacket(); }else { selectSendRedPacket(); } } }); // redbao_pill.setOnHeaderRefreshListener(new AbPullToRefreshView.OnHeaderRefreshListener() { // @Override // public void onHeaderRefresh(AbPullToRefreshView view) { // // } // }); // redbao_pill.setOnFooterLoadListener(new AbPullToRefreshView.OnFooterLoadListener() { // @Override // public void onFooterLoad(AbPullToRefreshView view) { // // } // }); } public void updata(){ if (isshoudao){ tv_name.setText(lzShouRedBaoData.receiveUserName+"共收到"); tv_money.setText("¥"+lzShouRedBaoData.redPacketMoney); tv_numbao.setText(Html.fromHtml(String.format("共<font color=\"#fc8038\">%s</font>个红包", lzShouRedBaoData.redPacketNum))); rcv_redbaolist.setAdapter(SCommonAdapter); }else { tv_name.setText(lzFaRedBaoData.fromUserName+"共发出"); tv_money.setText("¥"+lzFaRedBaoData.redPacketMoney); tv_numbao.setText(Html.fromHtml(String.format("共<font color=\"#fc8038\">%s</font>个红包", lzFaRedBaoData.redPacketNum))); rcv_redbaolist.setAdapter(fCommonAdapter); } } //120.发红包记录查询(song) private void selectSendRedPacket() { Map<String, String> map = new HashMap(); MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("token", APPCache.getToken()); mlHttpParam.put("pageNo", String.valueOf(fapageNo)); mlHttpParam.put("pageSize", fapageSize); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.SELECTSENDREDPACKET, mlHttpParam, LZFaRedBaoData.class, CommService.getInstance(), true); loadData(LZRedBaoRecordAty.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { if(mIsRefresh){ lzFaRedBaoData= (LZFaRedBaoData) obj; fCommonAdapter.removeAllDate(); fCommonAdapter.addDate(lzFaRedBaoData.redPacketVos); updata(); redbao_pill.stopRefresh(); }else { LZFaRedBaoData lzFaRedBaoData1= (LZFaRedBaoData) obj; lzFaRedBaoData.redPacketVos.addAll(lzFaRedBaoData1.redPacketVos); fCommonAdapter.addDate(lzFaRedBaoData1.redPacketVos); redbao_pill.stopLoadMore(); } } } // , new IHttpResultError() { // @Override // public void error(MLHttpType.RequestType type, Object obj) { // // } // } ); } //.121.收红包记录查询(song) private void selectReceiveRedPacket() { Map<String, String> map = new HashMap(); MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("token", APPCache.getToken()); mlHttpParam.put("pageNo", String.valueOf(pageNo)); mlHttpParam.put("pageSize", pageSize); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.SELECTRECEIVEREDPACKET, mlHttpParam, LZShouRedBaoData.class, CommService.getInstance(), true); loadData(LZRedBaoRecordAty.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { // SCommonAdapter.addDate(lzShouRedBaoData.redPacketReceives); if(mIsRefresh){ lzShouRedBaoData= (LZShouRedBaoData) obj; SCommonAdapter.removeAllDate(); SCommonAdapter.addDate(lzShouRedBaoData.redPacketReceives); redbao_pill.stopRefresh(); }else { LZShouRedBaoData lzFaRedBaoData1 = (LZShouRedBaoData) obj; lzShouRedBaoData.redPacketReceives.addAll(lzFaRedBaoData1.redPacketReceives); SCommonAdapter.addDate(lzFaRedBaoData1.redPacketReceives); redbao_pill.stopLoadMore(); } } } // , new IHttpResultError() { // @Override // public void error(MLHttpType.RequestType type, Object obj) { // // } // } ); } @OnClick(R.id.titlebar_tv_left) public void leftClick(View view) { finish(); } }