text
stringlengths
10
2.72M
package com.vuforia.samples.VuforiaSamples.ui.Common; /** * Created by K.Oda on 2017/12/16. */ public class JsonUserInfo { public String userName; public String userId; public int sex; public JsonUserInfo(){} }
package cn.kitho.core.dal.base; import cn.kitho.core.model.SelfCheck; public interface SelfCheckMapper { int deleteByPrimaryKey(Integer id); int insert(SelfCheck record); int insertSelective(SelfCheck record); SelfCheck selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(SelfCheck record); int updateByPrimaryKeyWithBLOBs(SelfCheck record); int updateByPrimaryKey(SelfCheck record); }
package Object; import java.util.ArrayList; /** * La classe ProgAllenCombObject mappa la tabella "prog_allen_comb" del database */ public class ProgAllenCombObject extends ProgrammaAllenamentoObject { private int calorie_da_consumare; private int disponibilita; public ProgAllenCombObject () { calorie_da_consumare=0; disponibilita=0; settimanaallenamento = new ArrayList<GiornoAllenProgObject>(); for (int i=0; i<7; i++) settimanaallenamento.add(i, new GiornoAllenProgObject()); } public ProgAllenCombObject(ArrayList<GiornoAllenProgObject> giorniprogrammati, int caloriedaconsumare, int disponibilita) { this.calorie_da_consumare = caloriedaconsumare; this.disponibilita = disponibilita; settimanaallenamento = giorniprogrammati; } public int getCalorie_da_consumare() { return calorie_da_consumare; } public void setCalorie_da_consumare(int calorie_da_consumare) { this.calorie_da_consumare = calorie_da_consumare; } public int getDisponibilita() { return disponibilita; } public void setDisponibilita(int disponibilita) { this.disponibilita = disponibilita; } }
package com.datastax.autoloader; import com.datastax.autoloader.CsvParser; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by alexandergauthier on 1/4/18. */ public class CsvParserTest { public static final String PATH = "/Users/alexandergauthier/Downloads/redfin_2017-10-14-20-35-06.csv"; public static final String DELIM = ","; @org.junit.Test public void test() throws Exception { List<String> columns = CsvParser.getColumns(PATH, DELIM); System.out.println(columns.size()); Iterator<String> it = columns.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
package com.nayank.eightpuzzle; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import com.nayank.eightpuzzle.R; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class MainActivity extends AppCompatActivity { Integer[] initarr = new Integer[8]; int free_x=0; int free_y=0; Button[][] buttons = new Button[3][3]; int board[][] = new int [3][3]; long moves=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); resetBoard(); Button resetButton =findViewById(R.id.resetBoard); } private void resetBoard() { generateInitialRandomArray(initarr); populateInitBoard(initarr, board); mapBoardButtonstoViewXml(buttons); setBoardArrayToButtons(buttons, board); moves=0; } private void setBoardArrayToButtons(Button[][] buttons, int[][] board) { for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { if(board[i][j]!=0) { buttons[i][j].setText(" "+new Integer(board[i][j]).toString()+" "); buttons[i][j].setTag(R.id.TAG_KEY_1,i); buttons[i][j].setTag(R.id.TAG_KEY_2,j); buttons[i][j].setTag(R.id.TAG_KEY_3,board[i][j]); buttons[i][j].setTextSize(100); //buttons[i][j].setBackgroundColor(Color.GRAY); buttons[i][j].setVisibility(View.VISIBLE); } else { buttons[i][j].setText(new String(" ")); buttons[i][j].setTag(R.id.TAG_KEY_1,i); buttons[i][j].setTag(R.id.TAG_KEY_2,j); buttons[i][j].setTag(R.id.TAG_KEY_3,board[i][j]); buttons[i][j].setTextSize(100); buttons[i][j].setVisibility(View.INVISIBLE); free_x=i; free_y=j; } } } } private void mapBoardButtonstoViewXml(Button[][] buttons) { buttons[0][0]= (Button) findViewById(R.id.button1); buttons[0][1]= (Button) findViewById(R.id.button2); buttons[0][2]= (Button) findViewById(R.id.button3); buttons[1][0]= (Button) findViewById(R.id.button4); buttons[1][1]= (Button) findViewById(R.id.button5); buttons[1][2]= (Button) findViewById(R.id.button6); buttons[2][0]= (Button) findViewById(R.id.button7); buttons[2][1]= (Button) findViewById(R.id.button8); buttons[2][2]= (Button) findViewById(R.id.button9); } public void clickNumber(View view) { //Crouton.cancelAllCroutons(); Button clickedButton =(Button) view; int x= (int)clickedButton.getTag(R.id.TAG_KEY_1); int y= (int )clickedButton.getTag(R.id.TAG_KEY_2); int val= (int ) clickedButton.getTag(R.id.TAG_KEY_3); //left if( free_x==x && free_y==y-1) { swapButtonValues(clickedButton, x, y, val); } //right else if( free_x==x && free_y==y+1) { swapButtonValues(clickedButton, x, y, val); } //up else if( free_x==x-1 && free_y==y) { swapButtonValues(clickedButton, x, y, val); } //down else if (free_x==x+1 && free_y==y) { swapButtonValues(clickedButton, x, y, val); } else { Snackbar.make(view,R.string.invalidMoveMessage,Snackbar.LENGTH_SHORT).show(); } ckeckIfSolved(); } private void ckeckIfSolved() { boolean solved=false; if (board[0][0]==1 && board[0][1]==2 && board[0][2]==3 && board[1][0]==4 && board[1][1]==5 && board[1][2]==6 && board[2][0]==7 && board[2][1]==8 ) { solved=true; } if(solved) { String message = "Congratulations!! You did it.You took "+moves+" moves."; Snackbar.make(this.findViewById(R.id.board), message,Snackbar.LENGTH_SHORT).show(); } } private void swapButtonValues(Button clickedButton, int x, int y, int val) { Button freeButton = buttons[free_x][free_y]; freeButton.setText(" "+new Integer(val).toString()+" "); freeButton.setTag(R.id.TAG_KEY_3,val); freeButton.setVisibility(View.VISIBLE); clickedButton.setText(new String(" ")); clickedButton.setTag(R.id.TAG_KEY_3,0); clickedButton.setVisibility(View.INVISIBLE); board[free_x][free_y]=val; board[x][y]=0; free_x=x; free_y=y; moves++; Button movecnt = findViewById(R.id.movesCount); movecnt.setText("Moves:"+moves); } public void resetBoardClick(View view) { resetBoard(); Button movecnt = findViewById(R.id.movesCount); movecnt.setText("Moves:"+0); Snackbar.make(view, R.string.resetMessage, Snackbar.LENGTH_SHORT).show(); } private int populateInitBoard(Integer[] initarr, int[][] board) { int emptyspace= new Random().nextInt(9); int k=0; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { if(k==emptyspace) { System.out.println("skipping empty space"); emptyspace=-1; board[i][j]=0; } else { board[i][j]= initarr[k]; System.out.println("board:"+i+","+j+":"+board[i][j]+",k:"+k+",empty:"+emptyspace); k++; } if(k>=8) break; } } return emptyspace; } @Override protected void onDestroy() { //Crouton.cancelAllCroutons(); super.onDestroy(); } private void generateInitialRandomArray(Integer[] initarr) { System.out.println("init array"); List<Integer> arr= new ArrayList<Integer>(8); for(int i =0;i<8;i++) { arr.add(i+1); } Collections.shuffle(arr, new Random()); for(int i=0;i<8;i++) { initarr[i]=arr.get(i); } } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } }
package mvc.vista; import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import mvc.controlador.InitialMenuLoadController; import mvc.controlador.SearchButtonController; public class Marco extends JFrame { private JComboBox secciones; private JComboBox paises; private JTextArea resultado; public Marco() { this.setTitle("Consulta BBDD"); this.setBounds(500, 300, 400, 400); this.setLayout(new BorderLayout()); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.addWindowListener(new InitialMenuLoadController(this)); JPanel menus = new JPanel(); menus.setLayout(new FlowLayout()); secciones = new JComboBox(); secciones.setEditable(false); secciones.addItem("Todos"); paises = new JComboBox(); paises.setEditable(false); paises.addItem("Todos"); resultado = new JTextArea(4, 50); resultado.setEditable(false); add(resultado); menus.add(secciones); menus.add(paises); add(menus, BorderLayout.NORTH); add(resultado, BorderLayout.CENTER); JButton botonConsulta = new JButton("Consulta"); botonConsulta.addActionListener(new SearchButtonController(this)); add(botonConsulta, BorderLayout.SOUTH); this.setVisible(true); } public JComboBox getSecciones() { return this.secciones; } public JComboBox getPaises() { return this.paises; } public JTextArea getResultado() { return this.resultado; } }
package modelo; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import Controlador.ConexionBD; public class tableSupplierDAO { ConexionBD conex=new ConexionBD(); Connection cnx=conex.conexionbd(); PreparedStatement ps; ResultSet rs; public boolean insertSupplier(tableSupplierDTO Supp) { int S; boolean dat=false; try { ps=cnx.prepareStatement("INSERT INTO proveedores Values (?,?,?,?,?)"); ps.setLong(1, Supp.getNitSupplier()); ps.setString(2, Supp.getCiudad_Supplier()); ps.setString(3, Supp.getDireccion_Supplier()); ps.setString(4, Supp.getNombre_Supplier()); ps.setString(5, Supp.getTelefono_Supplier()); S=ps.executeUpdate(); if(S>0) { dat=true; } } catch (SQLException e) { e.printStackTrace(); } return dat; } }
package it.unibo.bd1819.job2.reducers; import it.unibo.bd1819.job2.utils.Utility; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import org.apache.log4j.Logger; import java.io.IOException; public class CounterRatingReducer extends Reducer<Text, IntWritable, Text, Text> { private Logger logger = Logger.getLogger(CounterRatingReducer.class); /** * Reduce tasks that compute the average rating of each book and the number of bookmarks * * @param key * @param values * @param context * @throws IOException * @throws InterruptedException */ public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { Double rating = 0.0; Integer countBM = 0; int countRating = 0; for (IntWritable r : values) { // it checks if value is BOOKMARK token if (r.equals(new IntWritable(Utility.IDENTIFIER))) { countBM++; } else { // or it is a rating rating += Double.parseDouble(r.toString()); countRating++; } } Double avg = 0.0; // now compute the avg rating for the book if (countRating > 0) avg = rating / countRating; // and now using bookmarks and rating chooses the group to put the book String group = ""; if(avg < Utility.RATING_THRESHOLD && countBM < Utility.BM_THRESHOLD){ group = Utility.LOWBMLOWRATING; } if(avg >= Utility.RATING_THRESHOLD && countBM < Utility.BM_THRESHOLD){ group = Utility.LOWBMHIGHRATING; } if(avg >= Utility.RATING_THRESHOLD && countBM >= Utility.BM_THRESHOLD){ group = Utility.HIGHBMHIGHRATING; } if(avg < Utility.RATING_THRESHOLD && countBM >= Utility.BM_THRESHOLD){ group = Utility.HIGHBMLOWRATING; } // it saves just the group context.write( new Text(group), new Text("")); } }
package com.aarus.server; import com.aarus.client.ChatClientIF; import java.rmi.Remote; import java.rmi.RemoteException; public interface ChatServerIF extends Remote { void registerChatClient(ChatClientIF chatClientIF) throws RemoteException; void broadcastMessage(String message) throws RemoteException; }
package com.examples.rxjavasamples; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import java.util.Random; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.reactivex.Completable; import io.reactivex.Single; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { @BindView(R.id.txt_mssg) TextView txtMssg; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.progress) ProgressBar progress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); setSupportActionBar(toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void execSingleOnBg() { showProgress(true); Disposable d = randomIntOnBg(integer -> { showProgress(false); showMessage(String.valueOf(integer)); }, throwable -> { showProgress(false); showMessage(throwable.getMessage()); } ); disposable.add(d); } private void execCompletableOnBg() { Disposable d = taskOnBg(() -> { showProgress(false); showMessage("Even Number Completed. Sucesss"); }, throwable -> { showProgress(false); showMessage(throwable.getMessage()); }); disposable.add(d); } private void clearViews() { txtMssg.setText(""); } private void showProgress(boolean enabled) { int visibility = enabled ? View.VISIBLE : View.GONE; progress.setVisibility(visibility); } private void showMessage(String message) { txtMssg.setText(message); } protected CompositeDisposable disposable; @Override protected void onStart() { super.onStart(); disposable = new CompositeDisposable(); } @Override protected void onStop() { super.onStop(); disposable.dispose(); } public static Disposable taskOnBg(Action onComplete, Consumer<? super Throwable> onError) { return completableSample() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(onError) .subscribe(onComplete, onError); } public static Disposable randomIntOnBg(Consumer<? super Integer> onSuccess, Consumer<? super Throwable> onError) { return randomIntObsv() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(onError) .subscribe(onSuccess, onError); } public static Completable completableSample() { return Completable.create(emitter -> { Thread.sleep(300); if (!randomNumberIsOdd()) { emitter.onComplete(); } else { emitter.onError(new RuntimeException("Random Number is Odd. Error!!!")); } }); } public static Single<Integer> randomIntObsv() { return Single.create(emitter -> { Thread.sleep(300); emitter.onSuccess(randomNumber()); } ); } public static int randomNumber() { return new Random().nextInt(100); } public static boolean randomNumberIsOdd() { return randomNumber() % 2 == 1; } @OnClick({R.id.bttnCompletable, R.id.bttnSingle}) public void onViewClicked(View view) { clearViews(); switch (view.getId()) { case R.id.bttnCompletable: execCompletableOnBg(); break; case R.id.bttnSingle: execSingleOnBg(); break; } } }
package com.atguigu.exer; import java.util.Random; import java.util.Scanner; /* 在main方法中创建并启动两个线程。第一个线程循环随机打印100以内的整数, 直到第二个线程从键盘读取了“Q”命令。 */ public class QTest { public static void main(String[] args) { Thread t = new Thread(new Runnable() { @Override public void run() { boolean isFlag = true; Random random = new Random(); while (isFlag) { /* * random.nextInt(100) : [0,100) */ System.out.println(random.nextInt(100)); //睡一秒 try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { return; } } } }); t.start(); //主线程 Scanner sc = new Scanner(System.in); String s = sc.next(); if ("q".equals(s)) { t.interrupt();//杀死t线程 } } }
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; import java.awt.Font; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.geom.Rectangle2D; import java.util.List; import java.util.Arrays; import java.util.ArrayList; /** * The heading at the top of every screen. * * @author (your name) * @version (a version number or a date) */ public class Heading extends Actor { /** * Constructor for objects of class Heading. * * @param text The text to be displayed. * @param fontSize The size of the font. * @param textColor The color of the text. * */ public Heading(String text, int fontSize, Color textColor) { // Create Font Font font = new Font("Lato", Font.BOLD, fontSize); // Set the font of the current image getImage().setFont(font); // TEXT CENTERING CODE FROM ZAMOHT: http://www.greenfoot.org/scenarios/9027 // Get the FontRenderContext of the font FontRenderContext frc = getImage().getAwtImage().createGraphics().getFontRenderContext(); // Create a Rectangle2D object from the StringBounds of the word, using the FontRenderContext Rectangle2D bounds = font.getStringBounds(text, frc); // Create GreenfootImage with the width and height of the Rectangle2D object with 2-pixel padding GreenfootImage image = new GreenfootImage((int)bounds.getWidth() + 2, (int)bounds.getHeight() + 2); image.setColor(textColor); image.setFont(font); //LineMetrics lm = font.getLineMetrics(text, frc); image.drawString(text, 0, Math.round(image.getHeight()/* + lm.getStrikethroughOffset() + lm.getStrikethroughThickness() - 1*/)); setImage(image); } }
package com.cs.payment.transaction; import com.cs.payment.EventCode; import com.cs.payment.PaymentStatus; import com.cs.payment.PaymentTransaction; import com.cs.player.Player; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.querydsl.QueryDslPredicateExecutor; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.Date; import java.util.List; /** * @author Omid Alaepour */ @Repository interface PaymentTransactionRepository extends JpaRepository<PaymentTransaction, Long>, QueryDslPredicateExecutor<PaymentTransaction> { PaymentTransaction findByProviderReference(final String providerReference); PaymentTransaction findByProviderReferenceAndEventCodeAndPaymentStatus(final String providerReference, final EventCode eventCode, final PaymentStatus paymentStatus); List<PaymentTransaction> findByPlayerAndEventCodeAndPaymentStatus(final Player player, final EventCode eventCode, final PaymentStatus paymentStatus); @Query("select pt from PaymentTransaction pt where pt.player = ?1 and pt.eventCode = ?2 and pt.paymentStatus in ?3 and pt.createdDate > ?4 order by pt.createdDate " + "asc") List<PaymentTransaction> findAwaitingPaymentsAfter(final Player player, final EventCode eventCode, final Collection<PaymentStatus> paymentStatuses, final Date date); @Query(value = "select count(p) from PaymentTransaction p where p.player = ?1 and p.eventCode = ?2 and p.paymentStatus = ?3 " + "and p.createdDate between ?4 and ?5 group by p.paymentMethod") List<Integer> countDifferentPaymentMethod(final Player player, final EventCode eventCode, final PaymentStatus paymentStatus, final Date startDate, final Date endDate); @Query(value = "select player_id, sum(deposit), sum(withdraw) from (select player_id, event_code, if(event_code='AUTHORISATION', sum(amount), 0) deposit, " + "if(event_code='REFUND_WITH_DATA', sum(amount), 0) withdraw from payment_transactions where status = 'SUCCESS' and event_code in ('AUTHORISATION' , " + "'REFUND_WITH_DATA') and created_date >= ?1 and created_date <= ?2 group by player_id, event_code) a group by player_id", nativeQuery = true) List<Object[]> getPlayersDepositAndWithdrawBetween(final Date startDate, final Date endDate); @Query(value = "select player_id, sum(deposit), sum(withdraw) " + "from" + "(select player_id," + "if(event_code in ('BACK_OFFICE_MONEY_DEPOSIT', 'CASHBACK', 'BONUS_CONVERSION'), sum(amount), 0) deposit," + "if(event_code='BACK_OFFICE_MONEY_WITHDRAW', sum(amount), 0) withdraw " + "from payment_transactions " + "where player_id in (select player_id from players_affiliates)" + "and status = 'SUCCESS' and event_code in ('CASHBACK', 'BONUS_CONVERSION' , 'BACK_OFFICE_MONEY_DEPOSIT', 'BACK_OFFICE_MONEY_WITHDRAW')" + "and created_date >= ?1 and created_date <= ?2 " + "group by player_id, event_code) a " + "group by player_id", nativeQuery = true) List<Object[]> getAffiliatePlayersPaymentSummary(final Date startDate, final Date endDate); }
package p0300; import robocode.Robot; import java.awt.Color; public class P0315 extends Robot { @Override public void run() { out.println("C'est parti !"); setBodyColor(Color.CYAN); setGunColor(Color.DARK_GRAY); setRadarColor(Color.CYAN); } public void onScannedRobot() { turnRadarLeft(360); } }
package controller.registrar.curriculum; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONObject; import configuration.EncryptandDecrypt; import connection.DBConfiguration; /** * Servlet implementation class CurriculumItemController */ @WebServlet("/Registrar/Controller/Registrar/Curriculum/CurriculumItemController") public class CurriculumItemController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CurriculumItemController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("plain/text"); String code = request.getParameter("codeTxt"); EncryptandDecrypt ec = new EncryptandDecrypt(); String latcode = request.getParameter("latcode"); String type = request.getParameter("type"); DBConfiguration db = new DBConfiguration(); Connection conn = db.getConnection(); Statement stmnt = null; try { stmnt = conn.createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sql = ""; // JsonObject json = new JsonObject(); // // // put some value pairs into the JSON object . // json.put("Mobile", 9999988888); // json.put("Name", "ManojSarnaik"); // // // finally output the json string // out.print(json.toString()); // // String json = new Gson().toJson(list); // // PrintWriter out = response.getWriter(); // String bindings = request.getParameter("bindings"); // response.getWriter().write(json); // out.print(json); // else if(type.equals("View")) // { // sql = "SELECT Subject_Code,Subject_Description,Subject_Units FROM `r_curriculumitem` \r\n" + // " INNER JOIN r_subject ON CurriculumItem_SubjectID = Subject_ID \r\n" + // " WHERE Subject_Display_Stat = 'Active' and CurriculumItem_Display_Status = 'Active' "; // // JSONObject obj = new JSONObject(); //// //// obj.put("name", "Anand"); //// obj.put("age", new Integer(24)); //// obj.put("place", "Bangalore"); // // try { // ResultSet rs = stmnt.executeQuery(sql); // while(rs.next()){ // obj.put("code", ec.decrypt(ec.key, ec.initVector, rs.getString("Subject_Code"))); // obj.put("desc", ec.decrypt(ec.key, ec.initVector, rs.getString("Subject_Description"))); // obj.put("unit", rs.getString("Subject_Units")); // PrintWriter out = response.getWriter(); // out.print(obj); // } // // // } catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // // List<String> list = new ArrayList<String>(); // list.add("item1"); // list.add("item2"); // list.add("item3"); // // // // } // response.getWriter().write(obj); // JSONObject jsonObject = JSONObject.fromObject( request.getQueryString() ); // // String username= jsonObject.get( "username" ); // String password= jsonObject.get( "password" ); // String type= jsonObject.get( "type" ); try { if(type.equals("Insert")) { sql = "Insert into r_curriculumitem (CurriculumItem_CurriculumID,CurriculumItem_SubjectID) values ((SELECT MAX(IFNULL(Curriculum_ID,0)) FROM r_curriculum),(SELECT Subject_ID FROM `r_subject` WHERE Subject_Code = '"+ec.encrypt(ec.key, ec.initVector, code) +"'))"; stmnt.execute(sql); } else if(type.equals("Update")){ PrintWriter out = response.getWriter(); sql = "SELECT COUNT(*) as cou FROM r_curriculumitem INNER JOIN r_subject ON CurriculumItem_SubjectID = Subject_ID INNER JOIN r_curriculum ON CurriculumItem_CurriculumID = Curriculum_ID WHERE Curriculum_Code = '"+ec.encrypt(ec.key, ec.initVector, latcode)+"' AND Subject_Code = '"+ec.encrypt(ec.key, ec.initVector, code)+"'"; out.print(sql); stmnt.execute(sql); ResultSet rs = stmnt.executeQuery(sql); while(rs.next()){ if(rs.getString("cou").equals("0")) { sql = "Insert into r_curriculumitem (CurriculumItem_CurriculumID,CurriculumItem_SubjectID) values ((SELECT Curriculum_ID FROM r_curriculum WHERE Curriculum_Code = '"+ec.encrypt(ec.key, ec.initVector, latcode) +"' ),(SELECT Subject_ID FROM `r_subject` WHERE Subject_Code = '"+ec.encrypt(ec.key, ec.initVector, code) +"'))"; out.print(sql); stmnt.execute(sql); } else { sql = "UPDATE `r_curriculumitem` SET CurriculumItem_Display_Status = 'Active' WHERE CurriculumItem_ID = (SELECT CurriculumItem_ID FROM (SELECT * FROM r_curriculumitem) AS A INNER JOIN r_curriculum ON Curriculum_ID = A.CurriculumItem_CurriculumID INNER JOIN r_subject ON Subject_ID = A.CurriculumItem_SubjectID WHERE Subject_Code = '"+ec.encrypt(ec.key, ec.initVector, code) +"' AND Curriculum_Code = '"+ec.encrypt(ec.key, ec.initVector, latcode) +"' LIMIT 1 )"; out.print(sql); stmnt.execute(sql); } } } else if(type.equals("Delete")) { sql = "Update r_curriculumitem set Subject_Display_Stat = 'Inactive' where Subject_Code = '"+ec.encrypt(ec.key, ec.initVector, latcode)+"'"; stmnt.execute(sql); } else if(type.equals("Retrieve")) { sql = "Update r_curriculumitem set Subject_Display_Stat = 'Active' where Subject_Code = '"+ec.encrypt(ec.key, ec.initVector, latcode)+"'"; stmnt.execute(sql); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package Eventos; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import Interfce_Grafica.Menu; public class EventoSorteaExercicio implements ActionListener{ private Menu menu; public EventoSorteaExercicio(Menu menu){ this.menu = menu; } public void actionPerformed(ActionEvent e) { this.menu.setMenu(this.menu.getTelaExercicio()); } }
package cn.com.signheart.common.exception; public class ConfigLoadExcetion extends DefaultException { public ConfigLoadExcetion(int errCode, String errMsg) { super(String.valueOf(errCode), errMsg); } }
package org.shiro.demo.service.impl; import java.util.List; import javax.annotation.Resource; import org.shiro.demo.entity.Goods; import org.shiro.demo.entity.Role; import org.shiro.demo.entity.User; import org.shiro.demo.service.IBaseService; import org.shiro.demo.service.IGoodsService; import org.shiro.demo.service.IRoleService; import org.springframework.stereotype.Service; @Service("goodsService") public class GoodsServiceImpl extends DefultBaseService implements IGoodsService{ @Resource(name="baseService") private IBaseService baseService; public boolean insertGoods(Goods goods) { boolean flag = false; try { baseService.save(goods); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } public boolean deleteGoods(Long id) { boolean flag = false; try { baseService.delete(Goods.class, id); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } public boolean updateGoods(Goods goods) { boolean flag = false; try { baseService.update(goods); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } public Long insertGoodsReturnId(Goods goods) { Long flag = new Long(0); try { List<Object> executeBySQLList = baseService.executeBySQLList("call p_insertgoods('"+goods.getName()+"'," +goods.getCategory().getCategoryid()+"," +goods.getShop().getCustomerid()+",'"+goods.getSummary()+"',@id);"); System.out.println(); flag = new Long(executeBySQLList.get(0).toString()); } catch (Exception e) { e.printStackTrace(); } return flag; } public boolean updateGoods(Long goodsid, String imgurl) { boolean flag = false; try { imgurl+=";"; baseService.executeBySQL("update g_goods set imgurls = concat(imgurls ,?) where goodsid = ?",imgurl,goodsid); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } public boolean deleteGoodsImgurl(Long id,String imgurl) { boolean flag = false; try { Goods goods = baseService.getById(Goods.class, id); String imgurls = goods.getImgurls(); String newImgurls = imgurls.replaceFirst(imgurl+";", ""); goods.setImgurls(newImgurls); baseService.update(goods); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } }
package com.lsjr.zizi.mvp.dialog; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.Button; import android.widget.LinearLayout.LayoutParams; import android.widget.PopupWindow; import com.lsjr.zizi.R; import com.lsjr.zizi.chat.xmpp.XmppMessage; public class SelectMessageWindow extends PopupWindow { private Button mCopy, mInstant, mCancle, mDelete; private View mMenuView; int type; private void hideButton() { if (mCopy != null) { if (type != XmppMessage.TYPE_TEXT) { mCopy.setVisibility(View.GONE); } else { mCopy.setVisibility(View.VISIBLE); } } if (mInstant != null) { if (type == XmppMessage.TYPE_CARD||type==XmppMessage.TYPE_FILE||type==XmppMessage.TYPE_GIF) { mInstant.setVisibility(View.GONE); }else{ mInstant.setVisibility(View.VISIBLE); } } } @SuppressLint("CutPasteId") public SelectMessageWindow(Context context, OnClickListener itemsOnClick, int type) { super(context); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mMenuView = inflater.inflate(R.layout.dialog_msg, null); mCopy = (Button) mMenuView.findViewById(R.id.btn_copy); mInstant = (Button) mMenuView.findViewById(R.id.btn_instant); mCancle = (Button) mMenuView.findViewById(R.id.btn_cancle); mDelete = (Button) mMenuView.findViewById(R.id.btn_delete); this.type = type; hideButton(); // 取消按钮 /* * btn_cancel.setOnClickListener(new OnClickListener() { * * public void onClick(View v) { //销毁弹出框 dismiss(); } }); */ // 设置按钮监听 mCopy.setOnClickListener(itemsOnClick); mInstant.setOnClickListener(itemsOnClick); mCancle.setOnClickListener(itemsOnClick); mDelete.setOnClickListener(itemsOnClick); // 设置SelectPicPopupWindow的View this.setContentView(mMenuView); // 设置SelectPicPopupWindow弹出窗体的宽 this.setWidth(LayoutParams.MATCH_PARENT); // 设置SelectPicPopupWindow弹出窗体的高 this.setHeight(LayoutParams.WRAP_CONTENT); // 设置SelectPicPopupWindow弹出窗体可点击 this.setFocusable(true); // 设置SelectPicPopupWindow弹出窗体动画效果 this.setAnimationStyle(R.style.Buttom_Popwindow); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw = new ColorDrawable(0xb0000000); // 设置SelectPicPopupWindow弹出窗体的背景 this.setBackgroundDrawable(dw); // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框 mMenuView.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { int height = mMenuView.findViewById(R.id.pop_layout).getTop(); int bottom = mMenuView.findViewById(R.id.pop_layout).getBottom(); int y = (int) event.getY(); if (event.getAction() == MotionEvent.ACTION_UP) { if (y < height) { dismiss(); } else if (y > bottom) { dismiss(); } } return true; } }); } }
/** * 湖北安式软件有限公司 * Hubei Anssy Software Co., Ltd. * FILENAME : InvestorVo.java * PACKAGE : com.anssy.inter.invest.vo * CREATE DATE : 2016-8-21 * AUTHOR : make it * MODIFIED BY : * DESCRIPTION : */ package com.anssy.inter.invest.vo; /** * @author make it * @version SVN #V1# #2016-8-21# * 投资人信息辅助类 */ public class InvestorVo { private Long id; /** * 图片 */ private String image; /** * 姓名 */ private String name; /** * 公司名称 */ private String companyName; /** * 职位 */ private String post; /** * 投资主体 (BODY) */ private Long body; /** * 投资领域 */ private String field; /** * 省ID */ private Long provinceId; /** * 市ID */ private Long cityId; /** * 区县ID */ private Long areaId; /** * 名片 */ private String callingCard; /** * 投资人简介 */ private String investIntro; /** * Email */ private String email; /** * 公司地址 */ private String companySite; /** * 成功案例 */ private String successfulCase; /** * 投资方式 (INVEST_WAY) */ private int investWay; /** * 投资方式1 (WAY) */ private String way; /** * 投资类型 (INVEST_TYPE) */ private int investType; /** * 投资金额 */ private String investSum; /** * 投资期限 */ private String deadline; /** * 关注地区 */ private String focus; /** * 备注 */ private String remark; /** * 其它 */ private String other; /** * 联系人 */ private String linkman; /** * 联系电话 */ private String phone; /** * 介绍网址 */ private String url; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getBody() { return body; } public void setBody(Long body) { this.body = body; } public String getField() { return field; } public void setField(String field) { this.field = field; } public Long getProvinceId() { return provinceId; } public void setProvinceId(Long provinceId) { this.provinceId = provinceId; } public Long getCityId() { return cityId; } public void setCityId(Long cityId) { this.cityId = cityId; } public Long getAreaId() { return areaId; } public void setAreaId(Long areaId) { this.areaId = areaId; } public String getCallingCard() { return callingCard; } public void setCallingCard(String callingCard) { this.callingCard = callingCard; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getInvestIntro() { return investIntro; } public void setInvestIntro(String investIntro) { this.investIntro = investIntro; } public String getPost() { return post; } public void setPost(String post) { this.post = post; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCompanySite() { return companySite; } public void setCompanySite(String companySite) { this.companySite = companySite; } public String getSuccessfulCase() { return successfulCase; } public void setSuccessfulCase(String successfulCase) { this.successfulCase = successfulCase; } public int getInvestWay() { return investWay; } public void setInvestWay(int investWay) { this.investWay = investWay; } public String getWay() { return way; } public void setWay(String way) { this.way = way; } public int getInvestType() { return investType; } public void setInvestType(int investType) { this.investType = investType; } public String getInvestSum() { return investSum; } public void setInvestSum(String investSum) { this.investSum = investSum; } public String getDeadline() { return deadline; } public void setDeadline(String deadline) { this.deadline = deadline; } public String getFocus() { return focus; } public void setFocus(String focus) { this.focus = focus; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getLinkman() { return linkman; } public void setLinkman(String linkman) { this.linkman = linkman; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOther() { return other; } public void setOther(String other) { this.other = other; } }
/** * Created by nsp on 2015/10/25. */ public class NoCard implements ATMState { ATMMachine atmMachine; public NoCard(ATMMachine machine) { this.atmMachine = machine; } @Override public void insertCard() { System.out.println("Please Enter a PIN"); this.atmMachine.setATMState(this.atmMachine.getHasCardState()); } @Override public void ejectCard() { System.out.println("Enter a card first"); } @Override public void insertPin(int pinEntered) { System.out.println("Enter a card first"); } @Override public void requestCash(int cashToWithdraw) { System.out.println("Enter a card first"); } }
public class Monster { public int hp; public int angriff; public int verteidigung; public int status; public int spezialA; public int spezialV; public int level; public int glueck; public int moral; public int element; public static void main(String[] args) { System.out.println("Hello World!"); } public int getAngriff() { return angriff; } public void setAngriff (int a) { angriff = a; } public int getHp () { return hp; } public void setHp (int b) { hp = b; } public int getVerteidigung () { return verteidigung; } public void setVerteidigung (int c) { verteidigung = c; } public int getStatus () { return status; } public void setStatus (int d) { status = d; } public int getSpezialA () { return hp; } public void setSpezialA (int e) { hp = e; } public int getSpezialV () { return spezialV; } public void setSpezialV (int f) { hp = f; } }
package cn.itcast.bookstore.cart.domain; import java.math.BigDecimal; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; /** * 购物车 * @author cpy * */ public class Cart { //private Map<String,CartItem> map = new LinkedHashMap<String,CartItem>(); private Map<String,CartItem> map = new LinkedHashMap<String,CartItem>(); public double getTotal(){ BigDecimal d = new BigDecimal("0"); for(CartItem cartItem: map.values()){ BigDecimal d1 = new BigDecimal(cartItem.getSubtotal()+""); d = d.add(d1); } return d.doubleValue(); } /** * 添加条目到购物车中 * @param cartItem */ /*public void add(CartItem cartItem){ if(map.containsKey(cartItem.getBook().getBid())){ CartItem _cartItem = map.get(cartItem.getBook().getBid()); _cartItem.setCount(_cartItem.getCount()+cartItem.getCount()); map.put(cartItem.getBook().getBid(), _cartItem); }else{ map.put(cartItem.getBook().getBid(), cartItem); } }*/ public void add(CartItem cartItem) { if(map.containsKey(cartItem.getBook().getBid())) {//判断原来车中是否存在该条目 CartItem _cartItem = map.get(cartItem.getBook().getBid());//返回原条目 _cartItem.setCount(_cartItem.getCount() + cartItem.getCount());//设置老条目的数量为,其自己数量+新条目的数量 map.put(cartItem.getBook().getBid(), _cartItem); } else { map.put(cartItem.getBook().getBid(), cartItem); } } /** * 清空所有条目 */ public void clear(){ map.clear(); } /** * 删除指定条目 * @param bid */ public void delete(String bid){ map.remove(bid); } /** * 获取所有条目 * @return */ public Collection<CartItem> getCartItems(){ return map.values(); } }
package loecraftpack.ponies.stats; import loecraftpack.LoECraftPack; import loecraftpack.enums.Race; import loecraftpack.ponies.abilities.AbilityBase; import loecraftpack.ponies.abilities.AbilityPlayerData; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; public class StatHandlerClient extends StatHandlerServer { @Override public void addPlayer(String player) { AbilityPlayerData data = AbilityPlayerData.RegisterPlayer(player); if (!LoECraftPack.isSinglePlayer()) stats.put(player, new Stats(data)); for(AbilityBase ability : data.activeAbilities) ability.SetPlayer(player, data); for(AbilityBase ability : data.passiveAbilities) ability.SetPlayer(player, data); data.bindPlayerStats(player); } //used by update packet public void updatePlayerData(String player, Race race, float energy) { if (stats.containsKey(player)) { //single-player load OR stat update Stats playerStats = (Stats)stats.get(player); playerStats.race = race; playerStats.abilityData.energy = energy; } else //multi-player load stats.put(player, new Stats(AbilityPlayerData.RegisterPlayer(player), race, energy)); } public boolean isRace(String player, Race race) { if (stats.containsKey(player)) { Stats playerStats = (Stats)stats.get(player); return playerStats.race == race || playerStats.race == Race.ALICORN; //Alicorn is master race } return false; } public Race getRace(String player) { if (stats.containsKey(player)) return ((Stats)stats.get(player)).race; else return Race.NONE; } @Override public void setRace(EntityPlayer player, Race race) { if (Minecraft.getMinecraft().isSingleplayer()) super.setRace(player, race); else setRace(player.username, race); } public void setRace(String player, Race race) { if (stats.containsKey(player)) ((Stats)stats.get(player)).race = race; } }
/* * Ara - Capture Species and Specimen Data * * Copyright © 2009 INBio (Instituto Nacional de Biodiversidad). * Heredia, Costa Rica. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.inbio.ara.facade.gis.impl; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import javax.ejb.EJB; import org.inbio.ara.facade.gis.*; import javax.ejb.Stateless; import org.inbio.ara.dto.gis.*; import org.inbio.ara.dto.taxonomy.CountryDTO; import org.inbio.ara.dto.taxonomy.CountryDTOFactory; import org.inbio.ara.eao.gis.CountryEAOLocal; import org.inbio.ara.eao.gis.FeatureTypeEAOLocal; import org.inbio.ara.eao.gis.GeographicLayerEAOLocal; import org.inbio.ara.eao.gis.GeoreferencedSiteEAOLocal; import org.inbio.ara.eao.gis.ProjectionEAOLocal; import org.inbio.ara.eao.gis.ProvinceEAOLocal; import org.inbio.ara.eao.gis.SiteCalculationMethodEAOLocal; import org.inbio.ara.eao.gis.SiteCoordinateEAOLocal; import org.inbio.ara.eao.gis.SiteEAOLocal; import org.inbio.ara.persistence.gis.Country; import org.inbio.ara.persistence.gis.FeatureType; import org.inbio.ara.persistence.gis.GeographicLayer; import org.inbio.ara.persistence.gis.GeoreferencedSite; import org.inbio.ara.persistence.gis.GeoreferencedSitePK; import org.inbio.ara.persistence.gis.Projection; import org.inbio.ara.persistence.gis.Province; import org.inbio.ara.persistence.gis.Site; import org.inbio.ara.persistence.gis.SiteCalculationMethod; import org.inbio.ara.persistence.gis.SiteCoordinate; /** * * @author esmata */ @Stateless public class GisFacadeImpl implements GisFacadeRemote { //Injections @EJB private CountryEAOLocal countryEAOImpl; @EJB private ProvinceEAOLocal provinceEAOImpl; @EJB private SiteEAOLocal siteEAOImpl; @EJB private GeographicLayerEAOLocal geographicLayerEAOImpl; @EJB private FeatureTypeEAOLocal featureTypeEAOImpl; @EJB private SiteCalculationMethodEAOLocal siteCalculationMethodEAOImpl; @EJB private ProjectionEAOLocal projectionEAOImpl; @EJB private GeoreferencedSiteEAOLocal georeferencedSiteEAOImpl; @EJB private SiteCoordinateEAOLocal siteCoordinateEAOImpl; //DTO factories private SiteDTOFactory siteDTOFactory = new SiteDTOFactory(); private SiteCoordinateDTOFactory siteCoordinateDTOFactory = new SiteCoordinateDTOFactory(); private FeatureTypeDTOFactory featureTypeDTOFactory = new FeatureTypeDTOFactory(); private SiteCalculationMethodDTOFactory siteCalculationMethodDTOFactory = new SiteCalculationMethodDTOFactory(); private ProjectionDTOFactory projectionDTOFactory = new ProjectionDTOFactory(); private CountryDTOFactory countryDTOFactory = new CountryDTOFactory(); private ProvinceDTOFactory provinceDTOFactory = new ProvinceDTOFactory(); /** * Listado de todos los feature type */ public List<FeatureTypeDTO> getAllFeatureType(){ return featureTypeDTOFactory.createDTOList (featureTypeEAOImpl.findAll(FeatureType.class)); } /** * Listado de todos los site calculation methods */ public List<SiteCalculationMethodDTO> getAllSiteCalculationMethods(){ String[] orderByFields = {"name"}; return siteCalculationMethodDTOFactory.createDTOList (siteCalculationMethodEAOImpl.findAllAndOrderBy( SiteCalculationMethod.class, orderByFields)); } /** * Listado de todos las projections */ public List<ProjectionDTO> getAllProjection(){ String[] orderByFields = {"name"}; return projectionDTOFactory.createDTOList (projectionEAOImpl.findAllAndOrderBy(Projection.class, orderByFields)); } public List<ProvinceDTO> getAllProvincesForContry(Long cId){ return provinceDTOFactory.createDTOList (provinceEAOImpl.listAllByContryId(cId)); } /** * Retorna un listado de la sitios */ public List<SiteDTO> getAllSitePaginated(int first, int totalResults) { String[] orderByFields = {"description"}; List<Site> sList = siteEAOImpl.findAllPaginatedFilterAndOrderBy(Site.class, first, totalResults,orderByFields,null); if (sList == null) { return null; } else { return updateCountryAndProvinceName(siteDTOFactory.createDTOList(sList)); } } public Long countSites() { return siteEAOImpl.count(Site.class); } /** * Metodo que retorna la lista completa de paises */ @Deprecated public List<GeographicLayerDTO> getAllCountries(){ return countryEAOImpl.getAllCountries(); } public List<CountryDTO> findAllCountries(){ String[] orderByFields = {"value"}; return countryDTOFactory.createDTOList (countryEAOImpl.findAllAndOrderBy(Country.class, orderByFields)); } public CountryDTO getCountryForSite(Long siteId) { List<GeoreferencedSite> geoRefSites = georeferencedSiteEAOImpl.findAllBySiteAndLayer (siteId, COUNTRY_LAYER); GeoreferencedSite gs; if(geoRefSites!=null && geoRefSites.size() !=0){ //System.out.println("[getCountryForSite] encontro sitios>"+geoRefSites.size()); gs = geoRefSites.get(0); Country aux = (Country) countryEAOImpl.findById (Country.class, gs.getGeoreferencedSitePK().getGeographicSiteId()); return countryDTOFactory.createDTO(aux); } else return null; } public ProvinceDTO getProvinceForSite(Long siteId) { List<GeoreferencedSite> geoRefSites = georeferencedSiteEAOImpl. findAllBySiteAndLayer(siteId, PROVINCE_LAYER); GeoreferencedSite gs; if(geoRefSites!=null && geoRefSites.size() !=0){ //System.out.println("[getProvinceForSite] encontro sitios>"+geoRefSites.size()); gs = geoRefSites.get(0); Province aux = (Province) provinceEAOImpl.findById (Province.class, gs.getGeoreferencedSitePK().getGeographicSiteId()); return provinceDTOFactory.createDTO(aux); } else return null; } /** * Metodo que retorna las provincias pertenecientes a un pais */ public List<GeographicLayerDTO> getProvincesByCountry(Long country){ return provinceEAOImpl.getProvincesByCountry(country); } /** * Metodo que retorna todos los sitios de la base de datos * @return */ public List<SiteDTO> getAllSites(){ List<Site> sitios = siteEAOImpl.findAllOrdered(); List<SiteDTO> result = new ArrayList<SiteDTO>(); for(Site s: sitios){ result.add(siteDTOFactory.createDTO(s)); } return result; } public SiteDTO updateCountryAndProvinceName(SiteDTO sDTO) { Country c; Province p; if (sDTO.getProvinceId() != null) { p = provinceEAOImpl.findById(Province.class, sDTO.getProvinceId()); sDTO.setProvinceName(p.getValue()); c = countryEAOImpl.findById(Country.class, p.getCountryId()); sDTO.setCountryName(c.getValue()); sDTO.setCountryId(c.getCountryId()); } else if (sDTO.getCountryId() != null) { c = countryEAOImpl.findById(Country.class, sDTO.getCountryId()); sDTO.setCountryName(c.getValue()); } return sDTO; } public List<SiteDTO> updateCountryAndProvinceName(List<SiteDTO> sDTOList) { List<SiteDTO> resultSiteDTOList = new ArrayList<SiteDTO>(); for (SiteDTO sDTO : sDTOList) { resultSiteDTOList.add(updateCountryAndProvinceName(sDTO)); } return resultSiteDTOList; } public GeographicLayerDTO getAllGeographicalLayer(Long geographicLayerId) { GeographicLayer gl = (GeographicLayer) geographicLayerEAOImpl. findById(GeographicLayer.class, geographicLayerId); GeographicLayerDTO glDTO = new GeographicLayerDTO (gl.getGeographicLayerId(), gl.getName(), gl.getDescription(), null, null); if(geographicLayerId.equals(PROVINCE_LAYER)){ GeographicLayer ancestorGL = (GeographicLayer) geographicLayerEAOImpl.findById(GeographicLayer.class, COUNTRY_LAYER); glDTO.setAncestorKey(ancestorGL.getGeographicLayerId()); glDTO.setAncestorName(ancestorGL.getName()); } return glDTO; } public List<GeographicLayerValueDTO> getAllGeographicalLayerValuesForGeographicLayerAndAncestor (Long geographicLayerId, Long ancestorGeographicValueId) { List<GeographicLayerValueDTO> glvDTOList= new ArrayList<GeographicLayerValueDTO>(); GeographicLayerValueDTO glvDTO; if(geographicLayerId.equals(PROVINCE_LAYER)){ Country c; for(Province p : provinceEAOImpl.listAllByContryId(ancestorGeographicValueId)){ c = (Country) countryEAOImpl.findById(Country.class, p.getCountryId()); glvDTO = new GeographicLayerValueDTO (PROVINCE_LAYER,p.getProvinceId(), p.getValue(), c.getCountryId(),c.getValue()); glvDTOList.add(glvDTO); } } return glvDTOList; } public List<GeographicLayerValueDTO> getAllGeographicalLayerValuesForGeographicLayer (Long geographicLayerId) { List<GeographicLayerValueDTO> glvDTOList= new ArrayList<GeographicLayerValueDTO>(); GeographicLayerValueDTO glvDTO; if(geographicLayerId.equals(COUNTRY_LAYER)){ for(Country c : countryEAOImpl.listAll()){ glvDTO = new GeographicLayerValueDTO (COUNTRY_LAYER,c.getCountryId(), c.getValue(), null, null); glvDTOList.add(glvDTO); } } else if(geographicLayerId.equals(PROVINCE_LAYER)){ Country c; for(Province p : provinceEAOImpl.listAll()){ c = (Country) countryEAOImpl.findById(Country.class, p.getCountryId()); glvDTO = new GeographicLayerValueDTO (PROVINCE_LAYER,p.getProvinceId(), p.getValue(), c.getCountryId(),c.getValue()); glvDTOList.add(glvDTO); } } return glvDTOList; } public List<GeographicLayerDTO> getAllGeographicalLayers() { List<GeographicLayer> glList = geographicLayerEAOImpl.findAll(GeographicLayer.class); GeographicLayer ancestorGL; List<GeographicLayerDTO> glDTOList = new ArrayList<GeographicLayerDTO>(); GeographicLayerDTO glDTO; for(GeographicLayer gl: glList){ glDTO = new GeographicLayerDTO (gl.getGeographicLayerId(), gl.getName(), gl.getDescription(), null, null); if(gl.getGeographicLayerId().equals(PROVINCE_LAYER)){ ancestorGL = (GeographicLayer) geographicLayerEAOImpl. findById(GeographicLayer.class, COUNTRY_LAYER); glDTO.setAncestorKey(ancestorGL.getGeographicLayerId()); glDTO.setAncestorName(ancestorGL.getName()); } glDTOList.add(glDTO); } return glDTOList; } public GeographicLayerValueDTO getAllGeographicalLayerValueForGeographicLayerAndId (Long geographicLayerId, Long geographicLayerValueId) { GeographicLayerValueDTO glvDTO = null; Country c; if(geographicLayerId.equals(COUNTRY_LAYER)){ c = (Country) countryEAOImpl.findById(Country.class, geographicLayerValueId); glvDTO = new GeographicLayerValueDTO (COUNTRY_LAYER, c.getCountryId(), c.getValue(), null, null); } else if(geographicLayerId.equals(PROVINCE_LAYER)){ Province p = (Province) provinceEAOImpl.findById (Province.class, geographicLayerValueId); c = (Country) countryEAOImpl.findById(Country.class, p.getCountryId()); glvDTO = new GeographicLayerValueDTO (PROVINCE_LAYER,p.getProvinceId(), p.getValue(), c.getCountryId(),c.getValue()); } return glvDTO; } /** * Metodo encargado de guardar en la base de datos un nuevo sitio con sus * respectivas coordenas y capas geograficas relacionadas */ public SiteDTO saveNewSite(SiteDTO sDTO, List<SiteCoordinateDTO> coorList, List<GeoreferencedSitePKDTO> georefSiteList) { //System.out.println("Entro a Save New Site"); //Nueva entidad a persistir //Site site = new Site(); //Asignar las propiedades de nuevo sition /*site.setBaseProjectionId(sDTO.getBaseProjectionId()); site.setDescription(sDTO.getDescription()); site.setFeatureTypeId(sDTO.getFeatureTypeId()); site.setGeodeticDatum(sDTO.getGeodeticDatum()); site.setName(sDTO.getName()); site.setOriginalProjectionId(sDTO.getOriginalProjectionId()); site.setPrecision(sDTO.getPrecision()); site.setSiteCalculationMethodId(sDTO.getSiteCalculationMethodId()); site.setSiteCoordinates(new ArrayList<SiteCoordinate>()); site.setGeoreferencedSites(new ArrayList<GeoreferencedSite>());*/ //System.out.println("Antes del Factory = " + sDTO.getUserName()); Site site = siteDTOFactory.createPlainEntity(sDTO); //System.out.println("Despues del Factory = " +site.getCreatedBy()); //Persistir la nueva entidad siteEAOImpl.create(site); //Actualizar el CurrentDTO con el id asignado SiteDTO result = siteDTOFactory.createDTO(site); //Persistir las coordenadas asociadas if (coorList != null) { if (coorList.size() > 0) { for (int i = 0; i < coorList.size(); i++) { SiteCoordinateDTO dto = coorList.get(i); //dto.setSiteId(result.getSiteId()); SiteCoordinate newCoor = new SiteCoordinate(); /* newCoor.setSiteId(site); newCoor.setSequence(new Long(i + 1)); newCoor.setLatitude(dto.getLatitude()); newCoor.setLongitude(dto.getLongitude()); newCoor.setOriginalX(dto.getOriginalX()); newCoor.setOriginalY(dto.getOriginalY()); newCoor.setVerbatimLongitude(dto.getVerbatimLongitude()); newCoor.setVerbatimLatitude(dto.getVerbatimLatitude()); */ newCoor = siteCoordinateDTOFactory.createPlainEntity(dto); newCoor.setSiteId(site); newCoor.setSequence(new Long(i + 1)); siteCoordinateEAOImpl.create(newCoor); } } } //Persistir la division politica del sitio if (georefSiteList != null) { for (GeoreferencedSitePKDTO gsPK : georefSiteList) { saveOrUpdateGeoreferenceForSite(site.getSiteId(), gsPK.getGeographicLayerId(), gsPK.getGeographicSiteId(), gsPK.getUserName()); } } //Retornar el nuevo dto return result; } /** * Metodo para eliminar Localidades por su id * Además elimina las dependencias en las tablas: * - site_coordinate * - * @param Id */ public void deleteSite(Long Id){ Site aux = this.siteEAOImpl.findById(Site.class, Id); if(aux!=null){ //Delete asociated coordinates this.siteCoordinateEAOImpl.deleteBySiteId(Id); //Delete asociated countries and provinces this.georeferencedSiteEAOImpl.deleteBySiteId(Id); //Finally delete the site this.siteEAOImpl.delete(aux); } } /** * Metodo encargado de guardar en la base de datos el sitio editado * respectivas coordenas y capas geograficas relacionadas */ public SiteDTO updateSite(SiteDTO sDTO, List<SiteCoordinateDTO> coorList, List<GeoreferencedSitePKDTO> georefSiteList) { //Nueva entidad a persistir Site site = siteEAOImpl.findById(Site.class, sDTO.getSiteId()); //Asignar las propiedades de nuevo sition /* site.setBaseProjectionId(sDTO.getBaseProjectionId()); site.setDescription(sDTO.getDescription()); site.setFeatureTypeId(sDTO.getFeatureTypeId()); site.setGeodeticDatum(sDTO.getGeodeticDatum()); site.setName(sDTO.getName()); site.setOriginalProjectionId(sDTO.getOriginalProjectionId()); site.setPrecision(sDTO.getPrecision()); site.setSiteCalculationMethodId(sDTO.getSiteCalculationMethodId()); site.setSiteCoordinates(new ArrayList<SiteCoordinate>()); site.setGeoreferencedSites(new ArrayList<GeoreferencedSite>()); */ site = siteDTOFactory.updatePlainEntity(sDTO, site); //Persistir la entidad siteEAOImpl.update(site); //Actualizar el CurrentDTO con el id asignado SiteDTO result = siteDTOFactory.createDTO(site); //Eliminar las coordenadas acuales siteCoordinateEAOImpl.deleteBySiteId(site.getSiteId()); //Persistir las coordenadas asociadas if (coorList != null) { if (coorList.size() > 0) { for (int i = 0; i < coorList.size(); i++) { SiteCoordinateDTO dto = coorList.get(i); SiteCoordinate newCoor = new SiteCoordinate(); newCoor = siteCoordinateDTOFactory.createPlainEntity(dto); newCoor.setSiteId(site); newCoor.setSequence(new Long(i + 1)); //para eliminar el id que fue asignado anteriormente newCoor.setSiteCoordinateId(null); /* newCoor.setLatitude(dto.getLatitude()); newCoor.setLongitude(dto.getLongitude()); newCoor.setOriginalX(dto.getOriginalX()); newCoor.setOriginalY(dto.getOriginalY()); newCoor.setVerbatimLongitude(dto.getVerbatimLongitude()); newCoor.setVerbatimLatitude(dto.getVerbatimLatitude()); */ siteCoordinateEAOImpl.create(newCoor); } } } //Persistir la division politica del sitio if (georefSiteList != null) { for (GeoreferencedSitePKDTO gsPK : georefSiteList) { saveOrUpdateGeoreferenceForSite(site.getSiteId(), gsPK.getGeographicLayerId(), gsPK.getGeographicSiteId(), gsPK.getUserName()); } } //Retornar el nuevo dto return result; } public void saveOrUpdateGeoreferenceForSite(Long siteId, Long layerId, Long value, String user) { //Busca las capas: PROVINCIA o COUNTRY para el site Id List<GeoreferencedSite> gsList = georeferencedSiteEAOImpl. findAllBySiteAndLayer(siteId,layerId); GeoreferencedSite gs = null; GeoreferencedSitePK gsPK; if(gsList == null || gsList.isEmpty()){ //Nuevo GeoreferencedSite gsPK = new GeoreferencedSitePK(siteId, layerId, value); gs = new GeoreferencedSite(gsPK); //aqui porque no usa DTOFacade gs.setCreatedBy(user); gs.setCreationDate(new GregorianCalendar()); gs.setLastModificationBy(user); gs.setLastModificationDate(new GregorianCalendar()); } else if (gsList.size() == 1){ //Edit GeoreferencedSite gs = gsList.get(0); georeferencedSiteEAOImpl.delete(gs); gsPK = new GeoreferencedSitePK(siteId, layerId, value); gs = new GeoreferencedSite(gsPK); gs.setCreatedBy(user); gs.setCreationDate(new GregorianCalendar()); gs.setLastModificationBy(user); gs.setLastModificationDate(new GregorianCalendar()); } //Falta un caso en que haya mas de un georeferecedSite, pero por ahora no se implementara georeferencedSiteEAOImpl.create(gs); } /** * Metodo encargado de guardar nuevas capas geograficas o editar existentes * @param geographicLayerValueDTO */ public boolean saveOrUpdateGeographicLayerValue (GeographicLayerValueDTO geographicLayerValueDTO) { Country c; Province p; //En caso de que la capa geografica sea un pais if(geographicLayerValueDTO.getGeographicLayerKey().equals(COUNTRY_LAYER)){ //Validar si los datos no son vacios String aux = geographicLayerValueDTO.getName(); if(aux==null||aux.equals("")) return false; if(geographicLayerValueDTO.getGeographicLayerValueKey() == null){ System.out.println("new country"); c = new Country(geographicLayerValueDTO.getName()); countryEAOImpl.create(c); } else { System.out.println("edit country"); c = (Country) countryEAOImpl.findById(Country.class, geographicLayerValueDTO.getGeographicLayerValueKey()); System.out.println(" country con Id>"+c.getCountryId()); System.out.println(" country con Name>"+geographicLayerValueDTO.getName()); c.setValue(geographicLayerValueDTO.getName()); countryEAOImpl.update(c); } //En caso de que la capa geografica sea una provincia } else if(geographicLayerValueDTO.getGeographicLayerKey().equals(PROVINCE_LAYER)){ //Validar si los datos no son vacios String aux = geographicLayerValueDTO.getName(); Long aux2 = geographicLayerValueDTO.getAncestorGeographicLayerValueKey(); if(aux==null||aux2==null||aux.equals("")||aux2.equals(new Long(-1))) return false; c = (Country) countryEAOImpl.findById(Country.class, geographicLayerValueDTO.getAncestorGeographicLayerValueKey()); if(geographicLayerValueDTO.getGeographicLayerValueKey() == null){ System.out.println("new province"); p = new Province(); p.setCountryId(c.getCountryId()); p.setValue(geographicLayerValueDTO.getName()); provinceEAOImpl.create(p); } else { System.out.println("edit province"); p = (Province) provinceEAOImpl.findById(Province.class, geographicLayerValueDTO.getGeographicLayerValueKey()); p.setCountryId(c.getCountryId()); p.setValue(geographicLayerValueDTO.getName()); provinceEAOImpl.update(p); } } return true; } public CountryDTO getCountryByCountryId(Long countryId) { CountryDTO result; Country country = (Country) countryEAOImpl.findById (Country.class, countryId); if(country !=null) { result = countryDTOFactory.createDTO(country); } else { result = null; } return result; } public List<SiteDTO> getSiteByDescription(String siteDescription, int base, int offset) { if(siteDescription != null) return siteDTOFactory.createDTOList(siteEAOImpl.getSiteByDescription(siteDescription, base, offset)); else return null; } public String getSiteDescriptionById(Long siteId) { return siteEAOImpl.getSiteDescriptionById(siteId); } public String getReprojection(float valueX, float valueY, Long projectionSRID, Long reprojectioSRID) { return projectionEAOImpl.reprojection(valueX, valueY, projectionSRID, reprojectioSRID); } public List<GeoreferencedDTO> getGeoreferencedSitesByCoordinates(List<SiteCoordinateDTO> coordinates, Long type) { List<GeoreferencedDTO> result = new ArrayList<GeoreferencedDTO>(); List<GeographicLayer> layers = geographicLayerEAOImpl.findAllAndOrderBy(GeographicLayer.class, null); List<String> sitesName; for(GeographicLayer layer: layers) { //manda al EAO sitesName = georeferencedSiteEAOImpl.findGeoreferencedSitesByCoordinate(layer.getTableName(), layer.getMainValueField(), coordinates, type); if(!sitesName.isEmpty()) { for(String siteName:sitesName) { GeoreferencedDTO georeferenced = new GeoreferencedDTO(); georeferenced.setLayerName(layer.getName()); georeferenced.setValue(siteName); result.add(georeferenced); } } } return result; } }
package two.essential; import java.math.BigDecimal; /** * @author O. Tedikova * @version 1.0 */ public class BigFactorialExecutor { public static int calculateZerosInFactorial(int number) { BigDecimal result = BigDecimal.ONE; int countOfZeros = 0; for (int i = 1; i <= number; i++) { result = result.multiply(new BigDecimal(i)); while (result.remainder(BigDecimal.TEN).equals(BigDecimal.ZERO)) { result = result.divide(BigDecimal.TEN); countOfZeros += 1; } } return countOfZeros; } public static BigDecimal calculateFactorial(int number) { BigDecimal result = BigDecimal.ONE; for (int i = 1; i <= number; i++) { result = result.multiply(new BigDecimal(i)); } return result; } public static int calculateZerosInFactorialString(int number) { BigDecimal factorial = calculateFactorial(number); String sequence = factorial.toString(); int countOfZeros = 0; int i = sequence.length() - 1; while (sequence.charAt(i) == '0') { countOfZeros += 1; i--; } return countOfZeros; } }
package de.domistiller.vp.android; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.text.Html; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import de.domistiller.vpapi.model.Metadata; public class MetadataActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_metadata); Bundle extras = getIntent().getExtras(); Metadata metadata = (Metadata) extras.getSerializable("metadata"); ((TextView) findViewById(R.id.metadata_version_content)).setText(String.valueOf(metadata.getVersion())); Date lastUpdated = metadata.getLastUpdated(); SimpleDateFormat dateFormatter = new SimpleDateFormat("'am' dd.MM. 'um' HH:mm"); String date = dateFormatter.format(lastUpdated); ((TextView) findViewById(R.id.metadata_lastUpdated_content)) .setText(date); String notes = metadata.getNotes(); notes = notes.replace("LF", "\n\n"); ((TextView) findViewById(R.id.metadata_notes_content)).setText(notes); ArrayList<String> missingRooms = metadata.getMissingRooms(); ArrayList<String> absentClasses = metadata.getAbsentClasses(); ArrayList<String> absentCourses = metadata.getAbsentCourses(); TextView missingRoomsView = (TextView) findViewById(R.id.metadata_missingRooms_content); TextView absentClassesView = (TextView) findViewById(R.id.metadata_absentClasses_content); TextView absentCoursesView = (TextView) findViewById(R.id.metadata_absentCourses_content); LinearLayout missingRoomsContainer = (LinearLayout) findViewById(R.id.missingRoomsContainer); LinearLayout absentClassesContainer = (LinearLayout) findViewById(R.id.absentClassesContainer); LinearLayout absentCoursesContainer = (LinearLayout) findViewById(R.id.absentCoursesContainer); View missingRoomsLine = findViewById(R.id.missingRoomsLine); View absentClassesLine = findViewById(R.id.absentClassesLine); View absentCoursesLine = findViewById(R.id.absentCoursesLine); if (missingRooms.isEmpty()) { missingRoomsContainer.setVisibility(View.GONE); missingRoomsLine.setVisibility(View.GONE); } else { missingRoomsView.setText(generateList(missingRooms)); } if (absentClasses.isEmpty()) { absentClassesContainer.setVisibility(View.GONE); absentClassesLine.setVisibility(View.GONE); } else { absentClassesView.setText(generateList(absentClasses)); } if (absentCourses.isEmpty()) { absentCoursesContainer.setVisibility(View.GONE); absentCoursesLine.setVisibility(View.GONE); } else { absentCoursesView.setText(generateList(absentCourses)); } getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } private String generateList(ArrayList<String> list) { StringBuilder builder = new StringBuilder(); for (String currentClass : list) { builder.append(Html.fromHtml("&#8226; ") + currentClass + "\n"); } builder.deleteCharAt(builder.length() - 1); return builder.toString(); } }
/* * Ara - Capture Species and Specimen Data * * Copyright © 2009 INBio (Instituto Nacional de Biodiversidad). * Heredia, Costa Rica. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.inbio.ara.eao.transaction; import java.util.Calendar; import java.util.List; import javax.ejb.Local; import org.inbio.ara.eao.BaseLocalEAO; import org.inbio.ara.persistence.transaction.Transaction; /** * * @author echinchilla */ @Local public interface TransactionEAOLocal extends BaseLocalEAO<Transaction, Long> { public Long countTransactionByCollecionId(Long collectionId); public boolean existsTransactionId(Long transactionId, Long collectionId); public List<org.inbio.ara.persistence.person.Person> getPersonsByInstitution(Long institutionId); public List<org.inbio.ara.persistence.institution.Institution> getAllInstitutions(); public List<org.inbio.ara.persistence.person.Person> getPersonsWithoutInstitution(); public List<java.lang.Long> findByInvoiceNumber(String invoiceNumber, Long collectionId); public List<Long> findByDescription(String description, Long collectionId); public List<Long> findByEstimatedSpecimenCount(Long estimatedSpecimenCount, Long collectionId); public List<Long> findBySenderInstitutionId(Long senderInstitutionId, Long collectionId); public List<Long> findBySenderPersonId(Long senderPersonId, Long collectionId); public List<Long> findByReceiverInstitutionId(Long receiverInstitutionId, Long collectionId); public List<Long> findByReceiverPersonId(Long receiverPersonId, Long collectionId); public List<Long> findByTransactionTypeId(Long transactionTypeId, Long collectionId); public List<Long> findByCollectionId(Long collectionId); public List<Long> findPersonIdByPersonName(String name); public List<Long> findInstitutionIdByInstitutionCode(String institutionCode); public List<Long> findByTransactionDateRange(Calendar initialTransactionDate, Calendar finalTransactionDate, Long collectionId); public List<Long> findByExpirationDateRange(Calendar initialExpirationDate, Calendar finalExpirationDate, Long collectionId); public List<Long> findBySpecimenId (Long collectionId, Long specimenId); public List<Long> findByDeliveryDateRange(Calendar initialDeliveryDate, Calendar finalDeliveryDate, Long collectionId); public List<Long> findByReceivingDateRange(Calendar initialReceivingDate, Calendar finalReceivingDate, Long collectionId); public List<Long> findByTransactedSpecimenStatusId (Long transactedSpecimenStatusId, Long collectionId); public List<Long> findByTransactedSpecimenDescription(String description, Long collectionId); }
package matthbo.mods.darkworld; import net.minecraftforge.common.MinecraftForge; import matthbo.mods.darkworld.handler.BiomeDecoratorHandler; import matthbo.mods.darkworld.handler.BucketHandler; import matthbo.mods.darkworld.handler.ConfigHandler; import matthbo.mods.darkworld.handler.EventHandler; import matthbo.mods.darkworld.init.ModAchievements; import matthbo.mods.darkworld.init.ModBiomes; import matthbo.mods.darkworld.init.ModBlocks; import matthbo.mods.darkworld.init.ModDimensions; import matthbo.mods.darkworld.init.ModFluids; import matthbo.mods.darkworld.init.ModItems; import matthbo.mods.darkworld.init.ModRecipes; import matthbo.mods.darkworld.proxy.IProxy; import matthbo.mods.darkworld.reference.Refs; import matthbo.mods.darkworld.utility.LogHelper; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod(modid = Refs.MOD_ID, name = Refs.MOD_NAME, version = Refs.VERSION, guiFactory = Refs.GUI_FACTORY_CLASS, dependencies = Refs.DEPENDS) public class DarkWorld { @Instance(Refs.MOD_ID) public static DarkWorld instance; @SidedProxy(clientSide = Refs.CLIENT_PROXY_CLASS, serverSide = Refs.SERVER_PROXY_CLASS) public static IProxy proxy; public static ConfigHandler Config = new ConfigHandler(); //TODO remake darkworldPortal ;( //TODO make it so that vanilla tools don't do shit in the darkworld (will be very nice if it is easy to do) //TODO make stuff added to the oreDictionary //TODO check for more broken shit //I like trains and how the DW portal spits out particles in overworld but sucks them in in the DW @Mod.EventHandler public static void preInit(FMLPreInitializationEvent event){ ConfigHandler.init(event.getSuggestedConfigurationFile()); FMLCommonHandler.instance().bus().register(Config); ModBlocks.init(); ModFluids.init(); ModItems.init(); MinecraftForge.EVENT_BUS.register(BucketHandler.INSTANCE); ModRecipes.initCrafting(); ModRecipes.initSmelting(); LogHelper.info("Pre Initialization Complete"); } @Mod.EventHandler public static void init(FMLInitializationEvent event){ proxy.textureFix(); ModBiomes.init(); MinecraftForge.TERRAIN_GEN_BUS.register(new BiomeDecoratorHandler()); ModDimensions.init(); ModAchievements.init(); FMLCommonHandler.instance().bus().register(new EventHandler()); LogHelper.info("Initialization Complete"); } @Mod.EventHandler public static void postInit(FMLPostInitializationEvent event){ LogHelper.info("Post Initialization Complete"); } }
package com.metoo.module.app.manage.buyer.tool; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.nutz.json.Json; import org.nutz.json.JsonFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.metoo.core.tools.CommUtil; import com.metoo.foundation.domain.GoodsSku; import com.metoo.foundation.domain.Goods; import com.metoo.foundation.domain.GoodsLog; import com.metoo.foundation.domain.GoodsSpecProperty; import com.metoo.foundation.domain.OrderForm; import com.metoo.foundation.domain.StoreLog; import com.metoo.lucene.LuceneUtil; import com.metoo.lucene.tools.LuceneVoTools; @Component public class AppOrderBuyerTools { @Autowired private LuceneVoTools luceneVoTools; }
package com.sda.company.service; import com.sda.company.model.Company; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public interface CompanyService { Company create(Company company); List<Company> getAll(); List<Company> getAllPaginated(Integer pageNumber, Integer pageSize, String shortBy); Company findByName(String name); String populate (List<Company> companiesList); void deleteCompanyById(Integer id); void deleteByRegistrationNumber(String registrationNumber); Optional<Company> findById(Integer id); }
package com.ipincloud.iotbj.srv.domain; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Time; import java.sql.Date; import java.sql.Timestamp; import com.alibaba.fastjson.annotation.JSONField; //(SensorCategary)传感器类型 //generate by redcloud,2020-07-24 19:59:20 public class SensorCategary implements Serializable { private static final long serialVersionUID = 53L; // 自增ID private Long id ; // 名称 private String title ; // 图标 private String icon ; // 数量 private String num ; public Long getId() { return id ; } public void setId(Long id) { this.id = id; } public String getTitle() { return title ; } public void setTitle(String title) { this.title = title; } public String getIcon() { return icon ; } public void setIcon(String icon) { this.icon = icon; } public String getNum() { return num ; } public void setNum(String num) { this.num = num; } }
package com.app.tools; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFComment; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFPatriarch; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.util.CellRangeAddress; /** * 利用开源组件POI3.0.2动态导出EXCEL文档 * * @version v1.0 * @param <T> * T传bean * 应用泛型,代表任意一个符合javabean风格的类 * 注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx() * byte[]表jpg格式的图片数据 */ public class ExcelExportUtils<T> { //获取文件分割符 public static final String FILE_SEPARATOR = System.getProperties() .getProperty("file.separator"); /** * @param paramList 字段名,用来从dataset拿取值 * @param tableTitle 表格标题头 * @param dataset 表格内容 */ public HSSFWorkbook exportExcel(String tableTitle,List<String> paramList, List<Map<String,Object>> dataset) { return exportExcel(tableTitle, null, paramList, dataset, "yyyy-MM-dd"); } /** * @param tableTitle 表格标题头 * @param headers 列头,每一列数据的列头 * @param paramList 字段名,用来从dataset拿取值 * @param dataset 表格内容 */ public HSSFWorkbook exportExcel(String tableTitle,String[] headers,List<String> paramList, List<Map<String,Object>> dataset) { return exportExcel(tableTitle, headers, paramList, dataset, "yyyy-MM-dd"); } /** * @param paramList 字段名,用来从dataset拿取值 * @param headers 列头,每一列数据的列头 * @param dataset 表格内容 * @param pattern 如果有时间数据,设定输出格式。默认为"yyy-MM-dd",可以自定义格式 */ public HSSFWorkbook exportExcel(String[] headers,List<String> paramList, List<Map<String,Object>> dataset, String pattern) { return exportExcel("未命名表格", headers, paramList, dataset,pattern); } /** * 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上 * @param paramList * 字段名,用来从dataset拿取值 * @param title * 表格sheet名字 * @param headers * 表格属性列名数组 * @param dataset * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) * @param pattern * 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd" */ @SuppressWarnings("unchecked") public HSSFWorkbook exportExcel(String tableTitle, String[] headers, List<String> paramList, List<Map<String,Object>> dataset, String pattern) { // 声明一个工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一个表格 HSSFSheet sheet = workbook.createSheet(tableTitle); // 设置表格默认列宽度为15个字节 sheet.setDefaultColumnWidth(15); //标题头样式 HSSFCellStyle styleHeadTitle = workbook.createCellStyle(); // 设置这些样式 styleHeadTitle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); styleHeadTitle.setBorderBottom(HSSFCellStyle.BORDER_THIN); styleHeadTitle.setBorderLeft(HSSFCellStyle.BORDER_THIN); styleHeadTitle.setBorderRight(HSSFCellStyle.BORDER_THIN); styleHeadTitle.setBorderTop(HSSFCellStyle.BORDER_THIN); styleHeadTitle.setFillForegroundColor(HSSFColor.WHITE.index); //左右 上下居中 styleHeadTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER); styleHeadTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 生成一个字体 HSSFFont fontHeadTitle = workbook.createFont(); fontHeadTitle.setColor(HSSFColor.VIOLET.index); fontHeadTitle.setFontHeightInPoints((short) 12); fontHeadTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); fontHeadTitle.setColor(HSSFColor.BLUE.index); // 把字体应用到当前的样式 styleHeadTitle.setFont(fontHeadTitle); // 生成一个样式 HSSFCellStyle style = workbook.createCellStyle(); // 设置这些样式 style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setFillForegroundColor(IndexedColors.TEAL.getIndex()); //左右 上下居中 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 生成一个字体 HSSFFont font = workbook.createFont(); font.setColor(HSSFColor.WHITE.index); font.setFontHeightInPoints((short) 12); // 把字体应用到当前的样式 style.setFont(font); // 生成并设置另一个样式 HSSFCellStyle style2 = workbook.createCellStyle(); style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); //框线 style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); style2.setBorderRight(HSSFCellStyle.BORDER_THIN); style2.setBorderTop(HSSFCellStyle.BORDER_THIN); style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //背景色 style2.setFillForegroundColor(HSSFColor.WHITE.index); // 生成另一个字体 HSSFFont font2 = workbook.createFont(); font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); font2.setColor(HSSFColor.BLACK.index); // 把字体应用到当前的样式 style2.setFont(font2); // 声明一个画图的顶级管理器 HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); // 定义注释的大小和位置,详见文档 HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); // 设置注释内容 comment.setString(new HSSFRichTextString("数据由学生在线考试系统提供")); // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容. comment.setAuthor("leno"); //产生表格标题 HSSFRow rowHeadTitle = sheet.createRow(0); rowHeadTitle.setHeight((short) 450);//目的是想把行高设置成30px for (short i = 0; i < headers.length; i++) { HSSFCell cell = rowHeadTitle.createCell(i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(tableTitle); cell.setCellValue(text); } //提供合并的起始列标,索引从0开始 int start = 0; int end = headers.length-1; CellRangeAddress region = new CellRangeAddress(0, 0, start, end); //合并单元格(给表头去用) sheet.addMergedRegion(region); // 产生表头行 HSSFRow row = sheet.createRow(1); row.setHeight((short) 400);//目的是想把行高设置成25px for (short i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } //遍历集合获取数据 if(!dataset.isEmpty()) { for(int i=0; i<dataset.size(); i++) { row = sheet.createRow(i + 2); //从第三行开始写数据 row.setHeight((short) 350);//目的是想把行高设置成22px Map<String,Object> map = dataset.get(i); //遍历字段集合,用字段来寻找map中的value int j = 0; for(String str : paramList) { HSSFCell dataCell = row.createCell(j); //给每个单元格设置样式 dataCell.setCellStyle(style2); dataCell.setCellValue(map.get(str).toString()); j++; } } } return workbook; } }
package com.jetruby.nfc.example.activities.keyexchange; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.jetruby.nfc.example.R; import com.jetruby.nfc.example.nfc.OutcomingNfcManager; public class KeyReceiverActivity extends AppCompatActivity implements OutcomingNfcManager.NfcActivity { private NfcAdapter nfcAdapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.key_exchange_activity); this.nfcAdapter = NfcAdapter.getDefaultAdapter(this); } public void enableForegroundDispatch(AppCompatActivity activity, NfcAdapter adapter) { final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass()); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0); IntentFilter[] filters = new IntentFilter[1]; String[][] techList = new String[][]{}; filters[0] = new IntentFilter(); filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED); filters[0].addCategory(Intent.CATEGORY_DEFAULT); try { filters[0].addDataType("text/plain"); } catch (IntentFilter.MalformedMimeTypeException ex) { throw new RuntimeException("Check your MIME type"); } adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList); } public void disableForegroundDispatch(final AppCompatActivity activity, NfcAdapter adapter) { adapter.disableForegroundDispatch(activity); } private void receiveMessageFromDevice(Intent intent) { String action = intent.getAction(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { Parcelable[] parcelables = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage inNdefMessage = (NdefMessage) parcelables[0]; NdefRecord[] inNdefRecords = inNdefMessage.getRecords(); NdefRecord ndefRecord_0 = inNdefRecords[0]; String inMessage = new String(ndefRecord_0.getPayload()); } } @Override public String getOutcomingMessage() { return null; } @Override public void signalResult() { } @Override protected void onResume() { super.onResume(); enableForegroundDispatch(this, this.nfcAdapter); receiveMessageFromDevice(getIntent()); } @Override protected void onPause() { super.onPause(); disableForegroundDispatch(this, this.nfcAdapter); } }
package vnfoss2010.smartshop.serverside.test; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.JsonObject; /** * @author VoMinhTam */ public class ProductImages { static List<Media2> images = new ArrayList<Media2>(); public static void main(String[] args) { images.add(new Media2("Iphone1", "http://localhost/testupload/images/img1.jpg")); images.add(new Media2("Iphone2", "http://localhost/testupload/images/img2.jpg")); images.add(new Media2("Iphone3", "http://localhost/testupload/images/img3.jpg")); images.add(new Media2("Iphone4", "http://localhost/testupload/images/img4.jpg")); JsonObject json = new JsonObject(); json.addProperty("errCode", 0); Gson gson = new Gson(); json.add("message", gson.toJsonTree(images)); System.out.println(json.toString()); } }
package jp.kusutmotolab.jgitTrial.git; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; public class GitSetUpperTest { // clone kGP @Test public void testCloneRemoteRepository() throws IOException, GitAPIException { final Path directoryPath = Paths.get("sample"); final GitSetUpper gitInitializer = new GitSetUpper(directoryPath.toString(), "https://github.com/kusumotolab/kGenProg"); final Git git = gitInitializer.setUp(); assertThat(git).isNotNull().isInstanceOf(Git.class); final List<Path> kGPContentsList = Files.list(directoryPath).collect(Collectors.toList()); final Path readmePath = Paths.get(directoryPath.toString(), "README.md"); assertThat(kGPContentsList).isNotEmpty().contains(readmePath); assertThat(Files.readAllLines(readmePath).get(0)).contains("kGenProg"); Files.walk(directoryPath) .sorted(Comparator.reverseOrder()) .forEach(e -> { try { Files.deleteIfExists(e); } catch (IOException e1) { e1.printStackTrace(); } }); } @Test public void testSpecifyLocalRepository() throws GitAPIException, IOException { final GitSetUpper gitSetUpper = new GitSetUpper(".", ""); final Git git = gitSetUpper.setUp(); assertThat(git).isNotNull().isInstanceOf(Git.class); } }
package collections; import java.util.ArrayDeque; import java.util.Deque; import java.util.Queue; public class Test_Dequeue { public static void main(String[] args) { Deque pilha = new ArrayDeque(); // LinkedList(); //Queue fila = pilha; pilha.add("1"); pilha.add("2"); pilha.add("3"); pilha.add("4"); System.out.println(pilha.remove()); System.out.println(pilha.remove()); System.out.println(pilha.remove()); System.out.println(pilha.remove()); } }
/** * */ package com.fidel.dummybank.service.impl; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fidel.dummybank.model.AccountInfo; import com.fidel.dummybank.model.PayLoad; import com.fidel.dummybank.repository.AccountRepositiory; import com.fidel.dummybank.service.AccountService; /** * @author Swapnil * */ @Service public class AccountServiceImpl implements AccountService { @Autowired AccountRepositiory accountRepositiory; private Integer remainBal; /** * */ public AccountServiceImpl() { // TODO Auto-generated constructor stub } @Override @Transactional public boolean updateBalance(PayLoad payLoad) { AccountInfo accountInfo = accountRepositiory.findByCustId(payLoad.getCustId()); if (accountInfo != null) { if (accountInfo.getAccountBalance() != null) { if (accountInfo.getAccountBalance() > 0 && accountInfo.getAccountBalance() >= Integer.parseInt(payLoad.getTxnAmount())) { setRemainBal(accountInfo.getAccountBalance() - Integer.parseInt(payLoad.getTxnAmount())); } else { return false; } } else { return false; } } else { return false; } return (accountRepositiory.updateBalance(payLoad.getCustId(), getRemainBal().toString()) > 0) ? true : false; } /** * @return the remainBal */ public Integer getRemainBal() { return remainBal; } /** * @param remainBal the remainBal to set */ public void setRemainBal(Integer remainBal) { this.remainBal = remainBal; } @Override public AccountInfo findById(String custId) { AccountInfo accountInfo = accountRepositiory.findByCustId(custId); if (accountInfo == null) { return new AccountInfo(); } return accountInfo; } }
package com.zyxo.hubformatapp.base.domain.tailoring; import lombok.Data; import javax.persistence.Embeddable; import javax.persistence.Embedded; @Data public class Tailoring { private Torso torso; private Arm arm; private Leg leg; }
/* * 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 TiraLabrAI.DataStructureTests; import TiraLab.Structures.StringMethods; import org.junit.Assert; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; /** * * @author ColdFish */ public class StringTests { private StringMethods stringMeth; public StringTests() { } @Before public void init() { stringMeth = new StringMethods(); } @Test public void substringWorks() { String test = "4352345ksjgcvljlk4325435"; for (int i = 0; i < test.length(); i++) { String control = test.substring(0, i); String mySub = stringMeth.substring(test, 0, i); assertTrue(control.equals(mySub)); control = test.substring(i, test.length() - 1); mySub = stringMeth.substring(test, i, test.length() - 1); System.out.println("control : " + control + ", mine :" + mySub); assertTrue(control.equals(mySub)); } } @Test public void indexOfWorksCorrectly() { String test = "43ssfa52345ssfaksjgcvljlk43ssfa25435"; String toFind = "52345ss"; int realIndex = test.indexOf(toFind); int myIndex = stringMeth.indexOf(toFind, test); System.out.println("control : " + realIndex + ", mine :" + myIndex); assertTrue(realIndex == myIndex); } @Test public void indexOfWorksCorrectlyWhenNoValueMatch() { String test = "43ssfa52345ssfaksjgcvljlk43ssfa25435"; String toFind = "asdfasdf"; int realIndex = test.indexOf(toFind); int myIndex = stringMeth.indexOf(toFind, test); System.out.println("control : " + realIndex + ", mine :" + myIndex); assertTrue(realIndex == myIndex); } @Test public void lastIndexOfWorksCorrectly() { String test = "43ssfa52345ssfaksjgcvljlk43ssfa25435"; String toFind = "ssfa"; int realIndex = test.lastIndexOf(toFind); int myIndex = stringMeth.lastIndexOf(toFind, test); System.out.println("control : " + realIndex + ", mine :" + myIndex); assertTrue(realIndex == myIndex); } @Test public void lastIndexOfWorksCorrectlyWhenNoMatch() { String test = "43ssfa52345ssfaksjgcvljlk43ssfa25435"; String toFind = "254351"; int realIndex = test.lastIndexOf(toFind); int myIndex = stringMeth.lastIndexOf(toFind, test); System.out.println("control : " + realIndex + ", mine :" + myIndex); assertTrue(realIndex == myIndex); } @Test public void indexOfFromIndexWorks() { String test = "43ssfa52345ssfaksjgcvljlk43ssfa25435"; String toFind = "sjgcv"; int realIndex = test.indexOf(toFind, 5); int myIndex = stringMeth.indexOf(toFind, test, 5); System.out.println("control : " + realIndex + ", mine :" + myIndex); assertTrue(realIndex == myIndex); } }
package com.qst.dms.app; import com.qst.dms.ui.LoginFrame; /** * @author 陌意随影 TODO :测试类 *2019年11月28日 下午11:39:47 */ public class AppMain { /** * @param args */ public static void main(String[] args) { new LoginFrame(); } }
package com.example.qiumishequouzhan.webviewpage; import android.annotation.TargetApi; import android.app.ActionBar; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import android.view.MenuItem; import android.webkit.WebView; import com.devspark.progressfragment.ProgressFragment; import com.example.qiumishequouzhan.LocalDataObj; import com.example.qiumishequouzhan.R; import com.example.qiumishequouzhan.Utils.*; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.umeng.analytics.MobclickAgent; import org.json.JSONException; import org.json.JSONObject; /** * Created with IntelliJ IDEA. * User: jinxing * Date: 14-3-20 * Time: 上午11:53 * To change this template use File | Settings | File Templates. */ public class MainFragment extends FragmentActivity { public static final String EXTRA_VIEW_URL = "com.MarsKingser.EXTRA_VIEW_URL"; public static final String EXTRA_FRAGMENT = "com.MarsKingser.EXTRA_FRAGMENT"; public static final String EXTRA_FRAGMENTTITLE = "com.MarsKingser.EXTRA_FRAGMENTTITLE"; public static final int FRAGMENT_ONEPAGEWEBVIEW = 0; public static final int FRAGMENT_EDITPAGEWEBVIEW = 1; public static MainFragment obj; public Fragment fragment; public int messagecount; public String sUrl; public static MainFragment GetInstance() { return obj; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setTitle(getIntent().getStringExtra(EXTRA_TITLE)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // new ActionBarHelper().setDisplayHomeAsUpEnabled(true); } // Check what fragment is shown, replace if needed. fragment = getSupportFragmentManager().findFragmentById(android.R.id.content); if (fragment == null) { // Make new fragment to show. int fragmentId = getIntent().getIntExtra(EXTRA_FRAGMENT, FRAGMENT_ONEPAGEWEBVIEW); String sTitle = getIntent().getStringExtra(EXTRA_FRAGMENTTITLE); // String counts = getIntent().getStringExtra("SchEvalCount"); switch (fragmentId) { case FRAGMENT_ONEPAGEWEBVIEW: { sUrl = getIntent().getStringExtra(EXTRA_VIEW_URL); fragment = OneWebPageView.newInstance(); ((OneWebPageView) fragment).SetWebViewUrl(sUrl); // OneWebPageView.SetWebViewUrl(sUrl); if (sTitle != null) { ((OneWebPageView) fragment).SetWebViewTitle(sTitle); //OneWebPageView.SetWebViewTitle(sTitle); } } break; case FRAGMENT_EDITPAGEWEBVIEW: { sUrl = getIntent().getStringExtra(EXTRA_VIEW_URL); fragment = EditOnePage.newInstance(); ((EditOnePage) fragment).SetWebViewUrl(sUrl); } break; } getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment).commit(); } obj = this; } @Override protected void onResumeFragments() { super.onResumeFragments(); MobclickAgent.onResume(this);//umeng统计时长 } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } /** * Helper for fix issue VerifyError on Android 1.6. On Android 1.6 virtual machine * tries to resolve (verify) getActionBar function, and since there is no such function, * Dalvik throws VerifyError. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private class ActionBarHelper { /** * Set whether home should be displayed as an "up" affordance. * Set this to true if selecting "home" returns up by a single level in your UI * rather than back to the top level or front page. * * @param showHomeAsUp true to show the user that selecting home will return one * level up rather than to the top level of the app. */ private void setDisplayHomeAsUpEnabled(boolean showHomeAsUp) { ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(showHomeAsUp); } } } Handler updateHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.arg1) { case 0: ((OneWebPageView) fragment).SetWebViewUrl(sUrl); ((OneWebPageView) fragment).updatecomment(msg.arg2); break; } } }; protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (resultCode) { //resultCode为回传的标记,我在B中回传的是RESULT_OK case RESULT_CANCELED: if (data != null) { Bundle bundle = data.getExtras(); int State = bundle.getInt("ChangeState"); // int counts = bundle.getInt("SchEvalCount"); switch (State) { case 2: // ((OneWebPageView) fragment).CallBack(bundle.getString("chageurl")); break; case 3: if (sUrl.contains("GuessWinLost")) { new Thread() { @Override public void run() { String webview_url = sUrl; String s1[] = webview_url.split("\\?"); s1 = s1[1].split("\\&"); s1 = s1[0].split("\\="); final String ScheduleID = s1[1]; messagecount = 0; String Url = getString(R.string.serverurl) + "/GetCampScheduleInfo"; byte[] data = HttpUtils.GetWebServiceJsonContent(Url, "{\"UserId\":" + LocalDataObj.GetUserLocalData("UserID") + "," + " \"Code\":\"" + LocalDataObj.GetUserLocalData("UserToken") + "\"," + "\"ScheduleID\":" + ScheduleID + "}"); String Result = FileUtils.Bytes2String(data); JSONObject Json = JsonUtils.Str2Json(Result); try { Json = Json.getJSONObject("d"); Json = Json.getJSONObject("Data"); messagecount = Json.getInt("ReplyCount"); Message MSG = new Message(); MSG.arg1 = 0; MSG.arg2 = messagecount; updateHandler.sendMessage(MSG); } catch (JSONException e) { LogUitls.WriteLog("FileUtils", "WriteFile2Store", Json.toString(), e); } } }.start(); } break; } } break; default: break; } } }
import java.util.Scanner; public class Task06_Substitute { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int firstNum = Integer.parseInt(scan.nextLine()); int secondNum = Integer.parseInt(scan.nextLine()); int thirdNum = Integer.parseInt(scan.nextLine()); int fourthNum = Integer.parseInt(scan.nextLine()); int counter = 0; for (int i = firstNum; i <= 8; i++) { for (int j = 9; j >= secondNum; j--) { for (int k = thirdNum; k <= 8; k++) { for (int l = 9; l >= fourthNum; l--) { if (i % 2 == 0 && j % 2 == 1 && k % 2 == 0 && l % 2 == 1) { if (i == k && j == l) { System.out.printf("Cannot change the same player.%n"); } else { System.out.printf("%d%d - %d%d%n", i,j,k,l); counter++; } if (counter == 6) { return; } } } } } } } }
package Task2; import java.io.FileReader; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args) { double sum = 0; ArrayList<Double> arr = new ArrayList<Double>(); try { FileReader fr = new FileReader("results.txt"); Scanner input = new Scanner(fr); while (input.hasNextLine()) { String line = input.nextLine(); double x = Double.parseDouble(line); arr.add(x); } input.close(); } catch (Exception e) { System.out.println("Error!"); } ArrayList<Double> newArr = new ArrayList<Double>(); for (int counter = 0; counter < arr.size(); counter++) { if(arr.get(counter) >= 0){ newArr.add(arr.get(counter)); } System.out.println(arr.get(counter)); } ArrayList<Double> newArr2 = new ArrayList<Double>(); for (int counter2 = 0; counter2 < arr.size(); counter2++) { if(arr.get(counter2) >= -2 && arr.get(counter2) <= 2){ sum += arr.get(counter2); newArr2.add(arr.get(counter2)); } System.out.println(arr.get(counter2)); } Collections.sort(arr); Collections.sort(newArr); System.out.println("უარყოფითებში მინიმუმი : " + arr.get(0)); System.out.println("დადებითებში მინიმუმი : " + newArr.get(0)); System.out.println("საშუალო [-2; 2] შუალედში : " + String.format(" %.2f", sum/newArr2.size())); } }
package com.example.demo.service; import com.example.demo.model.SysUser; /** * Created by HuangYanfei on 2018/8/16. */ public interface UserService { SysUser getOne(); }
package com.gaoshin.webservice; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import org.springframework.stereotype.Component; import com.gaoshin.beans.GenericResponse; import com.gaoshin.beans.Location; import com.gaoshin.beans.LocationList; import com.gaoshin.beans.User; import com.gaoshin.business.LocationService; import com.gaoshin.business.UserService; import com.sun.jersey.spi.inject.Inject; import common.web.BusinessException; import common.web.ServiceError; @Path("/location") @Component @Produces({ "text/html;charset=utf-8", "text/xml;charset=utf-8", "application/json;charset=utf-8" }) public class LocationResource extends GaoshinResource { @Inject private LocationService locationService; @Inject private UserService userService; @POST @Path("new") public Location save(Location location) { UserResource userResource = getResource(UserResource.class); User user = userResource.assertCurrentUser(); if (userService.checkUser(user) == null) throw new BusinessException(ServiceError.NoGuest); return locationService.save(user, location); } @POST @Path("current/{id}") public GenericResponse setCurrentLocation(@PathParam("id") long locationId) { UserResource userResource = getResource(UserResource.class); User user = userResource.assertCurrentUser(); locationService.setUserCurrentLocation(user, locationId); return new GenericResponse(); } @GET @Path("{id}") public Location get(@PathParam("id")Long id) { Location location = locationService.get(id); return location; } @GET @Path("my") public LocationList getUserLocationList() { UserResource userResource = getResource(UserResource.class); User user = userResource.assertCurrentUser(); return locationService.getUserLocationList(user); } @GET @Path("device") public LocationList getUserDeviceLocationList( @DefaultValue("0") @QueryParam("offset") int offset, @DefaultValue("10") @QueryParam("size") int size ) { if (size > 100) size = 100; UserResource userResource = getResource(UserResource.class); User user = userResource.assertCurrentUser(); return locationService.getUserDeviceLocationList(user, offset, size); } }
package com.cairenhui.dao; import java.io.Serializable; public interface EntityDao <T,PK extends Serializable>{ public T getById(PK id); public void deleteById(PK id); public int insert(T t); public void update(T t); }
/** * GUIRemote.java * * Created on January 19, 2007, 10:03 PM * Client-side part of the GUI for connecting to database * Description: it creates the main GUI that connects * to database. It has the internal class * LeftPanel.java that fill the upper part * of the screen and the bottom has the text area for display. * * @author Elena Villalon */ package jremote; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; public class GUIRemote extends JFrame{ static final long serialVersionUID = 7788L; private static final int DEFAULT_WIDTH= 500; private static final int DEFAULT_HEIGTH= 550; private int scale = 3; private final String [] vidf = {"http://www.jakesjokes.com/gallery/albums/userpics/10001/yellowcard.mpg", "file://bailey.mpg"}; private final static String strMess = "Select operations & submit your request to Server\n"; final JTextArea outputarea= new JTextArea(strMess, 100,20); private final JComboBox tags = new JComboBox(); final static int fsz =14; final static int NTHREADS = 6; String [] nameMenu; final JTextField videotxt; //videos selected for classification; index 0 is the video to test List<String> vidSelected; final String[] labels = {"people", "text", "indoor", "outdoor", "sport", "food", "fantasy", "transport"}; JCheckBox metavid; JCheckBox simvid; JList videoLst; List<Commands> commandsLst; static String host="localhost"; static int port = 1099; private static Logger mLog = Logger.getLogger(GUIRemote.class.getName()); private static boolean debug = false; public GUIRemote(String h, int p){ if(!debug) mLog.setLevel(Level.WARNING); host =h; port = p; setTitle("Remote Videos"); setSize(DEFAULT_WIDTH,DEFAULT_HEIGTH); setLayout(new BorderLayout(1,2)); vidSelected = new ArrayList<String>(); commandsLst = new ArrayList<Commands>(); Font f = new Font("menuF", Font.BOLD, fsz-1); videotxt= new JTextField(vidf[0], 200); LeftPanel left = new LeftPanel(); add(left.textpanel, BorderLayout.NORTH); GUIRemoteVid vidlst = new GUIRemoteVid(vidSelected,outputarea); simvid =vidlst.simVideo; videoLst = vidlst.videoLst; vidSelected =vidlst.getSelectedVid(); add(vidlst,BorderLayout.CENTER); outputarea.setLineWrap(true); outputarea.setWrapStyleWord(true); Font font3 = new Font("Courier", Font.PLAIN,fsz); outputarea.setFont(font3); outputarea.setToolTipText("Send your message to a file; write in the text area select it "); outputarea.addCaretListener(new CaretListener() { public void caretUpdate(CaretEvent caretEvent) { System.out.println(outputarea.getSelectedText()); if(outputarea.getSelectedText()!=null) new jclient.SendYourComments("emailFile.txt", outputarea); } }); JScrollPane scroller= new JScrollPane(outputarea); scroller.setPreferredSize(new Dimension(DEFAULT_WIDTH-10, DEFAULT_HEIGTH/scale)); JPanel panel = new JPanel(); panel.add(scroller); add(panel, BorderLayout.SOUTH); } /** * Internal class that creates a panel for video classification * */ public class LeftPanel extends JPanel { JPanel textpanel; JCheckBox vidadd; JCheckBox getTag; JCheckBox statServer; boolean stat = false; public LeftPanel(){ textpanel = new JPanel() { public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getPreferredSize() { return new Dimension(300, super.getPreferredSize().height); } public Dimension getMaximumSize() { return getPreferredSize(); } }; textpanel.setLayout(new GridLayout(1,2)); //create a sub-panel to add to text panel final JPanel textpanel1 = new JPanel(); textpanel1.setLayout(new GridLayout(3,1)); textpanel1.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Server & Video URL & Database Statistics"), BorderFactory.createEmptyBorder(5,5,5,5))); textpanel1.setAlignmentX(Component.LEFT_ALIGNMENT); final JPanel server = new JPanel(); final JTextField urltxt = new JTextField("localhost", 15); final JTextField porttxt = new JTextField("1099", 8); urltxt.setEditable(false); porttxt.setEditable(false); urltxt.setAlignmentX(JTextField.LEFT); urltxt.setToolTipText("Remote Database."); porttxt.setToolTipText("Remote Database."); urltxt.setMaximumSize(urltxt.getPreferredSize()); JButton submit = new JButton("Server"); submit.setMnemonic(KeyEvent.VK_S); submit.setToolTipText("Connet Database."); submit.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent event){ //connecting to the Server: host and port String host = urltxt.getText().trim(); if(host.equalsIgnoreCase("")|| host==null) host = "localhost"; //default String portstr = porttxt.getText().trim(); int port = 1099; //default if(!portstr.equalsIgnoreCase("")|| portstr!=null) port = Integer.parseInt(portstr); //add video to server database String url =null; boolean addb = vidadd.isSelected(); if(addb) url = videotxt.getText().trim(); if(url == null || url.equalsIgnoreCase("")) addb = false; if(addb) commandsLst.add(Commands.ADDVIDEO); //retreive videos under label boolean tagb = getTag.isSelected(); String strselect =null; if(tagb) strselect = ((String) tags.getSelectedItem()).trim(); if(tagb) commandsLst.add(Commands.SHOWLABEL); //stat the server database boolean statb = statServer.isSelected(); if(statb)commandsLst.add(Commands.STATDATABASE); //get similar under label categories for video in JList String urld =null; boolean simb = simvid.isSelected(); if(simb) urld =((String) videoLst.getSelectedValue()).trim(); if(urld==null) { simb = false; } if(simb)commandsLst.add(Commands.SIMILARVIDEO); //submit request ClientVideo client =null; try{ client= new ClientVideo(host, port, commandsLst, url, urld,strselect); StringBuffer responseBuf = client.buildOutput; String resp = responseBuf.toString() + strMess; outputarea.setText(null); outputarea.append(resp); } catch (Exception ae) { String mess="Exception occurred communicating with Videos"; mLog.severe(mess); JOptionPane.showMessageDialog(null, mess, "Error Message", JOptionPane.INFORMATION_MESSAGE); ae.printStackTrace(); } finally{ try{ client.vidRemote.getSocket().close(); }catch(IOException ioe){ ioe.printStackTrace(System.out); } } } }); server.add(urltxt); server.add(new JLabel(" Port: ")); server.add(porttxt); addRow("Connect : ", server, submit, textpanel1); videotxt.setMaximumSize(urltxt.getPreferredSize()); videotxt.setFont(new Font("Courier", Font.PLAIN,12)); videotxt.setAlignmentX(JTextField.LEFT); vidadd = new JCheckBox("Add", false); vidadd.setToolTipText("Add video URL to server database."); vidadd.setMnemonic(KeyEvent.VK_A); //done with the upper part JPanel metapanel = new JPanel(); metapanel.setLayout(new BoxLayout(metapanel, BoxLayout.X_AXIS)); metapanel.setAlignmentY(Component.LEFT_ALIGNMENT); JLabel lab = new JLabel("Database Labels: "); for(int n=0; n < labels.length; ++n) tags.addItem(labels[n]); tags.setEditable(true); tags.setMaximumSize(tags.getPreferredSize()); getTag = new JCheckBox("Retrieve Videos", false); getTag.setToolTipText("Retrieve videos category."); getTag.setMnemonic(KeyEvent.VK_R); statServer = new JCheckBox("Stat Database", false); statServer.setToolTipText("Statistics of Database."); statServer.setMnemonic(KeyEvent.VK_S); metapanel.add(lab); metapanel.add(tags); metapanel.add(getTag); metapanel.add(statServer); textpanel1.add(metapanel); textpanel.add(textpanel1); } } /** Takes a file name and reads line by line * Each line has the label and all videos * classified under the label; the separation is tab * Creates a HashMap with labels and videos. */ public void addRow(String label, final Component field, final JComponent but, JPanel textpanel){ Box h1= Box.createHorizontalBox();; if(label.startsWith("V")){ h1.add(Box.createRigidArea(new Dimension(0,15))); } textpanel.add(h1); String filler = " "; h1.add(new JLabel(label+ filler)); if(field!=null) h1.add(field); if(but!=null) h1.add(but); else h1.add(new Label("Compare to")); textpanel.add(h1); } public Box ButtonRow(String label1, final JButton but1,String label2, final JButton but2, final JPanel textpanel, int ord){ Box h1 =Box.createVerticalBox(); final int sep = 10; String filler = " "; h1.add(new JLabel(label1)); h1.add(but1); h1.add(Box.createVerticalStrut(sep)); // h1.add(Box.createGlue()); h1.add(new JLabel(label2)); h1.add(but2); return(h1); } public static void main(String[] args) { // TODO Auto-generated method stub if(args.length> 1){ host = args[0].trim(); port = Integer.parseInt(args[1].trim()); } javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { GUIRemote client = new GUIRemote(host, port); client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); client.setVisible(true); } }); } }
package br.com.entelgy.util; import java.security.SecureRandom; /** * Useful class for {@link String} tests needs. * * @author falvojr */ public class StringTestUtil { /** * Multiples spaces for increase your chances. */ private static final String SYMBOLS = "01234 56789 ABCDE FGHIJ KLMNO PQRST UVWXY Zabcd efghi jklmn opqrs tuvwx yz"; private static final SecureRandom SECURE_RANDOM = new SecureRandom(); private StringTestUtil() { super(); } public static String randomString(int length) { final StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { sb.append(SYMBOLS.charAt(SECURE_RANDOM.nextInt(SYMBOLS.length()))); } return sb.toString(); } }
package com.jgw.supercodeplatform.trace.dto.template.query; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * 查询字段属性 * 1:根据functionId和TypeClass可以确定定制功能字段 * 2:根据functionId和traceTemplateId可以确定节点属性字段 * @author czm * */ @ApiModel(value = "溯源功能--功能及节点字段查询参数类") public class TraceFunTemplateconfigQueryParam { @ApiModelProperty(value = "**-溯源模板id,如果businessType为自动节点类型则必传") private String traceTemplateId; //溯源模板号 @ApiModelProperty(value = "功能id",required=true) private String functionId; //功能ID号 @ApiModelProperty(value = "标明是节点属性还是定制功能属性",hidden=true) private Integer typeClass; //节点类型 @ApiModelProperty(value = "**-节点类型--用于区分请求的是节点字段还是定制功能字段如果请求的是节点字段属性则必传该值",notes="默认不传则请求的是定制功能节点属性",required=false) private Integer businessType; //功能ID号 public String getTraceTemplateId() { return traceTemplateId; } public void setTraceTemplateId(String traceTemplateId) { this.traceTemplateId = traceTemplateId; } public String getFunctionId() { return functionId; } public void setFunctionId(String functionId) { this.functionId = functionId; } public Integer getBusinessType() { return businessType; } public void setBusinessType(Integer businessType) { this.businessType = businessType; } public Integer getTypeClass() { return typeClass; } public void setTypeClass(Integer typeClass) { this.typeClass = typeClass; } }
public class File { public static void main(String[] args) { System.out.println("First Message"); System.out.println("Second Message"); } }
package com.example.demo.config; import org.springframework.beans.factory.annotation.Value; /** * SmtpConfig * 简单的JavaBean持有所有的配置,在需要读取的地方,使用#{smtpConfig.host}注入 或例 CustomerConfig * * @author ZhangJP * @date 2021/5/20 */ //@Component public class SmtpConfig { @Value("${spring.mail.protocol:smtp}") private String protocol; @Value("${spring.mail.host}") private String host; @Value("${spring.mail.port:25}") private int port; public String getProtocol() { return protocol; } public String getHost() { return host; } public int getPort() { return port; } }
package tasker.tasker.model; public enum Team { TEAM_JUNIOR, TEAM_MIDDLE, TEAM_SENIOR }
package com.islamiat.blackwallpapers.helper; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AlertDialog; import android.widget.Toast; import com.islamiat.blackwallpapers.R; import com.islamiat.blackwallpapers.model.FlickrPhoto; import com.islamiat.blackwallpapers.model.HistoryPhoto; import com.orm.SugarRecord; import com.ornach.andutils.java.StringUtils; import java.text.SimpleDateFormat; import java.util.Date; public class Utils { public static final String EXTRA_PHOTO = "EXTRA_PHOTO"; public static final String EXTRA_PHOTO_INFO = "EXTRA_PHOTO_INFO"; public static final String EXTRA_PHOTO_SIZE = "EXTRA_PHOTO_SIZE"; public static final String EXTRA_LIST = "EXTRA_LIST"; /*public static final String EXTRA_STRING_LIST = "EXTRA_STRING_LIST";*/ public static final String EXTRA_POSITION = "EXTRA_POSITION"; public static final String EXTRA_PAGE_NO = "EXTRA_PAGE_NO"; public static final String EXTRA_TAG = "EXTRA_TAG"; public static final String EXTRA_NAME = "EXTRA_NAME"; public static final String EXTRA_SEARCH_KEYWORD = "EXTRA_SEARCH_KEYWORD"; public static final String EXTRA_USER_ID = "EXTRA_USER_ID"; public static final String EXTRA_FLAG = "EXTRA_FLAG"; public static final String EXTRA_TEXT = "EXTRA_TEXT"; public static final int FLAG_PHOTO_RECENT = 501; public static final int FLAG_PHOTO_POPULAR = 502; public static final int FLAG_PHOTO_SAVED = 503; public static final int FLAG_PHOTO_HISTORY = 504; public static final int FLAG_PHOTO_USER = 505; public static final int FLAG_PHOTO_SEARCH = 506; public static final int FLAG_PHOTO_TAG = 507; public static String getMediumPicUrlFromPhoto(FlickrPhoto photo) { String picUrl = ""; if (!StringUtils.isEmpty(photo.url_c)) { picUrl = photo.url_c; } else if (!StringUtils.isEmpty(photo.url_n)) { picUrl = photo.url_n; } return picUrl; } public static String getLargePicUrlFromPhoto(FlickrPhoto photo) { String picUrl = ""; if (!StringUtils.isEmpty(photo.url_l)) { picUrl = photo.url_l; } else if (!StringUtils.isEmpty(photo.url_c)) { picUrl = photo.url_c; } else if (!StringUtils.isEmpty(photo.url_n)) { picUrl = photo.url_n; } return picUrl; } public static String getMaxPicUrlFromPhoto(FlickrPhoto photo) { String picUrl = ""; /*if (!StringUtils.isEmpty(photo.url_o)) { picUrl = photo.url_o; } else*/ if (!StringUtils.isEmpty(photo.url_k)) { picUrl = photo.url_k; } else if (!StringUtils.isEmpty(photo.url_h)) { picUrl = photo.url_h; } else if (!StringUtils.isEmpty(photo.url_l)) { picUrl = photo.url_l; } else if (!StringUtils.isEmpty(photo.url_c)) { picUrl = photo.url_c; } else { picUrl = photo.url_n; } return picUrl; } public static String getDateFromUnix(long timeStamp) { Date date = new Date(timeStamp * 1000); SimpleDateFormat sdf = new SimpleDateFormat("d MMMM, yyyy"); String newDate = sdf.format(date); return newDate; } public static String getMaxLargePhotoSize(FlickrPhoto photo) { /*if (!StringUtils.isEmpty(photo.size_o)) { return photo.size_o; } else if (!StringUtils.isEmpty(photo.size_k)) { return photo.size_k; } else*/ if (!StringUtils.isEmpty(photo.size_h)) { return photo.size_h; } else if (!StringUtils.isEmpty(photo.size_l)) { return photo.size_l; } else if (!StringUtils.isEmpty(photo.size_c)) { return photo.size_c; } else if (!StringUtils.isEmpty(photo.size_z)) { return photo.size_z; } else if (!StringUtils.isEmpty(photo.size_n)) { return photo.size_n; } return ""; } public static void goMoreApps(Context context) { Uri uriMarket = Uri.parse("market://dev?id=EL-Mansouri"); Uri uriHttp = Uri.parse("http://play.google.com/store/apps/developer?id=EL-Mansouri"); try { context.startActivity(new Intent(Intent.ACTION_VIEW, uriMarket)); //Log.e("TAG", "uriMarket not resolved"); } catch (ActivityNotFoundException e) { try { context.startActivity(new Intent(Intent.ACTION_VIEW, uriHttp)); } catch (Exception ex) { } } } public static void shareApps(Context context) { String appUrl = "http://play.google.com/store/apps/details?id=" + context.getPackageName(); String appMarket = "market://details?id=" + context.getPackageName(); String title = context.getString(R.string.app_name); //String msg = "Hey check out android app for HD Background at: " + appUrl; String msg = "HD Background. Hey check out android app for HD Background at: " + appUrl; Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); //intent.setData(Uri.parse(appUrl)); intent.putExtra(Intent.EXTRA_SUBJECT, title); intent.putExtra(Intent.EXTRA_TEXT, msg); try { //context.startActivity(intent); context.startActivity(Intent.createChooser(intent, "Share via")); } catch (ActivityNotFoundException e) { Toast.makeText(context, " Sorry, Not able to Share!", Toast .LENGTH_SHORT).show(); } } public static void clearHistory(Context context) { AlertDialog.Builder d = new AlertDialog.Builder(context); d.setTitle("Clear History"); d.setMessage("Are you want to clear history?"); d.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); d.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SugarRecord.deleteAll(HistoryPhoto.class); dialog.dismiss(); } }); d.create().show(); } }
/// Name: Nanako Chung // Date: April 24th, 2017 // Description: Game test class that utilizes the Enemy class and the Level1Enemy and Level2Enemy subclasses //test class public class Game { //main method public static void main(String[] args) { //creates an instance of each class Enemy myEnemy=new Enemy(); Level1Enemy myLev1En=new Level1Enemy(); Level2Enemy myLev2En=new Level2Enemy(); //hits each class with a random integer myEnemy.hit((int)(Math.random()*101)); myLev1En.hit((int)(Math.random()*151)); myLev2En.hit((int)(Math.random()*201)); //prints out health of each class System.out.println("Health for Enemy: "+myEnemy.getHealth()); System.out.println("Health for Level 1 Enemy: "+myLev1En.getHealth()); System.out.println("Health for Level 2 Enemy: "+myLev2En.getHealth()); //calls the move method on the Level1Enemy object myLev1En.move(); //prints out x & y position of myLev1En System.out.println("X Position of Level 1 Enemy: "+myLev1En.getX()+"\n"+"Y Position of Level 2 Enemy: "+myLev1En.getY()); //calls the fire method on the Level2Enemy object myLev2En.fire(); } }
package com.wizinno.shuhao.share.domain; import com.wizinno.shuhao.share.domain.model.Share; import java.util.List; import org.apache.ibatis.annotations.Param; public interface ShareMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table share * * @mbggenerated Wed Sep 27 15:39:44 CST 2017 */ int deleteByPrimaryKey(@Param("userId") Long userId, @Param("shareId") Long shareId, @Param("deviceId") Long deviceId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table share * * @mbggenerated Wed Sep 27 15:39:44 CST 2017 */ int insert(Share record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table share * * @mbggenerated Wed Sep 27 15:39:44 CST 2017 */ Share selectByPrimaryKey(@Param("userId") Long userId, @Param("shareId") Long shareId, @Param("deviceId") Long deviceId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table share * * @mbggenerated Wed Sep 27 15:39:44 CST 2017 */ List<Share> selectAll(); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table share * * @mbggenerated Wed Sep 27 15:39:44 CST 2017 */ int updateByPrimaryKey(Share record); List<Share> findByOrder(@Param("userId") Long userId, @Param("shareId") Long shareId, @Param("deviceId") Long deviceId); }
package com.java.practice.litcode; import java.util.HashMap; import java.util.Map; /** * Given an array a that contains only numbers in the range from 1 to a.length, find the * first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1. * Example * For a = [2, 1, 3, 5, 3, 2], the output should be firstDuplicate(a) = 3. * There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index * than the second occurrence of 2 does, so the answer is 3. * For a = [2, 2], the output should be firstDuplicate(a) = 2; * For a = [2, 4, 3, 5, 1], the output should be firstDuplicate(a) = -1. * Input/Output * [execution time limit] 4 seconds (py3) * [input] array.integer a * Guaranteed constraints: * 1 ≤ a.length ≤ 105, * 1 ≤ a[i] ≤ a.length. * [output] integer * The element in a that occurs in the array more than once and has the minimal index * for its second occurrence. If there are no such elements, return -1. */ public class FindFirstDuplicate { public static void main(String[] args) { int[] numbers = {2, 2,3,3}; System.out.println(getFirstMinimalIndexDuplicate(numbers)); } private static int getFirstMinimalIndexDuplicate(int[] numbers) { if (numbers == null || numbers.length == 1) { return -1; } int minimal = Integer.MAX_VALUE; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(numbers[i])) { minimal = Math.min(minimal, i - map.get(numbers[i])); } else { map.put(numbers[i], i); } } return minimal == Integer.MAX_VALUE ? -1 : numbers[minimal]; } }
package BankAccountManage; import java.util.Scanner; import java.util.ArrayList; import java.lang.String; import java.io.*; // public class BankAccountManage { public ArrayList<User> users=new ArrayList<User>();//所有的用户 public void BAMstrat(){ while(true){ System.out.println("请选择您的操作:\n1. 注册\n2. 登陆\n0. 退出账户管理"); Scanner scanner=new Scanner(System.in); int choose=scanner.nextInt(); if(choose==0) return; while(choose!=1&&choose!=2){ System.out.println("输入错误, 请重新输入!"); choose=scanner.nextInt(); } switch(choose) { case 1: addAccount(); break; case 2: login(); break; } } } public boolean addAccount(){ Scanner scanner=new Scanner(System.in); System.out.println("请输入用户名:"); String userName=scanner.next(); boolean nameNotExist=true; for(int i=0;i<users.size();i++){ if(users.get(i).getName().equals(userName)){ nameNotExist=false; } } if(userName.length()>=3&&userName.length()<=20&&nameNotExist) { System.out.println("请输入密码:"); String p1=scanner.next(); System.out.println("请再次输入密码:"); String p2=scanner.next(); if(p1.length()>0&&p1.equals(p2)){ User temp=new User(userName,p1); users.add(temp); System.out.println("创建成功!"); return true; } else{ System.out.println("密码不同, 创建失败!"); return false; } } else{ System.out.println("用户名长度不符或用户名已经被占用, 创建失败!"); } return false; } public void login(){ Scanner scanner=new Scanner(System.in); int times=0; for(;times<3;times++) { System.out.println("请输入用户名:"); String userName = scanner.next(); System.out.println("请输入密码:"); String password = scanner.next(); boolean nameExist=false; int rightUser=0; for(;rightUser<users.size();rightUser++){ if(users.get(rightUser).getName().equals(userName)){ nameExist=true; break;//只跳出了找正确的用户的循环 } } if (!nameExist) {// //没找到用户名 System.out.println("用户名错误!"); continue; } else if(!users.get(rightUser).login(userName,password)){ //用户名对,密码不对 System.out.println("密码错误!"); continue; } break; } if(times==3) System.out.println("您已经三次输入错误, 退出登录!"); } public void storeUsers(){ try{ ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("res/users.txt")); oos.writeObject(users); oos.close(); } catch(FileNotFoundException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } } public void loadUsers(){ try{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream("res/users.txt")); users = (ArrayList)ois.readObject(); ois.close(); } catch(FileNotFoundException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } catch(ClassNotFoundException e){ e.printStackTrace(); } } }
package co.qingmei.pm.entity; import java.io.Serializable; import java.util.Date; public class Bug implements Serializable { private Integer id; private String name; private Date createtime; private Integer createuid; private Integer actionuid; private Date finishtime; private Integer pid; private static final long serialVersionUID = 1L; public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public Integer getCreateuid() { return createuid; } public void setCreateuid(Integer createuid) { this.createuid = createuid; } public Integer getActionuid() { return actionuid; } public void setActionuid(Integer actionuid) { this.actionuid = actionuid; } public Date getFinishtime() { return finishtime; } public void setFinishtime(Date finishtime) { this.finishtime = finishtime; } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } Bug other = (Bug) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getCreatetime() == null ? other.getCreatetime() == null : this.getCreatetime().equals(other.getCreatetime())) && (this.getCreateuid() == null ? other.getCreateuid() == null : this.getCreateuid().equals(other.getCreateuid())) && (this.getActionuid() == null ? other.getActionuid() == null : this.getActionuid().equals(other.getActionuid())) && (this.getFinishtime() == null ? other.getFinishtime() == null : this.getFinishtime().equals(other.getFinishtime())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getCreatetime() == null) ? 0 : getCreatetime().hashCode()); result = prime * result + ((getCreateuid() == null) ? 0 : getCreateuid().hashCode()); result = prime * result + ((getActionuid() == null) ? 0 : getActionuid().hashCode()); result = prime * result + ((getFinishtime() == null) ? 0 : getFinishtime().hashCode()); return result; } }
package com.demo.customer.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * Created by tm1c14 on 09/06/2015. */ @Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; private String lastName; protected Person() {} public Person(String name, String lastName) { this.setName(name); this.setLastName(lastName); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String toString() { return String.format("[ id %d, name %s, lastName %s", id, name, lastName); } }
package com.dian.diabetes.widget; import android.content.Context; import android.support.v4.app.FragmentActivity; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.dian.diabetes.R; public class SigIndicateWidget extends RelativeLayout { private FragmentActivity context; private LayoutInflater inflater; private TextView valueView; private TextView bottomView; private ImageView bgIcon; private View line; private int[] imgSourceId; public SigIndicateWidget(Context context) { super(context); this.context = (FragmentActivity) context; initView(); } public SigIndicateWidget(Context context, AttributeSet attrs) { super(context, attrs); this.context = (FragmentActivity) context; initView(); } public SigIndicateWidget(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = (FragmentActivity) context; initView(); } private void initView() { inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.widget_notrend_layout, null); valueView = (TextView) view.findViewById(R.id.value); bottomView = (TextView) view.findViewById(R.id.bottom); bgIcon = (ImageView) view.findViewById(R.id.icon); line = view.findViewById(R.id.line); addView(view); imgSourceId = new int[] { R.drawable.good_circle, R.drawable.normal_circle, R.drawable.red_circle }; } public void setValue(float value, int level) { valueView.setText(value + ""); bgIcon.setImageResource(imgSourceId[level]); bottomView.setVisibility(View.GONE); line.setVisibility(View.GONE); } public void setValue(float value, int bottom, int level) { valueView.setText(value + ""); bgIcon.setImageResource(imgSourceId[level]); bottomView.setText(bottom + ""); } }
package com.letscrawl.test; import java.io.UnsupportedEncodingException; import java.util.List; import com.letscrawl.base.bean.Url; import com.letscrawl.processor.download.downloader.impl.CommonDownloader; import com.letscrawl.processor.extract.extractor.impl.JsoupExtractor; public class JsoupTest { public static void main(String[] args) { try { JsoupExtractor j = JsoupExtractor.getInstance(); List<Url> urlList = j.extract(new String( CommonDownloader.getInstance() .download(new Url("http://www.gamersky.com/")) .getContent(), "utf-8")); System.out.println(urlList.size()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
package com.ms.module.wechat.clear.activity.scan; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.ms.module.wechat.clear.R; import java.util.List; public class WeChatScanIngRecyclerViewAdapter extends RecyclerView.Adapter { private Context context; private List<WeChatScanIngRecyclerViewAdapterItem> datas; public static class WeChatScanIngRecyclerViewAdapterItem { public String name; public int icon; // 0 默认状态 // 1 扫描中 // 2 扫描完成 public SCAN_STATUS status = SCAN_STATUS.DEFAULT; public WeChatScanIngRecyclerViewAdapterItem(String name, int icon) { this.name = name; this.icon = icon; } } public static enum SCAN_STATUS { DEFAULT, ING, FINISH } public WeChatScanIngRecyclerViewAdapter(Context context, List<WeChatScanIngRecyclerViewAdapterItem> datas) { this.context = context; this.datas = datas; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.adapter_wechat_clear_scan_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { ViewHolder viewHolder = (ViewHolder) holder; viewHolder.textViewName.setText(datas.get(position).name); Glide.with(context).load(datas.get(position).icon).into(viewHolder.imageViewLogo); if (datas.get(position).status == SCAN_STATUS.DEFAULT) { Glide.with(context).load(R.drawable.image_no_start).into(viewHolder.imageViewStatus); } else if (datas.get(position).status == SCAN_STATUS.ING) { Glide.with(context).load(R.drawable.image_loading) .into(viewHolder.imageViewStatus); Animation animation = AnimationUtils.loadAnimation(context, R.anim.anim_loading_ing); viewHolder.imageViewStatus.startAnimation(animation); } else if (datas.get(position).status == SCAN_STATUS.FINISH) { Glide.with(context).load(R.drawable.image_finish).into(viewHolder.imageViewStatus); } } @Override public int getItemCount() { return datas.size(); } static class ViewHolder extends RecyclerView.ViewHolder { private TextView textViewName; private ImageView imageViewLogo; private ImageView imageViewStatus; public ViewHolder(@NonNull View itemView) { super(itemView); textViewName = itemView.findViewById(R.id.textViewName); imageViewLogo = itemView.findViewById(R.id.imageViewLogo); imageViewStatus = itemView.findViewById(R.id.imageViewStatus); } } }
package com.acewill.chikenprintlibrary.model; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017-05-02. */ public class PA_Order { public String id; // 订单ID public String sequenceNumber;// 订单号码 public int customerAmount;// 顾客人数 public String comment = "";//订单说明 // public String appId; // public String brandId; // public String storeId; public String total; public String cost; public String source; public double discount; public double subtraction; public String orderType; public String orderTypeStr; public String callNumber; public String createdBy; public String saleUserId; public String tableNames = ""; public long createdAt; //这里不能用Date, 因为app的date格式可能和服务器不一样 public long paidAt; //结账时间 public List<Long> tableIds = new ArrayList<Long>(); public Integer workShiftId;//班次ID public int printerType = -1;//打印订单类型 Constant.JsToAndroid 中有打印的详细类型 public int tableStyle;//桌台操作类型 是否是搭台 开台 并台 public int orderPrintType; public String createdAtStr;//订单产生时间 public String customerName;//外卖顾客的姓名 public String customerPhoneNumber;//外卖顾客的电话 public String customerAddress;//外卖顾客的地址 public String outerOrderid;//外部平台订单号 //电子流水号,打印小票使用 public String paymentNo;//微信、支付宝电子流水号 public List<PA_OrderItem> itemList; public List<PA_Option> optionList; private long tableId; //netOrder // public Long refOrderId; //如果是退单的话,这里会保存原单的id // public BigDecimal refund = new BigDecimal("0");// 退款金额 -- 放到这里是为了出报表方便 // public String memberid; // public String customerid; // public int netorderstatus; // public long deliverAt; // 门店接受订单时间 // public long preorderTime;//预订时间 // public String prepayId; // public int payType; // public String rejectReason; // public BigDecimal shippingFee = new BigDecimal("0");//网上订单配送费用 // public long netOrderid;//网络订单Id // // public String tableid = "";//对应的桌台ID, -1代表没有桌台 // public int operation_type; //0:新下单;1:加菜单 // public long refNetOrderId; /** * 退单人员名称 */ public String returnUserName; /** * 授权退单人员名称 */ public String authUserName; /** * 餐段名称 */ public String menuName; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(String sequenceNumber) { this.sequenceNumber = sequenceNumber; } public int getCustomerAmount() { return customerAmount; } public void setCustomerAmount(int customerAmount) { this.customerAmount = customerAmount; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } // public String getAppId() { // return appId; // } // // public void setAppId(String appId) { // this.appId = appId; // } // // public String getBrandId() { // return brandId; // } // // public void setBrandId(String brandId) { // this.brandId = brandId; // } // // public String getStoreId() { // return storeId; // } // // public void setStoreId(String storeId) { // this.storeId = storeId; // } public String getTotal() { return total; } public void setTotal(String total) { this.total = total; } public String getCost() { return cost; } public void setCost(String cost) { this.cost = cost; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public double getDiscount() { return discount; } public void setDiscount(double discount) { this.discount = discount; } public double getSubtraction() { return subtraction; } public void setSubtraction(double subtraction) { this.subtraction = subtraction; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public String getOrderTypeStr() { return orderTypeStr; } public void setOrderTypeStr(String orderTypeStr) { this.orderTypeStr = orderTypeStr; } public String getCallNumber() { return callNumber; } public void setCallNumber(String callNumber) { this.callNumber = callNumber; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public String getSaleUserId() { return saleUserId; } public void setSaleUserId(String saleUserId) { this.saleUserId = saleUserId; } public String getTableNames() { return tableNames; } public void setTableNames(String tableNames) { this.tableNames = tableNames; } public long getCreatedAt() { return createdAt; } public void setCreatedAt(long createdAt) { this.createdAt = createdAt; } public long getPaidAt() { return paidAt; } public void setPaidAt(long paidAt) { this.paidAt = paidAt; } public List<Long> getTableIds() { return tableIds; } public void setTableIds(List<Long> tableIds) { this.tableIds = tableIds; } public Integer getWorkShiftId() { return workShiftId; } public void setWorkShiftId(Integer workShiftId) { this.workShiftId = workShiftId; } public int getPrinterType() { return printerType; } public void setPrinterType(int printerType) { this.printerType = printerType; } public int getTableStyle() { return tableStyle; } public void setTableStyle(int tableStyle) { this.tableStyle = tableStyle; } public int getOrderPrintType() { return orderPrintType; } public void setOrderPrintType(int orderPrintType) { this.orderPrintType = orderPrintType; } public String getCreatedAtStr() { return createdAtStr; } public void setCreatedAtStr(String createdAtStr) { this.createdAtStr = createdAtStr; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getCustomerPhoneNumber() { return customerPhoneNumber; } public void setCustomerPhoneNumber(String customerPhoneNumber) { this.customerPhoneNumber = customerPhoneNumber; } public String getCustomerAddress() { return customerAddress; } public void setCustomerAddress(String customerAddress) { this.customerAddress = customerAddress; } public String getOuterOrderid() { return outerOrderid; } public void setOuterOrderid(String outerOrderid) { this.outerOrderid = outerOrderid; } public String getPaymentNo() { return paymentNo; } public void setPaymentNo(String paymentNo) { this.paymentNo = paymentNo; } public List<PA_OrderItem> getItemList() { return itemList; } public void setItemList(List<PA_OrderItem> orderItemList) { this.itemList = orderItemList; } public List<PA_Option> getOptionList() { return optionList; } public void setOptionList(List<PA_Option> optionList) { this.optionList = optionList; } public long getTableId() { return tableId; } public void setTableId(long tableId) { this.tableId = tableId; } public String getReturnUserName() { return returnUserName; } public void setReturnUserName(String returnUserName) { this.returnUserName = returnUserName; } public String getAuthUserName() { return authUserName; } public void setAuthUserName(String authUserName) { this.authUserName = authUserName; } public String getMenuName() { return menuName; } public void setMenuName(String menuName) { this.menuName = menuName; } }
package ru.mcfr.oxygen.updater.plugin; import org.apache.log4j.Logger; import ro.sync.exml.plugin.Plugin; import ro.sync.exml.plugin.PluginDescriptor; public class UpdateManagerPlugin extends Plugin { private static Logger logger = Logger.getLogger(UpdateManagerPlugin.class.getName()); private static UpdateManagerPlugin instance = null; public UpdateManagerPlugin(PluginDescriptor descriptor){ super(descriptor); if (instance != null) throw new IllegalStateException("Already instantinated!"); instance = this; } public static UpdateManagerPlugin getInstance(){ return instance; } }
package com.fanoi.dream.controler.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class FNDBHelper extends SQLiteOpenHelper { private static final String DB_NAME = "download.db"; private static FNDBHelper helper = null;//静态对象引用 //创建保存线程信息表 private static final String SQL_CREATE = "create table thread_info(" + "_id integer primary key autoincrement," + "thread_id integer," + "file_id integer," + "url text," + "start long," + "end long," + "finished long)"; private static final String SQL_DROP = "drop table if exists thread_info"; private static final int VERSION = 1; /** *获得单例对象 * @param context 上下文 * @return 单例对象 */ public static FNDBHelper getInstancere(Context context){ if (helper ==null){ helper = new FNDBHelper(context); } return helper; } private FNDBHelper(Context context) { super(context, DB_NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DROP); db.execSQL(SQL_CREATE); } }
package com.cb.cbfunny.utils; import android.graphics.Bitmap; import android.view.View; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class FileUtils { static boolean result = false; /** * ��ȡ�ļ��д�С * @return */ public static int getDirSize(File dir) { if(dir==null){ return 0; } long size = 0; for (File f : dir.listFiles()) { if (f.isDirectory()) { size += getDirSize(f); } else { size += f.length(); } } return (int) (size / 1024 / 1024); } /** * �����ļ� * @param srcPath �ļ�ԭ·�� * @param desPath �ļ�Ŀ��·�� * @return */ public static boolean copyFile(String srcPath, String desPath) { FileOutputStream fout = null; FileInputStream fin = null; try { File srcf = new File(srcPath); File desf = new File(desPath); if (!srcf.exists()) { return false; } if (!desf.exists()) { if(!desf.getParentFile().exists()){ desf.getParentFile().mkdirs(); } desf.createNewFile(); } fout = new FileOutputStream(desf); fin= new FileInputStream(srcf); byte[] temp = new byte[1024 * 5]; int len = 0; while ((len = fin.read(temp)) != -1) { fout.write(temp, 0, len); } return true; } catch (Exception e) { return false; } finally { if(fin!=null){ try { fin.close(); } catch (IOException e) { e.printStackTrace(); } } if(fout!=null){ try { fout.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 判断是否存在该文件(夹) * @param path * @return */ public static boolean isExist(String path){ return new File(path).exists(); } /** * 保存图片 * @param dstpath 目标路径 * @param url * @return */ public static boolean saveImg(String dstpath,String url){ final File file = new File(dstpath); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } ImageLoader loader = ImageLoader.getInstance(); try { loader.loadImage(url, new ImageLoadingListener() { FileOutputStream out = new FileOutputStream(file); @Override public void onLoadingStarted(String imageUri, View view) { // TODO Auto-generated method stub } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { // TODO Auto-generated method stub } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { // TODO Auto-generated method stub result = loadedImage.compress(Bitmap.CompressFormat.PNG, 100, out); } @Override public void onLoadingCancelled(String imageUri, View view) { // TODO Auto-generated method stub } }); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /** * 根据图片URI获取ImageLoader缓存到本地的图片 * @param uri * @param imageloader * @return */ public static File getImageFileInDiscCache(String uri,ImageLoader imageloader) { File imageFile = imageloader.getDiscCache().get(uri);; return imageFile; } }
package com.springboot.racemanage.util; import org.junit.jupiter.api.Test; import org.springframework.boot.json.GsonJsonParser; import org.springframework.boot.json.JsonParserFactory; import java.util.Map; public class ToolsTest { String json = "{\n" + " \"result\": {\n" + " \"id\": 2,\n" + " \"stuUuid\": \"951753\",\n" + " \"stuEmail\": \"1031145353111@qq.commm\",\n" + " \"stuNumber\": \"201470024136\",\n" + " \"stuName\": \"李自豪\",\n" + " \"stuPhone\": \"123456789\",\n" + " \"stuPassword\": \"123456asd\",\n" + " \"stuDescription\": \"无法描述\",\n" + " \"stuDuty\": \"不知道是一个好的worker还是开发者\",\n" + " \"stuStatus\": 1,\n" + " \"stuGender\": \"男\",\n" + " \"photo\": \"\"\n" + " },\n" + " \"code\": 1,\n" + " \"msg\": null\n" + "}"; @Test public void transJson() { Map map = JsonParserFactory.getJsonParser().parseMap(json); GsonJsonParser gsonJsonParser = new GsonJsonParser(); // System.out.println(map); // // Map<String,String> re = (Map<String, String>) map.get("result"); //// System.out.println(re); // String ss = re.get("stuUuid"); // System.out.println("stuUuid : " + ss); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.samal.taxi24.entities; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.annotations.GenericGenerator; /** * * @author john */ @Entity @Table(name = "driver") public class Driver implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid",strategy = "uuid") @Size(min = 1, max = 50) @Column(name = "id") private String id; @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "name") private String name; @Column(name = "age") private Integer age; @Basic(optional = false) @NotNull @Size(min = 1, max = 250) @Column(name = "licenseno") private String licenseno; @Basic(optional = false) @NotNull @Size(min = 1, max = 6) @Column(name = "gender") private String gender; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Column(name = "lon") private Double lon; @Column(name = "lat") private Double lat; @Basic(optional = false) @NotNull @Size(min = 1, max = 250) @Column(name = "description") private String description; @Basic(optional = false) @NotNull @Column(name = "is_active") private boolean isActive=true; @JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd HH:mm") @Basic(optional = false) @NotNull @Column(name = "creation_time") @Temporal(TemporalType.TIMESTAMP) private Date creationTime; @JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd HH:mm") @Column(name = "updation_time") @Temporal(TemporalType.TIMESTAMP) private Date updationTime; @JsonIgnore @OneToMany(cascade = CascadeType.ALL, mappedBy = "driver") private List<Trip> tripList; public Driver() { } public Driver(String id) { this.id = id; } public Driver(String id, String name, String licenseno, String gender, String description, boolean isActive, Date creationTime) { this.id = id; this.name = name; this.licenseno = licenseno; this.gender = gender; this.description = description; this.isActive = isActive; this.creationTime = creationTime; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getLicenseno() { return licenseno; } public void setLicenseno(String licenseno) { this.licenseno = licenseno; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Double getLon() { return lon; } public void setLon(Double lon) { this.lon = lon; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean getIsActive() { return isActive; } public void setIsActive(boolean isActive) { this.isActive = isActive; } public Date getCreationTime() { return creationTime; } public void setCreationTime(Date creationTime) { this.creationTime = creationTime; } public Date getUpdationTime() { return updationTime; } public void setUpdationTime(Date updationTime) { this.updationTime = updationTime; } public List<Trip> getTripList() { return tripList; } public void setTripList(List<Trip> tripList) { this.tripList = tripList; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Driver)) { return false; } Driver other = (Driver) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.samal.taxi24.entities.Driver[ id=" + id + " ]"; } }
public class ChuckleClikcer { }
package no.ntnu.stud.ubilearn.db; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.util.Log; /** * This is a Data Access Object. It is used to connect to a database, and insert and select objects by using spesific models * */ public abstract class DAO { // database management protected SQLiteDatabase database; protected DatabaseHandler dbHandler; protected final String LOG; public DAO(Context context, String childClass) { dbHandler = new DatabaseHandler(context); LOG = childClass; } /** * opens a connection to the database * @throws SQLException */ public void open() throws SQLException { database = dbHandler.getWritableDatabase(); } /** * closes the connection to the database */ public void close() { dbHandler.close(); } /** * converts the Date object to a string, which uses the SQLite format * @param date the date to be converted * @return the converted string */ protected String dateToString(Date date){ SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.getDefault()); return dateFormat.format(date); } /** * converts a string in the "yyyy-MM-dd HH:mm:ss" format to a date object * @param date the string to be converted * @return an initialized date object with the correct date */ protected Date stringToDate(String date){ SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.getDefault()); try { return dateFormat.parse(date); } catch (ParseException e) { e.printStackTrace(); return null; } } /** * Loggs the string with the tag of the class invoking the method * @param string the message to be logged */ protected void log(String string){ Log.i(LOG,string); } /** * Checks if a id exists in a table * @param table the table to ceck for the id * @param id the id to look for * @return a boolean. False if no id found. True if same id found in the table. */ protected boolean exists(String table, String id){ String query = selectWhere(table,DatabaseHandler.KEY_OBJECT_ID,id); Cursor result = database.rawQuery(query, null); return result.moveToFirst(); } /** * Checks if a id exists in a table * @param table the table to ceck for the id * @param id the id to look for * @return a boolean. False if no id found. True if same id found in the table. */ protected boolean exists(String table, int id){ String query = selectWhere(table,DatabaseHandler.KEY_ID,id); Cursor result = database.rawQuery(query, null); return result.moveToFirst(); } /** * Generates a query-string with SQL syntax for the values in the parameters, for an select query on foreign keys * @param table The table to select the values from * @param column the name of the column containing the foreign key * @param id the foreign key * @return a query-string with SQL syntax */ protected String selectWhere(String table, String column, String id){ return "SELECT * FROM " + table + " WHERE " + column + " = '" + id + "'"; } /** * Generates a query-string with SQL syntax for the values in the parameters, for an select query on foreign keys * @param table The table to select the values from * @param column the name of the column containing the foreign key * @param id the foreign key * @return a query-string with SQL syntax */ protected String selectWhere(String table, String column, int id){ return "SELECT * FROM " + table + " WHERE " + column + " = '" + id + "'"; } /** * Loggs an entire table. * @param table the name of table to be logged */ protected void printTable(String table){ String query = "SELECT * FROM " + table; log("Printing content of " + table); Cursor result = database.rawQuery(query, null); StringBuilder output = new StringBuilder(); if(result.moveToFirst()){ String[] columns = result.getColumnNames(); output.append(" | "); for (int i = 0; i < columns.length; i++) { output.append(columns[i] + " | "); } do{ output.append("\n | "); int n = result.getColumnCount(); for (int i = 0; i < n; i++) { try{ output.append(result.getString(i) + " | "); }catch(SQLiteException e){ output.append("BLOB" + " | "); } } }while(result.moveToNext()); }else return; log(output.toString()); } }
package view.aluno_frame; import javax.swing.*; import java.io.IOException; import static control.ExibirListas.exibirTurmasDumAluno; class ListaTurmas { JPanel listaTurmas; private JLabel listaTurmasLabel; public ListaTurmas(){ try { listaTurmasLabel.setText("<html>" + exibirTurmasDumAluno() + "</html>"); } catch (IOException e) { e.printStackTrace(); } } }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.core.network; import xyz.noark.core.lang.ByteArray; import java.io.Serializable; /** * Session. * * @author 小流氓[176543888@qq.com] * @since 3.0 */ public interface Session extends SessionAttrMap { /** * 获取Session的ID. * * @return 实际就是链接Channel的ID */ Serializable getId(); /** * 获取当前Session链接的IP地址 * * @return IP地址 */ String getIp(); /** * 关闭当前Session的链接. */ void close(); /** * 发送一个网络封包. * * @param opcode 协议编号 * @param protocol 协议对象 */ void send(Serializable opcode, Object protocol); /** * 发送完成后关闭当前链接. * * @param opcode 协议编号 * @param protocol 协议对象 */ void sendAndClose(Serializable opcode, Object protocol); /** * 发送一个网络封包. * <p> * 封包是已处理过的加密压缩等功能后的包 * * @param packet 封包内容 */ void send(ByteArray packet); /** * 发送一个网络协议 * * @param networkProtocol 网络协议 */ void send(NetworkProtocol networkProtocol); /** * 获取当前链接状态. * * @return 链接状态 */ State getState(); /** * 获取玩家的UID. * * @return 玩家的UID */ String getUid(); /** * 获取玩家ID * * @return 玩家ID */ Serializable getPlayerId(); /** * 清除账号和角色ID,用于顶号后解绑 */ void clearUidAndPlayerId(); /** * 获取封包统计情况. * * @return 封包统计情况 */ PacketStatistics getStatistics(); /** * 获取封包加密接口. * * @return 封包加密接口 */ PacketEncrypt getPacketEncrypt(); /** * Session状态. */ enum State { /** * 随便什么状态都可以访问. * <p> * 状态比较特殊,比如心跳 */ ALL, /** * 客户端刚刚链接上来的状态. * <p> * 未登录才可以调用的方法 */ CONNECTED, /** * 已认证状态. * <p> * 已登录但未进游戏(可能有选角界面) */ AUTHENTICATED, /** * 游戏中状态,选择角色进入游戏了. */ INGAME; } }
package com.ousl.SessionManagement.Base; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class SessionManager { public SharedPreferences sharedPreferences; public Editor editor; public Context context; private static final int PRIVATE_MODE = 0; private static final String PREF_NAME = "OUSLNavigationPreferences"; public SessionManager(Context c){ this.context = c; sharedPreferences = context.getApplicationContext().getSharedPreferences(PREF_NAME, PRIVATE_MODE); editor = sharedPreferences.edit(); } }
package org.uva.forcepushql.parser.ast.visitors; import org.uva.forcepushql.parser.ast.ValueType; import org.uva.forcepushql.parser.ast.elements.*; import org.uva.forcepushql.parser.ast.elements.expressionnodes.*; import org.uva.forcepushql.interpreter.gui.JPanelGUI; import org.uva.forcepushql.interpreter.gui.questions.Question; import javax.swing.*; import java.util.List; public interface ASTVisitor{ List<JPanel> visit(FormNode node); List<JPanelGUI> visit(ConditionalNode node); String visit(AdditionNode node); String visit(SubtractionNode node); String visit(NumberNode node); String visit(MultiplicationNode node); String visit(DivisionNode node); String visit(AndNode node); String visit(OrNode node); String visit(LessNode node); String visit(GreaterNode node); String visit(EqualLessNode node); String visit(EqualGreaterNode node); String visit(NotEqualNode node); String visit(IsEqualNode node); String visit(NotNode node); Question visit(QuestionNode node); Question visit(QuestionAssignValueNode node); String visit(LabelNode node); String visit(NameNode node); ValueType visit(TypeNode node); String visit(VariableNode node); String visit(DecimalNode node); }
package statistics; /** * * @author Kamil */ public class DragonStatistics implements DragonStatistics_Interface{ /** * ilość zeżartych ludzi * @var int */ protected int _numberOfEatenPeople; /** * Całkowita liczba ukradzionych dóbr * @val int */ protected int _totalBooty; /** * całkowite obrażenia */ protected int _totalInjuries; /** * Setter dla ilości zeżartych ludzi. * @param int numberOfEatenPeople * @return DragonStatistics_Interface */ @Override public DragonStatistics setNumberOfEatenPeople(int numberOfEatenPeople){ this._numberOfEatenPeople=numberOfEatenPeople; return this; } /** * Getter dla ilości zeżartych ludzi. * @return int */ @Override public int getNumberOfEatenPeople(){ return this._numberOfEatenPeople; } /** * Setter dla całkowitej liczby ukradzionych dóbr. * @param int totalBooty * @return DragonStatistics_Interface */ @Override public DragonStatistics setTotalBooty(int totalBooty){ this._totalBooty=totalBooty; return this; } /** * Getter dla całkowitej liczby ukradzionych dóbr. * @return int */ @Override public int getTotalBooty(){ return this._totalBooty; } /** * Setter dla całkowitych obrażeń. * @param int totalInjuries * @return DragonStatistics_Interface */ @Override public DragonStatistics setTotalInjuries(int totalInjuries){ this._totalInjuries=totalInjuries; return this; } /** * Getter dla całkowityh obrażeń. * @return int */ @Override public int getTotalInjuries(){ return this._totalInjuries; } }
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.util.task; import static javax.swing.SwingConstants.*; import java.awt.Component; import java.util.Objects; import javax.swing.SwingConstants; import ghidra.util.SystemUtilities; import util.CollectionUtils; /** * A builder object that allows clients to launch tasks in the background, with a progress * dialog representing the task. * * <P>Using this class obviates the need for clients to create full class objects to implement * the {@link Task} interface, which means less boiler-plate code. * * <P>An example of usage: * <pre> * MonitoredRunnable r = * monitor -> doWork(parameter, monitor); * new TaskBuilder("Task Title", r) * .setHasProgress(true) * .setCanCancel(true) * .setStatusTextAlignment(SwingConstants.LEADING) * .launchModal(); * </pre> */ public class TaskBuilder { private String title; private MonitoredRunnable runnable; private Component parent; private int launchDelay = -1; private int dialogWidth = TaskDialog.DEFAULT_WIDTH; private boolean hasProgress = true; private boolean canCancel = true; private boolean waitForTaskCompletion = false; private int statusTextAlignment = SwingConstants.CENTER; /** * Constructor. * * @param title the required title for your task. This will appear as the title of the * task dialog * @param runnable the runnable that will be called when the task is run */ public TaskBuilder(String title, MonitoredRunnable runnable) { this.title = Objects.requireNonNull(title); this.runnable = Objects.requireNonNull(runnable); } /** * Sets whether this task reports progress. The default is <tt>true</tt>. * * @param hasProgress true if the task reports progress * @return this builder */ public TaskBuilder setHasProgress(boolean hasProgress) { this.hasProgress = hasProgress; return this; } /** * Sets whether the task can be cancelled. The default is <tt>true</tt>. * * @param canCancel true if the task can be cancelled. * @return this builder */ public TaskBuilder setCanCancel(boolean canCancel) { this.canCancel = canCancel; return this; } /** * Sets the component over which the task dialog will be shown. The default is <tt>null</tt>, * which shows the dialog over the active window. * * @param parent the parent * @return this builder */ public TaskBuilder setParent(Component parent) { this.parent = parent; return this; } /** * Sets the amount of time that will pass before showing the dialog. The default is * {@link TaskLauncher#INITIAL_DELAY} for non-modal tasks and * {@link TaskLauncher#INITIAL_MODAL_DELAY} for modal tasks. * * @param delay the delay time * @return this builder */ public TaskBuilder setLaunchDelay(int delay) { SystemUtilities.assertTrue(delay > 0, "Launch delay must be greater than 0"); this.launchDelay = delay; return this; } /** * The desired width of the dialog. The default is {@link TaskDialog#DEFAULT_WIDTH}. * * @param width the width * @return this builder */ public TaskBuilder setDialogWidth(int width) { SystemUtilities.assertTrue(width > 0, "Dialog width must be greater than 0"); this.dialogWidth = width; return this; } /** * Sets the horizontal text alignment of messages shown in the task dialog. The * default is {@link SwingConstants#CENTER}. Valid values are {@link SwingConstants} * LEADING, CENTER and TRAILING. * * @param alignment the alignment * @return this builder */ public TaskBuilder setStatusTextAlignment(int alignment) { boolean isValid = CollectionUtils.isOneOf(alignment, LEADING, CENTER, TRAILING); SystemUtilities.assertTrue(isValid, "Illegal alignment argument: " + alignment); this.statusTextAlignment = alignment; return this; } /** * Launches the task built by this builder, using a blocking modal dialog. */ public void launchModal() { boolean isModal = true; Task t = new TaskBuilderTask(isModal); int delay = getDelay(launchDelay, isModal); new TaskLauncher(t, parent, delay, dialogWidth); } /** * Launches the task built by this builder, using a non-blocking dialog. * @return the launcher that launched the task */ public TaskLauncher launchNonModal() { boolean isModal = false; Task t = new TaskBuilderTask(isModal); int delay = getDelay(launchDelay, isModal); TaskLauncher launcher = new TaskLauncher(t, parent, delay, dialogWidth); return launcher; } private static int getDelay(int userDelay, boolean isModal) { if (userDelay >= 0) { return userDelay; } if (isModal) { return TaskLauncher.INITIAL_MODAL_DELAY; } return TaskLauncher.INITIAL_DELAY; } private class TaskBuilderTask extends Task { TaskBuilderTask(boolean isModal) { super(title, canCancel, hasProgress, isModal, waitForTaskCompletion); } @Override public int getStatusTextAlignment() { return statusTextAlignment; } @Override public void run(TaskMonitor monitor) { runnable.monitoredRun(monitor); } } }
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Server { private ServerSocket server = null; private Socket socket = null; private int port; private int num_clients=0; Server(int port){ this.port = port; try { server = new ServerSocket(this.port); System.out.println("Server Started at Port " + this.port); System.out.println("Server Waiting for Clients..."); while(true) { socket = server.accept(); Processing P = new Processing(socket,++num_clients); P.start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String args[]) { Server s = new Server(5000); } public int factorial(int num) { if(num<=0) { return 1; } return factorial(num-1)*num; } class Processing extends Thread{ Socket socket; int ClientId; Processing(Socket socket,int ClientId){ this.socket = socket; this.ClientId = ClientId; } public void process() { System.out.println("Client " + ClientId + " Connected"); try { //Setting Up Input and OutputStreams DataOutputStream os = new DataOutputStream(socket.getOutputStream()); DataInputStream is = new DataInputStream(socket.getInputStream()); Scanner scanner = new Scanner(System.in); String line=""; while(true) { line = is.readUTF(); int num = Integer.parseInt(line); if(num<0)break; System.out.println("Client " + ClientId+ ">> " + line); os.writeUTF("Factorial = " + factorial(num)); } os.close(); is.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void run() { process(); System.out.println("Connection with Client " + ClientId +" Terminated"); } } }
package pl.artursienkowski.service.bonus; import org.springframework.stereotype.Service; import pl.artursienkowski.model.Customer; import pl.artursienkowski.model.User; import pl.artursienkowski.repository.CustomerRepository; import java.util.List; @Service public class BonusCalculatorService { public double calculateBonusForUser(User user, List<Customer> customers) { double calculateBonus = 0.0; if (customers.size() > 0) { double carsValue = 0.0; double accessoriesValue = 0.0; for (Customer c : customers) { carsValue += c.getCar().getPrice(); accessoriesValue += c.getAccessoriesPrice(); } calculateBonus = User.calculateBonus(user.getType(), carsValue, accessoriesValue); } return calculateBonus; } }
package com.example.demo.service.bitmex; import java.io.IOException; import java.util.concurrent.ExecutionException; import javax.annotation.PreDestroy; import com.example.demo.service.CryptoService; import com.example.demo.service.event.CryptoMarketsEvent; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.client.standard.StandardWebSocketClient; @Slf4j @Service public class BitmexCryptoService implements CryptoService { private static final String SERVICE_URI = "wss://www.bitmex.com/realtime?subscribe=instrument:XBTUSD,trade:XBTUSD"; private final WebSocketSession session; public BitmexCryptoService(ApplicationContext context) throws ExecutionException, InterruptedException { StandardWebSocketClient simpleWebSocketClient = new StandardWebSocketClient(); this.session = simpleWebSocketClient.doHandshake( new BitmexWebSocketHandler(m -> context.publishEvent(new CryptoMarketsEvent(m))), SERVICE_URI) .get(); } @PreDestroy public void cleanUp() throws IOException { session.close(); } }
package com.junyoung.searchwheretogoapi.service.place.search; import com.junyoung.searchwheretogoapi.model.api.ListResponse; import com.junyoung.searchwheretogoapi.model.api.PageParam; import com.junyoung.searchwheretogoapi.model.data.PlaceSearchHistory; import com.junyoung.searchwheretogoapi.model.data.User; import com.junyoung.searchwheretogoapi.repository.PlaceSearchHistoryQueryRepository; import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; @Slf4j @RequiredArgsConstructor @Service public class PlaceSearchHistoryQueryService { private final PlaceSearchHistoryQueryRepository historyQueryRepository; public ListResponse<PlaceSearchHistory> getPlaceSearchHistories(User user, PageParam pageParam) { log.debug("> getPlaceSearchHistories(user={}, pageParam={})", user, pageParam); List<PlaceSearchHistory> searchHistories = historyQueryRepository.findByUserIdOrderByHistoryIdDesc( user.getUserId(), PageRequest.of(pageParam.getPageNum() - 1, pageParam.getPageSize())); int totalCount = historyQueryRepository.countByUserId(user.getUserId()); return new ListResponse<>(searchHistories, totalCount); } }
package hard; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class YearWithMaxNumberOfAlivePeople { public static int getYearWithMaxNumberOfAlivePeople(int[][] lifespans) { Map<Integer, Integer> yearToNumberOfPeopleAliveMapping = new HashMap<>(); // Keys can be birth year, I don't have to track all the years int start; int end; for (int index = 0; index < lifespans.length; index++) { start = lifespans[index][0]; yearToNumberOfPeopleAliveMapping.put(start, 0); } for (int index = 0; index < lifespans.length; index++) { start = lifespans[index][0]; end = lifespans[index][1]; for (int year = start; year <= end; year++) { if (yearToNumberOfPeopleAliveMapping.containsKey(year)) { yearToNumberOfPeopleAliveMapping.put(year, yearToNumberOfPeopleAliveMapping.get(year) + 1); } else { yearToNumberOfPeopleAliveMapping.put(year, 1); } } } int maxNumberOfPeopleAliveInAGivenYear = Integer.MIN_VALUE; int yearWithMaxNumberOfPeopleAlive = -1; for (Entry<Integer, Integer> yearToNumberOfPeople : yearToNumberOfPeopleAliveMapping.entrySet()) { if (maxNumberOfPeopleAliveInAGivenYear < yearToNumberOfPeople.getValue()) { maxNumberOfPeopleAliveInAGivenYear = yearToNumberOfPeople.getValue(); yearWithMaxNumberOfPeopleAlive = yearToNumberOfPeople.getKey(); } } System.out.println("maxNumberOfPeopleAliveInAGivenYear: " + maxNumberOfPeopleAliveInAGivenYear); System.out.println("yearWithMaxNumberOfPeopleAlive : " + yearWithMaxNumberOfPeopleAlive); return yearWithMaxNumberOfPeopleAlive; } public static int[] getRange(int[][] lifespans) { int start = Integer.MAX_VALUE; int end = Integer.MIN_VALUE; for (int index = 0; index < lifespans.length; index++) { if (start < lifespans[index][0]) { start = lifespans[index][0]; } if (end > lifespans[index][1]) { end = lifespans[index][1]; } } int[] range = { start, end }; return range; } public static void main(String[] args) { int[][] lifespans = { { 1900, 1990 }, { 1991, 2000 }, { 1985, 2000 }, { 1921, 1990 }, { 1955, 2000 } }; getYearWithMaxNumberOfAlivePeople(lifespans); } }
package repository; import Domain.Ride; public interface IRideRepository extends IRepository<Integer, Ride> { }
public class FitnessCalc { }
package com.engin.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.concurrent.locks.Lock; /** * @description: author:zhaoningqiang * @time 16/6/27/下午1:40 */ public class FloatSurfaceView extends SurfaceView implements SurfaceHolder.Callback { private static final String TAG = FloatSurfaceView.class.getSimpleName(); private static final int SLEEP_TIME = 10; private Paint mPathPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Bitmap floatBitmap; private Bitmap backBitmap; private RectF contentRect; private float offset; private Path mPath = new Path(); public FloatSurfaceView(Context context) { super(context); init(); } public FloatSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public FloatSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init(){ getHolder().addCallback(this); mPathPaint.setARGB(255,255,0,255); mPathPaint.setStyle(Paint.Style.FILL); } private final Object mSurfaceLock = new Object(); private DrawThread mThread; @Override public void surfaceCreated(SurfaceHolder holder) { mThread = new DrawThread(holder); mThread.setRun(true); mThread.start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { //这里可以获取SurfaceView的宽高等信息 contentRect = new RectF(getPaddingLeft(),getPaddingTop(),width - getPaddingLeft() - getPaddingRight(),height - getPaddingTop() - getPaddingBottom()); mPath.addRect(contentRect, Path.Direction.CW); mPath.addArc(contentRect,0,360); mPath.setFillType(Path.FillType.EVEN_ODD); } @Override public void surfaceDestroyed(SurfaceHolder holder) { synchronized (mSurfaceLock) { //这里需要加锁,否则doDraw中有可能会crash mThread.setRun(false); } } private class DrawThread extends Thread { private SurfaceHolder mHolder; private boolean mIsRun = false; public DrawThread(SurfaceHolder holder) { super(TAG); mHolder = holder; } @Override public void run() { while(true) { synchronized (mSurfaceLock) { if (!mIsRun) { return; } Canvas canvas = mHolder.lockCanvas(); if (canvas != null) { //绘制底层图 if (backBitmap != null){ canvas.drawBitmap(backBitmap, null, contentRect,null); } //绘制浮层图 if (floatBitmap != null){ canvas.save(); canvas.translate(getWidth() * offset, 0); canvas.drawBitmap(floatBitmap, null, contentRect,null); canvas.restore(); } //绘制中空圆 canvas.drawPath(mPath,mPathPaint); mHolder.unlockCanvasAndPost(canvas); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } } public void setRun(boolean isRun) { this.mIsRun = isRun; } } public void setImageBitmap(Bitmap bitmap){ } public void setUpperLayerBitmap(Bitmap bitmap){ floatBitmap = bitmap; } public void update(float offset){ if (offset >=0 && offset <=1){ this.offset = 1.f - offset; invalidate(); } } }
package org.google.code.netapps.chat.basic; import org.google.code.netapps.chat.primitive.*; import org.google.code.servant.util.SyncQueue; import org.google.code.servant.net.Server; import org.google.code.servant.net.DefaultContext; import org.google.code.servant.net.Servant; import org.google.code.servant.net.ServantManager; import org.google.code.servant.net.infoworm.InfoWorm; public class ChatContext extends DefaultContext { private SyncQueue txBuffer = new SyncQueue(); private Participant participant; private ChatRoom chatRoom; /** The name */ private String name; private String password; private Server server; /** * * * @param name the name */ public ChatContext(String name, String password, Server server) { this.name = name; this.password = password; this.server = server; } /** * Gets the name * * @return the name */ public String getName() { return name; } public String getPassword() { return password; } public SyncQueue getTxBuffer() { return txBuffer; } public Participant getParticipant() { return participant; } public void setParticipant(Participant participant) { this.participant = participant; } public ChatRoom getChatRoom() { return chatRoom; } public void setChatRoom(ChatRoom chatRoom) { this.chatRoom = chatRoom; } /** * Cancels the context * */ public void cancel() { StringBuffer body = new StringBuffer(); String login = participant.getType() + " " + participant.getName(); String password = "???"; InfoWorm infoWorm = new InfoWorm(); infoWorm.setField(Constants.USER_NAME_FIELD, login); infoWorm.setField(Constants.PASSWORD_FIELD, password); infoWorm.setField(Constants.COMMAND_FIELD, Command.CRASH); try { ServantManager servantManager = server.getServantManager(); Servant servant = servantManager.get(); Object response = servant.service(infoWorm); servantManager.release(servant); } catch(Throwable ex) { ex.printStackTrace(); } } }
package com.lxl.mvplibrary.base; /** * 基类View,可以根据实际情况写方法 * @author lxl */ public interface BaseView { }
package com.goldenasia.lottery.data; /** * 4.3.6 游戏报表 * Created by Gan on 2017/10/31. */ import com.goldenasia.lottery.base.net.RequestConfig; @RequestConfig(api = "?c=game&a=memberReport") public class GameReportCommand { private String startDate;// 2016-10-20 起始日期 private String endDate ;// String 2017-10-20 截止日期 public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } }
package com.sam.mdm.model; public class SAGAModel { private String saga; private String hmacSecured; private String failoverAction; private String hmac; public String getSaga() { return saga; } public void setSaga(String saga) { this.saga = saga; } public String getHmacSecured() { return hmacSecured; } public void setHmacSecured(String hmacSecured) { this.hmacSecured = hmacSecured; } public String getFailoverAction() { return failoverAction; } public void setFailoverAction(String failoverAction) { this.failoverAction = failoverAction; } public String getHmac() { return hmac; } public void setHmac(String hmac) { this.hmac = hmac; } }
package queueCircularArray; /********************************************************************************************************************** * Please refer to the Driver java file for a description of the project in a larger scope * * ******************************************************************************************************************** * *<b>Title:</b> Project 3: Airport Simulator <br> *<b>Filename:</b> QueueEmptyException.java <br> *<b>Date Written:</b> April, 2016<br> *<b>Due Date:</b> April 25th, 2016<br> *<p> **</p> *<p><b>Description:</b></p> *<p> *The QueueEmptyException Class extends the Exception class and has a default and parameterized constructor *for the Class objects *</p> * ********************************************************************************************************************* * @author VagnerMachado - ID N00820127 - Nassau Community College - Spring 2016 * ********************************************************************************************************************* */ public class QueueEmptyException extends Exception{ /** * QueueEmptyException default constructor - sends to super class a String */ public QueueEmptyException() { super ("Queue Empty Exception"); } /** * QueueEmptyException parameterized constructor - sends to the super class a String * @param message - the message sent to the super class */ public QueueEmptyException( String message) { super(message); } }
package com.dexvis.dex; import java.io.File; import java.util.List; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javafx.application.Application; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.scene.Scene; import javafx.stage.Stage; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.tbee.javafx.scene.layout.MigPane; import com.dexvis.dex.wf.DexEnvironment; import com.dexvis.dex.wf.DexTaskState; import com.dexvis.javafx.scene.control.DexTaskItem; public class DexCLI extends Application { // Thread factory for executing task serially. private final static BasicThreadFactory serialThreadFactory = new BasicThreadFactory.Builder() .namingPattern("Dex-Serial-Task-%d").daemon(true) .priority(Thread.MAX_PRIORITY).build(); // Executor for executing task serially. public final static ExecutorService serialExecutor = Executors .newSingleThreadExecutor(serialThreadFactory); // Thread factory for concurrent task execution. Such task may not update the // UI. private final static BasicThreadFactory concurrentThreadFactory = new BasicThreadFactory.Builder() .namingPattern("Dex-Concurrent-Task-%d").daemon(true) .priority(Thread.MAX_PRIORITY).build(); // Executor for parallel task execution. public final static ExecutorService concurrentExecutor = Executors .newFixedThreadPool( Math.max(1, Runtime.getRuntime().availableProcessors() - 1), concurrentThreadFactory); // Service for task completion notification. public final static CompletionService<Object> CCS = new ExecutorCompletionService( concurrentExecutor); // Main stage private Stage stage = null; // Main scene. private Scene scene; private static String[] arguments; private void init(Stage stage) { try { this.stage = stage; stage.setTitle("Data Explorer"); MigPane rootLayout = new MigPane("", "[grow]", "[][grow]"); scene = new Scene(rootLayout, 1600, 900); stage.setScene(scene); } catch(Exception ex) { ex.printStackTrace(); } } public void start(Stage stage) throws Exception { init(stage); stage.show(); Options options = new Options(); options.addOption("p", "project", true, "The project to be run."); options.addOption("e", "env", true, "The project environment."); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, arguments); System.out.println("Running: " + cmd.getOptionValue("project")); if (cmd.hasOption("e")) { DexEnvironment env = DexEnvironment.getInstance(); String envStr = cmd.getOptionValue("env"); String envVars[] = StringUtils.split(envStr, ';'); if (envVars != null) { for (String envVar: envVars) { if (envVar != null && envVar.indexOf('=') > -1) { int ei = envVar.indexOf('='); env.setVariable(envVar.substring(0, ei), envVar.substring(ei+1)); System.out.println("Setting Env Var: '" + envVar.substring(0, ei) + "'='" + envVar.substring(ei+1) + "'"); } } } // Split by semicolon. // Split by equals. } DexProject project = DexProject.readProject(stage, new File(cmd.getOptionValue("project"))); List<DexTaskItem> tasks = project.getTaskItems(); int taskNum = 1; DexTaskState state = new DexTaskState(); long projectStartTime = System.currentTimeMillis(); long taskStartTime; for (DexTaskItem task : tasks) { taskStartTime = System.currentTimeMillis(); System.out.println(" TASK[" + taskNum + "]: '" + task.getName().getValue() + "'"); // long startTime = System.currentTimeMillis(); if (task.getActive().getValue()) { state = task.getTask().getValue().execute(state); } System.out.println(" " + (System.currentTimeMillis() - taskStartTime) + " ms"); taskNum++; } serialExecutor.shutdown(); concurrentExecutor.shutdown(); if (!serialExecutor.awaitTermination(3600, TimeUnit.SECONDS)) { serialExecutor.shutdownNow(); } if (!concurrentExecutor.awaitTermination(3600, TimeUnit.SECONDS)) { concurrentExecutor.shutdownNow(); } System.out.println("Execution Completed In: " + (System.currentTimeMillis() - projectStartTime) + " ms"); Platform.exit(); } public void exit(ActionEvent evt) { System.exit(0); } private static void setDefault(String propertyName, String propertyValue) { if (!System.getProperties().containsKey(propertyName)) { System.setProperty(propertyName, propertyValue); } System.out.println(propertyName + "='" + System.getProperty(propertyName) + "'"); } public static void main(String[] args) { arguments = args; Platform.setImplicitExit(false); // Headless params, overridable from command line. setDefault("glass.platform", "Monocle"); setDefault("monocle.platform", "Headless"); setDefault("prism.order", "sw"); setDefault("prism.text", "t2k"); setDefault("headless.geometry", "1600x1200-32"); launch(args); } }
package com.github.fierioziy.particlenativeapi.core.mocks.nms.v1_17; import com.github.fierioziy.particlenativeapi.core.mocks.nms.v1_13.Particle; import com.github.fierioziy.particlenativeapi.core.mocks.nms.v1_13.ParticleType; import com.github.fierioziy.particlenativeapi.core.mocks.nms.v1_13.Particles_1_13; public class Particles_1_17 { public static ParticleType LAVA = Particles_1_13.LAVA; public static Particle<?> FALLING_DUST = Particles_1_13.FALLING_DUST; public static Particle<?> BLOCK = Particles_1_13.BLOCK; public static ParticleType ENTITY_EFFECT = Particles_1_13.ENTITY_EFFECT; public static Particle<?> DUST = Particles_1_13.DUST; public static Particle<?> DUST_COLOR_TRANSITION = new ParticleType(); public static Particle<?> VIBRATION = new ParticleType(); public static Particle<?> ITEM = Particles_1_13.ITEM; public static ParticleType FLAME = Particles_1_13.FLAME; public static ParticleType NOTE = Particles_1_13.NOTE; }
import java.util.concurrent.atomic.AtomicIntegerArray; class GetNSetState implements State { private AtomicIntegerArray value; private byte maxval; GetNSetState(byte[] v) { value = new AtomicIntegerArray(ByteArrToIntArr(v)); maxval = 127; } GetNSetState(byte[] v, byte m) { value = new AtomicIntegerArray(ByteArrToIntArr(v)); maxval = m; } public int size() { return value.length(); } public byte[] current() { return AtomIntArrToByteArr(value); } public boolean swap(int i, int j) { int ival = value.get(i); int jval = value.get(j); if (ival <= 0 || jval >= maxval) { return false; } value.set(i, ival+1); value.set(j, jval+1); return true; } private int[] ByteArrToIntArr(byte[] byteArr) { int[] intArr = new int[byteArr.length]; for (int i = 0; i < byteArr.length; intArr[i] = byteArr[i++]); return intArr; } private byte[] AtomIntArrToByteArr(AtomicIntegerArray atomIntArr) { int len = atomIntArr.length(); byte[] byteArr = new byte[len]; for (int i = 0; i < len; byteArr[i] = (byte) atomIntArr.get(i++)); return byteArr; } }
package edu.nyu.cs9053.homework7; public class StoppableThread { private final Thread thread; public StoppableThread(final Runnable runnable) { Runnable wrapper = () -> { while (!Thread.currentThread().isInterrupted()) { System.out.print("Thread is running"); } }; this.thread = new Thread(wrapper); } public void start() { thread.start(); } public void stop() { Thread.currentThread().interrupt(); } }
package com.cos.blog.domain.user.dto; import lombok.Builder; import lombok.Data; @Builder @Data public class UpdateReqDto { private String password; private String email; private String address; }
package com.rednovo.ace.handler.jsonData; import java.util.HashMap; import org.apache.log4j.Logger; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.rednovo.ace.constant.Constant; import com.rednovo.ace.handler.BasicServiceAdapter; import com.rednovo.tools.PPConfiguration; import com.rednovo.tools.Validator; import com.rednovo.tools.web.HttpSender; /** * @author wenhui.Wang/2016年5月18日 */ public class UserJsonHandler extends BasicServiceAdapter{ Logger logger = Logger.getLogger(OrderJsonHandler.class); @Override protected void service() { String key = this.getKey(); if("001-210".equals(key)){ //-用户管理--用户管理 this.getUserManage(); } else if ("001-420".equals(key)){ //-用户管理--实名认证 this.getCertify(); } else if ("001-410".equals(key)){ //-用户管理--修改实名认证状态 this.updateCertifyStatus(); } else if("".equals(key)){ } else if("".equals(key)){ } } private String page(JSONArray jsonArray, int pageInt, int pageSizeInt){ int size = jsonArray.size(); int startIndex = (pageInt - 1)*pageSizeInt; int endIndex = startIndex+pageSizeInt; JSONObject print = new JSONObject(); JSONArray data = new JSONArray(); print.put("rows", data); for (int i = startIndex; i < (endIndex>size?size:endIndex); i++) { JSONObject jsonObj = jsonArray.getJSONObject(i); data.add(jsonObj); } String json = print.toJSONString(); StringBuffer sbf = new StringBuffer(json); sbf.replace(0, 1, "{\"total\":\""+jsonArray.size()+"\","); return sbf.toString(); } /** * 用户管理 */ private void getUserManage(){ HashMap<String, String> para = new HashMap<String, String>(); String key = this.getWebHelper().getString("key"); para.put("key", key); String page = ""; int pageInt = this.getWebHelper().getInt("page"); para.put("page", page.valueOf(pageInt)); String pageSize = ""; int pageSizeInt = this.getWebHelper().getInt("rows"); para.put("pageSize", pageSize.valueOf(pageSizeInt)); String status = this.getWebHelper().getString("status"); para.put("status", status); String path = this.getWebHelper().getString("path"); String jsonData = getJsonData(path, para); JSONObject obj = JSONObject.parseObject(jsonData); JSONArray jsonArray =obj.getJSONArray("userList"); String json = page(jsonArray,pageInt,pageSizeInt); JSONObject jsonObject = JSONObject.parseObject(json); this.setJsonObj(jsonObject); } /** * 实名认证 */ private void getCertify(){ HashMap<String, String> para = new HashMap<String, String>(); String userId = this.getWebHelper().getString("userId"); para.put("userId", userId); String page = ""; int pageInt = this.getWebHelper().getInt("page"); para.put("page", page.valueOf(pageInt)); String pageSize = ""; int pageSizeInt = this.getWebHelper().getInt("rows"); para.put("pageSize", pageSize.valueOf(pageSizeInt)); String status = this.getWebHelper().getString("status"); para.put("status", status); String path = this.getWebHelper().getString("path"); String jsonData = getJsonData(path, para); JSONObject obj = JSONObject.parseObject(jsonData); JSONArray jsonArray =obj.getJSONArray("certifyList"); String json = page(jsonArray,pageInt,pageSizeInt); JSONObject jsonObject = JSONObject.parseObject(json); this.setJsonObj(jsonObject); } /** * 用户管理--修改实名认证状态 */ private void updateCertifyStatus(){ HashMap<String, String> para = new HashMap<String, String>(); String userId = this.getWebHelper().getString("userId"); para.put("userId", userId); String status = this.getWebHelper().getString("status"); para.put("status", status); String path = this.getWebHelper().getString("path"); if(Validator.isEmpty(userId) || Validator.isEmpty(status)){ this.setError("218"); return; } String jsonData = getJsonData(path, para); JSONObject obj = JSONObject.parseObject(jsonData); if (Constant.OperaterStatus.SUCESSED.getValue().equals(obj.getString("exeStatus"))) { this.setSuccess(); } else { this.setError(jsonData); } } }
/* Copyright (C) 2013-2014, Securifera, Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Securifera, Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================ Pwnbrew is provided under the 3-clause BSD license above. The copyright on this package is held by Securifera, Inc */ package pwnbrew.network.socket; import java.io.IOException; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; import pwnbrew.log.LoggableException; import pwnbrew.misc.Constants; import pwnbrew.misc.DebugPrinter; import pwnbrew.selector.SocketChannelHandler; import pwnbrew.xml.maltego.MaltegoMessage; import pwnbrew.xml.maltego.MaltegoTransformExceptionMessage; /** * A helper class which performs I/O using the SSLEngine API. * */ public class SecureSocketChannelWrapper extends SocketChannelWrapper { private final SSLEngine sslEngine; private static final String NAME_Class = SecureSocketChannelWrapper.class.getSimpleName(); private final int appBBSize; private final int netBBSize; /* * All I/O goes through these buffers. * <P> * It might be nice to use a cache of ByteBuffers so we're * not alloc/dealloc'ing ByteBuffer's for each new SSLEngine. * <P> * We use our superclass' requestBB for our application input buffer. * Outbound application data is supplied to us by our callers. */ private final ByteBuffer inNetBB; private final ByteBuffer outNetBB; /* * An empty ByteBuffer for use when one isn't available, say * as a source buffer during initial handshake wraps or for flush * operations. */ private static final ByteBuffer handshakeBB = ByteBuffer.allocate(0); //Accessible from several threads private volatile boolean initialHSComplete; private boolean handShakeMsg = true; /* * We have received the shutdown request by our caller, and have * closed our outbound side. */ private boolean shutdown = false; //=============================================================== /** * Constructor * * @param sc * @param passedHandler * @param isClient * @throws LoggableException * @throws IOException * @throws InterruptedException */ public SecureSocketChannelWrapper ( SocketChannel sc, SocketChannelHandler passedHandler, boolean isClient ) throws LoggableException, IOException, InterruptedException { super(sc, passedHandler ); //Get the type and the SSL context SSLContext theContext = passedHandler.getPortRouter().getSSLContext( isClient ); sslEngine = theContext.createSSLEngine(); sslEngine.setUseClientMode(isClient); sslEngine.setNeedClientAuth(true); netBBSize = sslEngine.getSession().getPacketBufferSize(); inNetBB = ByteBuffer.allocate(netBBSize); outNetBB = ByteBuffer.allocate(netBBSize); outNetBB.position(0); outNetBB.limit(0); //Set the size appBBSize = sslEngine.getSession().getApplicationBufferSize(); requestBB = ByteBuffer.allocate( appBBSize ); } /* * Returns the buffer size */ public int getBufferSize(){ return appBBSize; } /* * Calls up to the superclass to adjust the buffer size * by an appropriate increment. */ private void resizeRequestBB() { resizeRequestBB(appBBSize); } /* * Writes bb to the SocketChannel. * <P> * Returns true when the ByteBuffer has no remaining data. */ private boolean tryFlush(ByteBuffer bb) throws IOException { super.write(bb); return !bb.hasRemaining(); } /* * If any data remains in the output buffer then send it */ private boolean flushHandshakeBuffer(SelectionKey passedKey) throws IOException { HandshakeStatus currStatus = sslEngine.getHandshakeStatus(); boolean setRead = false; //Send data if (!tryFlush(outNetBB)) { return false; } // See if we need to switch from write to read mode. switch (currStatus) { //If finished case FINISHED: initialHSComplete = true; theSocketHandler.setState(Constants.CONNECTED); setRead = true; break; case NEED_UNWRAP: setRead = true; break; default: break; } //Set the selector to read if appropriate if(setRead && passedKey != null){ theSocketHandler.getPortRouter().getSelRouter().changeOps(theSocketChannel, SelectionKey.OP_READ); } return initialHSComplete; } /* * Perform any handshaking processing. * <P> * If a SelectionKey is passed, register for selectable * operations. * <P> * In the blocking case, our caller will keep calling us until * we finish the handshake. Our reads/writes will block as expected. * <P> * In the non-blocking case, we just received the selection notification * that this channel is ready for whatever the operation is, so give * it a try. * <P> * return: * true when handshake is done. * false while handshake is in progress */ @Override public boolean doHandshake(SelectionKey passedKey) throws IOException { HandshakeStatus currStatus; if ( initialHSComplete ){ return true; } /* * Flush out the outgoing buffer, if there's anything left in * it. */ if (outNetBB.hasRemaining()) { return flushHandshakeBuffer(passedKey); } //Get the current handshake status currStatus = sslEngine.getHandshakeStatus(); //If no data to send, switch on status switch (currStatus) { case NEED_UNWRAP: //If socket is closed try { //Read the next bytes int readCount; synchronized(inNetBB){ readCount = theSocketChannel.read(inNetBB); } if (readCount == -1) { sslEngine.closeInbound(); return initialHSComplete; } } catch (BufferOverflowException ex){ DebugPrinter.printMessage( NAME_Class, "doHandshake()", ex.getMessage(), ex); } doUnwrap(passedKey); break; case NEED_WRAP: doWrap(passedKey); break; case NEED_TASK: doTasks( passedKey ); break; default: // NOT_HANDSHAKING/NEED_TASK/FINISHED //TODO Come back and code handling for this case flushHandshakeBuffer(passedKey); passedKey.cancel(); throw new SSLException("Invalid Handshaking State" + currStatus); } // switch return initialHSComplete; } /* * Do all the outstanding handshake tasks in a separate thread. */ private void doTasks( final SelectionKey passedKey) { //Need to check for "No trusted certificate found" - ValidatorException Runnable taskRunnable; while((taskRunnable = sslEngine.getDelegatedTask()) != null) { taskRunnable.run(); } //Notify listener taskFinished(passedKey); } /* * Read the channel for more information, then unwrap the * (hopefully application) data we get. * <P> * If we run out of data, we'll return to our caller (possibly using * a Selector) to get notification that more is available. * <P> * Each call to this method will perform at most one underlying read(). */ @Override public int read() throws IOException { if (!initialHSComplete) throw new IllegalStateException(); final int pos = requestBB.position(); if (theSocketChannel.read(inNetBB) == -1) { sslEngine.closeInbound(); // probably throws exception return -1; } SSLEngineResult result; do { resizeRequestBB(); // guarantees enough room for unwrap inNetBB.flip(); result = sslEngine.unwrap(inNetBB, requestBB); inNetBB.compact(); /* * Could check here for a renegotation, but we're only * doing a simple read/write, and won't have enough state * transitions to do a complete handshake, so ignore that * possibility. */ switch (result.getStatus()) { case BUFFER_UNDERFLOW: case OK: if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { doTasks( null ); } case CLOSED: break; default: throw new SSLException("sslEngine error during data read: " + result.getStatus()); } } while ((inNetBB.position() != 0) && result.getStatus() != Status.BUFFER_UNDERFLOW); return (requestBB.position() - pos); } /* * Try to write out as much as possible from the src buffer. */ @Override public int write(ByteBuffer src) throws IOException { if (!initialHSComplete) { //Check if this is the handshake message if(handShakeMsg){ handShakeMsg = false; return super.write(src); } //TODO Possible change to wait or queue throw new IllegalStateException(); } return doWrite(src); } /* * Try to flush out any existing outbound data, then try to wrap * anything new contained in the src buffer. * <P> * Return the number of bytes actually consumed from the buffer, * but the data may actually be still sitting in the output buffer, * waiting to be flushed. */ private int doWrite(ByteBuffer src) throws IOException { int retValue = 0; if (outNetBB.hasRemaining() && !tryFlush(outNetBB)) { return retValue; } /* * The data buffer is empty, we can reuse the entire buffer. */ outNetBB.clear(); final SSLEngineResult result = sslEngine.wrap(src, outNetBB); retValue = result.bytesConsumed(); outNetBB.flip(); switch (result.getStatus()) { case OK: if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { doTasks( null ); } break; default: throw new IOException("sslEngine error during data write: " + result.getStatus()); } /* * Try to flush the data, regardless of whether or not * it's been selected. Odds of a write buffer being full * is less than a read buffer being empty. */ while (outNetBB.hasRemaining()) { tryFlush(outNetBB); try { Thread.sleep(10); } catch (InterruptedException ex) {} } return retValue; } //============================================================================= /** * Flush any remaining data. * <P> * Return true when the fileChannelBB and outNetBB are empty. * @return * @throws java.io.IOException */ @Override public boolean dataFlush() throws IOException { boolean fileFlushed = true; if (outNetBB.hasRemaining()) { tryFlush(outNetBB); } theSocketChannel.socket().getOutputStream().flush(); return (fileFlushed && !outNetBB.hasRemaining()); } /* * Begin the shutdown process. * <P> * Close out the SSLEngine if not already done so, then * wrap our outgoing close_notify message and try to send it on. * <P> * Return true when we're done passing the shutdown messsages. */ @Override public boolean shutdown() throws IOException { if (!shutdown) { sslEngine.closeOutbound(); shutdown = true; } if (outNetBB.hasRemaining() && tryFlush(outNetBB)) { return false; } /* * By RFC 2616, we can "fire and forget" our close_notify * message, so that's what we'll do here. */ outNetBB.clear(); final SSLEngineResult result = sslEngine.wrap(handshakeBB, outNetBB); if (result.getStatus() != Status.CLOSED) { throw new SSLException("Improper close state"); } outNetBB.flip(); /* * We won't wait for a select here, but if this doesn't work, * we'll cycle back through on the next select. */ if (outNetBB.hasRemaining()) { tryFlush(outNetBB); } //Close the socket close(); return (!outNetBB.hasRemaining() && (result.getHandshakeStatus() != HandshakeStatus.NEED_WRAP)); } /* * Begins the handshake process */ public void beginHandshake() throws SSLException { sslEngine.beginHandshake(); } /* * Called when the SSL engine needs to wrap data * */ private void doWrap(SelectionKey passedKey) throws IOException { SSLEngineResult result; // DebugPrinter.printMessage( this.getClass().getSimpleName(), "Wrapping."); // The flush above guarantees the out buffer to be empty outNetBB.clear(); result = sslEngine.wrap(handshakeBB, outNetBB); outNetBB.flip(); HandshakeStatus currStatus = result.getHandshakeStatus(); if(currStatus == HandshakeStatus.FINISHED){ initialHSComplete = true; // DebugPrinter.printMessage( this.getClass().getSimpleName(), "Finished handshaking."); //Flush the buffer so that the client will get a finished flag too if (outNetBB.hasRemaining()){ tryFlush(outNetBB); } //Notify the comm theSocketHandler.setState( Constants.CONNECTED); theSocketHandler.getPortRouter().beNotified(); return; } //Switch on ssl engine wrap switch (result.getStatus()) { case OK: if (currStatus == HandshakeStatus.NEED_TASK) { doTasks( passedKey ); } if (passedKey != null) { theSocketHandler.getPortRouter().getSelRouter().changeOps(theSocketChannel, SelectionKey.OP_WRITE | SelectionKey.OP_READ); } break; default: // BUFFER_OVERFLOW/BUFFER_UNDERFLOW/CLOSED: throw new SSLException("Received" + result.getStatus() + "during initial handshaking"); } } /* * Called when the SSL engine needs to unwrap data * */ private void doUnwrap(SelectionKey passedKey) throws IOException { SSLEngineResult result; // DebugPrinter.printMessage( this.getClass().getSimpleName(), "Unwrapping."); // Don't need to resize requestBB, since no app data should synchronized(inNetBB){ inNetBB.flip(); result = sslEngine.unwrap(inNetBB, requestBB); inNetBB.compact(); } HandshakeStatus currStatus = result.getHandshakeStatus(); //Switch on SSL engine unwrap switch (result.getStatus()) { case OK: //Switch on current status switch (currStatus) { case NOT_HANDSHAKING: throw new IOException("Not handshaking during initial handshake"); case NEED_TASK: doTasks( passedKey ); break; case FINISHED: initialHSComplete = true; // DebugPrinter.printMessage( this.getClass().getSimpleName(), "Finished handshaking."); //Notify the comm theSocketHandler.setState( Constants.CONNECTED); theSocketHandler.getPortRouter().beNotified(); break; case NEED_UNWRAP: doUnwrap(passedKey); break; case NEED_WRAP: doWrap(passedKey); break; } break; case BUFFER_UNDERFLOW: /* * Need to go reread the Channel for more data. */ if (passedKey != null) { theSocketHandler.getPortRouter().getSelRouter().changeOps(theSocketChannel, SelectionKey.OP_READ); } break; default: // BUFFER_OVERFLOW/CLOSED: throw new SSLException("Received" + result.getStatus() + "during initial handshaking"); } } //=============================================================== /** /* * Called when the SSL tasks have completed * */ private void taskFinished(SelectionKey passedKey) { HandshakeStatus currStatus = sslEngine.getHandshakeStatus(); try { switch (currStatus) { case NEED_UNWRAP: // Don't need to resize requestBB, since no app data should if(!outNetBB.hasRemaining()){ doUnwrap(passedKey); } break; case NEED_WRAP: if(!outNetBB.hasRemaining()) { // Wrap up the next data and change to read doWrap(passedKey); } break; case FINISHED: initialHSComplete = true; // DebugPrinter.printMessage( this.getClass().getSimpleName(), "Finished handshaking."); //Notify the comm theSocketHandler.setState( Constants.CONNECTED); theSocketHandler.getPortRouter().beNotified(); break; default: // DebugPrinter.printMessage(SecureSocketChannelWrapper.class, "Not handshaking."); } } catch ( SSLException ex ){ if( ex.getMessage().contains("Handshake message sequence violation, 2" )){ //Create a relay object MaltegoMessage theReturnMsg = new MaltegoMessage(); String retStr = "Unable to connect to Pwnbrew server. Please ensure the Pwnbrew MaltegoStub SSL Certificate has been imported into the target Pwnbrew server's keystore."; pwnbrew.xml.maltego.Exception exMsg = new pwnbrew.xml.maltego.Exception( retStr ); MaltegoTransformExceptionMessage malMsg = theReturnMsg.getExceptionMessage(); //Create the message list malMsg.getExceptionMessages().addExceptionMessage(exMsg); System.out.println(theReturnMsg.getXml()); System.exit(0); } } catch (IOException ex){ DebugPrinter.printMessage( NAME_Class, "taskFinished", ex.getMessage(), ex); } } }
package controlador; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import implementacion.ImpICapacitacion; import interfaces.IConsultas; import modelo.Capacitacion; /** * Servlet implementation class FormCrearCapacitacion */ @WebServlet("/FormCrearCapacitacion") public class FormCrearCapacitacion extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FormCrearCapacitacion() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Clase_7_Grupal_6 punto 7 String fecha = request.getParameter("fecha"); String hora = request.getParameter("hora"); String lugar = request.getParameter("lugar"); Integer duracion = Integer.parseInt(request.getParameter("duracion")); Integer rutCliente = Integer.parseInt(request.getParameter("rutCliente")); Capacitacion crearCapacitacion = new Capacitacion(null, fecha, hora, lugar, duracion, rutCliente); IConsultas<Capacitacion> implementacion = new ImpICapacitacion(); boolean mostrar = implementacion.registrar(crearCapacitacion); request.setAttribute("mostrarRegistrarCapacitacion", mostrar); HttpSession sesion = request.getSession(); String sesionUsuario = (String) sesion.getAttribute("sesionUsuario"); if (sesionUsuario == null) { request.getRequestDispatcher("login.jsp").forward(request, response); } else { request.getRequestDispatcher("vistaCrearCapacitacion.jsp").forward(request, response); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.akanar.controller; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.akanar.exceptions.BusinessException; import com.akanar.model.AccountInfo; import com.akanar.model.TransactionInfo; import com.akanar.service.AkanarService; import com.akanar.service.impl.AkanarServiceImpl; import com.google.gson.Gson; /** * Servlet implementation class TransactionHistoryController */ @WebServlet("/history") public class TransactionHistoryController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public TransactionHistoryController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { AkanarService service = new AkanarServiceImpl(); response.setContentType("application/json;charset=UTF-8"); Gson gson = new Gson(); ServletOutputStream jout = response.getOutputStream(); String json = request.getReader().lines().collect(Collectors.joining()); AccountInfo account = gson.fromJson(json, AccountInfo.class); if(request.getSession(false) != null) { try { List<TransactionInfo> history = service.getTransactionInfoByAccount(account.getAccount_id()); jout.print(gson.toJson(history)); } catch (BusinessException e) { System.out.println(e.getMessage()); } } } }
package com.engin.widget; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.graphics.Shader; import android.os.Build; import android.util.AttributeSet; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import com.engin.utils.LogUtil; /** * Created by zhaoningqiang on 16/6/25. */ public class FloatCircleImageView extends ImageView { Paint mPaint = new Paint(); Bitmap floatBitmap; Bitmap backBitmap; RectF contentRect; Matrix floatMatrix = new Matrix(); Matrix backMatrix = new Matrix(); BitmapShader backShader; BitmapShader floatShader; Paint floatPaint = new Paint(Paint.ANTI_ALIAS_FLAG); Paint backPaint = new Paint(Paint.ANTI_ALIAS_FLAG); public FloatCircleImageView(Context context) { super(context); init(); } public FloatCircleImageView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public FloatCircleImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init(){ } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public FloatCircleImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public void setUpperLayerBitmap(Bitmap bitmap){ // contentRect = new RectF(getPaddingLeft(),getPaddingTop(),getWidth() - getPaddingRight(),getHeight() - getPaddingBottom()); floatBitmap = bitmap; floatShader = new BitmapShader(floatBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); floatPaint.setShader(floatShader); updateFloatMatrix(); isDrawBitmap = true; invalidate(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inSampleSize = floatBitmap.getWidth()/getWidth(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); contentRect = new RectF(getPaddingLeft(),getPaddingTop(),getWidth() - getPaddingRight(),getHeight() - getPaddingBottom()); } private void updateFloatMatrix() { float scale; float dx = 0; float dy = 0; floatMatrix.set(null); int bitmapWidth = floatBitmap.getWidth(); int bitmapHeight = floatBitmap.getHeight(); if (bitmapWidth * contentRect.height() > contentRect.width() * bitmapHeight) { scale = contentRect.height() / (float) bitmapHeight; dx = (contentRect.width() - bitmapWidth * scale) * 0.5f; } else { scale = contentRect.width() / (float) bitmapWidth; dy = (contentRect.height() - bitmapHeight * scale) * 0.5f; } floatMatrix.setScale(scale, scale); floatMatrix.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f)); floatShader.setLocalMatrix(floatMatrix); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); } public void update(float offset){ LogUtil.d("test update 11111 offset = " + offset); if (offset >=0 && offset <=1){ this.offset = offset; invalidate(); } } private volatile float offset; private boolean isDrawBitmap = true; protected void onDraw(Canvas canvas) { super.onDraw(canvas); // if (floatBitmap != null){ // canvas.save(); // canvas.translate(getWidth() * offset, 0); // canvas.drawBitmap(floatBitmap, null, contentRect,null); // canvas.restore(); // } // // // // // // // mPaint.setARGB(255,255,0,255); // mPaint.setStyle(Paint.Style.FILL); // RectF rectF = new RectF(getPaddingLeft(),getPaddingTop(),getWidth() - getPaddingRight(),getHeight() - getPaddingBottom()); // Path mPath = new Path(); // mPath.addRect(rectF, Path.Direction.CW); // mPath.addArc(rectF,0,360); // mPath.setFillType(Path.FillType.EVEN_ODD); // canvas.drawPath(mPath,mPaint); } }