text
stringlengths
10
2.72M
package com.xampy.namboo.api.payement; import android.util.Log; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.xampy.namboo.api.database.AppDataBaseManager; import org.json.JSONException; import org.json.JSONObject; import static com.xampy.namboo.MainActivity.mCurrentUser; public class PayGatePaymentAPI { public final static String PAYGATE_PAYMENT_URL = "https://paygateglobal.com/api/v1/pay"; public final static String PAYGATE_PAYMENT_CHECK_URL = "https://paygateglobal.com/api/v1/status"; public final static String PAYMENT_PAYGATE_TOGO_KEY = "98a3a78f-7847-4ed5-941a-501ba5d81a6c"; //"a0471f0f-99d4-495b-b3ab-496ba9b4d1d7"; private static final String TX_REFERENCE_STRING = "tx_reference"; private static final String STATUS_STRING = "status"; private static final String IDENTIFIER_STRING = "identifier"; private static final String PHONE_NUMBER_STRING = "phone_number"; private static final String DATETIME_STRING = "datetime"; private static final String PAYMENT_REFERENCE_STRING = "payment_reference"; private static final String PAYMENT_METHOD_STRING = "payment_method"; public interface PayGatePaymentAPIListener { void onTransactionInitializationHas_Success(boolean success_state); void onTransactionCompleteHas_Success(boolean success_state); void onTransactionCompleteHas_Cancelled(); void onTransactionCompleteHas_OnGoing(); void onTransactionCompleteHas_Expired(); void onErrorOccurred(); } private PayGatePaymentAPIListener mListener; private String mTx_Reference; private int mStatus; private static PayGatePaymentAPI mPayGatePaymentAPI; private VolleyRequestQueueSingleton mVolleyRequestQueueSingleton; //By default no transaction on going private boolean mTransactionOnGoing = false; public static boolean mCheckingTransactionComplete = true; public void resetDataParameters(){ mTx_Reference = null; mStatus = -1; mListener = null; mTransactionOnGoing = false; mCheckingTransactionComplete = true; } public PayGatePaymentAPI(VolleyRequestQueueSingleton volley) { this.mVolleyRequestQueueSingleton = volley; //Load the last reference data here String ref = mCurrentUser.getLast_transaction_reference(); if(!ref.equals("@none")){ mTx_Reference = ref; mCheckingTransactionComplete = false; } } public static synchronized PayGatePaymentAPI getInstance(VolleyRequestQueueSingleton volley){ if(mPayGatePaymentAPI == null){ mPayGatePaymentAPI = new PayGatePaymentAPI(volley); } return mPayGatePaymentAPI; } public void initializeTransaction(int price){ JSONObject params = new JSONObject(); try { params.put("auth_token", PAYMENT_PAYGATE_TOGO_KEY); params.put(PHONE_NUMBER_STRING, mCurrentUser.getTel()); params.put("amount", price); //Tranfering 200 Fcfa as test params.put("description", "Test avec xampy num"); params.put("identifier", mCurrentUser.getTel() + "_" + System.currentTimeMillis()); Log.i("PAYMENT REQ", params.toString()); } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( Request.Method.POST, PAYGATE_PAYMENT_URL, params, new Response.Listener<JSONObject> () { @Override public void onResponse(JSONObject response) { //Update the payment initialization status //Initialization finished try { mTx_Reference = response.getString(TX_REFERENCE_STRING); mStatus = response.getInt(STATUS_STRING); //On success response is composed by ^tx_reference and @status //Call Payment listener for checking status Log.i("PAYMENT INFO", "ref + " + mTx_Reference + " status " + mStatus); //Transaction is saved with success on paygate if(mStatus == 0){ //Save the reference yo database mCurrentUser.setLast_transaction_reference(mTx_Reference); AppDataBaseManager.DB_USER_TABLE.updateUserLastTransaction(mCurrentUser); Log.d("PAY TRANS REF", mCurrentUser.getLast_transaction_reference()); //Update success state mTransactionOnGoing = true; //Under missed variable mCheckingTransactionComplete = false; if(mListener != null) mListener.onTransactionInitializationHas_Success(true); } } catch (JSONException e) { if(mListener != null) mListener.onErrorOccurred(); e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //Update success state if(mListener != null) mListener.onTransactionInitializationHas_Success(false); } } ); this.mVolleyRequestQueueSingleton.getRequestQueue().add(jsonObjectRequest); } public void getTransactionConfirmation(){ //We are not checking the state of a transaction //Then we can ask a new confirmation if(!mCheckingTransactionComplete) { JSONObject params = new JSONObject(); try { params.put("auth_token", PAYMENT_PAYGATE_TOGO_KEY); params.put(TX_REFERENCE_STRING, mTx_Reference); Log.i("PAYMENT REQ CHECK", params.toString()); } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( Request.Method.POST, PAYGATE_PAYMENT_CHECK_URL, params, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { //Update the payment initialization status //Initialization finished try { String _mTx_Reference = response.getString(TX_REFERENCE_STRING); String mIdentifier = response.getString(IDENTIFIER_STRING); String mPay_Reference = response.getString(PAYMENT_REFERENCE_STRING); int _mStatus = response.getInt(STATUS_STRING); String mDate_Time = response.getString(DATETIME_STRING); String mPay_Method = response.getString(PAYMENT_METHOD_STRING); //On success response is composed by ^tx_reference and @status //Call Payment listener for checking status Log.i("PAYMENT REQ CHECK", "Staus => " + _mStatus); String status_string = null; if (_mStatus == 0) { //re init the last transaction value in data base //to default mCurrentUser.setLast_transaction_reference("@none"); AppDataBaseManager.DB_USER_TABLE.updateUserLastTransaction(mCurrentUser); mTx_Reference = ""; //Success payment confirmation success //We ve finished checking transaction mCheckingTransactionComplete = true; //Update success state if (mListener != null) mListener.onTransactionCompleteHas_Success(true); status_string = "sucsess"; } else if (_mStatus == 2) { //Success payment on going //Update success state if (mListener != null) mListener.onTransactionCompleteHas_OnGoing(); status_string = "on going"; } else if (_mStatus == 4) { //Success payment confirmation expired //Update success state if (mListener != null) mListener.onTransactionCompleteHas_Expired(); status_string = "expired"; } else if (_mStatus == 6) { //Success payment confirmation cancelled //Update success state if (mListener != null) mListener.onTransactionCompleteHas_Cancelled(); status_string = "cancelled"; } Log.d("PAYMENT REQ CHECK", "Status " + _mStatus + " " + status_string); } catch (JSONException e) { e.printStackTrace(); if (mListener != null) mListener.onErrorOccurred(); //Error occurred when tracking the transaction state mCheckingTransactionComplete = false; } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //Update success state if (mListener != null) mListener.onTransactionCompleteHas_Success(false); //Error occurred when tracking the transaction state mCheckingTransactionComplete = false; } } ); this.mVolleyRequestQueueSingleton.getRequestQueue().add(jsonObjectRequest); } } public void setListener(PayGatePaymentAPIListener mListener) { this.mListener = mListener; } public void setTransactionOnGoingState(boolean mTransactionOnGoing) { this.mTransactionOnGoing = mTransactionOnGoing; } public String getmTx_Reference() { return mTx_Reference; } public boolean get_isTransactionOnGoingState(){ return this.mTransactionOnGoing; } }
package com.cnk.travelogix.custom.zif.erp.ws.opportunity; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ZifProdCatFlights complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ZifProdCatFlights"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="SectorFrom" type="{urn:sap-com:document:sap:rfc:functions}char20"/> * &lt;element name="SectorTo" type="{urn:sap-com:document:sap:rfc:functions}char20"/> * &lt;element name="DepartureDate" type="{urn:sap-com:document:sap:rfc:functions}date10"/> * &lt;element name="ReturnDate" type="{urn:sap-com:document:sap:rfc:functions}date10"/> * &lt;element name="NoOfAdults" type="{urn:sap-com:document:sap:rfc:functions}numeric2"/> * &lt;element name="NoOfChildren" type="{urn:sap-com:document:sap:rfc:functions}numeric2"/> * &lt;element name="NoOfInfants" type="{urn:sap-com:document:sap:rfc:functions}numeric2"/> * &lt;element name="PreferredAirline" type="{urn:sap-com:document:sap:rfc:functions}char10"/> * &lt;element name="Class" type="{urn:sap-com:document:sap:rfc:functions}char20"/> * &lt;element name="Meals" type="{urn:sap-com:document:sap:rfc:functions}char5"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ZifProdCatFlights", propOrder = { "sectorFrom", "sectorTo", "departureDate", "returnDate", "noOfAdults", "noOfChildren", "noOfInfants", "preferredAirline", "clazz", "meals" }) public class ZifProdCatFlights { @XmlElement(name = "SectorFrom", required = true) protected String sectorFrom; @XmlElement(name = "SectorTo", required = true) protected String sectorTo; @XmlElement(name = "DepartureDate", required = true) protected String departureDate; @XmlElement(name = "ReturnDate", required = true) protected String returnDate; @XmlElement(name = "NoOfAdults", required = true) protected String noOfAdults; @XmlElement(name = "NoOfChildren", required = true) protected String noOfChildren; @XmlElement(name = "NoOfInfants", required = true) protected String noOfInfants; @XmlElement(name = "PreferredAirline", required = true) protected String preferredAirline; @XmlElement(name = "Class", required = true) protected String clazz; @XmlElement(name = "Meals", required = true) protected String meals; /** * Gets the value of the sectorFrom property. * * @return * possible object is * {@link String } * */ public String getSectorFrom() { return sectorFrom; } /** * Sets the value of the sectorFrom property. * * @param value * allowed object is * {@link String } * */ public void setSectorFrom(String value) { this.sectorFrom = value; } /** * Gets the value of the sectorTo property. * * @return * possible object is * {@link String } * */ public String getSectorTo() { return sectorTo; } /** * Sets the value of the sectorTo property. * * @param value * allowed object is * {@link String } * */ public void setSectorTo(String value) { this.sectorTo = value; } /** * Gets the value of the departureDate property. * * @return * possible object is * {@link String } * */ public String getDepartureDate() { return departureDate; } /** * Sets the value of the departureDate property. * * @param value * allowed object is * {@link String } * */ public void setDepartureDate(String value) { this.departureDate = value; } /** * Gets the value of the returnDate property. * * @return * possible object is * {@link String } * */ public String getReturnDate() { return returnDate; } /** * Sets the value of the returnDate property. * * @param value * allowed object is * {@link String } * */ public void setReturnDate(String value) { this.returnDate = value; } /** * Gets the value of the noOfAdults property. * * @return * possible object is * {@link String } * */ public String getNoOfAdults() { return noOfAdults; } /** * Sets the value of the noOfAdults property. * * @param value * allowed object is * {@link String } * */ public void setNoOfAdults(String value) { this.noOfAdults = value; } /** * Gets the value of the noOfChildren property. * * @return * possible object is * {@link String } * */ public String getNoOfChildren() { return noOfChildren; } /** * Sets the value of the noOfChildren property. * * @param value * allowed object is * {@link String } * */ public void setNoOfChildren(String value) { this.noOfChildren = value; } /** * Gets the value of the noOfInfants property. * * @return * possible object is * {@link String } * */ public String getNoOfInfants() { return noOfInfants; } /** * Sets the value of the noOfInfants property. * * @param value * allowed object is * {@link String } * */ public void setNoOfInfants(String value) { this.noOfInfants = value; } /** * Gets the value of the preferredAirline property. * * @return * possible object is * {@link String } * */ public String getPreferredAirline() { return preferredAirline; } /** * Sets the value of the preferredAirline property. * * @param value * allowed object is * {@link String } * */ public void setPreferredAirline(String value) { this.preferredAirline = value; } /** * Gets the value of the clazz property. * * @return * possible object is * {@link String } * */ public String getClazz() { return clazz; } /** * Sets the value of the clazz property. * * @param value * allowed object is * {@link String } * */ public void setClazz(String value) { this.clazz = value; } /** * Gets the value of the meals property. * * @return * possible object is * {@link String } * */ public String getMeals() { return meals; } /** * Sets the value of the meals property. * * @param value * allowed object is * {@link String } * */ public void setMeals(String value) { this.meals = value; } }
package com.timmy.framework.imageLoaderFw.TimmyImageLoader.cache; import android.content.Context; import android.graphics.Bitmap; import com.timmy.framework.imageLoaderFw.TimmyImageLoader.request.BitmapRequest; /** * Created by admin on 2017/6/16. */ public class DoubleCache implements BitmapCache { private MemoryCache memoryCache = new MemoryCache(); private DiskCache diskCache; public DoubleCache(Context context) { diskCache = DiskCache.getInstance(context); } @Override public void put(BitmapRequest key, Bitmap bitmap) { memoryCache.put(key, bitmap); diskCache.put(key, bitmap); } /** * 先从内存缓存区 * 没有再从磁盘中取 * * @param key * @return */ @Override public Bitmap get(BitmapRequest key) { Bitmap bitmap = memoryCache.get(key); if (bitmap == null) { bitmap = diskCache.get(key); } return bitmap; } @Override public void remove(BitmapRequest key) { memoryCache.remove(key); diskCache.remove(key); } }
package Modelo; import java.awt.event.KeyEvent; import javax.swing.JTextField; public class restricciones { public void numberKeyPress(KeyEvent evt){ char car = evt.getKeyChar(); if((car<'0'||car>'9') && (car!=(char) KeyEvent.VK_BACK_SPACE)) { evt.consume(); } } public void numberDecimalKeyPress(KeyEvent evt, JTextField textField) { char car = evt.getKeyChar(); if ((car < '0' || car > '9') && textField.getText().contains(".") && (car != (char) KeyEvent.VK_BACK_SPACE)) { evt.consume(); } else if ((car < '0' || car > '9') && (car != '.') && (car != (char) KeyEvent.VK_BACK_SPACE)) { evt.consume(); } } }
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileNotFoundException; import java.util.*; import java.util.List; public class MainForm { private JPanel panel1; private JButton nowaGraButton; private JButton btn01; private JButton btn02; private JButton btn10; private JButton btn20; private JButton btn11; private JButton btn21; private JButton btn12; private JButton btn22; private JButton btn00; private JLabel player1; private JLabel player2; private JLabel labelScore1; private JLabel labelScore2; private List<JButton> board; Game game = new Game(); public MainForm() { labelScore1.setText("0"); labelScore2.setText("0"); game.neuralNetwork.readWages(); game.neuralNetwork.showWages(); game.setPlayers("komputer", "gracz"); player1.setText("komputer"); player2.setText("gracz"); nowaGraButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { startNewGame(); int index = networkMove(); int x = index / 3; int y = index % 3; if (game.canSet(x, y)) { String sign = game.set(x, y); board.get(index).setText(sign); game.convertBoard(); game.nextRound(); } } }); board = new ArrayList<>(); board.addAll(Arrays.asList(btn00, btn01, btn02, btn10, btn11, btn12, btn20, btn21, btn22)); connectButtonsToLogic(); } private int networkMove(){ double[] tabOutputNetwork; double out; int index=0; boolean end=true; tabOutputNetwork=game.neuralNetwork.doMove(game.getBoardNetwortk()); out=tabOutputNetwork[0]; while(end) { for (int i = 0; i < tabOutputNetwork.length; i++) { if (out < tabOutputNetwork[i]) { out = tabOutputNetwork[i]; index = i; } } if(game.getBoardNetwortk()[index]==0) { end=false; tabOutputNetwork[index]=1; } else { tabOutputNetwork[index]=-2; out=-2; } } return index; } private void checkGame(){ if (game.isDrawn()) { JOptionPane.showMessageDialog(null, "REMIS!", "KONIEC!", JOptionPane.WARNING_MESSAGE); //askForNextGame(); stopGame(); } else if (game.isWon()) { JOptionPane.showMessageDialog(null, "WYGRAL " + game.getCurrentPlayerName(), "KONIEC!", JOptionPane.INFORMATION_MESSAGE); game.addPoints(); updateGuiScores(); //askForNextGame(); stopGame(); } else { game.nextRound(); } } private void connectButtonsToLogic() { for(JButton btn : board){ btn.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { JButton btn = (JButton) e.getSource(); int index = board.indexOf(btn); int x = index/3; int y = index%3; if(game.canSet(x,y)) { String sign = game.set(x, y); btn.setText(sign); game.convertBoard(); checkGame(); } boolean end=false; if(game.isDrawn()||game.isWon()) end=true; if(!end) { index = networkMove(); x = index / 3; y = index % 3; if (game.canSet(x, y)) { String sign = game.set(x, y); board.get(index).setText(sign); game.convertBoard(); checkGame(); } } } }); } } /*private void askForNextGame() { int answ = JOptionPane.showConfirmDialog (null, "Jeszcze raz?", "Pytanie", JOptionPane.YES_NO_OPTION); if(answ == JOptionPane.YES_OPTION) { game.newGame(); resetGame(); } else { stopGame(); } }*/ private void updateGuiScores() { labelScore1.setText(String.valueOf(game.getScore1())); labelScore2.setText(String.valueOf(game.getScore2())); } private void resetGame() { for(JButton btn : board){ btn.setEnabled(true); btn.setText(""); } } private void stopGame() { for(JButton btn : board){ btn.setEnabled(false); } } private void startNewGame(){ for(JButton btn : board){ btn.setText(""); btn.setEnabled(true); } game.newGame(); } public static void main(String[] args) { JFrame frame = new JFrame("Tic Tac Toe"); frame.setContentPane(new MainForm().panel1); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }
package com.code; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /*** * @author 牛奶冻荔枝 */ public class Compile extends ClassLoader { private String javaFileName=""; /*** * 设置java文件 * @param javaFileName */ public void setJavaFileName(String javaFileName){ this.javaFileName=javaFileName; } /*** * 编译生成.class二进制文件 * @param javaFileName String 文件名 * @return 是否编译成功 */ private boolean compile(String javaFileName){ try { Process exec=Runtime.getRuntime().exec("javac C:/Users/牛奶冻荔枝/Desktop/untitled/" + javaFileName); exec.waitFor(); int result=exec.exitValue(); return result==0; } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } /*** * 读取.class文件 * @param classFile 二进制文件 * @return byte[] 字节数组 * @throws IOException */ private byte[] getBytes(File classFile) throws IOException { try(FileInputStream fileInputStream=new FileInputStream(classFile)){ int len =(int)classFile.length(); byte[] buf=new byte[len]; int hasRead=fileInputStream.read(buf); if (hasRead!=len){ throw new IOException("无法读取文件"); } return buf; } } /*** * * @param name * @return * @throws ClassNotFoundException */ @Override protected Class<?> findClass(String name)throws ClassNotFoundException{ String fileName=name.replace('.','/'); String classFilename="./src/"+fileName+".class"; File javaFile=new File(javaFileName); File classFile=new File(classFilename); if (javaFile.exists()&&(!classFile.exists())||javaFile.lastModified()>classFile.lastModified()) { try { if (!compile(javaFileName)||!classFile.exists()){ throw new ClassNotFoundException("ClassNotFoundExecption:"+javaFileName); } }catch (Exception e){ e.printStackTrace(); } } Class clazz=null; if (classFile.exists()){ try { byte[] buf=getBytes(classFile); //将byte[]数组转化成class类的实例 clazz=this.defineClass(name,buf,0,buf.length); } catch (IOException e) { e.printStackTrace(); } } if (clazz==null) {throw new ClassNotFoundException(name);} return clazz; } public Class<?> getClazz() throws ClassNotFoundException{ Class clazz=this.findClass("com.code.temp.Temp"); return clazz; } }
package com.atguigu.eduorder.service; import com.atguigu.eduorder.entity.TPayLog; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 支付日志表 服务类 * </p> * * @author shine * @since 2021-07-20 */ public interface TPayLogService extends IService<TPayLog> { }
package ar.com.ServiceLayer; import java.io.Serializable; import java.util.List; import java.util.Map; import ar.com.Request.data.Request; import ar.com.model.domain.Archivo; import ar.com.model.domain.Materias; import ar.com.model.domain.Persona; public interface ServiceCRUD { public List<Object> ReadAll(Request req); public Object ReadOne(Request req) throws Exception; public int Save(Request req); public void Update(Request req); public void Delete(Request req); public List<Object> ExecuteQuery(Request t,String field, Serializable id); public List<Object> GetAllByField(Request req, String field); public List<Object> ExecuteCriteria(Class clazz, Map<Object,Object> filters); public int getDiffFecha(String Fecha); public boolean exists(Request obj); public List<Materias> getMaterias(Persona persona); public List<Object> getFiles(List<Materias> materias,boolean approved); public List<Archivo> getArchivos(boolean alm, boolean prof, Materias ids); }
package com.dzz.user.service.domain.dao; import com.dzz.user.api.domain.bo.UserDetailBo; import com.dzz.user.api.domain.bo.UserListBo; import com.dzz.user.api.domain.dto.UserListParam; import com.dzz.user.service.domain.model.User; import java.util.List; import org.apache.ibatis.annotations.Param; import tk.mybatis.mapper.common.Mapper; /** * @author dzz */ public interface UserMapper extends Mapper<User> { /** * 用户列表查询 * @param listParam 查询条件 * @return 结果 */ List<UserListBo> listUser(@Param("param") UserListParam listParam); /** * 用户详情查询 * @param userName 用户名 * @return 返回结果 */ UserDetailBo detailUser(@Param("userName") String userName); }
package net.buildwarrior.playercapture.tasks; import lombok.Getter; import net.buildwarrior.playercapture.PlayerCapture; import net.buildwarrior.playercapture.utils.Actions; import net.buildwarrior.playercapture.utils.NPCPose; import net.buildwarrior.playercapture.versions.NPC; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.scheduler.BukkitRunnable; public class PlayTask extends BukkitRunnable { @Getter private NPC npc; @Getter private NPC clone; private int frame; public PlayTask(NPC npc, NPC clone) { this.npc = npc; this.clone = clone; clone.spawn(); } public PlayTask(NPC npc, NPC clone, int frame) { this.npc = npc; this.clone = clone; this.frame = frame; clone.spawn(); } @Override public void run() { if(!clone.getDisplayName().equals(npc.getDisplayName()) || !clone.getSkinCatch().equals(npc.getSkinCatch())) { cancel(); clone.remove(); PlayerCapture.getInstance().getRunning().remove(npc.getName()); PlayTask playTask = new PlayTask(npc, npc.clone(frame), frame); playTask.runTaskTimer(PlayerCapture.getInstance(), 0, 2); PlayerCapture.getInstance().getRunning().put(npc.getName(), playTask); return; } Location tp = npc.getFrames().get(frame).getLocation(); if(npc.getFrames().get(frame).isSneaking()) { clone.setEntityPos(NPCPose.SNEAKING); } else if(npc.getFrames().get(frame).isSwimming()) { clone.setEntityPos(NPCPose.SWIMMING); } else if(npc.getFrames().get(frame).isGliding()) { clone.setEntityPos(NPCPose.FALL_FLYING); } else if(npc.getFrames().get(frame).isSleeping()) { clone.setEntityPos(NPCPose.SLEEPING); clone.setBed(npc.getFrames().get(frame).getLocation().getBlockX(), npc.getFrames().get(frame).getLocation().getBlockY(), npc.getFrames().get(frame).getLocation().getBlockZ()); tp = new Location(tp.getWorld(), tp.getX() + 0.5f, tp.getY() + 0.6f, tp.getZ() + 0.5f, tp.getYaw(), tp.getPitch()); } else { clone.setEntityPos(NPCPose.STANDING); } clone.teleport(tp); if(npc.getFrames().get(frame).isMainHandHit()) { clone.playAnimation(Actions.MAIN_HAND); } clone.setEquipment(npc.getFrames().get(frame).getHelmet(), npc.getFrames().get(frame).getChestplate(), npc.getFrames().get(frame).getLeggings(), npc.getFrames().get(frame).getBoots(), npc.getFrames().get(frame).getMainHand(), npc.getFrames().get(frame).getOffHand()); if(npc.getFrames().get(frame).getChat() != null) { //TODO over head chat String message = npc.getFrames().get(frame).getChat().split("\\(")[1]; Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', message.substring(0, message.length() -1))); } frame++; if(npc.getFrames().size() == frame) { if(npc.isLoop()) { frame = 0; return; } cancel(); clone.remove(); PlayerCapture.getInstance().getRunning().remove(npc.getName()); } } }
/* * 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 data.validation; import java.awt.event.*; import javax.swing.JOptionPane; /** * * @author mattm */ public class GUIListener implements ActionListener{ public void actionPerformed(ActionEvent e){ Object command = e.getSource(); if (command.equals("txtFirstName")) { handleText(e); } else if (command.equals("bar")) { //handleBar(e); } } private void handleText(ActionEvent e) { JOptionPane.showMessageDialog(null, "Unable to Add New Customer", "Result", JOptionPane.OK_OPTION); } //private void handleBar(ActionEvent e) {...} }
package SUT.SE61.Team07.Entity; import lombok.*; import javax.validation.constraints.NotNull; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Entity; import java.util.Date; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.JoinColumn; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.FetchType; import javax.validation.constraints.*; @Entity @Data public class Drugdata { @Id @SequenceGenerator(name = "drugdata_seq", sequenceName = "drugdata_seq") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "drugdata_seq") @NotNull private Long drugdataId; @NotNull(message="detail must not be null to be valid") @Pattern(regexp = "[A-Za-z0-9 .]{3,200}") @Column(unique = true) @Size(min = 3, max = 200) private String detail; //สรรพคุณ @NotNull @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "staffId") private Staff staff; @NotNull @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "categoryId") private Category category; @NotNull @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "medicineId") private Medicine medicine; @NotNull @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "drugId") private Drug drug; public Drugdata(){} public Drugdata (String detail,Drug drug,Staff staff,Category category, Medicine medicine) { this.detail = detail; this.drug = drug; this.staff = staff; this.category = category; this.medicine = medicine; } }
package com.dlc.morepet.utils; import android.os.Environment; import android.text.TextUtils; import android.text.format.DateFormat; import android.util.Log; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; /** * Created by heardown on 2016/10/2. */ public class LogUtils { /** * isWrite:用于开关是否吧日志写入txt文件中</p> */ private static final boolean isWrite = false; /** * isDebug :是用来控制,是否打印日志 */ private static final boolean isDeBug = false; /** * 存放日志文件的所在路径 */ private static final String DIRPATH = "/AiYanJia"; /** * 存放日志的文本名 */ private static final String LOGNAME = "log.txt"; /** * 设置时间的格式 */ private static final String INFORMAT = "yyyy-MM-dd HH:mm:ss"; /** * VERBOSE日志形式的标识符 */ public static final int VERBOSE = 5; /** * DEBUG日志形式的标识符 */ public static final int DEBUG = 4; /** * INFO日志形式的标识符 */ public static final int INFO = 3; /** * WARN日志形式的标识符 */ public static final int WARN = 2; /** * ERROR日志形式的标识符 */ public static final int ERROR = 1; /** * 把异常用来输出日志的综合方法 * * @param @param tag 日志标识 * @param @param throwable 抛出的异常 * @param @param type 日志类型 * @return void 返回类型 * @throws */ public static void log(String tag, Throwable throwable, int type) { log(tag, exToString(throwable), type); } /** * 用来输出日志的综合方法(文本内容) * * @param @param tag 日志标识 * @param @param msg 要输出的内容 * @param @param type 日志类型 * @return void 返回类型 * @throws */ public static void log(String tag, String msg, int type) { switch (type) { case VERBOSE: v(tag, msg);// verbose等级 break; case DEBUG: d(tag, msg);// debug等级 break; case INFO: i(tag, msg);// info等级 break; case WARN: w(tag, msg);// warn等级 break; case ERROR: e(tag, msg);// error等级 break; default: break; } } /** * verbose等级的日志输出 * * @param tag 日志标识 * @param msg 要输出的内容 * @return void 返回类型 * @throws */ public static void v(String tag, String msg) { // 是否开启日志输出 if (isDeBug) { Log.v(tag, msg); } // 是否将日志写入文件 if (isWrite) { write(tag, msg); } } /** * debug等级的日志输出 * * @param tag 标识 * @param msg 内容 * @return void 返回类型 * @throws */ public static void d(String tag, String msg) { if (isDeBug) { Log.d(tag, msg); } if (isWrite) { write(tag, msg); } } public static void info(String msg) { if (isDeBug) { if (TextUtils.isEmpty(msg)) { Log.i("QianYan", " --> 当前打印值为 NULL "); } else { Log.i("QianYan", msg); } } if (true) { write("QianYan", msg); } } /** * info等级的日志输出 * * @param tag 标识 * @param msg 内容 * @return void 返回类型 * @throws */ public static void i(String tag, String msg) { if (isDeBug) { Log.i(tag, msg); } if (isWrite) { write(tag, msg); } } /** * warn等级的日志输出 * * @param tag 标识 * @param msg 内容 * @return void 返回类型 * @throws */ public static void w(String tag, String msg) { if (isDeBug) { Log.w(tag, msg); } if (isWrite) { write(tag, msg); } } /** * error等级的日志输出 * * @param tag 标识 * @param msg 内容 * @return void 返回类型 */ public static void e(String tag, String msg) { if (isDeBug) { Log.w(tag, msg); } if (isWrite) { write(tag, msg); } } /** * 用于把日志内容写入制定的文件 * * @param @param tag 标识 * @param @param msg 要输出的内容 * @return void 返回类型 * @throws */ public static void write(String tag, String msg) { String path = createMkdirsAndFiles(DIRPATH, LOGNAME); if (TextUtils.isEmpty(path)) { return; } String log = DateFormat.format(INFORMAT, System.currentTimeMillis()) + " " + tag + " ========>> " + msg + "\n=================================分割线================================="; write2File(path, log, true); } /** * 用于把日志内容写入制定的文件 * * @param ex 异常 */ public static void write(Throwable ex) { write("", exToString(ex)); } /** * 把异常信息转化为字符串 * * @param ex 异常信息 * @return 异常信息字符串 */ public static String exToString(Throwable ex) { Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); ex.printStackTrace(printWriter); printWriter.close(); String result = writer.toString(); return result; } /** * 判断sdcrad是否已经安装 * * @return boolean true安装 false 未安装 */ public static boolean isSDCardMounted() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } /** * 得到sdcard的路径 * * @return */ public static String getSDCardRoot() { System.out.println(isSDCardMounted() + Environment.getExternalStorageState()); if (isSDCardMounted()) { return Environment.getExternalStorageDirectory().getAbsolutePath(); } return ""; } /** * 创建文件的路径及文件 * * @param path 路径,方法中以默认包含了sdcard的路径,path格式是"/path...." * @param filename 文件的名称 * @return 返回文件的路径,创建失败的话返回为空 */ public static String createMkdirsAndFiles(String path, String filename) { if (TextUtils.isEmpty(path)) { throw new RuntimeException("路径为空"); } path = getSDCardRoot() + path; File file = new File(path); if (!file.exists()) { try { file.mkdirs(); } catch (Exception e) { throw new RuntimeException("创建文件夹不成功"); } } File f = new File(file, filename); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { throw new RuntimeException("创建文件不成功"); } } return f.getAbsolutePath(); } /** * 把内容写入文件 * * @param path 文件路径 * @param text 内容 */ public static void write2File(String path, String text, boolean append) { BufferedWriter bw = null; try { //1.创建流对象 bw = new BufferedWriter(new FileWriter(path, append)); //2.写入文件 bw.write(text); //换行刷新 bw.newLine(); bw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { //4.关闭流资源 if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 删除文件 * * @param path * @return */ public static boolean deleteFile(String path) { if (TextUtils.isEmpty(path)) { throw new RuntimeException("路径为空"); } File file = new File(path); if (file.exists()) { try { file.delete(); return true; } catch (Exception e) { e.printStackTrace(); } } return false; } }
package org.quarkchain.web3j.protocol.core.request; import org.quarkchain.web3j.utils.Numeric; import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_NULL) public class TransactionReq { private String nonce; private String from; private String to; private String gas; private String gasPrice; private String value; private String data; private String networkId; private String fromFullShardKey; private String toFullShardKey; private String v; private String r; private String s; private String gasTokenId; private String transferTokenId; public TransactionReq() { super(); } public TransactionReq(String from, String to, String gas, String gasPrice, String value, String data, String transferTokenId, String gasTokenId) { super(); this.from = from; this.to = to; this.gas = gas; this.gasPrice = gasPrice; this.value = value; this.gasTokenId = gasTokenId; this.transferTokenId = transferTokenId; if (data != null) { this.data = Numeric.prependHexPrefix(data); } } public TransactionReq(String fromAddress, String toAddress, String data, String transferTokenId, String gasTokenId) { super(); this.from = fromAddress; this.to = toAddress; this.gasTokenId = gasTokenId; this.transferTokenId = transferTokenId; if (data != null) { this.data = Numeric.prependHexPrefix(data); } } public String getNonce() { return nonce; } public void setNonce(String nonce) { this.nonce = nonce; } public String getV() { return v; } public void setV(String v) { this.v = v; } public String getR() { return r; } public void setR(String r) { this.r = r; } public String getS() { return s; } public void setS(String s) { this.s = s; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getGas() { return gas; } public void setGas(String gas) { this.gas = gas; } public String getGasPrice() { return gasPrice; } public void setGasPrice(String gasPrice) { this.gasPrice = gasPrice; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getGasTokenId() { return gasTokenId; } public void setGasTokenId(String gasTokenId) { this.gasTokenId = gasTokenId; } public String getTransferTokenId() { return transferTokenId; } public void setTransferTokenId(String transferTokenId) { this.transferTokenId = transferTokenId; } public String getToFullShardKey() { return toFullShardKey; } public void setToFullShardKey(String toFullShardKey) { this.toFullShardKey = toFullShardKey; } public String getFromFullShardKey() { return fromFullShardKey; } public void setFromFullShardKey(String fromFullShardKey) { this.fromFullShardKey = fromFullShardKey; } public String getNetworkId() { return networkId; } public void setNetworkId(String networkId) { this.networkId = networkId; } @Override public String toString() { return "TransactionReq [nonce=" + nonce + ", from=" + from + ", to=" + to + ", gas=" + gas + ", gasPrice=" + gasPrice + ", value=" + value + ", data=" + data + ", networkId=" + networkId + ", fromFullShardKey=" + fromFullShardKey + ", toFullShardKey=" + toFullShardKey + ", v=" + v + ", r=" + r + ", s=" + s + ", gasTokenId=" + gasTokenId + ", transferTokenId=" + transferTokenId + "]"; } }
package com.cjw.server.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.cjw.server.mapper.JoblevelMapper; import com.cjw.server.pojo.Joblevel; import com.cjw.server.service.IJoblevelService; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author cjw * @since 2021-07-12 */ @Service public class JoblevelServiceImpl extends ServiceImpl<JoblevelMapper, Joblevel> implements IJoblevelService { }
package by.epam.multifile.service; import org.apache.log4j.Logger; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Contains methods to work with multifile. */ public class FileService { private static String EMPTY_STRING=""; private static final Logger LOGGER = Logger.getLogger( FileService.class); public FileService(){} public static List<String> readFileToList(String fileName) throws FileNotFoundException { Scanner sc = new Scanner(new File(fileName)); List<String> lines = new ArrayList<>(); while (sc.hasNextLine()) { lines.add(sc.nextLine()); } return lines; } public static void rewriteFile(String filePath, double newString){ PrintWriter writer = null; try { writer = new PrintWriter(filePath); writer.print(EMPTY_STRING); writer.print(newString); LOGGER.info("File "+filePath+" rewrote"); } catch (FileNotFoundException e) { LOGGER.error(e); } finally { writer.close(); } } }
package at.wortha.dezsys09.db; import org.springframework.data.repository.CrudRepository; /** * CRUD Operations for User * * @author Simon Wortha 5BHIT * @version 20160311.1 */ public interface UserRepository extends CrudRepository<User, String> { }
package net.thumbtack.asurovenko.trainee.figures; import net.thumbtack.asurovenko.trainee.exceptions.ColorException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class RectangleTest { @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void testRectangle() { Rectangle rectangle = new Rectangle(10.11, 12.13, 14.15, 16.17); assertEquals(10.11, rectangle.getFirst().getX(), 0.000001); assertEquals(12.13, rectangle.getFirst().getY(), 0.000001); assertEquals(14.15, rectangle.getSecond().getX(), 0.000001); assertEquals(16.17, rectangle.getSecond().getY(), 0.000001); rectangle = new Rectangle(); assertEquals(0, rectangle.getFirst().getX(), 0.000001); assertEquals(0, rectangle.getFirst().getY(), 0.000001); assertEquals(1, rectangle.getSecond().getX(), 0.000001); assertEquals(1, rectangle.getSecond().getY(), 0.000001); } @Test public void testPrint() { Rectangle rectangle = new Rectangle(1, 2, 3, 4); assertEquals("1.0:2.0\n3.0:2.0\n3.0:4.0\n1.0:4.0", rectangle.print()); } @Test public void testMove() { Rectangle rectangle = new Rectangle(10.11, 12.13, 14.15, 16.17); rectangle.move(1, 5); assertEquals(11.11, rectangle.getFirst().getX(), 0.000001); assertEquals(17.13, rectangle.getFirst().getY(), 0.000001); assertEquals(15.15, rectangle.getSecond().getX(), 0.000001); assertEquals(21.17, rectangle.getSecond().getY(), 0.000001); } @Test public void testReduce() { Rectangle rectangle = new Rectangle(5, 10, 30, 40); rectangle.reduce(2, 3); assertEquals(5, rectangle.getFirst().getX(), 0.000001); assertEquals(10, rectangle.getFirst().getY(), 0.000001); assertEquals(17.5, rectangle.getSecond().getX(), 0.000001); assertEquals(20, rectangle.getSecond().getY(), 0.000001); } @Test public void testArea() { Rectangle rectangle = new Rectangle(10, 10, 20, 100); assertEquals(900, rectangle.area(), 0.000001); } @Test public void testPointContained() { Rectangle rectangle = new Rectangle(10, 10, 20, 100); assertTrue(rectangle.pointContained(15, 45)); } @Test public void testPointNotContained() { Rectangle rectangle = new Rectangle(10, 10, 20, 100); assertFalse(rectangle.pointContained(150, 450)); } @Test public void testCross() { Rectangle rectangle = new Rectangle(10, 10, 20, 100); assertTrue(rectangle.cross(new Rectangle(5, 50, 50, 70))); } @Test public void testNotCross() { Rectangle rectangle = new Rectangle(10, 10, 20, 100); assertFalse(rectangle.cross(new Rectangle(30, 0, 50, 10))); } @Test public void testRectangleContained() { Rectangle rectangle = new Rectangle(10, 10, 100, 100); assertTrue(rectangle.rectangleContained(new Rectangle(20, 25, 50, 70))); } @Test public void testRectangleNotContained() { Rectangle rectangle = new Rectangle(10, 10, 100, 100); assertFalse(rectangle.rectangleContained(new Rectangle(30, 0, 50, 10))); } @Test public void testLarge() { Rectangle rectangle = new Rectangle(1, 1, 2, 3); rectangle.large(3); assertTrue(rectangle.equals(new Rectangle(1, 1, 4, 7))); } @Test public void testColor() throws ColorException { Rectangle rectangle = new Rectangle(1, 1, 20, 15, "BLACK"); assertEquals("BLACK", rectangle.getColor().name()); } @Test(expected = ColorException.class) public void testWrongColor() throws ColorException { new Rectangle(1, 1, 20, 15, "BLK"); } @Test public void testWriteAndRead() throws IOException, ClassNotFoundException { Rectangle rectangle = new Rectangle(0.001, -8.201, 63.258, 101.1); File file = folder.newFile(); rectangle.writeToFile(file.getAbsolutePath()); Rectangle rectangle2 = Rectangle.readFromFile(file.getAbsolutePath()); assertEquals(0.001, rectangle2.getFirst().getX(), 0.000001); assertEquals(-8.201, rectangle2.getFirst().getY(), 0.000001); assertEquals(63.258, rectangle2.getSecond().getX(), 0.000001); assertEquals(101.1, rectangle2.getSecond().getY(), 0.000001); } @Test public void testWriteAndReadArray() throws IOException, ClassNotFoundException { Rectangle[] rectangles = new Rectangle[5]; for (int i = 0; i < 5; i++) { rectangles[i] = new Rectangle(i + 23.01, i * 0.158 - 6.225, i * 2 + 105.210, i + 1.0005); } File file = folder.newFile(); Rectangle.writeArrayToFile(file.getAbsolutePath(), rectangles); Rectangle[] rectangles2 = Rectangle.readArrayFromFile(file.getAbsolutePath(), 5); for (int i = 0; i < 5; i++) { assertTrue(rectangles[i].equals(rectangles2[i])); } } }
package org.mge.ds.graph; import java.util.Iterator; import java.util.LinkedList; import java.util.Stack; //Source : https://www.geeksforgeeks.org/strongly-connected-components/ public class StronglyConnectedComponents { private LinkedList<Integer>[] adjList; private int V; public StronglyConnectedComponents(int V) { this.V = V; adjList = new LinkedList[V]; for(int i = 0; i < V; i++) { adjList[i] = new LinkedList<>(); } } public static void main(String[] args) { StronglyConnectedComponents gr = new StronglyConnectedComponents(5); gr.addEdge(0, 2); gr.addEdge(0, 3); gr.addEdge(1, 0); gr.addEdge(2, 1); gr.addEdge(3, 4); gr.printSCCs(); } void addEdge(int src, int dest) { adjList[src].add(dest); } public void printSCCs() { Stack<Integer> s = new Stack<>(); boolean[] visited = new boolean[V]; for(int i = 0; i < V; i++) { if(!visited[i]) fillOrder(i, visited, s); } StronglyConnectedComponents gr = getTranspose(); for(int i = 0; i < V; i++) { visited[i] = false; } while(!s.isEmpty()) { int n = s.pop(); if(!visited[n]) { gr.printDFS(n, visited); System.out.println(); } } } public void fillOrder(int v, boolean visited[], Stack<Integer> s){ visited[v] = true; Iterator<Integer> i = adjList[v].iterator(); while(i.hasNext()) { int n = i.next(); if(!visited[n]) { fillOrder(n, visited, s); } } s.add(v); } public StronglyConnectedComponents getTranspose(){ StronglyConnectedComponents gr = new StronglyConnectedComponents(V); for(int i = 0; i < V; i++) { Iterator<Integer> itr = adjList[i].iterator(); while(itr.hasNext()) { gr.adjList[itr.next()].add(i); } } return gr; } void printDFS(int v, boolean[] visited) { visited[v] = true; System.out.print(v + " "); Iterator<Integer> i = adjList[v].iterator(); while(i.hasNext()) { int n = i.next(); if(!visited[n]) { visited[n] = true; printDFS(n, visited); } } } }
//package jpa.project.advide.exception; // //public class CMessageNotFoundException extends RuntimeException { // public CMessageNotFoundException(String msg, Throwable t) { // super(msg, t); // } // // public CMessageNotFoundException(String msg) { // super(msg); // } // // public CMessageNotFoundException() { // super(); // } //}
package com.goldgov.portal.studyreviews.service; import java.util.List; import java.util.Map; public interface IStudyReviewsService { public void saveReviews(StudyReviews studyReviews); public List<StudyReviews> findStudyReviewsByPage(StudyReviewsQuery query); public StudyReviews findStudyReviews(String id); public void deleteReviews(String[] ids); public List<StudyReviews> findReviewsAwardList(StudyReviewsQuery query); public List<StudyReviews> findReviewsAwardListByPage(StudyReviewsQuery query); public void saveReviewsForWs(StudyReviews studyReviews); public void deleteReviewsForWs(String ids); public List<Map<String, Object>> getOrganizationNameList(String partyOrganizationID, String[] userIds); Integer getPartyMemberJoinCount(String userId, String ratedId); }
package exercise_chapter11; import java.lang.annotation.Retention; public class exerciseOfDynamicBinding { public static void main(String[] args) { new Person2().printPerson(); new Student2().printPerson(); } } class Student2 extends Person2 { /*@Override public String getInfo() { return "Student"; } @Override public void printPerson() { super.printPerson(); System.out.println(super.getInfo()); System.out.println("2333"); }*/ private String getInfo() { return "Student"; } } class Person2 { /*public String getInfo() { return "Person"; } public void printPerson() { System.out.println(getInfo()); }*/ private String getInfo() { return "Person"; } public void printPerson() { System.out.println(getInfo()); } }
public class FizzBuzz{ public static void main(String[] args){ for(int i=1;i<31;i++){ //for i in range 1 to 30 if(i%15==0){ //if i is divisible by 15 System.out.println("FizzBuzz"); } else if(i%3==0){ //if i is divisible by 3 System.out.println("Fizz"); } else if(i%5==0){ //if i is divisible by 5 System.out.println("Buzz"); } } } }
package com.plainid.assignment.converter.mapper; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by Omer Dekel on 04/07/2020. * Helper class to map SQL result to String name. */ public class NameRowMapper implements RowMapper<String> { @Override public String mapRow(ResultSet resultSet, int i) throws SQLException { return resultSet.getString("NAME"); } }
package com.linkedin.algos; public class ReverseLinkedList<T> { public void reverse(Node<T> node){ Node<T> main = node; Node<T> next = node.next; Node<T> next2; main.next = null; while(next!=null){ next2 = next.next; next.setNext(main); main = next; next = next2; } } public static void main(String[] args) { Node<Integer> first = new Node<Integer>(1); Node<Integer> second = new Node<Integer>(2); Node<Integer> third = new Node<Integer>(3); Node<Integer> fourth = new Node<Integer>(4); first.setNext(second); second.setNext(third); third.setNext(fourth); Node.printLL(first); Node.printLL(fourth); new ReverseLinkedList<Integer>().reverse(first); Node.printLL(fourth); } }
package animatronics.client.gui.element; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; public abstract class GuiElement { int zLevel = 0; public abstract ResourceLocation getElementTexture(); public abstract void draw(int posX, int posY); public abstract int getX(); public abstract int getY(); public void drawTexturedModalRect(int x, int y, int u, int v, int width, int height) { float f = 0.00390625F; float f1 = 0.00390625F; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(x + 0), (double)(y + height), (double)this.zLevel, (double)((float)(u + 0) * f), (double)((float)(v + height) * f1)); tessellator.addVertexWithUV((double)(x + width), (double)(y + height), (double)this.zLevel, (double)((float)(u + width) * f), (double)((float)(v + height) * f1)); tessellator.addVertexWithUV((double)(x + width), (double)(y + 0), (double)this.zLevel, (double)((float)(u + width) * f), (double)((float)(v + 0) * f1)); tessellator.addVertexWithUV((double)(x + 0), (double)(y + 0), (double)this.zLevel, (double)((float)(u + 0) * f), (double)((float)(v + 0) * f1)); tessellator.draw(); } public void drawTexturedModelRectFromIcon(int x, int y, IIcon icon, int width, int height) { Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(x + 0), (double)(y + height), (double)this.zLevel, (double)icon.getMinU(), (double)icon.getMaxV()); tessellator.addVertexWithUV((double)(x + width), (double)(y + height), (double)this.zLevel, (double)icon.getMaxU(), (double)icon.getMaxV()); tessellator.addVertexWithUV((double)(x + width), (double)(y + 0), (double)this.zLevel, (double)icon.getMaxU(), (double)icon.getMinV()); tessellator.addVertexWithUV((double)(x + 0), (double)(y + 0), (double)this.zLevel, (double)icon.getMinU(), (double)icon.getMinV()); tessellator.draw(); } public static void func_146110_a(int p_146110_0_, int p_146110_1_, float p_146110_2_, float p_146110_3_, int p_146110_4_, int p_146110_5_, float p_146110_6_, float p_146110_7_) { float f4 = 1.0F / p_146110_6_; float f5 = 1.0F / p_146110_7_; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)p_146110_0_, (double)(p_146110_1_ + p_146110_5_), 0.0D, (double)(p_146110_2_ * f4), (double)((p_146110_3_ + (float)p_146110_5_) * f5)); tessellator.addVertexWithUV((double)(p_146110_0_ + p_146110_4_), (double)(p_146110_1_ + p_146110_5_), 0.0D, (double)((p_146110_2_ + (float)p_146110_4_) * f4), (double)((p_146110_3_ + (float)p_146110_5_) * f5)); tessellator.addVertexWithUV((double)(p_146110_0_ + p_146110_4_), (double)p_146110_1_, 0.0D, (double)((p_146110_2_ + (float)p_146110_4_) * f4), (double)(p_146110_3_ * f5)); tessellator.addVertexWithUV((double)p_146110_0_, (double)p_146110_1_, 0.0D, (double)(p_146110_2_ * f4), (double)(p_146110_3_ * f5)); tessellator.draw(); } public static void func_152125_a(int p_152125_0_, int p_152125_1_, float p_152125_2_, float p_152125_3_, int p_152125_4_, int p_152125_5_, int p_152125_6_, int p_152125_7_, float p_152125_8_, float p_152125_9_) { float f4 = 1.0F / p_152125_8_; float f5 = 1.0F / p_152125_9_; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)p_152125_0_, (double)(p_152125_1_ + p_152125_7_), 0.0D, (double)(p_152125_2_ * f4), (double)((p_152125_3_ + (float)p_152125_5_) * f5)); tessellator.addVertexWithUV((double)(p_152125_0_ + p_152125_6_), (double)(p_152125_1_ + p_152125_7_), 0.0D, (double)((p_152125_2_ + (float)p_152125_4_) * f4), (double)((p_152125_3_ + (float)p_152125_5_) * f5)); tessellator.addVertexWithUV((double)(p_152125_0_ + p_152125_6_), (double)p_152125_1_, 0.0D, (double)((p_152125_2_ + (float)p_152125_4_) * f4), (double)(p_152125_3_ * f5)); tessellator.addVertexWithUV((double)p_152125_0_, (double)p_152125_1_, 0.0D, (double)(p_152125_2_ * f4), (double)(p_152125_3_ * f5)); tessellator.draw(); } }
/* * Sonar Clirr Plugin * Copyright (C) 2009 SonarSource * dev@sonar.codehaus.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ /* * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.clirr; import org.junit.Test; import org.sonar.java.api.JavaClass; import static org.junit.Assert.assertEquals; public class ClirrViolationTest { @Test public void getAffectedClass() { ClirrViolation violation = new ClirrViolation("", "", "", this.getClass().getCanonicalName()); assertEquals(JavaClass.create("org.sonar.plugins.clirr.ClirrViolationTest"), violation.getJavaClass()); } @Test public void shouldGetRuleKey() { ClirrViolation error = new ClirrViolation("ERROR", "", "", ""); assertEquals("clirr-api-break", error.getRuleKey()); ClirrViolation warning = new ClirrViolation("WARNING", "", "", ""); assertEquals("clirr-api-behavior-change", warning.getRuleKey()); ClirrViolation info = new ClirrViolation("INFO", "", "", ""); assertEquals("clirr-new-api", info.getRuleKey()); } }
package com.basic.comp.impl.action; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.KeyStroke; import com.basic.icon.IconBase; import com.basic.lang.LApp; public class ExitAction extends AbstractAction { public ExitAction() { super(LApp.EXIT, IconBase.EXIT); putValue(SHORT_DESCRIPTION, LApp.EXIT_DESC); putValue(MNEMONIC_KEY, (int)LApp.EXIT_MNEMONIC); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl E")); } @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }
package com.bih.nic.saathi; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bih.nic.saathi.DataBaseHelper.DataBaseHelper; import com.bih.nic.saathi.Model.UserDetails; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class VerifyAadhaarGlobally extends Activity { TextView edt_Bene_No,edt_Bene_name,edt_Bene_ac_no,edt_Bene_uid_status,edt_Bene_nameInPass; EditText edt_Bene_aadhaarNo; Button btn_verify; DataBaseHelper dataBaseHelper; EditText filterText; ImageView img_filter,img_search; BenfiList benfiList; TextView txt_dist,txt_block,txt_pnchayat; UserDetails userDetails; String Userid = ""; String blockcode=""; String distcode=""; String panchyatcode=""; String blockName=""; String DistName=""; String PanchayatName=""; String str_aadhaarno,str_aadhaar_name; LinearLayout lin_data; ProgressDialog pd1; String BenId=""; ImageView right; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_verify_aadhaar); Utiilties.setActionBarBackground(VerifyAadhaarGlobally.this); Utiilties.setStatusBarColor(VerifyAadhaarGlobally.this); ActionBar actionBar = getActionBar(); actionBar.setTitle("Verify Aadhaar"); dataBaseHelper=new DataBaseHelper(getApplicationContext()); filterText=(EditText)findViewById(R.id.flterText) ; img_filter=(ImageView)findViewById(R.id.img_filter); img_search=(ImageView)findViewById(R.id.img_search); edt_Bene_No=(TextView) findViewById(R.id.edt_Bene_No); edt_Bene_name=(TextView) findViewById(R.id.edt_Bene_name); edt_Bene_ac_no=(TextView) findViewById(R.id.edt_Bene_ac_no); edt_Bene_uid_status=(TextView) findViewById(R.id.edt_Bene_uid_status); edt_Bene_aadhaarNo=(EditText) findViewById(R.id.edt_Bene_aadhaarNo); btn_verify=(Button)findViewById(R.id.btn_verify); edt_Bene_nameInPass=(TextView) findViewById(R.id.edt_Bene_nameInPass); lin_data=(LinearLayout)findViewById(R.id.lin_data); right=(ImageView) findViewById(R.id.right); txt_dist=(TextView)findViewById(R.id.txt_dist); txt_block=(TextView)findViewById(R.id.txt_block); txt_pnchayat=(TextView)findViewById(R.id.txt_pnchayat); Userid = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("UserId", ""); try { blockcode = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("Block", ""); distcode = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("District", ""); panchyatcode = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("PanchayatCode", ""); DistName = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("DistrictName", ""); blockName = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("BlockName", ""); PanchayatName = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("PanchayatName", ""); }catch (NullPointerException e){ e.printStackTrace(); } //Log.d("uiguigcug",""+Userid); txt_dist.setText(DistName); txt_block.setText(blockName); txt_pnchayat.setText(PanchayatName); img_search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String benId=filterText.getText().toString(); new SearchGlobal(benId).execute(); } }); btn_verify.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { str_aadhaar_name=benfiList.getBeneficiery_name(); str_aadhaarno=edt_Bene_aadhaarNo.getText().toString(); if(filterText.getText().toString().equals("")) { Toast.makeText(getApplicationContext(),"Enter data to filter",Toast.LENGTH_LONG).show(); }else { new USerStatus().execute(); } } }); } private void setData(BenfiList data){ benfiList= data; if(benfiList.getBeneficiery_name()!=null) { BenId=benfiList.getBeneficiary_id(); edt_Bene_No.setText(benfiList.getBeneficiary_id()); edt_Bene_name.setText(benfiList.getBeneficiery_name()); edt_Bene_ac_no.setText(benfiList.getAccountNo()); edt_Bene_uid_status.setText(benfiList.getUidStatus()); edt_Bene_aadhaarNo.setText(benfiList.getAadharNumber()); edt_Bene_nameInPass.setText(benfiList.getNameInPass()); btn_verify.setVisibility(View.VISIBLE); lin_data.setVisibility(View.VISIBLE); if(benfiList.getUidStatus().equalsIgnoreCase("Y")){ right.setVisibility(View.VISIBLE); }else { right.setVisibility(View.GONE); } }else { btn_verify.setVisibility(View.GONE); lin_data.setVisibility(View.GONE); } } public String getDataTimeStamp() { String pidTimeStamp=null; try { DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long now = System.currentTimeMillis(); Date date = new Date(now); Calendar localCalendar = GregorianCalendar .getInstance(); localCalendar.setTime(date); pidTimeStamp = String.valueOf(localCalendar .get(Calendar.YEAR)) + "-" + (String.valueOf(localCalendar.get(Calendar.MONTH) + 1).length() < 2 ? "0" + String.valueOf(localCalendar .get(Calendar.MONTH) + 1) : String.valueOf(localCalendar .get(Calendar.MONTH) + 1)) + "-" + (String.valueOf(localCalendar.get(Calendar.DATE)).length() < 2 ? "0" + String.valueOf(localCalendar.get(Calendar.DATE)) : String.valueOf(localCalendar.get(Calendar.DATE))) + "T" + (String.valueOf(localCalendar.get(Calendar.HOUR_OF_DAY)).length() < 2 ? "0" + String.valueOf(localCalendar.get(Calendar.HOUR_OF_DAY)) : String.valueOf(localCalendar.get(Calendar.HOUR_OF_DAY))) + ":" + (String.valueOf(localCalendar.get(Calendar.MINUTE)).length() < 2 ? "0" + String.valueOf(localCalendar.get(Calendar.MINUTE)) : String.valueOf(localCalendar.get(Calendar.MINUTE))) + ":" + (String.valueOf(localCalendar.get(Calendar.SECOND)).length() < 2 ? "0" + String.valueOf(localCalendar.get(Calendar.SECOND)) : String.valueOf(localCalendar.get(Calendar.SECOND))); pidTimeStamp= pidTimeStamp.replace("T", "").replace("-", "").replace(":", ""); } catch (Exception e) { e.printStackTrace(); } return pidTimeStamp; } class USerStatus extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); pd1 = new ProgressDialog(VerifyAadhaarGlobally.this); pd1.setTitle("please wait ...."); pd1.setCancelable(false); pd1.show(); } @Override protected String doInBackground(String... strings) { String s = ""; String myuser_id = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("myuserid", ""); try { HttpClient httpClient = new DefaultHttpClient(); //HttpPost httpPost = new HttpPost("http://erachat.condoassist2u.com/api/setOnlineOffline"); HttpPost httpPost = new HttpPost("http://baaf.bihar.gov.in:8080/authekycp25/api/authenticate"); httpPost.setHeader("Content-type", "application/json"); JSONObject jsonObject = new JSONObject(); //jsonObject.accumulate("uid", "675075550397"); jsonObject.accumulate("uid", str_aadhaarno); jsonObject.accumulate("uidType","A"); jsonObject.accumulate("consent","Y"); jsonObject.accumulate("subAuaCode","PSWDB22456"); // SimpleDateFormat postFormater = new SimpleDateFormat("yyyyMMddTHHmmss"); // String newDateStr = postFormater.format(Calendar.getInstance().getTime()); //jsonObject.accumulate("txn", "eLAuth" + "20181117T104125"); jsonObject.accumulate("txn", "eLAuth" + getDataTimeStamp()); jsonObject.accumulate("isPI","y"); jsonObject.accumulate("isBio","n"); jsonObject.accumulate("isOTP","n"); jsonObject.accumulate("bioType",""); // jsonObject.accumulate("name","Niraj Kumar Tiwary"); jsonObject.accumulate("name",str_aadhaar_name); jsonObject.accumulate("rdInfo",""); jsonObject.accumulate("rdData",""); jsonObject.accumulate("otpValue",""); StringEntity stringEntity = new StringEntity(jsonObject.toString()); // Log.d("ygygu",""+jsonObject.toString()); httpPost.setEntity(stringEntity); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); s = readResponse(httpResponse); Log.d("tag11", " " + s); } catch (Exception exception) { exception.printStackTrace(); } return s; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); if (pd1.isShowing()) { pd1.dismiss(); } try { if(s!=null) { JSONObject jsonObject = new JSONObject(s); String message = jsonObject.getString("status"); if (message.equalsIgnoreCase("ERROR")) { String errmessage = jsonObject.getString("errMsg"); showMessageDialogue(message, errmessage); } else { showSuccessMessageDialogue(message); BenfiList benfiList=new BenfiList(); benfiList.setBeneficiary_id(BenId); benfiList.setUidStatus("Y"); dataBaseHelper.updateInspectionDetails(benfiList); //setData(); } } } catch (JSONException e) { e.printStackTrace(); } } } public void showMessageDialogue(String messageTxt,String essage) { // MainActi.this.runOnUiThread(new Runnable() { // @Override // public void run() { new AlertDialog.Builder(VerifyAadhaarGlobally.this) .setCancelable(false) .setTitle("Error") .setMessage(essage) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .show(); // } // }); } public void showSuccessMessageDialogue(String messageTxt) { // MainActi.this.runOnUiThread(new Runnable() { // @Override // public void run() { new AlertDialog.Builder(VerifyAadhaarGlobally.this) .setCancelable(false) .setTitle("Success") .setMessage("Authenticated Successfully") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .show(); // } // }); } private String readResponse(HttpResponse httpResponse) { InputStream is = null; String return_text = ""; try { is = httpResponse.getEntity().getContent(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); String line = ""; StringBuffer sb = new StringBuffer(); while ((line = bufferedReader.readLine()) != null) { sb.append(line); } return_text = sb.toString(); Log.d("return_text", "" + return_text); } catch (Exception e) { } return return_text; } private class SearchGlobal extends AsyncTask<String, Void, ArrayList<BenfiList>> { String Search=""; public SearchGlobal(String benId) { Search=benId; } @Override protected void onPreExecute() { pd1 = new ProgressDialog(VerifyAadhaarGlobally.this); pd1.setTitle("please wait ...."); pd1.setCancelable(false); pd1.show(); } @Override protected ArrayList<BenfiList> doInBackground(String... param) { return WebserviceHelper.SearchGlobal(Search); } @Override protected void onPostExecute(ArrayList<BenfiList> result) { if (pd1.isShowing()) { pd1.dismiss(); } if (result != null) { if (result.size() > 0) { Log.d("datafromserver", "" + result); for (int i=0;i<result.size();i++) { benfiList = result.get(i); setData(benfiList); } } } } } @Override public void onBackPressed() { finish(); } }
package com.goldgov.dygl.module.partymemberrated.rated.services; import java.util.Date; /** * 党员评价POJO * Title: PartyMemberRated<br> * Description: <br> * Copyright @ 2011~2016 Goldgov .All rights reserved.<br> * * @author WangH * @createDate 2016年5月25日 * @version $Revision: $ */ public class PartyMemberRated { /** * 发布状态 */ public static final Integer PUBLISHED = 1; /** * 未发布状态 */ public static final Integer UNPUBLISHED = 2; private String ratedId;//党员评价Id private String ratedName;//评价名称 private String ratedYear;//评价年份 private Date ratedTimeStart;//评价开始时间 private Date ratedTimeEnd;//评价结束时间 private String createId;//创建人Id private String createName;//创建人姓名 private Date createTime;//发布时间 private Integer publishStatus;//发布状态 private Integer activeStatus;//活动状态 public String getRatedId() { return ratedId; } public void setRatedId(String ratedId) { this.ratedId = ratedId; } public String getRatedName() { return ratedName; } public void setRatedName(String ratedName) { this.ratedName = ratedName; } public String getRatedYear() { return ratedYear; } public void setRatedYear(String ratedYear) { this.ratedYear = ratedYear; } public Date getRatedTimeStart() { return ratedTimeStart; } public void setRatedTimeStart(Date ratedTimeStart) { this.ratedTimeStart = ratedTimeStart; } public Date getRatedTimeEnd() { return ratedTimeEnd; } public void setRatedTimeEnd(Date ratedTimeEnd) { this.ratedTimeEnd = ratedTimeEnd; } public String getCreateId() { return createId; } public void setCreateId(String createId) { this.createId = createId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getActiveStatus() { return activeStatus; } public void setActiveStatus(Integer activeStatus) { this.activeStatus = activeStatus; } public Integer getPublishStatus() { return publishStatus; } public void setPublishStatus(Integer publishStatus) { this.publishStatus = publishStatus; } }
package com.angrykings.pregame; public class LobbyPlayer { public String name; public int id; public String win; public String lose; public LobbyPlayer(String name, int id, String win, String lose){ this.name = name; this.id = id; this.win = win; this.lose = lose; } }
package fourthDayThirdHomework; import java.time.LocalDateTime; import Concrete.AuthenticationManager; import Concrete.CampaignManager; import Concrete.GameManager; import Concrete.PersonVerificationManager; import Concrete.SellingManager; import Concrete.UserManager; import Entities.Campaign; import Entities.Game; import Entities.Sell; import Entities.User; public class Main { public static void main(String[] args) { // GAMES Game witcher3 = new Game(); witcher3.setId(1); witcher3.setGenre("RPG/Aksiyon"); witcher3.setName("Witcher 3"); witcher3.setPrice(80); Game citiesSkylines = new Game(); citiesSkylines.setId(2); citiesSkylines.setGenre("Simülasyon"); citiesSkylines.setName("Cities Skylines"); citiesSkylines.setPrice(100); // CAMPAIGNS Campaign fridayCampaign = new Campaign(); fridayCampaign.setId(1); fridayCampaign.setName("Friday Discount!"); fridayCampaign.setDiscountAmount(35); Campaign midOfTheWeek = new Campaign(); midOfTheWeek.setId(2); midOfTheWeek.setName("Mid of The Week Discount!"); midOfTheWeek.setDiscountAmount(25); Campaign endOfTheSeason = new Campaign(); endOfTheSeason.setId(3); endOfTheSeason.setName("End Of The Season!!"); endOfTheSeason.setDiscountAmount(80); // USERS User murat = new User(); murat.setId(1); murat.setFirstName("Murat"); murat.setLastName("Topallar"); murat.setPassword("123456"); murat.setAge(34); // Yaş 18 den küçük ise kayıt gerçekleşmeyecek. User engin = new User(); engin.setId(2); engin.setFirstName("Engin"); engin.setLastName("Demiroğ"); engin.setPassword("654321"); engin.setAge(35); // Yaş 18 den küçük ise kayıt gerçekleşmeyecek. // SELLS Sell sellToMurat = new Sell(); sellToMurat.setId(1); sellToMurat.setUser(murat); sellToMurat.setGame(citiesSkylines); sellToMurat.setSellingDate(LocalDateTime.now()); Sell sellToEngin = new Sell(); sellToEngin.setId(2); sellToEngin.setUser(engin); sellToEngin.setGame(witcher3); sellToEngin.setSellingDate(LocalDateTime.now()); // Managers AuthenticationManager authManager = new AuthenticationManager(new PersonVerificationManager()); authManager.register(murat); CampaignManager campaignManager = new CampaignManager(); campaignManager.add(endOfTheSeason); campaignManager.update(midOfTheWeek); campaignManager.delete(fridayCampaign); GameManager gameManager = new GameManager(); gameManager.add(witcher3); gameManager.update(witcher3); gameManager.delete(witcher3); UserManager userManager = new UserManager(); userManager.update(murat); userManager.delete(engin); SellingManager sellingManager = new SellingManager(); sellingManager.sell(sellToMurat); sellingManager.sell(sellToEngin); SellingManager sellingWithCampaign = new SellingManager(endOfTheSeason); sellingWithCampaign.sell(sellToEngin); SellingManager sellingManagerWithCampaign2 = new SellingManager(midOfTheWeek); sellingManagerWithCampaign2.sell(sellToMurat); // Selling nesnesi yerine User ve Game parametreleri kullanılarak satış // gerçekleştirmek de mümkün, ben sell adında bir obje oluşturup game ve user ı // sell in içine gömerek kullandım. Doğrulama olarak yaşın 18 yaş üzerinde olup // olmaması şeklinde bir simülasyon gerçekleştirdim. } }
import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.table.DefaultTableModel; /* * @author Roziana */ public class Locadora { private Connection c; public Connection getConnection() { return c; } //Conecxão como o banco public void conectar(String IP, String porta, String database, String usuario, String senha) { try { String url = "jdbc:mysql://" + IP + ":" + porta + "/" + database + "?user=" + usuario + "&password=" + senha; System.out.println(url); c = (Connection) DriverManager.getConnection(url); System.out.println("Conectado!"); } catch (SQLException e) {System.out.println("Erro: "+ e); } } //Inserir clientes public int inserirCliente(Clientes cliente) { int resultado = 0; try { String query = "INSERT INTO CLIENTES (NOME_CLIENTE, ENDERECO, CPF, TELEFONE) " + "VALUES ('" + cliente.getNome() + "', '" + cliente.getEndereco() +"', '" + cliente.getCpf() + "', '" + cliente.getTelefone() + "')"; Statement st = (Statement) c.createStatement(); resultado = st.executeUpdate(query); } catch (Exception e) { System.out.println("Erro: "+ e); } return resultado; } //Inserir filmes public int inserirFilme(Filmes filme) { int resultado = 0; try { String query = "INSERT INTO FILMES (NOME_CLIENTE, ENDERECO, CPF, TELEFONE) " + "VALUES ('" + filme.getTitulo() + "', '" + filme.getTituloOriginal() + "', '" + filme.getDiretor() + "', '" + filme.getAnoLancamento() + "', '" + filme.getValorDiaria() +"', '" + filme.getImagem()+ "', '" + filme.getSinopse() +"')"; Statement st = (Statement) c.createStatement(); resultado = st.executeUpdate(query); } catch (Exception e) { } return resultado; } //Inserir emprestimos public int inserirEmprestimo(Emprestimos emp) { int resultado = 0; try { String query = "INSERT INTO EMPRESTIMOS (ID_CLIENTE, ID_FILME, DATA, DATA_DEVOLUCAO) " + "VALUES ('" + emp.getCliente() + "', '" + emp.getFilme()+ "', '" + emp.getData() + "', '" + emp.getDataDevolucao()+"')"; Statement st = (Statement) c.createStatement(); resultado = st.executeUpdate(query); } catch (Exception e) { } return resultado; } //Consultar emprestimos public Emprestimos consultarEmprestimos(String parametro, String condicao, DefaultTableModel model){ Emprestimos emp = new Emprestimos(); ResultSet rs = null; String query = "SELECT * FROM EMPRESTIMOS"; if(!parametro.isEmpty()){ query = query + "WHERE " + parametro + "LIKE '%" + condicao + "%';"; }else{ query = query + ";"; } try { Statement st = (Statement) c.createStatement(); rs = st.executeQuery(query); try { while(rs.next()){ emp.setCliente(rs.getString("ID_CLIENTE")); //... model.addRow(new String[]{}); } } catch (Exception e) { System.out.println("Erro: "+ e); } } catch (Exception e) { System.out.println("Erro: "+ e); } return emp; } //Consultar clientes public Clientes consultarClientes(String parametro, String condicao, DefaultTableModel model) { Clientes cliente = new Clientes(); ResultSet rs = null; String query = "SELECT * FROM CLIENTES"; if(!condicao.isEmpty()){ query = query + " WHERE "+ parametro +" LIKE '%"+ condicao +"%';"; }else{ query = query + ";"; } try { Statement st = (Statement) c.createStatement(); rs = st.executeQuery(query); try { while(rs.next()){ cliente.setNome(rs.getString("NOME_CLIENTE")); cliente.setCpf(rs.getString("CPF")); cliente.setEndereco(rs.getString("ENDERECO")); System.out.println(cliente.getNome()); model.addRow(new String[]{cliente.getNome()}); } } catch (Exception e) { System.out.println("Erro: "+ e); } } catch (Exception e) { System.out.println("Erro: "+ e); } return cliente; } //Consultar filmes public Filmes consultarFilmes(String parametro, DefaultTableModel model){ Filmes filme = new Filmes(); return filme; } //Alterar Filmes //Alterar Clientes //Aterar Emprestimos //Excluir }
package com.bank.service.ui.userlogin.domain; public class UserLogin { }
package com.aifurion.track.entity; import java.io.Serializable; /** * @author :zzy * @description:TODO 病单实体类 * @date :2021/4/3 14:27 */ public class TheCase implements Serializable { private static final long serialVersionUID = 2139022335408449627L; private String id; private String pid; private String did; private String rid; private String diagnosis; private String condition; private String treatment; private String createTime; private String state; private String building; private String floor; private String room; private String bed; private String hospitalized; private String wardId; public TheCase() { } public TheCase(String id, String pid, String did, String rid, String diagnosis, String condition, String treatment, String createTime, String state, String building, String floor, String room, String bed, String hospitalized, String wardId) { this.id = id; this.pid = pid; this.did = did; this.rid = rid; this.diagnosis = diagnosis; this.condition = condition; this.treatment = treatment; this.createTime = createTime; this.state = state; this.building = building; this.floor = floor; this.room = room; this.bed = bed; this.hospitalized = hospitalized; this.wardId = wardId; } @Override public String toString() { return "TheCase{" + "id='" + id + '\'' + ", pid='" + pid + '\'' + ", did='" + did + '\'' + ", rid='" + rid + '\'' + ", diagnosis='" + diagnosis + '\'' + ", condition='" + condition + '\'' + ", treatment='" + treatment + '\'' + ", createTime='" + createTime + '\'' + ", state='" + state + '\'' + ", building='" + building + '\'' + ", floor='" + floor + '\'' + ", room='" + room + '\'' + ", bed='" + bed + '\'' + ", hospitalized='" + hospitalized + '\'' + ", wardId='" + wardId + '\'' + '}'; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getDid() { return did; } public void setDid(String did) { this.did = did; } public String getRid() { return rid; } public void setRid(String rid) { this.rid = rid; } public String getDiagnosis() { return diagnosis; } public void setDiagnosis(String diagnosis) { this.diagnosis = diagnosis; } public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } public String getTreatment() { return treatment; } public void setTreatment(String treatment) { this.treatment = treatment; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getBuilding() { return building; } public void setBuilding(String building) { this.building = building; } public String getFloor() { return floor; } public void setFloor(String floor) { this.floor = floor; } public String getRoom() { return room; } public void setRoom(String room) { this.room = room; } public String getBed() { return bed; } public void setBed(String bed) { this.bed = bed; } public String getHospitalized() { return hospitalized; } public void setHospitalized(String hospitalized) { this.hospitalized = hospitalized; } public String getWardId() { return wardId; } public void setWardId(String wardId) { this.wardId = wardId; } }
package com.example.v3.list; /** * 自定义List接口 * @param <E> */ public interface MyList<E> { void add(E object); void add(int index, E object); Object remove(int index); boolean remove(E object); int getSize(); Object get(int index); }
package com.example.user.simplelife; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Spinner; import android.widget.Toast; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link FragmentAddTV_step1.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link FragmentAddTV_step1#newInstance} factory method to * create an instance of this fragment. */ public class FragmentAddTV_step1 extends FragmentAdd_step { ArrayList<String> ids; ArrayList<String> names; ArrayList<String> arduino; public static FragmentAddTV_step1 newInstance() { FragmentAddTV_step1 fragment = new FragmentAddTV_step1(); Bundle args = new Bundle(); return fragment; } public FragmentAddTV_step1() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_add_tv_step1, container, false); setSpinnerView(); ImageButton nextButton = (ImageButton) view.findViewById(R.id.ibtnNext_addTV1); nextButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TV appliance = (TV)((Add_TVActivity)getActivity()).getAppliance(); Spinner spinner = (Spinner)view.findViewById(R.id.spinner_whichMain_addTV); String mainName =spinner.getSelectedItem().toString(); for(int i=0 ;i < names.size(); i++){ if(mainName.equals(names.get(i))){ appliance.setMainControllerID(ids.get(i)); appliance.setMainControllerName(names.get(i)); } } Spinner spinner2 = (Spinner)view.findViewById(R.id.spinner_addTV); String andrunoID = spinner2.getSelectedItem().toString(); EditText audinoText = (EditText)view.findViewById(R.id.editTextID_addTV); if(!audinoText.getText().toString().equals("")){ andrunoID = audinoText.getText().toString(); } appliance.setArduinoID(andrunoID); MainController mc = ObjectReader.loadMainController(appliance.getMainControllerID()); Integer noAppliance = mc.getAppliances().size(); String deviceID = noAppliance.toString(); appliance.setDeviceID(deviceID); Toast.makeText(getActivity(), deviceID, Toast.LENGTH_LONG); mListener.onFragmentInteraction("next"); } }); return view; } public boolean hasArduino(String id){ for(int i=0 ; i<arduino.size();i++){ if(id.equals(arduino.get(i))){ return true; } } return false; } public void setSpinnerView(){ ids = ObjectReader.loadMC("MC_ID"); names = ObjectReader.loadMC("MC_Name"); arduino = new ArrayList<String>(); for(int i=0 ; i<ids.size();i++) { MainController main = ObjectReader.loadMainController(ids.get(i)); ArrayList<Appliance> appliances = main.getAppliances(); for(int j=0 ;j<appliances.size();j++){ if(!appliances.get(j).getType().equals("Light")){ String id = appliances.get(j).getArduinoID(); if(hasArduino(id) == false){ arduino.add(id); } } } } Spinner mainName = (Spinner)view.findViewById(R.id.spinner_whichMain_addTV); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_dropdown_item,names); mainName.setAdapter(adapter); Spinner arduinoName = (Spinner)view.findViewById(R.id.spinner_addTV); ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_dropdown_item,arduino); arduinoName.setAdapter(adapter2); } }
package com.itheima; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Random; public class Exam1 { /* 定义一个长度为5的数组arr1,用于存放5个1~9的随机整数(范围包含1和9), 再定义一个长度为2的数组arr2,统计arr1中的元素对2求余等于0的个数,保存到arr2[0], 统计arr1中的元素对3求余等于0的个数,保存到arr2[1],在控制台打印输出arr2的所有元素 */ public static void main(String[] args) { int arr1[] = new int[5]; int arr2[] = new int[2]; int count2 = 0 ; int count3 = 0; Random random = new Random(); for (int i = 0; i < arr1.length; i++) { arr1[i] = random.nextInt(9)+1; if(arr1[i] % 2 == 0 ){ count2 ++; } else if(arr1[i] % 3 == 0){ count3++; } } arr2[0] = count2; arr2[1] = count3; for (int i = 0; i < arr2.length; i++) { System.out.print(arr2[i]+" "); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.magapinv.www.logicanegocios.clases; import java.sql.Date; /** * * @author User */ public class Mantenimiento extends Estado_ac{ private String encargadomant; private Date fecha_ingreso; private Date fecha_salida; private String descripcion_danio; private int id_estado; public Mantenimiento() { } public Mantenimiento(String encargadomant, Date fecha_ingreso, Date fecha_salida, String descripcion_danio, int id_estado) { this.encargadomant = encargadomant; this.fecha_ingreso = fecha_ingreso; this.fecha_salida = fecha_salida; this.descripcion_danio = descripcion_danio; this.id_estado = id_estado; } public String getEncargadomant() { return encargadomant; } public void setEncargadomant(String encargadomant) { this.encargadomant = encargadomant; } public Date getFecha_ingreso() { return fecha_ingreso; } public void setFecha_ingreso(Date fecha_ingreso) { this.fecha_ingreso = fecha_ingreso; } public Date getFecha_salida() { return fecha_salida; } public void setFecha_salida(Date fecha_salida) { this.fecha_salida = fecha_salida; } public String getDescripcion_danio() { return descripcion_danio; } public void setDescripcion_danio(String descripcion_danio) { this.descripcion_danio = descripcion_danio; } @Override public int getId_estado() { return id_estado; } @Override public void setId_estado(int id_estado) { this.id_estado = id_estado; } }
package org.opentosca.containerapi.resources; /** * This package contains resource classes. */
/* * 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 tolteco.sigma.model.tables; import tolteco.sigma.model.entidades.Cliente; import tolteco.sigma.utils.eventsAndListeners.ChangePropertyEvent; /** * * @author Juliano */ public class ClienteTable extends SigmaAbstractTableModel<Cliente>{ public static final int COLUMN_COUNT = 8; public static final int NOME = 0; public static final int SOBRENOME = 1; public static final int OBS = 2; public static final int ENDERECO = 3; public static final int TELEFONE = 4; public static final int CPF = 5; public static final int CLIENTE_ID = 6; public static final int USER_ID = 7; @Override public int getColumnCount() { return COLUMN_COUNT; } @Override public Object getValueAt(int rowIndex, int columnIndex) { Cliente cliente = getRow(rowIndex); switch(columnIndex){ case NOME: return cliente.getNome(); case SOBRENOME: return cliente.getSobrenome(); case OBS: return cliente.getObs(); case ENDERECO: return cliente.getEnd(); case TELEFONE: return cliente.getTel(); case CPF: return cliente.getCpf(); case CLIENTE_ID: return cliente.getClienteId(); case USER_ID: return cliente.getUserId(); default: throw new IndexOutOfBoundsException( "Exceeded Max Column Count: " + columnIndex + " out of " + COLUMN_COUNT + "."); } } @Override public Class<?> getColumnClass(int columnIndex) { switch(columnIndex){ case NOME: return String.class; case SOBRENOME: return String.class; case OBS: return String.class; case ENDERECO: return String.class; case TELEFONE: return String.class; case CPF: return String.class; case CLIENTE_ID: return Integer.class; case USER_ID: return Integer.class; default: throw new IndexOutOfBoundsException( "Exceeded Max Column Count: " + columnIndex + " out of " + COLUMN_COUNT + "."); } } @Override public String getColumnName(int column) { switch(column){ case NOME: return "Nome"; case SOBRENOME: return "Sobrenome"; case OBS: return "Observações"; case ENDERECO: return "Endereço"; case TELEFONE: return "Telefone"; case CPF: return "CPF"; case CLIENTE_ID: return "ID Cliente"; case USER_ID: return "ID Usuário"; default: throw new IndexOutOfBoundsException( "Exceeded Max Column Count: " + column + " out of " + COLUMN_COUNT + "."); } } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { Cliente cliente = getRow(rowIndex); switch(columnIndex){ case NOME: cliente.setNome((String) aValue); fireChangeProperty(new ChangePropertyEvent(aValue)); break; case SOBRENOME: cliente.setSobrenome((String) aValue); fireChangeProperty(new ChangePropertyEvent(aValue)); break; case OBS: cliente.setObs((String) aValue); fireChangeProperty(new ChangePropertyEvent(aValue)); break; case ENDERECO: cliente.setEnd((String) aValue); fireChangeProperty(new ChangePropertyEvent(aValue)); break; case TELEFONE: cliente.setTel((String) aValue); fireChangeProperty(new ChangePropertyEvent(aValue)); break; case CPF: cliente.setCpf((String) aValue); fireChangeProperty(new ChangePropertyEvent(aValue)); break; case CLIENTE_ID: cliente.setClienteId((int) aValue); fireChangeProperty(new ChangePropertyEvent(aValue)); break; case USER_ID: cliente.setUserId((int) aValue); fireChangeProperty(new ChangePropertyEvent(aValue)); break; default: throw new IndexOutOfBoundsException( "Exceeded Max Column Count: " + columnIndex + " out of " + COLUMN_COUNT + "."); } } @Override public Cliente search(int key) { for (Cliente cliente : getList()){ if (cliente.getClienteId() == key) return cliente; } return null; } @Override public int search(Cliente object) { int DIDNOT_FIND_ROW=-1; int counter=0; for (Cliente cliente : getList()){ if (cliente.equals(object)) return counter; counter++; } return DIDNOT_FIND_ROW; } }
package com.tencent.tencentmap.mapsdk.a; import java.net.HttpURLConnection; import java.net.URL; class sl$1 extends Thread { private /* synthetic */ sl a; sl$1(sl slVar) { this.a = slVar; } public final void run() { Throwable th; HttpURLConnection httpURLConnection; HttpURLConnection httpURLConnection2; try { String str = Integer.toString(sl.c) + "," + Integer.toString(sl.d); String str2 = Integer.toString(sl.a) + "," + Integer.toString(sl.b); String str3 = Integer.toString(sl.e) + "," + Integer.toString(0); String str4 = Integer.toString(sl.f) + "," + Integer.toString(0); StringBuilder stringBuilder = new StringBuilder("https://pr.map.qq.com/pingd?"); String str5 = (sl.a(this.a) == null || sl.a(this.a).c() == null) ? "" : sl.a(this.a).c() + "&"; httpURLConnection2 = (HttpURLConnection) new URL(stringBuilder.append(str5).append("appid=sdk&logid=ditu&miss=").append(str).append("&hit=").append(str2).append("&keep=").append(str3).append("&change=").append(str4).toString()).openConnection(); try { httpURLConnection2.setRequestMethod("GET"); httpURLConnection2.connect(); if (httpURLConnection2.getResponseCode() == 200) { httpURLConnection2.getInputStream(); sl.c = 0; sl.d = 0; sl.a = 0; sl.b = 0; sl.e = 0; sl.f = 0; sl.g = 0; sl.b = 0; } if (httpURLConnection2 != null) { httpURLConnection2.disconnect(); } } catch (Exception e) { if (httpURLConnection2 != null) { httpURLConnection2.disconnect(); } } catch (Throwable th2) { th = th2; httpURLConnection = httpURLConnection2; if (httpURLConnection != null) { httpURLConnection.disconnect(); } throw th; } } catch (Exception e2) { httpURLConnection2 = null; } catch (Throwable th3) { th = th3; httpURLConnection = null; if (httpURLConnection != null) { httpURLConnection.disconnect(); } throw th; } } }
package com.tencent.mm.g.a; import com.tencent.mm.sdk.b.b; public final class ih extends b { public a bRN; public ih() { this((byte) 0); } private ih(byte b) { this.bRN = new a(); this.sFm = false; this.bJX = null; } }
package com.santander.bi.adminFiles; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.StandardCharsets; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class AdminHTML { private FileOutputStream output; int lineasEscritas= 0 ; String sheetName=""; char carSep='|'; char carStr=0; char carReplaceSepStr = '-'; char carComodin = '?'; StringBuffer dat = new StringBuffer(); Charset charset = StandardCharsets.UTF_8; CharsetEncoder encoder = charset.newEncoder(); static final String PATRON_VALIDO = "[0-9]|[a-zA-Z]|[,-@.\\s\\|]"; //Patrón con caracteres válido para archivos e interfaces Pattern pattGen = Pattern.compile(PATRON_VALIDO); // Compilación del Patrón public void setPattronValido(String nuevoPatron) { pattGen = Pattern.compile(nuevoPatron); } public int htmlToTXT(String pathOrigen, String pathDestino) { return htmlToGen(pathOrigen, pathDestino, '|', '-'); } public int htmlToCSV(String pathOrigen, String pathDestino) { return htmlToGen(pathOrigen, pathDestino, ',', '-'); } public int htmlToGen(String pathOrigen, String pathDestino, char carSep, char carReplaceSepStr) { try { File input = new File(pathOrigen); output = new FileOutputStream(pathDestino); Document doc = Jsoup.parse(input, "UTF-8", "http://santander.com/"); //Document doc = Jsoup.connect(html).get(); Elements tableElements = doc.select("table"); Elements tableHeaderEles = tableElements.select("thead tr th"); for (int i = 0; i < tableHeaderEles.size(); i++) { dat.append(tableHeaderEles.get(i).text().replace(carSep, carReplaceSepStr).trim()); dat.append(carSep); } Elements tableRowElements = tableElements.select(":not(thead) tr"); for (int i = 0; i < tableRowElements.size(); i++) { Element row = tableRowElements.get(i); Elements rowItems = row.select("td"); for (int j = 0; j < rowItems.size(); j++) { dat.append(limpiaBuffer(new String(rowItems.get(j).text().replace(carSep, carReplaceSepStr).trim().getBytes(), charset), carComodin)); dat.append(carSep); } dat.append('\n'); if((lineasEscritas%1000)==0) { escribeArchivo(output, dat); dat=new StringBuffer(); } lineasEscritas++; } if(dat.length() > 0) { escribeArchivo(output, dat); dat = null; } output.flush(); output.close(); } catch (IOException e) { e.printStackTrace(); } return lineasEscritas; } private void escribeArchivo(FileOutputStream fcOut, StringBuffer line){ try { // No allocation performed, just wraps the StringBuilder. CharBuffer buffer = CharBuffer.wrap(line); ByteBuffer byteBuffer = encoder.encode(buffer); byte[] bytes; int arrayLen = byteBuffer.limit(); if (arrayLen == byteBuffer.capacity()) { bytes = byteBuffer.array(); } else { // This will place two copies of the byte sequence in memory, // until byteBuffer gets garbage-collected (which should happen // pretty quickly once the reference to it is null'd). bytes = new byte[arrayLen]; byteBuffer.get(bytes); } fcOut.write(bytes); byteBuffer = null; }catch(IOException ex) { ex.printStackTrace(); } } public String limpiaBuffer(String cad, char carComodin) { StringBuffer newStr = new StringBuffer(); if(cad!=null) { for(int index=0; index < cad.length(); index++) { char car = cad.charAt(index); if( ejecutaReglasVal(car) ) { newStr.append(car); }else { //System.out.println(":"+car+":"+(int)car+":"); newStr.append(carComodin); } } } return newStr.toString(); } public boolean ejecutaReglasVal(char carInt) { char car = carInt; return caracterValido(car); } public boolean caracterValido(char car) { StringBuffer carSB = new StringBuffer(); carSB.append(car); Matcher encaja = pattGen.matcher(carSB); return encaja.find(); } public static void main(String[] args) { AdminHTML adm = new AdminHTML(); System.out.println(adm.htmlToTXT("C:\\TMP\\Pruebas\\herrclien\\origen\\ContactCenter\\REGISTROS_ACTUALIZACIONDATOS_11102018Pruebas.xls", "C:\\TMP\\Pruebas\\herrclien\\destino\\ContactCenter\\REGISTROS_ACTUALIZACIONDATOS_11102018Pruebas.txt")); } }
package com.yfancy.service.notify.dao; import com.yfancy.common.base.dao.BaseDao; import com.yfancy.common.base.entity.Notify; public interface NotifyDao extends BaseDao<Notify> { int insert(Notify notify); int update(Notify notify); }
package org.training.issuetracker.dao.hibernate; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Order; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.training.issuetracker.dao.entities.Role; import org.training.issuetracker.dao.interfaces.RoleDAO; @Repository("roleDAO") @Transactional public class HibernateRoleDAO implements RoleDAO { private static final Logger logger = Logger.getLogger(HibernateRoleDAO.class); private static final String TAG = HibernateRoleDAO.class.getSimpleName(); @Autowired protected SessionFactory sessionFactory; @SuppressWarnings("unchecked") @Override public List<Role> getRoles() { List<Role> roles = null; final Session session = sessionFactory.getCurrentSession(); try { Criteria criteria = session.createCriteria(Role.class); criteria.addOrder(Order.asc(Role.COLUMN_ID)); roles = (List<Role>) criteria.list(); } catch (Exception e) { logger.error(TAG + " Getting all roles failed!", e); throw e; } return roles; } @Override public Role getRoleById(int roleId) { Role role = null; final Session session = sessionFactory.getCurrentSession(); try { role = (Role) session.get(Role.class, roleId); } catch (Exception e) { logger.error(TAG + " Getting Role-object " + roleId + " failed!", e); throw e; } return role; } @Override public boolean createRole(Role role) { boolean success = false; final Session session = sessionFactory.getCurrentSession(); try { session.save(role); success = true; } catch(Exception e) { logger.error(TAG + " Creating Role-object failed!", e); } return success; } @Override public boolean updateRole(Role role) { boolean success = false; final Session session = sessionFactory.getCurrentSession(); try { session.update(role); success = true; } catch(Exception e) { logger.error(TAG + " Updating Role-object with id=" + role.getRoleId() + " failed!", e); } return success; } @Override public boolean deleteRole(int roleId) { boolean success = false; Role deletingRole = new Role(); deletingRole.setRoleId(roleId); final Session session = sessionFactory.getCurrentSession(); try { session.delete(deletingRole); success = true; } catch(Exception e) { logger.error(TAG + " Deleting Role-object with id=" + roleId + " failed!", e); } return success; } }
package com.duanxr.yith.midium; import java.util.Arrays; /** * @author 段然 2021/8/26 */ public class BoatsToSavePeople { /** * You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. * * Return the minimum number of boats to carry every given person. * *   * * Example 1: * * Input: people = [1,2], limit = 3 * Output: 1 * Explanation: 1 boat (1, 2) * Example 2: * * Input: people = [3,2,2,1], limit = 3 * Output: 3 * Explanation: 3 boats (1, 2), (2) and (3) * Example 3: * * Input: people = [3,5,3,4], limit = 5 * Output: 4 * Explanation: 4 boats (3), (3), (4), (5) *   * * Constraints: * * 1 <= people.length <= 5 * 104 * 1 <= people[i] <= limit <= 3 * 104 * * 第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit。 * * 每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。 * * 返回载到每一个人所需的最小船数。(保证每个人都能被船载)。 * *   * * 示例 1: * * 输入:people = [1,2], limit = 3 * 输出:1 * 解释:1 艘船载 (1, 2) * 示例 2: * * 输入:people = [3,2,2,1], limit = 3 * 输出:3 * 解释:3 艘船分别载 (1, 2), (2) 和 (3) * 示例 3: * * 输入:people = [3,5,3,4], limit = 5 * 输出:4 * 解释:4 艘船分别载 (3), (3), (4), (5) * 提示: * * 1 <= people.length <= 50000 * 1 <= people[i] <= limit <= 30000 * */ class Solution { public int numRescueBoats(int[] people, int limit) { Arrays.sort(people); int l = 0; int r = people.length - 1; int num = 0; while (l <= r) { if (people[l] + people[r] <= limit && l != r) { l++; r--; num++; } else { r--; num++; } } return num; } } }
package com.qswy.app.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.qswy.app.R; import com.qswy.app.activity.affairremind.AffairRemindActivity; import com.qswy.app.activity.angelstore.AngelStoreActivity; import com.qswy.app.activity.aroundbusiness.ABHomeActivity; import com.qswy.app.activity.communityresource.CRHomeActivity; import com.qswy.app.activity.hotspot.HotSpotActivity; import com.qswy.app.activity.paymanage.PayManageHomeActivity; import com.qswy.app.activity.propertyhelp.PropertyHelpActivity; import com.qswy.app.activity.repairservice.RepairHomeActivity; import com.qswy.app.model.BannerModel; import com.sivin.Banner; import com.sivin.BannerAdapter; import java.util.ArrayList; import java.util.List; /** * A simple {@link Fragment} subclass. * 首页 */ public class HomeFragment extends BaseFragment implements View.OnClickListener{ private View homeView; private LinearLayout tagLayout1,tagLayout2,tagLayout3,tagLayout4,tagLayout5,tagLayout6,tagLayout7,tagLayout8; private Banner mBanner; private List<BannerModel> mBannerDatas = new ArrayList<>(); private ImageView ivBack; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment initView(inflater,container); initListener(); loadData(); return homeView; } private void initView(LayoutInflater inflater, ViewGroup container) { homeView = inflater.inflate(R.layout.fragment_home, container, false); tagLayout1 = (LinearLayout) homeView.findViewById(R.id.layout_home_thingremind); tagLayout2 = (LinearLayout) homeView.findViewById(R.id.layout_home_propertyhelp); tagLayout3 = (LinearLayout) homeView.findViewById(R.id.layout_home_aroundshop); tagLayout4 = (LinearLayout) homeView.findViewById(R.id.layout_home_communityresource); tagLayout5 = (LinearLayout) homeView.findViewById(R.id.layout_home_paymanage); tagLayout6 = (LinearLayout) homeView.findViewById(R.id.layout_home_angelstore); tagLayout7 = (LinearLayout) homeView.findViewById(R.id.layout_home_repairservice); tagLayout8 = (LinearLayout) homeView.findViewById(R.id.layout_home_communityhotspot); mBanner = (Banner) homeView.findViewById(R.id.banner_home); ivBack = (ImageView) homeView.findViewById(R.id.iv_public_back); ivBack.setVisibility(View.INVISIBLE); } private void initListener(){ tagLayout1.setOnClickListener(this); tagLayout2.setOnClickListener(this); tagLayout3.setOnClickListener(this); tagLayout4.setOnClickListener(this); tagLayout5.setOnClickListener(this); tagLayout6.setOnClickListener(this); tagLayout7.setOnClickListener(this); tagLayout8.setOnClickListener(this); } protected void loadData() { for (int i=0;i<5;i++){ BannerModel bannerModel = new BannerModel(); bannerModel.setImageId(R.mipmap.banner); mBannerDatas.add(bannerModel); } BannerAdapter adapter = new BannerAdapter<BannerModel>(mBannerDatas) { @Override protected void bindTips(TextView tv, BannerModel bannerModel) { } @Override public void bindImage(ImageView imageView, BannerModel bannerModel) { imageView.setImageResource(bannerModel.getImageId()); } }; mBanner.setBannerAdapter(adapter); mBanner.notifiDataHasChanged(); } @Override public void onClick(View view) { Intent intent = null; switch (view.getId()){ case R.id.layout_home_thingremind: intent = new Intent(getActivity(), AffairRemindActivity.class); startActivity(intent); break; case R.id.layout_home_propertyhelp: intent = new Intent(getActivity(), PropertyHelpActivity.class); startActivity(intent); break; case R.id.layout_home_aroundshop: intent = new Intent(getActivity(), ABHomeActivity.class); startActivity(intent); break; case R.id.layout_home_communityresource: intent = new Intent(getActivity(), CRHomeActivity.class); startActivity(intent); break; case R.id.layout_home_paymanage: intent = new Intent(getActivity(), PayManageHomeActivity.class); startActivity(intent); break; case R.id.layout_home_angelstore: intent = new Intent(getActivity(), AngelStoreActivity.class); startActivity(intent); break; case R.id.layout_home_repairservice: intent = new Intent(getActivity(), RepairHomeActivity.class); startActivity(intent); break; case R.id.layout_home_communityhotspot: intent = new Intent(getActivity(), HotSpotActivity.class); startActivity(intent); break; } } }
package com.xiaomi; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.Random; public class ZKClientTutorial { private ZooKeeper zk = null; private ArrayList<String> onlineServers = new ArrayList<>(); public void connectZK() throws Exception { zk = new ZooKeeper("10.232.33.211", 2000, watchedEvent -> { if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected && watchedEvent.getType() == Watcher.Event.EventType.NodeChildrenChanged) { try { getOnlineServers(); } catch (Exception e) { e.printStackTrace(); } } }); } public void getOnlineServers() throws Exception{ List<String> children = zk.getChildren("/servers", true); ArrayList<String> currentServer = new ArrayList<>(); for (String child : children) { byte[] data = zk.getData("/servers/" + child, false, null); currentServer.add(new String(data)); } onlineServers = currentServer; System.out.println("更新服务器列表: " + onlineServers); } public void sendRequest() throws Exception { Random random = new Random(); while (true) { int nextInt = random.nextInt(onlineServers.size()); String server = onlineServers.get(nextInt); String hostName = server.split(":")[0]; int port = Integer.parseInt(server.split(":")[1]); System.out.println("开始进行服务器请求查询, 选择的服务器为: " + server); Socket socket = new Socket(hostName, port); OutputStream outputStream = socket.getOutputStream(); InputStream inputStream = socket.getInputStream(); outputStream.write("Test".getBytes()); outputStream.flush(); byte[] buffer = new byte[256]; int read = inputStream.read(buffer); System.out.println("服务器响应时间为: " + new String(buffer, 0, read)); outputStream.close(); inputStream.close(); socket.close(); Thread.sleep(5000); } } public static void main(String[] args) throws Exception{ ZKClientTutorial zkClientTutorial = new ZKClientTutorial(); zkClientTutorial.connectZK(); zkClientTutorial.getOnlineServers(); zkClientTutorial.sendRequest(); } }
package com.xiaolh.swagger2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * Create by 肖橙橙 * Date: 2020:08:04 00:34 */ @Configuration @SpringBootApplication // 组件扫描 @EnableScheduling @EnableAsync @EnableSwagger2 //@EnableSwagger2来启动swagger注解 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
/* * 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 forms; import dao.ClienteDAO; import dao.LivroDAO; import dao.VendaDAO; /** * * @author alunoces */ public class FormPrincipal extends javax.swing.JFrame { /** * Creates new form FormPrincipal */ public static ClienteDAO daoCliente = null; public static LivroDAO daoLivro = null; public static VendaDAO daoVenda = null; public FormPrincipal() { initComponents(); this.setExtendedState(this.MAXIMIZED_BOTH); daoCliente = new ClienteDAO(); daoLivro = new LivroDAO(); daoVenda = new VendaDAO(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); JMenuCadastros = new javax.swing.JMenu(); jMenuItemCadCliente = new javax.swing.JMenuItem(); jMenuItemCadProdutos = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); jMenuItemSair = new javax.swing.JMenuItem(); jMenuSuporte = new javax.swing.JMenu(); jMenuItemSuporteAjuda = new javax.swing.JMenuItem(); jSeparator2 = new javax.swing.JPopupMenu.Separator(); jMenuItemSuporteSobre = new javax.swing.JMenuItem(); jMenuVenda = new javax.swing.JMenu(); jMenuItemVendaNovaVenda = new javax.swing.JMenuItem(); jMenuItemVendaEmitirNotaFiscal = new javax.swing.JMenuItem(); JMenuConsultas = new javax.swing.JMenu(); jMenuItemConsuClientes = new javax.swing.JMenuItem(); jMenuItemConsuProdutos = new javax.swing.JMenuItem(); jMenuCompras = new javax.swing.JMenu(); jMenuItemComprasDia = new javax.swing.JMenuItem(); jMenuItemComprasMes = new javax.swing.JMenuItem(); jMenuItemComprasAno = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Sistema eletrônico de livraria"); setExtendedState(6); setResizable(false); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED)); jPanel1.setLayout(new java.awt.BorderLayout()); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/logo.png"))); // NOI18N jPanel1.add(jLabel1, java.awt.BorderLayout.CENTER); JMenuCadastros.setText("Cadastros"); JMenuCadastros.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JMenuCadastrosActionPerformed(evt); } }); jMenuItemCadCliente.setText("Clientes"); jMenuItemCadCliente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemCadClienteActionPerformed(evt); } }); JMenuCadastros.add(jMenuItemCadCliente); jMenuItemCadProdutos.setText("Produto"); JMenuCadastros.add(jMenuItemCadProdutos); JMenuCadastros.add(jSeparator1); jMenuItemSair.setText("Sair"); JMenuCadastros.add(jMenuItemSair); jMenuBar1.add(JMenuCadastros); jMenuSuporte.setText("Suporte"); jMenuItemSuporteAjuda.setText("Ajuda"); jMenuSuporte.add(jMenuItemSuporteAjuda); jMenuSuporte.add(jSeparator2); jMenuItemSuporteSobre.setText("Sobre"); jMenuSuporte.add(jMenuItemSuporteSobre); jMenuBar1.add(jMenuSuporte); jMenuVenda.setText("Venda"); jMenuItemVendaNovaVenda.setText("Nova Venda"); jMenuVenda.add(jMenuItemVendaNovaVenda); jMenuItemVendaEmitirNotaFiscal.setText("Emitir Nota Fiscal"); jMenuVenda.add(jMenuItemVendaEmitirNotaFiscal); jMenuBar1.add(jMenuVenda); JMenuConsultas.setText("Consultas"); JMenuConsultas.setToolTipText(""); jMenuItemConsuClientes.setText("Clientes"); jMenuItemConsuClientes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemConsuClientesActionPerformed(evt); } }); JMenuConsultas.add(jMenuItemConsuClientes); jMenuItemConsuProdutos.setText("Produtos"); JMenuConsultas.add(jMenuItemConsuProdutos); jMenuCompras.setText("Compras"); jMenuItemComprasDia.setText("Dia"); jMenuItemComprasDia.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemComprasDiaActionPerformed(evt); } }); jMenuCompras.add(jMenuItemComprasDia); jMenuItemComprasMes.setText("Mes"); jMenuItemComprasMes.setToolTipText(""); jMenuCompras.add(jMenuItemComprasMes); jMenuItemComprasAno.setText("Ano"); jMenuCompras.add(jMenuItemComprasAno); JMenuConsultas.add(jMenuCompras); jMenuBar1.add(JMenuConsultas); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 837, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 586, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jMenuItemComprasDiaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemComprasDiaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jMenuItemComprasDiaActionPerformed private void JMenuCadastrosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JMenuCadastrosActionPerformed // TODO add your handling code here: this.dispose(); }//GEN-LAST:event_JMenuCadastrosActionPerformed private void jMenuItemCadClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCadClienteActionPerformed // TODO add your handling code here: new FormCliente().setVisible(true); // this.dispose(); estava fechando o form principal }//GEN-LAST:event_jMenuItemCadClienteActionPerformed private void jMenuItemConsuClientesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemConsuClientesActionPerformed // TODO add your handling code here: new FormConsultaCliente().setVisible(true); }//GEN-LAST:event_jMenuItemConsuClientesActionPerformed /** * @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(FormPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormPrincipal.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 FormPrincipal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenu JMenuCadastros; private javax.swing.JMenu JMenuConsultas; private javax.swing.JLabel jLabel1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenu jMenuCompras; private javax.swing.JMenuItem jMenuItemCadCliente; private javax.swing.JMenuItem jMenuItemCadProdutos; private javax.swing.JMenuItem jMenuItemComprasAno; private javax.swing.JMenuItem jMenuItemComprasDia; private javax.swing.JMenuItem jMenuItemComprasMes; private javax.swing.JMenuItem jMenuItemConsuClientes; private javax.swing.JMenuItem jMenuItemConsuProdutos; private javax.swing.JMenuItem jMenuItemSair; private javax.swing.JMenuItem jMenuItemSuporteAjuda; private javax.swing.JMenuItem jMenuItemSuporteSobre; private javax.swing.JMenuItem jMenuItemVendaEmitirNotaFiscal; private javax.swing.JMenuItem jMenuItemVendaNovaVenda; private javax.swing.JMenu jMenuSuporte; private javax.swing.JMenu jMenuVenda; private javax.swing.JPanel jPanel1; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JPopupMenu.Separator jSeparator2; // End of variables declaration//GEN-END:variables }
package com.development.shanujbansal.mileagecalc; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; /** * Created by shanuj.bansal on 4/20/2015. */ public class DatabaseHelper extends SQLiteOpenHelper { // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "Mileage Calculator"; // table's name private static final String TABLE_VEHICLES = "Vehicles"; private static final String TABLE_FUELPRICES = "Region_Fuel_Prices"; private static final String TABLE_ENTRIES = "Records"; // TABLE_VEHICLES columns // private static final String ID : would be used same as of fuel prices private static final String BASE_ODO_READING = "Base_Odometer_Reading"; private static final String NAME = "Vehicle_Name"; private static final String REGN_NO = "Registration_Number"; private static final String REGION_ID = "Region_Id"; private static final String FUEL_TYPE = "Fuel_Type"; private static final String PREVIOUS_REFILL_ODO_READING = "Reading_At_Last_Refill"; private static final String FUEL_PRICE = "Fuel_Price"; private static final String EXPECTED_MILEAGE = "Expected_Mileage"; // TABLE_FUELPRICES columns private static final String ID = "Id"; private static final String REGION = "Region"; private static final String PETROL_PRICE = "Petrol_Price"; private static final String DIESEL_PRICE = "Diesel_Price"; private static final String CNG_PRICE = "CNG_Price"; // TABLE_ENTRIES columns private static final String VEHICLE_ID = "Vehicle_Id"; private static final String PREV_ODO_READING = "Previous_Odometer_Reading"; private static final String CURR_ODO_READING = "Current_Odometer_Reading"; private static final String FUEL_AMOUNT = "Fuel_Amount"; private static final String REFILL_DATE = "Refilling_Date"; private static final String MILEAGE = "Mileage"; private static DatabaseHelper instance; Random r = new Random(); private Context _context; //private static final String FUEL_PRICE = "Fuel_Price"; private DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this._context = context; } public static DatabaseHelper getInstance(Context context) { if (instance == null) instance = new DatabaseHelper(context); instance._context = context; return instance; } @Override public void onCreate(SQLiteDatabase db) { String createFuelPricesTable = "CREATE TABLE " + TABLE_FUELPRICES + "(" + ID + " INTEGER PRIMARY KEY," + REGION + " TEXT," + PETROL_PRICE + " REAL," + DIESEL_PRICE + " REAL," + CNG_PRICE + " REAL" + ")"; db.execSQL(createFuelPricesTable); enterFuelPricesForRegions(db); String createVehiclesTable = "CREATE TABLE " + TABLE_VEHICLES + "(" + ID + " INTEGER PRIMARY KEY," + BASE_ODO_READING + " INTEGER," + NAME + " TEXT," + REGN_NO + " TEXT," + REGION_ID + " INTEGER," + PREVIOUS_REFILL_ODO_READING + " INTEGER," + EXPECTED_MILEAGE + " REAL," + FUEL_PRICE + " REAL," + FUEL_TYPE + " TEXT" + ")"; db.execSQL(createVehiclesTable); String createEntriesTable = "CREATE TABLE " + TABLE_ENTRIES + "(" + VEHICLE_ID + " INTEGER," + PREV_ODO_READING + " INTEGER," + CURR_ODO_READING + " INTEGER," + FUEL_AMOUNT + " REAL," + MILEAGE + " REAL," + FUEL_PRICE + " REAL," + REFILL_DATE + " TEXT" + ")"; db.execSQL(createEntriesTable); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public void closeConnection() { SQLiteDatabase db = this.getWritableDatabase(); if (db != null) db.close(); } private void enterFuelPricesForRegions(SQLiteDatabase db) { try { ArrayList<RegionFuel> regionFuelList = prepareRegionsList(); for (RegionFuel regionFuel : regionFuelList) { ContentValues values = new ContentValues(); values.put(ID, regionFuel.getId()); values.put(REGION, regionFuel.getRegion()); values.put(PETROL_PRICE, regionFuel.getPetrolPrice()); values.put(DIESEL_PRICE, regionFuel.getDieselPrice()); values.put(CNG_PRICE, regionFuel.getCngPrice()); // Inserting Row db.insert(TABLE_FUELPRICES, null, values); } // db.close(); // Closing database connection } catch (Exception ex) { String err = ex.getMessage(); } } private ArrayList<RegionFuel> prepareRegionsList() { ArrayList<RegionFuel> regionFuelArrayList = new ArrayList<RegionFuel>(); regionFuelArrayList.add(new RegionFuel(1, "Andhra Pradesh", 71.37, 56.63, 48)); regionFuelArrayList.add(new RegionFuel(2, "Arunachal Pradesh", 62.66, 49.22, 0)); //nu regionFuelArrayList.add(new RegionFuel(3, "Assam", 66.06, 52.15, 0)); regionFuelArrayList.add(new RegionFuel(4, "Bihar", 70.94, 55.61, 0)); regionFuelArrayList.add(new RegionFuel(5, "Chhattisgarh", 65.46, 55.22, 0)); regionFuelArrayList.add(new RegionFuel(6, "Goa", 60.25, 53.75, 0)); regionFuelArrayList.add(new RegionFuel(7, "Gujarat", 66.52, 54.85, 46.75)); regionFuelArrayList.add(new RegionFuel(8, "Haryana", 67.24, 49.72, 0)); regionFuelArrayList.add(new RegionFuel(9, "Himachal Pradesh", 68.07, 49.92, 0)); regionFuelArrayList.add(new RegionFuel(10, "Jammu and Kashmir", 68.21, 52.6, 0)); regionFuelArrayList.add(new RegionFuel(11, "Jharkhand", 64.94, 54.81, 0)); regionFuelArrayList.add(new RegionFuel(12, "Karnataka", 69.59, 54.34, 0)); regionFuelArrayList.add(new RegionFuel(13, "Kerala", 69.68, 55.57, 0)); regionFuelArrayList.add(new RegionFuel(14, "Madhya Pradesh", 69.25, 56.27, 0)); regionFuelArrayList.add(new RegionFuel(15, "Maharashtra", 70.89, 56.9, 43.45)); regionFuelArrayList.add(new RegionFuel(16, "Manipur", 62.34, 49.53, 0)); regionFuelArrayList.add(new RegionFuel(17, "Meghalaya", 64.05, 51.05, 0)); regionFuelArrayList.add(new RegionFuel(18, "Mizoram", 62.34, 48.96, 0)); regionFuelArrayList.add(new RegionFuel(19, "Nagaland", 64.62, 49.8, 0)); regionFuelArrayList.add(new RegionFuel(20, "Odisha", 64.99, 54.89, 0)); regionFuelArrayList.add(new RegionFuel(21, "Punjab", 70.73, 49.65, 0)); regionFuelArrayList.add(new RegionFuel(22, "Rajasthan", 68.86, 54.65, 0)); regionFuelArrayList.add(new RegionFuel(23, "Sikkim", 68.93, 53.99, 0)); regionFuelArrayList.add(new RegionFuel(24, "Tamil Nadu", 66.13, 52.79, 0)); regionFuelArrayList.add(new RegionFuel(25, "Telangana", 71.21, 56.04, 52)); regionFuelArrayList.add(new RegionFuel(26, "Tripura", 62.15, 49.40, 0)); regionFuelArrayList.add(new RegionFuel(27, "Uttar Pradesh", 70.21, 54.61, 40.5)); regionFuelArrayList.add(new RegionFuel(28, "Uttarakhand", 66.84, 54.57, 0)); regionFuelArrayList.add(new RegionFuel(29, "West Bengal", 70.49, 54.19, 0)); regionFuelArrayList.add(new RegionFuel(30, "Andaman and Nicobar Islands", 56.40, 47.46, 0)); regionFuelArrayList.add(new RegionFuel(31, "Chandigarh", 64.69, 49.23, 0)); regionFuelArrayList.add(new RegionFuel(32, "Dadra and Nagar Haveli", 64.69, 52.14, 0)); regionFuelArrayList.add(new RegionFuel(33, "Daman and Diu", 65.15, 52.14, 0)); regionFuelArrayList.add(new RegionFuel(34, "Lakshadweep", 0, 0, 0)); regionFuelArrayList.add(new RegionFuel(35, "National Capital Territory of Delhi", 63.21, 49.59, 38.15)); regionFuelArrayList.add(new RegionFuel(36, "Puducherry", 62.05, 51.74, 0)); return regionFuelArrayList; } public ArrayList<String> getRegionsList() { ArrayList<String> regionsList = new ArrayList<String>(); try { // Select All Query String selectQuery = "SELECT " + REGION + " FROM " + TABLE_FUELPRICES; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { String regionName = cursor.getString(0); regionsList.add(regionName); } while (cursor.moveToNext()); } } catch (Exception ex) { } return regionsList; } public double getExpectedMileage(int vehicleId) { double expMileage = 0.0; DecimalFormat valueFormat = new DecimalFormat("#.##"); try { String selectQuery = "SELECT " + EXPECTED_MILEAGE + " FROM " + TABLE_VEHICLES + " WHERE " + ID + " =" + vehicleId; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { expMileage = cursor.getDouble(0); } while (cursor.moveToNext()); } } catch (Exception ex) { } return expMileage; } public HashMap<String, String> getVehicleMileage(int vehicleId) { HashMap<String, String> mileageInfo = new HashMap<>(); double mileageSum = 0.0; int numEntries = 0; double expensePerKmSum = 0.0; try { String selectQuery = "SELECT " + MILEAGE + "," + FUEL_PRICE + " FROM " + TABLE_ENTRIES + " WHERE " + VEHICLE_ID + " =" + vehicleId; DecimalFormat valueFormat = new DecimalFormat("#.##"); SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { mileageSum += cursor.getDouble(0); expensePerKmSum += cursor.getDouble(1) / cursor.getDouble(0); numEntries++; } while (cursor.moveToNext()); } if (numEntries != 0) { mileageInfo.put("Mileage", String.valueOf(valueFormat.format(mileageSum / numEntries)).toString()); mileageInfo.put("ExpensePerKm", String.valueOf(valueFormat.format(expensePerKmSum / numEntries)).toString()); } } catch (Exception ex) { } return mileageInfo; } public int getVehicleId(String vehicleName) { try { String selectQuery = "SELECT " + ID + " FROM " + TABLE_VEHICLES + " WHERE " + NAME + " ='" + vehicleName + "'"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { return cursor.getInt(0); } } catch (Exception ex) { } return 0; } public HashMap<String, String> getVehicleDetails(String vehicleName) { HashMap<String, String> details = new HashMap<String, String>(); try { String selectQuery = "SELECT " + PREVIOUS_REFILL_ODO_READING + "," + FUEL_PRICE + " FROM " + TABLE_VEHICLES + " WHERE " + NAME + " ='" + vehicleName + "'"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { details.put("prevReading", cursor.getString(0)); details.put("fuelPrice", cursor.getString(1)); } } catch (Exception ex) { } return details; } public HashMap<String, String> getFuelPrices(int regionId) { HashMap<String, String> fuelPricesDetails = new HashMap<String, String>(); try { String selectQuery = "SELECT " + PETROL_PRICE + "," + DIESEL_PRICE + "," + CNG_PRICE + " FROM " + TABLE_FUELPRICES + " WHERE " + ID + " =" + regionId; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { String petrolPrice = cursor.getString(0); if (petrolPrice.equals("0")) petrolPrice = "N.A"; String dieselPrice = cursor.getString(1); if (dieselPrice.equals("0")) dieselPrice = "N.A"; String cngPrice = cursor.getString(2); if (cngPrice.equals("0")) cngPrice = "N.A"; fuelPricesDetails.put("petrolPrice", petrolPrice); fuelPricesDetails.put("dieselPrice", dieselPrice); fuelPricesDetails.put("cngPrice", cngPrice); } } catch (Exception ex) { } return fuelPricesDetails; } public ArrayList<String> getVehiclesList() { ArrayList<String> vehiclesList = new ArrayList<String>(); try { // Select All Query String selectQuery = "SELECT " + NAME + " FROM " + TABLE_VEHICLES; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { String vehicleName = cursor.getString(0); // Adding vehicle to list vehiclesList.add(vehicleName); } while (cursor.moveToNext()); } } catch (Exception ex) { } return vehiclesList; } public boolean addVehicle(String name, String fuelType, String baseOdoReading, int regionId, String regNumber, double expecMileage) { try { SQLiteDatabase db = this.getWritableDatabase(); double fuelPrice = 0.0; String selectQuery = "SELECT * FROM " + TABLE_FUELPRICES + " WHERE " + ID + "=" + regionId; Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { if (fuelType.toLowerCase().equals("petrol")) fuelPrice = cursor.getDouble(2); else if (fuelType.toLowerCase().equals("diesel")) fuelPrice = cursor.getDouble(3); else if (fuelType.toLowerCase().equals("cng")) fuelPrice = cursor.getDouble(4); } ContentValues values = new ContentValues(); values.put(ID, r.nextInt()); values.put(BASE_ODO_READING, baseOdoReading); values.put(NAME, name); values.put(REGN_NO, regNumber); values.put(REGION_ID, regionId); values.put(FUEL_TYPE, fuelType); values.put(PREVIOUS_REFILL_ODO_READING, baseOdoReading); values.put(FUEL_PRICE, fuelPrice); values.put(EXPECTED_MILEAGE, expecMileage); // Inserting Row db.insert(TABLE_VEHICLES, null, values); return true; // now the vehicle has been added in the Vehicle table, we need to make an entry to another table too. } catch (Exception ex) { } return false; } public boolean addEntry(int vehicleId, int prevReading, int currReading, double fuelAmt, String date, double mileage, double fuelPrice) { try { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(VEHICLE_ID, vehicleId); values.put(PREV_ODO_READING, prevReading); values.put(CURR_ODO_READING, currReading); values.put(FUEL_AMOUNT, fuelAmt); values.put(REFILL_DATE, date); values.put(MILEAGE, mileage); values.put(FUEL_PRICE, fuelPrice); // Inserting Row db.insert(TABLE_ENTRIES, null, values); String updateQuery = "Update " + TABLE_VEHICLES + " Set " + PREVIOUS_REFILL_ODO_READING + "=" + currReading + " Where " + ID + "=" + vehicleId; db.execSQL(updateQuery); return true; } catch (Exception ex) { } return false; } public boolean updateVehicleFuelPrice(double updatedFuelPrice, int vehicleId) { try { SQLiteDatabase db = this.getWritableDatabase(); String updateQuery = "Update " + TABLE_VEHICLES + " Set " + FUEL_PRICE + "=" + updatedFuelPrice + " Where " + ID + "=" + vehicleId; db.execSQL(updateQuery); return true; // Now the vehicle fuel prices have been updated for the corresponding vehicle. // TODO : should we set this updated price for the whole state(region) or not? } catch (Exception ex) { } return false; } public boolean updateRegionFuelPrices(double petrolPrice, double dieselPrice, double cngPrice, int regionId) { try { SQLiteDatabase db = this.getWritableDatabase(); String updateQuery = "Update " + TABLE_FUELPRICES + " Set " + PETROL_PRICE + "=" + petrolPrice + "," + DIESEL_PRICE + "=" + dieselPrice + "," + CNG_PRICE + "=" + cngPrice + " Where " + ID + "=" + regionId; db.execSQL(updateQuery); return true; } catch (Exception ex) { } return false; } }
/* (c) Julian Vera & Nathan S. Andersen * CS 136 Spring 2015 * Lab Section 12 - 2 * Lab 4 * */ import java.util.Comparator; /* * This StudentVowelComparator class provides a way to compare * the number of vowels in the names of two Students. Comparators * are an essential part of the sorting method found in the MyVector * class. */ public class StudentVowelComparator implements Comparator<Student> { public int compare(Student one, Student two) { // First, we take the entire names of both students // and save them as 'a' and 'b'. Important: the // names will be put togther as firstNamelastName, // without a space in between. String a = one.getFirstName() + one.getLastName(); String b = two.getFirstName() + two.getLastName(); // We will also create local int variables to store // the number of vowels in each name, which will // be compared at the end. int vowelCountA = 0; int vowelCountB = 0; // This next String 'characters' simply contains // all the vowels. String characters = "aeiouy"; // These next two loops simply iterate through the // two Student names, 'a' and 'b', and call the // String method 'contains' on the characters // String to see if the character at the current // position is a vowel or not. for (int x = 0; x < a.length(); x++) { if (characters.contains("" + a.charAt(x))) { vowelCountA++; } } for (int x = 0; x < b.length(); x++) { if (characters.contains("" + b.charAt(x))) { vowelCountB++; } } if (vowelCountA > vowelCountB) { return 1; } else if (vowelCountA < vowelCountB) { return -1; } else { return 0; } } }
package com.ojas.rpo.security.entity; import java.sql.Blob; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.codehaus.jackson.map.annotate.JsonView; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type; import com.ojas.rpo.security.JsonViews; @Table(name = "candidate") @javax.persistence.Entity public class Candidate implements Entity { private static final long serialVersionUID = 1L; @Id @GenericGenerator(name = "candidate_id", strategy = "com.ojas.rpo.security.util.CandidateIdGenerator") @GeneratedValue(generator = "candidate_id") private Long id; @Column private Date date; @Column private String title; @Column private String status; @Column private String street1; @Column private String street2; @Column private String candidateSource; @Column private String altenateEmail; @Column private String alternateMobile; private String profileDate; @Column private String firstName; @Column private String lastName; @Column private String mobile; @Column private String email; @Column private String gender; @Column private String totalExperience; @Column private String relevantExperience; @Column private String currentCTC; @Column private String expectedCTC; @Column private String salaryNegotiable; @Column private String noticePeriod; @Column private String pincode; @Column private String city; @Column private String country; @Column private String state; @Column private String willingtoRelocate; @Column private String skypeID; @Column private String currentJobType; @Column private String payRollCompanyName; @Column private String currentCompanyName; private String pancardNumber; @Column private String certificationscheck; @Column private String filename; @Column private String resume; @Column private byte[] _10thMarkmemo; @Column private String _12thMarkmemo; @Column private String highestMarkmemo; @Column private String latestSalaryslips; @Column private String salaryCertificates; @Column private String bankStatements; @Column private String birthCertificate; @Column private String form16Certificate; @Column private Date doj; @ManyToOne private User user; private Date submissionDate; private Date statusLastUpdatedDate; private String noOfMonths; private String appliedPossitionFor; private String applyingAs; private String currentLocation; // @Column // private String otherSkils; // // // // public String getOtherSkils() { // return otherSkils; // } // // public void setOtherSkils(String otherSkils) { // this.otherSkils = otherSkils; // } @ManyToOne private Location location; public String getCurrentLocation() { return currentLocation; } public void setCurrentLocation(String currentLocation) { this.currentLocation = currentLocation; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public String getAppliedPossitionFor() { return appliedPossitionFor; } public void setAppliedPossitionFor(String appliedPossitionFor) { this.appliedPossitionFor = appliedPossitionFor; } public String getApplyingAs() { return applyingAs; } public void setApplyingAs(String applyingAs) { this.applyingAs = applyingAs; } public String getNoOfMonths() { return noOfMonths; } public void setNoOfMonths(String noOfMonths) { this.noOfMonths = noOfMonths; } public Date getStatusLastUpdatedDate() { return statusLastUpdatedDate; } public void setStatusLastUpdatedDate(Date statusLastUpdatedDate) { this.statusLastUpdatedDate = statusLastUpdatedDate; } @Column @Type(type = "org.hibernate.type.StringClobType") private String resumeData; @ManyToMany @JoinTable(name = "skillcandidate", joinColumns = @JoinColumn(name = "candidate_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "SKILL_ID", referencedColumnName = "ID")) private List<Skill> skills = new ArrayList<Skill>(); @ManyToMany @JoinTable(name = "candidateCertificatesMap", joinColumns = @JoinColumn(name = "candidate_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "certificate_ID", referencedColumnName = "ID")) private List<Certificate> certificates = new ArrayList<Certificate>(); @ManyToMany @JoinTable(name = "candidateEducationMap", joinColumns = @JoinColumn(name = "candidate_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "education_ID", referencedColumnName = "ID")) private List<AddQualification> education = new ArrayList<AddQualification>(); public Date getSubmissionDate() { return submissionDate; } public void setSubmissionDate(Date submissionDate) { this.submissionDate = submissionDate; } public static long getSerialversionuid() { return serialVersionUID; } public String getStreet1() { return street1; } public void setStreet1(String street1) { this.street1 = street1; } public String getStreet2() { return street2; } public void setStreet2(String street2) { this.street2 = street2; } public void set_10thMarkmemo(byte[] _10thMarkmemo) { this._10thMarkmemo = _10thMarkmemo; } public String getAltenateEmail() { return altenateEmail; } public void setAltenateEmail(String altenateEmail) { this.altenateEmail = altenateEmail; } public String getAlternateMobile() { return alternateMobile; } public void setAlternateMobile(String alternateMobile) { this.alternateMobile = alternateMobile; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getProfileDate() { return profileDate; } public void setProfileDate(String profileDate) { this.profileDate = profileDate; } public String getResumeData() { return resumeData; } public void setResumeData(String resumeData) { this.resumeData = resumeData; } public String getCandidateSource() { return candidateSource; } public void setCandidateSource(String candidateSource) { this.candidateSource = candidateSource; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getResume() { return resume; } public void setResume(String resume) { this.resume = resume; } public Candidate() { this.date = new Date(); } @JsonView(JsonViews.Admin.class) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @JsonView(JsonViews.User.class) public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } @JsonView(JsonViews.User.class) public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @JsonView(JsonViews.User.class) public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @JsonView(JsonViews.User.class) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @JsonView(JsonViews.User.class) public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } @JsonView(JsonViews.User.class) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @JsonView(JsonViews.User.class) public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @JsonView(JsonViews.User.class) public String getTotalExperience() { return totalExperience; } public void setTotalExperience(String totalExperience) { this.totalExperience = totalExperience; } @JsonView(JsonViews.User.class) public String getRelevantExperience() { return relevantExperience; } public void setRelevantExperience(String relevantExperience) { this.relevantExperience = relevantExperience; } @JsonView(JsonViews.User.class) public String getCurrentCTC() { return currentCTC; } public void setCurrentCTC(String currentCTC) { this.currentCTC = currentCTC; } @JsonView(JsonViews.User.class) public String getExpectedCTC() { return expectedCTC; } public void setExpectedCTC(String expectedCTC) { this.expectedCTC = expectedCTC; } @JsonView(JsonViews.User.class) public String getSalaryNegotiable() { return salaryNegotiable; } public void setSalaryNegotiable(String salaryNegotiable) { this.salaryNegotiable = salaryNegotiable; } @JsonView(JsonViews.User.class) public String getNoticePeriod() { return noticePeriod; } public void setNoticePeriod(String noticePeriod) { this.noticePeriod = noticePeriod; } @JsonView(JsonViews.User.class) public String getPincode() { return pincode; } public void setPincode(String pincode) { this.pincode = pincode; } @JsonView(JsonViews.User.class) public String getWillingtoRelocate() { return willingtoRelocate; } public void setWillingtoRelocate(String willingtoRelocate) { this.willingtoRelocate = willingtoRelocate; } @JsonView(JsonViews.User.class) public String getSkypeID() { return skypeID; } public void setSkypeID(String skypeID) { this.skypeID = skypeID; } @JsonView(JsonViews.User.class) public String getCurrentJobType() { return currentJobType; } public void setCurrentJobType(String currentJobType) { this.currentJobType = currentJobType; } @JsonView(JsonViews.User.class) public String getPayRollCompanyName() { return payRollCompanyName; } public void setPayRollCompanyName(String payRollCompanyName) { this.payRollCompanyName = payRollCompanyName; } @JsonView(JsonViews.User.class) public String getCurrentCompanyName() { return currentCompanyName; } public void setCurrentCompanyName(String currentCompanyName) { this.currentCompanyName = currentCompanyName; } @JsonView(JsonViews.User.class) public String getPancardNumber() { return pancardNumber; } public void setPancardNumber(String pancardNumber) { this.pancardNumber = pancardNumber; } @JsonView(JsonViews.User.class) public String getCertificationscheck() { return certificationscheck; } public void setCertificationscheck(String certificationscheck) { this.certificationscheck = certificationscheck; } @JsonView(JsonViews.User.class) public String getCity() { return city; } public void setCity(String city) { this.city = city; } @JsonView(JsonViews.User.class) public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @JsonView(JsonViews.User.class) public String getState() { return state; } public void setState(String state) { this.state = state; } public List<Skill> getSkills() { return skills; } public void setSkills(List<Skill> skills) { this.skills = skills; } public List<Certificate> getCertificates() { return certificates; } public void setCertificates(List<Certificate> certificates) { this.certificates = certificates; } public List<AddQualification> getEducation() { return education; } public void setEducation(List<AddQualification> education) { this.education = education; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public byte[] get_10thMarkmemo() { return _10thMarkmemo; } public String get_12thMarkmemo() { return _12thMarkmemo; } public void set_12thMarkmemo(String _12thMarkmemo) { this._12thMarkmemo = _12thMarkmemo; } public String getHighestMarkmemo() { return highestMarkmemo; } public void setHighestMarkmemo(String highestMarkmemo) { this.highestMarkmemo = highestMarkmemo; } public String getLatestSalaryslips() { return latestSalaryslips; } public void setLatestSalaryslips(String latestSalaryslips) { this.latestSalaryslips = latestSalaryslips; } public String getSalaryCertificates() { return salaryCertificates; } public void setSalaryCertificates(String salaryCertificates) { this.salaryCertificates = salaryCertificates; } public String getBankStatements() { return bankStatements; } public void setBankStatements(String bankStatements) { this.bankStatements = bankStatements; } public String getBirthCertificate() { return birthCertificate; } public void setBirthCertificate(String birthCertificate) { this.birthCertificate = birthCertificate; } public String getForm16Certificate() { return form16Certificate; } public void setForm16Certificate(String form16Certificate) { this.form16Certificate = form16Certificate; } public Date getDoj() { return doj; } public void setDoj(Date doj) { this.doj = doj; } }
package com.tencent.mm.plugin.gallery.ui; class ImageFolderMgrView$4 implements Runnable { final /* synthetic */ ImageFolderMgrView jDn; ImageFolderMgrView$4(ImageFolderMgrView imageFolderMgrView) { this.jDn = imageFolderMgrView; } public final void run() { ImageFolderMgrView.d(this.jDn).notifyDataSetChanged(); } public final String toString() { return super.toString() + "|onQueryAlbumFinished"; } }
/** * Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro * Copyright: 2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package seava.ad.presenter.impl.attachment.model; import seava.ad.domain.impl.attachment.Attachment; import seava.ad.domain.impl.attachment.AttachmentType; import seava.j4e.api.annotation.Ds; import seava.j4e.api.annotation.DsField; import seava.j4e.api.annotation.Param; import seava.j4e.api.annotation.RefLookup; import seava.j4e.api.annotation.RefLookups; import seava.j4e.presenter.impl.model.AbstractAuditable_Ds; @Ds(entity = Attachment.class) @RefLookups({@RefLookup(refId = Attachment_Ds.f_typeId, namedQuery = AttachmentType.NQ_FIND_BY_NAME, params = {@Param(name = "name", field = Attachment_Ds.f_type)})}) public class Attachment_Ds extends AbstractAuditable_Ds<Attachment> { public static final String ALIAS = "ad_Attachment_Ds"; public static final String f_targetRefid = "targetRefid"; public static final String f_targetAlias = "targetAlias"; public static final String f_targetType = "targetType"; public static final String f_name = "name"; public static final String f_location = "location"; public static final String f_contentType = "contentType"; public static final String f_url = "url"; public static final String f_typeId = "typeId"; public static final String f_type = "type"; public static final String f_category = "category"; public static final String f_baseUrl = "baseUrl"; @DsField private String targetRefid; @DsField private String targetAlias; @DsField private String targetType; @DsField private String name; @DsField private String location; @DsField private String contentType; @DsField(fetch = false) private String url; @DsField(join = "left", path = "type.id") private String typeId; @DsField(join = "left", path = "type.name") private String type; @DsField(join = "left", path = "type.category") private String category; @DsField(join = "left", path = "type.baseUrl") private String baseUrl; public Attachment_Ds() { super(); } public Attachment_Ds(Attachment e) { super(e); } public String getTargetRefid() { return this.targetRefid; } public void setTargetRefid(String targetRefid) { this.targetRefid = targetRefid; } public String getTargetAlias() { return this.targetAlias; } public void setTargetAlias(String targetAlias) { this.targetAlias = targetAlias; } public String getTargetType() { return this.targetType; } public void setTargetType(String targetType) { this.targetType = targetType; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getLocation() { return this.location; } public void setLocation(String location) { this.location = location; } public String getContentType() { return this.contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getUrl() { return this.url; } public void setUrl(String url) { this.url = url; } public String getTypeId() { return this.typeId; } public void setTypeId(String typeId) { this.typeId = typeId; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public String getCategory() { return this.category; } public void setCategory(String category) { this.category = category; } public String getBaseUrl() { return this.baseUrl; } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } }
///////////////////////// // Hello World in Java // ///////////////////////// class myClass { public static void main(String[] args){ System.out.println("Hello World"); } } - Every line of code written in Java that can run must be inside a 'class'. - The entry point to every Java application is a method called 'main'. - Definitions - public: anyone can access it - static: method can be run without creating an instance of the class containing the main method - void: method does not return a value - main: the name of the method. //////////// // ARRAYS // //////////// Array: A collection of variables of the same type. Declaration: * int[ ] arr = new int[5]; -> declares an array meant to hold 5 integers. Initializing: * String[ ] myNames = {"A", "B", "C", "D", "E"}; * System.out.println(myNames[2]) // Outputs: "C" - Initializing does not require a size specification as the array will auto-size to the amount of elements given to it on initialization. ///////////// // CLASSES // ///////////// Classes describe what an object will be. It is not the object but rather an object Blueprint Attributes and Behavior are defined in the blueprint - (class) to descibe the objects that can be made by using it - See METHODS ////////////////////// // CREATING CLASSES // ////////////////////// Syntax * public class Animal { * public void bark(){ * System.out.println("Woof Woof"); * } * } This created a class - (blueprint) called Animal with a public method called bark that outputs "Woof Woof" ////////////////// // CONDITIONALS // ////////////////// if - else if() - else: - Same structure as JS switch statements: - Same structure as JS /////////// // LOOPS // /////////// for: -Same as JS while: -Same as JS do while: -Same as JS enhanced for: ( Also called a 'forEach' ) Syntax * int[ ] numbers = {1, 2, 3, 4, 5} * for(int b: numbers){ * System.out.println(b) // 1 2 3 4 5 * } ///////////// // METHODS // ///////////// Methods define behavoir in a class. They are functions that can be `called` on an object instantiated with the class. - Methods are called with (). Such as ' add(2, 3);' Return Types: - You must declare the type of data the method is expecting to return, such as String, int, boolean, or void - void is used to declare the method should not return anything. /////////////////////////////////////// // OOP - OBJECT ORIENTED PROGRAMMING // /////////////////////////////////////// OOP: Java used OOP, a programming style that is intended to make thinking about programmin closer to thinking about the real world. - In OOP, each object is an indepenedent unit with a unique identity. - Objects have Characteristics also called Attributes that define what the object Is - Object Behavoir is defined by methods and describes what the Object Does /////////////// // OPERATORS // /////////////// Mathmatical Operators: +, -, *, /, %, ++n, n++, --n, n--, +=, -=, *=, /= ++n used to increment 'n'by one and store that new num in a var. n++ used to assign value of 'n' to var, then increment 'n' by one. Logical Operators: &&, ||, ==, !, != //////////// // OUTPUT // //////////// System (class): * - System.out.println("String to print to console."); ///////////// // STRINGS // ///////////// String: An Object that represents a sequence of characters. "Hello" is a string of 5 characters for example. Declaration: String myStr = "Nate" Concatenation: * String a = "Hello"; * String b = "World"; * System.out.println(a + " " + b); // "Hello World" //////////////// // USER INPUT // //////////////// Scanner (object): - The 'Scanner' object in Java is the most commonly used Java method for getting user input. - Must Import the Scanner object to use its methods: * import java.util.Scanner; - Must create a instance of Scanner obj to use it: * Scanner myVar = new Scanner(System.in); - Some other Scanner methods available: nextByte() = Read a byte nextShort() = Read a short nextInt() = Read an int nextLong() = Read a long nextFloat() = Read a float nextDouble() = Read a double nextBoolean() = Read a boolean nextLine() = Read a complete line next() = Read a word Example of getting user input: * import java.util.Scanner; * * class MyClass { * public static void main(String[ ] args){ * Scanner myVar = new Scanner(System.in); * System.out.println(myVar.nextLine()); * } /////////////// // VARIABLES // /////////////// Types: - int: for integers(whole numbers) such as 123 or 456. - double: for floating-point or real numbers with optional decimal points and fractional parts - String: for texts such as "Hello" - boolean: for true/false values only. Syntax: * int num = 20; * String name = "Nate";
package com.dishcuss.foodie.hub.Fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.dishcuss.foodie.hub.Adapters.PhotosAdapter; import com.dishcuss.foodie.hub.Models.FoodItems; import com.dishcuss.foodie.hub.Models.PhotoModel; import com.dishcuss.foodie.hub.Models.Restaurant; import com.dishcuss.foodie.hub.R; import java.util.ArrayList; import io.realm.Realm; import io.realm.RealmList; import io.realm.RealmResults; /** * Created by Naeem Ibrahim on 7/25/2016. */ public class RestaurantPhotosFragment extends Fragment { AppCompatActivity activity; RecyclerView nearbySearchRecyclerView; private GridLayoutManager gridLayout; ArrayList<String> itemsData = new ArrayList<>(); int restaurantID; public RestaurantPhotosFragment() { } public RestaurantPhotosFragment(int restaurantID) { this.restaurantID=restaurantID; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.simple_recycler_view_for_all, container, false); activity = (AppCompatActivity) getActivity(); gridLayout = new GridLayoutManager(getActivity(),3); nearbySearchRecyclerView = (RecyclerView) rootView.findViewById(R.id.simple_recycler_view_for_all); nearbySearchRecyclerView.setLayoutManager(gridLayout); nearbySearchRecyclerView.setHasFixedSize(true); SetImageURL(); nearbySearchRecyclerView.setNestedScrollingEnabled(false); PhotosAdapter adapter = new PhotosAdapter(itemsData,getActivity()); nearbySearchRecyclerView.setAdapter(adapter); return rootView; } void SetImageURL(){ Realm realm = Realm.getDefaultInstance(); RealmResults<Restaurant> restaurants = realm.where(Restaurant.class).equalTo("id", restaurantID).findAll(); realm.beginTransaction(); RealmList<FoodItems> foodItems =restaurants.get(restaurants.size()-1).getFoodItemsArrayList(); for(int i=0;i<foodItems.size();i++){ RealmList<PhotoModel> photoModels=foodItems.get(i).getPhotoModels(); // Log.e("photoModels : ",""+photoModels.size()); // if(photoModels.size()>7){ // for (int j = 0; j <7; j++) { // if (!photoModels.get(j).getUrl().equals("")) { // itemsData.add(photoModels.get(j).getUrl()); // } // } // } // else // { // for (int j = 0; j < photoModels.size(); j++) { // if (!photoModels.get(j).getUrl().equals("")) { // itemsData.add(photoModels.get(j).getUrl()); // } // } // } for (int j=0;j<photoModels.size();j++){ if(!photoModels.get(j).getUrl().equals("")) { itemsData.add(photoModels.get(j).getUrl()); } } } realm.commitTransaction(); realm.close(); } }
package Threads; import java.util.*; /** * Created by Admin on 23-10-2016. */ public class Synchronize_4 extends Thread{ private String info; private Vector aVector = new Vector(); /* if this is changed to static, it will work, since it will be using same aVector. But now it wont work since new aVector will be created for different objects*/ public Synchronize_4 (String info) { this.info = info; } public void inProtected () { synchronized ( aVector ) { System.err.println(info + ": is in protected()"); try { sleep(3000); } catch ( InterruptedException e ) { System.err.println("Interrupted!"); } System.err.println(info + ": exit run"); } } public void run () { inProtected(); } public static void main (String args []) { Synchronize_4 aT5_0 = new Synchronize_4("first"); Synchronize_4 aT5_1 = new Synchronize_4("second"); aT5_0.start(); aT5_1.start(); } }
package pl.czyzycki.towerdef.menus; import pl.czyzycki.towerdef.TowerDef; import pl.czyzycki.towerdef.TowerDef.GameSound; import pl.czyzycki.towerdef.gameplay.GameplayScreen; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Preferences; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.ui.ClickListener; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.Table; import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.TableLayout; import com.esotericsoftware.tablelayout.Cell; /** * Ekran wyboru mapki rozgrywki. * */ public class SelectLevelScreen extends MenuBaseScreen { class LevelInfo { int stars; } public LevelInfo []levelInfos = null; private int selectedLevel = 0; public SelectLevelScreen(TowerDef game) { super(game, false); } void setLevelInfos() { Preferences prefs = Gdx.app.getPreferences("stars"); levelInfos = new LevelInfo[5]; for(int i=0; i<5; i++) levelInfos[i] = new LevelInfo(); levelInfos[0].stars = prefs.getInteger("level-"+0, 0);; levelInfos[1].stars = prefs.getInteger("level-"+1, 0);; levelInfos[2].stars = prefs.getInteger("level-"+2, 0);; levelInfos[3].stars = prefs.getInteger("level-"+3, 0);; levelInfos[4].stars = prefs.getInteger("level-"+4, 0);; } @Override public void resize(int width, int height) { super.resize(width, height); setLevelInfos(); Skin skin = getSkin(); Table table = new Table(skin); table.width = stage.width(); table.height = stage.height(); stage.addActor(table); TableLayout layout = table.getTableLayout(); layout.parse("* spacing:5"); Label caption = new Label("Wybierz poziom", skin); Cell<Actor> captionCell = layout.add(caption); captionCell.align("center"); captionCell.colspan(5); captionCell.spaceBottom(30); layout.row(); for(int i=0; levelInfos!=null && i<levelInfos.length; i++) { LevelInfo info = levelInfos[i]; TextButton level1 = new TextButton("Poziom "+(i+1), skin); class LevelClickListener implements ClickListener { private int levelId = 0; public LevelClickListener(int level) { levelId = level; } @Override public void click(Actor actor, float x, float y) { game.playSound(GameSound.CLICK); selectedLevel = levelId; GameplayScreen gameplayScreen = game.getGameplayScreen(); gameplayScreen.loadMap("lvl"+levelId); game.setScreen(gameplayScreen); } } level1.setClickListener(new LevelClickListener(i)); level1.width(195); layout.add(level1); Cell<Actor> nullCell = layout.add(null); nullCell.width(40); for(int j=0; j<3; j++) { Image img; if(j<info.stars) img = new Image(game.getAssetManager().get("layouts/star.png", Texture.class)); else img = new Image(game.getAssetManager().get("layouts/starslot.png", Texture.class)); layout.add(img); } layout.row(); } TextButton exitButton = new TextButton("Wstecz", skin); exitButton.setClickListener( new ClickListener() { @Override public void click(Actor actor, float x, float y ) { game.playSound(GameSound.CLICK); game.setScreen(game.getMainMenuScreen()); } } ); exitButton.width(300); Cell<Actor> backCell = layout.add(exitButton); backCell.colspan(5); backCell.spaceTop(30); } @Override public void backDown() { Gdx.app.exit(); } // Pierwszy level=0, drugi=1, ... public int getSelectedLevel() { return selectedLevel; } public void nextLevel() { if(++selectedLevel >= levelInfos.length) selectedLevel = 0; } }
package com.nuuedscore.dto; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.extern.slf4j.Slf4j; /** * ACT Token * * @author PATavares * @since May 2021 * */ @Slf4j @Data public class ACTToken { @JsonProperty("access_token") private String accessToken; @JsonProperty("scope") private String scope; @JsonProperty("expires_in") private String expiresIn; @JsonProperty("token_type") private String tokenType; }
/* * 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 oopproject; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JPanel; import static oopproject.Oopproject.frAme; import static oopproject.Oopproject.height; import static oopproject.Oopproject.width; public class gammeplay extends JPanel { static boolean ballcontrol = false; private int mousex; boolean running ; private BufferedImage image;//store image in memory // private BufferedImage img; Image img; Image ballimg; Image img2; Image img3; Image img4; Image img5; private Graphics2D g; // this graphics object is for drawing on the Buffered Image private ball theball; private paddel pad; public bricks map ; public static int count;//to test the levels player player; public static int levelcount=1 ; private int mousexdir; private mouselis mouse; private Sound s; boolean checker = true; public enemy enem; public static boolean endlevelPU=false; private boolean enemyend; public gammeplay() throws IOException { this.setVisible(true); img = Toolkit.getDefaultToolkit().createImage("level1.jpg"); img2 = Toolkit.getDefaultToolkit().createImage("level2.jpg"); img3 = Toolkit.getDefaultToolkit().createImage("level3.jpg"); img4 = Toolkit.getDefaultToolkit().createImage("level4.jpg"); img5 = Toolkit.getDefaultToolkit().createImage("level5.jpg"); // ballimg = Toolkit.getDefaultToolkit().createImage("ball5.jpg"); initail(); s=new Sound("sound\\bensound-slowmotion_2.wav"); s.playSound(); count=0; } public void initail() throws IOException { running= true; // BufferedImage image = ImageIO.read(new File("C:\\Users\\LENOVO\\Desktop\\screen shut\\project3.jpg")); image = new BufferedImage(Oopproject.width, Oopproject.height,BufferedImage.TYPE_INT_RGB); g =image.createGraphics(); //(Graphics2D)image.getGraphics(); // map=new bricks(6,7);////// //map =new bricks(7,8); theball = new ball(); pad = new paddel(); mouse = new mouselis(); addMouseMotionListener(mouse);//intialize motion of mouse g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); enem = new enemy (); } public void run() throws IOException, InterruptedException { // game main Thread thread =new Thread(); boolean enemystart= true; while(running){ if(levelcount >=6){running = false; break; } // music(); s.playSound(); updata(); draw(); repaint();//subcalss in jpanel if(enem.checkbricks()) enemystart=true ; try{ Thread.sleep(10); } catch (InterruptedException ex) { Logger.getLogger(gammeplay.class.getName()).log(Level.SEVERE, null, ex); } if(map.checkbricks()&&enemystart) { if(levelcount == 1){ player = new player(adddata.pname, count); player.add(); } else{ player.update(adddata.pname, count); } for (int i=0;i<1;i++) { thread.sleep(500); } levelcount++; levels(); if (levelcount==5){ enemystart=false; if(enemystart){ player.update(adddata.pname, count); enemy.gameend=true ; } } } } if(!running){ System.out.println("eee"); Oopproject.frAme.dispose(); won_lose neww= new won_lose(); neww.setVisible(true); } } public void updata() throws InterruptedException { theball.checkcol(pad, map, mousex, enem); if (ballcontrol){ theball.update();} map.PUupdate(); if(endlevelPU){ map.EndlevelPU(); endlevelPU=false; } if(levelcount == 5){ enem.updatepos();} } public void draw(){ g.setColor(Color.DARK_GRAY); g.fillRect(0, 0, Oopproject.width, Oopproject.height); switch(levelcount) { case 1: { g.drawImage(img,0,0,null); break; } case 2: { g.drawImage(img2,0,0,null); break; } case 3: { g.drawImage(img3,0,0,null); break; } case 4: { g.drawImage(img4,0,0,null); break; } case 5: { g.drawImage(img5,0,0,null); break; } } theball.draw(g); pad.draw(g); map.PUdraw(g); map.draw(g); g.setColor(Color.WHITE); g.setFont(new Font("serif",Font.ITALIC,25)); g.drawString("score : "+count, 650, 30); g.setColor(Color.WHITE); g.setFont(new Font("serif",Font.ITALIC,25)); g.drawString("level : "+levelcount, 30, 30); g.setColor(Color.WHITE); g.setFont(new Font("serif",Font.ITALIC,25)); g.drawString("lifes : "+paddel.lifes, 350, 30); if(levelcount ==5){ enem.draw(g); } } //this methd is for painint on Jpanel @Override public void paintComponent(Graphics g) { super.paintComponent(g); //g: is a graphics component for drawinng in Jpanel //g.fillRect(0, 0, Oopproject.width, Oopproject.height); draw(); g.drawImage(image, 0, 0, this); } private class mouselis implements MouseMotionListener{ @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { mousex= e.getX(); pad.mousemove(e.getX()); } } public void levels() { theball.setballpostion(theball.intialxpos, theball.intialypos); int level=levelcount ; switch(level) { case 1: { map =new bricks(3,3); map.draw(g); break; } case 2: { map.PUdisable(); map=new bricks(4, 4); map.draw(g); break; } case 3: { map.PUdisable(); map =new bricks(4,5); map.draw(g); break; } case 4: { map.PUdisable(); map =new bricks(6,6); map.draw(g); break ; } case 5: { map.PUdisable(); enem.createmap(1, 1); break; } default: { break; } }} // public boolean winthegame() // { // if(enemyend) // return true ; // else // return false ; // // } }
package com.voksel.electric.pc.repository.search; import com.voksel.electric.pc.domain.entity.Form; import com.voksel.electric.pc.domain.entity.User; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Created by edsarp on 8/21/16. */ public interface FormSearchRepository extends ElasticsearchRepository<Form,String> { }
package com.findthewaygame.mygdx.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public class MainInterface { public MainGame Main; public String Status; public SpriteBatch TextSprite = new SpriteBatch(); //public Texture TestSize36 = new Texture("Text_Test_Size36.png"); //public Texture TestSize40 = new Texture("Text_Test_Size40.png"); // Screen Width = 1200 Height = 700 // 1 cm = 28.4 pi // width = 13.8 cm private Texture StartGame = new Texture("Text_StartGame_Size40.png"); private Texture ChooseMap = new Texture("Text_ChooseMap_Size40.png"); private Texture GreenCircle = new Texture("GreenCircle.png"); // width = 15.2 private Texture PressRight = new Texture("Text_PressRight_Size32.png"); private int Point = 0; private float MiddleScreen; public MainInterface(MainGame Main) { this.Main = Main; this.Status = "MainInterface"; this.MiddleScreen = this.Main.width/2; } public void Draw() { this.Checkkey(); if(this.Status == "MainInterface") { System.out.println("This is in draw MainInterface"); this.TextSprite.begin(); //this.TextSprite.draw(this.TestSize36,200,200); //this.TextSprite.draw(this.TestSize40,200,160); this.TextSprite.draw(this.StartGame, (float)(this.MiddleScreen - (13.8*14.2)), (float)(450)); this.TextSprite.draw(this.ChooseMap, (float)(this.MiddleScreen - (13.8*14.2)), (float)(250)); if(this.Point == 0) this.TextSprite.draw(this.GreenCircle, (float)(this.MiddleScreen -(13*14.2)), (float)(465)); else this.TextSprite.draw(this.GreenCircle, (float)(this.MiddleScreen - (13.7*14.2)), (float)(330)); this.TextSprite.draw(PressRight, (float)(this.Main.width-(15.5*28.4)), (float)10); this.TextSprite.end(); } } private void Checkkey() { if(this.Status == "MainInterface") if(Gdx.input.isKeyJustPressed(Keys.UP)) this.Point = (this.Point - 1)%2; else if(Gdx.input.isKeyJustPressed(Keys.DOWN)) this.Point = (this.Point + 1)%2; else if(Gdx.input.isKeyJustPressed(Keys.RIGHT)) if(this.Point == 0) { //this.Main.NumMap = 0; this.Main.StateGame = "GameRunning"; this.Main.create(); this.dispose(); } } private void dispose() { this.PressRight.dispose(); this.StartGame.dispose(); this.ChooseMap.dispose(); this.GreenCircle.dispose(); } }
package jc.sugar.JiaHui.jmeter.postprocessor; import jc.sugar.JiaHui.jmeter.*; import org.apache.jmeter.extractor.json.jsonpath.JSONPostProcessor; import java.util.HashMap; import java.util.Map; import static org.apache.jorphan.util.Converter.getBoolean; import static org.apache.jorphan.util.Converter.getString; @JMeterElementMapperFor(value = JMeterElementType.JSONPostProcessor, testGuiClass = JMeterElement.JSONPostProcessor) public class JSONPostProcessorMapper extends AbstractJMeterElementMapper<JSONPostProcessor> { public static final String WEB_REFERENCE_NAMES = "referenceNames"; public static final String WEB_JSON_PATH_EXPRS = "jsonPathExprs"; public static final String WEB_MATCH_NUMBERS = "matchNumbers"; public static final String WEB_DEFAULT_VALUES = "defaultValues"; public static final String WEB_COMPUTE_CONCAT = "computeConcat"; private JSONPostProcessorMapper(JSONPostProcessor element, Map<String, Object> attributes) { super(element, attributes); } public JSONPostProcessorMapper(Map<String, Object> attributes){ this(new JSONPostProcessor(), attributes); } public JSONPostProcessorMapper(JSONPostProcessor element){ this(element, new HashMap<>()); } @Override public JSONPostProcessor fromAttributes() { element.setRefNames(getString(attributes.get(WEB_REFERENCE_NAMES))); element.setJsonPathExpressions(getString(attributes.get(WEB_JSON_PATH_EXPRS))); element.setMatchNumbers(getString(attributes.get(WEB_MATCH_NUMBERS))); element.setDefaultValues(getString(attributes.get(WEB_DEFAULT_VALUES))); element.setComputeConcatenation(getBoolean(attributes.get(WEB_COMPUTE_CONCAT))); return element; } @Override public Map<String, Object> toAttributes() { attributes.put(WEB_CATEGORY, JMeterElementCategory.Postprocessor); attributes.put(WEB_TYPE, JMeterElementType.JSONPostProcessor); attributes.put(WEB_REFERENCE_NAMES, element.getRefNames()); attributes.put(WEB_JSON_PATH_EXPRS, element.getJsonPathExpressions()); attributes.put(WEB_MATCH_NUMBERS, element.getMatchNumbers()); attributes.put(WEB_DEFAULT_VALUES, element.getDefaultValues()); attributes.put(WEB_COMPUTE_CONCAT, element.getComputeConcatenation()); return attributes; } }
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Room> roomsList = new ArrayList<>(); Room room1 = new Room("001"); Room room2 = new Room("002"); Room room3 = new Room("003"); roomsList.add(room1); roomsList.add(room2); roomsList.add(room3); Scheduler scheduler =new Scheduler(roomsList); System.out.println(scheduler.book(1,2,5)); //001 System.out.println(scheduler.book(1,5,8)); //001 System.out.println(scheduler.book(1,9,10)) ; //002 System.out.println(scheduler.book(1,11,12)) ; //003 System.out.println(scheduler.book(1,7,8)) ; //003 System.out.println(scheduler.book(1,11,12)) ; //001 } }
package com.example.gastos; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class IntroductionActivity extends Activity { Button loginButton, helpButton; EditText passwordText; String password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_introduction); loginButton = (Button) findViewById(R.id.loginButton); helpButton = (Button) findViewById(R.id.ayudaButton); passwordText = (EditText) findViewById(R.id.contrasenaEdit); loginButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if(passwordText.getText().toString().equals("admin")){ Intent myIntent = new Intent(v.getContext(), MainActivity.class); startActivityForResult(myIntent,0); } else { Toast.makeText(getBaseContext(), "Contraseña incorrecta!",Toast.LENGTH_LONG).show(); passwordText.setText(""); } } }); helpButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(v.getContext(), AyudaActivity.class); startActivityForResult(myIntent,0); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.introduction, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void onBackPressed() { Intent startMain = new Intent(Intent.ACTION_MAIN); startMain.addCategory(Intent.CATEGORY_HOME); startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(startMain); } }
package GUI; import Algorithm.MyAlgorithm; import Algorithm.QuestionState; import Algorithm.Arithemic.Subtraction; import Calculator.CalculatorPrevention; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.font.TextAttribute; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class MyCanvas { private final String TITLE = "Practice Exercise"; private final int MAX_INCORRECT = 5; private final int QUESTION_GOAL = 60; private final String PASS = "Nice Angel Cider"; private final int INITIAL_MAX_RANDOM_RANGE = 5; private final int NUM_CHARS_ANSWER = 5; private final int calcTimer = 1000; private STATE s = STATE.IN_GAME; private CORRECTNESS correctnessFlag = CORRECTNESS.CORRECT; private CheckboxGroup percentIncDec = new CheckboxGroup(); private Checkbox increaseCheckBox = new Checkbox("Increase", percentIncDec, false); private Checkbox decreaseCheckBox = new Checkbox("Decrease", percentIncDec, false); private Canvas canvas; private Frame mainFrame; private Panel controlPanel = new Panel(); private Panel percentIncreaseDecreasePlaceHolder = new Panel(); private Panel percentIncreaseDecreasePanel = new Panel(); private Panel fractionPlaceHolder = new Panel(); private Panel fractionPanel = new Panel(); private JTextField ans = new JTextField(NUM_CHARS_ANSWER); private JTextField numer = new JTextField(NUM_CHARS_ANSWER); private JTextField denom = new JTextField(NUM_CHARS_ANSWER); private Panel answerPanel = new Panel(); private int numQuestionSoFar = 0; private int maxRandomRange = INITIAL_MAX_RANDOM_RANGE; private int incorrectScore = 0; private String currQuestion = ""; private String prevQuestion = ""; private String correctness = ""; private String answer = ""; private String incorrectScoreText = "Incorrect: 0/5"; private MyAlgorithm operation = new Subtraction(); private CalculatorPrevention c = new CalculatorPrevention(this, calcTimer); public MyCanvas() { mainFrame = new Frame(); mainFrame.setTitle(TITLE); mainFrame.setLayout(new BorderLayout()); mainFrame.setSize(750, 500); mainFrame.add(controlPanel, BorderLayout.CENTER); controlPanel.add(canvas = new MyMiniCanvas()); InitialAnswerPanel(); mainFrame.add(answerPanel, BorderLayout.SOUTH); mainFrame.setBackground(Color.WHITE); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent) { System.exit(0); } }); mainFrame.setVisible(true); mainFrame.setResizable(false); try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } // percentIncreaseDecreasePlaceHolder.setVisible(false); setUpQuestion(); } private void InitialAnswerPanel() { // Answer Panel // Answer Box Panel answerPlaceHolder = new Panel(new FlowLayout()); answerPlaceHolder.add(new JLabel("Answer:")); ans.setHorizontalAlignment(JTextField.CENTER); numer.setHorizontalAlignment(JTextField.CENTER); denom.setHorizontalAlignment(JTextField.CENTER); answerPlaceHolder.add(ans); answerPanel.add(answerPlaceHolder); // Increase/Decrease Radio Button percentIncreaseDecreasePlaceHolder.setLayout(new FlowLayout()); percentIncreaseDecreasePanel.setLayout(new GridLayout(2, 1)); percentIncreaseDecreasePanel.add(increaseCheckBox); percentIncreaseDecreasePanel.add(decreaseCheckBox); percentIncreaseDecreasePlaceHolder.add(percentIncreaseDecreasePanel); fractionPlaceHolder.setLayout(new FlowLayout()); fractionPanel.setLayout(new GridLayout(2, 1)); fractionPanel.add(numer); fractionPanel.add(denom); fractionPlaceHolder.add(fractionPanel); JButton submit = new JButton("Submit"); percentIncreaseDecreasePlaceHolder.add(submit); submit.addActionListener(new MyActionListener()); // answerPanel.add(percentIncreaseDecreasePlaceHolder); ans.addActionListener(new MyActionListener()); numer.addActionListener(new MyActionListener()); denom.addActionListener(new MyActionListener()); ans.addKeyListener(new MyKeyAdapter()); numer.addKeyListener(new MyKeyAdapter()); denom.addKeyListener(new MyKeyAdapter()); ans.setFocusTraversalKeysEnabled(true); numer.setFocusTraversalKeysEnabled(true); denom.setFocusTraversalKeysEnabled(true); } public void setUpQuestion() { operation = operation.instantiateQuestion(); currQuestion = operation.generateQuestion(maxRandomRange) + " = "; // System.out.println(operation.getstate() == PERCENT_STATE.INC_DEC); setUpAnswerPanel(operation.getState()); System.out.println("Question state is " + operation.getState()); if (operation.getState() == QuestionState.NO_CALC || operation.getState() == QuestionState.FRACTION) { if (s != STATE.CAL_DETECTED) { s = STATE.CAL_WARNING_FLAG; } System.out.println("Timer started"); c.startTimer(); } ans.requestFocus(); mainFrame.setVisible(true); // System.out.println(percentIncreaseDecreasePlaceHolder.isVisible()); // System.out.println("---------"); canvas.repaint(); } private void setUpAnswerPanel(QuestionState gameState) { if (gameState == QuestionState.PERCENT_INC_DEC) { clearRadioSelectionButtons(); answerPanel.remove(fractionPlaceHolder); fractionPlaceHolder.setVisible(false); answerPanel.add(percentIncreaseDecreasePlaceHolder); percentIncreaseDecreasePlaceHolder.setVisible(true); } else if (gameState == QuestionState.FRACTION) { clearFractionAns(); answerPanel.remove(percentIncreaseDecreasePlaceHolder); percentIncreaseDecreasePlaceHolder.setVisible(false); answerPanel.add(fractionPlaceHolder); fractionPlaceHolder.setVisible(true);; } else { answerPanel.remove(fractionPlaceHolder); fractionPlaceHolder.setVisible(false); answerPanel.remove(percentIncreaseDecreasePlaceHolder); percentIncreaseDecreasePlaceHolder.setVisible(false); } } private void clearFractionAns() { numer.setText(""); denom.setText(""); } private void clearRadioSelectionButtons() { percentIncDec.setSelectedCheckbox(null); } public STATE getGameState() { return s; } public void setGameState(STATE gameState) { STATE prevState = s; s = gameState; if (gameState == STATE.CAL_DETECTED) { incorrectScoreText = "Incorrect: " + ((prevState == STATE.CAL_WARNING_FLAG) ? incorrectScore : ++incorrectScore) + "/" + MAX_INCORRECT; if (incorrectScore >= MAX_INCORRECT) { numQuestionSoFar = 0; incorrectScore = 0; maxRandomRange = INITIAL_MAX_RANDOM_RANGE; } c.stop(); setUpQuestion(); } } /** * @author MSDK */ private class MyMiniCanvas extends Canvas { /** * */ // Padding space setup private static final long serialVersionUID = 1L; private static final int PADDING_SPACE = 10; private static final int SEPARATION_SPACE = PADDING_SPACE; public MyMiniCanvas() { setBackground(Color.WHITE); setSize(mainFrame.getSize()); } public void paint(Graphics g) { // Set up Parameters setSize(mainFrame.getSize()); Font font = new Font("default", Font.PLAIN, 20); Map<TextAttribute, Object> attributes = new HashMap<>(); attributes.put(TextAttribute.TRACKING, 0.1); Font font2 = font.deriveFont(attributes); // Begin Drawing Components Graphics2D g2; g2 = (Graphics2D) g; // Write incorrect string on top right in red g2.setColor(Color.RED); g2.setFont(new Font("default", Font.BOLD, 16)); g2.drawString(incorrectScoreText, mainFrame.getSize().width - 120, 20); // Write current score in top left corner in blue g2.setColor(Color.BLUE); g2.setFont(new Font("default", Font.BOLD, 16)); g2.drawString("Score: " + Integer.toString(numQuestionSoFar) + "/" + QUESTION_GOAL, 10, 20); // Write previous question with answer and correctness // and current question g2.setColor(Color.BLACK); g2.setFont(font2); printCurrentQuestion(g2, font2); printPrevQuestion(g2, font2); } /** * Based on the size of the frame and window, the current question will * be printed at the bottom panel of the frame below the imaginary half * height line * * @param g2D graphic element of the canvas * @param f reference fonts */ private void printCurrentQuestion(Graphics2D g2D, Font f) { if (!currQuestion.isEmpty()) { FontMetrics metrics = g2D.getFontMetrics(f); ArrayList<String> currQuestionElement = new ArrayList<>( Arrays.asList(currQuestion.split("\n"))); int yCoordinate = mainFrame.getSize().height / 2 + metrics.getHeight() + SEPARATION_SPACE + PADDING_SPACE; int xCoordinate; for (String s : currQuestionElement) { int beginIndex = -1; int endIndex = -1; xCoordinate = (mainFrame.getSize().width / 2) - ((metrics.stringWidth(s) - metrics.stringWidth(countExtraCharacters(s))) / 2); while ((beginIndex = s.indexOf("{", endIndex)) != -1) { endIndex = s.indexOf("}", beginIndex); xCoordinate = printFraction(s.substring(beginIndex + 1, endIndex), xCoordinate, yCoordinate, g2D, f); int index; if ((index = s.indexOf("{", endIndex)) != -1) { g2D.drawString(s.substring(endIndex + 1, index), xCoordinate, yCoordinate); xCoordinate += metrics.stringWidth(s.substring(endIndex + 1, index)); } } beginIndex = endIndex + 1; g2D.drawString(s.substring(beginIndex), xCoordinate, yCoordinate); yCoordinate += metrics.getHeight() + PADDING_SPACE; } } } /** * This method prints the fractions on the canvas * @param s String format of a^^b//c * @param xCoordinate starting x-coordinate on canvas * @param yCoordinate starting y-coordinate on canvas * @param g2D graphics of canvas * @param f font of canvas * @return next x-coordinate to be printed */ private int printFraction(String s, int xCoordinate, int yCoordinate, Graphics2D g2D, Font f) { FontMetrics metrics = g2D.getFontMetrics(f); int beginIndex = 0; int endIndex = s.indexOf("^^"); String sub = s.substring(beginIndex, endIndex); beginIndex = endIndex + 2; endIndex = s.indexOf("//"); String numer = s.substring(beginIndex, endIndex); String denom = s.substring(endIndex + 2); String max = (numer.length() < denom.length()) ? denom : numer; // print the mixed number g2D.drawString(sub, xCoordinate, yCoordinate); xCoordinate += metrics.stringWidth(sub); yCoordinate -= metrics.getHeight() / 2; // printing the numerator g2D.drawString(numer, xCoordinate, yCoordinate); yCoordinate += metrics.getHeight() / 2; g2D.drawLine(xCoordinate, yCoordinate, xCoordinate + metrics.stringWidth(max), yCoordinate); yCoordinate += (metrics.getHeight() * 3 / 2) - (metrics.getHeight() / 2); g2D.drawString(denom, xCoordinate, yCoordinate); return xCoordinate + metrics.stringWidth(max) + PADDING_SPACE - 5; } private String countExtraCharacters(String s) { String result = ""; int beginIndex = 0; while((beginIndex = s.indexOf("^^", beginIndex)) > -1) { result += "^^//+"; beginIndex = s.indexOf("//", beginIndex) + 2; } return result; } /** * Based on the height of the window and canvas frame, the previous * question will be printed in the top half of the frame, above the * imaginary half height line * * @param g2D graphic element of the canvas * @param f reference fonts */ private void printPrevQuestion(Graphics2D g2D, Font f) { if (!prevQuestion.isEmpty()) { FontMetrics metrics = g2D.getFontMetrics(f); ArrayList<String> preQuestionElement = new ArrayList<>( Arrays.asList(prevQuestion.split("\n"))); int yCoordinate = mainFrame.getSize().height / 2 - preQuestionElement.size() * (metrics.getHeight() + PADDING_SPACE) - SEPARATION_SPACE; int xCoordinate = 0; System.out.println(xCoordinate + " " + yCoordinate); for (String s : preQuestionElement) { int beginIndex = -1; int endIndex = -1; xCoordinate = (mainFrame.getSize().width / 2) - ((metrics.stringWidth(s) - metrics.stringWidth(countExtraCharacters(s))) / 2); while ((beginIndex = s.indexOf("{", endIndex)) != -1) { endIndex = s.indexOf("}", beginIndex); xCoordinate = printFraction(s.substring(beginIndex + 1, endIndex), xCoordinate, yCoordinate, g2D, f); int index; if ((index = s.indexOf("{", endIndex)) != -1) { g2D.drawString(s.substring(endIndex + 1, index), xCoordinate, yCoordinate); xCoordinate += metrics.stringWidth(s.substring(endIndex + 1, index)); } } beginIndex = endIndex + 1; g2D.drawString(s.substring(beginIndex), xCoordinate, yCoordinate); yCoordinate += metrics.getHeight() + PADDING_SPACE; xCoordinate = (mainFrame.getSize().width / 2) - ((metrics.stringWidth(s) - metrics.stringWidth(countExtraCharacters(s))) / 2); } int yCoordinateCorrectness = yCoordinate - metrics.getHeight() - PADDING_SPACE; int xCoordinateForCorrectness = xCoordinate + metrics.stringWidth(preQuestionElement.get(preQuestionElement.size() - 1)) - metrics.stringWidth(countExtraCharacters(preQuestionElement.get(preQuestionElement.size() - 1))) + PADDING_SPACE; g2D.setColor(correctnessFlag.getColor()); g2D.drawString(correctness, xCoordinateForCorrectness, yCoordinateCorrectness); } } } private class MyKeyAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { System.out.println(e.getKeyCode()); System.out.println(KeyEvent.VK_TAB); if (e.getKeyCode() == KeyEvent.VK_TAB) { if (e.getModifiers() > 0) { e.getComponent().transferFocusBackward(); } else { e.getComponent().transferFocus(); } e.consume(); } } } private class MyActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { try { if (s == STATE.END) { System.exit(0); } if (operation.getState() == QuestionState.PERCENT_INC_DEC && !increaseCheckBox.getState() && !decreaseCheckBox.getState()) { ans.setText("null"); } double a = Double.parseDouble(ans.getText()); if (operation.getState() == QuestionState.PERCENT_INC_DEC && decreaseCheckBox.getState()) { a = -(Math.abs(a)); } if (operation.getState() == QuestionState.FRACTION) { double delta = (a == 0) ? 1 : a / Math.abs(a); double b = Double.parseDouble(numer.getText()); double c = Double.parseDouble(denom.getText()); a = ((Math.abs(a) * c + b) / c) * delta; } answer = String.format("%.2f", a); prevQuestion = currQuestion + answer; if (operation.checkAnswer(a)) { numQuestionSoFar++; correctness = "CORRECT !!!"; correctnessFlag = CORRECTNESS.CORRECT; } else { incorrectScore++; correctness = "WRONG !!!"; correctnessFlag = CORRECTNESS.WRONG; prevQuestion += " " + "(" + String.format("%.2f", operation.getAnswer()) + ")"; } s = STATE.IN_GAME; c.stop(); if (incorrectScore > MAX_INCORRECT) { numQuestionSoFar = 0; incorrectScore = 0; maxRandomRange = INITIAL_MAX_RANDOM_RANGE; } if (numQuestionSoFar >= QUESTION_GOAL) { currQuestion = PASS + " !!!!!"; s = STATE.END; } maxRandomRange += 2; /* * operation new with switch statements for diff kind of * question */ if (s != STATE.END) { setUpQuestion(); } incorrectScoreText = "Incorrect: " + incorrectScore + "/" + MAX_INCORRECT; answer = ""; canvas.repaint(); } catch (Exception E) { if (ans.getText().equalsIgnoreCase(PASS)) { currQuestion = PASS + " !!!!!"; prevQuestion = "Entered Password to Finish !!!"; s = STATE.END; } if (ans.getText().equalsIgnoreCase("V1")) { percentIncreaseDecreasePlaceHolder.setVisible(true); System.out.println("setVisible to true"); } if (ans.getText().equalsIgnoreCase("V2")) { percentIncreaseDecreasePlaceHolder.setVisible(false); System.out.println("setVisible to false"); } if (ans.getText().equalsIgnoreCase("")) { System.out.println("empty answer"); } canvas.repaint(); } ans.setText(""); numer.setText(""); denom.setText(""); } } }
package io.fab.connector.rules; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import io.fab.connector.data.CatalogEventMessage; import io.fab.connector.data.EventType; import io.fab.connector.processors.CatalogEventProcessorStrategy; @Component public class CatalogEventRules { @Autowired private IFoodAuthenticationRules authenticationRules; @Autowired private Map<EventType, CatalogEventProcessorStrategy> strategiesMap; public void processMessage(final CatalogEventMessage message) { authenticationRules.loadIFoodApiAccessToken(); final CatalogEventProcessorStrategy strategy = findStrategy(message.getEvent().getType()); strategy.processCatalogEvent(message); } private CatalogEventProcessorStrategy findStrategy(final EventType type) { return strategiesMap.entrySet() .parallelStream() .filter(entry -> entry.getKey() == type) .findAny() .orElseThrow(() -> new IllegalArgumentException("Catalog event unknown: " + type)) .getValue(); } }
/* * 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 model.user; import entity.OrderDetail; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; /** * * @author MinhQuan */ public class UserOrderDetailModel extends UserAllModel { //Tao order detail moi public boolean insertOrderDetail(OrderDetail orderDetail) { boolean check = false; Session session = getSession(); //Tao isDisable orderDetail.setIsDisabled(false); //Tao created if (orderDetail.getCreated() == null) { orderDetail.setCreated(getCurrentDate()); } try { //Luu Order Detail moi vao CSDL session.save(orderDetail); session.getTransaction().commit(); check = true; } catch (Exception e) { //in ra loi va dong Transaction e.printStackTrace(); session.getTransaction().rollback(); } //Dong session session.close(); return check; } //tim orderDetail qua OrderId public List<OrderDetail> getListByOrderId(int orderId) { List<OrderDetail> listOrderDetail = null; Session session = getSession(); try { Query query = null; query = session.createQuery("from OrderDetail where isDisabled = false and orderId=:orderId"); query.setInteger("orderId", orderId); listOrderDetail = query.list(); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } return listOrderDetail; } }
package com.projeto.model.dao; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import com.projeto.model.models.Ingrediente; public class IngredienteDao extends GenericDao<Ingrediente, Integer>{ public IngredienteDao(EntityManager entityManager) { super(entityManager); } @SuppressWarnings("unchecked") public List<Ingrediente> listIngredientePaginacao(Integer numeroPagina, Integer defaultPagina) { List<Ingrediente> listaIngrediente = new ArrayList<Ingrediente>(); Query query = this.getEntityManager().createQuery("SELECT u FROM Ingrediente u " + "LEFT JOIN FETCH u.produtos ") .setFirstResult(numeroPagina) .setMaxResults(defaultPagina); listaIngrediente = query.getResultList(); return listaIngrediente; } }
interface WritingPerson { String getName(); Handedness getHanded(); }
package org.zerock.domain; import lombok.Data; @Data public class BrandVO { private int brandOid; private String userId; private String name; private String content; }
/* 1: */ package com.kaldin.user.register.dto; /* 2: */ /* 3: */ public class AcademicInfoDTO /* 4: */ { /* 5: */ private CandidateDTO candidateDTO; /* 6: */ private int academicId; /* 7: */ private String qualification; /* 8: */ private int passingYear; /* 9: */ private float percentage; /* 10: */ private String university; /* 11: */ /* 12: */ public CandidateDTO getCandidateDTO() /* 13: */ { /* 14:14 */ return this.candidateDTO; /* 15: */ } /* 16: */ /* 17: */ public void setCandidateDTO(CandidateDTO candidateDTO) /* 18: */ { /* 19:18 */ this.candidateDTO = candidateDTO; /* 20: */ } /* 21: */ /* 22: */ public int getAcademicId() /* 23: */ { /* 24:22 */ return this.academicId; /* 25: */ } /* 26: */ /* 27: */ public void setAcademicId(int academicId) /* 28: */ { /* 29:26 */ this.academicId = academicId; /* 30: */ } /* 31: */ /* 32: */ public String getQualification() /* 33: */ { /* 34:30 */ return this.qualification; /* 35: */ } /* 36: */ /* 37: */ public void setQualification(String qualification) /* 38: */ { /* 39:34 */ this.qualification = qualification; /* 40: */ } /* 41: */ /* 42: */ public int getPassingYear() /* 43: */ { /* 44:38 */ return this.passingYear; /* 45: */ } /* 46: */ /* 47: */ public void setPassingYear(int passingYear) /* 48: */ { /* 49:42 */ this.passingYear = passingYear; /* 50: */ } /* 51: */ /* 52: */ public float getPercentage() /* 53: */ { /* 54:46 */ return this.percentage; /* 55: */ } /* 56: */ /* 57: */ public void setPercentage(float percentage) /* 58: */ { /* 59:50 */ this.percentage = percentage; /* 60: */ } /* 61: */ /* 62: */ public String getUniversity() /* 63: */ { /* 64:54 */ return this.university; /* 65: */ } /* 66: */ /* 67: */ public void setUniversity(String university) /* 68: */ { /* 69:58 */ this.university = university; /* 70: */ } /* 71: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.user.register.dto.AcademicInfoDTO * JD-Core Version: 0.7.0.1 */
package com.cybx.member.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.cybx.member.dao.MemberDao; import com.cybx.member.model.Member; import com.cybx.member.service.MemberService; @Service("memberService") public class MemberServiceImpl implements MemberService { @Resource private MemberDao memberDao; @Override public List<Member> getMembers() { return memberDao.getMembers(); } }
package com.flutterwave.raveandroid.rave_presentation.uk; import com.flutterwave.raveandroid.rave_java_commons.Meta; import com.flutterwave.raveandroid.rave_java_commons.Payload; import com.flutterwave.raveandroid.rave_java_commons.SubAccount; import com.flutterwave.raveandroid.rave_presentation.DaggerTestRaveComponent; import com.flutterwave.raveandroid.rave_presentation.TestNetworkModule; import com.flutterwave.raveandroid.rave_presentation.TestRaveComponent; import com.flutterwave.raveandroid.rave_presentation.TestUtilsModule; import com.flutterwave.raveandroid.rave_presentation.data.PayloadEncryptor; import com.flutterwave.raveandroid.rave_presentation.data.PayloadToJson; import com.flutterwave.raveandroid.rave_remote.Callbacks; import com.flutterwave.raveandroid.rave_remote.FeeCheckRequestBody; import com.flutterwave.raveandroid.rave_remote.RemoteRepository; import com.flutterwave.raveandroid.rave_remote.ResultCallback; import com.flutterwave.raveandroid.rave_remote.requests.ChargeRequestBody; import com.flutterwave.raveandroid.rave_remote.requests.RequeryRequestBody; import com.flutterwave.raveandroid.rave_remote.responses.ChargeResponse; import com.flutterwave.raveandroid.rave_remote.responses.FeeCheckResponse; import com.flutterwave.raveandroid.rave_remote.responses.RequeryResponse; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.inject.Inject; import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.noResponse; import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.success; import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.transactionError; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class UkHandlerTest { @Mock UkContract.Interactor interactor; @Inject RemoteRepository networkRequest; @Inject PayloadToJson payloadToJson; @Inject PayloadEncryptor payloadEncryptor; private UkHandler paymentHandler; @Before public void setUp() { MockitoAnnotations.initMocks(this); paymentHandler = new UkHandler(interactor); TestRaveComponent component = DaggerTestRaveComponent.builder() .testNetworkModule(new TestNetworkModule()) .testUtilsModule(new TestUtilsModule()) .build(); component.inject(this); component.inject(paymentHandler); } @Test public void fetchFee_onError_showFetchFeeFailedCalledWithCorrectParams() { //arrange Payload payload = generatePayload(); //act paymentHandler.fetchFee(payload); ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class); verify(networkRequest).getFee(any(FeeCheckRequestBody.class), captor.capture()); String error = generateRandomString(); captor.getAllValues().get(0).onError(error); //assert verify(interactor).showFetchFeeFailed(error); } @Test public void fetchFee_onSuccess_onTransactionFeeFetchedCalledWithCorrectParams() { //arrange Payload payload = generatePayload(); FeeCheckResponse feeCheckResponse = generateFeeCheckResponse(); //act paymentHandler.fetchFee(payload); ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class); verify(networkRequest).getFee(any(FeeCheckRequestBody.class), captor.capture()); captor.getAllValues().get(0).onSuccess(feeCheckResponse); //assert verify(interactor).onTransactionFeeFetched(feeCheckResponse.getData().getCharge_amount(), payload, feeCheckResponse.getData().getFee()); } @Test public void fetchFee_onSuccess_exceptionThrown_showFetchFeeFailedCalledWithCorrectParams() { paymentHandler.fetchFee(generatePayload()); doThrow(new NullPointerException()).when(interactor).onTransactionFeeFetched(any(String.class), any(Payload.class), anyString()); ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class); verify(networkRequest).getFee(any(FeeCheckRequestBody.class), captor.capture()); captor.getAllValues().get(0).onSuccess(generateFeeCheckResponse()); verify(interactor, times(1)).showFetchFeeFailed(transactionError); } @Test(expected = Exception.class) public void fetchFee_onSuccess_displayFeeException_showFetchFeeFailedCalledWithCorrectParams() { //arrange Payload payload = generatePayload(); FeeCheckResponse feeCheckResponse = generateFeeCheckResponse(); //act paymentHandler.fetchFee(payload); ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class); verify(networkRequest).getFee(any(FeeCheckRequestBody.class), captor.capture()); captor.getAllValues().get(0).onSuccess(feeCheckResponse); doThrow(new Exception()).when(interactor).onTransactionFeeFetched(feeCheckResponse.getData().getCharge_amount(), payload, feeCheckResponse.getData().getFee()); //assert verify(interactor).showFetchFeeFailed(transactionError); } @Test public void chargeUK_onSuccess_requeryTxCalled() { //arrange Payload payload = generatePayload(); String encryptionKey = generateRandomString(); when(payloadEncryptor.getEncryptedData(any(String.class), any(String.class))).thenReturn(generateRandomString()); //act paymentHandler.chargeUk(payload, encryptionKey); ArgumentCaptor<ResultCallback> onChargeRequestCompleteArgumentCaptor = ArgumentCaptor.forClass(ResultCallback.class); verify(networkRequest).chargeWithPolling(any(ChargeRequestBody.class), onChargeRequestCompleteArgumentCaptor.capture()); onChargeRequestCompleteArgumentCaptor.getAllValues().get(0).onSuccess(generateValidChargeResponse()); //assert paymentHandler.requeryTx(generateRandomString(), generateRandomString(), generateRandomString()); } @Test public void chargeUK_onError_onPaymentErrorCalled() { //arrange Payload payload = generatePayload(); String encryptionKey = generateRandomString(); when(payloadEncryptor.getEncryptedData(any(String.class), any(String.class))).thenReturn(generateRandomString()); //act paymentHandler.chargeUk(payload, encryptionKey); ArgumentCaptor<ResultCallback> onChargeRequestCompleteArgumentCaptor = ArgumentCaptor.forClass(ResultCallback.class); String message = generateRandomString(); verify(networkRequest).chargeWithPolling(any(ChargeRequestBody.class), onChargeRequestCompleteArgumentCaptor.capture()); onChargeRequestCompleteArgumentCaptor.getAllValues().get(0).onError(message); verify(interactor).onPaymentError(message); } @Test public void chargeUK_onSuccessWithNullData_onPaymentError_noResponse_Called() { //arrange Payload payload = generatePayload(); String encryptionKey = generateRandomString(); when(payloadEncryptor.getEncryptedData(any(String.class), any(String.class))).thenReturn(generateRandomString()); //act paymentHandler.chargeUk(payload, encryptionKey); ArgumentCaptor<ResultCallback> onChargeRequestCompleteArgumentCaptor = ArgumentCaptor.forClass(ResultCallback.class); verify(networkRequest).chargeWithPolling(any(ChargeRequestBody.class), onChargeRequestCompleteArgumentCaptor.capture()); onChargeRequestCompleteArgumentCaptor.getAllValues().get(0).onSuccess(generateNullChargeResponse()); //assert verify(interactor).onPaymentError(noResponse); } @Test public void requeryTx_onSuccess_nullData_onPaymentFailedCalled() { //arrange String flwRef = generateRandomString(); String txRef = generateRandomString(); String encryptionKey = generateRandomString(); //act paymentHandler.requeryTx(flwRef, txRef, encryptionKey); ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class); verify(networkRequest).requeryTx(any(RequeryRequestBody.class), captor.capture()); RequeryResponse requeryResponse = generateNullQuery(); String jsonResponse = generateRandomString(); captor.getAllValues().get(0).onSuccess(requeryResponse, jsonResponse); //assert verify(interactor).onPaymentFailed(requeryResponse.getStatus(), jsonResponse); } @Test public void requeryTx_onSuccessWithChargeResponseCode00_onPaymentSuccessfulCalled() { //arrange String flwRef = generateRandomString(); String txRef = generateRandomString(); //act paymentHandler.requeryTx(flwRef, txRef, generateRandomString()); ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class); verify(networkRequest).requeryTx(any(RequeryRequestBody.class), captor.capture()); RequeryResponse requeryResponse = generateRequerySuccessful_00(); String jsonResponse = generateRandomString(); captor.getAllValues().get(0).onSuccess(requeryResponse, jsonResponse); //assert verify(interactor).onPaymentSuccessful(flwRef, txRef, jsonResponse); } @Test public void requeryTx_onSuccessWithChargeResponseCode02_onPollingRoundComplete() { //arrange String flwRef = generateRandomString(); String txRef = generateRandomString(); String encryptionKey = generateRandomString(); //act paymentHandler.requeryTx(flwRef, txRef, encryptionKey); ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class); verify(networkRequest).requeryTx(any(RequeryRequestBody.class), captor.capture()); RequeryResponse requeryResponse = generateRequerySuccessful_02(); String jsonResponse = generateRandomString(); captor.getAllValues().get(0).onSuccess(requeryResponse, jsonResponse); //assert verify(networkRequest, times(2)).requeryTx(any(RequeryRequestBody.class), any(Callbacks.OnRequeryRequestComplete.class)); } @Test public void requeryTx_onSuccessWithChargeResponseCodeNot00or02_onPaymentFailedCalled() { //arrange Payload payload = generatePayload(); String encryptionKey = generateRandomString(); when(payloadEncryptor.getEncryptedData(any(String.class), any(String.class))).thenReturn(generateRandomString()); //act paymentHandler.chargeUk(payload, encryptionKey); paymentHandler.requeryTx(generateRandomString(), generateRandomString(), generateRandomString()); ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class); verify(networkRequest).requeryTx(any(RequeryRequestBody.class), captor.capture()); RequeryResponse requeryResponse = generateRandomRequerySuccessful(); String jsonResponse = generateRandomString(); captor.getAllValues().get(0).onSuccess(requeryResponse, jsonResponse); //assert verify(interactor).onPaymentFailed(requeryResponse.getStatus(), jsonResponse); } @Test public void requeryTx_onError_onPaymentFailedCalled() { //arrange String flwRef = generateRandomString(); String txRef = generateRandomString(); String encryptionKey = generateRandomString(); String message = generateRandomString(); String jsonResponse = generateRandomString(); //act paymentHandler.requeryTx(flwRef, txRef, encryptionKey); ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class); verify(networkRequest).requeryTx(any(RequeryRequestBody.class), captor.capture()); captor.getAllValues().get(0).onError(message, jsonResponse); //assert verify(interactor).onPaymentFailed(message, jsonResponse); } private FeeCheckResponse generateFeeCheckResponse() { FeeCheckResponse feeCheckResponse = new FeeCheckResponse(); FeeCheckResponse.Data feeCheckResponseData = new FeeCheckResponse.Data(); feeCheckResponseData.setCharge_amount(generateRandomString()); feeCheckResponse.setData(feeCheckResponseData); feeCheckResponse.getData().setFee(generateRandomString()); return feeCheckResponse; } private RequeryResponse generateNullQuery() { return new RequeryResponse(); } private RequeryResponse generateRequerySuccessful_00() { RequeryResponse requeryResponse = new RequeryResponse(); RequeryResponse.Data data = new RequeryResponse.Data(); data.setChargeResponseCode("00"); requeryResponse.setData(data); return requeryResponse; } private RequeryResponse generateRequerySuccessful_02() { RequeryResponse requeryResponse = new RequeryResponse(); RequeryResponse.Data data = new RequeryResponse.Data(); data.setChargeResponseCode("02"); requeryResponse.setData(data); return requeryResponse; } private RequeryResponse generateRandomRequerySuccessful() { RequeryResponse requeryResponse = new RequeryResponse(); RequeryResponse.Data data = new RequeryResponse.Data(); data.setChargeResponseCode("03"); requeryResponse.setData(data); return requeryResponse; } private Payload generatePayload() { List<Meta> metas = new ArrayList<>(); List<SubAccount> subAccounts = new ArrayList<>(); return new Payload(generateRandomString(), metas, subAccounts, generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString()); } private ChargeResponse generateRandomChargeResponse() { ChargeResponse chargeResponse = new ChargeResponse(); ChargeResponse.Data chargeResponseData = new ChargeResponse.Data(); chargeResponseData.setChargeResponseCode(generateRandomString()); chargeResponse.setData(chargeResponseData); return chargeResponse; } private ChargeResponse generateNullChargeResponse() { return new ChargeResponse(); } private ChargeResponse generateValidChargeResponse() { ChargeResponse chargeResponse = generateRandomChargeResponse(); chargeResponse.getData().setChargeResponseCode("00"); chargeResponse.setStatus(success); chargeResponse.getData().setAuthurl("http://www.rave.com"); chargeResponse.getData().setFlwRef(generateRandomString()); chargeResponse.getData().setTx_ref(generateRandomString()); return chargeResponse; } private String generateRandomString() { return UUID.randomUUID().toString(); } }
package com.company.hackerrank; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class JavaList { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); List<Integer> integerList = new ArrayList<>(); for (int i = 0; i < n; i++) { integerList.add(i, scanner.nextInt()); } int q = scanner.nextInt(); while (q-- > 0) { String query = scanner.next(); if (query.equalsIgnoreCase("Insert")) { int index = scanner.nextInt(); int value = scanner.nextInt(); integerList.add(index, value); } else { integerList.remove(scanner.nextInt()); } } for (int i : integerList) { System.out.print(i + " "); } } }
// Colgate University COSC 290 Labs // Version 0.1, 2017 // Author: Michael Hay /** * An atomic proposition. */ public class PropVariable extends Proposition { private String symbol; public PropVariable(String symbol) { this.symbol = symbol; } @Override public String toString() { return symbol; //throw new UnsupportedOperationException("implement me!"); } @Override public boolean isVariable() { return (symbol.length()==1); //throw new UnsupportedOperationException("implement me!"); } @Override public boolean equals(Object other) { return (other instanceof PropVariable) && symbol.equals(((PropVariable)other).symbol); } @Override public int hashCode() { return symbol.hashCode(); } @Override public Proposition copy() { return new PropVariable(symbol); } }
package chapter11; import java.util.ArrayList; import java.util.Scanner; public class Exercise11_17 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter an integer m:"); int m = input.nextInt(); int n = getSmallestNumberForPerfectSquare(m); System.out.println("The smallest number n for m * n to be a perfect square is " + n + " m * n is " + (m * n)); } public static int getSmallestNumberForPerfectSquare(int m) { ArrayList<Integer> primeFactors = primeFactors(m); ArrayList<Integer> oddNumberOfTimesPrimeNumbers = new ArrayList<>(); ArrayList<Integer> checkedNumbers = new ArrayList<>(); for (int i = 0; i < primeFactors.size() ; i++) { int appearTimes = 0; for (int j = i ; j < primeFactors.size(); j++) { if (primeFactors.get(i) == primeFactors.get(j) && !checkedNumbers.contains(primeFactors.get(i))) { appearTimes++; } } checkedNumbers.add(primeFactors.get(i)); if (appearTimes % 2 != 0) { oddNumberOfTimesPrimeNumbers.add(primeFactors.get(i)); } } int oddNumberMultiply = oddNumberOfTimesPrimeNumbers.get(0); for (int i = 1; i < oddNumberOfTimesPrimeNumbers.size(); i++) { oddNumberMultiply *= oddNumberOfTimesPrimeNumbers.get(i); } return oddNumberMultiply; } private static ArrayList<Integer> primeFactors(int m) { ArrayList<Integer> primeFactors = new ArrayList<>(); int i = 2; while (m > 1) { if (m % i == 0) { primeFactors.add(i); m /= i; } else { for (int j = i + 1;; j++) { if (isPrime(j)) { i = j; break; } } } } return primeFactors; } public static boolean isPrime(int number) { if(number<2) { return false; } for (int i = 2; i < number; i++) { if (number % i == 0) { return false; } } return true; } }
package br.eti.ns.nssuite.requisicoes._genericos; public class ConsNaoEncerradosReq { public String tpAmb; public String cUF; public String CNPJ; }
package util; import java.sql.Connection; import java.sql.DriverManager; public class DatabaseUtil { private DatabaseUtil() {} private static class LazyHolder { public static final DatabaseUtil INSTANCE = new DatabaseUtil(); } public static DatabaseUtil getInstance() { return LazyHolder.INSTANCE; } public Connection getConnection() { try { String dbURL = "jdbc:mysql://34.69.65.28:3306/jsp_lecture_evaluation?characterEncoding=UTF-8&serverTimezone=UTC"; String dbID = "root"; String dbPassword = "19941104"; Class.forName("com.mysql.cj.jdbc.Driver"); return DriverManager.getConnection(dbURL, dbID, dbPassword); } catch (Exception e) { e.printStackTrace(); } return null; } }
package enthu_leitner; public class e_1343 { int x; public static void main(String[] args){ this.x; } }
/* * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.test.failurehandler.action; import com.sun.tools.attach.VirtualMachine; import com.sun.tools.attach.VirtualMachineDescriptor; import jdk.test.failurehandler.value.InvalidValueException; import jdk.test.failurehandler.value.Value; import jdk.test.failurehandler.value.ValueHandler; import jdk.test.failurehandler.HtmlSection; import jdk.test.failurehandler.Stopwatch; import jdk.test.failurehandler.Utils; import java.io.BufferedReader; import java.io.CharArrayReader; import java.io.CharArrayWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; public class ActionHelper { private final Path workDir; @Value(name = "execSuffix") private String executableSuffix = ""; private Path[] paths; private final PatternAction getChildren; public ActionHelper(Path workDir, String prefix, Properties properties, Path... jdks) throws InvalidValueException { this.workDir = workDir.toAbsolutePath(); getChildren = new PatternAction(null, Utils.prependPrefix(prefix, "getChildren"), properties); ValueHandler.apply(this, properties, prefix); String[] pathStrings = System.getenv("PATH").split(File.pathSeparator); paths = new Path[pathStrings.length]; for (int i = 0; i < paths.length; ++i) { paths[i] = Paths.get(pathStrings[i]); } addJdks(jdks); } public List<Long> getChildren(HtmlSection section, long pid) { String pidStr = "" + pid; ProcessBuilder pb = getChildren.prepareProcess(section, this, pidStr); PrintWriter log = getChildren.getSection(section).getWriter(); CharArrayWriter writer = new CharArrayWriter(); ExitCode code = run(log, writer, pb, getChildren.getParameters()); Reader output = new CharArrayReader(writer.toCharArray()); if (!ExitCode.OK.equals(code)) { log.println("WARNING: get children pids action failed"); try { Utils.copyStream(output, log); } catch (IOException e) { e.printStackTrace(log); } return Collections.emptyList(); } List<Long> result = new ArrayList<>(); try { try (BufferedReader reader = new BufferedReader(output)) { String line; while ((line = reader.readLine()) != null) { String value = line.trim(); if (value.isEmpty()) { // ignore empty lines continue; } try { result.add(Long.valueOf(value)); } catch (NumberFormatException e) { log.printf("WARNING: can't parse child pid %s : %s%n", line, e.getMessage()); e.printStackTrace(log); } } } } catch (IOException e) { e.printStackTrace(log); } return result; } public ProcessBuilder prepareProcess(PrintWriter log, String app, String... args) { File appBin = findApp(app); if (appBin == null) { log.printf("ERROR: can't find %s in %s.%n", app, Arrays.toString(paths)); return null; } List<String> command = new ArrayList<>(args.length + 1); command.add(appBin.toString()); Collections.addAll(command, args); return new ProcessBuilder() .command(command) .directory(workDir.toFile()); } private File findApp(String app) { String name = app + executableSuffix; for (Path pathElem : paths) { File result = pathElem.resolve(name).toFile(); if (result.exists()) { return result; } } return null; } private void addJdks(Path[] jdkPaths) { if (jdkPaths != null && jdkPaths.length != 0) { Path[] result = new Path[jdkPaths.length + paths.length]; for (int i = 0; i < jdkPaths.length; ++i) { result[i] = jdkPaths[i].resolve("bin"); } System.arraycopy(paths, 0, result, jdkPaths.length, paths.length); paths = result; } } private ExitCode run(PrintWriter log, Writer out, ProcessBuilder pb, ActionParameters params) { char[] lineChars = new char[40]; Arrays.fill(lineChars, '-'); String line = new String(lineChars); Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); log.printf("%s%n[%tF %<tT] %s timeout=%s%n%1$s%n", line, new Date(), pb.command(), params.timeout); Process process; KillerTask killer; ExitCode result = ExitCode.NEVER_STARTED; try { process = pb.start(); killer = new KillerTask(process); killer.schedule(params.timeout); Utils.copyStream(new InputStreamReader(process.getInputStream()), out); try { result = new ExitCode(process.waitFor()); } catch (InterruptedException e) { log.println("WARNING: interrupted when waiting for the tool:%n"); e.printStackTrace(log); } finally { killer.cancel(); } if (killer.hasTimedOut()) { log.printf( "WARNING: tool timed out: killed process after %d ms%n", params.timeout); result = ExitCode.TIMED_OUT; } } catch (IOException e) { log.printf("WARNING: caught IOException while running tool%n"); e.printStackTrace(log); result = ExitCode.LAUNCH_ERROR; } stopwatch.stop(); log.printf("%s%n[%tF %<tT] exit code: %d time: %d ms%n%1$s%n", line, new Date(), result.value, TimeUnit.NANOSECONDS.toMillis(stopwatch.getElapsedTimeNs())); return result; } public void runPatternAction(SimpleAction action, HtmlSection section) { if (action != null) { HtmlSection subSection = action.getSection(section); PrintWriter log = subSection.getWriter(); ProcessBuilder pb = action.prepareProcess(log, this); exec(subSection, pb, action.getParameters()); } } public void runPatternAction(PatternAction action, HtmlSection section, String value) { if (action != null) { ProcessBuilder pb = action.prepareProcess(section, this, value); HtmlSection subSection = action.getSection(section); exec(subSection, pb, action.getParameters()); } } public boolean isJava(long pid, PrintWriter log) { ProcessBuilder pb = prepareProcess(log, "jps", "-q"); if (pb == null) { return false; } pb.redirectErrorStream(true); boolean result = false; String pidStr = "" + pid; try { Process process = pb.start(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null){ if (pidStr.equals(line)) { result = true; } } } process.waitFor(); } catch (IOException e) { log.printf("WARNING: can't run jps : %s%n", e.getMessage()); e.printStackTrace(log); } catch (InterruptedException e) { log.printf("WARNING: interrupted%n"); e.printStackTrace(log); } return result; } private static class KillerTask extends TimerTask { private static final Timer WATCHDOG = new Timer("WATCHDOG", true); private final Process process; private boolean timedOut; public KillerTask(Process process) { this.process = process; } public void run() { try { process.exitValue(); } catch (IllegalThreadStateException e) { process.destroyForcibly(); timedOut = true; } } public boolean hasTimedOut() { return timedOut; } public void schedule(long timeout) { if (timeout > 0) { WATCHDOG.schedule(this, timeout); } } } private void exec(HtmlSection section, ProcessBuilder process, ActionParameters params) { if (process == null) { return; } PrintWriter sectionWriter = section.getWriter(); if (params.repeat > 1) { for (int i = 0, n = params.repeat; i < n; ++i) { HtmlSection iteration = section.createChildren( String.format("iteration_%d", i)); PrintWriter writer = iteration.getWriter(); ExitCode exitCode = run(writer, writer, process, params); if (params.stopOnError && !ExitCode.OK.equals(exitCode)) { sectionWriter.printf( "ERROR: non zero exit code[%d] -- break.", exitCode.value); break; } // sleep, if this is not the last iteration if (i < n - 1) { try { Thread.sleep(params.pause); } catch (InterruptedException e) { sectionWriter.printf( "WARNING: interrupted while sleeping between invocations"); e.printStackTrace(sectionWriter); } } } } else { run(section.getWriter(), section.getWriter(), process, params); } } /** * Special values for prepareProcess exit code. * * <p>Can we clash with normal codes? * On Solaris and Linux, only [0..255] are returned. * On Windows, prepareProcess exit codes are stored in unsigned int. * On MacOSX no limits (except it should fit C int type) * are defined in the exit() man pages. */ private static class ExitCode { /** Process exits gracefully */ public static final ExitCode OK = new ExitCode(0); /** Error launching prepareProcess */ public static final ExitCode LAUNCH_ERROR = new ExitCode(-1); /** Application prepareProcess has been killed by watchdog due to timeout */ public static final ExitCode TIMED_OUT = new ExitCode(-2); /** Application prepareProcess has never been started due to program logic */ public static final ExitCode NEVER_STARTED = new ExitCode(-3); public final int value; private ExitCode(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ExitCode exitCode = (ExitCode) o; return value == exitCode.value; } @Override public int hashCode() { return value; } } }
package main; import java.io.IOException; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { static boolean onlyFrom0to10=true; static boolean only2digit=true; enum RomArab { Arab(1),Rom(2),NoElse(0),Err(-1); private int val; RomArab(int v) { this.val=v; } } public static RomArab tipRA; enum Action{ none,Plus,Minus,Div,Mult,Eqv,Err; } public static Action action=Action.none; public static void main(String[] args) throws IOException,NoValidateTipExeption { System.out.println("Введите выражение:"); Scanner sc=new Scanner(System.in); try { Pattern pattern=Pattern.compile("(?:([0-9]+)|([IVXLDMC]+))(\\s*[*/+-]\\s*)?+"); while (sc.hasNext()) { int cntDig=0; action=Action.none; String inputs=sc.nextLine(); Matcher matcher=pattern.matcher(inputs); Expression exp=new Expression(); tipRA=RomArab.NoElse; while (matcher.find()) { int ival=-1; if (matcher.start(1)>=0) { String si=matcher.group(1); if (tipRA ==RomArab.Rom) { throw new NoValidateTipExeption("НЕ РИМСКАЯ ЦИФРА:"+si); } tipRA=RomArab.Arab; cntDig++; ival=StringParser.inputToInt(si); if (onlyFrom0to10 && (ival< 0 || ival>10)) throw new NoValidateTipExeption("Только от 0 до 10ти"); } if (matcher.start(2)>=0) { String si=matcher.group(2); if (tipRA ==RomArab.Arab) { throw new NoValidateTipExeption("НЕ АРАБСКАЯ ЦИФРА:"+si); } tipRA=RomArab.Rom; cntDig++; ival=StringParser.inputToInt(si); if (onlyFrom0to10 && (ival< 0 || ival>10)) throw new NoValidateTipExeption("Только от 0 до 10ти"); } if (matcher.start(3)>=0) { String sz = matcher.group(3).trim(); action = StringParser.toAction(sz); } if(cntDig>1) { if (only2digit && cntDig>2 ) throw new NoValidateTipExeption("Только 2 числа"); if(action==Action.none) throw new NoValidateTipExeption("НЕ БЫЛО ЗНАКА ОПЕРАЦИИ:"); else if(only2digit) {action = Action.Eqv;} } exp.calc(ival,action); } System.out.println("Результат="+exp.getiRez()); } } catch (Exception | NoValidateTipExeption e) { System.out.println("Неверный формат, "+e.getMessage()); } sc.close(); } }
package com.example.demo.domain; public class ProvincePage { private int pageNo; private int size; private int start; public void calculateStart(){ start=(pageNo-1)*size; } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } }
/** * */ package question1; import java.util.LinkedList; import entity.Student; /** * @author Golu * * This class demonstrates various operations of list on objects * */ public class LinkedListObject { private LinkedList<Student> list = new LinkedList<Student>(); /** * */ public LinkedListObject() { // TODO Auto-generated constructor stub } public LinkedListObject(LinkedList<Student> list) { super(); this.list = list; } public void adddetails(Student... students) { for (Student s : students) this.list.add(s); } public void addElementsusingArr(Student[] students) { for (Student s : students) this.list.add(s); } public void listIterateForEach() { for (Student s : list) { System.out.println(s.getName() + " " + s.getDateOfBirth() + " " + s.getYear() + " " + s.getDept().getDept() + " " + s.getDept().getHod()); } } public void revStudentlist() { LinkedList<Student> list1 = new LinkedList<Student>(); for (int i = list.size() - 1; i >= 0; i--) list1.add(this.list.get(i)); list.removeAll(list1); list.addAll(list1); //System.out.println(list.toString()); for (Student st : list) { System.out.println(st.toString()); } } }
/* 1: */ package com.kaldin.group.action; /* 2: */ /* 3: */ import com.kaldin.group.dao.impl.GroupImplementor; /* 4: */ import com.kaldin.group.dao.impl.UserGroupImplementor; /* 5: */ import com.kaldin.group.dto.GroupUserListDTO; /* 6: */ import com.kaldin.group.form.GroupForm; /* 7: */ import java.util.List; /* 8: */ import javax.servlet.http.HttpServletRequest; /* 9: */ import javax.servlet.http.HttpServletResponse; /* 10: */ import javax.servlet.http.HttpSession; /* 11: */ import org.apache.struts.action.Action; /* 12: */ import org.apache.struts.action.ActionForm; /* 13: */ import org.apache.struts.action.ActionForward; /* 14: */ import org.apache.struts.action.ActionMapping; /* 15: */ /* 16: */ public class GroupUserAction /* 17: */ extends Action /* 18: */ { /* 19: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) /* 20: */ throws Exception /* 21: */ { /* 22:30 */ String result = "error"; /* 23:31 */ int groupid = 0; /* 24:32 */ String operation = ""; /* 25: */ /* 26:34 */ GroupForm groupForm = (GroupForm)form; /* 27: */ /* 28:36 */ int companyid = ((Integer)request.getSession().getAttribute("CompanyId")).intValue(); /* 29:38 */ if (request.getParameter("groupid") != null) { /* 30:39 */ groupid = Integer.parseInt("" + request.getParameter("groupid")); /* 31: */ } /* 32:41 */ if (groupForm.getOperation() != null) { /* 33:42 */ operation = groupForm.getOperation(); /* 34: */ } /* 35:44 */ if (operation.equalsIgnoreCase("getUsers")) /* 36: */ { /* 37:45 */ UserGroupImplementor usergroupImpl = new UserGroupImplementor(); /* 38:46 */ List<GroupUserListDTO> groupuserList = usergroupImpl.getUserGroup(groupid, companyid, -1, -1, ""); /* 39:47 */ request.setAttribute("groupuserList", groupuserList); /* 40:48 */ result = "success"; /* 41: */ } /* 42:50 */ GroupImplementor groupImpl = new GroupImplementor(); /* 43:51 */ List<?> listObj1 = groupImpl.showGroup(companyid); /* 44:53 */ if (listObj1 != null) /* 45: */ { /* 46:54 */ result = "success"; /* 47:55 */ request.setAttribute("groupList", listObj1); /* 48: */ } /* 49:58 */ return mapping.findForward(result); /* 50: */ } /* 51: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.group.action.GroupUserAction * JD-Core Version: 0.7.0.1 */
package com.SkyBlue.hr.attendance.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.SkyBlue.common.mapper.DatasetBeanMapper; import com.SkyBlue.hr.attendance.serviceFacade.AttendanceServiceFacade; import com.SkyBlue.hr.attendance.to.ConditionBean; import com.SkyBlue.hr.attendance.to.DayAnnualBean; import com.tobesoft.xplatform.data.PlatformData; @Controller public class DayAnnualController{ @Autowired private AttendanceServiceFacade attendanceServiceFacade; @Autowired private DatasetBeanMapper datasetBeanMapper; /* 해당년도, 해당사원의 연차정보, 사원정보를 조회하는 메서드 */ @RequestMapping("/hr/attendance/findAnnualMgt.do") public void findAnnualMgt(@RequestAttribute("inData") PlatformData inData, @RequestAttribute("outData") PlatformData outData) throws Exception { String empCode = inData.getVariable("empCode").getString(); String standardYear = inData.getVariable("standardYear").getString(); List<DayAnnualBean> dayAnnualList=attendanceServiceFacade.findAnnualMgt(empCode,standardYear); datasetBeanMapper.beansToDataset(outData, dayAnnualList, DayAnnualBean.class); } // 연차를 신청하는 메서드 @RequestMapping("/hr/attendance/addDayAnnual.do") public void addDayAnnual(@RequestAttribute("inData") PlatformData inData, @RequestAttribute("outData") PlatformData outData) throws Exception { DayAnnualBean dayAnnualBean=datasetBeanMapper.datasetToBean(inData, DayAnnualBean.class); List<DayAnnualBean> dayAnnualList=attendanceServiceFacade.addDayAnnual(dayAnnualBean); datasetBeanMapper.beansToDataset(outData, dayAnnualList, DayAnnualBean.class); } // 연차 승인, 관리부분에서 조건에 따라 조회하는 메서드 @RequestMapping("/hr/attendance/findDayAnnualListByCondition.do") public void findDayAnnualListByCondition(@RequestAttribute("inData") PlatformData inData, @RequestAttribute("outData") PlatformData outData) throws Exception { String deptCode = inData.getVariable("deptCode").getString(); String empCode = inData.getVariable("empCode").getString(); String fromDate = inData.getVariable("fromDate").getString(); String toDate = inData.getVariable("toDate").getString(); String approvalStatus = inData.getVariable("approvalStatus").getString(); List<DayAnnualBean> dayAnnualList=attendanceServiceFacade.findDayAnnualListByCondition(deptCode,empCode,fromDate,toDate,approvalStatus); datasetBeanMapper.beansToDataset(outData, dayAnnualList, DayAnnualBean.class); } // 연차 승인화면에서 연차를 일괄적으로 승인처리 하는 메서드 @RequestMapping("/hr/attendance/batchDayAnnual.do") public void batchDayAnnual(@RequestAttribute("inData") PlatformData inData, @RequestAttribute("outData") PlatformData outData) throws Exception { List<DayAnnualBean> dayAnnualList=datasetBeanMapper.datasetToBeans(inData, DayAnnualBean.class); attendanceServiceFacade.batchDayAnnual(dayAnnualList); } }
package com.fabmo.toolminder; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; public class MainActivity extends Activity { public ArrayList<Device> dev_list; private Timer statusTimer; Button rescan_button; ListView listDevicesView ; Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext =this; dev_list = Device.ScanWifiNetwork(getApplicationContext()); setContentView(R.layout.activity_main); rescan_button = (Button) findViewById(R.id.button_rescan); listDevicesView = (ListView)findViewById(R.id.listDevices); Device[] devices_to_display = new Device[dev_list.size()]; for (int i=0;i<dev_list.size();i++) { devices_to_display[i]=dev_list.get(i); } StatusReportAdapter myStatusAdapter = new StatusReportAdapter(this,devices_to_display); listDevicesView.setAdapter(myStatusAdapter); statusTimer = new Timer(); statusTimer.schedule(new TimerTask() { @Override public void run() { updateStatus(); } }, 0, 100); rescan_button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click DetectionService.run_server = false; try {Device.detection_service.socket.close();}catch(Exception ex) {} dev_list = Device.ScanWifiNetwork(getApplicationContext()); } }); listDevicesView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @SuppressWarnings("unchecked") @Override public void onItemClick(AdapterView a, View v, int position, long id) { //on r�cup�re la HashMap contenant les infos de notre item (titre, description, img) Device d = (Device) listDevicesView.getItemAtPosition(position); //On cr�� un objet Bundle, c'est ce qui va nous permetre d'envoyer des donn�es � l'autre Activity Bundle objetbunble = new Bundle(); //Cela fonctionne plus ou moins comme une HashMap, on entre une clef et sa valeur en face objetbunble.putString("ip", d.chooseInterface().ip_address); objetbunble.putInt("port", d.server_port); //On cr�� l'Intent qui va nous permettre d'afficher l'autre Activity //Attention il va surement falloir que vous modifier le premier param�tre (Tutoriel9_Android.this) //Mettez le nom de l'Activity dans la quelle vous �tes actuellement Intent intent = new Intent(MainActivity.this, WebBrowserActivity.class); //On affecte � l'Intent le Bundle que l'on a cr�� intent.putExtras(objetbunble); //On d�marre l'autre Activity startActivityForResult(intent, 0); } }); } @Override protected void onPause() { statusTimer.cancel(); DetectionService.run_server = false; try {Device.detection_service.socket.close();}catch(Exception ex) {} super.onPause(); }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void updateStatus() { //This method is called directly by the timer //and runs in the same thread as the timer. for(Device dev : dev_list){ dev.getStatus(); } //We call the method that will work with the UI //through the runOnUiThread method. this.runOnUiThread(Update_status_on_UI); } private Runnable Update_status_on_UI = new Runnable() { public void run() { Device[] devices_to_display = new Device[dev_list.size()]; for (int i=0;i<dev_list.size();i++) { devices_to_display[i]=dev_list.get(i); } StatusReportAdapter myStatusAdapter = new StatusReportAdapter(mContext,devices_to_display); listDevicesView.setAdapter(myStatusAdapter); //This method runs in the same thread as the UI. //Do something to the UI thread here } }; }
package org.lvzr.fast.java.patten.create.factoryMethod.statiz; import org.lvzr.fast.java.patten.create.factoryMethod.Sender; /** * 1.3静态工厂方法模式,将上面的多个工厂方法模式里的方法置为静态的,不需要创建实例,直接调用即可。 * 总体来说,工厂模式适合:凡是出现了大量的产品需要创建,并且具有共同的接口时, * 可以通过工厂方法模式进行创建。在以上的三种模式中,第一种如果传入的字符串有误,不能正确创建对象, * 第三种相对于第二种,不需要实例化工厂类,所以,大多数情况下,我们会选用第三种——静态工厂方法模式。 */ public class FactoryTest { public static void main(String[] args) { Sender sender = SendFactory.produceMail(); sender.Send(); } }
package org.study.design_patterns.observer; public interface Observer { void handle(Subject subject); }
package webserver; public interface RequestHandler { void initialize(ServerConfig sc) throws Exception; }
import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) { /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_- PARTIE 1 : DEMARRAGE -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ ////////// Création du fichier des machines en état de fonctionnement ///////////// // ******** TIMESTAMP ******** long startTime = System.currentTimeMillis(); // DECLARATION VARIABLE : liste de machines sur lesquelles tester la disponibilité // DECLARATION VARIABLE : liste des résultats de tests de connexion // DECLARATION VARIABLE : liste des machines disponibles liste_machines_ok List<String> machines; ArrayList<TestConnectionSSH> listeTests = new ArrayList<TestConnectionSSH>(); ArrayList<String> liste_machines_ok = new ArrayList<String>(); //Lance toutes les connexions ssh en même temps avec un timeout de 7 secondes Path filein = Paths.get("liste_machines.txt"); try { machines = Files.readAllLines(filein, Charset.forName("UTF-8")); for (String machine : machines) { /* * on teste la connection SSH pendant 7 secondes maximum */ TestConnectionSSH test = new TestConnectionSSH(machine, 7); test.start(); listeTests.add(test); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Attend la fin de tentatives de connexion ssh ci-dessus pour récupérer les noms des machines for (TestConnectionSSH test : listeTests) { try { test.join();// on attend la fin du test if (test.isConnectionOK()) { liste_machines_ok.add(test.getMachine()); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Ecrit les noms des machines en état de fonctionnement dans un fichier // Et compte leur nombre // DECLARATION VARIABLE : nombre de machines disponibles int nb_machines = liste_machines_ok.size(); Path file = Paths.get("liste_machines_OK.txt"); try { Files.write(file, liste_machines_ok, Charset.forName("UTF-8")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ******** TIMESTAMP ******** long endTime = System.currentTimeMillis(); long totalTime1 = endTime - startTime; /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_- PARTIE 2 : SPLITTING -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ ///////// Lire le fichier INPUT et créer autant de fichier Sx qu'on a de machines disponibles //////////// // ******** TIMESTAMP ******** startTime = System.currentTimeMillis(); // Si il y a plus de machines que de lignes, on rentre dans la première condition du if ci-dessous. // Si il y a plus de lignes que de machines, on rentre dans la deuxième condition du if : chaque // fichier Sx contient donc le nombre de lignes du fichier initial divisé par le nombre de machines. Path fileinput = Paths.get(args[0]); // DECLARATION VARIABLE : Compteur de sections = compteur de fichiers Sx = compteur de fichiers UMx int Sx_counter = 0; try { List<String> lines; lines = Files.readAllLines(fileinput, Charset.forName("UTF-8")); int nb_lignes = lines.size(); ////// IF plus de machines que de lignes ////// if (nb_machines >= nb_lignes) { for(int i = 0; i<lines.size(); i++ ){ String Sxname = "S"+i+".txt"; try (PrintWriter out = new PrintWriter(Sxname);){ out.println(lines.get(i)); out.close(); } catch (IOException e) { e.printStackTrace(); } Sx_counter ++; } } else { ////// IF plus de lignes que de machines ////// int nbLignesParFichier = (int) nb_lignes/nb_machines + 1; int ligneRepriseEcriture = 0; for(int f = 0; f < nb_machines; f++ ){ String AEcrire = ""; for (int i = ligneRepriseEcriture; i < Math.min(ligneRepriseEcriture + nbLignesParFichier, nb_lignes); i++){ AEcrire += " " + lines.get(i); } ligneRepriseEcriture += nbLignesParFichier; String Sx_name = "S"+f+".txt"; //try { PrintWriter p = new PrintWriter(Sx_name); p.println(AEcrire); p.close(); Sx_counter ++; } } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // ******** TIMESTAMP ******** endTime = System.currentTimeMillis(); long totalTime2 = endTime - startTime; /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_- ON LANCE LE MAP -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ ///////// Lancer en parallèle le SLAVE sur toutes ces machines //////////// ///////// Le dictionnaire UMx_Machines mappe le nom de fichier UMx à la machine qui l'a créé. //////////// // ******** TIMESTAMP ******** startTime = System.currentTimeMillis(); // lancer en parallèle le SLAVE sur toutes ces machines // Le dictionnaire UMx_Machines mappe le nom de fichier UMx à la machine qui l'a créé. Map<String, LaunchSlaveShavadoop> slaves = new HashMap<String, LaunchSlaveShavadoop>(); Map<String, String> UMx_Machines = new HashMap<String, String>(); HashMap<String, ArrayList<String>> attributions = new HashMap<String, ArrayList<String>>(); // UMx + clés try { machines = Files.readAllLines(file, Charset.forName("UTF-8")); System.out.println(machines); for (int i = 0; i < Sx_counter; i++) { // on lance les threads de slave LaunchSlaveShavadoop slave = new LaunchSlaveShavadoop(machines.get(i),"cd workspace/;java -jar SLAVESHAVADOOP.jar map " + i, 20); slave.start(); slaves.put(machines.get(i), slave); String um_name = "UM"+i+".txt"; UMx_Machines.put(machines.get(i), um_name); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (Map.Entry<String, LaunchSlaveShavadoop> entry : slaves.entrySet()) { LaunchSlaveShavadoop slave = entry.getValue(); try { slave.join(); } catch (InterruptedException e) { e.printStackTrace(); } ArrayList<String> liste = slave.getSortie(); String umx = UMx_Machines.get(slave.getMachine()); System.out.println(umx); attributions.put(umx, liste); } //System.out.println("slaves"); //System.out.println(slaves); System.out.println("UMx_machines"); System.out.println(UMx_Machines); System.out.println("\nATTRIBUTIONS : \n"); System.out.println(attributions); // ******** TIMESTAMP ******** endTime = System.currentTimeMillis(); long totalTime3 = endTime - startTime; /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ ON LANCE LE SHUFFLE _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ // ******** TIMESTAMP ******** startTime = System.currentTimeMillis(); ///////// création du dictionnaire "Clé - liste des fichier UMx" à partir du dictionnaire d'attributions HashMap <String, ArrayList<String>> cle_UMx = new HashMap <String, ArrayList<String>>() ; for (String file_UM : attributions.keySet()) { for (String mot : attributions.get(file_UM)) { if (! cle_UMx.containsKey(mot)){ // on met en attribut un tableau avec juste la machine ArrayList<String> liste_file = new ArrayList<String>(); liste_file.add(file_UM); cle_UMx.put(mot,liste_file); } else { // on le rajoute au tableau ArrayList<String> liste_file = cle_UMx.get(mot); liste_file.add(file_UM); cle_UMx.put(mot,liste_file); } } } System.out.println(cle_UMx); System.out.println("Le map est fini"); // ******** TIMESTAMP ******** endTime = System.currentTimeMillis(); long totalTime4 = endTime - startTime; /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_- ON LANCE LE REDUCE -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ // ******** TIMESTAMP ******** startTime = System.currentTimeMillis(); // Lire la liste des machines en état de fonctionnement et // lancer en parallèle le SLAVE sur toutes ces machines // Le dictionnaire RMx_Machines mappe le nom de fichier RMx à la machine qui l'a créé (le possède) int s = 0; //slaves.clear(); ArrayList<LaunchSlaveShavadoop> slaves2 = new ArrayList<LaunchSlaveShavadoop>(); attributions.clear(); ArrayList<String> AllRMaps = new ArrayList<String>(); try { machines = Files.readAllLines(file, Charset.forName("UTF-8")); for(String key : cle_UMx.keySet()){ // on lance les threads de slave String UMList = ""; for(String um : cle_UMx.get(key)){ UMList += " " + um; } LaunchSlaveShavadoop slave = new LaunchSlaveShavadoop(machines.get(s%machines.size()),"cd workspace/;java -jar SLAVESHAVADOOP.jar reduce "+key+" RM"+s+UMList, 20); slave.start(); //slaves.put(machines.get(s%machines.size()), slave); slaves2.add(slave); s++; } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Attente de la fin des threads de Reduce for (LaunchSlaveShavadoop slave : slaves2){ //for (Map.Entry<String, LaunchSlaveShavadoop> entry : slaves.entrySet()) { // LaunchSlaveShavadoop slave = entry.getValue(); try { slave.join(); } catch (InterruptedException e) { e.printStackTrace(); } ArrayList<String> cles = slave.getSortie(); for (String st : cles){ AllRMaps.add(st); } } // ******** TIMESTAMP ******** endTime = System.currentTimeMillis(); long totalTime5 = endTime - startTime; /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_- ON LANCE L'ASSEMBLING -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ /* _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ // ******** TIMESTAMP ******** startTime = System.currentTimeMillis(); Path out = Paths.get("output_Shavadoop"); try { Files.write(out, AllRMaps, Charset.forName("UTF-8")); } catch (IOException e) { e.printStackTrace(); } System.out.println(AllRMaps); System.out.println("Le reduce est fini"); // ******** TIMESTAMP ******** endTime = System.currentTimeMillis(); long totalTime6 = endTime - startTime; /* _-_-_-_-_-_-_-_-_-_-_-_ ON AFFICHE LES TEMPS DE TRAITEMENT _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ */ System.out.print("Durée du démarrage : "+totalTime1/1000.0+"s\n"); System.out.print("Durée du split : "+totalTime2/1000.0+"s\n"); System.out.print("Durée du map : "+totalTime3/1000.0+"s\n"); System.out.print("Durée du shuffle : "+totalTime4/1000.0+"s\n"); System.out.print("Durée du reduce : "+totalTime5/1000.0+"s\n"); System.out.print("Durée de l'assembling : "+totalTime6/1000.0+"s\n"); } }
package com.joseph.MemberDatabse; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MemberDB_Application { public static void main(String[] args) { // SpringApplication.run(MemberDB_Application.class, args); UserPanel userPanel = new UserPanel(); Database list = new MemberList(); IdGenerator idGen = new IdGenerator(); Controller controller = new Controller(); controller.Configure(userPanel, list, idGen); while (true) { controller.mainController(); } } }
package com.telyo.trainassistant.utils; /** * Created by Administrator on 2017/6/7. */ public class StaticClass { public static final String TRAIN_QUERY = "5e2b70941ffd42a2becbb66d10100e7c"; //AppName public static final String APPNAME = "TrainAssistant"; //百度AK key public static final String BaiduAK = "hwar207h8pMjSMBv7dRQ3p3dXZrYhzCa"; //天气接口 public static final String WETHER_KEY = "4e4dd1b9627a492ea626b2c377fcfde1"; //火车查询 public static final String TRAIN_KEY = "cdf5941e5573460ebba3bef26c311180"; //ApplicationKey public static final String ApplicationKey = "7e6e2163cb5b96b57f957f7c31a5cdc4"; //短信名称 public static final String TRAIN_01 = "TRAIN_01"; //火车票Key public static final String TRAIN_TICKETS_KEY = "9b1f69bd7ac58a801663610e80b9dc3a"; //腾讯bugly public static final String TENG_CENT_BUGLY_APP_KEY = "c8bc2b23-0c21-43e7-b5c2-47855e1b2039"; public static final String TENG_CENT_BUGLY_APP_ID = "adbf42997f"; /** 支付宝支付业务:入参app_id */ public static final String APPID = "2016080600184374"; /** 支付宝账户登录授权业务:入参pid值 */ public static final String PID = "2088102170277665"; /** 支付宝账户登录授权业务:入参target_id值 */ public static final String TARGET_ID = "2088102170277665"; /** 商户私钥,pkcs8格式 */ /** 如下私钥,RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */ /** 如果商户两个都设置了,优先使用 RSA2_PRIVATE */ /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行,建议使用 RSA2_PRIVATE */ /** 获取 RSA2_PRIVATE,建议使用支付宝提供的公私钥生成工具生成, */ /** 工具地址:https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1 */ public static final String RSA2_PRIVATE = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDtpJA9N0tJKiNAR8+Wq9Ip/mEy7v8NZryWj5o1jJ1XkcPcxLCopj25EkeIeaKZMAYh//WnhmVZB/jnrXCetjECfsLI9wzvx94WZ1jjVguOQJg+Q4aGUbwsLxA8m6UQK/xWQsM56QNlcw8O0Z7EeA5gpdUcO4j0UgOz2xlNR2cWlsOf8K/iNBPtEhjakjWRuEtZhjrdT4URiFlqtgmiza5l6PofoS7qaSJuKcETCfxjuzxfa5iVEtVbJcOuDpJXdeeadPQOnGhTHxw9avdCHkA9ArwUzaMSt7ODSvtJRjaenAbFoiriJ5LJUgRLP1Fbd3ytxfZIqADFGRyswd0KUqxrAgMBAAECggEAUHHZpe9W2/CYuETW39FQNoj3DE/dJQM3Kdx4vlHYXXFplQ08JAsKb+DhODC8uxCHsvC7jrcvDaFmP771lbRlCMwyUedXiL/mzTy02VgiV0hEgSdInaWDho1z+KBTkxLgu66j+bGIRcpaOZD6JtXhQBRC/OimZtZwjGzJtuBJ5FoD3ZuuoWrGqlUUrKORefOm6xlVCg68mv6tNOEn8k3B55eolp4Jod8bVwObTlV/0+W1u9ZaMCzW/sqfBfHB5/AhCL+FqOElTL/7J2qhmm09hLWfPw6IuHQTMKx+ChfQ+Iq6wAfZ9y+A41KQ6LaBiLhIX0iVTTNqui+pbHtAXZBOsQKBgQD79EwTixUhVQd4hIK3XO4rPzgF8giBJeNqfj4bWk5QEUEyW0P6u3UxCFJjKcKPn0P3wSpn2esjJU92UrYPaLZq2KinOzu8d+d6VS4ugCL4Uv2sLgn2HZ9WJMdMjNAVEazHZncUk7yGhtS86pplDC9RpZaSPjLN0+x7QyhTmfJPIwKBgQDxdW+8GGxLd/Qc7fYg0u8/uTAHn2it7rjWGKAT//zhHQeCLoTH5j8hexX2yPKzhaO7u3uXMbipqfY420AMwBUh7rDvho0PoGXq9USPvcKN4K7OX4+CRgjNYmUv+z+kQJr48zMMn9iFSUTt+qekvXwPNEEbwtA41+Ap9Kn4e+tmGQKBgBRdNXzq4+VSywzJoQsS/skODggk/Nz7Y/sqgviQ/v1nt55LVB5C4oD5DDepm2kiVUsEGNpV+bRYgqisnLx4GS5fnpoNppFgG5x+oAHwJ2NsycYN3o4+7K74wAcG5padXBqtxHgsTLOO2EkAqUP7jSOLP7VIQ7DxLQ71aaAANF6DAoGAEOVw3i6vVVCdinC0anOYPlNNIxtqjdFIqeKrQPsGzRHk9p0euYZJIKSmUtCY+yr83CQwb9IQ4/56tlvRTZMbZ3Z2dyxpLpDA0QI8u/pBZQA1+0cAmdMgxo5+Gi9wsqO6tHUAO3/r/Ne1tRl3JbYEumOjsredLn0cuJLgWf0B6fECgYA4yRcbpfY8NfdRnsfQKHvS8yImpVE3MtJBs4/kIicxEFRKyR+Lt3Ky+VxXK4wrldUCElx90HYcTbtvJnEeCeW7CPm8v4eo39VRu8gvF/fov2kc9hLd53pSZX51r1WIn28OhyiNTCMaZUEzxvHdydIllGloIr/+dUZHDbMleS3mvA=="; public static final String RSA_PRIVATE = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDtpJA9N0tJKiNAR8+Wq9Ip/mEy7v8NZryWj5o1jJ1XkcPcxLCopj25EkeIeaKZMAYh//WnhmVZB/jnrXCetjECfsLI9wzvx94WZ1jjVguOQJg+Q4aGUbwsLxA8m6UQK/xWQsM56QNlcw8O0Z7EeA5gpdUcO4j0UgOz2xlNR2cWlsOf8K/iNBPtEhjakjWRuEtZhjrdT4URiFlqtgmiza5l6PofoS7qaSJuKcETCfxjuzxfa5iVEtVbJcOuDpJXdeeadPQOnGhTHxw9avdCHkA9ArwUzaMSt7ODSvtJRjaenAbFoiriJ5LJUgRLP1Fbd3ytxfZIqADFGRyswd0KUqxrAgMBAAECggEAUHHZpe9W2/CYuETW39FQNoj3DE/dJQM3Kdx4vlHYXXFplQ08JAsKb+DhODC8uxCHsvC7jrcvDaFmP771lbRlCMwyUedXiL/mzTy02VgiV0hEgSdInaWDho1z+KBTkxLgu66j+bGIRcpaOZD6JtXhQBRC/OimZtZwjGzJtuBJ5FoD3ZuuoWrGqlUUrKORefOm6xlVCg68mv6tNOEn8k3B55eolp4Jod8bVwObTlV/0+W1u9ZaMCzW/sqfBfHB5/AhCL+FqOElTL/7J2qhmm09hLWfPw6IuHQTMKx+ChfQ+Iq6wAfZ9y+A41KQ6LaBiLhIX0iVTTNqui+pbHtAXZBOsQKBgQD79EwTixUhVQd4hIK3XO4rPzgF8giBJeNqfj4bWk5QEUEyW0P6u3UxCFJjKcKPn0P3wSpn2esjJU92UrYPaLZq2KinOzu8d+d6VS4ugCL4Uv2sLgn2HZ9WJMdMjNAVEazHZncUk7yGhtS86pplDC9RpZaSPjLN0+x7QyhTmfJPIwKBgQDxdW+8GGxLd/Qc7fYg0u8/uTAHn2it7rjWGKAT//zhHQeCLoTH5j8hexX2yPKzhaO7u3uXMbipqfY420AMwBUh7rDvho0PoGXq9USPvcKN4K7OX4+CRgjNYmUv+z+kQJr48zMMn9iFSUTt+qekvXwPNEEbwtA41+Ap9Kn4e+tmGQKBgBRdNXzq4+VSywzJoQsS/skODggk/Nz7Y/sqgviQ/v1nt55LVB5C4oD5DDepm2kiVUsEGNpV+bRYgqisnLx4GS5fnpoNppFgG5x+oAHwJ2NsycYN3o4+7K74wAcG5padXBqtxHgsTLOO2EkAqUP7jSOLP7VIQ7DxLQ71aaAANF6DAoGAEOVw3i6vVVCdinC0anOYPlNNIxtqjdFIqeKrQPsGzRHk9p0euYZJIKSmUtCY+yr83CQwb9IQ4/56tlvRTZMbZ3Z2dyxpLpDA0QI8u/pBZQA1+0cAmdMgxo5+Gi9wsqO6tHUAO3/r/Ne1tRl3JbYEumOjsredLn0cuJLgWf0B6fECgYA4yRcbpfY8NfdRnsfQKHvS8yImpVE3MtJBs4/kIicxEFRKyR+Lt3Ky+VxXK4wrldUCElx90HYcTbtvJnEeCeW7CPm8v4eo39VRu8gvF/fov2kc9hLd53pSZX51r1WIn28OhyiNTCMaZUEzxvHdydIllGloIr/+dUZHDbMleS3mvA=="; public static final String TENSENT_APP_ID = "1106253404"; public static final String WECHAT_JUHE_KEY = "5a887d3888c26672dec13e32b6a34b12"; //cruvzq1fhmwl70v4 public static final String WETHER_XINZHI_KEY = "cruvzq1fhmwl70v4"; //天气参数 public static final String[] weaterId = new String[]{"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","53"}; public static final String[] weaterSrt = new String[]{"晴","多云","阴","阵雨","雷阵雨","雷阵雨伴有冰雹","雨夹雪","小雨","中雨","大雨","暴雨","大暴雨","特大暴雨","阵雪","小雪","中雪","大雪","暴雪","雾","冻雨","沙尘暴","小雨-中雨","中雨-大雨","大雨-暴雨","暴雨-大暴雨","大暴雨-特大暴雨","小雪-中雪","中雪-大雪","大雪-暴雪","浮尘","扬沙","强沙尘暴","霾"}; }
package org.fuserleer.crypto; import java.util.Collection; import java.util.Objects; import java.util.stream.Collectors; import org.bouncycastle.util.Arrays; import org.fuserleer.crypto.bls.group.G2Point; import org.fuserleer.utils.Base58; import org.fuserleer.utils.Numbers; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * Forked from https://github.com/ConsenSys/mikuli/tree/master/src/main/java/net/consensys/mikuli/crypto * * Modified for use with Cassandra as internal code not a dependency * * Original repo source has no license headers. */ public final class BLSPublicKey extends PublicKey { @JsonCreator public static BLSPublicKey from(final byte[] bytes) { return new BLSPublicKey(bytes); } public static BLSPublicKey from(final String key) throws CryptoException { Objects.requireNonNull(key, "Key string is null"); Numbers.isZero(key.length(), "Key string is empty"); return BLSPublicKey.from(Base58.fromBase58(Objects.requireNonNull(key, "Key string is null"))); } private byte[] bytes; private transient G2Point point; @SuppressWarnings("unused") private BLSPublicKey() { // FOR SERIALIZER } BLSPublicKey(final byte[] bytes) { Objects.requireNonNull(bytes, "Bytes for public key is null"); Numbers.isZero(bytes.length, "Bytes length is zero"); this.point = G2Point.fromBytes(bytes); this.bytes = Arrays.clone(bytes); } BLSPublicKey(final G2Point point) { Objects.requireNonNull(point, "Public key point is null"); this.point = point; this.bytes = this.point.toBytes(); } public BLSPublicKey combine(final Collection<BLSPublicKey> publicKeys) { Objects.requireNonNull(publicKeys, "Public keys to combine is null"); return new BLSPublicKey(g2Point().add(publicKeys.stream().map(pk -> pk.point).collect(Collectors.toList()))); } public BLSPublicKey combine(final BLSPublicKey publicKey) { Objects.requireNonNull(publicKey, "Public key for combine is null"); return new BLSPublicKey(g2Point().add(publicKey.point)); } public synchronized G2Point g2Point() { if (this.point == null) this.point = G2Point.fromBytes(this.bytes); return new G2Point(this.point); } public final Identity getIdentity() { return new Identity(Identity.BLS, this); } @JsonValue @Override public byte[] toByteArray() { return Arrays.clone(this.bytes); } @Override public boolean verify(final byte[] hash, final Signature signature) { Objects.requireNonNull(hash, "Hash to verify is null"); Numbers.isZero(hash.length, "Hash length is zero"); Objects.requireNonNull(signature, "Signature to verify is null"); return BLS12381.verify(this, (BLSSignature) signature, hash); } }
package test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.Test; import page.DashBoardPage; import page.LoginPage; import util.BrowserFactory; import util.ExcelReader; public class LoginTest { WebDriver driver; ExcelReader reader = new ExcelReader(".\\Data\\Techfios.xlsx"); String username = reader.getCellData("LoginInfo", "UserName", 2); String password = reader.getCellData("LoginInfo", "Password", 2) ; @Test public void userShouldBeAbleToLogin() { driver = BrowserFactory.init(); //LoginPage login = new LoginPage(); LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class); loginPage.enterUserName(username); loginPage.enterPassword(password); loginPage.clickSignInButton(); } }
package data; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import model.project; public class projectLogic implements projectInterface{ static String sql = null; static ConnectMySQL db = null; static ResultSet ret = null; public int addProject(String projectName,String creatorName){ sql="insert into project (projectName,creatorId) values(?,?)"; db=new ConnectMySQL(sql); userLogic u=new userLogic(); try { db.pst.setString(1, projectName); db.pst.setInt(2, u.getUserIdByName(creatorName)); db.pst.executeUpdate(); db.close(); } catch (SQLException e) { e.printStackTrace(); } return 0; }//添加风险管理计划 public int deleteProject(int projectId){ sql="delete from project where id='" +projectId+ "'"; db=new ConnectMySQL(sql); try { db.pst.executeUpdate(); db.close(); } catch (SQLException e) { e.printStackTrace(); } return 0; }//删除风险管理计划 public int modifyProject(project p){ sql="update project set projectName="+p.getProjectName()+"' where id="+p.getId(); db=new ConnectMySQL(sql); try { db.pst.executeUpdate(); db.close(); } catch (SQLException e) { e.printStackTrace(); } return 0; }//修改风险管理计划 public ArrayList<project> getAllProject(String creatorName){ ArrayList<project> result=new ArrayList<project>(); userLogic u=new userLogic(); sql="select * from project where creatorId="+u.getUserIdByName(creatorName); db=new ConnectMySQL(sql); try { ret = db.pst.executeQuery(); while (ret.next()) { project p=new project(); p.setId(ret.getInt(1)); p.setProjectName(ret.getString(2)); p.setCreatorName(ret.getString(3)); result.add(p); } ret.close(); db.close(); } catch (SQLException e) { e.printStackTrace(); } return result; }//获得用户所有风险管理计划 }
package asc.desktop.step_definitions; public class OrdersPackagingSteps { }
package com.practice.one; public class Practice1 { public static void main(String[] args) { // TODO Auto-generated method stub int r = fun(); System.out.println("r = " + r); } private static int fun(){ return 3*5-8; } }