text
stringlengths
10
2.72M
package cn.itcast.sunnet.web.servlet; import cn.itcast.sunnet.service.UserService; import cn.itcast.sunnet.service.impl.UserServiceImpl; 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 java.io.IOException; import java.util.List; /** * Created by cdx on 2019/11/28. * desc: */ @WebServlet("/delSelectedUserServlet") public class DelSelectedUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String[] ids = req.getParameterValues("uid"); UserService service = new UserServiceImpl(); for (String id : ids) { service.delete(Integer.parseInt(id)); } resp.sendRedirect(req.getContextPath() + "/userListServlet"); } }
/** * Created on 2020/2/28. * * @author ray */ //编写一个程序,通过已填充的空格来解决数独问题。 // // 一个数独的解法需遵循如下规则: // // // 数字 1-9 在每一行只能出现一次。 // 数字 1-9 在每一列只能出现一次。 // 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。 // // // 空白格用 '.' 表示。 // // // // 一个数独。 // // // // 答案被标成红色。 // // Note: // // // 给定的数独序列只包含数字 1-9 和字符 '.' 。 // 你可以假设给定的数独只有唯一解。 // 给定数独永远是 9x9 形式的。 // // Related Topics 哈希表 回溯算法 public class SolveSudoku { public static void solveSudoku(char[][] board) { if (board == null || board.length == 0) { return; } int[][] row = new int[9][9]; int[][] col = new int[9][9]; int[][] boxes = new int[9][9]; prepareTheLimit(row, col, boxes, board); solve(board, row, col, boxes); } public static boolean solve(char[][] board, int[][] row, int[][] col, int[][] boxes) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] == '.') { for (char c = '1'; c <= '9'; c++) { int convertValue = c - 49; if (isValid(i, j, convertValue, row, col, boxes)) { board[i][j] = c; row[i][convertValue] += 1; col[j][convertValue] += 1; boxes[getIndex(i, j)][convertValue] += 1; if (solve(board, row, col, boxes)) { return true; } board[i][j] = '.'; row[i][convertValue] -= 1; col[j][convertValue] -= 1; boxes[getIndex(i, j)][convertValue] -= 1; } } return false; } } } return true; } private static boolean isValid(int idxRow, int idxCol, int ch, int[][] row, int[][] col, int[][] boxes) { return row[idxRow][ch] == 0 && col[idxCol][ch] == 0 && boxes[getIndex(idxRow, idxCol)][ch] == 0; } private static void prepareTheLimit(int[][] row, int[][] col, int[][] boxes, char[][] board) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { char ch = board[i][j]; if (ch != '.') { int convertValue = ch - 49; row[i][convertValue] += 1; col[j][convertValue] += 1; boxes[getIndex(i, j)][convertValue] += 1; } } } } private static int getIndex(int i, int j) { int p; if (i >= 0 && i <= 2) { p = 0; } else if (i >= 3 && i <= 5) { p = 1; } else { p = 2; } if (j >= 0 && j <= 2) { return p; } else if (j >= 3 && j <= 5) { return p + 3; } else { return p + 6; } } public static void main(String[] args) { char[][] arr = {{'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}}; solveSudoku(arr); System.out.println("hahah"); } }
package rent.common.projection; import org.springframework.data.rest.core.config.Projection; import rent.common.entity.UserEntity; @Projection(types = {UserEntity.class}) public interface UserMinimal { String getId(); String getLogin(); String getFullName(); String getEmail(); Boolean getBlocked(); Boolean getOnline(); RoleMinimal getRole(); }
package shape; import java.awt.Shape; import java.awt.geom.Path2D; import java.awt.geom.RoundRectangle2D; import main.GConstants; public class GRoundRectangle extends GShape implements Cloneable { private static final long serialVersionUID = GConstants.serialVersionUID; int X1 = 0; int Y1 = 0; int arcWidth = 20; int arcHeight = 20; public GRoundRectangle() { this.eDrawingStyle = EDrawingStyle.e2Points; this.shape = new RoundRectangle2D.Double(); init(); } @Override public void setOrigin(int x, int y) { RoundRectangle2D roundR = (RoundRectangle2D) this.shape; roundR.setRoundRect(x, y, 0, 0, arcWidth, arcHeight); X1 = x; Y1 = y; } @Override public void setPoint(int x, int y) { RoundRectangle2D roundR = (RoundRectangle2D) this.shape; int newX = Math.min(x, X1); int newY = Math.min(y, Y1); int newW = Math.abs(x - X1); int newH = Math.abs(y - Y1); roundR.setFrame(newX, newY, newW, newH); } @Override public void addPoint(int x, int y) { } @Override public void setShape(Shape shape) { try { RoundRectangle2D originRoundR = (RoundRectangle2D) shape; this.shape = (Shape) originRoundR.clone(); } catch (ClassCastException e) { Path2D originRectangle = (Path2D) shape; this.shape = (Shape) originRectangle.clone(); } } }
package com.fansolomon.Structural.Decorator.Shape; public class ColorShapeDecorator extends ShapeDecorator { private String color; public ColorShapeDecorator(Shape decoratedShape, String color) { super(decoratedShape); this.color = color; } @Override public void draw() { decoratedShape.draw(); setColor(color); } private void setColor(String color) { System.out.println("color set: " + color); } }
package org.ca.View; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.ca.controller.ClinicController; import org.ca.Model.Clinic; import org.softech.FileUpload; /** * Servlet implementation class ClinicSubmit */ @WebServlet("/ClinicSubmit") @MultipartConfig(fileSizeThreshold=1024*1024*2,//2MB maxFileSize=1024*1024*10,//10MB maxRequestSize=1024*1024*50) public class ClinicSubmit extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ClinicSubmit() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub try{ PrintWriter out=response.getWriter(); Clinic C=new Clinic(); C.setTypeid(request.getParameter("tid")); C.setClinicid(request.getParameter("clid")); C.setClinicname(request.getParameter("clin")); C.setDoctorname(request.getParameter("dn")+" "+request.getParameter("odn")); C.setSpecialist(request.getParameter("cs")); C.setExperience(request.getParameter("de")); C.setPayment(request.getParameter("dp")); C.setOpeningtime(request.getParameter("ot")); C.setClosingtime(request.getParameter("ct")); C.setClimobno(request.getParameter("cmob")); C.setCliemail(request.getParameter("cm")); C.setCliaddress(request.getParameter("cad")); C.setClistate(request.getParameter("cstate")); C.setClicity(request.getParameter("ccity")); C.setOtherfacility(request.getParameter("of")); C.setCertificate(request.getParameter("ecr")); //for file uploading Part part=request.getPart("dph"); String path="C:/Users/HP/workspace/ClinicalAdvisor/WebContent/images/doctor"; FileUpload f=new FileUpload(part,path); C.setDoctorphotoes(f.filename); boolean st=ClinicController.addNewRecord(C); if(st) { out.println("record submitted"); } else { out.println("record not found...."); } }catch(Exception e) {System.out.println("clinicSubmit"+e); } } }
package com.ytt.springcoredemo.service.base; import com.ytt.springcoredemo.model.BaseEntity; import com.ytt.springcoredemo.dao.mapper.core.CoreMapper; @Deprecated public abstract class SaveBaseServiceImpl<T extends BaseEntity<ID>, ID, K extends CoreMapper<T,ID>> extends DaoBaseServiceImpl<T, ID, K> implements SaveBaseService<T,ID> { @Override public int save(T record){ return mapper.insert(record); } @Override public int saveSelective(T record){ return mapper.insertSelective(record); } }
package io.bega.kduino.fragments; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.ArrayList; import java.util.List; import io.bega.kduino.R; import io.bega.kduino.fragments.intro.PlaceSlideFragment; public class IntroductionImageFragmentPageAdapter extends FragmentPagerAdapter { // List of fragments which are going to set in the view pager widget private int[] Images = new int[] { R.drawable.intro1, R.drawable.intro2, R.drawable.intro3, R.drawable.intro4 }; /** * Constructor * * @param fm * interface for interacting with Fragment objects inside of an * Activity */ public IntroductionImageFragmentPageAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int arg0) { return PlaceSlideFragment.newInstance(Images[arg0]); } @Override public int getCount() { return Images.length; } }
package com.myhome.lee.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * Created by lee on 17/3/1. */ @Entity @Table(name = "Article") public class Article { @Id @Column(name="id", nullable = false) private String id; @Column(name="title", unique=true, nullable=false) private String title; }
package cn.omsfuk.library.web.dao; import cn.omsfuk.library.web.model.Book; import cn.omsfuk.library.web.model.Borrow; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.data.domain.PageRequest; import java.util.List; @Mapper public interface BorrowDAO { List<Book> listBorrowByUsername(@Param("username") String username, @Param("page") PageRequest page); Integer borrowBookById(@Param("ids") List<Integer> ids, @Param("userId")int userId); Integer returnBookById(@Param("ids") List<Integer> ids, @Param("userId")int userId); Integer renewBorrowById(@Param("book_id") int id, @Param("user_id") Integer userId); Integer countBorrowByUserId(@Param("userId") int userId); Integer countOverdueSoonByUserId(@Param("userId") int userId); Integer isBorrowed(@Param("ids") List<Integer> ids, @Param("userId") Integer userId); List<Borrow> listBorrowedByUserId(@Param("userId") int id, @Param("page") PageRequest page); }
package app.com.bugdroidbuilder.paulo.droidhealth.view; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import app.com.bugdroidbuilder.paulo.droidhealth.R; import app.com.bugdroidbuilder.paulo.droidhealth.controller.HealthController; import app.com.bugdroidbuilder.paulo.droidhealth.controller.PreferencesDAO; import app.com.bugdroidbuilder.paulo.droidhealth.model.Person; /** * Created by paulo on 13/04/16. */ public class MainActivity extends AppCompatActivity implements ToolbarInterface { PreferencesDAO preferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); startToolbar(); startTabControl(); this.preferences = new PreferencesDAO(this); if(this.preferences.hasDataStored()){ this.preferences.restoreUserData(); } } @Override protected void onStop(){ super.onStop(); this.preferences.storeUserData(); } /** Initialize system toolbar * */ public void startToolbar(){ final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } /** Initialize and control MainActivity tabs * */ private void startTabControl(){ final TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); // /Add tabs and their respective title tabLayout.addTab(tabLayout.newTab().setText("Perfil")); tabLayout.addTab(tabLayout.newTab().setText("Dicas")); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); //Set the color of the text in the tab tabLayout.setTabTextColors(getResources().getColor(R.color.colorTextTabUnselected), getResources().getColor(R.color.colorTextTabSelected)); final ViewPager viewPager = (ViewPager) findViewById(R.id.pager); final PagerAdapter adapter = new PagerAdapter (getSupportFragmentManager(), tabLayout.getTabCount()); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } @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) { int id = item.getItemId(); // if this option is selected, the app goes to SettingsActivity if (id == R.id.action_settings) { startActivity(new Intent(this, SettingsActivity.class)); return true; }else if(id == R.id.information_settings){ startActivity(new Intent(this, InformationActivity.class)); return true; } return super.onOptionsItemSelected(item); } public static void main(String args) { } }
package com.ArcLancer.Test.Spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SayHello { public SayHello() { } @SuppressWarnings("resource") public String SayHello2() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringBeans.xml"); HelloBeans helloBeans = (HelloBeans) applicationContext.getBean("helloBeans"); return helloBeans.getMessage(); } }
package com.test.pages; import java.util.ArrayList; import java.util.List; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import com.test.utils.TestBase; /** * @author Mohitesh.B.Kumar * */ public class HomePage extends TestBase { static WebDriver driver; public HomePage(WebDriver driver) { HomePage.driver = driver; PageFactory.initElements(driver, this); } @FindBy(how = How.XPATH, using = HomeScreen.registerButton_Xpath) public WebElement registerButton; @FindBy(how = How.XPATH, using = HomeScreen.searchIcon_Xpath) public WebElement searchIcon; @FindBy(how = How.XPATH, using = HomeScreen.searchInBlog_Xpath) public WebElement searchInBlog; @FindBy(how = How.XPATH, using = HomeScreen.continueWithoutBonus_Xpath) public WebElement continueWithoutBonus; @FindBy(how = How.XPATH, using = HomeScreen.acceptCookies_Xpath) public WebElement acceptCookies; // Method to click on Register button public void clickOnRegisterButton() { try { registerButton.click(); } catch (Exception e) { log.info("Exception occured while clicking on register button :: " + e); } } // Method to click on Search Icon public void clickOnSearchIcon() { try { searchIcon.click(); } catch (Exception e) { log.info("Exception occured while clicking on Search Icon :: " + e); } } // Method to search on Blog page public void enterSearchKeyword(String searchKeyword) { try { sendKeys(searchKeyword, searchInBlog, "Search in blog"); sendKeysFromKeyBoard(Keys.ENTER, searchInBlog, "Search in blog"); } catch (Exception e) { log.info("Exception occured while entering data in Search in blog :: " + e); } } // Method to click on Accept cookies button public void clickOnAcceptCookies() { try { acceptCookies.click(); } catch (Exception e) { log.info("Exception occured while clicking on Accept cookies button :: " + e); } } // Method to click on Search Icon public void clickOnContinueWithoutBonus() { try { continueWithoutBonus.click(); } catch (Exception e) { log.info("Exception occured while clicking on continueWithoutBonus button :: " + e); } } }
package edu.weber; public class Banana extends Fruit { public Banana() { super(FruitName.BANANA, FruitColor.YELLOW); } }
package leecode.other; import java.util.Stack; public class 验证栈序列_946 { public boolean validateStackSequences(int[] pushed, int[] popped) { /*考察堆栈,就用堆栈模拟,两个指针太麻烦 Stack<Integer>stack=new Stack<>(); int pop=0; int push=0; while (pop<popped.length){ if(popped[pop]>pushed[push]){ stack.push(pushed[push++]); } if(popped[pop]==pushed[push]){ push++; pop++; } } */ Stack<Integer>stack=new Stack<>(); int j=0; for (int i = 0; i <pushed.length ; i++) { stack.push(pushed[i]); while (!stack.isEmpty()&&popped[j]==stack.peek()){ stack.pop(); j++; } } return stack.isEmpty(); } }
package com.design.state; public class TVStopState implements PdkState{ public void doAction() { // TODO Auto-generated method stub System.out.println("TV is going to switch off......"); } }
package stalls; import interfaces.IRestrictable; import persons.Visitor; public class TobaccoStall extends Stall implements IRestrictable { private int minAge; public TobaccoStall(String name, String ownerName, String parkingSpot, int funRating, double price) { super(name, ownerName, parkingSpot, funRating, price); this.minAge = 18; } public boolean isAllowedTo(Visitor visitor) { return visitor.getAge() >= minAge; } }
package ie.brewer.controller; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import ie.brewer.model.Beer; @Controller public class BeersController { @RequestMapping("/beers/page") public String page(Beer beer) { return "beer/addBeer"; } @RequestMapping(value = "/beers/page", method = RequestMethod.POST) public String addBeer(@Valid Beer beer, BindingResult result, Model model, RedirectAttributes attributes) { if( result.hasErrors() ) { return page(beer); } attributes.addFlashAttribute("message", "Beer add successfyly :) "); return "redirect:/beers/page"; } }
package start.entity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; /** * @Author: Jason * @Create: 2020/10/11 20:57 * @Description 分布式锁类 */ @Component public class DistributedLockHandler { private static final Logger logger = LoggerFactory.getLogger(DistributedLockHandler.class); private final static long LOCK_EXPIRE = 30 * 1000L; //单个业务持有锁的时间 private final static long LOCK_TRY_INTERVAL = 30L; //默认30ms一次 private final static long LOCK_TRY_TIMEOUT = 20 * 1000L; //默认尝试20s @Autowired private StringRedisTemplate stringRedisTemplate; /** * 尝试获取全局锁 * @param lock 锁的名称 * @return true 获取成功,false获取失败 */ public boolean tryLock(Lock lock){ return getLock(lock, LOCK_TRY_TIMEOUT, LOCK_TRY_INTERVAL, LOCK_EXPIRE); } /** *尝试获取全局锁 * @param lock 锁的名称 * @param timeout 获取锁的超时时间,单位ms * @return true 获取成功, false 获取失败 */ public boolean tryLock(Lock lock, long timeout){ return getLock(lock, timeout, LOCK_TRY_INTERVAL, LOCK_EXPIRE); } /** * 尝试获取全局锁 * @param lock 锁的名称 * @param timeout 获取锁的超时时间 * @param tryInterval 获取成功 true 代表成功 false 代表失败 * @return */ public boolean tryLock(Lock lock, long timeout, long tryInterval){ return getLock(lock, timeout, tryInterval, LOCK_EXPIRE); } /** * 尝试获取全局锁 * @param lock 锁的名称 * @param timeout 获取锁的超时时间 * @param tryInterval 尝试间隔次数 * @param lockExpireTime 锁的过期时间 * @return */ public boolean tryLock(Lock lock, long timeout, long tryInterval, long lockExpireTime){ return getLock(lock, timeout, tryInterval, LOCK_EXPIRE); } /** * 操作redis获取全局锁 * @param lock 锁的名称 * @param timeout 获取的超时时间 * @param tryInterval 多少ms尝试一次 * @param lockExpireTime 获取成功后锁的过期时间 * @return true 获取成功 false 获取失败 * @throws InterruptedException * 其原理是:在判断是否有key的基础上,进行循环,只有当不存在key才对其进行加锁操作,其他不对其进行任何操作 */ public boolean getLock(Lock lock, long timeout, long tryInterval, long lockExpireTime) { if(StringUtils.isEmpty(lock.getName()) || StringUtils.isEmpty(lock.getValue())){ return false; } long startTime = System.currentTimeMillis(); do{ if (!stringRedisTemplate.hasKey(lock.getName())){ ValueOperations<String, String> ops = stringRedisTemplate.opsForValue(); ops.set(lock.getName(),lock.getValue(), lockExpireTime); return true; }else{//存在锁 logger.debug("lock is exist"); } //尝试超过设定值之后直接跳出循环 if (System.currentTimeMillis() - startTime > timeout){ return false; } try { Thread.sleep(tryInterval); } catch (InterruptedException e) { e.printStackTrace(); } } while (stringRedisTemplate.hasKey(lock.getName())); return false; } /** * 释放锁方法 * @param lock */ public void releaseLock(Lock lock){ if (!StringUtils.isEmpty(lock.getName())){ stringRedisTemplate.delete(lock.getName()); } } }
package app.playground2; import java.util.Date; import util.Address; public class CreditCard { private Integer ident = null; private String name; private Address address; private String number; private String cvv; private Date expiry; public CreditCard() { } public CreditCard( String name, Address address, String number, String cvv, Date expiry ) { this.name = name; this.address = address; this.number = number; this.cvv = cvv; this.expiry = expiry; } public Integer getIdent() { return ident; } public void setIdent(Integer ident) { this.ident = ident; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getCvv() { return cvv; } public void setCvv(String cvv) { this.cvv = cvv; } public Date getExpiry() { return expiry; } public void setExpiry(Date expiry) { this.expiry = expiry; } @Override public String toString() { StringBuilder bldr = new StringBuilder(); bldr.append( ident ).append( "," ); bldr.append( name ).append( "," ); bldr.append( address ).append( "," ); bldr.append( number ).append( "," ); bldr.append( cvv ).append( "," ); bldr.append( expiry ); return bldr.toString(); } }
package arrays; public class RotationUsingReversal { //Complexity=O(n) public static void main(String[] args) { int array[]= {2, 5, 7, 9, 6, 3, 4, 8}; RotationUsingReversal rur=new RotationUsingReversal(); int d=3; int n=array.length; //for left rotation /*rur.reverse(array, 0, d-1); rur.reverse(array, 3, n-1); rur.reverse(array, 0, n-1);*/ //for right rotation rur.reverse(array, 0, n-1-d); //d=3 rur.reverse(array, n-d, n-1); rur.reverse(array, 0, n-1); for(int ele:array) System.out.print(ele+" "); } void reverse(int[] arr, int start, int end) { int temp; while(start<end) { temp=arr[start]; arr[start]=arr[end]; arr[end]=temp; start++; end--; } } }
package com.assignment08_sudoku; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import androidx.core.app.TaskStackBuilder; import androidx.preference.PreferenceManager; import java.util.Locale; public class settingsActivity extends AppCompatActivity { SharedPreferences sharedPreferences; SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener(){ @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) { String newLanguageCode = sharedPreferences.getString(getString(R.string.current_language_code),""); Log.i(getLocalClassName(),"onSharedPreferenceChanged s: "+s+" new language: "+newLanguageCode); Locale locale = new Locale(newLanguageCode); Configuration configuration=new Configuration(); configuration.setLocale(locale); Resources resources=getResources(); resources.updateConfiguration(configuration,resources.getDisplayMetrics()); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(this.getClass().getSimpleName(),"OnCreate"); setContentView(R.layout.activity_settings); if(findViewById(R.id.fragment_settings)!=null){ //legger til fragmentet med innstillingene. getFragmentManager().beginTransaction().add(R.id.fragment_settings,new SettingsFragment()).commit(); }else Log.i(this.getClass().getSimpleName(), "onCreate: fant ikke fragment_settings"); sharedPreferences=PreferenceManager.getDefaultSharedPreferences(this); } @Override public void onPrepareSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) { super.onPrepareSupportNavigateUpTaskStack(builder); } @Override public void onOptionsMenuClosed(Menu menu) { super.onOptionsMenuClosed(menu); Log.i(this.getClass().getSimpleName(),"onOptionsMenuClosed"); } @Override public void onContextMenuClosed(@NonNull Menu menu) { super.onContextMenuClosed(menu); Log.i(this.getClass().getSimpleName(),"onContextMenuClosed"); } @Override public void closeContextMenu() { super.closeContextMenu(); Log.i(this.getClass().getSimpleName(),"closeContextMenu"); } @Override public void onBackPressed() { super.onBackPressed(); Log.i(this.getClass().getSimpleName(),"onBackPressed"); finish(); // startActivity(new Intent(getApplicationContext(),DifficultSelect.class)); } public void settings(View v){ } public void reset(View v){ /* Tatt inspirasjon fra følgende nettside for advarsels dialogen https://www.tutorialspoint.com/android/android_alert_dialoges.htm */ AlertDialog.Builder warning = new AlertDialog.Builder(this); warning.setTitle(R.string.dataBaseMessage); warning.setPositiveButton(getString(R.string.yes),new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialogInterface, int i) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); sharedPreferences.edit().putBoolean("resetDatabase",true).apply(); finish(); startActivity(new Intent(getApplicationContext(),MainActivity.class)); } }); warning.setNegativeButton(getString(R.string.no),new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialogInterface, int i) { } }); warning.show(); } @Override protected void onDestroy() { super.onDestroy(); Log.i(getLocalClassName(),"onDestroy"); } @Override protected void onPostResume() { super.onPostResume(); Log.i(getLocalClassName(),"onPostResume"); sharedPreferences.registerOnSharedPreferenceChangeListener(listener); } @Override protected void onPause() { super.onPause(); Log.i(getLocalClassName(),"onPause"); sharedPreferences.unregisterOnSharedPreferenceChangeListener(null); } }
package com.gauro.consumer; import com.fasterxml.jackson.databind.ObjectMapper; import com.gauro.domain.Picture; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Service; import java.io.IOException; /** * @author Chandra */ @Service @Slf4j public class PictureVectorConsumer { private ObjectMapper objectMapper=new ObjectMapper(); @RabbitListener(queues = "q.picture.vector") public void listen(String message){ try { log.info("On Vector:{}", objectMapper.readValue(message, Picture.class)); } catch (IOException e) { e.printStackTrace(); } } }
package com.sourceallies.filter; import static org.mockito.Mockito.mock; import static org.junit.Assert.*; import java.io.Writer; import org.junit.Test; public class PrintWriterLoggerFactoryTest { @Test public void testCreate(){ PrintWriterLoggerFactory factory = new PrintWriterLoggerFactory(); Writer mockWriter = mock(Writer.class); PrintWriterLogger printWriterLogger = factory.create(mockWriter); assertNotNull(printWriterLogger); assertSame(mockWriter, printWriterLogger.getWriter()); } }
package materialdesign.practice.com.recyclerfragment.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import java.util.ArrayList; import java.util.List; import materialdesign.practice.com.recyclerfragment.Adapter.rvAdapter; import materialdesign.practice.com.recyclerfragment.R; import materialdesign.practice.com.recyclerfragment.Util.ModelClass; //https://www.youtube.com/watch?v=DGdU2EssTE0 //https://proandroiddev.com/playing-with-material-design-transitions-b3ea90c5794c public class MainActivity extends AppCompatActivity { List<ModelClass> data = new ArrayList<>(); ModelClass modelClass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar =(Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); onLoadData(); RecyclerView recyclerView = findViewById(R.id.rvList); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(new rvAdapter(MainActivity.this, data)); /*, title, descp, name, time));*/ recyclerView.setHasFixedSize(true); } private void onLoadData() { modelClass = new ModelClass(); data.add(new ModelClass("name1","title1","descp1","link1" ,"time1")); data.add(new ModelClass("name2","title1","descp1","link2", "time2" )); data.add(new ModelClass("name2","title1","descp1","link1","time2" )); data.add(new ModelClass("name2","title1","descp1","link","time2" )); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.toolbar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.add: Intent i = new Intent(MainActivity.this, AddDataActivity.class); startActivity(i); break; } return true; } }
package com.foosbot.service.model.season; public class RankResult { }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import Conexion.ConexionBD; import logica.DetalleCamara; import logica.DetalleCamaraId; import logica.DetallePredio; import logica.DetallePredioId; /** * Clase que permite realizar acciones sobre detallePredio en la * base de datos * @author LEIDY * */ public class DetallePredioDao{ /** * Método que permite almacenar la informacion en la base de datos * @param detallePredio * @return */ public boolean guardaDetallePredio(DetallePredio detallePredio){ try { Connection conn = ConexionBD.obtenerConexion(); String queryInsertar = "INSERT INTO detalle_predio VALUES(?,?,?)"; PreparedStatement ppStm = conn.prepareStatement(queryInsertar); ppStm.setString(1, detallePredio.getDescripcionPredio()); ppStm.setInt(2, detallePredio.getId().getClienteCedula()); ppStm.setInt(3, detallePredio.getId().getImpuestoPredialNPredio()); ppStm.executeUpdate(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } /** * Método que permite actualizar la informacion en la base de datos * @param detallePredio * @return */ public boolean actualizaDetallePredio(DetallePredio detallePredio){ try { Connection conn = ConexionBD.obtenerConexion(); String queryUpdate = "UPDATE detalle_predio SET" + " Descripcion_Predio = ? WHERE " + "Impuesto_Predial_N_Predio= ?"; PreparedStatement ppStm = conn.prepareStatement(queryUpdate); ppStm.setString(1, detallePredio.getDescripcionPredio()); ppStm.setInt(2, detallePredio.getId().getImpuestoPredialNPredio()); ppStm.executeUpdate(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } /** * Método que permite eliminar la informacion de detalle de predio * @param detallePredio * @return */ public boolean eliminaDetallePredio(DetallePredio detallePredio){ try { Connection conn = ConexionBD.obtenerConexion(); String queryDelete = "DELETE FROM detalle_predio " + "WHERE Impuesto_Predial_N_Predio = ?"; PreparedStatement ppStm = conn.prepareStatement(queryDelete); ppStm.setInt(1, detallePredio.getId().getImpuestoPredialNPredio()); ppStm.executeUpdate(); conn.close(); return true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } /** * Método que permite obtener la informacion del detalle de predio * @param id * @return */ public DetallePredio obtenDetallePredio(DetallePredioId id){ DetallePredio detallePredio = null; try { Connection conn = ConexionBD.obtenerConexion(); String querySearch = "SELECT FROM detalle_predio " + "WHERE Impuesto_Predial_N_Predio = ?"; PreparedStatement ppStm = conn.prepareStatement(querySearch); ppStm.setInt(1, id.getImpuestoPredialNPredio()); ResultSet resultSet = ppStm.executeQuery(); if(resultSet.next()){ detallePredio = new DetallePredio(); detallePredio.setDescripcionPredio(resultSet.getString(1)); detallePredio.setId(new DetallePredioId(resultSet.getInt(2), resultSet.getInt(3))); }else{ return detallePredio; } conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return detallePredio; } public List<DetallePredio> obtenListaDetallePredio(){ List<DetallePredio> listaDetallePredio = null; return listaDetallePredio; } // public static void main(String[] args) { // // DetallePredioDao daodp = new DetallePredioDao(); // ClienteDao daoc = new ClienteDao(); // SoatDao daos = new SoatDao(); // // Guardar // //daodp.guardaDetallePredio(new DetallePredio(new DetallePredioId(108796548, 846259), "Finca Duitama")); // // Actualizar // //daodp.actualizaDetallePredio(new DetallePredio(new DetallePredioId(108796548, 846259), "Finca Sogamoso")); // //Borrar // daodp.eliminaDetallePredio(new DetallePredio(new DetallePredioId(108796548, 846259), null)); // //daods.eliminaDetalleSoat(new DetalleSoat(new DetalleSoatId(108796548, "rft458"), null)); // } }
package com.goldgov.dygl.module.partyMemberInfo.web; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.goldgov.dygl.module.partyMemberInfo.service.IPartyMemberService_AJ; import com.goldgov.dygl.module.partyMemberInfo.service.IPartyMemberService_AJ1; import com.goldgov.dygl.module.partymember.exception.NoAuthorizedFieldException; import com.goldgov.dygl.module.partymember.service.PartyMemberQuery; import com.goldgov.dygl.module.partymemberSh.domain.CheckInfo; import com.goldgov.dygl.module.partymemberSh.web.CheckUtil; import com.goldgov.dygl.module.partyorganization.web.BasePartyOrganizationController; import com.goldgov.gtiles.core.web.GoTo; import com.goldgov.gtiles.core.web.OperatingType; import com.goldgov.gtiles.core.web.annotation.ModelQuery; import com.goldgov.gtiles.core.web.annotation.ModuleOperating; import com.goldgov.gtiles.core.web.annotation.ModuleResource; import com.goldgov.gtiles.core.web.json.JsonObject; import com.goldgov.gtiles.core.web.token.WebToken; import com.goldgov.gtiles.module.businessfield.service.BusinessField; /** * * Title: partyMemberController_AJ1<br> * Description: 个人动态信息(个人)婚姻状态<br> * Copyright @ 2011~2016 Goldgov .All rights reserved.<br> * * @author gxp * @createDate 2016年06月25日 * @version $Revision: $ */ @RequestMapping("/module/partyMemberInfo/aj1") @Controller("partyMemberController_AJ1") @ModuleResource(name="个人动态信息(个人)婚姻状态") public class partyMemberController_AJ1 extends BasePartyOrganizationController{ public static final String PAGE_BASE_PATH = "partyMemberInfo/web/pages/"; private String infoType = "AJ1"; @Autowired @Qualifier("PartyMemberServiceImpl_AJ1") private IPartyMemberService_AJ1 partyMemberServiceImpl_AJ1; @Autowired @Qualifier("PartyMemberServiceImpl_AJ") private IPartyMemberService_AJ partyMemberServiceImpl_AJ; @RequestMapping("/findInfoByAAID") public String findInfoByAAID(Model model,HttpServletRequest request) throws NoAuthorizedFieldException{ String aaid = request.getParameter("AA_ID"); Map<String,Object> map=partyMemberServiceImpl_AJ1.findInfoByAAID(aaid); model.addAttribute("AA_ID", aaid); if(map==null||map.get("entityID")==null){ return preAdd(model, request); }else{ return preUpdate(model,map.get("entityID").toString(), request); } } @RequestMapping("/preAdd") public String preAdd(Model model,HttpServletRequest request) throws NoAuthorizedFieldException{ List<BusinessField> fields = partyMemberServiceImpl_AJ1.preAddInfo(); model.addAttribute("fields",fields); return new GoTo(this).sendPage("partyMemberForm_" + infoType + ".ftl"); } @RequestMapping("/addInfo") @ModuleOperating(name="信息添加",type=OperatingType.Save) public String addInfo(Model model,HttpServletRequest request) throws NoAuthorizedFieldException{ Map<String,Object> paramsMap = buildAttachmentParamsMap(request); partyMemberServiceImpl_AJ1.addInfo(paramsMap); return new GoTo(this).sendForward("findInfoList"); } @RequestMapping("/updateInfo") @ModuleOperating(name="信息修改",type=OperatingType.Update) public String updateInfo(Model model,String entityID,HttpServletRequest request) throws NoAuthorizedFieldException{ Map<String,Object> paramsMap = buildAttachmentParamsMap(request); partyMemberServiceImpl_AJ1.updateInfo(entityID, paramsMap); return new GoTo(this).sendForward("findInfoList"); } @RequestMapping("/preUpdate") @ModuleOperating(name="预修改",type=OperatingType.Find) public String preUpdate(Model model,String id,HttpServletRequest request) throws NoAuthorizedFieldException{ List<BusinessField> businessFieldList = partyMemberServiceImpl_AJ1.findInfoById(id); model.addAttribute("fields",businessFieldList); model.addAttribute("entityID",id); return new GoTo(this).sendPage("partyMemberForm_" + infoType + ".ftl"); } @RequestMapping("/checkRepeat") @ModuleOperating(name="信息查询",type=OperatingType.Delete) public JsonObject checkRepeat(String AA_ID,String searchDate,String id)throws NoAuthorizedFieldException{ // PartyMemberQuery partyMemberQuery=new PartyMemberQuery(); partyMemberQuery.setAA_ID(AA_ID); partyMemberQuery.setSearchDate(searchDate); List<Map<String, Object>> resultList = partyMemberServiceImpl_AJ1.findInfoList(partyMemberQuery, null); JsonObject result = new JsonObject(); if(id!=null&&!id.equals("")&&resultList.size()==1){ for(Map<String, Object> map:resultList){ if(map.get("entityID").equals(id)){ return result; } } } if(resultList.size()>0){ result.setSuccess(false); } return result; } @RequestMapping("/deleteInfo") @ModuleOperating(name="信息删除",type=OperatingType.Delete) public JsonObject deleteBusinessTable(String[] ids,String AA_ID)throws NoAuthorizedFieldException{ JsonObject result = new JsonObject(); if(ids.length>0){ partyMemberServiceImpl_AJ1.deleteInfo(ids,AA_ID); result.setSuccess(true); } return result; } @SuppressWarnings("unchecked") @RequestMapping("/findInfoList") @ModuleOperating(name="信息查询",type=OperatingType.FindList) public String findInfoList(@ModelQuery("query") PartyMemberQuery partyMemberQuery,Boolean readonly,String AA_ID,String id,Model model,HttpServletRequest request) throws NoAuthorizedFieldException{ model.addAttribute("AA_ID", AA_ID); readonly=readonly==null?false:readonly; model.addAttribute("readonly", readonly); if(id!=null&&!"".equals(id)){ preUpdate(model, id, request); }else { preAdd(model, request); } //审核状态 Map<String,Object> map=partyMemberServiceImpl_AJ.findInfoByAAID(AA_ID); String ajid=null; if(map!=null&&map.get("entityID")!=null){ ajid=map.get("entityID").toString(); } model.addAttribute("checkInfoState", CheckUtil.getPassState(ajid, CheckInfo.SH_TYPE_PM_AJ)); List<Map<String, Object>> resultList = partyMemberServiceImpl_AJ1.findInfoList(partyMemberQuery, request.getParameterMap()); partyMemberQuery.setResultList(resultList); return new GoTo(this).sendPage("partyMemberList_" + infoType + ".ftl"); } @RequestMapping("/findInfoDetail") @ModuleOperating(name="信息查看",type=OperatingType.Find) public String findInfoDetail(Model model,HttpServletRequest request) throws NoAuthorizedFieldException{ String DAID = request.getParameter("DA_ID"); List<BusinessField> businessFieldList = partyMemberServiceImpl_AJ1.findInfoById(DAID); model.addAttribute("fields", businessFieldList); model.addAttribute("readOnly","readOnly"); return new GoTo(this).sendPage("partyMemberDetail_" + infoType + ".ftl"); } }
package com.e6soft.bpm.vo.grid; import com.alibaba.fastjson.annotation.JSONType; import com.e6soft.core.views.FieldLabel; @JSONType(orders = {"id","flowbaseId","businessFormId","requestName","requestCode","operator"}) public class FlowbaseFormGrid { @FieldLabel("id") private String id; @FieldLabel("flowbaseId") private String flowbaseId; @FieldLabel("businessFormId") private String businessFormId; @FieldLabel("请求名称") private String requestName; @FieldLabel("请求代码") private String requestCode; @FieldLabel("操作") private String operator; public void setId (String id){ this.id = id; } public void setFlowbaseId (String flowbaseId){ this.flowbaseId = flowbaseId; } public void setBusinessFormId (String businessFormId){ this.businessFormId = businessFormId; } public void setRequestName (String requestName){ this.requestName = requestName; } public String getId (){ return this.id; } public String getFlowbaseId (){ return this.flowbaseId; } public String getBusinessFormId (){ return this.businessFormId; } public String getRequestName (){ return this.requestName; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public String getRequestCode() { return requestCode; } public void setRequestCode(String requestCode) { this.requestCode = requestCode; } }
package com.geekparkhub.hadoop.compress; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionOutputStream; import org.apache.hadoop.util.ReflectionUtils; import java.io.*; /** * Geek International Park | 极客国际公园 * GeekParkHub | 极客实验室 * Website | https://www.geekparkhub.com/ * Description | Open开放 · Creation创想 | OpenSource开放成就梦想 GeekParkHub共建前所未见 * HackerParkHub | 黑客公园枢纽 * Website | https://www.hackerparkhub.com/ * Description | 以无所畏惧的探索精神 开创未知技术与对技术的崇拜 * GeekDeveloper : JEEP-711 * * @author system * <p> * TestCompress * <p> */ public class TestCompress { public static void main(String[] args) throws IOException, ClassNotFoundException { /** * Get the specified compressed file and set it to compress using B Zip 2 Codec format. * 获取指定压缩文件,并设置使用BZip2Codec格式进行压缩 */ compress("/Volumes/GEEK-SYSTEM/Technical_Framework/Hadoop/projects/mapreduce/src/main/resources/input_combine_textInput_format/b.txt" , "org.apache.hadoop.io.compress.BZip2Codec"); } /** * Compression method * 压缩方法 * * @param fileName * @param method */ private static void compress(String fileName, String method) throws IOException, ClassNotFoundException { /** * 获取输入流 */ FileInputStream fis = new FileInputStream(new File(fileName)); /** * Pass the method parameter to the compression mode tool class through the reflection mechanism, * and set the encoding mode to obtain the compression extension. * 通过反射机制,将method参数传递给压缩方式工具类,并设置编码方式,获取压缩扩展名 */ Class classCodec = Class.forName(method); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(classCodec, new Configuration()); /** * Get the output stream * 获取输出流 */ FileOutputStream fos = new FileOutputStream(fileName + codec.getDefaultExtension()); /** * Set the obtained normal output stream to the compressed output stream * 将获取到的普通输出流,设置为压缩输出流 */ CompressionOutputStream cos = codec.createOutputStream(fos); /** * Copy between streams * 流之间对拷 */ IOUtils.copyBytes(fis, cos, 1024 * 1024, false); /** * Close resource * 关闭资源 */ IOUtils.closeStream(cos); IOUtils.closeStream(fos); IOUtils.closeStream(fis); } }
package com.elvarg.net.packet; import java.util.List; import com.elvarg.GameConstants; import com.elvarg.world.entity.Entity; import com.elvarg.world.entity.impl.object.GameObject; import com.elvarg.world.entity.impl.player.Player; import com.elvarg.world.model.Animation; import com.elvarg.world.model.EffectTimer; import com.elvarg.world.model.Graphic; import com.elvarg.world.model.Item; import com.elvarg.world.model.PlayerInteractingOption; import com.elvarg.world.model.PlayerRights; import com.elvarg.world.model.PlayerStatus; import com.elvarg.world.model.Position; import com.elvarg.world.model.Skill; import com.elvarg.world.model.container.ItemContainer; import com.elvarg.world.model.container.impl.Bank; /** * This class manages making the packets that will be sent (when called upon) onto * the associated player's client. * * @author relex lawl & Gabbe */ public class PacketSender { /** * Sends information about the player to the client. * @return The PacketSender instance. */ public PacketSender sendDetails() { PacketBuilder out = new PacketBuilder(249); out.put(1, ValueType.A); out.putShort(player.getIndex()); player.getSession().write(out); return this; } /** * Sends the map region a player is located in and also * sets the player's first step position of said region as their * {@code lastKnownRegion}. * @return The PacketSender instance. */ public PacketSender sendMapRegion() { player.setRegionChange(true).setAllowRegionChangePacket(true); player.setLastKnownRegion(player.getPosition().copy()); PacketBuilder out = new PacketBuilder(73); out.putShort(player.getPosition().getRegionX() + 6, ValueType.A); out.putShort(player.getPosition().getRegionY() + 6); player.getSession().write(out); return this; } /** * Sends the logout packet for the player. * @return The PacketSender instance. */ public PacketSender sendLogout() { PacketBuilder out = new PacketBuilder(109); player.getSession().write(out); return this; } /** * Requests a reload of the region */ public PacketSender sendRegionReload() { PacketBuilder out = new PacketBuilder(89); player.getSession().write(out); return this; } /** * Sets the world's system update time, once timer is 0, everyone will be disconnected. * @param time The amount of seconds in which world will be updated in. * @return The PacketSender instance. */ public PacketSender sendSystemUpdate(int time) { PacketBuilder out = new PacketBuilder(114); out.putShort(time, ByteOrder.LITTLE); player.getSession().write(out); return this; } public PacketSender sendSound(int soundId, int volume, int delay) { PacketBuilder out = new PacketBuilder(175); out.putShort(soundId, ValueType.A, ByteOrder.LITTLE).put(volume).putShort(delay); player.getSession().write(out); return this; } public PacketSender sendSong(int id) { PacketBuilder out = new PacketBuilder(74); out.putShort(id, ByteOrder.LITTLE); player.getSession().write(out); return this; } public PacketSender sendAutocastId(int id) { PacketBuilder out = new PacketBuilder(38); out.putShort(id); player.getSession().write(out); return this; } public PacketSender sendEnableNoclip() { PacketBuilder out = new PacketBuilder(250); player.getSession().write(out); return this; } public PacketSender sendURL(String url) { PacketBuilder out = new PacketBuilder(251); out.putString(url); player.getSession().write(out); return this; } /** * Sends a game message to a player in the server. * @param message The message they will receive in chat box. * @return The PacketSender instance. */ public PacketSender sendMessage(String message) { PacketBuilder out = new PacketBuilder(253); out.putString(message); player.getSession().write(out); return this; } /** * Sends a clan message to a player in the server. * @param message The message they will receive in chat box. * @return The PacketSender instance. */ public PacketSender sendClanMessage(String message) { PacketBuilder out = new PacketBuilder(252); out.putString(message); player.getSession().write(out); return this; } /** * Sends skill information onto the client, to calculate things such as * constitution, prayer and summoning orb and other configurations. * @param skill The skill being sent. * @return The PacketSender instance. */ public PacketSender sendSkill(Skill skill) { PacketBuilder out = new PacketBuilder(134); out.put(skill.ordinal()); out.putInt(player.getSkillManager().getCurrentLevel(skill)); out.putInt(player.getSkillManager().getMaxLevel(skill)); out.putInt(player.getSkillManager().getExperience(skill)); player.getSession().write(out); return this; } /** * Sends a configuration button's state. * @param configId The id of the configuration button. * @param state The state to set it to. * @return The PacketSender instance. */ public PacketSender sendConfig(int id, int state) { PacketBuilder out = new PacketBuilder(36); out.putShort(id, ByteOrder.LITTLE); out.put(state); player.getSession().write(out); return this; } /** * Sends a interface child's toggle. * @param id The id of the child. * @param state The state to set it to. * @return The PacketSender instance. */ public PacketSender sendToggle(int id, int state) { PacketBuilder out = new PacketBuilder(87); out.putShort(id, ByteOrder.LITTLE); out.putInt(state, ByteOrder.MIDDLE); player.getSession().write(out); return this; } /** * Sends the state in which the player has their chat options, such as public, private, friends only. * @param publicChat The state of their public chat. * @param privateChat The state of their private chat. * @param tradeChat The state of their trade chat. * @return The PacketSender instance. */ public PacketSender sendChatOptions(int publicChat, int privateChat, int tradeChat) { PacketBuilder out = new PacketBuilder(206); out.put(publicChat).put(privateChat).put(tradeChat); player.getSession().write(out); return this; } public PacketSender sendRunEnergy(int energy) { PacketBuilder out = new PacketBuilder(110); out.put(energy); player.getSession().write(out); return this; } public PacketSender sendQuickPrayersState(boolean activated) { PacketBuilder out = new PacketBuilder(111); out.put(activated ? 1 : 0); player.getSession().write(out); return this; } public PacketSender updateSpecialAttackOrb() { PacketBuilder out = new PacketBuilder(137); out.put(player.getSpecialPercentage()); player.getSession().write(out); return this; } public PacketSender sendDungeoneeringTabIcon(boolean show) { PacketBuilder out = new PacketBuilder(103); out.put(show ? 1 : 0); player.getSession().write(out); return this; } public PacketSender sendHeight() { player.getSession().write(new PacketBuilder(86).put(player.getPosition().getZ())); return this; } public PacketSender sendIronmanMode(int ironmanMode) { PacketBuilder out = new PacketBuilder(112); out.put(ironmanMode); player.getSession().write(out); return this; } public PacketSender sendShowClanChatOptions(boolean show) { PacketBuilder out = new PacketBuilder(115); out.put(show ? 1 : 0); //0 = no right click options player.getSession().write(out); return this; } public PacketSender sendRunStatus() { PacketBuilder out = new PacketBuilder(113); out.put(player.isRunning() ? 1 : 0); player.getSession().write(out); return this; } public PacketSender sendWeight(int weight) { PacketBuilder out = new PacketBuilder(240); out.putShort(weight); player.getSession().write(out); return this; } public PacketSender commandFrame(int i) { PacketBuilder out = new PacketBuilder(28); out.put(i); player.getSession().write(out); return this; } public PacketSender sendInterface(int id) { PacketBuilder out = new PacketBuilder(97); out.putShort(id); player.getSession().write(out); player.setInterfaceId(id); return this; } public PacketSender sendWalkableInterface(int interfaceId) { player.setWalkableInterfaceId(interfaceId); PacketBuilder out = new PacketBuilder(208); out.putInt(interfaceId); player.getSession().write(out); return this; } public PacketSender sendInterfaceDisplayState(int interfaceId, boolean hide) { PacketBuilder out = new PacketBuilder(171); out.put(hide ? 1 : 0); out.putShort(interfaceId); player.getSession().write(out); return this; } public PacketSender sendPlayerHeadOnInterface(int id) { PacketBuilder out = new PacketBuilder(185); out.putShort(id, ValueType.A, ByteOrder.LITTLE); player.getSession().write(out); return this; } public PacketSender sendNpcHeadOnInterface(int id, int interfaceId) { PacketBuilder out = new PacketBuilder(75); out.putShort(id, ValueType.A, ByteOrder.LITTLE); out.putShort(interfaceId, ValueType.A, ByteOrder.LITTLE); player.getSession().write(out); return this; } public PacketSender sendEnterAmountPrompt(String title) { PacketBuilder out = new PacketBuilder(27); out.putString(title); player.getSession().write(out); return this; } public PacketSender sendEnterInputPrompt(String title) { PacketBuilder out = new PacketBuilder(187); out.putString(title); player.getSession().write(out); return this; } public PacketSender sendInterfaceReset() { PacketBuilder out = new PacketBuilder(68); player.getSession().write(out); return this; } /** * Closes a player's client. */ public PacketSender sendExit() { PacketBuilder out = new PacketBuilder(62); player.getSession().write(out); return this; } public PacketSender sendInterfaceComponentMoval(int x, int y, int id) { PacketBuilder out = new PacketBuilder(70); out.putShort(x); out.putShort(y); out.putShort(id, ByteOrder.LITTLE); player.getSession().write(out); return this; } /*public PacketSender sendBlinkingHint(String title, String information, int x, int y, int speed, int pause, int type, final int time) { player.getSession().queueMessage(new PacketBuilder(179).putString(title).putString(information).putShort(x).putShort(y).put(speed).put(pause).put(type)); if(type > 0) { TaskManager.submit(new Task(time, player, false) { @Override public void execute() { player.getPacketSender().sendBlinkingHint("", "", 0, 0, 0, 0, -1, 0); stop(); } }); } return this; } */ public PacketSender sendInterfaceAnimation(int interfaceId, Animation animation) { PacketBuilder out = new PacketBuilder(200); out.putShort(interfaceId); out.putShort(animation.getId()); player.getSession().write(out); return this; } public PacketSender sendInterfaceModel(int interfaceId, int itemId, int zoom) { PacketBuilder out = new PacketBuilder(246); out.putShort(interfaceId, ByteOrder.LITTLE); out.putShort(zoom).putShort(itemId); player.getSession().write(out); return this; } public PacketSender sendTabInterface(int tabId, int interfaceId) { PacketBuilder out = new PacketBuilder(71); out.putShort(interfaceId); out.put(tabId, ValueType.A); player.getSession().write(out); return this; } public PacketSender sendTabs() { for(int i = 0; i < GameConstants.TAB_INTERFACES.length; i++) { int tab = GameConstants.TAB_INTERFACES[i][0]; int interface_ = GameConstants.TAB_INTERFACES[i][1]; if(tab == 6) { interface_ = player.getSpellbook().getInterfaceId(); } sendTabInterface(tab, interface_); } return this; } public PacketSender sendTab(int id) { PacketBuilder out = new PacketBuilder(106); out.put(id, ValueType.C); player.getSession().write(out); return this; } public PacketSender sendFlashingSidebar(int id) { PacketBuilder out = new PacketBuilder(24); out.put(id, ValueType.S); player.getSession().write(out); return this; } public PacketSender sendChatboxInterface(int id) { PacketBuilder out = new PacketBuilder(164); out.putShort(id, ByteOrder.LITTLE); player.getSession().write(out); return this; } public PacketSender sendMapState(int state) { PacketBuilder out = new PacketBuilder(99); out.put(state); player.getSession().write(out); return this; } public PacketSender sendCameraAngle(int x, int y, int level, int speed, int angle) { PacketBuilder out = new PacketBuilder(177); out.put(x / 64); out.put(y / 64); out.putShort(level); out.put(speed); out.put(angle); player.getSession().write(out); return this; } public PacketSender sendCameraShake(int verticalAmount, int verticalSpeed, int horizontalAmount, int horizontalSpeed) { PacketBuilder out = new PacketBuilder(35); out.put(verticalAmount); out.put(verticalSpeed); out.put(horizontalAmount); out.put(horizontalSpeed); player.getSession().write(out); return this; } public PacketSender sendCameraSpin(int x, int y, int z, int speed, int angle) { PacketBuilder out = new PacketBuilder(166); out.put(x / 64); out.put(y / 64); out.putShort(z); out.put(speed); out.put(angle); player.getSession().write(out); return this; } public PacketSender sendGrandExchangeUpdate(String s) { PacketBuilder out = new PacketBuilder(244); out.putString(s); player.getSession().write(out); return this; } public PacketSender sendCameraNeutrality() { PacketBuilder out = new PacketBuilder(107); player.getSession().write(out); return this; } public PacketSender sendInterfaceRemoval() { if(player.getStatus() == PlayerStatus.BANKING) { if(player.isSearchingBank()) { Bank.exitSearch(player, false); } } else if(player.getStatus() == PlayerStatus.PRICE_CHECKING) { player.getPriceChecker().withdrawAll(); } else if(player.getStatus() == PlayerStatus.TRADING) { player.getTrading().closeTrade(); } else if(player.getStatus() == PlayerStatus.DUELING) { if(!player.getDueling().inDuel()) { player.getDueling().closeDuel(); } } player.setStatus(PlayerStatus.NONE); player.setEnterSyntax(null); player.setDialogue(null); player.setDialogueOptions(null); player.setDestroyItem(-1); player.setInterfaceId(-1); player.setSearchingBank(false); player.getAppearance().setCanChangeAppearance(false); player.getSession().write(new PacketBuilder(219)); return this; } public PacketSender sendInterfaceScrollReset(int interfaceId) { PacketBuilder out = new PacketBuilder(9); out.putInt(interfaceId); player.getSession().write(out); return this; } public PacketSender sendScrollbarHeight(int interfaceId, int scrollMax) { PacketBuilder out = new PacketBuilder(10); out.putInt(interfaceId); out.putShort(scrollMax); player.getSession().write(out); return this; } public PacketSender sendInterfaceSet(int interfaceId, int sidebarInterfaceId) { PacketBuilder out = new PacketBuilder(248); out.putShort(interfaceId, ValueType.A); out.putShort(sidebarInterfaceId); player.getSession().write(out); player.setInterfaceId(interfaceId); return this; } public PacketSender sendItemContainer(ItemContainer container, int interfaceId) { PacketBuilder out = new PacketBuilder(53); out.putInt(interfaceId); out.putShort(container.capacity()); for (Item item: container.getItems()) { if(item == null || item.getAmount() <= 0) { out.putInt(0); continue; } out.putInt(item.getAmount()); out.putShort(item.getId() + 1); } player.getSession().write(out); return this; } public PacketSender sendCurrentBankTab(int current_tab) { PacketBuilder out = new PacketBuilder(55); out.put(current_tab); player.getSession().write(out); return this; } public PacketSender sendEffectTimer(int delay, EffectTimer e) { PacketBuilder out = new PacketBuilder(54); out.putShort(delay); out.putShort(e.getClientSprite()); player.getSession().write(out); return this; } public PacketSender sendInterfaceItems(int interfaceId, List<Item> items) { PacketBuilder out = new PacketBuilder(53); out.putInt(interfaceId); out.putShort(items.size()); for (Item item: items) { if(item == null) { out.putInt(0); out.putShort(-1); continue; } out.putInt(item.getAmount()); out.putShort(item.getId() + 1); } player.getSession().write(out); return this; } public PacketSender sendItemOnInterface(int interfaceId, int item, int amount) { PacketBuilder out = new PacketBuilder(53); out.putInt(interfaceId); out.putShort(1); out.putInt(amount); out.putShort(item + 1); player.getSession().write(out); return this; } public PacketSender sendItemOnInterface(int frame, int item, int slot, int amount) { PacketBuilder out = new PacketBuilder(34); out.putShort(frame); out.put(slot); out.putInt(amount); out.putShort(item + 1); player.getSession().write(out); return this; } public PacketSender clearItemOnInterface(int frame) { PacketBuilder out = new PacketBuilder(72); out.putShort(frame); player.getSession().write(out); return this; } public PacketSender sendSmithingData(int id, int slot, int column, int amount) { PacketBuilder out = new PacketBuilder(34); out.putShort(column); out.put(4); out.putInt(slot); out.putShort(id+1); out.put(amount); player.getSession().write(out); return this; } /*public PacketSender sendConstructionInterfaceItems(ArrayList<Furniture> items) { PacketBuilder builder = new PacketBuilder(53); builder.writeShort(38274); builder.writeShort(items.size()); for (int i = 0; i < items.size(); i++) { builder.writeByte(1); builder.writeLEShortA(items.get(i).getItemId() + 1); } player.write(builder.toPacket()); return this; }*/ public PacketSender sendInteractionOption(String option, int slot, boolean top) { PacketBuilder out = new PacketBuilder(104); out.put(slot, ValueType.C); out.put(top ? 1 : 0, ValueType.A); out.putString(option); player.getSession().write(out); PlayerInteractingOption interactingOption = PlayerInteractingOption.forName(option); if(option != null) player.setPlayerInteractingOption(interactingOption); return this; } public PacketSender sendString(int id, String string) { if(!player.getFrameUpdater().shouldUpdate(string, id)) { return this; } PacketBuilder out = new PacketBuilder(126); out.putString(string); out.putInt(id); player.getSession().write(out); return this; } /** * Sends the players rights ordinal to the client. * @return The packetsender instance. */ public PacketSender sendRights() { PacketBuilder out = new PacketBuilder(127); out.put(player.getRights().ordinal()); player.getSession().write(out); return this; } /** * Sends a hint to specified position. * @param position The position to create the hint. * @param tilePosition The position on the square (middle = 2; west = 3; east = 4; south = 5; north = 6) * @return The Packet Sender instance. */ public PacketSender sendPositionalHint(Position position, int tilePosition) { PacketBuilder out = new PacketBuilder(254); out.put(tilePosition); out.putShort(position.getX()); out.putShort(position.getY()); out.put(position.getZ()); player.getSession().write(out); return this; } /** * Sends a hint above an entity's head. * @param entity The target entity to draw hint for. * @return The PacketSender instance. */ public PacketSender sendEntityHint(Entity entity) { int type = entity instanceof Player ? 10 : 1; PacketBuilder out = new PacketBuilder(254); out.put(type); out.putShort(entity.getIndex()); out.putInt(0, ByteOrder.TRIPLE_INT); player.getSession().write(out); return this; } /** * Sends a hint removal above an entity's head. * @param playerHintRemoval Remove hint from a player or an NPC? * @return The PacketSender instance. */ public PacketSender sendEntityHintRemoval(boolean playerHintRemoval) { int type = playerHintRemoval ? 10 : 1; PacketBuilder out = new PacketBuilder(254); out.put(type).putShort(-1); out.putInt(0, ByteOrder.TRIPLE_INT); player.getSession().write(out); return this; } public PacketSender sendMultiIcon(int value) { PacketBuilder out = new PacketBuilder(61); out.put(value); player.getSession().write(out); player.setMultiIcon(value); return this; } public PacketSender sendPrivateMessage(long name, PlayerRights rights, String message) { PacketBuilder out = new PacketBuilder(196); out.putLong(name); out.putInt(player.getRelations().getPrivateMessageId()); out.put(rights.ordinal()); out.putString(message); player.getSession().write(out); return this; } public PacketSender sendFriendStatus(int status) { PacketBuilder out = new PacketBuilder(221); out.put(status); player.getSession().write(out); return this; } public PacketSender sendFriend(long name, int world) { world = world != 0 ? world + 9 : world; PacketBuilder out = new PacketBuilder(50); out.putLong(name); out.put(world); player.getSession().write(out); return this; } public PacketSender sendDeleteFriend(long name) { PacketBuilder out = new PacketBuilder(51); out.putLong(name); player.getSession().write(out); return this; } public PacketSender sendAddIgnore(long name) { PacketBuilder out = new PacketBuilder(214); out.putLong(name); player.getSession().write(out); return this; } public PacketSender sendDeleteIgnore(long name) { PacketBuilder out = new PacketBuilder(215); out.putLong(name); player.getSession().write(out); return this; } public PacketSender sendTotalExp(long exp) { PacketBuilder out = new PacketBuilder(108); out.putLong(exp); player.getSession().write(out); return this; } public PacketSender sendAnimationReset() { PacketBuilder out = new PacketBuilder(1); player.getSession().write(out); return this; } public PacketSender sendGraphic(Graphic graphic, Position position) { sendPosition(position); PacketBuilder out = new PacketBuilder(4); out.put(0); out.putShort(graphic.getId()); out.put(position.getZ()); out.putShort(graphic.getDelay()); player.getSession().write(out); return this; } public PacketSender sendGlobalGraphic(Graphic graphic, Position position) { sendGraphic(graphic, position); for(Player p : player.getLocalPlayers()) { if(p.getPosition().distanceToPoint(player.getPosition().getX(), player.getPosition().getY()) > 20) continue; p.getPacketSender().sendGraphic(graphic, position); } return this; } public PacketSender sendObject(GameObject object) { sendPosition(object.getPosition()); PacketBuilder out = new PacketBuilder(151); out.put(object.getPosition().getZ(), ValueType.A); out.putShort(object.getId(), ByteOrder.LITTLE); out.put((byte) ((object.getType() << 2) + (object.getFace() & 3)), ValueType.S); player.getSession().write(out); return this; } public PacketSender sendObjectRemoval(GameObject object) { sendPosition(object.getPosition()); PacketBuilder out = new PacketBuilder(101); out.put((object.getType() << 2) + (object.getFace() & 3), ValueType.C); out.put(object.getPosition().getZ()); player.getSession().write(out); return this; } public PacketSender sendObjectAnimation(GameObject object, Animation anim) { sendPosition(object.getPosition()); PacketBuilder out = new PacketBuilder(160); out.put(0, ValueType.S); out.put((object.getType() << 2) + (object.getFace() & 3), ValueType.S); out.putShort(anim.getId(), ValueType.A); player.getSession().write(out); return this; } public PacketSender sendGroundItemAmount(Position position, Item item, int amount) { sendPosition(position); PacketBuilder out = new PacketBuilder(84); out.put(0); out.putShort(item.getId()).putShort(item.getAmount()).putShort(amount); player.getSession().write(out); return this; } public PacketSender createGroundItem(int itemID, int itemX, int itemY, int itemAmount) { sendPosition(new Position(itemX, itemY)); PacketBuilder out = new PacketBuilder(44); out.putShort(itemID, ValueType.A, ByteOrder.LITTLE); out.putShort(itemAmount).put(0); player.getSession().write(out); return this; } public PacketSender createGroundItem(int itemID, Position position, int itemAmount) { sendPosition(position); PacketBuilder out = new PacketBuilder(44); out.putShort(itemID, ValueType.A, ByteOrder.LITTLE); out.putShort(itemAmount).put(0); player.getSession().write(out); return this; } public PacketSender removeGroundItem(int itemID, int itemX, int itemY, int Amount) { sendPosition(new Position(itemX, itemY)); PacketBuilder out = new PacketBuilder(156); out.put(0, ValueType.A); out.putShort(itemID); player.getSession().write(out); return this; } public PacketSender sendPosition(final Position position) { final Position other = player.getLastKnownRegion(); PacketBuilder out = new PacketBuilder(85); out.put(position.getY() - 8 * other.getRegionY(), ValueType.C); out.put(position.getX() - 8 * other.getRegionX(), ValueType.C); player.getSession().write(out); return this; } public PacketSender sendConsoleMessage(String message) { PacketBuilder out = new PacketBuilder(123); out.putString(message); player.getSession().write(out); return this; } public PacketSender sendInterfaceSpriteChange(int childId, int firstSprite, int secondSprite) { // player.write(new PacketBuilder(140).writeShort(childId).writeByte((firstSprite << 0) + (secondSprite & 0x0)).toPacket()); return this; } public int getRegionOffset(Position position) { int x = position.getX() - (position.getRegionX() << 4); int y = position.getY() - (position.getRegionY() & 0x7); int offset = ((x & 0x7)) << 4 + (y & 0x7); return offset; } public PacketSender(Player player) { this.player = player; } private Player player; public PacketSender sendProjectile(Position position, Position offset, int angle, int speed, int gfxMoving, int startHeight, int endHeight, int lockon, int time) { sendPosition(position); PacketBuilder out = new PacketBuilder(117); out.put(angle); out.put(offset.getY()); out.put(offset.getX()); out.putShort(lockon); out.putShort(gfxMoving); out.put(startHeight); out.put(endHeight); out.putShort(time); out.putShort(speed); out.put(16); out.put(64); player.getSession().write(out); return this; } /* public PacketSender sendCombatBoxData(Character character) { PacketBuilder out = new PacketBuilder(125); out.putShort(character.getIndex()); out.put(character.isPlayer() ? 0 : 1); if(character.isPlayer()) { player.getSession().queueMessage(out); } else { NPC npc = (NPC) character; boolean sendList = npc.getDefaultConstitution() >= 2500 && Location.inMulti(npc); out.put(sendList ? 1 : 0); if(sendList) { List<DamageDealer> list = npc.fetchNewDamageMap() ? npc.getCombatBuilder().getTopKillers(npc) : npc.getDamageDealerMap(); if(npc.fetchNewDamageMap()) { npc.setDamageDealerMap(list); npc.setFetchNewDamageMap(false); } out.put(list.size()); for(int i = 0; i < list.size(); i++) { DamageDealer dd = list.get(i); out.putString(dd.getPlayer().getUsername()); out.putShort(dd.getDamage()); } } player.getSession().queueMessage(out); } return this; }*/ public PacketSender sendHideCombatBox() { player.getSession().write(new PacketBuilder(128)); return this; } public void sendObject_cons(int objectX, int objectY, int objectId, int face, int objectType, int height) { sendPosition(new Position(objectX, objectY)); PacketBuilder bldr = new PacketBuilder(152); if (objectId != -1) // removing player.getSession().write(bldr.put(0, ValueType.S).putShort(objectId, ByteOrder.LITTLE).put((objectType << 2) + (face & 3), ValueType.S).put(height)); if (objectId == -1 || objectId == 0 || objectId == 6951) { //CustomObjects.spawnObject(player, new GameObject(objectId, new Position(objectX, objectY, height))); } } /*public PacketSender constructMapRegion(Palette palette) { PacketBuilder bldr = new PacketBuilder(241); if(palette != null) { bldr.putString("palette"); //Inits map construction sequence bldr.putString(""+(player.getPosition().getRegionY() + 6)+""); bldr.putString(""+(player.getPosition().getRegionX() + 6)+""); for (int z = 0; z < 4; z++) { for (int x = 0; x < 13; x++) { for (int y = 0; y < 13; y++) { PaletteTile tile = palette.getTile(x, y, z); boolean b = false; if (x < 2 || x > 10 || y < 2 || y > 10) b = true; int toWrite = !b && tile != null ? 5 : 0; bldr.putString(""+toWrite+""); if(toWrite == 5) { int val = tile.getX() << 14 | tile.getY() << 3 | tile.getZ() << 24 | tile.getRotation() << 1; bldr.putString(""+val+""); } } } } } else { bldr.putString("null"); //Resets map construction sequence } player.getSession().queueMessage(bldr); return this; } public PacketSender constructMapRegion(Palette palette) { PacketBuilder bldr = new PacketBuilder(241); bldr.putShort(player.getPosition().getRegionY() + 6, ValueType.A); for (int z = 0; z < 4; z++) { for (int x = 0; x < 13; x++) { for (int y = 0; y < 13; y++) { PaletteTile tile = palette.getTile(x, y, z); boolean b = false; if (x < 2 || x > 10 || y < 2 || y > 10) b = true; int toWrite = !b && tile != null ? 5 : 0; bldr.put(toWrite); if(toWrite == 5) { int val = tile.getX() << 14 | tile.getY() << 3 | tile.getZ() << 24 | tile.getRotation() << 1; bldr.putString(""+val+""); } } } } bldr.putShort(player.getPosition().getRegionX() + 6); player.getSession().queueMessage(bldr); return this; } public PacketSender sendConstructionInterfaceItems(ArrayList<Furniture> items) { PacketBuilder builder = new PacketBuilder(53); builder.putShort(38274); builder.putShort(items.size()); for (int i = 0; i < items.size(); i++) { builder.put(1); builder.putShort(items.get(i).getItemId() + 1, ValueType.A, ByteOrder.LITTLE); } player.getSession().queueMessage(builder); return this; }*/ public PacketSender sendObjectsRemoval(int chunkX, int chunkY, int height) { player.getSession().write(new PacketBuilder(153).put(chunkX).put(chunkY).put(height)); return this; } }
package digital_goods.mobileTopup.page_object; import com.codeborne.selenide.SelenideElement; import global.helpers.AbstractPage; import global.helpers.NameOfElement; import org.openqa.selenium.support.FindBy; public class LoginMobilePage extends AbstractPage { @NameOfElement("Email") @FindBy(xpath = "//*[@id=\"container\"]/div/div/div/div/div[1]/div/div[1]/input") public SelenideElement emailInput; @NameOfElement("Password") @FindBy(xpath = "//*[@id=\"container\"]/div/div/div/div/div[1]/div/div[2]/input") public SelenideElement passwordInput; @NameOfElement("Login button") @FindBy(xpath = "//*[@id=\"container\"]/div/div/div/div/div[2]/button") public SelenideElement loginButton; }
package org.jahia.modules.academy.services; import org.drools.core.spi.KnowledgeHelper; import org.jahia.services.content.JCRNodeWrapper; import org.jahia.services.content.rules.AddedNodeFact; import org.jahia.services.content.rules.ImageService; import org.jahia.services.image.Image; import org.jahia.services.image.JahiaImageService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.RepositoryException; import java.io.IOException; /** * Service allowing to addThumbnail for an image */ public class AcademyImageService { private static final Logger logger = LoggerFactory.getLogger(AcademyImageService.class); private JahiaImageService jahiaImageService; private ImageService rulesImageService; public void setJahiaImageService(JahiaImageService jahiaImageService) { this.jahiaImageService = jahiaImageService; } public void setRulesImageService(ImageService rulesImageService) { this.rulesImageService = rulesImageService; } /** * Will create a thumbnail for the giving image and the specified thumbnailSize. If the original image's width is * inferior than the thumbnail size, the created thumbnail will have the original width of the image : it will be * a duplicate * * @param imageNode the AddedNodeFact which called the rule * @param name the name to use for the new thumbnail * @param thumbnailSize the size to use for the new thumbnail * @param drools drools helper * @throws Exception */ public void addThumbnail(AddedNodeFact imageNode, String name, int thumbnailSize, KnowledgeHelper drools) throws Exception { String path = imageNode.getPath(); if (! path.endsWith(".svg")) { logger.debug("addThumbnail called for the name '" + name + "' and the size '" + thumbnailSize); Image image; try { JCRNodeWrapper theNode = imageNode.getNode(); if (theNode != null) { image = jahiaImageService.getImage(theNode); int originalWidth = jahiaImageService.getWidth(image); logger.debug("Original width : " + originalWidth); // We create the thumbnail with the expected size if (originalWidth >= thumbnailSize) { logger.info("Creating thumbnail image with size : " + thumbnailSize); rulesImageService.addThumbnail(imageNode, name, thumbnailSize, drools); } // We create a thumbnail with the original size : it is a duplicate of the original image else { logger.info("Creating thumbnail image with original size : " + originalWidth); rulesImageService.addThumbnail(imageNode, name, originalWidth, drools); } } else { logger.debug("Image node for '" + path + " is null"); } } catch (RepositoryException e) { logger.error(e.getMessage(),e); } catch (IOException e) { logger.error(e.getMessage(),e); } } } }
package c.sakshi.lab5; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button login; EditText username; EditText password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String usernameKey = "username"; SharedPreferences sharedPreferences = getSharedPreferences("c.sakshi.lab5", Context.MODE_PRIVATE); if(!sharedPreferences.getString(usernameKey, "").equals("")){ // if(sharedPreferences.getString("username", "").equals("hello")){ startActivity(new Intent(this, Main2Activity.class)); // } } else { setContentView(R.layout.activity_main); } login = (Button) findViewById(R.id.login); username = (EditText) findViewById(R.id.username); password = (EditText) findViewById(R.id.password); } public String getUserInfo(){ return username.getText().toString(); } public void login(View view){ String user = username.getText().toString(); String pass = password.getText().toString(); SharedPreferences sharedPreferences = getSharedPreferences("c.sakshi.lab5", Context.MODE_PRIVATE); sharedPreferences.edit().putString("username", user).apply(); Toast toast = Toast.makeText(this, user + " " + pass, Toast.LENGTH_SHORT); toast.show(); Intent intent = new Intent(this, Main2Activity.class); startActivity(intent); } }
package mnm.mods.tabbychat.api.listener.events; import net.minecraft.client.gui.GuiChat; /** * Event for when the chat screen gets initialized. */ public class ChatInitEvent extends Event { public final GuiChat chatScreen; public ChatInitEvent(GuiChat chat) { this.chatScreen = chat; } }
package GameState; public class GameStateManager { private GameState[] gameStates; private int currentState; public static final int CANTGAMESTATES= 5; public static final int MENUSTATE = 0; public static final int LEVELBASE = 1; public static final int LEVELARENA = 2; public static final int LEVEL1 = 3; public static final int ARENA2PLAYERS = 4; public GameStateManager() { gameStates = new GameState[CANTGAMESTATES]; currentState = MENUSTATE; loadState(currentState); } private void loadState(int state) { if(state == MENUSTATE){ gameStates[state] = new MenuState(this);} if(state == LEVELBASE){ gameStates[state] = new LevelBase(this);} if(state == LEVELARENA){ gameStates[state] = new LevelArcade(this);} if(state == LEVEL1){ gameStates[state] = new Level1(this);} if(state == ARENA2PLAYERS){ gameStates[state] = new Arena2players(this);} } private void unloadState(int state) { gameStates[state] = null; } public void setState(int state) { unloadState(currentState); currentState = state; loadState(currentState); //gameStates[currentState].init(); } public void update() { try { gameStates[currentState].update(); } catch(Exception e) {} } public void draw(java.awt.Graphics2D g) { try { gameStates[currentState].draw(g); } catch(Exception e) {} } public void keyPressed(int k) { gameStates[currentState].keyPressed(k); } public void keyReleased(int k) { gameStates[currentState].keyReleased(k); } }
package com.ehootu.park.dao; import com.ehootu.core.util.BaseDao; import com.ehootu.park.model.ChemicalsInspectionEntity; import org.springframework.stereotype.Repository; import java.util.List; /** * 易制毒化学品检验表 * * @author yinyujun * @email * @date 2017-09-26 16:27:31 */ @Repository public interface ChemicalsInspectionDao extends BaseDao<ChemicalsInspectionEntity> { List<ChemicalsInspectionEntity> select(String id); List<ChemicalsInspectionEntity> selectOne(String dizhibianma); List<ChemicalsInspectionEntity> selectAddress(String enterprise_address); }
package anton25360.github.com.cascade2; import android.app.Application; import android.app.NotificationChannel; import android.app.NotificationManager; import android.os.Build; public class Cascade extends Application { public static final String CHANNEL_1_ID = "Notification channel"; @Override public void onCreate() { super.onCreate(); createNotificationChannel(); } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //if Oreo or higher NotificationChannel channel = new NotificationChannel(CHANNEL_1_ID, "Cascade Reminders", NotificationManager.IMPORTANCE_DEFAULT); channel.setDescription("Handles notifications for Cascade Reminders"); NotificationManager manager = getSystemService(NotificationManager.class); assert manager != null; manager.createNotificationChannel(channel); } } }
package com.guru.mplayer.data_model; import android.net.Uri; import java.io.Serializable; /** * Created by Guru on 09-03-2018. */ public class MusicData implements Serializable { private String Id,Title,AlbumName,AlbumID; int Length; String TrackUri; public MusicData() { } public MusicData(String id, String title, int length, String albumName, String albumID) { Id = id; Title = title; AlbumName = albumName; Length = length; AlbumID = albumID; } public String getAlbumID() { return AlbumID; } public void setAlbumID(String albumID) { AlbumID = albumID; } public String getTrackUri() { return TrackUri; } public void setTrackUri(String trackUri) { TrackUri = trackUri; } // public MusicData(String string, String mCursorString, int anInt, String albumArt, String s) { // // } public String getId() { return Id; } public int getLength() { return Length; } public String getTitle() { return Title; } public String getAlbumName() { return AlbumName; } public void setId(String id) { Id = id; } public void setLength(int length) { Length = length; } public void setTitle(String title) { Title = title; } public void setAlbumName(String albumName) { AlbumName = albumName; } }
/* * 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 marier.business; /** * * @author linma */ public interface CustomerWriter { boolean addCustomer(Customer c); boolean deleteCustomer( Customer c); boolean updateCustomer(String email, Customer c); }
package com.redhat.manuela.sensor; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import com.redhat.manuela.model.Measure; import org.eclipse.microprofile.config.inject.ConfigProperty; @ApplicationScoped public class GpsSensor implements Sensor { @ConfigProperty(name = "sensor.gps.enabled") boolean enabled; @ConfigProperty(name = "sensor.gps.frequency") int frequency; @ConfigProperty(name = "sensor.gps.initialLatitude") double initialLatitude; @ConfigProperty(name = "sensor.gps.initialLongitude") double initialLongitude; @ConfigProperty(name = "sensor.gps.iterationLongitude") double iterationLatitude; @ConfigProperty(name = "sensor.gps.iterationLongitude") double iterationLongitude; @ConfigProperty(name = "sensor.gps.finalLatitude") double finalLatitude; @ConfigProperty(name = "sensor.gps.finalLongitude") double finalLongitude; private double currentLongitude; private double currentLatitude; private int count = 0; @PostConstruct @Override public void initAndReset() { currentLongitude = initialLongitude; currentLatitude = initialLatitude; } @Override public int getFrequency() { return frequency; } @Override public boolean isEnabled() { return enabled; } @Override public Measure calculateCurrentMeasure(Measure measure) { if(count > 0) { currentLatitude = currentLatitude + iterationLatitude; currentLongitude = currentLongitude + iterationLongitude; if(currentLatitude <= finalLatitude && currentLongitude <= finalLongitude) { initAndReset(); } } String payload = formatPayload(currentLatitude, currentLongitude); measure.setPayload(String.valueOf(payload)); ++count; return measure; } private String formatPayload(double latitude, double longitude) { StringBuilder sb = new StringBuilder(); sb.append(latitude); sb.append("|"); sb.append(longitude); return sb.toString(); } }
/* * 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 serverexile; import logica.impresion.Imprimir; /** * * @author dark */ public class ServerExile { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Imprimir i = new Imprimir(); i.main(); } }
package com.example.andreykochetkov.rk.Service; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.example.andreykochetkov.rk.NewsResultReceiver; public class ServiceHelper { private static final ServiceHelper instance = new ServiceHelper(); private NewsResultReceiver resultReceiver = new NewsResultReceiver(new Handler()); private ServiceHelper() { } public static ServiceHelper getInstance() { return instance; } public void requestNews(Context context) { Intent intent = new Intent(context, NewsService.class); intent.putExtra(NewsService.ACTION_NEW_NEWS, resultReceiver); context.startService(intent); } public void setCallback(Callback callback) { resultReceiver.setCallback(callback); } public interface Callback { void onNewsLoad(int code); } }
package com.openkm.vernum; import org.hibernate.Query; import org.hibernate.Session; import com.openkm.dao.bean.NodeDocument; import com.openkm.dao.bean.NodeDocumentVersion; public class LetterVersionAdapter implements VersionNumerationAdapter { public String getInitialVersionNumber() { return "A"; } public String getNextVersionNumber(Session paramSession, NodeDocument paramNodeDocument, NodeDocumentVersion paramNodeDocumentVersion, int paramInt) { String str1 = paramNodeDocumentVersion.getName(); String str2 = ""; String[] arrayOfString = new String[702]; Query localQuery = paramSession.createQuery("from NodeDocumentVersion ndv where ndv.parent=:parent and ndv.name=:name"); NodeDocumentVersion localNodeDocumentVersion = null; buildR(arrayOfString, 702); str2 = searchArr(arrayOfString, str1); do { localQuery.setString("parent", paramNodeDocument.getUuid()); localQuery.setString("name", str2); localNodeDocumentVersion = (NodeDocumentVersion)localQuery.setMaxResults(1).uniqueResult(); }while (localNodeDocumentVersion != null); return str2; } public void buildR(String[] paramArrayOfString, int paramInt) { char[] arrayOfChar1 = new char[1]; char[] arrayOfChar2 = new char[2]; for (int i = 0; i < paramInt; i++) { int k = i / 26; if (k == 0) { int j = i + 65; arrayOfChar1[0] = ((char)j); paramArrayOfString[i] = new String(arrayOfChar1); } else { arrayOfChar2[0] = ((char)(k + 64)); arrayOfChar2[1] = ((char)(i % 26 + 65)); paramArrayOfString[i] = new String(arrayOfChar2); } } } public String searchArr(String[] paramArrayOfString, String paramString) { String str = ""; for (int i = 0; i < paramArrayOfString.length; i++) { if (paramArrayOfString[i].equals(paramString)) str = paramArrayOfString[(++i)]; } return str; } }
package com.tencent.mm.plugin.readerapp.ui; import android.app.ProgressDialog; import com.tencent.mm.plugin.readerapp.c.g.a; import com.tencent.mm.plugin.readerapp.ui.b.1; class b$1$1 implements a { final /* synthetic */ ProgressDialog mnA; final /* synthetic */ 1 mnB; b$1$1(1 1, ProgressDialog progressDialog) { this.mnB = 1; this.mnA = progressDialog; } public final void bpQ() { this.mnA.dismiss(); } }
package com.fang.example.db.store; import com.fang.example.db.constant.Magic; /** * Created by andy on 6/26/16. */ public class RecordHeader { // offsets private static final short O_CURRENTSIZE = 0; // int currentSize private static final short O_AVAILABLESIZE = Magic.SZ_INT; // int availableSize public static final int SIZE = O_AVAILABLESIZE + Magic.SZ_INT; // my block and the position within the block private BlockIo block; private short pos; /** * Constructs a record header from the indicated data starting at * the indicated position. */ public RecordHeader(BlockIo block, short pos) { this.block = block; this.pos = pos; if (pos > (RecordFile.BLOCK_SIZE - SIZE)) throw new Error("Offset too large for record header (" + block.getBlockId() + ":" + pos + ")"); } /** Returns the current size */ public int getCurrentSize() { return block.readInt(pos + O_CURRENTSIZE); } /** Sets the current size */ public void setCurrentSize(int value) { block.writeInt(pos + O_CURRENTSIZE, value); } /** Returns the available size */ public int getAvailableSize() { return block.readInt(pos + O_AVAILABLESIZE); } /** Sets the available size */ public void setAvailableSize(int value) { block.writeInt(pos + O_AVAILABLESIZE, value); } // overrides java.lang.Object public String toString() { return "RH(" + block.getBlockId() + ":" + pos + ", avl=" + getAvailableSize() + ", cur=" + getCurrentSize() + ")"; } }
package LC0_200.LC150_200; import LeetCodeUtils.ListNode; import org.junit.Test; import java.util.HashMap; public class LC160_Intersection_Of_Two_Linked_Lists { @Test public void test() { } public ListNode getIntersectionNode(ListNode headA, ListNode headB) { HashMap<ListNode, ListNode> map = new HashMap<>(); ListNode result = null; ListNode p = headA; while (p != null) { map.put(p, p); p = p.next; } p = headB; while (p != null) { ListNode tem = map.getOrDefault(p, null); if (tem != null) { return tem; } p = p.next; } return result; } }
package com.fnsvalue.skillshare.hello; import java.util.ArrayList; import java.util.HashMap; public class ReportNotifyLoading { private ArrayList<HashMap> content; public ReportNotifyLoading(ArrayList<HashMap> content){ this.content=content; } public ArrayList<HashMap> getContent() { return content; } }
package switch2019.project.assemblers; import switch2019.project.DTO.deserializationDTO.CreateGroupInfoDTO; import switch2019.project.DTO.deserializationDTO.MemberInfoDTO; import switch2019.project.DTO.serializationDTO.AddedMemberDTO; import switch2019.project.DTO.serializationDTO.GroupDTO; import switch2019.project.DTO.serviceDTO.AddMemberDTO; import switch2019.project.DTO.serviceDTO.CreateGroupDTO; import switch2019.project.domain.domainEntities.group.Group; import switch2019.project.domain.domainEntities.person.Person; import switch2019.project.domain.domainEntities.shared.GroupID; public class GroupDTOAssembler { private GroupDTOAssembler() { } public static GroupDTO createGroupDTO(GroupID groupID) { return new GroupDTO(groupID.getDescription()); } public static CreateGroupDTO creationOfGroupDTO(String groupDescription, String personEmail) { return new CreateGroupDTO(groupDescription, personEmail); } public static CreateGroupDTO transformOfCreationOfGroupDTO(CreateGroupInfoDTO dto) { return new CreateGroupDTO(dto.getGroupDescription(), dto.getPersonEmail()); } public static AddMemberDTO createAddMemberDTO(String personEmail, String groupDescription) { return new AddMemberDTO(personEmail, groupDescription); } public static AddMemberDTO transformIntoAddMemberDTO(MemberInfoDTO memberInfoDTO, String groupDescription) { return new AddMemberDTO(memberInfoDTO.getPersonEmail(), groupDescription); } public static AddedMemberDTO createAddedMemberDTO(boolean wasMemberAdded, Person person, Group group) { return new AddedMemberDTO(wasMemberAdded, person.getID().getEmail(), group.getID().getDescription()); } }
package arrays; import java.util.Arrays; public class FindMaxLengthLIS { public static int countNumberOfLISMax(int[] nums) { int n = nums.length; if (n == 0) return 0; int[] length = new int[n]; int[] count = new int[n]; Arrays.fill(length, 1); Arrays.fill(count, 1); int les = 0; for (int i = 1; i < nums.length; i++) { for (int j = 0; j < i; j++) { if (nums[j] < nums[i]) { if (length[i] < length[j] + 1) { length[i] = length[j] + 1; count[i] = count[j]; } else if (length[i] == length[j] + 1) { count[i] += count[j]; } } } les = Math.max(les, length[i]); } int lisCount = 0; for (int i = 0; i < n; i++) { if (length[i] == les) { lisCount += count[i]; } } return lisCount; } public static int findNumberOfLIS(int[] nums) { int[] result = new int[nums.length]; Arrays.fill(result, 1); for (int i = 1; i <= nums.length - 1; i++) { for (int j = 0; j < i; j++) { if (nums[j] < nums[i]) { result[i] = Math.max(result[i], result[j] + 1); } } } int max = Integer.MIN_VALUE; for (int i = 0; i < result.length; i++) { if (max < result[i]) { max = result[i]; } } return max; } public static void main(String[] args) { int[] arr = {1, 3, 5, 4, 7}; System.out.println(findNumberOfLIS(arr)); System.out.println(countNumberOfLISMax(arr)); } }
package edu.curtin.comp2008.mad2020assignment1; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.fragment.app.Fragment; /** * FragAVertical fragment class is the 'Fragment A' based on the assignment specification that implements Fragment. It is the vertical Fragment A. * It contains a 4 buttons which are oneRow, twoRow, threeRow and scrollDirectionToV buttons, to change how many col it displays or change the scroll direction. * The default layout for fragment A is vertically scrollable in 2 cols. * This fragment uses WhichFrag interface to communicate data to its activity, which is SecondScreen or ThirdScreen */ public class FragAVertical extends Fragment { private Button oneRow, twoRow, threeRow, scrollDirectionToH; private int col; //to communicate from between fragment its activity container private WhichFrag whichFragB; //define the fragment @Override public View onCreateView(LayoutInflater inflater, ViewGroup ui, Bundle bundle) { //LayoutInflater takes a layout reference, instantiates all the View objects and returns the root View object. It reads the XML and creates the UI based on it. //The root View object is used to find a specific UI elements by view.findViewById(..). View view = inflater.inflate(R.layout.fragment_a_vertical, ui,false); //find each view by id oneRow = (Button) view.findViewById(R.id.oneRow); twoRow = (Button) view.findViewById(R.id.twoRow); threeRow = (Button) view.findViewById(R.id.threeRow); scrollDirectionToH = (Button) view.findViewById(R.id.scrollDirectionToH); //col is 2 as it is the default col col = 2; //declare whichFragB based on the activity container whichFragB = (WhichFrag) getActivity(); //When oneRow button is pressed, user will have 1 col scroll layout oneRow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //change col to 1 for one col scroll layout col = 1; //use whichFragB changeFragRowCol method to pass data whichFragB.changeFragRowCol(col, "V"); } }); //When twoRow button is pressed, user will have 2 col scroll layout twoRow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //change col to 2 for two col scroll layout col = 2; //use whichFragB changeFragRowCol method to pass data whichFragB.changeFragRowCol(col, "V"); } }); //When threeRow button is pressed, user will have 3 col scroll layout threeRow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //change col to 3 for three col scroll layout col = 3; //use whichFragB changeFragRowCol method to pass data whichFragB.changeFragRowCol(col, "V"); } }); //When scrollDirectionToH button is pressed, it will change the scroll direction from vertical to horizontal scrolling scrollDirectionToH.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //initialize and declare a new FragAHorizontal object Fragment frag = new FragAHorizontal(); //use whichFragB changeFrag method and pass the FragAHorizontal object to change into horizontal scrolling whichFragB.changeFrag(frag); //use whichFragB changeFragRowCol method to pass data whichFragB.changeFragRowCol(col, "H"); } }); //return the view return view; } }
public class Main { public static void main(String[] args) { CustomLinkedList customLinkedList = new CustomLinkedList(); customLinkedList.head = new Node(1); customLinkedList.head.appendToTail(1); customLinkedList.head.appendToTail(2); customLinkedList.head.appendToTail(3); customLinkedList.head.appendToTail(3); customLinkedList.head.appendToTail(2); // 1 1 2 3 3 2 System.out.println(getKthElementFromLast(customLinkedList, 3)); System.out.println(getKthElementFromLast(customLinkedList, 4)); System.out.println(getKthElementFromLast(customLinkedList, 1)); } static int getKthElementFromLast(CustomLinkedList customLinkedList, int k) { var size = customLinkedList.size(); // 1 2 3 4 5 6 // => size - k + 1 int index = customLinkedList.size() - k + 1; int i = 1; var currentNode = customLinkedList.head; while(i < index && currentNode != null) { i++; currentNode = currentNode.next; } return currentNode.data; } }
package com.libedi.jpa.compositekey.nonidentify; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * ParentId : 복합키 매핑을 위한 식별자 클래스 * * @IdClass 와 다르게 @EmbeddedId 를 적용한 식별자 클래스에는 기본키를 직접 매핑한다. * * - @Embeddable 애노테이션을 붙여주어야 한다. * - Serializable 인터페이스를 구현해야 한다. * - equals, hashCode를 구현해야 한다. * - 기본 생성자가 있어야 한다. * - 식별자 클래스는 public 이어야 한다. * * @author Sang-jun, Park * @since 2019. 05. 29 */ @Embeddable @NoArgsConstructor(access = AccessLevel.PROTECTED) @AllArgsConstructor @EqualsAndHashCode public class ParentId_EmbeddedId_Nonidentify implements Serializable { private static final long serialVersionUID = -2399550482298518739L; @Column(name = "PARENT_ID1") private String id1; @Column(name = "PARENT_ID2") private String id2; }
package com.tencent.mm.protocal.c; import f.a.a.c.a; import java.util.LinkedList; public final class aft extends bhp { public db rJD; public as rJE; public LinkedList<cgb> rJF = new LinkedList(); protected final int a(int i, Object... objArr) { int fS; byte[] bArr; if (i == 0) { a aVar = (a) objArr[0]; if (this.six != null) { aVar.fV(1, this.six.boi()); this.six.a(aVar); } if (this.rJD != null) { aVar.fV(2, this.rJD.boi()); this.rJD.a(aVar); } if (this.rJE != null) { aVar.fV(3, this.rJE.boi()); this.rJE.a(aVar); } aVar.d(4, 8, this.rJF); return 0; } else if (i == 1) { if (this.six != null) { fS = f.a.a.a.fS(1, this.six.boi()) + 0; } else { fS = 0; } if (this.rJD != null) { fS += f.a.a.a.fS(2, this.rJD.boi()); } if (this.rJE != null) { fS += f.a.a.a.fS(3, this.rJE.boi()); } return fS + f.a.a.a.c(4, 8, this.rJF); } else if (i == 2) { bArr = (byte[]) objArr[0]; this.rJF.clear(); f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler); for (fS = bhp.a(aVar2); fS > 0; fS = bhp.a(aVar2)) { if (!super.a(aVar2, this, fS)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; aft aft = (aft) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); LinkedList IC; int size; f.a.a.a.a aVar4; boolean z; switch (intValue) { case 1: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); fl flVar = new fl(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = flVar.a(aVar4, flVar, bhp.a(aVar4))) { } aft.six = flVar; } return 0; case 2: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); db dbVar = new db(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = dbVar.a(aVar4, dbVar, bhp.a(aVar4))) { } aft.rJD = dbVar; } return 0; case 3: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); as asVar = new as(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = asVar.a(aVar4, asVar, bhp.a(aVar4))) { } aft.rJE = asVar; } return 0; case 4: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); cgb cgb = new cgb(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = cgb.a(aVar4, cgb, bhp.a(aVar4))) { } aft.rJF.add(cgb); } return 0; default: return -1; } } } }
package com.hladkevych.menu.controllers; import com.hladkevych.menu.dto.DietDTO; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.hladkevych.menu.service.DietServiceImpl; import com.hladkevych.menu.service.RecipeService; /** * Created by ggladko97 on 04.02.18. */ @org.springframework.web.bind.annotation.RestController @RequestMapping("/load") public class RestController { private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(RestController.class); @Autowired private DietServiceImpl dietService; @RequestMapping("/diet-{id}") @ResponseBody public DietDTO loadDetails(@PathVariable String id) { List<DietDTO> dietDTOS = dietService.listDiets(); logger.info("DietsDTO from file: " + dietDTOS.toString()); for(DietDTO diett : dietDTOS) { if (diett.getTitle().equals(id)) { logger.info("Found: " + diett); return diett; } } return null; } }
package com.pjc.notepad.home.service; public class HomeService { }
package offer; // 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 // 数组中某些数字是重复的,但不知道有几个数字是重复的。 // 也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 // 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。 // // Parameters: // // numbers: an array of integers // // length: the length of array numbers // // duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation; // // Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++ // // 这里要特别注意~返回任意重复的一个,赋值duplication[0] // // Return value: true if the input is valid, and there are some duplications in the array number // // otherwise false public class 数组中的重复数字 { public static void main(String[] args) { int[] nums = {2,3,1,0,2,5,3}; int len = nums.length; int[] dup = new int[1]; System.out.println(duplicate(nums,len,dup)); } public static boolean duplicate(int numbers[],int length,int [] duplication) { boolean[] idx = new boolean[length]; int k = 0; for (int i = 0; i < length; i++) { if(idx[numbers[i]] == false) idx[numbers[i]] = true; else{ duplication[k++] = numbers[i]; break; } } return k!=0? true:false; } }
package com.adobe.util; import java.util.Date; public class DateUtil { public static Date getDate() { return new Date(); } }
package com.tibco.as.io.cli; import com.tibco.as.io.IChannel; import com.tibco.as.io.IExecutor; public interface ICommand { IExecutor getExecutor(IChannel channel) throws Exception; }
package au.com.autogeneral.testAPI.service.impl; import au.com.autogeneral.testAPI.service.BracketsValidatorService; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * BracketsValidatorServiceImpl Tester. * * @author dym * @version 1.0 * @since <pre>Jul 24, 2018</pre> */ public class BracketsValidatorServiceImplTest { /** * Method: validate(String input) */ @Test public void testValidate() { BracketsValidatorService validatorService = new BracketsValidatorServiceImpl(); assertTrue("No string - no problems", validatorService.validate(null)); assertTrue("Empty string is balanced", validatorService.validate("")); assertTrue("Perfectly balanced string", validatorService.validate("some ( string [ with {{[(brackets)]}}])")); assertFalse("Missing closing bracket", validatorService.validate("(([]) a bracket is missing")); assertFalse("Extra closing bracket", validatorService.validate("(([]))) <- this one should not be there")); assertFalse("Intersection of brackets", validatorService.validate("(({ oops )})")); assertFalse("Just wrong", validatorService.validate("[)()(]")); } }
package com.db.dao.review; import java.io.IOException; import com.db.FileDB; import com.db.dao.AbstractDao; public class ReservesDao extends AbstractDao{ private static ReservesDao instance; public static ReservesDao getInstance() throws IOException { if (instance == null) { synchronized (ReservesDao.class) { if (instance == null) { instance = new ReservesDao(); } } } return instance; } private ReservesDao() throws IOException { super(new FileDB("cop6726.review.reserves.db")); } }
package com.smxknife.java2.thread.futureAndCallable.exception; import java.util.concurrent.Callable; /** * @author smxknife * 2019-08-22 */ public class ExceptionCallable implements Callable<String> { @Override public String call() throws Exception { Integer.parseInt("a"); return null; } }
package application; import java.util.Scanner; import entities.Person; public class herancaTest { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Person person = new Person(); System.out.print("Enter with name: "); String nome = scan.nextLine(); System.out.print("Enter with age: "); int idade = scan.nextInt(); Person atributo = new Person(nome, idade); System.out.printf(atributo.toString()); } }
package com.pad; /** * Created by Admin on 13.12.2016. */ public class MulticastGroup { public static final String PROTOCOL_GROUP_ADDRESS = "228.5.6.7"; public static final int PROTOCOL_GROUP_PORT = 10100; public static final int PROTOCOL_GROUP_TIMEOUT = 2000; // milliseconds }
package edu.iit.cs445.StateParking.UnitTest; import static org.junit.Assert.*; import org.junit.Test; import edu.iit.cs445.StateParking.Objects.*; public class VisitorTest { private Visitor visitor1 = new VisitorObj("John Doe","john.doe@example.com"); private Visitor visitor2 = new VisitorObj("Tom cat","TomAndJerry123@gmail.com"); @Test public void test() { assertEquals(visitor1.getVid(), visitor2.getVid()-1); assertTrue("Tom cat".equals(visitor2.getName())); assertFalse("John Doe".equals(visitor2.getName())); assertTrue("TomAndJerry123@gmail.com".equals(visitor2.getEmail())); assertFalse("john.doe@example.com".equals(visitor2.getEmail())); assertTrue(visitor2.KeywordMatch("To")); assertFalse(visitor2.KeywordMatch("Jo")); assertFalse(visitor2.isNull()); } }
package com.github.astefanich.broker.concurrent.threaded; import com.github.astefanich.broker.concurrent.ConcurrentOrderManager; import edu.uw.ext.framework.order.PricedOrder; import edu.uw.ext.framework.order.StopBuyOrder; import edu.uw.ext.framework.order.StopSellOrder; /** * Concrete implementation of {@link ConcurrentOrderManager}. Maintains a pair of * {@link ThreadedOrderQueue}s, of types {@link StopBuyOrder} and {@link StopSellOrder}. * * @author AndrewStefanich * */ public final class ThreadedOrderManager extends ConcurrentOrderManager { /** * Constructs an instance of {@code ThreadedOrderManager}, and initializes {@link PricedOrder} * queues. * * @param stockSymbolTicker * the ticker symbol of the stock this instance manages orders for * @param price * the current price of the stock to be managed */ public ThreadedOrderManager(String stockSymbolTicker, int price) { super(stockSymbolTicker); initializePricedOrderQueues(price); } /** * Initializes this OrderManager queues with {@link ThreadedOrderQueue}s. * * @param initialPrice * the initial "stop" price for the queues */ protected void initializePricedOrderQueues(int initialPrice) { stopBuyOrderQueue = new ThreadedOrderQueue<Integer, StopBuyOrder>(initialPrice, STOP_BUY_ORDER_FILTER, STOP_BUY_ORDER_COMPARATOR); stopSellOrderQueue = new ThreadedOrderQueue<Integer, StopSellOrder>(initialPrice, STOP_SELL_ORDER_FILTER, STOP_SELL_ORDER_COMPARATOR); } }
package com.tencent.mm.plugin.game.ui; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.tencent.mm.ak.o; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.game.a.b; import com.tencent.mm.plugin.game.a.c; import com.tencent.mm.plugin.game.f.e; import com.tencent.mm.plugin.game.model.an; import com.tencent.mm.plugin.game.model.s; import com.tencent.mm.plugin.game.model.s.d; import com.tencent.mm.plugin.game.model.t; import com.tencent.mm.plugin.game.model.v; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.rtmp.TXLiveConstants; public class GameMessageBubbleView extends LinearLayout implements OnClickListener { View kaM; private TextView kaN; private ImageView kaO; private s kaP; private final long kaQ = 500; private long kaR = 0; private Context mContext; private boolean mHasInit = false; public GameMessageBubbleView(Context context, AttributeSet attributeSet) { super(context, attributeSet); this.mContext = context; } protected void onFinishInflate() { super.onFinishInflate(); if (!this.mHasInit) { this.kaO = (ImageView) findViewById(e.game_msg_bubble_icon); this.kaN = (TextView) findViewById(e.game_msg_bubble_desc); this.kaM = findViewById(e.game_msg_bubble_layout); setVisibility(8); this.mHasInit = true; } } public final void aVb() { ((b) g.l(b.class)).aSi(); this.kaP = v.aUb(); if (this.kaP == null) { this.kaM.setOnClickListener(null); setVisibility(8); return; } this.kaP.aTW(); if (this.kaP.field_msgType == 100 && (bi.oW(this.kaP.jMv.cZG) || bi.oW(this.kaP.jMv.jNg) || bi.oW(this.kaP.jMv.jNh) || !this.kaP.jMw.containsKey(this.kaP.jMv.jNh))) { x.w("MicroMsg.GameMessageHeaderView", "bubble is invalid"); this.kaM.setOnClickListener(null); setVisibility(8); return; } this.kaN.setText(this.kaP.jMv.cZG); o.Pj().a(this.kaP.jMv.jNg, this.kaO); this.kaM.setOnClickListener(this); setVisibility(0); } public void onClick(View view) { if (System.currentTimeMillis() - this.kaR > 500 && this.kaP != null) { ((b) g.l(b.class)).aSi(); v.aUc(); int a; if (this.kaP.field_msgType == 100) { if (!bi.oW(this.kaP.jMv.jNh)) { d dVar = (d) this.kaP.jMw.get(this.kaP.jMv.jNh); if (dVar != null) { a = t.a(this.mContext, this.kaP, dVar, this.kaP.field_appId, TXLiveConstants.PUSH_EVT_FIRST_FRAME_AVAILABLE); if (a != 0) { an.a(this.mContext, 10, TXLiveConstants.PUSH_EVT_FIRST_FRAME_AVAILABLE, 1, a, 0, this.kaP.field_appId, 0, this.kaP.jNa, this.kaP.field_gameMsgId, this.kaP.jNb, null); } if (dVar.jNj != 4) { this.kaP.field_isRead = true; ((c) g.l(c.class)).aSj().c(this.kaP, new String[0]); } } } this.kaR = System.currentTimeMillis(); return; } if (!(this.kaP == null || this.kaP.jMy == 3)) { this.kaP.field_isRead = true; ((c) g.l(c.class)).aSj().c(this.kaP, new String[0]); } switch (this.kaP.jMy) { case 1: String str = this.kaP.jMk; if (!bi.oW(str)) { a = com.tencent.mm.plugin.game.e.c.r(this.mContext, str, "game_center_bubble"); break; } else { a = 0; break; } case 2: if (!bi.oW(this.kaP.field_appId)) { Bundle bundle = new Bundle(); bundle.putCharSequence("game_app_id", this.kaP.field_appId); bundle.putInt("game_report_from_scene", TXLiveConstants.PUSH_EVT_FIRST_FRAME_AVAILABLE); a = com.tencent.mm.plugin.game.e.c.b(this.mContext, this.kaP.field_appId, null, bundle); break; } x.e("MicroMsg.GameMessageHeaderView", "message type : " + this.kaP.field_msgType + " ,message.field_appId is null."); a = 0; break; case 3: Intent intent = new Intent(this.mContext, GameMessageUI.class); intent.putExtra("game_report_from_scene", TXLiveConstants.PUSH_EVT_FIRST_FRAME_AVAILABLE); this.mContext.startActivity(intent); a = 6; break; default: x.e("MicroMsg.GameMessageHeaderView", "unknown bubble_action = " + this.kaP.jMy); return; } an.a(this.mContext, 10, TXLiveConstants.PUSH_EVT_FIRST_FRAME_AVAILABLE, 1, a, 0, this.kaP.field_appId, 0, this.kaP.field_msgType, this.kaP.field_gameMsgId, this.kaP.jNb, null); this.kaR = System.currentTimeMillis(); } } }
package com.sfa.repository; import java.util.HashMap; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.sfa.vo.CustomerVo; @Repository public class CustomerDao { @Autowired SqlSession sqlSession; public List<CustomerVo> select(String dept) { // TODO Auto-generated method stub HashMap <String,String> map= new HashMap<String,String>(); map.put("dept", dept); return sqlSession.selectList("customer.selectbyDept", map); } public int insert(CustomerVo customerVo) { // TODO Auto-generated method stub return sqlSession.insert("customer.insert", customerVo); } public int update(CustomerVo customerVo) { // TODO Auto-generated method stub return sqlSession.update("customer.update",customerVo); } public int delete(String customer_code) { // TODO Auto-generated method stub return sqlSession.update("customer.delete",customer_code); } public CustomerVo select() { // TODO Auto-generated method stub return sqlSession.selectOne("customer.last_select"); } public List<CustomerVo> selectById(String id) { // TODO Auto-generated method stub return sqlSession.selectList("customer.selectbyid", id); } public List<CustomerVo> selectByName(String name, String id) { // TODO Auto-generated method stub HashMap <String,String> map= new HashMap<String,String>(); map.put("name", name); map.put("id", id); return sqlSession.selectList("customer.selectByName",name); } public List<CustomerVo> getPosition(CustomerVo customerVo) { // TODO Auto-generated method stub return sqlSession.selectList("customer.getPosition", customerVo); } public CustomerVo getCustomer(String customer_code) { // TODO Auto-generated method stub return sqlSession.selectOne("customer.getCustomer", customer_code); } }
package service; import java.io.IOException; import java.net.ServerSocket; public class Servidor { private PaginaHtm pagina; private ServerSocket socketServidor; private static Servidor instance = null; private Servidor(){ try{ this.socketServidor = new ServerSocket(12345); this.pagina = new PaginaHtm(); System.out.println("Servidor iniciado"); } catch(IOException e){ System.out.println(e.getMessage()); } } public static Servidor getInstance(){ if(instance == null) instance = new Servidor(); return instance; } public ServerSocket getSocketServidor() { return socketServidor; } private static String tratarString(String requisicao) { String resultado = requisicao.substring(5, requisicao.length() -9); if(resultado.trim().equals("")){ resultado = "index.htm"; } return resultado; } protected String tratarRequisicao(String requisicao){ String codigo = null; String status = null; if(requisicao.startsWith("GET /") && (requisicao.endsWith(" HTTP/1.1") || requisicao.endsWith(" HTTP/1.0") || requisicao.endsWith(" HTTP/0.9"))){ if(tratarString(requisicao).equals(pagina.getNome())){ codigo = "200"; status = "OK"; return "HTTP/1.0 " + codigo + " "+ status + "* " + pagina.getConteudo(); } else{ codigo = "404"; status = "HTTP Not Found"; return "HTTP/1.0 " + codigo + " "+ status + "* "; } } else{ codigo = "400"; status = "Bad Request"; return "HTTP/1.0 " + codigo + " "+ status + "* "; } } }
package com.JDBC; import java.sql.*; import java.sql.Connection; import java.util.Scanner; import java.util.regex.Pattern; /** * Created by Анна on 02.08.2016. */ public class Main { private static final String USERNAME = "root"; private static final String PASSWORD = "root"; private static final String URL = "jdbc:mysql://localhost:3306/employees"; Main(){} public static void main (String args []) throws SQLException { Main main = new Main(); DBProcessor db = new DBProcessor(); Connection conn= db.getConnection(URL,USERNAME,PASSWORD); main.enterUser(conn); main.showDatabase(conn); conn.close(); } private void enterUser(Connection connection) throws SQLException{ Scanner scanner=new Scanner(System.in); String fName, lName; do{ System.out.println("Введите имя: "); fName=scanner.next(); System.out.println("Введите фамилию: "); lName=scanner.next(); putUserIntoDatabase(fName,lName,connection); }while (isAddUser()); } private void putUserIntoDatabase(String fName, String lName, Connection connection) throws SQLException{ PreparedStatement prepInsert; if (isUsernameCorrect(fName,lName)) { prepInsert = connection.prepareStatement(queryInsert()); prepInsert.setString(1, fName); prepInsert.setString(2, lName); prepInsert.execute(); prepInsert.close(); } else { System.out.println("имя или фамилия введены некорректно, пользователь не будет добавлен в бд!"); } } private String queryInsert(){ return "INSERT INTO employees.users (first_name, last_name) VALUES (?, ?)"; } private boolean isUsernameCorrect(String fName,String lName){ if (patternString().matcher(fName).matches() && patternString().matcher(lName).matches()){ return true; }else return false; } private Pattern patternString(){ return Pattern.compile("([А-ЯЁ]{1}[a-яё]{0,21})|([A-Z]{1}[a-z]{0,43})"); } private boolean isAddUser(){ Scanner scanner=new Scanner(System.in); System.out.println("Добавить еще пользователя? "); String addUser=scanner.next().toLowerCase(); if (isAddUserYes(addUser)){ return true; }else if (isAddUserNo(addUser)){ return false; }else return isAddUser(); } private boolean isAddUserYes(String addUser){ if(addUser.equals("y")||addUser.equals("yes")||addUser.equals("да")) { return true; } else return false; } private boolean isAddUserNo(String addUser){ if(addUser.equals("n")||addUser.equals("no")||addUser.equals("нет")) { return true; }else return false; } private void showDatabase(Connection connection) throws SQLException{ PreparedStatement prepSelect = connection.prepareStatement(querySelect()); ResultSet resultSet = prepSelect.executeQuery(); while (resultSet.next()) { System.out.println(resultSet.getString("last_name") + " " + resultSet.getString("first_name")); } prepSelect.close(); } private String querySelect(){ return "SELECT * FROM employees.users"; } }
package superintendent.features.wiki.links; public enum SupportedWikis implements SupportedWiki { WIKIPEDIA("Wikipedia", "Wikipedia:", "https://en.wikipedia.org/wiki/"), MEDIAWIKI("MediaWiki", "mw:", "https://www.mediawiki.org/wiki/"), WIKIA("Wikia", "w:c:", "https://community.wikia.com/wiki/w:c:"), HALOPEDIA("Halopedia", "", "https://www.halopedia.org/"); public static final SupportedWiki DEFAULT = HALOPEDIA; private final String name; private final String prefix; private final String url; private SupportedWikis(String name, String prefix, String url) { this.name = name; this.prefix = prefix; this.url = url; } @Override public String getName() { return name; } @Override public String getBaseUrl() { return url; } @Override public String getPrefix() { return prefix; } }
package com.tencent.mm.g.a; import com.tencent.mm.sdk.b.b; public final class ti extends b { public a ceP; public b ceQ; public ti() { this((byte) 0); } private ti(byte b) { this.ceP = new a(); this.ceQ = new b(); this.sFm = false; this.bJX = null; } }
/* * @Author : fengzhi * @date : 2019 - 04 - 22 20 : 55 * @Description : */ package nowcoder_leetcode; import java.util.HashMap; import java.util.HashSet; import java.util.Map; public class p_13 { public RandomListNode copyRandomList(RandomListNode head) { // next和random是有区别的,next一路走下去定然能够遍历所有的节点,而random指向的不过是这些节点 // 因此分为两步走:1.使用next实现所有的节点复制 2.实现random的连接 // 在第二步中,可以使用循环查找实现,也可以使用hashmap以空间换时间 if (head == null) return null; RandomListNode newHead = new RandomListNode(head.label); RandomListNode pointer1 = head.next; RandomListNode pointer2 = newHead; while (pointer1 != null) { pointer2.next = new RandomListNode(pointer1.label); pointer2 = pointer2.next; pointer1 = pointer1.next; } pointer1 = head; pointer2 = newHead; RandomListNode p1, p2; while (pointer1 != null) { if (pointer1.random == null) { pointer1 = pointer1.next; pointer2 = pointer2.next; continue; } else { p1 = head; p2 = newHead; while (pointer1.random != p1) { p1 = p1.next; p2 = p2.next; } pointer2.random = p2; } pointer1 = pointer1.next; pointer2 = pointer2.next; } return newHead; } // public RandomListNode copyRandomList2(RandomListNode head) { // // 使用hashmap // if (head == null) // return null; // Map<RandomListNode, RandomListNode> map = new HashMap<>(); // RandomListNode newHead = new RandomListNode(head.label); // map.put(newHead, head.random); // RandomListNode pointer1 = head.next; // RandomListNode pointer2 = newHead; // // while (pointer1 != null) { // pointer2.next = new RandomListNode(pointer1.label); // map.put(pointer1, ) // pointer2 = pointer2.next; // pointer1 = pointer1.next; // } // pointer1 = head; // pointer2 = newHead; // while (pointer1 != null) { // // } // return newHead; // } public static void main(String[] args) { RandomListNode node1 = new RandomListNode(1); RandomListNode node2 = new RandomListNode(2); RandomListNode node3 = new RandomListNode(3); RandomListNode node4 = new RandomListNode(4); node1.next = node2; node2.next = node3; node3.next = node4; p_13 p13 = new p_13(); RandomListNode node = p13.copyRandomList(node1); while (node != null) { System.out.println(node.label); node = node.next; } } }
package switch2019.project.domain.repositories; import switch2019.project.domain.domainEntities.frameworks.ID; import switch2019.project.domain.domainEntities.frameworks.OwnerID; import switch2019.project.domain.domainEntities.ledger.Ledger; import switch2019.project.domain.domainEntities.ledger.Transaction; import switch2019.project.domain.domainEntities.ledger.Type; import switch2019.project.domain.domainEntities.shared.*; import java.util.List; public interface LedgerRepository extends Repository { Ledger getByID(ID ledgerID); boolean isIDOnRepository(ID ledgerID); Transaction getTransactionByID(String ownerID, Long id); long repositorySize(); Ledger createLedger(OwnerID ownerID); Transaction addTransactionToLedger(LedgerID ledgerID, MonetaryValue amount, Description description, DateAndTime localDate, CategoryID category, AccountID accountFrom, AccountID accountTo, Type type); List<Transaction> findAllTransactionsByLedgerID(String ownerID); List<Transaction> getTransactionsInDateRange(OwnerID ledgerID, String initDate, String finDate); }
package com.eazy.firda.eazy; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.eazy.firda.eazy.Tasks.JSONParser; import org.json.JSONException; import org.json.JSONObject; public class DescCarOwner extends AppCompatActivity { String carId, f_type, f_reg, textDesc, data; int ac; Spinner fuelType, fuelReg; CheckBox cbAc; EditText desc; Button add; Intent intent; Bundle extras; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_desc_car_owner); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); this.getSupportActionBar().setTitle("Car Description"); intent = getIntent(); extras = intent.getExtras(); carId = extras.getString("car_id"); fuelType = findViewById(R.id.carFuel); fuelReg = findViewById(R.id.carRegulation); cbAc = findViewById(R.id.carAc); desc = findViewById(R.id.carDesc); add = findViewById(R.id.btnSave); call c = new call(); c.execute(); fuelType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { f_type = parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); fuelReg.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { f_reg = parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(cbAc.isChecked()){ ac = 1; } else{ ac = 0; } if(desc.length() > 0){ textDesc = desc.getText().toString(); } data = carId + "|" + f_type + "|" + f_reg + "|" + ac + "|" + textDesc; save s = new save(); s.execute(); } }); } private class call extends AsyncTask<Void, Void, Void>{ ProgressDialog progressDialog; @Override protected void onPreExecute(){ progressDialog = new ProgressDialog(DescCarOwner.this); progressDialog.setMessage("Getting Data ..."); progressDialog.setIndeterminate(false); progressDialog.setCancelable(true); progressDialog.show(); } @Override protected Void doInBackground(Void... voids) { f_type = extras.getString("fuel_type"); f_reg = extras.getString("fuel_regulation"); textDesc = extras.getString("desc"); ac = extras.getInt("ac"); return null; } @Override protected void onPostExecute(Void jsonObject) { if(f_type.length() == 0){ f_type = "Not Set"; fuelType.setSelection(0); } else{ if(f_type.equals("Pertamax")){ fuelType.setSelection(1); } else if(f_type.equals("Pertalite")){ fuelType.setSelection(2); } else if(f_type.equals("Premium")){ fuelType.setSelection(3); } else if(f_type.equals("Solar")){ fuelType.setSelection(4); } } if(f_reg.length() == 0){ f_reg = "Not Set"; fuelReg.setSelection(0); } else{ if(f_reg.equals("Full to Full")){ fuelReg.setSelection(1); } else if(f_reg.equals("Half to Half")){ fuelReg.setSelection(2); } else if(f_reg.equals("Full to Half")){ fuelReg.setSelection(3); } else if(f_reg.equals("Half to Full")){ fuelReg.setSelection(4); } } if(ac == 0){ cbAc.setChecked(false); }else{ cbAc.setChecked(true); } if(textDesc.length() > 0){ desc.setText(textDesc); } progressDialog.dismiss(); } } private class save extends AsyncTask<Void, Void, JSONObject>{ ProgressDialog progressDialog; String saveUrl = "http://new.entongproject.com/api/provider/rental/api_save_cardesc"; @Override protected void onPreExecute(){ progressDialog = new ProgressDialog(DescCarOwner.this); progressDialog.setMessage("Getting Data ..."); progressDialog.setIndeterminate(false); progressDialog.setCancelable(true); progressDialog.show(); } @Override protected JSONObject doInBackground(Void... voids) { JSONParser jParser = new JSONParser(); Log.v("carId", carId); JSONObject response = jParser.getJsonFromUrl(saveUrl, data); return response; } @Override protected void onPostExecute(JSONObject jsonObject) { try{ String msg = jsonObject.getString("message"); Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show(); }catch (JSONException e){ e.printStackTrace(); } progressDialog.dismiss(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent(DescCarOwner.this, DetailCarOwner.class); Bundle extras = new Bundle(); extras.putString("car_id", carId); intent.putExtras(extras); startActivity(intent); finish(); } }
package com.example.demojackson.dao; import com.example.demojackson.common.IMapper; import com.example.demojackson.entity.User; public interface UserMapper extends IMapper<User> { }
package com.fixit.rest.responses; import java.util.Date; import java.util.Map; /** * Created by konstantin on 5/16/2017. * */ public class TwilioMessageResponse { private String sid; private Date date_created; private Date date_updated; private Date data_sent; private String account_sid; private String to; private String from; private String body; private String status; private String num_segments; private String num_media; private String direction; private String api_version; private String price; private String price_unit; private String error_code; private String error_message; private String uri; private Map<String, String> subresource_uris; public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public Date getDate_created() { return date_created; } public void setDate_created(Date date_created) { this.date_created = date_created; } public Date getDate_updated() { return date_updated; } public void setDate_updated(Date date_updated) { this.date_updated = date_updated; } public Date getData_sent() { return data_sent; } public void setData_sent(Date data_sent) { this.data_sent = data_sent; } public String getAccount_sid() { return account_sid; } public void setAccount_sid(String account_sid) { this.account_sid = account_sid; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getNum_segments() { return num_segments; } public void setNum_segments(String num_segments) { this.num_segments = num_segments; } public String getNum_media() { return num_media; } public void setNum_media(String num_media) { this.num_media = num_media; } public String getDirection() { return direction; } public void setDirection(String direction) { this.direction = direction; } public String getApi_version() { return api_version; } public void setApi_version(String api_version) { this.api_version = api_version; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getPrice_unit() { return price_unit; } public void setPrice_unit(String price_unit) { this.price_unit = price_unit; } public String getError_code() { return error_code; } public void setError_code(String error_code) { this.error_code = error_code; } public String getError_message() { return error_message; } public void setError_message(String error_message) { this.error_message = error_message; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public Map<String, String> getSubresource_uris() { return subresource_uris; } public void setSubresource_uris(Map<String, String> subresource_uris) { this.subresource_uris = subresource_uris; } @Override public String toString() { return "TwilioMessage{" + "sid='" + sid + '\'' + ", date_created=" + date_created + ", date_updated=" + date_updated + ", data_sent=" + data_sent + ", account_sid='" + account_sid + '\'' + ", to='" + to + '\'' + ", from='" + from + '\'' + ", body='" + body + '\'' + ", status='" + status + '\'' + ", num_segments='" + num_segments + '\'' + ", num_media='" + num_media + '\'' + ", direction='" + direction + '\'' + ", api_version='" + api_version + '\'' + ", price='" + price + '\'' + ", price_unit='" + price_unit + '\'' + ", error_code='" + error_code + '\'' + ", error_message='" + error_message + '\'' + ", uri='" + uri + '\'' + ", subresource_uris=" + subresource_uris + '}'; } }
package jooqexercise; import org.codehaus.groovy.runtime.powerassert.SourceText; import org.openqa.selenium.JavascriptExecutor; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; import java.util.concurrent.TimeUnit; /** * Created by acedric on 20/04/2017. */ public class Main { WebDriver driver ; @BeforeClass public void setUp(){ System.setProperty("webdriver.chrome.driver", "C:\\Workspace\\execise\\src\\test\\java\\jooqexercise\\chromedriver.exe"); driver = new ChromeDriver(); } @Test public void test() throws InterruptedException { driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("http://qa.data3.sis.tv:8080/SISTrader/traderUI/index"); driver.findElement(By.id("username")).sendKeys("admin"); driver.findElement(By.id("password")).sendKeys("password"); driver.findElement(By.id("loginButton_submit")).click(); JavascriptExecutor jse = (JavascriptExecutor)driver; System.out.println((String)jse.executeScript("document.readyState")); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.className("meeting-wrapper"))); clickMeeting(); enterPrice("Permian","10/1"); ////button[@id='save-btn'] Thread.sleep(1000); driver.findElement(By.xpath("//button[@id='save-btn']")).click(); Thread.sleep(2000); System.out.println(driver.findElement(By.xpath("//div[@class='notification-message']")).getText()); driver.quit(); } private void clickMeeting(){ if(!isMeetingsVisible()){ driver.findElement(By.id("burger-button")).click(); } WebElement meeting = driver.findElement(By.xpath("//a/span[contains(text(),'Bath')]")); System.out.println(meeting.getAttribute("aria-expanded")); if(!Boolean.parseBoolean(meeting.getAttribute("aria-expanded"))){ meeting.click(); } // if (!Boolean.parseBoolean(meeting.getAttribute("aria-expanded"))){ // meeting.click(); // } try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } driver.findElement(By.xpath("//div/label[contains(text(),'15:30')]")).click(); try { Thread.sleep(2000L); } catch (InterruptedException e) { e.printStackTrace(); } } private boolean isMeetingsVisible(){ WebElement element = driver.findElement(By.id("burger-button")); System.out.println(element.getText()); if(element.getAttribute("class").equalsIgnoreCase("open")){ return true; } else{ return false; } } public void enterPrice(String runnerName, String price){ getRunnerRowByTitle(runnerName).findElement(By.cssSelector("td:nth-of-type(3) input")).clear(); getRunnerRowByTitle(runnerName).findElement(By.cssSelector("td:nth-of-type(3) input")).sendKeys(price); } public WebElement getRunnerRowByTitle(String runnerName){ WebElement element = null; List<WebElement> rows = driver.findElements(By.cssSelector("div#race-table table#history-table tbody tr")); for(WebElement row : rows){ String name = row.findElement(By.cssSelector("td:nth-of-type(1)")).getText(); if (name.contains(runnerName)) { element = row; break; } } return element; } // public ExpectedCondition<Boolean> waitTillMeetingsAreLoaded(){ // return new ExpectedCondition<Boolean>() { // // @Override // public Boolean apply(WebDriver input) { // return driver.findElements(By.cssSelector("meeting-wrapper")).size() > 0; // } @AfterClass public void after(){ driver.quit(); } }
package com.example.easysingletonexample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { private SomeSingletone someSingletone = AppConfig.getInstance().getSomeSingletone(); //вызов инициализированного синглтона @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); someSingletone.outLog(); //использование метода синглтона } }
public class SumOfAllSubsetXORTotals { static int sum = 0; public static int subsetXORSum(int[] nums) { sum = backTrack(nums,0,0); return sum; } private static int backTrack(int[] nums, int index, int current) { sum = sum + current; for (int i = index;i< nums.length;i++){ current = current^nums[i]; backTrack(nums,i+1,current); current = current ^ nums[i]; } return sum; } public static void main(String[] args) { int arr[] = {1,3}; System.out.println(subsetXORSum(arr)); } }
package com.lspring.proxy.demo; /** * @ClassName: 人 * @Description: 真实主题 * @author: amosli * @email:amosli@infomorrow.com * @date Nov 24, 2013 5:34:24 PM */ public class 人 implements 打牛 { public void 打() { System.out.println("牛被打了!"); } }
package c.t.m.g; import com.tencent.map.geolocation.TencentLocation; import com.tencent.map.geolocation.TencentLocationUtils; class dl$a { double a; double b; long c; int d; dl$a() { } public final String toString() { return "[" + this.a + "," + this.b + "]"; } static dl$a a(TencentLocation tencentLocation) { int i = 2; dl$a dl_a = new dl$a(); dl_a.a = tencentLocation.getLatitude(); dl_a.b = tencentLocation.getLongitude(); dl_a.c = tencentLocation.getTime(); tencentLocation.getSpeed(); if (TencentLocationUtils.isFromGps(tencentLocation)) { if (tencentLocation.getAccuracy() < 100.0f) { i = 3; } dl_a.d = i; } else { if (tencentLocation.getAccuracy() >= 500.0f) { i = 1; } dl_a.d = i; } return dl_a; } }
package com.github.isaichkindanila.ioc; import java.util.List; class ComponentInfo { private final Class componentClass; private final List<Parameter> parameters; private final Class[] argClasses; ComponentInfo(Class componentClass, List<Parameter> parameters) { this.componentClass = componentClass; this.parameters = parameters; argClasses = parameters.stream() .map(Parameter::getClazz) .toArray(Class[]::new); } Class getComponentClass() { return componentClass; } List<Parameter> getParameters() { return parameters; } Class[] getArgClasses() { return argClasses; } }
package test.algorithm; /** * Created by maguoqiang on 2016/9/28. * 折半 */ public class BinaryTest { public static void main(String[] args) { int arr[]={44,21,43,3,4,33,65,32,1,435}; } }
package com.hxzy.entity; import java.io.Serializable; /** * @author */ public class Major implements Serializable { /** * 编号 */ private Integer id; private String name; /** * 状态:1启用 0禁用 */ private Integer state; private static final long serialVersionUID = 1L; 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 Integer getState() { return state; } public void setState(Integer state) { this.state = state; } }
/* * 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 databaseinterface; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; /** * @author Veronika */ public class ClientDetails extends javax.swing.JFrame { private static final String USERNAME = "root"; private static final String PASSWORD = "root"; private static final String CONN_STRING = "jdbc:mysql://localhost:3306/mydbtest?useUnicode=true&useSSL=true&useJDBCCompliantTimezoneShift=true"; /** * Creates new form ClientDetails */ public ClientDetails() { initComponents(); DefaultTableModel dms = new DBclassClient().getData(); ViewClient.setModel(dms); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); AddC = new javax.swing.JPanel(); textCityClient = new javax.swing.JTextField(); textSurnameClient = new javax.swing.JTextField(); textGenderClient = new javax.swing.JComboBox<>(); textNameClient = new javax.swing.JTextField(); textDataClient = new javax.swing.JTextField(); textEmailClient = new javax.swing.JTextField(); textPhoneClient = new javax.swing.JTextField(); textCountryClient = new javax.swing.JTextField(); jCheckBox1 = new javax.swing.JCheckBox(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); HomeSearchRoom = new javax.swing.JButton(); LogoutSearchRoom = new javax.swing.JButton(); DeleteC = new javax.swing.JPanel(); IDclient = new javax.swing.JTextField(); DelDataClient = new javax.swing.JTextField(); DelCountryClient = new javax.swing.JTextField(); DelEmailClient = new javax.swing.JTextField(); DelSurnameClient = new javax.swing.JTextField(); DelGenderClient = new javax.swing.JTextField(); DelCityClient = new javax.swing.JTextField(); DelNameClient = new javax.swing.JTextField(); DelPhoneClient = new javax.swing.JTextField(); DelReservClient = new javax.swing.JCheckBox(); jLabel2 = new javax.swing.JLabel(); LogoutDeleteClient = new javax.swing.JButton(); HomeDeleteClient = new javax.swing.JButton(); SearchDelClient = new javax.swing.JButton(); DeleteButClient = new javax.swing.JButton(); UpdateC = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); ReservUpdateButt = new javax.swing.JCheckBox(); CityUpdateC = new javax.swing.JTextField(); PhoneUpdateC = new javax.swing.JTextField(); GenderUpdateC = new javax.swing.JTextField(); SurnameUpdateC = new javax.swing.JTextField(); CountryUpdateC = new javax.swing.JTextField(); NameUpdateC = new javax.swing.JTextField(); DateUpdateC = new javax.swing.JTextField(); EmailUpdateC = new javax.swing.JTextField(); IDclient2 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); HomeUpdateClient = new javax.swing.JButton(); LogoutUpdateClient = new javax.swing.JButton(); searchCupd = new javax.swing.JButton(); updateCbutt = new javax.swing.JButton(); SearchC = new javax.swing.JPanel(); IDclient1 = new javax.swing.JTextField(); SearchCityClient = new javax.swing.JTextField(); SearchNameClient = new javax.swing.JTextField(); SearchDataClient = new javax.swing.JTextField(); SearchCountryClient = new javax.swing.JTextField(); SearchEmailClient = new javax.swing.JTextField(); SearchSurnameClient = new javax.swing.JTextField(); SearchGenderClient = new javax.swing.JTextField(); SearchPhoneClient = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); HomeSearchClient = new javax.swing.JButton(); LogoutSearchClient = new javax.swing.JButton(); searchCButt = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); ViewClient = new javax.swing.JTable(); jLabel5 = new javax.swing.JLabel(); LogoutViewClient = new javax.swing.JButton(); HomeViewClient = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setMinimumSize(new java.awt.Dimension(1300, 869)); getContentPane().setLayout(null); AddC.setLayout(null); textCityClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textCityClientActionPerformed(evt); } }); AddC.add(textCityClient); textCityClient.setBounds(760, 570, 150, 40); textSurnameClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textSurnameClientActionPerformed(evt); } }); AddC.add(textSurnameClient); textSurnameClient.setBounds(760, 330, 150, 40); textGenderClient.setModel(new javax.swing.DefaultComboBoxModel<>(new String[]{"Male", "Female"})); textGenderClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textGenderClientActionPerformed(evt); } }); AddC.add(textGenderClient); textGenderClient.setBounds(760, 410, 150, 40); textNameClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textNameClientActionPerformed(evt); } }); AddC.add(textNameClient); textNameClient.setBounds(330, 330, 150, 40); textDataClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textDataClientActionPerformed(evt); } }); AddC.add(textDataClient); textDataClient.setBounds(330, 410, 150, 40); textEmailClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textEmailClientActionPerformed(evt); } }); AddC.add(textEmailClient); textEmailClient.setBounds(330, 570, 150, 40); textPhoneClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textPhoneClientActionPerformed(evt); } }); AddC.add(textPhoneClient); textPhoneClient.setBounds(760, 490, 150, 40); textCountryClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textCountryClientActionPerformed(evt); } }); AddC.add(textCountryClient); textCountryClient.setBounds(330, 490, 150, 40); AddC.add(jCheckBox1); jCheckBox1.setBounds(380, 640, 21, 40); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/databaseinterface/assets/AddClientFinal.png"))); // NOI18N AddC.add(jLabel1); jLabel1.setBounds(0, 10, 1300, 867); jButton1.setText("jButton1"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); AddC.add(jButton1); jButton1.setBounds(710, 730, 170, 40); HomeSearchRoom.setText("jButton1"); HomeSearchRoom.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { HomeSearchRoomActionPerformed(evt); } }); AddC.add(HomeSearchRoom); HomeSearchRoom.setBounds(1194, 60, 40, 40); LogoutSearchRoom.setText("jButton2"); LogoutSearchRoom.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LogoutSearchRoomActionPerformed(evt); } }); AddC.add(LogoutSearchRoom); LogoutSearchRoom.setBounds(1250, 60, 40, 40); jTabbedPane1.addTab("Add Client", AddC); DeleteC.setLayout(null); IDclient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { IDclientActionPerformed(evt); } }); DeleteC.add(IDclient); IDclient.setBounds(330, 170, 150, 50); DelDataClient.setEditable(false); DelDataClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DelDataClientActionPerformed(evt); } }); DeleteC.add(DelDataClient); DelDataClient.setBounds(330, 400, 150, 40); DelCountryClient.setEditable(false); DelCountryClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DelCountryClientActionPerformed(evt); } }); DeleteC.add(DelCountryClient); DelCountryClient.setBounds(330, 480, 150, 40); DelEmailClient.setEditable(false); DelEmailClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DelEmailClientActionPerformed(evt); } }); DeleteC.add(DelEmailClient); DelEmailClient.setBounds(330, 560, 150, 40); DelSurnameClient.setEditable(false); DelSurnameClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DelSurnameClientActionPerformed(evt); } }); DeleteC.add(DelSurnameClient); DelSurnameClient.setBounds(760, 330, 150, 40); DelGenderClient.setEditable(false); DelGenderClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DelGenderClientActionPerformed(evt); } }); DeleteC.add(DelGenderClient); DelGenderClient.setBounds(760, 410, 150, 40); DelCityClient.setEditable(false); DelCityClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DelCityClientActionPerformed(evt); } }); DeleteC.add(DelCityClient); DelCityClient.setBounds(760, 570, 150, 40); DelNameClient.setEditable(false); DelNameClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DelNameClientActionPerformed(evt); } }); DeleteC.add(DelNameClient); DelNameClient.setBounds(330, 330, 150, 40); DelPhoneClient.setEditable(false); DelPhoneClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DelPhoneClientActionPerformed(evt); } }); DeleteC.add(DelPhoneClient); DelPhoneClient.setBounds(760, 490, 150, 40); DeleteC.add(DelReservClient); DelReservClient.setBounds(380, 640, 21, 40); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/databaseinterface/assets/DeleteClient.png"))); // NOI18N DeleteC.add(jLabel2); jLabel2.setBounds(0, 10, 1300, 867); LogoutDeleteClient.setText("jButton2"); LogoutDeleteClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LogoutDeleteClientActionPerformed(evt); } }); DeleteC.add(LogoutDeleteClient); LogoutDeleteClient.setBounds(1250, 60, 40, 40); HomeDeleteClient.setText("jButton1"); HomeDeleteClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { HomeDeleteClientActionPerformed(evt); } }); DeleteC.add(HomeDeleteClient); HomeDeleteClient.setBounds(1194, 60, 40, 40); SearchDelClient.setText("jButton2"); SearchDelClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SearchDelClientActionPerformed(evt); } }); DeleteC.add(SearchDelClient); SearchDelClient.setBounds(530, 170, 180, 50); DeleteButClient.setText("jButton2"); DeleteButClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DeleteButClientActionPerformed(evt); } }); DeleteC.add(DeleteButClient); DeleteButClient.setBounds(1100, 170, 170, 50); jTabbedPane1.addTab("Delete Client", DeleteC); UpdateC.setLayout(null); UpdateC.add(jLabel6); jLabel6.setBounds(470, 710, 0, 0); UpdateC.add(ReservUpdateButt); ReservUpdateButt.setBounds(380, 640, 21, 40); CityUpdateC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CityUpdateCActionPerformed(evt); } }); UpdateC.add(CityUpdateC); CityUpdateC.setBounds(760, 560, 150, 40); PhoneUpdateC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { PhoneUpdateCActionPerformed(evt); } }); UpdateC.add(PhoneUpdateC); PhoneUpdateC.setBounds(760, 490, 150, 40); GenderUpdateC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { GenderUpdateCActionPerformed(evt); } }); UpdateC.add(GenderUpdateC); GenderUpdateC.setBounds(760, 410, 150, 40); SurnameUpdateC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SurnameUpdateCActionPerformed(evt); } }); UpdateC.add(SurnameUpdateC); SurnameUpdateC.setBounds(760, 330, 150, 40); CountryUpdateC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CountryUpdateCActionPerformed(evt); } }); UpdateC.add(CountryUpdateC); CountryUpdateC.setBounds(330, 480, 150, 40); NameUpdateC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NameUpdateCActionPerformed(evt); } }); UpdateC.add(NameUpdateC); NameUpdateC.setBounds(330, 330, 150, 40); DateUpdateC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DateUpdateCActionPerformed(evt); } }); UpdateC.add(DateUpdateC); DateUpdateC.setBounds(330, 400, 150, 40); EmailUpdateC.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EmailUpdateCActionPerformed(evt); } }); UpdateC.add(EmailUpdateC); EmailUpdateC.setBounds(330, 560, 150, 40); IDclient2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { IDclient2ActionPerformed(evt); } }); UpdateC.add(IDclient2); IDclient2.setBounds(330, 170, 150, 50); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/databaseinterface/assets/UpdateClient.png"))); // NOI18N UpdateC.add(jLabel3); jLabel3.setBounds(0, 10, 1300, 867); HomeUpdateClient.setText("jButton1"); HomeUpdateClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { HomeUpdateClientActionPerformed(evt); } }); UpdateC.add(HomeUpdateClient); HomeUpdateClient.setBounds(1194, 60, 40, 40); LogoutUpdateClient.setText("jButton2"); LogoutUpdateClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LogoutUpdateClientActionPerformed(evt); } }); UpdateC.add(LogoutUpdateClient); LogoutUpdateClient.setBounds(1250, 60, 40, 40); searchCupd.setText("jButton2"); searchCupd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchCupdActionPerformed(evt); } }); UpdateC.add(searchCupd); searchCupd.setBounds(540, 170, 160, 40); updateCbutt.setText("jButton2"); updateCbutt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { updateCbuttActionPerformed(evt); } }); UpdateC.add(updateCbutt); updateCbutt.setBounds(1100, 170, 170, 40); jTabbedPane1.addTab("Update Client", UpdateC); SearchC.setLayout(null); IDclient1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { IDclient1ActionPerformed(evt); } }); SearchC.add(IDclient1); IDclient1.setBounds(330, 170, 150, 50); SearchCityClient.setEditable(false); SearchCityClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SearchCityClientActionPerformed(evt); } }); SearchC.add(SearchCityClient); SearchCityClient.setBounds(760, 570, 150, 40); SearchNameClient.setEditable(false); SearchNameClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SearchNameClientActionPerformed(evt); } }); SearchC.add(SearchNameClient); SearchNameClient.setBounds(330, 330, 150, 40); SearchDataClient.setEditable(false); SearchDataClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SearchDataClientActionPerformed(evt); } }); SearchC.add(SearchDataClient); SearchDataClient.setBounds(330, 400, 150, 40); SearchCountryClient.setEditable(false); SearchCountryClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SearchCountryClientActionPerformed(evt); } }); SearchC.add(SearchCountryClient); SearchCountryClient.setBounds(330, 480, 150, 40); SearchEmailClient.setEditable(false); SearchEmailClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SearchEmailClientActionPerformed(evt); } }); SearchC.add(SearchEmailClient); SearchEmailClient.setBounds(330, 560, 150, 40); SearchSurnameClient.setEditable(false); SearchSurnameClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SearchSurnameClientActionPerformed(evt); } }); SearchC.add(SearchSurnameClient); SearchSurnameClient.setBounds(760, 330, 150, 40); SearchGenderClient.setEditable(false); SearchGenderClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SearchGenderClientActionPerformed(evt); } }); SearchC.add(SearchGenderClient); SearchGenderClient.setBounds(760, 410, 150, 40); SearchPhoneClient.setEditable(false); SearchPhoneClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SearchPhoneClientActionPerformed(evt); } }); SearchC.add(SearchPhoneClient); SearchPhoneClient.setBounds(760, 490, 150, 40); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/databaseinterface/assets/SearchClient.png"))); // NOI18N SearchC.add(jLabel4); jLabel4.setBounds(0, 10, 1300, 867); HomeSearchClient.setText("jButton1"); HomeSearchClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { HomeSearchClientActionPerformed(evt); } }); SearchC.add(HomeSearchClient); HomeSearchClient.setBounds(1194, 60, 40, 40); LogoutSearchClient.setText("jButton2"); LogoutSearchClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LogoutSearchClientActionPerformed(evt); } }); SearchC.add(LogoutSearchClient); LogoutSearchClient.setBounds(1250, 60, 40, 40); searchCButt.setText("jButton2"); searchCButt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchCButtActionPerformed(evt); } }); SearchC.add(searchCButt); searchCButt.setBounds(530, 170, 170, 50); jTabbedPane1.addTab("Search Client", SearchC); jPanel5.setLayout(null); ViewClient.setModel(new javax.swing.table.DefaultTableModel( new Object[][]{ {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null} }, new String[]{ "ID", "Name", "Surname", "Email", "Date", "Gender", "Country", "City", "Phone number" } ) { boolean[] canEdit = new boolean[]{ false, false, false, false, false, true, true, true, true }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); jScrollPane1.setViewportView(ViewClient); jPanel5.add(jScrollPane1); jScrollPane1.setBounds(0, 190, 1300, 402); jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/databaseinterface/assets/ViewClient.png"))); // NOI18N jPanel5.add(jLabel5); jLabel5.setBounds(0, 10, 1300, 867); LogoutViewClient.setText("jButton2"); LogoutViewClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LogoutViewClientActionPerformed(evt); } }); jPanel5.add(LogoutViewClient); LogoutViewClient.setBounds(1250, 60, 40, 40); HomeViewClient.setText("jButton1"); HomeViewClient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { HomeViewClientActionPerformed(evt); } }); jPanel5.add(HomeViewClient); HomeViewClient.setBounds(1194, 60, 40, 40); jTabbedPane1.addTab("View Patient", jPanel5); getContentPane().add(jTabbedPane1); jTabbedPane1.setBounds(0, 0, 1305, 891); pack(); }// </editor-fold>//GEN-END:initComponents private void HomeViewClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HomeViewClientActionPerformed // TODO add your handling code here: WorkerPortail workerPortail = new WorkerPortail(); workerPortail.setVisible(true); this.hide(); }//GEN-LAST:event_HomeViewClientActionPerformed private void LogoutViewClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogoutViewClientActionPerformed // TODO add your handling code here: Interface interFace = new Interface(); interFace.setVisible(true); this.hide(); }//GEN-LAST:event_LogoutViewClientActionPerformed private void LogoutSearchClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogoutSearchClientActionPerformed // TODO add your handling code here: Interface interFace = new Interface(); interFace.setVisible(true); this.hide(); }//GEN-LAST:event_LogoutSearchClientActionPerformed private void HomeSearchClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HomeSearchClientActionPerformed // TODO add your handling code here: WorkerPortail workerPortail = new WorkerPortail(); workerPortail.setVisible(true); this.hide(); }//GEN-LAST:event_HomeSearchClientActionPerformed private void LogoutUpdateClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogoutUpdateClientActionPerformed // TODO add your handling code here: Interface interFace = new Interface(); interFace.setVisible(true); this.hide(); }//GEN-LAST:event_LogoutUpdateClientActionPerformed private void HomeUpdateClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HomeUpdateClientActionPerformed // TODO add your handling code here: WorkerPortail workerPortail = new WorkerPortail(); workerPortail.setVisible(true); this.hide(); }//GEN-LAST:event_HomeUpdateClientActionPerformed private void LogoutDeleteClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogoutDeleteClientActionPerformed // TODO add your handling code here: Interface interFace = new Interface(); interFace.setVisible(true); this.hide(); }//GEN-LAST:event_LogoutDeleteClientActionPerformed private void HomeDeleteClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HomeDeleteClientActionPerformed // TODO add your handling code here: WorkerPortail workerPortail = new WorkerPortail(); workerPortail.setVisible(true); this.hide(); }//GEN-LAST:event_HomeDeleteClientActionPerformed private void LogoutSearchRoomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LogoutSearchRoomActionPerformed // TODO add your handling code here: Interface interFace = new Interface(); interFace.setVisible(true); this.hide(); }//GEN-LAST:event_LogoutSearchRoomActionPerformed private void HomeSearchRoomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HomeSearchRoomActionPerformed // TODO add your handling code here: WorkerPortail workerPortail = new WorkerPortail(); workerPortail.setVisible(true); this.hide(); }//GEN-LAST:event_HomeSearchRoomActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: sqlKeyClient clientKey = new sqlKeyClient(); int id = clientKey.id_incrementable(); if (new DBclassClient().add(id, textNameClient.getText(), textSurnameClient.getText(), Integer.parseInt(textDataClient.getText()), textCountryClient.getText(), textEmailClient.getText(), textGenderClient.getSelectedItem().toString(), Integer.parseInt(textPhoneClient.getText()), textCityClient.getText())) { if (jCheckBox1.isSelected()) { ReservationRoomForm reservRoomForm = new ReservationRoomForm(); reservRoomForm.setVisible(true); this.hide(); } this.hide(); System.out.println("Successfully Inserted"); } else { System.out.println("Error"); } }//GEN-LAST:event_jButton1ActionPerformed private void textCityClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textCityClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textCityClientActionPerformed private void textNameClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textNameClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textNameClientActionPerformed private void textDataClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textDataClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textDataClientActionPerformed private void textCountryClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textCountryClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textCountryClientActionPerformed private void textEmailClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textEmailClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textEmailClientActionPerformed private void textPhoneClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textPhoneClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textPhoneClientActionPerformed private void textGenderClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textGenderClientActionPerformed // TODO add your handling code here: String[] gender = {"Male", "Female"}; }//GEN-LAST:event_textGenderClientActionPerformed private void DelDataClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DelDataClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_DelDataClientActionPerformed private void DelCountryClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DelCountryClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_DelCountryClientActionPerformed private void DelEmailClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DelEmailClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_DelEmailClientActionPerformed private void DelCityClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DelCityClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_DelCityClientActionPerformed private void DelSurnameClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DelSurnameClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_DelSurnameClientActionPerformed private void DelNameClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DelNameClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_DelNameClientActionPerformed private void DelGenderClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DelGenderClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_DelGenderClientActionPerformed private void DelPhoneClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DelPhoneClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_DelPhoneClientActionPerformed private void IDclientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IDclientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_IDclientActionPerformed private void SearchDelClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchDelClientActionPerformed // TODO add your handling code here: Function f = new Function(); ResultSet rs = null; rs = f.find(IDclient.getText()); try { if (rs.next()) { DelNameClient.setText(rs.getString("Name")); DelSurnameClient.setText(rs.getString("Surname")); DelDataClient.setText(rs.getString("Date")); DelCountryClient.setText(rs.getString("Country")); DelEmailClient.setText(rs.getString("Email")); DelGenderClient.setText(rs.getString("Gender")); DelPhoneClient.setText(rs.getString("PhoneNum")); DelCityClient.setText(rs.getString("City")); } else { System.out.println("NO DATA"); } } catch (SQLException ex) { System.out.println(ex); } }//GEN-LAST:event_SearchDelClientActionPerformed private void DeleteButClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteButClientActionPerformed // TODO add your handling code here: Connection conn = null; try { conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); PreparedStatement ps = conn.prepareStatement("delete from clients where Id_client =?"); ps.setString(1, IDclient.getText()); ps.execute(); } catch (SQLException e) { System.out.println(e); } }//GEN-LAST:event_DeleteButClientActionPerformed private void IDclient1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IDclient1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_IDclient1ActionPerformed private void SearchCityClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchCityClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_SearchCityClientActionPerformed private void SearchNameClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchNameClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_SearchNameClientActionPerformed private void SearchDataClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchDataClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_SearchDataClientActionPerformed private void SearchCountryClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchCountryClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_SearchCountryClientActionPerformed private void SearchEmailClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchEmailClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_SearchEmailClientActionPerformed private void SearchSurnameClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchSurnameClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_SearchSurnameClientActionPerformed private void SearchGenderClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchGenderClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_SearchGenderClientActionPerformed private void SearchPhoneClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SearchPhoneClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_SearchPhoneClientActionPerformed private void searchCButtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchCButtActionPerformed Function f = new Function(); ResultSet rs = null; rs = f.find(IDclient1.getText()); try { if (rs.next()) { SearchNameClient.setText(rs.getString("Name")); SearchSurnameClient.setText(rs.getString("Surname")); SearchDataClient.setText(rs.getString("Date")); SearchCountryClient.setText(rs.getString("Country")); SearchEmailClient.setText(rs.getString("Email")); SearchGenderClient.setText(rs.getString("Gender")); SearchPhoneClient.setText(rs.getString("PhoneNum")); SearchCityClient.setText(rs.getString("City")); } else { System.out.println("NO DATA"); } } catch (SQLException ex) { System.out.println(ex); } }//GEN-LAST:event_searchCButtActionPerformed private void searchCupdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchCupdActionPerformed Function f = new Function(); ResultSet rs = null; rs = f.find(IDclient2.getText()); try { if (rs.next()) { NameUpdateC.setText(rs.getString("Name")); SurnameUpdateC.setText(rs.getString("Surname")); DateUpdateC.setText(rs.getString("Date")); CountryUpdateC.setText(rs.getString("Country")); EmailUpdateC.setText(rs.getString("Email")); GenderUpdateC.setText(rs.getString("Gender")); PhoneUpdateC.setText(rs.getString("PhoneNum")); CityUpdateC.setText(rs.getString("City")); } else { System.out.println("NO DATA"); } } catch (SQLException ex) { System.out.println(ex); } }//GEN-LAST:event_searchCupdActionPerformed private void IDclient2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IDclient2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_IDclient2ActionPerformed private void NameUpdateCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NameUpdateCActionPerformed // TODO add your handling code here: }//GEN-LAST:event_NameUpdateCActionPerformed private void DateUpdateCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DateUpdateCActionPerformed // TODO add your handling code here: }//GEN-LAST:event_DateUpdateCActionPerformed private void CountryUpdateCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CountryUpdateCActionPerformed // TODO add your handling code here: }//GEN-LAST:event_CountryUpdateCActionPerformed private void EmailUpdateCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmailUpdateCActionPerformed // TODO add your handling code here: }//GEN-LAST:event_EmailUpdateCActionPerformed private void SurnameUpdateCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SurnameUpdateCActionPerformed // TODO add your handling code here: }//GEN-LAST:event_SurnameUpdateCActionPerformed private void GenderUpdateCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GenderUpdateCActionPerformed // TODO add your handling code here: }//GEN-LAST:event_GenderUpdateCActionPerformed private void PhoneUpdateCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PhoneUpdateCActionPerformed // TODO add your handling code here: }//GEN-LAST:event_PhoneUpdateCActionPerformed private void CityUpdateCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CityUpdateCActionPerformed // TODO add your handling code here: }//GEN-LAST:event_CityUpdateCActionPerformed private void updateCbuttActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateCbuttActionPerformed // TODO add your handling code here: Connection conn; try { conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); String id = IDclient2.getText(); String name = NameUpdateC.getText(); String surname = SurnameUpdateC.getText(); int date = Integer.parseInt(DateUpdateC.getText()); String country = CountryUpdateC.getText(); String email = EmailUpdateC.getText(); String gender = GenderUpdateC.getText(); int phone = Integer.parseInt(PhoneUpdateC.getText()); String city = CityUpdateC.getText(); String sql = "update clients set Name ='" + name + "',Surname ='" + surname + "',Date ='" + date + "',Country='" + country + "',Email='" + email + "',Gender ='" + gender + "',PhoneNum='" + phone + "',City='" + city + "' where Id_client ='" + id + "' "; PreparedStatement ps = conn.prepareStatement(sql); ps.execute(); jLabel6.setText("Updated"); } catch (SQLException e) { System.out.println(e); } }//GEN-LAST:event_updateCbuttActionPerformed private void textSurnameClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textSurnameClientActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textSurnameClientActionPerformed public class Function { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; public ResultSet find(String s) { try { conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); ps = conn.prepareStatement("select * from clients where Id_client =?"); ps.setString(1, s); rs = ps.executeQuery(); } catch (SQLException e) { System.out.println(e); } return rs; } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ClientDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClientDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClientDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClientDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { new ClientDetails().setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel AddC; private javax.swing.JTextField CityUpdateC; private javax.swing.JTextField CountryUpdateC; private javax.swing.JTextField DateUpdateC; private javax.swing.JTextField DelCityClient; private javax.swing.JTextField DelCountryClient; private javax.swing.JTextField DelDataClient; private javax.swing.JTextField DelEmailClient; private javax.swing.JTextField DelGenderClient; private javax.swing.JTextField DelNameClient; private javax.swing.JTextField DelPhoneClient; private javax.swing.JCheckBox DelReservClient; private javax.swing.JTextField DelSurnameClient; private javax.swing.JButton DeleteButClient; private javax.swing.JPanel DeleteC; private javax.swing.JTextField EmailUpdateC; private javax.swing.JTextField GenderUpdateC; private javax.swing.JButton HomeDeleteClient; private javax.swing.JButton HomeSearchClient; private javax.swing.JButton HomeSearchRoom; private javax.swing.JButton HomeUpdateClient; private javax.swing.JButton HomeViewClient; private javax.swing.JTextField IDclient; private javax.swing.JTextField IDclient1; private javax.swing.JTextField IDclient2; private javax.swing.JButton LogoutDeleteClient; private javax.swing.JButton LogoutSearchClient; private javax.swing.JButton LogoutSearchRoom; private javax.swing.JButton LogoutUpdateClient; private javax.swing.JButton LogoutViewClient; private javax.swing.JTextField NameUpdateC; private javax.swing.JTextField PhoneUpdateC; private javax.swing.JCheckBox ReservUpdateButt; private javax.swing.JPanel SearchC; private javax.swing.JTextField SearchCityClient; private javax.swing.JTextField SearchCountryClient; private javax.swing.JTextField SearchDataClient; private javax.swing.JButton SearchDelClient; private javax.swing.JTextField SearchEmailClient; private javax.swing.JTextField SearchGenderClient; private javax.swing.JTextField SearchNameClient; private javax.swing.JTextField SearchPhoneClient; private javax.swing.JTextField SearchSurnameClient; private javax.swing.JTextField SurnameUpdateC; private javax.swing.JPanel UpdateC; private javax.swing.JTable ViewClient; private javax.swing.JButton jButton1; private javax.swing.JCheckBox jCheckBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JButton searchCButt; private javax.swing.JButton searchCupd; private javax.swing.JTextField textCityClient; private javax.swing.JTextField textCountryClient; private javax.swing.JTextField textDataClient; private javax.swing.JTextField textEmailClient; private javax.swing.JComboBox<String> textGenderClient; private javax.swing.JTextField textNameClient; private javax.swing.JTextField textPhoneClient; private javax.swing.JTextField textSurnameClient; private javax.swing.JButton updateCbutt; // End of variables declaration//GEN-END:variables }
package com.fundwit.sys.shikra.email; import javax.mail.MessagingException; import javax.mail.Part; import java.io.IOException; public class RawEmailMessage { private String from; private String recipient; private String subject; private Part body; public String getTextContent() throws IOException, MessagingException { return new PlainTextRender().render(body); } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getRecipient() { return recipient; } public void setRecipient(String recipient) { this.recipient = recipient; } public Part getBody() { return body; } public void setBody(Part body) { this.body = body; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } }
/* Test File */ package jenkins.model; import hudson.Util; import hudson.util.StreamTaskListener; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.Map; import java.util.TimeZone; import java.util.TreeMap; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import org.apache.commons.io.FileUtils; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestIdFromFilename{ String Filename = "[a-z0-9_. -]+"; @Test public void testIdEqual(){ jenkins.model.IdStrategy.CaseSensitive cs; cs = new jenkins.model.IdStrategy.CaseSensitive(); String result = cs.idFromFilename(Filename); assertEquals(result, "a-z0-9_. -"); } @Test public void testIdNull(){ jenkins.model.IdStrategy.CaseSensitive cs; cs = new jenkins.model.IdStrategy.CaseSensitive(); String result = cs.idFromFilename("$abcd"); assertEquals(result, "ꯍ"); } }
package com.vibexie.jianai.MiniPTR; import android.content.Context; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.RectF; import android.graphics.Shader.TileMode; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.AbsListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.vibexie.jianai.R; import java.lang.reflect.Field; import java.util.Timer; import java.util.TimerTask; /** * 下拉刷新的主框架 * @author vibexie.com * @version 1.0 */ public class MiniPTRFrame extends RelativeLayout implements OnTouchListener { /** * 下拉刷新 */ public static final int PULL_TO_REFRESH = 0; /** * 释放刷新 */ public static final int RELEASE_TO_REFRESH = 1; /** * 正在刷新 */ public static final int REFRESHING = 2; /** * 当前状态 */ private int state = PULL_TO_REFRESH; /** * 刷新回调接口 */ private MiniPTROnRefreshListener mListener; /** * 刷新成功还是失败 */ private int FRESHFLAG; /** * 刷新成功 */ public static final int REFRESH_SUCCEED = 0; /** * 刷新失败 */ public static final int REFRESH_FAIL = 1; /** * 下拉头布局 */ private View headView; /** * 内容布局 */ private View contentView; /** * 按下Y坐标,上一个事件点Y坐标 */ private float downY, lastY; /** * 下拉的距离 */ public float moveDeltaY = 0; /** * 释放刷新的距离 */ private float refreshDist = 200; /** * Timer */ private Timer timer; private MyTimerTask mTask; /** * 回滚速度 */ public float MOVE_SPEED = 8; /** * 第一次执行布局 */ private boolean isLayout = false; /** * 是否可以下拉 */ private boolean canPull = true; /** * 在刷新过程中滑动操作 */ private boolean isTouchInRefreshing = false; /** * 手指滑动距离与下拉头的滑动距离比,中间会随正切函数变化 */ private float radio = 2; /** * 下拉箭头的转180°动画 */ private RotateAnimation rotateAnimation; /** * 均匀旋转动画 */ private RotateAnimation refreshingAnimation; /** * 下拉的箭头 */ private View pullView; /** * 正在刷新的图标 */ private View refreshingView; /** * 刷新结果图标 */ private View stateImageView; /** * 刷新结果:成功或失败 */ private TextView stateTextView; /** * 是否正显示刷新结果,失败/成功 */ private boolean isShowingSuccessOrFail; /** * 执行自动回滚的handler */ Handler updateHandler = new Handler() { @Override public void handleMessage(Message msg) { /** * 回弹速度随下拉距离moveDeltaY增大而增大 */ MOVE_SPEED = (float) (8 + 5 * Math.tan(Math.PI / 2 / getMeasuredHeight() * moveDeltaY)); if (state == REFRESHING && moveDeltaY <= refreshDist && !isTouchInRefreshing) { /** * 正在刷新,且没有往上推的话则悬停,显示"正在刷新..." */ moveDeltaY = refreshDist; mTask.cancel(); } /** * 此时可以下拉 */ if (canPull){ moveDeltaY -= MOVE_SPEED; } if (moveDeltaY <= 0) { /** * 已完成回弹 */ moveDeltaY = 0; pullView.clearAnimation(); /** * 隐藏下拉头时有可能还在刷新,只有当前状态不是正在刷新时才改变状态 */ if (state != REFRESHING){ changeState(PULL_TO_REFRESH); } mTask.cancel(); } /** * 刷新整个view tree * @see View#requestLayout */ requestLayout(); } }; /** * 根据刷新结果处理UI效果的handler */ Handler refressHandler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); refreshingView.clearAnimation(); refreshingView.setVisibility(View.GONE); switch (FRESHFLAG) { case REFRESH_SUCCEED: /*刷新成功*/ stateImageView.setVisibility(View.VISIBLE); stateTextView.setText(R.string.refresh_succeed); stateImageView.setBackgroundResource(R.drawable.miniptr_success); break; case REFRESH_FAIL: /*刷新失败*/ stateImageView.setVisibility(View.VISIBLE); stateTextView.setText(R.string.refresh_fail); stateImageView.setBackgroundResource(R.drawable.miniptr_fail); break; default: break; } /** * 正在显示刷新结果,在onTouch()中劫持焦点,此时无法滑动AbslistView */ isShowingSuccessOrFail=true; /** * 刷新结果停留1秒,在头部显示刷新成功 */ new Handler() { @Override public void handleMessage(Message msg) { state = PULL_TO_REFRESH; hideHead(); } }.sendEmptyMessageDelayed(0, 1000); /** * 由于上面handle中hideHead()动画需要时间执行,所以得比上面handle晚一些执行 */ new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); /** * 已经显示完了刷新结果在,onTouch()中取消劫持 */ isShowingSuccessOrFail=false; } }.sendEmptyMessageDelayed(0,1200); } }; /** * 三个构造方法 * @param context */ public MiniPTRFrame(Context context) { this(context,null); } public MiniPTRFrame(Context context, AttributeSet attrs) { this(context,attrs,0); } public MiniPTRFrame(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } /** * 设置滑动监听器 * @param listener */ public void setOnRefreshListener(MiniPTROnRefreshListener listener) { mListener = listener; } /** * 相关的初始化,注意,其它view的初始化再onLayout()中 * @param context */ private void init(Context context) { /** * Timer任务 */ timer = new Timer(); mTask = new MyTimerTask(updateHandler); /** * 设置箭头旋转动画 */ rotateAnimation = (RotateAnimation) AnimationUtils.loadAnimation(context, R.anim.miniptr_reverse); /** * 设置刷新旋转动画 */ refreshingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(context, R.anim.miniptr_rotating); /** * 添加匀速转动效果 */ LinearInterpolator lir = new LinearInterpolator(); rotateAnimation.setInterpolator(lir); refreshingAnimation.setInterpolator(lir); } /** * 隐藏头布局 */ private void hideHead() { if (mTask != null) { mTask.cancel(); mTask = null; } /** * 重复执行task达到回弹效果 */ mTask = new MyTimerTask(updateHandler); timer.schedule(mTask, 0, 5); } class MyTimerTask extends TimerTask { Handler handler; public MyTimerTask(Handler handler) { this.handler = handler; } @Override public void run() { handler.sendMessage(handler.obtainMessage()); } } /** * 刷新成功 */ public void refreshSuccess(){ FRESHFLAG=REFRESH_SUCCEED; refressHandler.sendEmptyMessage(0); } /** * 刷新失败 */ public void refressFail(){ FRESHFLAG=REFRESH_FAIL; refressHandler.sendEmptyMessage(0); } /** * 对当前状态进行判断并该改变显示效果 * @param to */ private void changeState(int to) { state = to; switch (state) { case PULL_TO_REFRESH: /*下拉刷新*/ stateImageView.setVisibility(View.GONE); stateTextView.setText(R.string.pull_to_refresh); pullView.clearAnimation(); pullView.setVisibility(View.VISIBLE); break; case RELEASE_TO_REFRESH: /*释放刷新*/ stateTextView.setText(R.string.release_to_refresh); pullView.startAnimation(rotateAnimation); break; case REFRESHING: /*正在刷新*/ pullView.clearAnimation(); refreshingView.setVisibility(View.VISIBLE); pullView.setVisibility(View.INVISIBLE); refreshingView.startAnimation(refreshingAnimation); stateTextView.setText(R.string.refreshing); break; default: break; } } /** * 由父控件决定是否分发触屏事件,防止事件冲突 * @param ev * @return 返会true,则交给本view的onTouchEvent()处理 * 返回false,交给这个 view 的 interceptTouchEvent 方法来决定是否要拦截这个事件, * 如果 interceptTouchEvent 返回 true ,也就是拦截掉了,则交给它的 onTouchEvent 来处理, * 如果 interceptTouchEvent 返回 false ,那么就传递给子 view , * 由子 view 的 dispatchTouchEvent 再来开始这个事件的分发。 */ @Override public boolean dispatchTouchEvent(MotionEvent ev) { switch (ev.getActionMasked())/*当然ev.getAction()也是一样的*/ { case MotionEvent.ACTION_DOWN: downY = ev.getY(); /** * 记录点击触屏的Y坐标 */ lastY = downY; if (mTask != null) { mTask.cancel(); } /** * 按下点击的地方位于下拉头布局,由于我们没有对下拉头做事件响应, * 这时候它会给我们返回一个false导致接下来的事件不再分发进来。 * 所以我们不能交给父类分发,直接返回true * 这样这次点击的ACTION_MOVE和ACTION_UP均无效 */ if (ev.getY() < moveDeltaY){ return true; } break; case MotionEvent.ACTION_MOVE: /** * canPull这个值在底下onTouch中会根据ListView是否滑到顶部来改变,意思是是否可下拉 */ if (canPull) { /** * 对实际滑动距离做缩小,即阻尼效果,造成用力拉的感觉 */ moveDeltaY = moveDeltaY + (ev.getY() - lastY) / radio; if (moveDeltaY < 0){ moveDeltaY = 0; } if (moveDeltaY > getMeasuredHeight()){ moveDeltaY = getMeasuredHeight(); } if (state == REFRESHING) { /*正在刷新的时候触摸移动*/ isTouchInRefreshing = true; } } lastY = ev.getY(); /** * 根据下拉距离改变比例 */ radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight() * moveDeltaY)); /** * Call this when something has changed which has invalidated the layout of this view. * 重新布局 */ requestLayout(); if (moveDeltaY <= refreshDist && state == RELEASE_TO_REFRESH) { /** * 如果下拉距离没达到刷新的距离且当前状态是释放刷新,改变状态为下拉刷新 */ changeState(PULL_TO_REFRESH); } if (moveDeltaY >= refreshDist && state == PULL_TO_REFRESH) { changeState(RELEASE_TO_REFRESH); } if (moveDeltaY > 0) { /** * 防止下拉过程中误触发长按事件和点击事件 */ clearContentViewEvents(); /** * 正在下拉,不将touch事件分发给子view */ return true; } break; case MotionEvent.ACTION_UP: if (moveDeltaY > refreshDist){ /*正在刷新时往下拉释放后下拉头不隐藏*/ isTouchInRefreshing = false; } if (state == RELEASE_TO_REFRESH) { changeState(REFRESHING); /** * 执行刷新所要执行的任务 */ if (mListener != null){ mListener.onRefresh(); } } /** * 隐藏头部 */ hideHead(); default: break; } /** * 在这之前没有return的话,父类进行事件分发 */ return super.dispatchTouchEvent(ev); } /** * 通过反射AbsListView修改字段去掉长按事件和点击事件 */ private void clearContentViewEvents() { try { Field[] fields = AbsListView.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) if (fields[i].getName().equals("mPendingCheckForLongPress")) { /** * mPendingCheckForLongPress是AbsListView中的字段,通过反射获取并从消息列表删除,去掉长按事件 */ fields[i].setAccessible(true); contentView.getHandler().removeCallbacks((Runnable) fields[i].get(contentView)); } else if (fields[i].getName().equals("mTouchMode")) { /** * TOUCH_MODE_REST = -1, 这个可以去除点击事件 */ fields[i].setAccessible(true); fields[i].set(contentView, -1); } /** * 去掉焦点 */ ((AbsListView) contentView).getSelector().setState(new int[]{ 0 }); } catch (Exception e) { e.printStackTrace(); } } /* * 绘制contentView顶部,或者说头部布局底部的阴影效果,颜色值可以修改,这里使用了android绘图 * @see android.view.ViewGroup#dispatchDraw(android.graphics.Canvas) */ @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); /** * 没有出现头部View,不使用该效果,也没有必要使用该效果 */ if (moveDeltaY == 0){ return; } RectF rectF = new RectF(0, 0, getMeasuredWidth(), moveDeltaY); Paint paint = new Paint(); paint.setAntiAlias(true); /** * 这里使用线性梯度,阴影的高度为25,最底部颜色值为0x66000000,25高度处颜色为0x00000000,高度和颜色值也可以根据需要改变 */ LinearGradient linearGradient = new LinearGradient(0, moveDeltaY, 0, moveDeltaY - 25, 0x66000000, 0x00000000, TileMode.CLAMP); paint.setShader(linearGradient); paint.setStyle(Style.FILL); /** * 在moveDeltaY处往上变淡 */ canvas.drawRect(rectF, paint); } /** * 重载onLayout(),给子view布局 * @param changed * @param l * @param t * @param r * @param b */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { /** * 保证初始化一次 */ if (!isLayout) { headView = getChildAt(0); contentView = getChildAt(1); /** * view的相关初始化 */ pullView = headView.findViewById(R.id.pull_icon); stateTextView = (TextView) headView.findViewById(R.id.state_tv); refreshingView = headView.findViewById(R.id.refreshing_icon); stateImageView = headView.findViewById(R.id.state_iv); /** * 给AbsListView设置OnTouchListener */ contentView.setOnTouchListener(this); /** * 获取headView的高度,并赋值给refreshDist */ refreshDist = ((ViewGroup) headView).getChildAt(0).getMeasuredHeight(); isLayout = true; } if (canPull) { /**可以下拉,手动给子控件布局**/ headView.layout(0, (int) moveDeltaY - headView.getMeasuredHeight(), headView.getMeasuredWidth(), (int) moveDeltaY); contentView.layout(0, (int) moveDeltaY, contentView.getMeasuredWidth(), (int) moveDeltaY + contentView.getMeasuredHeight()); }else{ /*不可以下拉,默认布局*/ super.onLayout(changed, l, t, r, b); } } /** * 对dispatchTouchEvent()分发给onTouch的事件进行处理 * @param v * @param event * @return */ @Override public boolean onTouch(View v, MotionEvent event) { /** * 正在显示刷新结果,劫持 */ if(isShowingSuccessOrFail){ return true; } AbsListView alv = (AbsListView) v; if (alv.getCount() == 0) { /*没有item的时候也可以下拉刷新*/ canPull = true; } else if (alv.getFirstVisiblePosition() == 0 && alv.getChildAt(0).getTop() >= 0) { /*滑到AbsListView的顶部了,即第一个item可见且滑动到顶部*/ canPull = true; } else{ canPull = false; } /** * 此事件交给下一级AbsListView子类进行处理 */ return false; } }
package com.stem.dao; import com.stem.entity.WxTextReply; import com.stem.entity.WxTextReplyExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface WxTextReplyMapper { int countByExample(WxTextReplyExample example); int deleteByExample(WxTextReplyExample example); int deleteByPrimaryKey(Integer id); int insert(WxTextReply record); int insertSelective(WxTextReply record); List<WxTextReply> selectByExample(WxTextReplyExample example); WxTextReply selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") WxTextReply record, @Param("example") WxTextReplyExample example); int updateByExample(@Param("record") WxTextReply record, @Param("example") WxTextReplyExample example); int updateByPrimaryKeySelective(WxTextReply record); int updateByPrimaryKey(WxTextReply record); }
package 多线程.生产者消费者模式.实现阻塞队列; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; //https://juejin.im/post/5df8f1776fb9a015fe568013 public class MyBlockingQueue<E> { private static int DEFAULT_CAPITY=10; private ReentrantLock lock=new ReentrantLock(); private Condition notFull = lock.newCondition(); private Condition notEmpty = lock.newCondition(); private E[] elements; private int capcity; private int size; private int head;//取元素的下标 take private int tail;//放元素的小标 put //不传的话,设置默认容量 public MyBlockingQueue(){ this(DEFAULT_CAPITY); } public MyBlockingQueue(int capcity){ this.capcity=capcity; elements=(E[])new Object[capcity]; } public void put(E e){ lock.lock(); try { while (size==capcity){ notFull.await();//等待不满 } elements[tail]=e; ++size; ++tail; tail=tail==capcity?0:tail;//如果tail走到尾部,则指向0,从头开始放 } catch (InterruptedException ex) { ex.printStackTrace(); } finally { notEmpty.signal();//不空了 lock.unlock(); } } public E take() { lock.lock(); E e = (E)new Object(); try { while (size == 0) { notEmpty.await();//等待不空 } --size; e = elements[head++]; head = head == capcity ? 0 : head; }catch(InterruptedException exception){ exception.printStackTrace(); }finally { notFull.signalAll();//已经不满了 lock.unlock(); } return e; } }
package bonimed.vn.products; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by acv on 10/30/17. */ public class DataProduct { @SerializedName("ProductName") @Expose public String productName; @SerializedName("ProductType") @Expose public Integer productType; @SerializedName("BarCode") @Expose public Object barCode; @SerializedName("Description") @Expose public String description; @SerializedName("IsVAT") @Expose public Boolean isVAT; @SerializedName("Company") @Expose public String company; @SerializedName("MadeIn") @Expose public String madeIn; @SerializedName("IsSpecial") @Expose public Boolean isSpecial; @SerializedName("PicturePath") @Expose public String picturePath; @SerializedName("MinPrice") @Expose public Integer minPrice; @SerializedName("MaxPrice") @Expose public Integer maxPrice; @SerializedName("SalePrice") @Expose public Integer salePrice; @SerializedName("ImageFullPath") @Expose public String imageFullPath; @SerializedName("SellerId") @Expose public String sellerId; @SerializedName("SellerName") @Expose public String sellerName; @SerializedName("Quantity") @Expose public Integer quantity; @SerializedName("TotalQuantity") @Expose public Integer totalQuantity; @SerializedName("TotalSaleQuantity") @Expose public Integer totalSaleQuantity; @SerializedName("SellerCode") @Expose public Object sellerCode; @SerializedName("Image") @Expose public Object image; @SerializedName("Id") @Expose public String id; @SerializedName("CreatedDate") @Expose public String createdDate; @SerializedName("CreatedBy") @Expose public String createdBy; @SerializedName("LastModifiedDate") @Expose public String lastModifiedDate; @SerializedName("LastModifiedBy") @Expose public String lastModifiedBy; @SerializedName("Message") @Expose public Object message; @SerializedName("Status") @Expose public Integer status; @SerializedName("SecurityToken") @Expose public String securityToken; public boolean isChecked; public Integer orderQuantity = 1; }
package repita; import javax.swing.JOptionPane; public class Repita { public static void main(String[] args) { //JOptionPane.showMessageDialog(null, "Olá, mundo!", "Boas vindas", JOptionPane.WARNING_MESSAGE); //JOptionPane.showMessageDialog(null, "Você digitou o valor " +n); int n, s = 0; do{ n = Integer.parseInt(JOptionPane.showInputDialog(null, "<html>Informe um valor<br>" + "<em>(valor 0 interrompe)</em>: </html>")); s += n; } while (n != 0); JOptionPane.showMessageDialog(null, "A soma dos valores é igual a " +s); } }
package com.beiyelin.account.bean; import lombok.Data; /** * @Author: xinsh * @Description: 前端拿到code之后,提交到后台去拿token时,需要提交的内容 * @Date: Created in 8:38 2018/8/19. */ @Data public class OAuthTokenQuery { private String code; private String redirectUri; private String state; }
package com.sdavids; import com.sdavids.domain.Action; import com.sdavids.domain.ObjectType; import com.sdavids.domain.Verb; import com.sdavids.service.ActionsRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import javax.transaction.Transactional; import java.util.Arrays; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.isEmptyString; import static org.junit.Assert.assertThat; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WithMockUser("tester") @Transactional @ActiveProfiles("unit-test") @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = ActionRecorderApplication.class) public class ActionRecorderApplicationTests { @Autowired private ActionsRepository actionsRepository; @Autowired private WebApplicationContext context; private MockMvc mvc; @Before public void setUp() { mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } @Test public void createAction() throws Exception { String uri = "http://google.com"; long oldActionCount = actionsRepository.count(); mvc.perform(post("/").param("verb", Verb.PLAY.name()) .param("objectType", ObjectType.BOOKMARK.name()).param("objectUri", uri)) .andDo(print()) .andExpect(status().isCreated()) .andExpect(jsonPath("$.user").value("tester")) .andExpect(jsonPath("$.verb").value("PLAY")) .andExpect(jsonPath("$.objectType").value("BOOKMARK")) .andExpect(jsonPath("$.objectUri").value(uri)) .andExpect(jsonPath("$.id").isNumber()); assertThat("Action was not created", actionsRepository.count(), is(oldActionCount + 1)); } @Test public void getUserActionsForObjectUri() throws Exception { String uri = "https://foo.com"; actionsRepository.save(Arrays.asList( new Action(Verb.SAVE, ObjectType.BOOKMARK, uri), new Action(Verb.PLAY, ObjectType.BOOKMARK, uri), new Action(Verb.SAVE, ObjectType.BOOKMARK, "https://address.com"))); mvc.perform(get("/").param("objectUri", uri)) .andExpect(status().isOk()) .andExpect(jsonPath("$._embedded.actionList").value(hasSize(2))) .andExpect(jsonPath("$._embedded.actionList[0].user").value("tester")) .andExpect(jsonPath("$._embedded.actionList[0].verb").value("SAVE")) .andExpect(jsonPath("$._embedded.actionList[0].objectType").value("BOOKMARK")) .andExpect(jsonPath("$._embedded.actionList[0].objectUri").value(uri)) .andExpect(jsonPath("$._embedded.actionList[1].user").value("tester")) .andExpect(jsonPath("$._embedded.actionList[1].verb").value("PLAY")) .andExpect(jsonPath("$._embedded.actionList[1].objectType").value("BOOKMARK")) .andExpect(jsonPath("$._embedded.actionList[1].objectUri").value(uri)); } @Test public void getPageableUserAction() throws Exception { actionsRepository.save(Arrays.asList( new Action(Verb.SAVE, ObjectType.BOOKMARK, "https://foo.com"), new Action(Verb.PLAY, ObjectType.BOOKMARK, "https://foo2.com"), new Action(Verb.SAVE, ObjectType.BOOKMARK, "https://foo3.com"))); mvc.perform(get("/").param("page", "0").param("size", "2").param("sort", "verb,objectUri")) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$._embedded.actionList").value(hasSize(2))) .andExpect(jsonPath("$._embedded.actionList.[0].verb").value("PLAY")) .andExpect(jsonPath("$._embedded.actionList.[0].objectUri").value("https://foo2.com")) .andExpect(jsonPath("$._embedded.actionList.[1].verb").value("SAVE")) .andExpect(jsonPath("$._embedded.actionList.[1].objectUri").value("https://foo.com")) .andExpect(jsonPath("$._links.first.href").value("http://localhost?page=0&size=2&sort=verb,objectUri,asc")) .andExpect(jsonPath("$._links.next.href").value("http://localhost?page=1&size=2&sort=verb,objectUri,asc")) .andExpect(jsonPath("$._links.prev.href").doesNotExist()); mvc.perform(get("/").param("page", "1").param("size", "2").param("sort", "verb,objectUri")) .andExpect(status().isOk()) .andExpect(jsonPath("$._embedded.actionList").value(hasSize(1))) .andExpect(jsonPath("$._embedded.actionList.[0].verb").value("SAVE")) .andExpect(jsonPath("$._embedded.actionList.[0].objectUri").value("https://foo3.com")) .andExpect(jsonPath("$._links.first.href").value("http://localhost?page=0&size=2&sort=verb,objectUri,asc")) .andExpect(jsonPath("$._links.prev.href").value("http://localhost?page=0&size=2&sort=verb,objectUri,asc")) .andExpect(jsonPath("$._links.next.href").doesNotExist()); } @Test public void deleteAction() throws Exception { Action action = actionsRepository.saveAndFlush(new Action(Verb.SAVE, ObjectType.BOOKMARK, "https://foo.com")); long oldActionCount = actionsRepository.count(); mvc.perform(delete("/{id}", action.getId())) .andExpect(status().isNoContent()) .andExpect(content().string(isEmptyString())); assertThat("Action was not deleted", actionsRepository.count(), is(oldActionCount - 1)); } @Test public void doNotDeleteOtherUserAction() throws Exception { Action action = actionsRepository.saveAndFlush(new Action(Verb.SAVE, ObjectType.BOOKMARK, "https://foo.com")); long oldActionCount = actionsRepository.count(); mvc.perform(delete("/{id}", action.getId()).with(user("user"))) .andExpect(status().isNoContent()) .andExpect(content().string(isEmptyString())); assertThat("Action should not have been deleted by a user who didn't create the action.", actionsRepository.count(), is(oldActionCount)); } @Test public void badCreateParams() throws Exception { mvc.perform(post("/")).andExpect(status().isBadRequest()); } }
package com.jack.Uv; import com.jack.beans.ItemViewCount; import com.jack.beans.UserBehavior; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.datastream.DataStreamSource; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor; import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.api.windowing.triggers.Trigger; import org.apache.flink.streaming.api.windowing.triggers.TriggerResult; import org.apache.flink.streaming.api.windowing.windows.TimeWindow; import org.apache.flink.util.Collector; import redis.clients.jedis.Jedis; import java.net.URL; public class UvWithBloomFilter { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); URL resource = UniqueVisitor.class.getResource("/UserBehavior.csv"); DataStreamSource<String> inputData = env.readTextFile(resource.getPath()); SingleOutputStreamOperator<UserBehavior> dataStream = inputData.map(line -> { String[] field = line.split(","); return new UserBehavior(new Long(field[0]), new Long(field[1]), new Integer(field[2]), field[3], new Long(field[4])); }).assignTimestampsAndWatermarks(new AscendingTimestampExtractor<UserBehavior>() { @Override public long extractAscendingTimestamp(UserBehavior element) { return element.getTimeStamp()*1000L; } }); SingleOutputStreamOperator<ItemViewCount> process = dataStream .filter(data -> "pv".equals(data.getBehavior())) .timeWindowAll(Time.hours(1)) .trigger(new MyTrigger()) //自定义定时器状态 .process(new MyProcessCount()); process.print(); env.execute(); } public static class MyTrigger extends Trigger<UserBehavior, TimeWindow> { // 有数据过来 @Override public TriggerResult onElement(UserBehavior element, long timestamp, TimeWindow window, TriggerContext ctx) throws Exception { return TriggerResult.FIRE_AND_PURGE; //返回一个枚举类型 (boolean,boolean)(计算,清空) } // 处理时间发生变化 @Override public TriggerResult onProcessingTime(long time, TimeWindow window, TriggerContext ctx) throws Exception { return TriggerResult.CONTINUE; } // 时间时间发生变化 即wasterMask @Override public TriggerResult onEventTime(long time, TimeWindow window, TriggerContext ctx) throws Exception { return TriggerResult.CONTINUE; } // 清空自定义状态 @Override public void clear(TimeWindow window, TriggerContext ctx) throws Exception { } } // 自定义boolFilter public static class MyBloomFilter{ private Integer cap; // 位图大小 public MyBloomFilter(Integer cap) { this.cap = cap; } // 自定义hash public Long hashMap(String value, Integer seed){ Long result = 0L; for (int i = 0; i < value.length(); i++) { result = result * seed + value.charAt(i); } return result & (cap-1); } } public static class MyProcessCount extends ProcessAllWindowFunction<UserBehavior,ItemViewCount,TimeWindow>{ // 连接redis Jedis redisConn; MyBloomFilter myBloomFilter; @Override public void open(Configuration parameters) throws Exception { redisConn = new Jedis ("localhost", 6379); myBloomFilter = new MyBloomFilter(1 << 29); // 假设定义一个亿的数据,64MB位图 } @Override public void close() throws Exception { redisConn.close(); } @Override public void process(Context context, Iterable<UserBehavior> elements, Collector<ItemViewCount> out) throws Exception { Long userId = elements.iterator().next().getUserId(); String userName = userId.toString(); Long windowEnd = context.window().getEnd(); String CountKey = windowEnd.toString(); String CountHashName = "uv_count"; Long offset = myBloomFilter.hashMap(userName, 61); Boolean getbit = redisConn.getbit(CountKey, offset); if(!getbit){ // 不存在这个用户计入 redisConn.setbit(CountKey,offset,true); Long count = 0L; String countKey = redisConn.hget(CountHashName, CountKey); if( countKey!=null & !"".equals(countKey)){ count = Long.valueOf(countKey); } redisConn.hset(CountHashName, CountKey, String.valueOf(count + 1)); out.collect(new ItemViewCount(1L, windowEnd, count + 1)); } } } }
package com.atn.app.task; import java.util.ArrayList; import java.util.List; import android.os.AsyncTask; import android.os.AsyncTask.Status; import android.os.Build; import android.os.Handler; import android.os.Message; import com.atn.app.AtnApp; import com.atn.app.database.handler.DbHandler; import com.atn.app.datamodels.AtnOfferData; import com.atn.app.datamodels.AtnOfferData.VenueType; import com.atn.app.datamodels.AtnRegisteredVenueData; import com.atn.app.datamodels.VenueModel; import com.atn.app.httprequester.AtnBarRequest; import com.atn.app.provider.Atn; public class FollowingBarTask implements Runnable{ private static FollowingBarTask followingBarTask = null; private GetBarTask getBarTask = null; Thread localDbThread = null; private boolean isOnceLoadedFromServer = false; private static final List<Handler> listeners = new ArrayList<Handler>(); private FollowingBarTask(){ } public void setLoadFromServer(boolean server){ isOnceLoadedFromServer = !server; } public void registerListener(Handler listener){ if(listeners!=null&&!listeners.contains(listener)){ listeners.add(listener); } } public void unRegisterListener(Handler listener){ if(listeners!=null){ listeners.remove(listener); } } public static FollowingBarTask getInstance() { if(followingBarTask==null) { followingBarTask = new FollowingBarTask(); } return followingBarTask; } public void loadDataFromServer() { if(getBarTask==null||getBarTask.getStatus()==Status.FINISHED) { getBarTask = new GetBarTask(); getBarTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } public void refreshDataFromDb(){ //check if data is not loaded from server once then load if(!isOnceLoadedFromServer){ loadDataFromServer(); } if(localDbThread==null||!localDbThread.isAlive()){ localDbThread = new Thread(this); localDbThread.start(); } } public Status getStatus(){ if(getBarTask==null) return Status.FINISHED; return getBarTask.getStatus(); } private class GetBarTask extends AsyncTask<Void, List<AtnOfferData>, List<AtnOfferData>>{ private String errorMessage = "unKnow Error Occured"; @Override protected List<AtnOfferData> doInBackground(Void... params) { List<AtnOfferData> atnBar = null; AtnBarRequest newFavRequest = new AtnBarRequest(AtnApp.getAppContext()); if(newFavRequest.fetchFavorites()) { isOnceLoadedFromServer = true; atnBar = DbHandler.getInstance().getBulkFavoriteVenueDetails(); atnBar.addAll(Atn.Venue.getNonAtnVenue()); return prepareData(atnBar); } else { errorMessage = newFavRequest.getError(); } return null; } @Override protected void onPostExecute(List<AtnOfferData> result) { super.onPostExecute(result); sendMessageTohandlers(result,errorMessage); AtnIgMediaHadler.getInstance().load(); } } private void sendMessageTohandlers(List<AtnOfferData> result,String message){ for (Handler handler : listeners) { Message messsage = null; if (result == null) { messsage = Message.obtain(handler, 0, message); } else { messsage = Message.obtain(handler, 1, result); } messsage.sendToTarget(); } } private List<AtnOfferData> prepareData(List<AtnOfferData> regBars){ List<AtnOfferData> offerData = new ArrayList<AtnOfferData>(); for (AtnOfferData atnBar : regBars) { if(atnBar.getDataType()==VenueType.ANCHOR) { AtnRegisteredVenueData atnVenueData = (AtnRegisteredVenueData)atnBar; offerData.add(atnVenueData); if ((atnVenueData.getFsVenueModel() == null)) { offerData.addAll(atnVenueData.getBulkPromotion()); } } else { VenueModel venueModel = (VenueModel) atnBar; offerData.add(venueModel); } } return offerData; } //fetch data from local @Override public void run() { // Moves the current Thread into the background android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); List<AtnOfferData> atnBar = DbHandler.getInstance().getBulkFavoriteVenueDetails(); atnBar.addAll(Atn.Venue.getNonAtnVenue()); sendMessageTohandlers(prepareData(atnBar), null); } public void cancel(){ if(getBarTask!=null&&getBarTask.getStatus()!=Status.FINISHED){ getBarTask.cancel(true); } } }
package MRCategoriesRanking; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.Writable; public class AvgWritable implements Writable { private float rate; private int ratings; // number of ratings // private float avg = 0; AvgWritable() { } public float getRate() { return rate; } public void setRate(float rate) { this.rate = rate; } public int getRatings() { return ratings; } public void setRatings(int ratings) { this.ratings = ratings; } public void set(float rate, int ratings) { this.rate = rate; this.ratings = ratings; } public void readFields(DataInput in) throws IOException { ratings = in.readInt(); rate = in.readFloat(); } public void write(DataOutput out) throws IOException { out.writeInt(ratings); out.writeFloat(rate); } }
package com.kingdee.lightapp.service.mcloud; import net.sf.json.JSONObject; public interface McloudService { String getAccessToken(String appId, String appSecret) throws Exception; JSONObject getContextByTicket(String ticket) throws Exception; }
package com.taka.muzei.imgboard.posts; import android.net.Uri; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.taka.muzei.imgboard.Utils; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Post { private int id; private String hash; private String author; private String tags; @JsonSerialize(using = ToStringSerializer.class) private Uri directImageUrl; @JsonSerialize(using = ToStringSerializer.class) private Uri postUrl; private String fileSize; public static final Set<String> allowedExtensions = new HashSet<>(Arrays.asList("png", "jpeg", "jpg")); public Post(int id, String hash, String author, String tags, Uri directImageUrl, Uri postUrl, String fileSize) { this.id = id; this.hash = hash; this.author = author; this.tags = tags; this.directImageUrl = directImageUrl; this.postUrl = postUrl; this.fileSize = fileSize; } public int getId() { return id; } public String getHash() { return hash; } public String getTags() { return tags; } public String getAuthor() { return author; } public Uri getDirectImageUrl() { return directImageUrl; } public String getImageExtension() { return null == directImageUrl ? null : Utils.extractFileExtension(directImageUrl.toString()); } public Uri getPostUrl() { return null == postUrl ? getDirectImageUrl() : postUrl; } public boolean isValid() { return null != getHash() && null != getDirectImageUrl(); } public boolean isExtensionValid() { Uri imageUrl = getDirectImageUrl(); if(null == imageUrl) return false; final String extension = Utils.extractFileExtension(imageUrl.toString()); return allowedExtensions.contains(extension); } public int getFileSize() { try { return null == fileSize ? 0 : Integer.parseInt(fileSize); } catch (NumberFormatException e) { return 0; } } private <T> String fieldToString(T fieldValue) { return null == fieldValue ? "<null>" : fieldValue.toString(); } @Override public String toString() { return Utils.pojoToJsonString(this); } }