text
stringlengths
10
2.72M
package ro.siit.aut.gr4.exam.test.functional; import org.openqa.selenium.WebDriver; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; public class BaseTest { static WebDriver driver; File[] getListOfFiles(String directoryName) throws URISyntaxException { ClassLoader classLoader = getClass().getClassLoader(); URL path = classLoader.getResource(directoryName); String configPath = null; try { assert path != null; configPath = URLDecoder.decode(path.getFile(), "UTF-8"); System.out.println(configPath); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } assert configPath != null; File directory = new File(configPath); File[] files = directory.listFiles(); assert files != null; System.out.println("Found " + files.length + " files in " + directoryName + " folder"); return files; } }
package com.bytedance.sandboxapp.protocol.service.k; import com.bytedance.sandboxapp.b.b; import com.tt.miniapp.notification.MiniAppNotificationManager; public interface a extends b { c createPayNotification(); void payOnH5(String paramString1, String paramString2, b paramb, a parama); void reportPayInformation(); public static interface a { void a(); void a(String param1String); void b(); void c(); } public static final class b { public final int a; public final int b; public final int c; public final int d; public b(int param1Int1, int param1Int2, int param1Int3, int param1Int4) { this.a = param1Int1; this.b = param1Int2; this.c = param1Int3; this.d = param1Int4; } } public static final class c { private final MiniAppNotificationManager.NotificationEntity a; public c(MiniAppNotificationManager.NotificationEntity param1NotificationEntity) { this.a = param1NotificationEntity; } public final void a() { MiniAppNotificationManager.cancelPayNotification(this.a); } } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\sandboxapp\protocol\service\k\a.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package interviews.others; public class Streamlabs { // project demonstration }
package de.jmda.home.ui.vaadin.usermgmt; public class EventLogin { private String previousUsername; public EventLogin(String previousUsername) { super(); this.previousUsername = previousUsername; } public String getOldUser() { return previousUsername; } }
import java.util.HashSet; import java.util.Random; public class CountOfEqual { public static void main(String... args) { /*Integer[] an = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Integer[] bn = {1, 2, 3, 4, 5}; System.out.println(countOfEqual(an, bn));*/ Random random = new Random(); HashSet<Integer> hm = new HashSet<>(); int nc = 100; int mc = 5; int ok = 0, fail = 0; for (int j = 10; j <= 300; j += 10) { int n = nc * j, m = mc * j; Integer[] a = new Integer[n]; long count = 0; for (int i = 0; i < n; i++) { int k = random.nextInt(); if (hm.add(k)) { a[i] = k; System.out.print(k + " "); } else { i--; } } System.out.println(); Integer[] b = new Integer[m]; HashSet<Integer> hs = new HashSet<>(); for (int i = 0; i < m; i++) { int k = random.nextInt(); if (hs.add(k)) { b[i] = k; System.out.print(k + " "); if (hm.contains(k)) { count++; } } else { i--; } } System.out.println(); if (count == countOfEqual(a, b)) { System.out.println("Ok " + count); ok++; } else { System.out.println("Fail " + count); fail++; } } System.out.println("Ok = " + ok + " Fail = " + fail); } public static long countOfEqual(Integer[] a, Integer[] b) { int n = a.length; int m = b.length; if (n < m) { Integer[] c = a; a = b; b = c; } long count = 0; HashSet<Integer> hashSet = new HashSet<>(); for (Integer i : b) { hashSet.add(i); } for (Integer i : a) { count += hashSet.contains(i) ? 1 : 0; } return count; } }
package pages; import libs.myUtil; import org.apache.log4j.Logger; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import static libs.ConfigData.ui; import static libs.ConfigData.getCfgValue; import java.io.IOException; import libs.WebElementOnPage; public class SignUpPage { WebDriver driver; Logger log; WebElementOnPage webElementOnPage; /** * CONSTRUCTOR for SignUpPage * @param externalDriver */ public SignUpPage(WebDriver externalDriver){ this.driver = externalDriver; log = Logger.getLogger(getClass()); webElementOnPage = new WebElementOnPage(driver); } /** * Method opens page SignUp */ public void openSignUpPage() { try { webElementOnPage.openBrowseAndURL(getCfgValue("MAIN_URL") + "/sign-up/"); log.info("Browser and url " + getCfgValue("MAIN_URL") + "/sign-up/" + "was opened!"); } catch (IOException e) { log.error(e); } } /** * Method closes page SignUP */ public void closeSignUpPage(){ webElementOnPage.closeBrowser(); log.info("Page SignUP and browser was closed!"); } /** * Method types first name into input FirstName * @param firstName * @return */ public boolean typeFirstNameIntoInputFirstName(String firstName) { webElementOnPage.wait.until(ExpectedConditions.elementToBeClickable( driver.findElement(ui("SignUP.FirstName.Input")))); boolean tempElement= webElementOnPage.typeTextIntoInput(firstName, "SignUP.FirstName.Input"); log.info("First name was typed in input FirstName: " + tempElement); return tempElement; } /** * Method types last name into input LastName * @param lastName * @return */ public boolean typeLastNameIntoInputLastName(String lastName) { boolean tempElement= webElementOnPage.typeTextIntoInput(lastName, "SignUP.LastName.Input"); webElementOnPage.clickLink("SignUP.LastName.Input"); log.info("Last name was typed into input LastName: " + tempElement); return tempElement; } /** * Method type email into input Email * @param email * @return */ public boolean typeEmailIntoInputEmail(String email) { boolean tempElement= webElementOnPage.typeTextIntoInput(email, "SignUP.Email.Input"); log.info("Email was typed into input Email: " + tempElement); return tempElement; } /** * Method types random email into input Email * @return */ public boolean typeRandomEmailIntoInputEmail(){ String randomEmail = String.valueOf(myUtil.getNumFromDate()) + "@gmail.com"; boolean tempElement= webElementOnPage.typeTextIntoInput(randomEmail, "SignUP.Email.Input"); log.info("Random email " + randomEmail + " was typed into input email: " + tempElement); return tempElement; } /** * Method types password into input Password * @param passw * @return */ public boolean typePasswIntoInputPassword(String passw) { boolean tempElement= webElementOnPage.typeTextIntoInput(passw, "SignUP.Password.Input"); log.info("Password was typed into input Password: " + tempElement); return tempElement; } /** * Method have checked checkbox Updates * @return */ public boolean checkUpdatesCheckBox() { boolean tempElement= webElementOnPage.setActionInCheckBox("Check", "SignUP.CheckBoxUpdates.Input"); log.info("Check box \"Updates\" was checked: " + tempElement); return tempElement; } /** * Method have unchecked checkbox Updates * @return */ public boolean unCheckUpdatesCheckBox() { boolean tempElement= webElementOnPage.setActionInCheckBox("Uncheck", "SignUP.CheckBoxUpdates.Input"); log.info("Check box \"Updates\" was unchecked: " + tempElement); return tempElement; } /** * Method clicks NewFeatures link * @return */ public boolean clickNewFeaturesLink() { boolean tempElement= webElementOnPage.clickLink("SignUP.NewFeatures.Link"); log.info("Link NewFeatures was clicked: " + tempElement); return tempElement; } /** * Method clicks on SignUP button * @return */ public boolean clickSignUPButton() { boolean tempElement= webElementOnPage.clickButton("SignUP.SignUpSubmit.Button"); log.info("Button \"Sign Up\" was clicked: " + tempElement); return tempElement; } /** * Method clicks on TermsOfService link * @return */ public boolean clickTermsOfServiceLink() { boolean tempElement= webElementOnPage.clickLink("SignUP.TermsOfService.Link"); log.info("Link \"Terms of Service\" was clicked: " + tempElement); return tempElement; } /** * Method clicks on GetHelp button * @return */ public boolean clickGetHelpButton() { boolean tempElement= webElementOnPage.clickButton("SignUP.GetHelp.Button"); log.info("BUtton \"GetHelp\" was clicked: " + tempElement); return tempElement; } /** * Method checks is ErrorMessages on page * @return */ public boolean isErrorMessages() { boolean tempElement= webElementOnPage.isElementOnPage("SignUP.Error.Message"); log.info("Error message on page: " + tempElement); return tempElement; } /** * Method press TAB "numerosity" times * @param numerosity * @return */ public boolean pressTabOnPage(int numerosity){ webElementOnPage.pressTabKey(numerosity); log.info("TAB was pressed " + numerosity + "times"); return true; } /** * Method press ENTER "numerosity" times * @param numerosity * @return */ public boolean pressEnterOnPage(int numerosity){ webElementOnPage.pressEnter(numerosity); log.info("Enter was pressed " + numerosity + "times"); return true; } public boolean isAppSelectionOnPage() { webElementOnPage.wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(ui("SignUP.SearchApp.Input")))); boolean tempElement = webElementOnPage.isElementOnPage("SignUP.SearchApp.Input"); return tempElement; } /** * Method clicks button Continue * @return */ public boolean clickContinueButton() { boolean tempElement = webElementOnPage.clickButton("SignUP.Continue.Button"); return tempElement; } /** * Method clicks button "No Thanks" * @return */ public boolean clickNoThanksButton() { boolean tempElement = webElementOnPage.clickButton("SignUP.NoThanks.Button"); return tempElement; } public boolean isUserIconOnPage() { boolean tempElement = webElementOnPage.isElementOnPage("SignUP.UserIcon.Img"); return tempElement; } }
package com.vuelos.domain; import java.io.Serializable; import java.util.Date; import javax.persistence.*; @Entity @Table public class Clientes implements Serializable{ @Column(name="correo_electronico") private String correo_electronico; @Column(name="password") private String password; @Column(name="numero_tarjeta") private Integer numero_tarjeta; @Column(name="tipo_vuelos") private Date fecha_expiracion; @Id @Column(name="rut_cliente") private String rut; @Column(name="nombre_cliente") private String nombre; @Column(name="fecha_nacimiento") private Date fecha_nacimiento; @Column(name="fecha_registro") private Date fecha_registro; @Column(name="cliente_frecuete") private Boolean cliente_frecuete; @Column(name="bool_activo") private Boolean bool_activo; public Clientes() { } public String getCorreo_electronico() { return correo_electronico; } public void setCorreo_electronico(String correo_electronico) { this.correo_electronico = correo_electronico; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getNumero_tarjeta() { return numero_tarjeta; } public void setNumero_tarjeta(Integer numero_tarjeta) { this.numero_tarjeta = numero_tarjeta; } public Date getFecha_expiracion() { return fecha_expiracion; } public void setFecha_expiracion(Date fecha_expiracion) { this.fecha_expiracion = fecha_expiracion; } public String getRut() { return rut; } public void setRut(String rut) { this.rut = rut; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public Date getFecha_nacimiento() { return fecha_nacimiento; } public void setFecha_nacimiento(Date fecha_nacimiento) { this.fecha_nacimiento = fecha_nacimiento; } public Date getFecha_registro() { return fecha_registro; } public void setFecha_registro(Date fecha_registro) { this.fecha_registro = fecha_registro; } public Boolean getCliente_frecuete() { return cliente_frecuete; } public void setCliente_frecuete(Boolean cliente_frecuete) { this.cliente_frecuete = cliente_frecuete; } public Boolean getBool_activo() { return bool_activo; } public void setBool_activo(Boolean bool_activo) { this.bool_activo = bool_activo; } }
package com.example.coronapp; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.test.context.SpringBootTest; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest public class ParameterizedTest { @org.junit.jupiter.params.ParameterizedTest @ValueSource(ints = { 1, 2, 3 }) void testParametreAvecValueSource(int valeur) { assertThat(valeur + valeur).isEqualTo(valeur * 2); } }
package negocio.material; import java.util.Collection; public interface SAMaterial { public Integer altaMaterial(TransferMaterial transferMaterial) throws ClassNotFoundException, Exception; public void bajaMaterial(Integer idMaterial) throws ClassNotFoundException, Exception; public Integer modificarMaterial(TransferMaterial transferMaterial) throws ClassNotFoundException, Exception; public Collection<TransferMaterial> listarMaterial() throws ClassNotFoundException, Exception; public TransferMaterial mostrarMaterial(Integer id) throws ClassNotFoundException, Exception; }
package net.rainmore.persistent.events; import net.rainmore.common.persistent.AbstractEntity; import org.hibernate.event.internal.DefaultSaveOrUpdateEventListener; import org.hibernate.event.spi.SaveOrUpdateEvent; public class EntitySaveOrUpdateListener extends DefaultSaveOrUpdateEventListener { @Override public void onSaveOrUpdate(SaveOrUpdateEvent event) { if (event.getObject() instanceof AbstractEntity) { AbstractEntity record = (AbstractEntity) event.getObject(); if (record.getSysCreatedDate() == null) record.prePersist(); else record.preUpdate(); // // set the Updated date/time // record.setSysUpdatedDate(new DateTime()); // // // set the Created date/time // if (record.getSysCreatedDate() == null) { // record.setSysCreatedDate(new DateTime()); // } } } }
package com.luban.command.materialprocurement.service.impl; import com.luban.command.materialprocurement.dao.MaterialProcurementDao; import com.luban.command.materialprocurement.service.MaterialProcurementService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Calendar; import java.util.HashMap; import java.util.List; /** * @ClassName MaterialProcurementServiceImpl * @Author yuanlei * @Date 2018/10/16 10:35 * @Version 1.0 **/ @Service("materialprocurementService") public class MaterialProcurementServiceImpl implements MaterialProcurementService { @Autowired private MaterialProcurementDao materialProcurementDao; @Override public HashMap<String, Object> getMaterialProcurement() { HashMap<String, Object> MaterialProcurementMap = new HashMap<>(); //返回采购总额 double totalPurchase = materialProcurementDao.queryTotalPurchase(); //返回采集总额 double totalCollect = materialProcurementDao.queryTotalCollect(); //根据材料名称返回大宗材料的数量 //查询所有的材料名称 List<String> materialNames = materialProcurementDao.queryMaterialName(); HashMap<String, Integer> materialmap = new HashMap<>(); Integer materialNum = 0; for (String materialName : materialNames) { materialNum = materialProcurementDao.queryMaterialNumByName(materialName); //materialName材料名称,materialNum材料数量 materialmap.put(materialName,materialNum); } //返回采购地区的占比 HashMap<String, Integer> areaAndNum = new HashMap<>(); Integer areaNum = 0; List<String> areaNames = materialProcurementDao.queryAreaName(); //根据地区的名称来查询数量 for (String areaName : areaNames) { areaNum = materialProcurementDao.queryAreaNumByName(areaName); areaAndNum.put(areaName,areaNum); } //返回每年的总采购额 //查询出最大年份和最小年份 // Calendar MaxDate = materialProcurementDao.queryMaxYear(); // Calendar MinDate = materialProcurementDao.queryMinYear(); // // int maxyear = MaxDate.get(Calendar.YEAR); // int minyear = MinDate.get(Calendar.YEAR); HashMap<Integer, Double> totalPurchaseMap = new HashMap<>(); // for (int year = minyear;year<=maxyear;year++){ //根据年份查找该年份的总采购额,先按照年份分组,在查询出每组的采购总额 List<Double> totalPurchaseByTime = materialProcurementDao.queryTotalPurchaseByTime(); // //year年份,totalPurchaseByTime该年份的总采购额 // totalPurchaseMap.put(year,totalPurchaseByTime); // } //返回采购方式预算的占比(招标类,竞争性谈判,单一来源,其他) //查询所有的采购方式的数量 List<String> purchaseWays = materialProcurementDao.queryPurchaseWay(); HashMap<String, Object> purchaseWaymap = new HashMap<>(); Integer purchaseNum = 0; for (String purchaseWay : purchaseWays) { //根据采购方式获取各采购方式的数量 purchaseNum = materialProcurementDao.queryPurchaseNumByPurchaseWay(purchaseWay); purchaseWaymap.put(purchaseWay,purchaseNum); } MaterialProcurementMap.put("totalPurchase",totalPurchase); MaterialProcurementMap.put("totalCollect",totalCollect); MaterialProcurementMap.put("materialmap",materialmap); MaterialProcurementMap.put("areaAndNum",areaAndNum); MaterialProcurementMap.put("totalPurchaseMap",totalPurchaseMap); MaterialProcurementMap.put("purchaseWaymap",purchaseWaymap); return MaterialProcurementMap; } }
package jc.sugar.JiaHui.entity; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.util.JMeterUtils; import java.util.ArrayList; import java.util.List; /** * @Code 谢良基 2021/7/2 */ public class SugarJMeterSamplerResult extends SampleResult{ private String resultType; private List<SugarJMeterSamplerResult> childResults; public SugarJMeterSamplerResult(SampleResult sampleResult){ super(sampleResult); extractSampleResult(sampleResult); } private void extractSampleResult(SampleResult sampleResult){ String sampleResultClass = sampleResult.getClass().getName(); this.resultType = sampleResultClass.substring(1 + sampleResultClass.lastIndexOf('.')) + " " + JMeterUtils.getResString("view_results_fields"); this.childResults = new ArrayList<>(); for(SampleResult subSampleResult: sampleResult.getSubResults()){ childResults.add(new SugarJMeterSamplerResult(subSampleResult)); } } public String getResultType() { return resultType; } public void setResultType(String resultType) { this.resultType = resultType; } public List<SugarJMeterSamplerResult> getChildResults() { return childResults; } public void setChildResults(List<SugarJMeterSamplerResult> childResults) { this.childResults = childResults; } }
/** * @author Paweł Włoch ©SoftLab * @date 10 sty 2019 */ package com.softlab.ubscoding.cli.menu.commands; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(value = 0) public class MenuHeaderCmd implements MenuCommand { private final static String menuText = "----- Bitcoin notification client -----\nPlease choose a menu item:"; /* * (non-Javadoc) * * @see com.softlab.ubscoding.cli.menu.MenuCommand#print() */ @Override public void print(StringBuffer buffer) { buffer.append(menuText).append('\n'); } /* (non-Javadoc) * @see com.softlab.ubscoding.cli.menu.MenuCommand#execute() */ @Override public void execute() { // do nothing } }
package cityUnknown; public class Inn { }
package com.gtfs.dto; import java.io.Serializable; import java.util.Date; import com.gtfs.bean.LicPisMst; public class LicCmsMstDto implements Serializable{ private Long id; private Double amount; private String cmsNo; private Long createdBy; private Date createdDate; private String deleteFlag; private Long deletedBy; private Date deletedDate; private Long modifiedBy; private Date modifiedDate; private String payMode; private LicPisMst licPisMst; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public String getCmsNo() { return cmsNo; } public void setCmsNo(String cmsNo) { this.cmsNo = cmsNo; } public Long getCreatedBy() { return createdBy; } public void setCreatedBy(Long createdBy) { this.createdBy = createdBy; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public String getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } public Long getDeletedBy() { return deletedBy; } public void setDeletedBy(Long deletedBy) { this.deletedBy = deletedBy; } public Date getDeletedDate() { return deletedDate; } public void setDeletedDate(Date deletedDate) { this.deletedDate = deletedDate; } public Long getModifiedBy() { return modifiedBy; } public void setModifiedBy(Long modifiedBy) { this.modifiedBy = modifiedBy; } public Date getModifiedDate() { return modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } public String getPayMode() { return payMode; } public void setPayMode(String payMode) { this.payMode = payMode; } public LicPisMst getLicPisMst() { return licPisMst; } public void setLicPisMst(LicPisMst licPisMst) { this.licPisMst = licPisMst; } @Override public boolean equals(Object obj) { LicCmsMstDto licCmsMstDto = (LicCmsMstDto) obj; return (payMode+amount).equals(licCmsMstDto.getPayMode()+licCmsMstDto.getAmount()); } @Override public int hashCode() { return (payMode+amount).hashCode(); } }
package SystemDesign; import java.util.Map; import java.util.Random; import java.util.Scanner; import java.util.HashMap; /** * @author Vignesh Kumar Subramanian * * * Assumptions and implementation details: * * 1. ChutesAndLadder is the main class, which has "Board" and the "Player" has nested class. * 2. "Player" class has "spinTheSpinner" function which every player uses to play his turn. * 3. Assumed board to be single-dimension array of length = 100. * 4. "Board" class has ladders and chutes hashmap, which captures the next position of player, once he encounters * a ladder or chute. * * * Nice to have: * 1. Capability of dynamically setting the ladders and chutes for each game, such that we can have different boards. * */ public class ChutesAndLadder { class Board { protected int[] board; protected Map<Integer, Integer> ladders; protected Map<Integer, Integer> chutes; Board() { board = new int[100]; ladders = new HashMap<>(); chutes = new HashMap<>(); } } class Player { // Position of the player in the board. private int currentPositionOfPlayer; private String playerName; Player(String name) { this.playerName = name; this.currentPositionOfPlayer = -1; } /* * spinTheSpinner - Player uses this function to spin the spinner, which is equivalent of playing a dice. * input - none * output- int (The outcome will be equal probablity of 1-6 inclusive) */ protected int spinTheSpinner() { Random rand = new Random(); int result = rand.nextInt(7); if(result == 0) result++; return result; } /* * movePawn - Player uses this function to move his pawn from current pos to new position. * input - currPos(Current position of player), count(number of steps) * output - int (new position) */ protected int movePawn(int currPos, int count) { int newPosition = currPos+count; if(newPosition > 99) return -1; this.currentPositionOfPlayer = newPosition; return this.currentPositionOfPlayer; } protected int getCurrentPosition() { return this.currentPositionOfPlayer; } protected void setCurrentPosition(int pos) { this.currentPositionOfPlayer = pos; } protected String getPlayerName() { return this.playerName; } } protected int numberOfTurns; protected int numberOfPlayers; protected Board boardObj; protected Player[] players; private boolean gameCompleted; private String winner; ChutesAndLadder(int numberOfPlayers, String[] names) { boardObj = new Board(); gameCompleted = false; numberOfTurns = 0; players = new Player[numberOfPlayers]; // set the number of players for(int i=0; i < numberOfPlayers; i++) { Player player = new Player(names[i]); players[i] = player; } } protected boolean isGameCompleted() { return this.gameCompleted; } protected void setGameCompleted() { this.gameCompleted = true; } protected void announceWinner() { System.out.println("The Winner is: " + this.winner); } protected void setWinner(String playerName) { this.winner = playerName; } /* * startGame - Function used by the system to simulate the game of Chutes and Ladders * input - none * output - none */ protected void startGame() { while(!isGameCompleted()) { for(int playerNumber = 0; playerNumber < players.length; playerNumber++) { Player player = players[playerNumber]; String playerName = player.getPlayerName(); int numberOfSquaresToHop = player.spinTheSpinner(); int currentPositionOfPlayer = player.getCurrentPosition(); int nextPossiblePositionOfPlayer = player.movePawn(currentPositionOfPlayer, numberOfSquaresToHop); // Printing each turn as it goes.. System.out.print(++numberOfTurns + " : " + playerName + " " + (currentPositionOfPlayer+1) + " ---> " + (nextPossiblePositionOfPlayer+1)); //if player reaches 100th square, declare player winner if(checkGameIsAlreadyOver(nextPossiblePositionOfPlayer)) { System.out.println(); setGameCompleted(); setWinner(playerName); break; } // scenario when position of player goes beyond 100, skip chance else if(nextPossiblePositionOfPlayer == -1) { System.out.println(); continue; } //check in ladders map, if there is a ladder from current position else if(boardObj.ladders.containsKey(nextPossiblePositionOfPlayer)) { int positionElevatedFromLadder = boardObj.ladders.get(nextPossiblePositionOfPlayer); player.setCurrentPosition(positionElevatedFromLadder); nextPossiblePositionOfPlayer = positionElevatedFromLadder; System.out.print(" ---LADDER--- " + (nextPossiblePositionOfPlayer+1)); if(checkGameIsAlreadyOver(nextPossiblePositionOfPlayer)) { System.out.println(); setGameCompleted(); setWinner(playerName); break; } } //check in chutes map, if there is a chute from current position else if(boardObj.chutes.containsKey(nextPossiblePositionOfPlayer)) { int positionElevatedFromLadder = boardObj.chutes.get(nextPossiblePositionOfPlayer); player.setCurrentPosition(positionElevatedFromLadder); nextPossiblePositionOfPlayer = positionElevatedFromLadder; System.out.print(" ---CHUTE--- " + (nextPossiblePositionOfPlayer+1)); } System.out.println(); } } } protected boolean checkGameIsAlreadyOver(int position) { if(position == boardObj.board.length-1) { return true; } return false; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner reader = new Scanner(System.in); System.out.print("(Note: min 2 players, max 4 players) Enter number of players: "); int numberOfPlayers = reader.nextInt(); // max 4 players String[] names = new String[numberOfPlayers]; System.out.println("Enter their names: "); for(int i=0; i<numberOfPlayers; i++) { System.out.println("Player " + (i+1) + ": "); names[i] = reader.next(); } reader.close(); ChutesAndLadder game = new ChutesAndLadder(numberOfPlayers, names); //Add the ladders in the board game.boardObj.ladders.put(0, 37); game.boardObj.ladders.put(3, 13); game.boardObj.ladders.put(8, 30); game.boardObj.ladders.put(20, 41); game.boardObj.ladders.put(27, 83); game.boardObj.ladders.put(35, 43); game.boardObj.ladders.put(50, 66); game.boardObj.ladders.put(70, 90); game.boardObj.ladders.put(79, 99); //Add the chutes in the board game.boardObj.chutes.put(15, 5); game.boardObj.chutes.put(48, 10); game.boardObj.chutes.put(46, 26); game.boardObj.chutes.put(55, 52); game.boardObj.chutes.put(63, 59); game.boardObj.chutes.put(61, 18); game.boardObj.chutes.put(86, 23); game.boardObj.chutes.put(92, 72); game.boardObj.chutes.put(94, 74); game.boardObj.chutes.put(97, 77); //Start the game System.out.println(); System.out.println("Game Starts......."); System.out.println(); game.startGame(); game.announceWinner(); } }
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 luma <stubma@163.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq.ui.helper; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import edu.tsinghua.lumaqq.LumaQQ; /** * 读取群分类二进制文件的工具类 * * @author luma */ public class ClusterCategoryTool { public static final int ENTRY_COUNT = 10000; public static final int HEADER_LENGTH = 4; public static final int ENTRY_LENGTH = 12; private RandomAccessFile file; private static final List<String> sTemp = new ArrayList<String>(); private static final List<Integer> iTemp = new ArrayList<Integer>(); private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final Integer[] EMPTY_INTEGER_ARRAY = new Integer[0]; private static final StringBuilder sb = new StringBuilder(); public void init() { try { file = new RandomAccessFile(LumaQQ.CLUSTER_CATEGORY_FILE, "r"); } catch(IOException e) { } } public void dispose() { try { if(file != null) file.close(); } catch(IOException e) { } } public String getName(int id) { if(id < 1 || id > ENTRY_COUNT || file == null) return ""; else { try { file.seek(HEADER_LENGTH + ENTRY_LENGTH * id); file.seek(file.readInt() + 12); return file.readUTF(); } catch(IOException e) { return ""; } } } public String[] getSubCategory(int parentId) { if(file == null) return EMPTY_STRING_ARRAY; sTemp.clear(); try { int subId = getFirstSubId(parentId); while(subId > 0) { sTemp.add(getName(subId)); subId = getNextSubId(subId); } return sTemp.toArray(new String[sTemp.size()]); } catch(IOException e) { return EMPTY_STRING_ARRAY; } } public Integer[] getSubCategoryId(int parentId) { if(file == null) return EMPTY_INTEGER_ARRAY; iTemp.clear(); try { int subId = getFirstSubId(parentId); while(subId > 0) { iTemp.add(subId); subId = getNextSubId(subId); } return iTemp.toArray(new Integer[iTemp.size()]); } catch(IOException e) { return EMPTY_INTEGER_ARRAY; } } public String getCategoryPath(int id) { if(file == null) return ""; try { sb.delete(0, sb.length()); while(id > 0) { sb.insert(0, '-').insert(0, getName(id)); id = getParentId(id); } if(sb.length() > 0) sb.deleteCharAt(sb.length() - 1); return sb.toString(); } catch(IOException e) { return ""; } } private int getParentId(int subId) throws IOException { file.seek(HEADER_LENGTH + ENTRY_LENGTH * subId); file.seek(file.readInt() + 4); return file.readInt(); } public int getLevelId(int id, int level) { if(file == null) return 0; try { if(id == 0) return 0; int p1 = getParentId(id); int p2 = (p1 > 0) ? getParentId(p1) : 0; int idLevel = (p2 > 0) ? 2 : ((p1 > 0) ? 1 : 0); if(level < 0 || level > idLevel) return 0; else { switch(idLevel - level) { case 0: return id; case 1: return p1; case 2: return p2; default: return 0; } } } catch(IOException e) { return 0; } } private int getFirstSubId(int parentId) throws IOException { file.seek(HEADER_LENGTH + ENTRY_LENGTH * parentId + 4); return file.readInt(); } private int getNextSubId(int prevSubId) throws IOException { file.seek(HEADER_LENGTH + ENTRY_LENGTH * prevSubId); file.seek(file.readInt() + 8); return file.readInt(); } }
package screenReading; import java.awt.Point; import com.sun.jna.*; import com.sun.jna.platform.win32.WinDef.HWND; //import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.win32.*; public class WindowFinder { public interface User32 extends StdCallLibrary { User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class, W32APIOptions.DEFAULT_OPTIONS); HWND FindWindow(String lpClassName, String lpWindowName); int GetWindowRect(HWND handle, int[] rect); } public static int getXConstant(){ return screenSize.x; } public static boolean relat1610 = false; public static int getRealX(int x){ double dx = x; double base = (dx / 1694) * screenSize.x; // if(relat1610){ // System.out.println("Lasse har 16:10 tamefan"); // return (int) (base*(Math.sqrt(Math.sqrt(Math.sqrt(Math.sqrt(base/dx)))))); // } return (int) base; } public static int getRealY(int y){ double dy = y; double base = (dy / 941) * screenSize.y; return (int) base; } private static Point screenSize = null; public static Point getPointOfInterest() throws Exception { int[] location = new int[2]; location = getRect("Hearthstone"); screenSize = new Point((location[2]-location[0]),(location[3]-location[1])); double tempX = screenSize.x; double tempY = screenSize.y; String tempString = Double.toString(tempX/tempY); tempString = tempString.substring(0, 3); double relationship = Double.valueOf((tempString)); if(relationship == 1.6){ // 16:10 format relat1610 = true; } return new Point(location[0], location[1]); } public static Point getScreenSize(){ try { getPointOfInterest(); } catch (Exception e) { System.out.println("Kunde inte hitta fönstret"); e.printStackTrace(); } return screenSize; } private static int[] getRect(String windowName) throws WindowNotFoundException, GetWindowRectException { windowName = "Hearthstone"; HWND hwnd = User32.INSTANCE.FindWindow(null, windowName); if (hwnd == null) { throw new WindowNotFoundException("", windowName); } int[] rect = { 0, 0, 0, 0 }; int result = User32.INSTANCE.GetWindowRect(hwnd, rect); if (result == 0) { throw new GetWindowRectException(windowName); } return rect; } @SuppressWarnings("serial") public static class WindowNotFoundException extends Exception { public WindowNotFoundException(String className, String windowName) { super(String.format( "Window null for className: %s; windowName: %s", className, windowName)); } } @SuppressWarnings("serial") public static class GetWindowRectException extends Exception { public GetWindowRectException(String windowName) { super("Window Rect not found for " + windowName); } } }
package com.coding.java.thread; import com.coding.java.thread.base.ThreadTestIII; import org.junit.Test; public class ThreadTestIIITest { @Test public void test01() { System.out.println(Thread.currentThread().getName()+"主线程运行开始!"); ThreadTestIII th1 = new ThreadTestIII("A"); ThreadTestIII th2 = new ThreadTestIII("B"); th1.start(); th2.start(); System.out.println(Thread.currentThread().getName()+ "主线程运行结束!"); } @Test public void test02() { System.out.println(Thread.currentThread().getName()+"主线程运行开始!"); ThreadTestIII th1 = new ThreadTestIII("A"); ThreadTestIII th2 = new ThreadTestIII("B"); th1.start(); th2.start(); try { th1.join(); } catch (InterruptedException e) { e.printStackTrace(); } try { th2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+ "主线程运行结束!"); } }
/* * Copyright (c) 2009-2009 by Bjoern Kolbeck, Nele Andersen, * Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.utils.xtfs_scrub; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.EmptyStackException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.xtreemfs.common.libxtreemfs.AdminClient; import org.xtreemfs.common.libxtreemfs.AdminVolume; import org.xtreemfs.common.libxtreemfs.ClientFactory; import org.xtreemfs.common.libxtreemfs.Options; import org.xtreemfs.common.libxtreemfs.exceptions.PosixErrorException; import org.xtreemfs.foundation.SSLOptions; import org.xtreemfs.foundation.TimeSync; import org.xtreemfs.foundation.VersionManagement; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.pbrpc.Schemes; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials; import org.xtreemfs.foundation.util.CLIParser; import org.xtreemfs.foundation.util.CLIParser.CliOption; import org.xtreemfs.foundation.util.OutputUtils; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.PORTS; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL; import org.xtreemfs.pbrpc.generatedinterfaces.MRC.DirectoryEntries; import org.xtreemfs.pbrpc.generatedinterfaces.MRC.DirectoryEntry; import org.xtreemfs.pbrpc.generatedinterfaces.MRC.XATTR_FLAGS; import org.xtreemfs.utils.DefaultDirConfig; import org.xtreemfs.utils.utils; /** * * @author bjko */ public class xtfs_scrub { public static interface FileScrubbedListener { public void fileScrubbed(String FileName, long bytesScrubbed, Collection<ReturnStatus> rstatus); } public static enum ReturnStatus { FILE_OK, FILE_LOST, WRONG_FILE_SIZE, FAILURE_OBJECTS, FAILURE_REPLICAS, UNREACHABLE; }; public static String latestScrubAttr = "scrubber.latestscrub"; public static final UserCredentials credentials; static { credentials = UserCredentials.newBuilder().setUsername("root").addGroups("root").build(); } private static final int DEFAULT_NUM_THREADS = 10; private AdminVolume volume; private final boolean repair, delete, silent; private final ExecutorService tPool; private long lastBytesScrubbed; private final Stack<String> directories; private final Stack<String> files; private final Object completeLock; private int returnCode; private int numInFlight; private final int numThrs; private boolean hasFinished; private boolean isLatestScrubAttrSettable; private String currentDirName = null; private int numFiles, numReplicaFailure, numObjectFailure, numFileOk, numUnreachable, numWrongFS, numDead; private final Set<String> removedOSDs; public xtfs_scrub(AdminClient client, AdminVolume volume, int numThrs, boolean repair, boolean delete, boolean silent) throws IOException { this.repair = repair; this.delete = delete; this.silent = silent; this.numThrs = numThrs; directories = new Stack<String>(); files = new Stack<String>(); tPool = Executors.newFixedThreadPool(numThrs); numInFlight = 0; completeLock = new Object(); hasFinished = false; isLatestScrubAttrSettable = true; this.volume = volume; numFiles = 0; numReplicaFailure = 0; numObjectFailure = 0; numFileOk = 0; numUnreachable = 0; if (!repair && !delete) { System.out.println("running in check mode, no changes to files will be made"); } else { if (repair) System.out.println("running in repair mode"); if (delete) System.out .println("WARNING: delete is enabled, corrupt files (data lost due to failed OSDs) will be deleted"); } removedOSDs = client.getRemovedOsds(); if (removedOSDs.size() > 0) { System.out .println("list of OSDs that have been removed (replicas on these OSDs will be deleted):"); for (String uuid : removedOSDs) { System.out.println("\t" + uuid); } } } public int scrub() { System.out.println(""); directories.push("/"); // create scrub xattr if not done yet try { volume.setXAttr(credentials, "/", latestScrubAttr, Long.toString(TimeSync.getLocalSystemTime()), XATTR_FLAGS.XATTR_FLAGS_CREATE); } catch (PosixErrorException e) { // scrub xattr already exists, nothing to do here. } catch (IOException e) { isLatestScrubAttrSettable = false; System.out.println("\nWarning: cannot mark volume as scrubbed: " + e); } fillQueue(); synchronized (completeLock) { try { if (!hasFinished) { completeLock.wait(); } } catch (InterruptedException ex) { } } tPool.shutdown(); try { tPool.awaitTermination(1, TimeUnit.HOURS); } catch (InterruptedException e) { } if (!silent) System.out.format("scrubbed %-42s %15s - total %15s\n\u001b[100D\u001b[A", "all files", "", OutputUtils.formatBytes(lastBytesScrubbed)); System.out.println("\n\nsummary:"); System.out.println("files checked : " + numFiles); System.out.println(" files ok : " + numFileOk); System.out.println(" files corrupted : " + (numFiles - numFileOk)); System.out.println(" of which had lost replicas (caused by removed OSDs) : " + numReplicaFailure); System.out.println(" of which had corrupted objects (caused by invalid checksums): " + numObjectFailure); System.out.println(" of which had a wrong file size : " + numWrongFS); System.out.println(" of which are lost (unrecoverable) : " + numDead); System.out.println(" of which are unreachable (caused by communication errors) : " + numUnreachable); System.out.println("bytes checked : " + OutputUtils.formatBytes(lastBytesScrubbed)); return returnCode; } private void fillQueue() { try { synchronized (directories) { while (numInFlight < numThrs) { try { String fileName = files.pop(); try { FileScrubbedListener fsListener = new FileScrubbedListener() { public void fileScrubbed(String fileName, long bytesScrubbed, Collection<ReturnStatus> rstatus) { xtfs_scrub.this.fileScrubbed(fileName, bytesScrubbed, rstatus); } }; FileScrubber fi = new FileScrubber(fileName, volume, fsListener, removedOSDs, repair, delete); tPool.submit(fi); numInFlight++; } catch (IOException ex) { Logging.logError(Logging.LEVEL_WARN, this, ex); } } catch (EmptyStackException ex) { // fetch next dir fetchNextDir(); } } } } catch (EmptyStackException ex) { // no more entries, finished! if (isLatestScrubAttrSettable) { try { // mark volume as scrubbed volume.setXAttr(credentials, "/", latestScrubAttr, Long.toString(TimeSync.getLocalSystemTime()), XATTR_FLAGS.XATTR_FLAGS_REPLACE); } catch (IOException ex2) { System.out.println("\nWarning: cannot mark volume as successfully scrubbed: " + ex2); } } finish(0); return; } } private void finish(int returnCode) { synchronized (directories) { if (numInFlight == 0) { synchronized (completeLock) { this.returnCode = returnCode; this.hasFinished = true; completeLock.notifyAll(); } } } } public void fileScrubbed(String fileName, long bytesScrubbed, Collection<ReturnStatus> rs) { // update statistics if (fileName.length() > 42) { fileName = "..." + fileName.substring(fileName.length() - 39, fileName.length()); } synchronized (directories) { lastBytesScrubbed += bytesScrubbed; numFiles++; for (ReturnStatus status : rs) { switch (status) { case FILE_OK: numFileOk++; break; case WRONG_FILE_SIZE: numWrongFS++; break; case UNREACHABLE: numUnreachable++; break; case FILE_LOST: numDead++; break; case FAILURE_REPLICAS: numReplicaFailure++; break; case FAILURE_OBJECTS: numObjectFailure++; break; } } if (!silent) System.out.format("scrubbed %-42s with %15s - total %15s\n\u001b[100D\u001b[A", fileName, OutputUtils.formatBytes(bytesScrubbed), OutputUtils.formatBytes(lastBytesScrubbed)); numInFlight--; fillQueue(); } } private void fetchNextDir() { currentDirName = directories.pop(); try { DirectoryEntries ls = volume.readDir(credentials, currentDirName, 0, 0, false); if (ls == null) { Logging.logMessage(Logging.LEVEL_ERROR, this, "path %s does not exist!", currentDirName); return; } for (int i = 0; i < ls.getEntriesCount(); i++) { DirectoryEntry e = ls.getEntries(i); if ((e.getStbuf().getMode() & SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_S_IFREG.getNumber()) != 0) { // regular file files.push(currentDirName + e.getName()); } else if ((e.getStbuf().getMode() & SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_S_IFDIR.getNumber()) != 0) { if (!e.getName().equals(".") && !e.getName().equals("..")) directories.push(currentDirName + e.getName() + "/"); } } } catch (IOException ex) { System.err.println("cannot contact MRC... aborting"); System.err.println(ex); } catch (Exception ex) { ex.printStackTrace(); throw new EmptyStackException(); } } public static void main(String[] args) { Logging.start(Logging.LEVEL_WARN); System.out.println("XtreemFS scrubber version " + VersionManagement.RELEASE_VERSION + " (file system data integrity check)\n"); Map<String, CliOption> options = utils.getDefaultAdminToolOptions(false); List<String> arguments = new ArrayList<String>(1); CliOption oDir = new CliOption( CliOption.OPTIONTYPE.STRING, "directory service to use (e.g. 'pbrpc://localhost:32638'). If no URI is specified, URI and security settings are taken from '" + DefaultDirConfig.DEFAULT_DIR_CONFIG + "'", "<uri>"); oDir.urlDefaultPort = PORTS.DIR_PBRPC_PORT_DEFAULT.getNumber(); oDir.urlDefaultProtocol = Schemes.SCHEME_PBRPC; options.put("dir", oDir); options.put("repair", new CliOption(CliOption.OPTIONTYPE.SWITCH, "repair files (update file size, replace replicas) when possible", "")); options.put("delete", new CliOption(CliOption.OPTIONTYPE.SWITCH, "delete lost files (incomplete due to OSD failures)", "")); options.put("silent", new CliOption(CliOption.OPTIONTYPE.SWITCH, "don't show the progress bar", "")); options.put("thrs", new CliOption(CliOption.OPTIONTYPE.NUMBER, "number of concurrent file scrub threads (default=" + DEFAULT_NUM_THREADS + ")", "n")); CLIParser.parseCLI(args, options, arguments); if (arguments.size() != 1) error("invalid number of arguments", options); if (options.get(utils.OPTION_HELP).switchValue || options.get(utils.OPTION_HELP_LONG).switchValue) { usage(options); System.exit(0); } String[] dirURLs = (options.get("dir").stringValue != null) ? options.get("dir").stringValue .split(",") : null; SSLOptions sslOptions = null; String[] dirAddrs = null; if (dirURLs != null) { int i = 0; boolean gridSSL = false; dirAddrs = new String[dirURLs.length]; for (String dirURL : dirURLs) { // parse security info if protocol is 'https' if (dirURL.contains(Schemes.SCHEME_PBRPCS + "://") || dirURL.contains(Schemes.SCHEME_PBRPCG + "://") && sslOptions == null) { String serviceCredsFile = options.get(utils.OPTION_USER_CREDS_FILE).stringValue; String serviceCredsPass = options.get(utils.OPTION_USER_CREDS_PASS).stringValue; String trustedCAsFile = options.get(utils.OPTION_TRUSTSTORE_FILE).stringValue; String trustedCAsPass = options.get(utils.OPTION_TRUSTSTORE_PASS).stringValue; if (dirURL.contains(Schemes.SCHEME_PBRPCG + "://")) { gridSSL = true; } if (serviceCredsFile == null) { System.out.println("SSL requires '-" + utils.OPTION_USER_CREDS_FILE + "' parameter to be specified"); usage(options); System.exit(1); } else if (trustedCAsFile == null) { System.out.println("SSL requires '-" + utils.OPTION_TRUSTSTORE_FILE + "' parameter to be specified"); usage(options); System.exit(1); } // TODO: support custom SSL trust managers try { sslOptions = new SSLOptions(new FileInputStream(serviceCredsFile), serviceCredsPass, SSLOptions.PKCS12_CONTAINER, new FileInputStream(trustedCAsFile), trustedCAsPass, SSLOptions.JKS_CONTAINER, false, gridSSL, null); } catch (Exception e) { System.err.println("unable to set up SSL, because:" + e.getMessage()); System.exit(1); } } // add URL to dirAddrs if (dirURL.contains("://")) { // remove Protocol information String[] tmp = dirURL.split("://"); // remove possible slash dirAddrs[i++] = tmp[1].replace("/", ""); } else { // remove possible slash dirAddrs[i++] = dirURL.replace("/", ""); } } } // read default settings if (dirURLs == null) { try { DefaultDirConfig cfg = new DefaultDirConfig(); sslOptions = cfg.getSSLOptions(); dirAddrs = cfg.getDirectoryServices(); } catch (Exception e) { System.err.println("unable to get SSL options, because: " + e.getMessage()); System.exit(1); } } boolean repair = options.get("repair").switchValue; boolean silent = options.get("silent").switchValue; boolean delete = options.get("delete").switchValue; int numThreads = DEFAULT_NUM_THREADS; if (options.get("thrs").numValue != null) { numThreads = options.get("thrs").numValue.intValue(); } final String volumeName = arguments.get(0); Options userOptions = new Options(); AdminClient c = ClientFactory.createAdminClient(dirAddrs, credentials, sslOptions, userOptions); AdminVolume volume = null; try { c.start(); volume = c.openVolume(volumeName, sslOptions, new Options()); volume.start(); } catch (Exception e) { System.err.println("unable to scrub Volume, because: " + e.getMessage()); System.exit(1); } int exitCode = 1; try { xtfs_scrub scrubber = new xtfs_scrub(c, volume, numThreads, repair, delete, silent); exitCode = scrubber.scrub(); if (exitCode == 0) { System.out.println("\n\nsuccessfully scrubbed volume '" + volumeName + "'"); } else { System.out.println("\n\nscrubbing volume '" + volumeName + "' FAILED!"); } System.exit(exitCode); } catch (Exception e) { System.err.println("unable to scrub Volume, because: " + e.getMessage()); System.exit(1); } c.shutdown(); } private static void error(String message, Map<String, CliOption> options) { System.err.println(message); System.out.println(); usage(options); System.exit(1); } private static void usage(Map<String, CliOption> options) { System.out.println("usage: xtfs_scrub [options] <volume_name>"); System.out.println("<volume_name> the volume to scrub\n"); System.out.println("options:"); utils.printOptions(options); } }
package kr.ko.nexmain.server.MissingU.friends.service; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import kr.ko.nexmain.server.MissingU.common.Constants; import kr.ko.nexmain.server.MissingU.common.model.CommReqVO; import kr.ko.nexmain.server.MissingU.common.model.Result; import kr.ko.nexmain.server.MissingU.common.service.CommonService; import kr.ko.nexmain.server.MissingU.common.utils.MsgUtil; import kr.ko.nexmain.server.MissingU.common.utils.UTL; import kr.ko.nexmain.server.MissingU.friends.controller.FriendsController; import kr.ko.nexmain.server.MissingU.friends.dao.FriendsDao; import kr.ko.nexmain.server.MissingU.friends.model.FriendsEditReqVO; import kr.ko.nexmain.server.MissingU.friends.model.FriendsVO; import kr.ko.nexmain.server.MissingU.friends.model.SearchFriendsReqVO; import kr.ko.nexmain.server.MissingU.friends.model.SendGiftReqVO; import kr.ko.nexmain.server.MissingU.harmony.model.TotalInfoReqVO; import kr.ko.nexmain.server.MissingU.harmony.service.HarmonyService; import kr.ko.nexmain.server.MissingU.membership.dao.MembershipDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional(timeout=15) public class FriendsServiceImpl implements FriendsService { protected static Logger log = LoggerFactory.getLogger(FriendsServiceImpl.class); @Autowired private CommonService commonService; @Autowired private FriendsDao friendsDao; @Autowired private MembershipDao membershipDao; @Autowired private HarmonyService harmonyService; @Autowired private MsgUtil msgUtil; private Locale gLocale; /** * 친구 리스트 조회 */ @Transactional(readOnly=true) public Map<String,Object> getMemberListForSearchFriends(SearchFriendsReqVO inputVO) { gLocale = new Locale(inputVO.getgLang()); Map<String,Object> returnMap = new HashMap<String,Object>(); Map<String,Object> responseMap = new HashMap<String,Object>(); // 지역검색이 있는 경우 if(inputVO.getAreaCd() != null && inputVO.getAreaCd().length() > 0 && inputVO.getAreaNm() != null && inputVO.getAreaNm().length() > 0) { // 지역검색중 한국 해외, 기타인 경우 if("A06017".equals(inputVO.getAreaCd())) { inputVO.setAreaCd(null); inputVO.setAreaNm(null); inputVO.setCountryExclusive("kr"); // 지역검색중 일본 기타지역인 경우 }else if("AJ6048".equals(inputVO.getAreaCd())) { inputVO.setAreaCd(null); inputVO.setAreaNm(null); inputVO.setCountryExclusive("ja"); // 지역검색중 중국 기타지역인 경우 }else if("AZ6035".equals(inputVO.getAreaCd())) { inputVO.setAreaCd(null); inputVO.setAreaNm(null); inputVO.setCountryExclusive("zh"); }else{ // 빈값이라도 있어야함 inputVO.setCountryExclusive(""); } }else{ inputVO.setCountryExclusive(null); } // 가까운 거리 검색(랜덤인 경우 전체 적용을 위함) if(inputVO.getDistance().compareTo(0) <= 0) { // inputVO.setDistance(30); inputVO.setDistance(null); } log.info("Input Param : {}", inputVO.toString()); //Input 계정정보로 회원조회 List<Map<String,Object>> memberList = friendsDao.selectMemberListForSearchFriends(inputVO); responseMap.put("member", memberList); if(memberList != null && memberList.size() > 0) { //조회 결과가 있는 경우 Result result = new Result( Constants.ReturnCode.SUCCESS, msgUtil.getMsgCd("comm.success.search", gLocale), msgUtil.getMsgText("comm.success.search", gLocale)); returnMap.put("result", result); returnMap.put("response", responseMap); } else { //조회 결과 없음 Result result = new Result( Constants.ReturnCode.LOGIC_ERROR, msgUtil.getMsgCd("friends.searchFriends.le.noResult", gLocale), msgUtil.getMsgText("friends.searchFriends.le.noResult", gLocale)); returnMap.put("result", result); } return returnMap; } /** 친구 추가 */ public Map<String,Object> addFriend(FriendsEditReqVO inputVO) { gLocale = new Locale(inputVO.getgLang()); Map<String,Object> returnMap = new HashMap<String,Object>(); FriendsVO vo = new FriendsVO(); vo.setMemberId(inputVO.getgMemberId()); vo.setFriendId(inputVO.getFriendId()); FriendsVO friend = friendsDao.selectFriends(vo); if(friend != null) { //이미 등록된 친구인 경우 Result result = new Result( Constants.ReturnCode.LOGIC_ERROR, msgUtil.getMsgCd("friends.addFriend.le.alreadyExist", gLocale), msgUtil.getMsgText("friends.addFriend.le.alreadyExist", gLocale)); returnMap.put("result", result); return returnMap; } else { vo.setStatus("A"); //Active friendsDao.insertIntoFriends(vo); } Result result = new Result( Constants.ReturnCode.SUCCESS, msgUtil.getMsgCd("friends.addFriend.ss.success", gLocale), msgUtil.getMsgText("friends.addFriend.ss.success", gLocale)); returnMap.put("result", result); return returnMap; } /** 친구 삭제 */ public Map<String,Object> deleteFriend(FriendsEditReqVO inputVO) { gLocale = new Locale(inputVO.getgLang()); Map<String,Object> returnMap = new HashMap<String,Object>(); FriendsVO vo = new FriendsVO(); vo.setMemberId(inputVO.getgMemberId()); vo.setFriendId(inputVO.getFriendId()); int deleteCnt = friendsDao.deleteFromFriends(vo); if(deleteCnt > 0) { //성공 Result result = new Result( Constants.ReturnCode.SUCCESS, msgUtil.getMsgCd("friends.deleteFriend.ss.success", gLocale), msgUtil.getMsgText("friends.deleteFriend.ss.success", gLocale)); returnMap.put("result", result); } else { //삭제 건이 없는 경우 Result result = new Result( Constants.ReturnCode.LOGIC_ERROR, msgUtil.getMsgCd("friends.deleteFriend.le.notDeleted", gLocale), msgUtil.getMsgText("friends.deleteFriend.le.notDeleted", gLocale)); returnMap.put("result", result); } return returnMap; } /** * 친구 상세정보 조회 */ public Map<String,Object> getDetailInfo(FriendsEditReqVO inputVO) { gLocale = new Locale(inputVO.getgLang()); Map<String,Object> returnMap = new HashMap<String,Object>(); Map<String,Object> responseMap = new HashMap<String,Object>(); //친구 상세정보 조회 CommReqVO vo = new CommReqVO(); vo.setgMemberId(inputVO.getFriendId()); Map<String,Object> friendMap = membershipDao.selectMemberByMemberId(vo); List<Map<String,Object>> friendAttrList = membershipDao.selectMemberAttrByMemberId(vo); //내 정보 조회 //vo = new CommReqVO(); //vo.setgMemberId(inputVO.getgMemberId()); //Map<String,Object> memberMap = membershipDao.selectMemberByMemberId(inputVO); if(friendMap != null) { //회원 존재 if(friendAttrList != null && friendAttrList.size() > 0) { Map<String,String> friendAttrMap = new HashMap<String,String>(); for(Map<String, Object> attrMap : friendAttrList){ friendAttrMap.put((String)attrMap.get("attrName"), (String)attrMap.get("attrValue")); } friendMap.put("attr", friendAttrMap); } responseMap.put("friend", friendMap); //responseMap.put("member", memberMap); //TODO : 추가개발 필요 TotalInfoReqVO harmonyReqVO = new TotalInfoReqVO(); harmonyReqVO.setgMemberId(inputVO.getgMemberId()); harmonyReqVO.setFriendId(inputVO.getFriendId()); harmonyReqVO.setgLang(inputVO.getgLang()); Map<String,Object> harmonyMap = harmonyService.getHarmonyResultMap(harmonyReqVO); responseMap.put("harmony", harmonyMap); /* harmonyMap.put("myBloodTypeCd", "B01001"); harmonyMap.put("myNickName", "내 닉네임"); harmonyMap.put("mySignCd", "S02"); harmonyMap.put("myElementCd", "E02"); harmonyMap.put("yourBloodTypeCd", "B01001"); harmonyMap.put("yourNickName", "상대 닉네임"); harmonyMap.put("yourSignCd", "S01"); harmonyMap.put("yourElementCd", "E01"); harmonyMap.put("totalHarmonyScore", 90); */ //추가 개발 필요 /* Map<String,Object> etcMap = new HashMap<String,Object>(); etcMap.put("participateCnt", 5); etcMap.put("votedCnt", 3); etcMap.put("curRank", 3); etcMap.put("totalRank", 5); responseMap.put("etc", etcMap); */ Result result = new Result( Constants.ReturnCode.SUCCESS, msgUtil.getMsgCd("comm.success.search", gLocale), msgUtil.getMsgText("comm.success.search", gLocale)); returnMap.put("result", result); returnMap.put("response", responseMap); } else { //회원 미존재 Result result = new Result( Constants.ReturnCode.LOGIC_ERROR, msgUtil.getMsgCd("membership.getMyPage.le.fail", gLocale), msgUtil.getMsgText("membership.getMyPage.le.fail", gLocale)); returnMap.put("result", result); } return returnMap; } /** 윙크 보내기 */ public Map<String,Object> sendWink(FriendsEditReqVO inputVO) { gLocale = new Locale(inputVO.getgLang()); Map<String,Object> returnMap = new HashMap<String,Object>(); boolean flag = false; // 자기 자신에게 쪽지를 보낼 수 없다. if(inputVO.getFriendId() == inputVO.getgMemberId()) { Result result = new Result( Constants.ReturnCode.LOGIC_ERROR, msgUtil.getMsgCd("friends.sendWink.le.sameFriendId", gLocale), msgUtil.getMsgText("friends.sendWink.le.sameFriendId", gLocale)); returnMap.put("result", result); return returnMap; } Map<String,Object> winkItem = new HashMap<String,Object>(); winkItem.put("senderId", inputVO.getgMemberId()); winkItem.put("receiverId", inputVO.getFriendId()); winkItem.put("itemCd", Constants.ItemCode.WINK); winkItem.put("itemAmount", 1); friendsDao.insertIntoItemSndRcvHist(winkItem); //아이템 송수신 내역 Insert friendsDao.updateInventoryToIncreaseItemAmount(winkItem); //수신자 인벤토리 업데이트 : item_amount 증가 // gcm 발송 if(!inputVO.isGcmPass()) flag = sendGCMMsgByMemberId(inputVO.getFriendId(), inputVO.getgMemberId(), Constants.ActionType.WINK_MSG); //성공 Result result = new Result( Constants.ReturnCode.SUCCESS, msgUtil.getMsgCd("friends.sendWink.ss.success", gLocale), msgUtil.getMsgText("friends.sendWink.ss.success", gLocale)); returnMap.put("result", result); //포인트 차감 if(!inputVO.isPointPass()) commonService.updatePointInfo(inputVO.getgMemberId(), Constants.EventTypeCd.OUTCOME, "O206", -300, inputVO.getgLang()); return returnMap; } /** 선물 보내기 */ public Map<String,Object> sendGift(SendGiftReqVO inputVO) { gLocale = new Locale(inputVO.getgLang()); Map<String,Object> returnMap = new HashMap<String,Object>(); boolean flag = false; // 자기 자신에게 쪽지를 보낼 수 없다. if(inputVO.getFriendId() == inputVO.getgMemberId()) { Result result = new Result( Constants.ReturnCode.LOGIC_ERROR, msgUtil.getMsgCd("friends.sendGift.le.sameFriendId", gLocale), msgUtil.getMsgText("friends.sendGift.le.sameFriendId", gLocale)); returnMap.put("result", result); return returnMap; } Map<String,Object> giftItem = new HashMap<String,Object>(); giftItem.put("senderId", inputVO.getgMemberId()); giftItem.put("receiverId", inputVO.getFriendId()); giftItem.put("itemCd", inputVO.getItemCd()); giftItem.put("itemAmount", 1); friendsDao.insertIntoItemSndRcvHist(giftItem); //아이템 송수신 내역 Insert friendsDao.updateInventoryToIncreaseItemAmount(giftItem); //수신자 인벤토리 업데이트 : item_amount 증가 flag = sendGCMMsgByMemberId(inputVO.getFriendId(), inputVO.getgMemberId(), Constants.ActionType.GIFT_MSG); //성공 Result result = new Result( Constants.ReturnCode.SUCCESS, msgUtil.getMsgCd("friends.sendGift.ss.success", gLocale), msgUtil.getPropMsg("itemCode.T03001", gLocale) + msgUtil.getMsgText("friends.sendGift.ss.success", gLocale)); returnMap.put("result", result); String usageCd = ""; if(Constants.ItemCode.GIFT_FLOWER.equalsIgnoreCase(inputVO.getItemCd())) { usageCd = "O205"; } //포인트 정보 업데이트 commonService.updatePointInfo(inputVO.getgMemberId(), Constants.EventTypeCd.OUTCOME, usageCd, -1000, inputVO.getgLang()); return returnMap; } public boolean sendGCMMsgByMemberId(Integer receiverId, Integer senderId, String action) { Map<String,Object> receiver = this.membershipDao.selectSimpleMemberInfoByMemberId(receiverId); Map<String,Object> sender = this.membershipDao.selectSimpleMemberInfoByMemberId(senderId); StringBuilder sb = new StringBuilder(); sb.append( (sender.get("nickName")) ); if(Constants.ActionType.WINK_MSG.equalsIgnoreCase(action)) { sb.append( msgUtil.getPropMsg("friends.sendWink.winkNotice", gLocale)); } else if (Constants.ActionType.GIFT_MSG.equalsIgnoreCase(action)) { sb.append( msgUtil.getPropMsg("friends.sendGift.giftNotice", gLocale)); } Map<String,String> gcmParams = new HashMap<String,String>(); gcmParams.put("msg", sb.toString()); gcmParams.put("action", action); gcmParams.put("senderId", String.valueOf(senderId)); gcmParams.put("senderSex", UTL.nvl(((String)sender.get("sex")))); gcmParams.put("senderPhotoUrl", UTL.nvl((String)sender.get("mainPhotoUrl"))); if(receiver.get("gcmRegId") != null && !"".equals((String)receiver.get("gcmRegId"))) { UTL.sendGCM((String)receiver.get("gcmRegId"), gcmParams); } else { return false; } return true; } }
package crossing.expireRule; import common.OrderType; import leafNode.OrderEntry; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Created by dharmeshsing on 1/12/15. */ public class MarketOrderExpireRuleTest { @Test public void testIsMarketOrderExpired(){ OrderEntry orderEntry = mock(OrderEntry.class); when(orderEntry.getType()).thenReturn(OrderType.MARKET.getOrderType()); ExpireRule expireRule = new MarketOrderExpireRule(); boolean result = expireRule.isOrderExpired(orderEntry); assertEquals(true,result); } }
package com.dyny.gms.controller; import com.dyny.gms.controller.commonController.BaseController; import com.dyny.gms.db.pojo.Basis; import com.dyny.gms.db.pojo.Generator; import com.dyny.gms.service.BasisService; import com.dyny.gms.service.GeneratorService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.math.BigDecimal; import java.text.ParseException; import java.util.ArrayList; import java.util.List; @RestController public class GeneratorController extends BaseController { @Autowired GeneratorService generatorService; @Autowired BasisService basisService; /** * 获得油机详情 * * @param machNo * @return */ @RequestMapping(value = "/getGeneratorDetail", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String getGeneratorDetail(@RequestParam(name = "mach_no") String machNo) { return super.getSuccessResult(generatorService.getGeneratorDetailFromCache(machNo)); } /** * 根据客户编号获得油机 * * @param cusNo * @return */ @RequestMapping(value = "/getGeneratorByCusNo", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String getGeneratorByCusNo(@RequestParam(name = "user_cus") String cusNo) { return super.getSuccessResult(generatorService.getGeneratorDetail(cusNo)); } /** * 更新油机信息 * * @param generator * @return */ @RequestMapping(value = "/updateGenerator", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String updateGenerator(@RequestBody Generator generator) { if (generator != null) { return super.getSuccessResult(generatorService.updateGenerator(generator)); } else { return super.getErrorMsg("请输入机器编号"); } } /** * 更新油机信息 * * @param generatorList * @return */ @RequestMapping(value = "/updateGeneratorList", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String updateGeneratorList(@RequestBody List<Generator> generatorList) { return super.getSuccessResult(generatorService.updateGenerator(generatorList)); } /** * 获得指定客户编号的油机,条件为该基站的编号或者基站编号为空 * * @param stationNo * @param user_cus * @return */ @RequestMapping(value = "/getGeneratorForStation", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String getGeneratorForStation(@RequestParam(name = "stationNo") String stationNo, @RequestParam(name = "searchContent", required = false, defaultValue = "") String searchContent, @RequestParam(name = "user_cus") String user_cus) { return super.getSuccessResult(generatorService.getGeneratorForStation(stationNo, user_cus, searchContent)); } /** * 获得指定客户编号的油机,条件为该基站的编号或者基站编号为空 * * @param stationNo * @param user_cus * @return */ @RequestMapping(value = "/changeBootVoltage", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String changeBootVoltage(@RequestParam(name = "generatorNoList[]") List<String> generatorNoList, @RequestParam(name = "bootVoltage") BigDecimal bootVoltage) { return super.getSuccessResult(generatorService.changeBootVoltage(generatorNoList, bootVoltage)); } /** * 关联/取消关联油机 * * @param stationNo * @param machNo * @param relate * @param user_cus * @return */ @RequestMapping(value = "/relateGeneratorWithStation", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String relateGeneratorWithStation(@RequestParam(name = "stationNo", required = false, defaultValue = "") String stationNo, @RequestParam(name = "machNo") String machNo, @RequestParam(name = "relate") boolean relate, // @RequestParam(name = "contactIdList") List<Integer> contactIdList, @RequestParam(name = "user_cus") String user_cus) { return super.getSuccessResult(generatorService.relateGeneratorWithStation(machNo, stationNo, user_cus, relate, new ArrayList<Integer>()));//暂时不需要选择油机操作人员 } /** * 效率不高!!!!!!!!!!但基站与油机通常是1对1,应该不会超过1对3,因此性能差别应该不大 * * @param stationNo * @param machNoList * @param relate * @param user_cus * @return */ @RequestMapping(value = "/relateGeneratorListWithStation", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String relateGeneratorListWithStation(@RequestParam(name = "stationNo", required = false, defaultValue = "") String stationNo, @RequestParam(name = "machNoList[]") List<String> machNoList, @RequestParam(name = "relate") boolean relate, @RequestParam(name = "user_cus") String user_cus) { int cnt = 0; for (String temp : machNoList) { cnt += generatorService.relateGeneratorWithStation(temp, stationNo, user_cus, relate, new ArrayList<Integer>()); } return super.getSuccessResult(cnt);//暂时不需要选择油机操作人员 } /** * 获得各个状态的油机数量,status参数暂时没有用上 * * @param status * @param user_cus * @return */ @RequestMapping(value = "/getGeneratorNumByStatus", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String getGeneratorNumByStatus( @RequestParam(name = "status") String status, @RequestParam(name = "user_cus") String user_cus) { return super.getSuccessResult(generatorService.getGeneratorNumByStatus(status, user_cus)); } /** * 获得各个状态的油机数量,status参数暂时没有用上 * * @param status * @param user_cus * @return */ @RequestMapping(value = "/activateGenerator", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String activateGenerator( @RequestParam(name = "generatorNoList[]") List<String> generatorNoList, @RequestParam(name = "username", required = false, defaultValue = "") String username, @RequestParam(name = "activate") boolean activate) { return super.getSuccessResult(generatorService.activateGenerator(generatorNoList, activate, username)); } /** * 获得各个状态的油机数量,status参数暂时没有用上 * * @param status * @param user_cus * @return */ @RequestMapping(value = "/getActivateLog", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String getActivateLog( @RequestParam(name = "keyWord") String keyWord, @RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum, @RequestParam(name = "pageSize", required = false, defaultValue = "20") int pageSize, @RequestParam(name = "startTimestamp", required = false, defaultValue = "") long startTimestamp, @RequestParam(name = "endTimestamp", required = false, defaultValue = "") long endTimestamp) { return generatorService.getActivateLog(keyWord, startTimestamp, endTimestamp, pageNum, pageSize); } @RequestMapping(value = "/getBasisInfo", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String getFuelInfo( @RequestParam(name = "offset") int offset, @RequestParam(name = "machNo") String machNo, @RequestParam(name = "samplingInterval", required = false, defaultValue = "3600") int samplingInterval, @RequestParam(name = "startTimestamp", required = false, defaultValue = "") long startTimestamp, @RequestParam(name = "endTimestamp", required = false, defaultValue = "") long endTimestamp) throws ParseException { return super.getSuccessResult(basisService.getBasisByOffset(offset, machNo, samplingInterval, startTimestamp, endTimestamp)); } @RequestMapping(value = "/cache/setBasis", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String setBasisInfo(@RequestBody Basis basis) { return generatorService.saveGeneratorData(basis, false) + ""; } @RequestMapping(value = "/cache/getBasis", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String getBasisInfo(@RequestParam(name = "generatorNo") String generatorNo) { return super.getSuccessResult(basisService.getBasisFromCache(generatorNo)); } @RequestMapping(value = "/setBasisToCacheAndDB", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String setBasisToCacheAndDB(@RequestBody Basis basis) { return generatorService.saveGeneratorData(basis, true) + ""; } @RequestMapping(value = "/getGeneratorStatusData", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String getGeneratorStatusData(@RequestParam(name = "generatorNo") String generatorNo) { return super.getSuccessResult(generatorService.getGeneratorStatusData(generatorNo)); } /** * 获得各个状态的油机数量,status参数暂时没有用上 * * @param status * @param user_cus * @return */ @RequestMapping(value = "/generatorRegister", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String generatorRegister(@RequestBody Generator generator) { return super.getSuccessResult(generatorService.generatorRegister(generator)); } }
package com.accp.domain; public class Warehouse { private Integer waeid; private String waename; private Integer waekd; private Integer waecx; public Integer getWaeid() { return waeid; } public void setWaeid(Integer waeid) { this.waeid = waeid; } public String getWaename() { return waename; } public void setWaename(String waename) { this.waename = waename; } public Integer getWaekd() { return waekd; } public void setWaekd(Integer waekd) { this.waekd = waekd; } public Integer getWaecx() { return waecx; } public void setWaecx(Integer waecx) { this.waecx = waecx; } }
package org.wso2.charon3.impl.provider.resources; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.wso2.charon3.core.exceptions.CharonException; import org.wso2.charon3.core.extensions.CreateUserManager; import org.wso2.charon3.core.extensions.UserManager; import org.wso2.charon3.core.protocol.SCIMResponse; import org.wso2.charon3.core.protocol.endpoints.BulkResourceManager; import org.wso2.charon3.utils.DefaultCharonManager; @Path(value = "/scim/v2/Bulk") public class BulkResource extends AbstractResource{ Logger logger = Logger.getLogger(BulkResource.class.getName()); @GET public String bulkResponse() { return "Bulk request successfully"; } @POST @Produces({"application/json", "application/scim+json"}) @Consumes("application/scim+json") public Response bulkRequest(String resourceString) { try { System.out.println("/Bulk calls"); UserManager userManager = DefaultCharonManager.getInstance().getUserManager(); BulkResourceManager resourceManager = new BulkResourceManager(); SCIMResponse response = resourceManager.processBulkData(resourceString, userManager); return buildResponse(response); } catch (CharonException e) { // TODO Auto-generated catch block logger.info("Error occure in bulkREquest....."); e.printStackTrace(); } return null; } }
package makeabilitylab.a02_gesturelogger; public abstract class SensorEventCache{ protected long _currentTimeMs = -1; // The time in nanoseconds at which the sensorevent happened. See https://developer.android.com/reference/android/hardware/SensorEvent.html protected long _sensorTimeStampNano = -1; protected String _sensorEventType = null; public SensorEventCache(String sensorEventType, long currentTimeMs, long sensorTimestampNano){ _sensorEventType = sensorEventType; _currentTimeMs = currentTimeMs; _sensorTimeStampNano = sensorTimestampNano; } public abstract String getCsvHeaderString(); public abstract String toCsvString(); @Override public String toString(){ return toCsvString(); } }
/* * Copyright (C) 2015 Miquel Sas * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.qtplaf.library.trading.chart.drawings; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import com.qtplaf.library.trading.chart.parameters.CandlestickPlotParameters; import com.qtplaf.library.trading.chart.plotter.PlotterContext; import com.qtplaf.library.trading.data.Data; import com.qtplaf.library.util.ColorUtils; /** * A candlestick drawing. * * @author Miquel Sas */ public class Candlestick extends DataDrawing { /** Plot parameters. */ private CandlestickPlotParameters parameters; /** Indexes to retrieve data. */ private int[] indexes; /** * Constructor assigning the values. * * @param index The data index. * @param data The data. * @param indexes The indexes to retrieve values. * @param parameters Plot parameters. */ public Candlestick(int index, Data data, int[] indexes, CandlestickPlotParameters parameters) { super(index, data); this.indexes = indexes; this.parameters = parameters; setName("Candlestick"); } /** * Returns the plot parameters. * * @return The plot parameters. */ public CandlestickPlotParameters getParameters() { return parameters; } /** * Check if this bar or candlestick is bullish. * * @return A boolean indicating if this bar or candlestick is bullish. */ public boolean isBullish() { return Data.isBullish(getData()); } /** * Check if this bar or candlestick is bearish. * * @return A boolean indicating if this bar or candlestick is bearish. */ public boolean isBearish() { return Data.isBearish(getData()); } /** * Returns the candlestick shape. * * @param context The plotter context. * @return The candlestick shape. */ @Override public Shape getShape(PlotterContext context) { // The values to plot. Data data = getData(); double open = data.getValue(indexes[0]); double high = data.getValue(indexes[1]); double low = data.getValue(indexes[2]); double close = data.getValue(indexes[3]); // The X coordinate to start painting. int x = context.getCoordinateX(getIndex()); // And the Y coordinate for each value. int openY = context.getCoordinateY(open); int highY = context.getCoordinateY(high); int lowY = context.getCoordinateY(low); int closeY = context.getCoordinateY(close); // The X coordinate of the vertical line, either the candle. int candlestickWidth = context.getDataItemWidth(); int verticalLineX = context.getDrawingCenterCoordinateX(x); // The bar candle is bullish/bearish. boolean bullish = Data.isBullish(data); // The candlestick shape. GeneralPath shape = new GeneralPath(GeneralPath.WIND_EVEN_ODD, 6); // If bar width is 1... if (candlestickWidth == 1) { // The vertical line only. shape.moveTo(verticalLineX, highY); shape.lineTo(verticalLineX, lowY); } else { if (bullish) { // Upper shadow. shape.moveTo(verticalLineX, highY); shape.lineTo(verticalLineX, closeY - 1); // Body. shape.moveTo(x, closeY); shape.lineTo(x + candlestickWidth - 1, closeY); shape.lineTo(x + candlestickWidth - 1, openY); shape.lineTo(x, openY); shape.lineTo(x, closeY); // Lower shadow. shape.moveTo(verticalLineX, openY + 1); shape.lineTo(verticalLineX, lowY); } else { // Upper shadow. shape.moveTo(verticalLineX, highY); shape.lineTo(verticalLineX, openY - 1); // Body. shape.moveTo(x, openY); shape.lineTo(x + candlestickWidth - 1, openY); shape.lineTo(x + candlestickWidth - 1, closeY); shape.lineTo(x, closeY); shape.lineTo(x, openY); // Lower shadow. shape.moveTo(verticalLineX, closeY + 1); shape.lineTo(verticalLineX, lowY); } } return shape; } /** * Draw the candlestick. * * @param g2 The graphics object. * @param context The plotter context. */ @Override public void draw(Graphics2D g2, PlotterContext context) { // The shape. Shape shape = getShape(context); // Save color and stroke. Color saveColor = g2.getColor(); Stroke saveStroke = g2.getStroke(); // Set the stroke. g2.setStroke(getParameters().getStroke()); // Once defined the path the paint strategy will depend on whether the border if painted or not, and whether // the color is raised or not. Color color = getParameters().getFillColor(); if (getParameters().isPaintBorder()) { if (getParameters().isColorRaised()) { // Create a raised color. Data data = getData(); double open = Data.getOpen(data); double close = Data.getClose(data); int candlestickWidth = context.getDataItemWidth(); int x = context.getCoordinateX(getIndex()); int yOpen = context.getCoordinateY(open); int yClose = context.getCoordinateY(close); Color colorRaised = ColorUtils.brighter(color, getParameters().getBrightnessFactor()); Point2D pt1; Point2D pt2; if (isBullish()) { pt1 = new Point2D.Float(x, yClose); pt2 = new Point2D.Float(x + candlestickWidth - 1, yClose); } else { pt1 = new Point2D.Float(x, yOpen); pt2 = new Point2D.Float(x + candlestickWidth - 1, yOpen); } GradientPaint raisedPaint = new GradientPaint(pt1, colorRaised, pt2, color, true); g2.setPaint(raisedPaint); g2.fill(shape); } else { // Set the fill color and do fill. g2.setPaint(color); g2.fill(shape); } // Set the border color and draw the path. g2.setPaint(getParameters().getBorderColor()); g2.draw(shape); } else { // Set the fill color and do fill. g2.setPaint(color); g2.fill(shape); g2.draw(shape); } // Restore color and stroke. g2.setColor(saveColor); g2.setStroke(saveStroke); } }
package util.localVersion; import trees.localVersion.Node; import util.ReadWritePhaseStrategy; public class LocalVersionReadWritePhase<K,V> extends ReadWritePhaseStrategy<K,V>{ @Override public Node<K,V> assign(Node<K,V> prevValue, Node<K,V> newValue, Thread self) { acquire(newValue, self); release(prevValue); return newValue; } @Override public Node<K,V> acquire(Node<K,V> node, Thread self) { if (node != null) { node.acquire(self); } return node; } @Override public void release(Node<K,V> node) { if (node != null){ node.release(); } } }
package LeetCode.DynamicProgramming; import java.util.HashMap; public class TwoNonOverlappingSumK { public int minOfLengths(int[] arr, int target){ int sum = 0, l = Integer.MAX_VALUE, res = Integer.MAX_VALUE; HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, -1); for(int i = 0; i < arr.length; i++){ sum += arr[i]; map.put(sum, i); } sum = 0; for(int i = 0; i < arr.length; i++){ sum += arr[i]; if(map.containsKey(sum-target)) l = Math.min(l, i - map.get(sum - target)); if(map.containsKey(sum+target) && l < Integer.MAX_VALUE) res = Math.min(res, map.get(sum+target) - i + l); } return res == Integer.MAX_VALUE ? -1 : res; } public static void main(String[] args){ TwoNonOverlappingSumK tn = new TwoNonOverlappingSumK(); int[] arr = {3, 2, 2, 4, 3}; int t = 3; System.out.print(tn.minOfLengths(arr, t)); } }
package ElementsOfProgrammingInterview.chapter10.Exercise5.SumBinary; import ElementsOfProgrammingInterview.chapter10.BinaryTreeNode; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class Solution { public static int sumRootToLeaf(BinaryTreeNode<Integer> root) { // find paths from root -> leaf // convert path to number => += sum return sumRootToLeafHelper(root, 0); } private static int sumRootToLeafHelper(BinaryTreeNode<Integer> node, int partialPathSum) { if (node == null) { return 0; } // key partialPathSum = partialPathSum * 2 + node.data; // reaching the leaf node if (node.left == null && node.right == null) { return partialPathSum; } // non-leaf var leftSumRootToLeaf = sumRootToLeafHelper(node.left, partialPathSum); var rightSumRootToLeaf = sumRootToLeafHelper(node.right, partialPathSum); return leftSumRootToLeaf + rightSumRootToLeaf; } public static void printAllPaths(BinaryTreeNode<Integer> node) { Stack<Integer> paths = new Stack<>(); printAllPath(node, paths); } public static void printAllPath(BinaryTreeNode<Integer> node, Stack<Integer> paths) { // pre-order // create an array, put path into it, when reaching leaf => print if (node == null) return; paths.push(node.data); if (node.left == null && node.right == null) { for (Integer element : paths) { System.out.print(element + "->"); } System.out.println(); } else { printAllPath(node.left, paths); printAllPath(node.right, paths); } paths.pop(); } public static List<String> binaryTreePaths(BinaryTreeNode<Integer> root) { var result = new ArrayList<String>(); Stack<Integer> paths = new Stack<>(); printAllPaths(root, paths, result); return result; } // leetcode private static void printAllPaths(BinaryTreeNode<Integer> node, Stack<Integer> paths, List<String> result){ if (node == null) return; paths.push(node.data); if (node.left == null && node.right == null) { int i = 0; StringBuilder sb = new StringBuilder(); for (Integer element : paths) { sb.append(element); if (i < paths.size() - 1) sb.append("->"); i++; } result.add(sb.toString()); } else { printAllPaths(node.left, paths, result); printAllPaths(node.right, paths, result); } paths.pop(); } public static void main(String[] args) { var root = new BinaryTreeNode<>(1); root.left = new BinaryTreeNode<>(0); root.right = new BinaryTreeNode<>(1); root.left.left = new BinaryTreeNode<>(0); root.left.right = new BinaryTreeNode<>(1); root.right.right = new BinaryTreeNode<>(1); root.right.left = new BinaryTreeNode<>(0); printAllPaths(root); System.out.println(sumRootToLeaf(root)); } }
package com.lera.vehicle.reservation.repository.vehicle; public class ModelRepositoryTest { }
package com.github.emailtohl.integration.web.service.flow; import org.springframework.data.jpa.repository.JpaRepository; /** * 流程数据的存档 * @author HeLei */ interface FlowRepository extends JpaRepository<FlowData, Long> { FlowData findByProcessInstanceId(String processInstanceId); FlowData findByFlowNum(String flowNum); }
package sfd; /** * Created by zhuxinquan on 16-8-28. */ public class Student { private String sno; private String name; private String academy; private String department; private String classAndGrade; public Student() { } public Student(String sno, String name, String academy, String department, String classAndGrade) { this.sno = sno; this.name = name; this.academy = academy; this.department = department; this.classAndGrade = classAndGrade; } public String getSno() { return sno; } public void setSno(String sno) { this.sno = sno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAcademy() { return academy; } public void setAcademy(String academy) { this.academy = academy; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getClassAndGrade() { return classAndGrade; } public void setClassAndGrade(String classAndGrade) { this.classAndGrade = classAndGrade; } }
package Interfaces; public interface Term { public double getCoefficient(); public int getExponent(); public double evaluate(double x); }
package com.tencent.mm.plugin.fav.b.d; class a$a { int errCode; int ewn; final /* synthetic */ a iXG; long iXJ; private a$a(a aVar) { this.iXG = aVar; this.errCode = 0; } /* synthetic */ a$a(a aVar, byte b) { this(aVar); } }
package com.akiosoft.mycoach.com.akiosoft.mycoach; import android.accounts.Account; import android.accounts.AccountManager; import android.app.AlertDialog; import android.app.DialogFragment; import android.app.Fragment; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.akiosoft.coachapi.server.dao.coachApi.CoachApi; import com.akiosoft.coachapi.server.dao.coachApi.model.Sport; import com.akiosoft.mycoach.AppConstants; import com.akiosoft.mycoach.Application; import com.akiosoft.mycoach.R; import com.akiosoft.mycoach.com.akiosoft.mycoach.dialog.AbstractCallbackDialog; import com.akiosoft.mycoach.com.akiosoft.mycoach.dialog.CreateSportDialog; import com.akiosoft.mycoach.com.akiosoft.mycoach.dialog.DeleteConfirmationFragment; import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.common.AccountPicker; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.json.GenericJson; import com.google.api.client.util.Strings; import java.io.IOException; import java.util.List; /** * Created by nvoskeritchian on 9/12/14. */ public abstract class AbstractModelFragment<T extends GenericJson> extends Fragment implements View.OnClickListener, AbstractCallbackDialog.NoticeDialogListener { protected final String LOG_TAG = this.getClass().getName(); private static final int ACTIVITY_RESULT_FROM_ACCOUNT_SELECTION = 2222; private DataAdapter<T> mListAdapter; private AuthorizationCheckTask mAuthTask; private String mEmailAccount = ""; protected T selectedItem; private ListView listView; public AbstractModelFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_sports, container, false); listView = (ListView) rootView.findViewById(R.id.model_list_view); mListAdapter = new DataAdapter<T>((Application) getActivity().getApplication()){ }; listView.setAdapter(mListAdapter); listView.setLongClickable(true); listView.setClickable(true); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) { DeleteConfirmationFragment d = new DeleteConfirmationFragment(); d.setTargetFragment(AbstractModelFragment.this, 0); d.show(getFragmentManager(), (String)((T) parent.getItemAtPosition(position)).get("label")); return true; } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { selectedItem = (T) adapterView.getItemAtPosition(position); } }); Button b = (Button) rootView.findViewById(R.id.sign_in_button); b.setOnClickListener(this); // b = (Button) rootView.findViewById(R.id.create_sport_button); // b.setOnClickListener(this); // b = (Button) rootView.findViewById(R.id.get_all_sport_button); b.setOnClickListener(this); this.onClickSignIn(rootView); return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.sports_action_items, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // handle item selection switch (item.getItemId()) { case R.id.new_item: Log.d(LOG_TAG, "New action item selected"); this.onNewActionItemSelected(); return true; case R.id.delete_item: Log.d(LOG_TAG, "Delete action item selected"); if(selectedItem!=null) { DeleteConfirmationFragment dc = new DeleteConfirmationFragment(); dc.setTargetFragment(AbstractModelFragment.this, 0); dc.show(getFragmentManager(), (String)((GenericJson)selectedItem).get("label")); } else { Toast.makeText(getActivity(), "You must select an item first.", Toast.LENGTH_LONG).show(); } return true; default: return super.onOptionsItemSelected(item); } } protected abstract boolean onNewActionItemSelected(); @Override public void onClick(View v) { switch (v.getId()) { case R.id.sign_in_button: onClickSignIn(v); break; // case R.id.get_all_sport_button: // this.populateItemList(v); // break; // case R.id.create_sport_button: // this.createNewSport(v); // break; } } public void onClickSignIn(View view) { //REVERT TextView emailAddressTV = (TextView) view.getRootView().findViewById(R.id.email_address_tv); // Check to see how many Google accounts are registered with the device. int googleAccounts = AppConstants.countGoogleAccounts(getActivity()); if (googleAccounts == 0) { // No accounts registered, nothing to do. Toast.makeText(getActivity(), R.string.toast_no_google_accounts_registered, Toast.LENGTH_LONG).show(); } else if (googleAccounts == 1) { // If only one account then select it. Toast.makeText(getActivity(), R.string.toast_only_one_google_account_registered, Toast.LENGTH_LONG).show(); AccountManager am = AccountManager.get(getActivity()); Account[] accounts = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE); if (accounts != null && accounts.length > 0) { // Select account and perform authorization check. emailAddressTV.setText(accounts[0].name); mEmailAccount = accounts[0].name; performAuthCheck(accounts[0].name); this.populateItemList(view); } } else { // More than one Google Account is present, a chooser is necessary. // Reset selected account. emailAddressTV.setText(""); // Invoke an {@code Intent} to allow the user to select a Google account. Intent accountSelector = AccountPicker.newChooseAccountIntent(null, null, new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, false, "Select the account to access the HelloEndpoints API.", null, null, null); startActivityForResult(accountSelector, ACTIVITY_RESULT_FROM_ACCOUNT_SELECTION); } } public void performAuthCheck(String emailAccount) { // Cancel previously running tasks. if (mAuthTask != null) { try { mAuthTask.cancel(true); } catch (Exception e) { e.printStackTrace(); } } new AuthorizationCheckTask().execute(emailAccount); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { //REVERT super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTIVITY_RESULT_FROM_ACCOUNT_SELECTION && resultCode == getActivity().RESULT_OK) { // This path indicates the account selection activity resulted in the user selecting a // Google account and clicking OK. // Set the selected account. String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); TextView emailAccountTextView = (TextView) getActivity().findViewById(R.id.email_address_tv); emailAccountTextView.setText(accountName); // Fire off the authorization check for this account and OAuth2 scopes. performAuthCheck(accountName); } } public void populateItemList(View unused) { if (!isSignedIn()) { Toast.makeText(getActivity(), "You must sign in for this action.", Toast.LENGTH_LONG).show(); return; } AsyncTask<Void, Void, List<T>> getAuthedSportList = new AsyncTask<Void, Void, List<T>>() { @Override protected List<T> doInBackground(Void... unused) { if (!isSignedIn()) { return null; } ; if (!AppConstants.checkGooglePlayServicesAvailable(getActivity())) { return null; } // Create a Google credential since this is an authenticated request to the API. GoogleAccountCredential credential = GoogleAccountCredential.usingAudience( getActivity(), AppConstants.AUDIENCE); credential.setSelectedAccountName(mEmailAccount); // Retrieve service handle using credential since this is an authenticated call. CoachApi apiServiceHandle = AppConstants.getApiServiceHandle(credential); try { CoachApi.CoachAPI.GetAllSports getAuthedGreetingCommand = apiServiceHandle.coachAPI().getAllSports(); GenericJson greeting = getAuthedGreetingCommand.execute(); return (List<T>)greeting.get("items"); } catch (IOException e) { Log.e(LOG_TAG, "Exception during API call", e); } return null; } @Override protected void onPostExecute(List<T> greeting) { if (greeting != null) { displayItems(greeting); } else { Log.e(LOG_TAG, "No greetings were returned by the API."); } } }; getAuthedSportList.execute((Void) null); } private void displayItems(List<T> greetings) { String msg; if (greetings == null || greetings.size() < 1) { msg = "Greeting was not present"; Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show(); } else { Log.d(LOG_TAG, "Displaying " + greetings.size() + " greetings."); // List<Sport> greetingsList = greetings.Arrays.asList(greetings); mListAdapter.replaceData(greetings); } } protected abstract void onDeleteItemConfirmed(T item); @Override public void onDialogConfirmClick(DialogFragment dialog) { if (dialog instanceof DeleteConfirmationFragment && selectedItem !=null) { Log.e(LOG_TAG, "Delete sport was selected"); this.onDeleteItemConfirmed(selectedItem); listView.clearChoices(); selectedItem = null; } } @Override public void onDialogCancelClick(DialogFragment dialog) { Toast.makeText(getActivity(), "Cancel was touched", Toast.LENGTH_SHORT).show(); } private boolean isSignedIn() { if (!Strings.isNullOrEmpty(mEmailAccount)) { return true; } else { return false; } } class AuthorizationCheckTask extends AsyncTask<String, Integer, Boolean> { @Override protected Boolean doInBackground(String... emailAccounts) { Log.i(LOG_TAG, "Background task started."); if (!AppConstants.checkGooglePlayServicesAvailable(getActivity())) { return false; } String emailAccount = emailAccounts[0]; // Ensure only one task is running at a time. mAuthTask = this; // Ensure an email was selected. if (Strings.isNullOrEmpty(emailAccount)) { publishProgress(R.string.toast_no_google_account_selected); // Failure. return false; } Log.d(LOG_TAG, "Attempting to get AuthToken for account: " + mEmailAccount); try { // If the application has the appropriate access then a token will be retrieved, otherwise // an error will be thrown. GoogleAccountCredential credential = GoogleAccountCredential.usingAudience( getActivity(), AppConstants.AUDIENCE); credential.setSelectedAccountName(emailAccount); String accessToken = credential.getToken(); Log.d(LOG_TAG, "AccessToken retrieved"); // Success. return true; } catch (GoogleAuthException unrecoverableException) { Log.e(LOG_TAG, "Exception checking OAuth2 authentication.", unrecoverableException); publishProgress(R.string.toast_exception_checking_authorization); // Failure. return false; } catch (IOException ioException) { Log.e(LOG_TAG, "Exception checking OAuth2 authentication.", ioException); publishProgress(R.string.toast_exception_checking_authorization); // Failure or cancel request. return false; } } @Override protected void onProgressUpdate(Integer... stringIds) { // Toast only the most recent. Integer stringId = stringIds[0]; Toast.makeText(getActivity(), stringId, Toast.LENGTH_SHORT).show(); } @Override protected void onPreExecute() { mAuthTask = this; } @Override protected void onPostExecute(Boolean success) { //REVERT TextView emailAddressTV = (TextView) getActivity().findViewById(R.id.email_address_tv); if (success) { // Authorization check successful, set internal variable. mEmailAccount = emailAddressTV.getText().toString(); } else { // Authorization check unsuccessful, reset TextView to empty. emailAddressTV.setText(""); } mAuthTask = null; } @Override protected void onCancelled() { mAuthTask = null; } } }
package com.iontrading.buildbot; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.pircbotx.Colors; import org.pircbotx.PircBotX; import org.pircbotx.hooks.Event; import org.pircbotx.hooks.Listener; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.core.Persister; import com.iontrading.model.Build; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.io.impl.Base64; /** * @author g.arora@iontrading.com * @version $Id$ * @since 0.7.6 */ public class Bot extends PircBotX implements Listener<Bot> { private static final String CHANNEL = "#xtp-tests"; private static final Pattern BUILDINFO = Pattern.compile(".*::([a-zA-Z_]*) #(\\d+).*"); private static final Pattern BUILDID = Pattern.compile(".*buildId=(\\d+)&.*"); private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = Executors.newScheduledThreadPool(1); private static final Set<String> REPORTED_BUILDS = new HashSet<String>(); private static final AtomicBoolean START = new AtomicBoolean(true); public Bot() { setName("buildbot"); } public static void main(String[] args) throws Exception { final Bot bot = new Bot(); bot.setVerbose(true); // Connect to the IRC server. bot.connect("192.168.45.44", 6697); // Join the #pircbot channel. bot.joinChannel(CHANNEL); bot.sendMessage(CHANNEL, Colors.UNDERLINE + "Up & running, will report build status"); SCHEDULED_EXECUTOR_SERVICE.scheduleWithFixedDelay(new Runnable() { public void run() { try { System.out.println("Getting builds"); for (SyndEntry entry : getBuilds()) { String key = makeKey(entry.getTitle()); // System.out.println("Key is " + key); if (START.get()) { REPORTED_BUILDS.add(key); } if (REPORTED_BUILDS.contains(key)) { // System.out.println("Key found " + key); continue; } // System.out.println("Seding key " + key); if (entry.getAuthor().contains("Failed")) { String link = entry.getLink(); Matcher matcher = BUILDID.matcher(link); String failures = ""; if (matcher.matches() && matcher.groupCount() > 0) { URL url = new URL("http://192.168.150.38/httpAuth/app/rest/builds/id:" + matcher.group(1)); System.out.println("URL is " + url); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); String encoded = Base64.encode("garora:gaurav"); httpcon.setRequestProperty("Authorization", "Basic " + encoded); Serializer serializer = new Persister(); Build build = serializer.read(Build.class, httpcon.getInputStream()); System.out.println(build.getStatusText()); failures = build.getStatusText(); } bot.sendMessage(CHANNEL, Colors.RED + entry.getTitle() + " (" + link + ") [" + failures + "]"); } if (entry.getAuthor().contains("Success")) { bot.sendMessage(CHANNEL, Colors.DARK_GREEN + entry.getTitle() + " (" + entry.getLink() + ")"); } REPORTED_BUILDS.add(key); } START.set(false); } catch (Exception e) { e.printStackTrace(); } } private String makeKey(String title) { Matcher matcher = BUILDINFO.matcher(title); matcher.matches(); matcher.groupCount(); return matcher.group(1) + "_" + matcher.group(2); } }, 1, 120, TimeUnit.SECONDS); } private static final List<SyndEntry> getFails() throws Exception { List<SyndEntry> entries = new ArrayList<SyndEntry>(); for (SyndEntry entry : getBuilds()) { if (entry.getAuthor().contains("Failed")) { entries.add(entry); } } return entries; } private static final List<SyndEntry> getBuilds() throws Exception { List<SyndEntry> entries = new ArrayList<SyndEntry>(); Iterator iterator = App.readFeed(); while (iterator.hasNext()) { entries.add((SyndEntry) iterator.next()); } return entries; } /** {@inheritDoc} */ // @Override // protected void onPrivateMessage(String sender, String login, String hostname, String message) { // super.onPrivateMessage(sender, login, hostname, message); // if (message.equals("!fails")) { // try { // for (SyndEntry entry : getFails()) { // sendMessage(CHANNEL, entry.getTitle() + "(" + entry.getLink() + ")"); // } // } catch (Exception e) { // e.printStackTrace(); // } // } else if (message.equals("!checkbuild")) { // System.out.println("check builds"); // try { // URL url = new URL("http://192.168.150.38/httpAuth/app/rest/builds/id:875130"); // HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); // String encoded = Base64.encode("garora:gaurav"); // httpcon.setRequestProperty("Authorization", "Basic " + encoded); // // Serializer serializer = new Persister(); // Build build = serializer.read(Build.class, httpcon.getInputStream()); // System.out.println(build.getStatusText()); // } catch (Exception e) { // e.printStackTrace(); // } // } // } /** {@inheritDoc} */ public void onEvent(Event<Bot> event) throws Exception { System.out.println(event); } }
package com.sunsun.nbapic.Frament; import android.os.Message; import com.kugou.framework.component.base.BaseWorkerFragment; public class GalleryFragment extends BaseWorkerFragment { public static GalleryFragment newInstance() { GalleryFragment fragment = new GalleryFragment(); return fragment; } @Override protected void handleBackgroundMessage(Message msg) { } }
package L5; public class Car { private String vin; private String color; private String model; private double price; public String getVin() { return vin; } public void setVin(String vin){ this.vin = vin; } public String getColor(){ return color; } public void setColor(){ this.color = color; } public String getModel(){ return model; } public void setModel(String model){ this.model = model; } public double getPrice(){ return price; } public void setPrice(double price){ this.price = price; } }
public class Leaf implements Cluster{ // Holds single element private UnitRow unitRow; private int depth; private int width; Leaf(Unit unit){ unitRow = new UnitRow(1); unitRow.addPredefinedUnit(unit); depth = 0; width = 1; } public int getDepth(){ return depth; } public int getWidth(){ return width; } public UnitRow getUnits(){ return unitRow; } public boolean hasChildren(){ return false; } }
import lab01.example.model.AccountHolder; import lab01.example.model.BankAccount; import lab01.example.model.SimpleBankAccountWithAtm; public class SimpleBankAccountWithAtmTest extends AbstractBankAccountTest { @Override public BankAccount getBankAccount(final AccountHolder accountHolder) { return new SimpleBankAccountWithAtm(accountHolder, 0); } @Override int getExpectedDeposit() { return 99; } @Override int getExpectedWrongDeposit() { return 99; } @Override int getExpectedWithdraw() { return 28; } @Override int getExpectedWrongWithdraw() { return 99; } }
package marchal.gabriel.bl.Usuario; import marchal.gabriel.bl.Administrador.Administrador; import marchal.gabriel.bl.Coleccionista.Coleccionista; import marchal.gabriel.dl.Conector; import java.sql.ResultSet; import java.time.LocalDate; import java.util.ArrayList; /** * @author Gabriel Marchal * @version V1 * @since 2020-07-31 * */ public class MySqlUsuario implements IUsuarioDAO{ @Override public Usuario retornarUsuario(String email) throws Exception { System.out.println("CALL BD retornarUsuario"); String queryColeccionista = "SELECT * FROM collectorsbazar.coleccionistas WHERE correoelectronico = '"+email+"' ;"; String queryAdministrador ="SELECT * FROM collectorsbazar.administradores WHERE correoelectronico = '"+email+"';"; Usuario usuario = null; ResultSet rs = Conector.getConnector().ejecutarSELECT(queryColeccionista); if(rs.next()){ Coleccionista coleccionista = new Coleccionista(); coleccionista.setIdentificacion(rs.getString("identificacion")); coleccionista.setNombre(rs.getString("nombre")); coleccionista.setCorreoElectronico(rs.getString("correoelectronico")); coleccionista.setContrasena(rs.getString("contrasena")); coleccionista.setFechaNacimiento(LocalDate.parse(rs.getDate("fechanacimiento").toString())); coleccionista.setEstado(rs.getBoolean("estado")); coleccionista.setAvatar(rs.getString("avatar")); coleccionista.setDireccion(rs.getString("direccion")); coleccionista.setCalificacion(rs.getInt("calificacion")); coleccionista.setEsModerador(rs.getBoolean("esmoderador")); usuario = coleccionista; }else{ rs = Conector.getConnector().ejecutarSELECT(queryAdministrador); if(rs.next()){ Administrador administrador = new Administrador(); administrador.setIdentificacion(rs.getString("identificacion")); administrador.setNombre(rs.getString("nombre")); administrador.setCorreoElectronico(rs.getString("correoelectronico")); administrador.setContrasena(rs.getString("contrasena")); administrador.setFechaNacimiento( LocalDate.parse(rs.getDate("fechanacimiento").toString())); administrador.setEstado(rs.getBoolean("estado")); administrador.setAvatar(rs.getString("avatar")); usuario = administrador; } } return usuario; } @Override public int editarPerfilUsuario(Usuario usuario) { System.out.println("CALL BD editarPerfilUsuario"); String query; if(usuario instanceof Coleccionista){ query = "UPDATE collectorsbazar.coleccionistas "; query += "SET direccion = '"+((Coleccionista) usuario).getDireccion()+"', "; query+= " esmoderador= "+((Coleccionista) usuario).isEsModerador()+", "; }else{ query = "UPDATE collectorsbazar.administradores "; query +="SET "; } query += " estado= "+usuario.isEstado()+", "; query+=" avatar = '"+usuario.getAvatar()+"', "; query +="identificacion = '"+usuario.getIdentificacion()+"', "; query +=" nombre = '"+usuario.getNombre()+"', "; query += "fechanacimiento = '"+usuario.getFechaNacimiento().toString()+"' "; query +=" WHERE correoelectronico = '"+usuario.getCorreoElectronico()+"';"; int exitoso; try { Conector.getConnector().ejecutarINSERT_UPDATE_DELETE(query); exitoso = 1; } catch (Exception e) { System.out.println(e.getMessage()); exitoso = 0; } return exitoso; } @Override public void cambiarContrasena(Usuario usuario, String nuevaContrasena) { System.out.println("CALL BD cambiarContrasena"); String query; if(usuario instanceof Administrador){ query = "UPDATE collectorsbazar.administradores "; }else{ query = "UPDATE collectorsbazar.coleccionistas "; } query += "SET contrasena = '"+nuevaContrasena+"' "; query+= "WHERE correoelectronico = '"+usuario.getCorreoElectronico()+"';"; try { Conector.getConnector().ejecutarINSERT_UPDATE_DELETE(query); } catch (Exception e) { System.out.println(e.getMessage()); } } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.cmsitems.impl; import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.SESSION_CLONE_COMPONENT_CONTEXT; import de.hybris.platform.cmsfacades.cmsitems.CloneComponentContextProvider; import de.hybris.platform.core.model.ItemModel; import de.hybris.platform.servicelayer.session.SessionService; import java.util.Deque; import java.util.LinkedList; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; import org.springframework.beans.factory.annotation.Required; /** * Default implementation of {@link CloneComponentContextProvider} responsible for storing (in a stack-like data * structure) context information per transaction when cloning a component. */ public class DefaultCloneComponentContextProvider implements CloneComponentContextProvider { private SessionService sessionService; @Override public void initializeItem(final Entry<String, Object> entry) { Object value = getValueFromSession(false); if (value == null) { final Deque<ItemModel> stack = new LinkedList<>(); value = new AtomicReference<>(stack); getSessionService().setAttribute(SESSION_CLONE_COMPONENT_CONTEXT, value); } getWrappedStack(value).push(entry); } @Override public boolean isInitialized() { return getValueFromSession(false) != null; } @Override public Entry<String, Object> getCurrentItem() { final Object value = getValueFromSession(true); return getWrappedStack(value).peek(); } @Override public Object findItemForKey(final String key) { final Object value = getValueFromSession(false); return value == null ? value : getWrappedStack(value).stream().filter(entry -> entry.getKey().equals(key)).map(Entry::getValue) .findFirst().orElse(null); } @Override public void finalizeItem() { final Object value = getValueFromSession(true); getWrappedStack(value).pop(); } /** * Get the value stored in the session associated to the key {@code SESSION_CLONE_COMPONENT_CONTEXT} * * @param shouldThrowException * when set to <tt>TRUE</tt>, an {@link IllegalStateException} is thrown if no value is found in the * session * @return the value stored in the session */ protected Object getValueFromSession(final boolean shouldThrowException) { final Object value = getSessionService().getAttribute(SESSION_CLONE_COMPONENT_CONTEXT); if (value == null && shouldThrowException) { throw new IllegalStateException( "There is no current entry. Please Initialize with #initializeItem before using this method."); } return value; } /** * Values stored in the session service must be wrapped in AtomicReference objects to protect them from being altered * during serialization. When values are read from the session service, they must be unwrapped. Thus, this method is * used to retrieve the original value (stack) stored in the AtomicReference wrapper. * * @param rawValue * Object retrieved from the session service. The object must be an AtomicReference. Otherwise, an * IllegalStateException is thrown. * @return stack stored within the AtomicReference. */ @SuppressWarnings("unchecked") protected Deque<Entry<String, Object>> getWrappedStack(final Object rawValue) { if (rawValue instanceof AtomicReference) { final AtomicReference<Deque<Entry<String, Object>>> originalValue = (AtomicReference<Deque<Entry<String, Object>>>) rawValue; return originalValue.get(); } throw new IllegalStateException( "Session object for SESSION_CLONE_ITEM_CONTEXT should hold a reference of AtomicReference object."); } protected SessionService getSessionService() { return sessionService; } @Required public void setSessionService(final SessionService sessionService) { this.sessionService = sessionService; } }
package ch.ubx.startlist.server; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ch.ubx.startlist.shared.FeFlightEntry; public class ExcelFileServlet extends HttpServlet { private static final long serialVersionUID = 1L; private FlightEntryDAO2 flightEntryDAO = new FlightEntryDAOobjectify2(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); int year = 0; int month = -1; int day = -1; String place = ""; List<FeFlightEntry> flightEnties = null; String[] params = pathInfo.split("/"); year = Integer.parseInt(params[1]); if (params.length == 2) { year = Integer.parseInt(params[1]); flightEnties = flightEntryDAO.listflightEntry(year); } else if (params.length == 3) { // flightEnties = flightEntryDAO.listflightEntry(Integer.parseInt(params[1]), Integer.parseInt(params[2])); // TODO - // what for is this? // month } else if (params.length == 5) { year = Integer.parseInt(params[1]); month = Integer.parseInt(params[2]); day = Integer.parseInt(params[3]); place = params[4]; flightEnties = flightEntryDAO.listflightEntry(year, month, day, place); } else { return; } if (flightEnties != null) { String sheetname = String.valueOf(year) + (month == -1 ? "" : String.format("%02d", month + 1)) + (day == -1 ? "" : String.format("%02d", day)) + "-" + place.replace(" ", "_"); String filename = sheetname + ".xls"; resp.setContentType("application/ms-excel"); resp.setHeader("Content-Disposition", "attachment; filename=" + filename); ExcelSheet.createExcel(flightEnties, resp.getOutputStream(), sheetname); } } }
package com.sourceallies.web; import net.sourceforge.jwebunit.htmlunit.HtmlUnitTestingEngineImpl; import net.sourceforge.jwebunit.junit.WebTestCase; import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController; import com.gargoylesoftware.htmlunit.WebClient; public class AjaxWebTest extends WebTestCase{ public void setUp() throws Exception{ super.setUp(); setBaseUrl("http://localhost:8888/interview-webapp"); } public void testWithoutAjaxEnabled() { beginAt("/show/time.do"); assertTitleEquals("Show Time"); assertTextNotInElement("time", "The current time in milliseconds is: "); clickButton("retrieveTime"); assertTextNotInElement("time", "The current time in milliseconds is: "); } public void testWithAjaxEnabled() { beginAt("/show/time.do"); HtmlUnitTestingEngineImpl engine = (HtmlUnitTestingEngineImpl) getTestingEngine(); WebClient webClient = engine.getWebClient(); webClient.waitForBackgroundJavaScript(10000); webClient.setAjaxController(new NicelyResynchronizingAjaxController()); assertTitleEquals("Show Time"); assertTextNotInElement("time", "The current time in milliseconds is: "); clickButton("retrieveTime"); assertTextInElement("time", "The current time in milliseconds is: "); } }
package com.projects.houronearth.activities.activities; 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.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import com.projects.houronearth.R; import com.projects.houronearth.activities.adapters.VikritiResultsAdapter; import com.projects.houronearth.activities.fragments.VikritiResultsFragment; import com.projects.houronearth.activities.utils.ActivityUtils; public class VikritiActivity extends AppCompatActivity { private Toolbar mToolbar; private RecyclerView mResultsRecyclerView; private Button mNextButton; private VikritiResultsAdapter mVikritiResultAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_vikriti); initView(); setEventClickListener(); //setAdapter(); } private void loadVikritiResultFragment() { VikritiResultsFragment vikritiResultsFragment = VikritiResultsFragment.newInstance(); ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), vikritiResultsFragment, R.id.fl_vikriti_activity); } private void setEventClickListener() { mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //go back to home activity } }); } private void initView() { mToolbar = findViewById(R.id.toolbar_vikriti_activity); mToolbar.setTitle("Vikriti"); mToolbar.setNavigationIcon(R.drawable.back_arrow_grey); mResultsRecyclerView = findViewById(R.id.rv_results); mNextButton = findViewById(R.id.btn_next_vikriti_activity); StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL); staggeredGridLayoutManager.offsetChildrenHorizontal(0); staggeredGridLayoutManager.offsetChildrenVertical(0); mResultsRecyclerView.setLayoutManager(staggeredGridLayoutManager); } /* private void setAdapter() { mVikritiResultAdapter = new VikritiResultsAdapter(VikritiActivity.this); mResultsRecyclerView.setAdapter(mVikritiResultAdapter); }*/ }
/* * 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 org.forit.corsoDiStudi.servlet; import java.io.IOException; import java.io.PrintWriter; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.forit.corsoDiStudi.dao.CorsoDiStudiDAO; import org.forit.corsoDiStudi.dto.ProfessoreDTO; import org.forit.corsoDiStudi.exceptions.CDSException; /** * * @author UTENTE */ public class ProfessoriServlet extends CorsoDiStudiServlet { private final static String THEAD = "<thead>" + " <tr>" + " <th class='col-sm-1'>" + " <a href='?action=new' class='btn btn-primary'>Nuovo</a>" + " </th>" + " <th class='col-sm-2'>Nome</th>" + " <th class='col-sm-2'>Cognome</th>" + " <th class='col-sm-3'>Email</th>" + " </tr>" + "</thead>"; private final static String THEAD_MATERIA = "<thead>" + " <tr>" + " <th class='col-sm-12'>Nome Materia</th>" + " </tr>" + "</thead>"; private final static String THEAD_ESAMI = "<thead>\n" + " <tr>\n" + "\n" + " <th class='col-sm-4'>Materia</th>\n" + " <th class='col-sm-2'>Valutazione</th>\n" + " <th class='col-sm-2'>Data</th>\n" + " <th class='col-sm-2'>Studente</th>\n" + "\n" + " </tr>\n" + " </thead>"; @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { long ID = Long.parseLong(req.getParameter("id")); String nome = req.getParameter("nome"); String cognome = req.getParameter("cognome"); String mail = req.getParameter("mail"); try { ProfessoreDTO prof = new ProfessoreDTO(ID, nome, cognome, mail); CorsoDiStudiDAO corsoDAO = new CorsoDiStudiDAO(); corsoDAO.updateProfessore(prof); resp.sendRedirect("professori"); // resp.sendRedirect("clienti"); } catch (CDSException ex) { System.out.println("Si è verificato un errore " + ex.getMessage()); if (ID == -1) { resp.sendRedirect("professori?ID=&action=view"); } else { resp.sendRedirect("professori?ID=" + ID + "&action=edit"); } } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); String action = req.getParameter("action"); if (action == null) { this.listaProfessori(resp); } else { switch (action) { case "view": String ID = req.getParameter("ID"); this.dettaglioProfessore(resp, Long.parseLong(ID), true); break; case "edit": ID = req.getParameter("ID"); this.dettaglioProfessore(resp, Long.parseLong(ID), false); break; case "new": this.dettaglioProfessore(resp, -1, false); break; default: this.listaProfessori(resp); } } } private void dettaglioProfessore(HttpServletResponse resp, long ID, boolean disabled) throws IOException { ProfessoreDTO prof = null; String messaggioErrore = null; if (ID == -1) { prof = new ProfessoreDTO(-1, "", "", ""); prof.setId(-1); } else { try { CorsoDiStudiDAO corsoDAO = new CorsoDiStudiDAO(); prof = corsoDAO.getProfessore(ID); } catch (CDSException ex) { messaggioErrore = "Impossibile leggere i dati dal database"+ ex.getMessage(); } } try (PrintWriter out = resp.getWriter()) { this.apriHTML(out, messaggioErrore, "$$clienti$$"); if (prof != null) { this.creaDettaglioProfessore(out, prof, disabled); } this.chiudiHTML(out); } } private void creaDettaglioProfessore(PrintWriter out, ProfessoreDTO professore, boolean disabled) { out.println("<form class='container-fluid' action='professori' method='post'>"); out.println("<div class='panel panel-default'>"); out.println("<div class='panel-heading'>"); out.println("<div class='panel-title'>Dettaglio Professore</div>"); out.println("</div>"); out.println("<div class='panel-body'>"); out.println("<input type='hidden' name='id' value='" + professore.getId() + "' />"); this.creaDatiAnagrafici(out, professore, disabled); this.creaTabellaMateria(out, professore); this.createTabellaEsami(out, professore); out.println("</div>"); out.println("<div class='panel-footer text-right'>"); if (!disabled) { out.println("<input type='submit' class='btn btn-primary' value='Salva Modifiche'/>"); } out.println("</div>"); out.println("</div>"); out.println("</form>"); } private void listaProfessori(HttpServletResponse resp) throws IOException { List<ProfessoreDTO> professori; String messaggioErrore = null; try { CorsoDiStudiDAO corsoDiStudiDAO = new CorsoDiStudiDAO(); professori = corsoDiStudiDAO.getListaProfessori(); } catch (CDSException ex) { professori = new ArrayList<>(); messaggioErrore = "Impossibile leggere i dati dal database" + ex.getLocalizedMessage(); } try (PrintWriter out = resp.getWriter()) { this.apriHTML(out, messaggioErrore, "$$professori$$"); this.createTabellaProfessori(out, professori); this.chiudiHTML(out); } } private void creaDatiAnagrafici(PrintWriter out, ProfessoreDTO professore, boolean disabled) { out.println("<div class='row'>"); out.println("<div class='col-sm-6'>"); out.println("<label>Nome</label>"); out.println("<input type='text' name='nome' class='form-control' value='" + professore.getNome() + "'" + (disabled ? " disabled='disabled'" : "") + ">"); out.println("</div>"); out.println("<div class='col-sm-6'>"); out.println("<label>Cognome</label>"); out.println("<input type='text' name='cognome' class='form-control' value='" + professore.getCognome() + "'" + (disabled ? " disabled='disabled'" : "") + ">"); out.println("</div>"); out.println("</div>"); out.println("<div class='row'>"); out.println("<div class='col-sm-12'>"); out.println("<label>Email</label>"); out.println("<input type='email' name='mail' class='form-control' value='" + professore.getEmail() + "'" + (disabled ? " disabled='disabled'" : "") + ">"); out.println("</div>"); out.println("</div>"); } private void creaTabellaMateria(PrintWriter out, ProfessoreDTO professore) { out.println("<div class='row'>"); out.println("<div class='col-sm-12'>"); out.println("<h3>Materia</h3>"); out.println("</div>"); out.println("<table class='table'>"); out.println(THEAD_MATERIA); out.println("<tbody'>"); professore.getMateria().forEach(materia -> { out.println("<tr>"); out.println("<td>" + materia.getNome() + "</td>"); out.println("</tr>"); }); out.println("</tbody'>"); out.println("</table>"); out.println("</div>"); } private void createTabellaEsami(PrintWriter out, ProfessoreDTO professore) { out.println(" <div class='row'>"); out.println(" <div class='col-sm-12'>"); out.println(" <h3>Esami</h3>"); out.println(" </div>"); out.println(" </div>"); out.println(" <div class='table-responsive'>"); out.println(" <table class='table'>"); out.println(THEAD_ESAMI); out.println("<tbody>"); professore.getVoti().forEach(voto -> { out.println("<tr>"); out.println("<td>" + voto.getMateria() + "</td>"); out.println("<td>" + voto.getValutazione() + "[in mesi] </td>"); out.println("<td>" + voto.getDataVoto().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")) + "</td>"); out.println("</tr>"); }); out.println("</tbody>"); out.println(" </table>"); out.println(" </div> "); } private void createTabellaProfessori(PrintWriter out, List<ProfessoreDTO> professori) { out.println("<div class='table-responsive'>"); out.println("<table class='table'>"); out.println(THEAD); out.println("<tbody>"); professori.forEach(professore -> { out.println("<tr>"); out.println(" <td>"); out.println(" <a href='?ID=" + professore.getId() + "&action=view' class='btn btn-default' title='Visualizza Dettaglio'>"); out.println(" <span class='glyphicon glyphicon-eye-open'></span>"); out.println(" </a>"); out.println(" <a href='?ID=" + professore.getId() + "&action=edit' class='btn btn-default' title='Modifica Dati'>"); out.println(" <span class='glyphicon glyphicon-pencil'></span>"); out.println(" </a>"); out.println(" </td>"); out.println(" <td>" + professore.getNome() + "</td>"); out.println(" <td>" + professore.getCognome() + "</td>"); out.println(" <td>" + professore.getEmail() + "</td>"); out.println("</tr>"); }); out.println("</tbody>"); out.println("</table>"); out.println("</div>"); } }
package com.kdp.wanandroidclient.ui.core.model.impl; import com.kdp.wanandroidclient.bean.Chapter; import com.kdp.wanandroidclient.net.RxSchedulers; import com.kdp.wanandroidclient.net.callback.RxObserver; import com.kdp.wanandroidclient.ui.core.model.IChapterModel; import java.util.List; /*** * @author kdp * @date 2019/3/25 16:35 * @description */ public class ChapterModel extends BaseModel implements IChapterModel{ /** * 获取公众号 * @param rxObserver */ @Override public void getChapters(RxObserver<List<Chapter>> rxObserver) { doRxRequest() .getChapters() .compose(RxSchedulers.<List<Chapter>>io_main()) .subscribe(rxObserver); } }
package com.kh.runLearn.member.model.vo; import java.sql.Date; public class Member_Image { private String m_origin_name; private String m_changed_name; private Date m_upload_date; private String m_id; public Member_Image() {} public Member_Image(String m_origin_name, String m_changed_name, Date m_upload_date, String m_id) { super(); this.m_origin_name = m_origin_name; this.m_changed_name = m_changed_name; this.m_upload_date = m_upload_date; this.m_id = m_id; } public String getM_origin_name() { return m_origin_name; } public void setM_origin_name(String m_origin_name) { this.m_origin_name = m_origin_name; } public String getM_changed_name() { return m_changed_name; } public void setM_changed_name(String m_changed_name) { this.m_changed_name = m_changed_name; } public Date getM_upload_date() { return m_upload_date; } public void setM_upload_date(Date m_upload_date) { this.m_upload_date = m_upload_date; } public String getM_id() { return m_id; } public void setM_id(String m_id) { this.m_id = m_id; } @Override public String toString() { return "MemberImage [m_origin_name=" + m_origin_name + ", m_changed_name=" + m_changed_name + ", m_upload_date=" + m_upload_date + ", m_id=" + m_id + "]"; } }
package com.kh.efp.login.google.model.dao; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; import com.kh.efp.member.model.vo.Member; import com.kh.efp.member.model.vo.Profile; @Repository public class GgDaoImpl implements GgDao{ @Override public Member selectGGMember(SqlSessionTemplate sqlSession, Member m) { // TODO Auto-generated method stub return sqlSession.selectOne("Login.selectMember", m); } @Override public int insertGGMember(SqlSessionTemplate sqlSession, Member m) { // TODO Auto-generated method stub return sqlSession.insert("Login.insertGGMember", m); } @Override public int insertGGProfile(SqlSessionTemplate sqlSession, Profile pf) { // TODO Auto-generated method stub return sqlSession.insert("Login.insertProfile", pf); } }
package io.github.skyhacker2.home_component.component; import android.content.Context; import io.github.skyhacker2.export_api.component_home.ComponentHome; import io.github.skyhacker2.home_component.HomeActivity; public class ComponentHomeImpl implements ComponentHome { @Override public void goToHome(Context context) { HomeActivity.start(context); } @Override public String getName() { return "ComponentHomeImpl"; } }
/* * 文 件 名: SignInController.java * 描 述: SignInController.java * 时 间: 2013-7-14 */ package com.babyshow.operator.controller; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.babyshow.operator.bean.Operator; import com.babyshow.operator.dao.OperatorDao; /** * <一句话功能简述> * * @author ztc * @version [BABYSHOW V1R1C1, 2013-7-14] */ @Controller public class SignInController { @Autowired private HttpServletRequest httpServletRequest; @Autowired private OperatorDao operatorDao; private static final String SIGNIN_MESSAGE = "message"; private static final String SIGNIN_PASSWORD_ERROR = "密码错误"; /** * 登录rest地址重定向至jsp页面 * * @param model * @return */ @RequestMapping(value = "/signin", method = RequestMethod.GET) public @ResponseBody ModelAndView signInForward(Map<String,Object> model) { return new ModelAndView("forward:/page/signin/signin.jsp"); } /** * * 登录控制 * * @param username * @param password * @param model * @return */ @RequestMapping(value = "/signin", method = RequestMethod.POST) public @ResponseBody ModelAndView signIn(String username, String password, Map<String,Object> model, HttpSession session) { Operator operator = this.operatorDao.findOperatorByLoginName(username); if (isValid(operator, password)) { session.setAttribute("operator", username); return new ModelAndView("redirect:/rest/mock/upload"); } else { model.put(SIGNIN_MESSAGE, SIGNIN_PASSWORD_ERROR); return new ModelAndView("forward:/page/signin/signin.jsp"); } } /** * * 登出控制 * * @param username * @param password * @param model * @return */ @RequestMapping(value = "/signout", method = RequestMethod.GET) public @ResponseBody ModelAndView signOut(String username, String password, Map<String,Object> model, HttpSession session) { session.removeAttribute("operator"); return new ModelAndView("forward:/page/signin/signin.jsp"); } /** * * 校验登录 * * @param loginForm * @return */ public boolean isValid(Operator operator, String password) { if (operator != null && operator.getPassword() != null && operator.getPassword().equals(password)) { return true; } else { return false; } } }
import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.stream.IntStream; /** * Assembler : * 이 프로그램은 SIC/XE 머신을 위한 Assembler 프로그램의 메인 루틴이다. * 프로그램의 수행 작업은 다음과 같다. * 1) 처음 시작하면 Instruction 명세를 읽어들여서 assembler를 세팅한다. * 2) 사용자가 작성한 input 파일을 읽어들인 후 저장한다. * 3) input 파일의 문장들을 단어별로 분할하고 의미를 파악해서 정리한다. (pass1) * 4) 분석된 내용을 바탕으로 컴퓨터가 사용할 수 있는 object code를 생성한다. (pass2) * * * 작성중의 유의사항 : * 1) 새로운 클래스, 새로운 변수, 새로운 함수 선언은 얼마든지 허용됨. 단, 기존의 변수와 함수들을 삭제하거나 완전히 대체하는 것은 안된다. * 2) 마찬가지로 작성된 코드를 삭제하지 않으면 필요에 따라 예외처리, 인터페이스 또는 상속 사용 또한 허용됨. * 3) 모든 void 타입의 리턴값은 유저의 필요에 따라 다른 리턴 타입으로 변경 가능. * 4) 파일, 또는 콘솔창에 한글을 출력시키지 말 것. (채점상의 이유. 주석에 포함된 한글은 상관 없음) * * * + 제공하는 프로그램 구조의 개선방법을 제안하고 싶은 분들은 보고서의 결론 뒷부분에 첨부 바랍니다. 내용에 따라 가산점이 있을 수 있습니다. */ public class Assembler { /** instruction 명세를 저장한 공간 */ InstTable instTable; /** 읽어들인 input 파일의 내용을 한 줄 씩 저장하는 공간. */ ArrayList<String> lineList; /** 프로그램의 section별로 symbol table을 저장하는 공간*/ ArrayList<SymbolTable> symtabList; /** 프로그램의 section별로 literal table을 저장하는 공간*/ ArrayList<LiteralTable> literaltabList; /** 프로그램의 section별로 프로그램을 저장하는 공간*/ ArrayList<TokenTable> TokenList; /** * Token, 또는 지시어에 따라 만들어진 오브젝트 코드들을 출력 형태로 저장하는 공간. * 필요한 경우 String 대신 별도의 클래스를 선언하여 ArrayList를 교체해도 무방함. */ ArrayList<String> codeList; /** * 클래스 초기화. instruction Table을 초기화와 동시에 세팅한다. * * @param instFile : instruction 명세를 작성한 파일 이름. */ public Assembler(String instFile) { instTable = new InstTable(instFile); lineList = new ArrayList<String>(); symtabList = new ArrayList<SymbolTable>(); literaltabList = new ArrayList<LiteralTable>(); TokenList = new ArrayList<TokenTable>(); codeList = new ArrayList<String>(); } /** * 어셈블러의 메인 루틴 */ public static void main(String[] args) { Assembler assembler = new Assembler("inst.data"); assembler.loadInputFile("input.txt"); assembler.pass1(); assembler.printSymbolTable(null); assembler.printLiteralTable(null); assembler.printSymbolTable("symtab_20160283.txt"); assembler.printLiteralTable("literaltab_20160283.txt"); assembler.pass2(); assembler.printObjectCode("output_20160283.txt"); assembler.printObjectCode(null); } /** * inputFile을 읽어들여서 lineList에 저장한다. * @param inputFile : input 파일 이름. */ private void loadInputFile(String inputFile) { File file = new File("src//"+inputFile); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; while((line = br.readLine())!= null) { lineList.add(line); } } catch (IOException e) { e.printStackTrace(); } } /** * pass1 과정을 수행한다. * 1) 프로그램 소스를 스캔하여 토큰단위로 분리한 뒤 토큰테이블 생성 * 2) label을 symbolTable에 정리 * * 주의사항 : SymbolTable과 TokenTable은 프로그램의 section별로 하나씩 선언되어야 한다. */ private void pass1() { //SYMTAB과 LITTAB를 생성한 뒤 list에 넣어주기 SymbolTable symTab = new SymbolTable(); LiteralTable litTab = new LiteralTable(); symtabList.add(symTab); literaltabList.add(litTab); //TokenTable 생성 뒤 SYMTAB와 LITTAB 링크해주기 TokenTable tokenTab = new TokenTable(symTab, litTab, instTable); TokenList.add(tokenTab); //token idx int t_idx = 0; //한줄씩 읽어 토큰화 진행 for(int i = 0 ; i <lineList.size();i++) { if(lineList.get(i) !=null&& lineList.get(i).charAt(0)=='.') continue; /* * 새로운 Control Section 시작 */ if(lineList.get(i).contains("CSECT")) { //새로운 Section Control 시작 시 변수 초기화 symTab = new SymbolTable(); litTab = new LiteralTable(); tokenTab = new TokenTable(symTab, litTab, instTable); symtabList.add(symTab); literaltabList.add(litTab); TokenList.add(tokenTab); t_idx = 0; } tokenTab.putToken(lineList.get(i)); // Token t = tokenTab.getToken(t_idx); t_idx++; } } /** * 작성된 SymbolTable들을 출력형태에 맞게 출력한다. * @param fileName : 저장되는 파일 이름 */ private void printSymbolTable(String fileName) { PrintStream out = null; //fileName이 Null일 경우 표준 출력 if(fileName == null) out= new PrintStream(System.out); else { //null이 아닐 경우 fileName에 wirte하기 try { String path = System.getProperty("user.dir"); File file = new File(path+"\\src\\"+fileName); out = new PrintStream(new FileOutputStream(file)); } catch(IOException e){ e.printStackTrace(); } } //출력하기 : SymbolTable Class toString() Method Override for(SymbolTable symTab : symtabList) { out.println(symTab); } } /** * 작성된 LiteralTable들을 출력형태에 맞게 출력한다. * @param fileName : 저장되는 파일 이름 */ private void printLiteralTable(String fileName) { PrintStream out = null; if(fileName == null) out= new PrintStream(System.out); else { //null이 아닐 경우 fileName에 wirte하기 try { String path = System.getProperty("user.dir"); File file = new File(path+"\\src\\"+fileName); out = new PrintStream(new FileOutputStream(file)); } catch(IOException e){ e.printStackTrace(); } } //출력하기 : LiteralTable Class toString() Method Override for(LiteralTable litTab : literaltabList) { out.print(litTab); } } /** * pass2 과정을 수행한다. * 1) 분석된 내용을 바탕으로 object code를 생성하여 codeList에 저장. */ private void pass2() { for(TokenTable tt:TokenList) { StringBuilder sb = new StringBuilder(); for(int i = 0 ; i <tt.tokenList.size();i++) { tt.makeObjectCode(i); Token t = tt.getToken(i); switch (t.record) { case 'H': sb = new StringBuilder(); //H Record일 때 sb.append('H'); //프로그램 이름 6자리 sb.append(String.format("%-6s",t.label)); //프로그램 시작 주소 sb.append(String.format("%06X",t.location)); //프로그램 길이 int sum_len = tt.tokenList.stream().mapToInt(tok->tok.byteSize).sum(); sb.append(String.format("%06X", sum_len)); codeList.add(sb.toString()); sb = new StringBuilder(); break; case 'D': //D Record sb.append('D'); //외부로 보내는 변수이름 + 위치 for(int j = 0 ; j < TokenTable.MAX_OPERAND;j++) { if(t.operand[j] == null) break; //외부로 보내는 변수 이름 sb.append(String.format("%-6s",t.operand[j])); //외부로 보내는 변수 위치 sb.append(String.format("%06X",tt.symTab.search(t.operand[j]))); } codeList.add(sb.toString()); sb = new StringBuilder(); break; case 'R': //R Record 일 때 sb.append('R'); for(int j = 0 ; j < TokenTable.MAX_OPERAND;j++) { if(t.operand[j] == null) break; sb.append(String.format("%-6s", t.operand[j])); } codeList.add(sb.toString()); sb = new StringBuilder(); break; case 'T': //T Record 출력 sb.append('T'); //시작 주소 출력 sb.append(String.format("%06X",tt.getToken(i-1).location)); //해당 라인의 길이의 합을 저장 int sum = 0; //현재 토큰 T 중 어느 위치에 있는지 확인한다. int idx_T = 0; for(int j = i;j<tt.tokenList.size();j++) { tt.makeObjectCode(j); if(tt.getToken(j).objectCode == null&&tt.getToken(j).record!='T') { idx_T = j; break; } sum += tt.getToken(j).byteSize; if(sum>30) { idx_T = j; sum -= tt.getToken(j).byteSize; break; } if(j==tt.tokenList.size()-1) idx_T = j+1; } sb.append(String.format("%02X", sum)); //object code for(int j = i;j<idx_T;j++) { sb.append(tt.getToken(j).objectCode); } i = idx_T-1; codeList.add(sb.toString()); sb = new StringBuilder(); break; case 'E': break; } //M Record 출력 EX) M 위치 + Reference일때 더할것 if(i == tt.tokenList.size()-1) { for(Token tok:tt.tokenList) { for(int j = 0;j<tok.memoCnt;j++) { //4형식일 경우 if(tok.byteSize == 4) { sb.append('M'); sb.append(String.format("%06X05",(int)(tok.location-2.5))); //EXTREF 사용 시 if(tt.refList.indexOf(tok.operand[0])>=0) { sb.append('+'); sb.append(String.format("%-6s",tok.operand[0])); } codeList.add(sb.toString()); sb = new StringBuilder(); } if(tok.byteSize == 3) { String[] st = null; sb.append('M'); //Expression이 + 일때 if(tok.operand[0].contains("+")) { st = tok.operand[0].split("+"); sb.append(String.format("%06X06",tok.location-3)); sb.append("+"); sb.append(String.format("%-6s",st[j])); } //Expression이 - 일때 else if(tok.operand[0].contains("-")) { st = tok.operand[0].split("-"); sb.append(String.format("%06X06",tok.location-3)); if(j==0) sb.append("+"); else sb.append("-"); sb.append(String.format("%-6s",st[j])); } codeList.add(sb.toString()); sb = new StringBuilder(); } } } //E 출력 sb.append('E'); if(tt.isMain) sb.append(String.format("%06X",0)); sb.append("\n"); codeList.add(sb.toString()); sb = new StringBuilder(); } } } } /** * 작성된 codeList를 출력형태에 맞게 출력한다. * @param fileName : 저장되는 파일 이름 */ private void printObjectCode(String fileName) { PrintStream out = null; if(fileName == null) out = new PrintStream(System.out); else { try { String path = System.getProperty("user.dir"); File file = new File(path+"\\src\\"+fileName); out = new PrintStream(new FileOutputStream(file)); } catch(IOException ie) { ie.printStackTrace(); } } for(String str:codeList) { out.println(str); } } }
package com.it.userportrait.entity; import java.util.ArrayList; import java.util.List; import java.util.Map; public class SandianEntity { private List<String> dataList = new ArrayList<String>(); private List<List<Object>> listxiaomi = new ArrayList<List<Object>>(); private List<List<Object>> huaweilist = new ArrayList<List<Object>>(); private List<List<Object>> oppolist = new ArrayList<List<Object>>(); private List<List<Object>> list1 = new ArrayList<List<Object>>(); private List<List<Object>> list2 = new ArrayList<List<Object>>(); private List<List<Object>> list3 = new ArrayList<List<Object>>(); public List<String> getDataList() { return dataList; } public void setDataList(List<String> dataList) { this.dataList = dataList; } public List<List<Object>> getListxiaomi() { return listxiaomi; } public void setListxiaomi(List<List<Object>> listxiaomi) { this.listxiaomi = listxiaomi; } public List<List<Object>> getHuaweilist() { return huaweilist; } public void setHuaweilist(List<List<Object>> huaweilist) { this.huaweilist = huaweilist; } public List<List<Object>> getOppolist() { return oppolist; } public void setOppolist(List<List<Object>> oppolist) { this.oppolist = oppolist; } public List<List<Object>> getList1() { return list1; } public void setList1(List<List<Object>> list1) { this.list1 = list1; } public List<List<Object>> getList2() { return list2; } public void setList2(List<List<Object>> list2) { this.list2 = list2; } public List<List<Object>> getList3() { return list3; } public void setList3(List<List<Object>> list3) { this.list3 = list3; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.fernando.projects; import java.util.ArrayList; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * * @author Fernando */ public abstract class Employee extends Thread implements Comparable<Employee>{ protected String type; protected EmployeePriority ePriority; private Call callEmployee; private Dispatcher dispatcher; public Employee(String type, Dispatcher dispatcher) { this.type = type; this.dispatcher = dispatcher; } public String getType() { return type; } public int getPriorities() { return this.ePriority.getPriority(); } //Al usar una PriorityBlockingQueue es necesario implementar esta funcion, la cual utiliza para evaluar las prioridades public int compareTo(Employee emp) { if (this.getPriority() < emp.getPriority()) { return -1; } if (this.getPriority() > emp.getPriority()) { return 1; } return 0; } public void setType(String eType) { this.type = eType; } abstract void addAvailableEmployee(Dispatcher disp); public void asignCall(Call call) throws InterruptedException { this.callEmployee = call; this.start(); } // Hilo de atencion de llamada. public void run() { try { Thread.sleep(1000 * callEmployee.getDuration()); System.out.println( "Llamada " + callEmployee.getDescription() + " terminada. Duracion:" + callEmployee.getDuration() + " milisegundos"); this.addAvailableEmployee(dispatcher); System.out.println("Empleado " + this.getType() + " disponible"); } catch (InterruptedException e) { System.out.println("Error al responder la llamada " + callEmployee.getDescription()); e.printStackTrace(); } } }
package dan.ndvor.com.dangol; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import dan.ndvor.com.util.control.SQLiteHandler; import dan.ndvor.com.util.control.SessionManager; import dan.ndvor.com.util.control.u00_ApiConnector_store; /** * Created by macbook on 16. 2. 5.. */ public class f01_tabview_menulike extends Activity implements View.OnClickListener { private String categoryName; private ImageView categoryView; private ListView GetAllCustomerListView; private JSONArray jsonArray; private TextView top, below; private ImageView backButton; private String uid; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; private SQLiteHandler db; private SessionManager session; HashMap<String, String> user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.e00_like_list); // SqLite database handler db = new SQLiteHandler(getApplicationContext()); user = db.getUserDetails(); uid = user.get("uid"); this.categoryName = getIntent().getStringExtra("category"); Toast.makeText(this, categoryName, Toast.LENGTH_LONG).show(); this.categoryView = (ImageView) findViewById(R.id.storeCategoryImageView); this.GetAllCustomerListView = (ListView) findViewById(R.id.my_store_list); this.top = (TextView) findViewById(R.id.storeCategory_text_top); this.below = (TextView) findViewById(R.id.storeCategory_text_below); this.backButton = (ImageView) findViewById(R.id.back_button); this.backButton.setOnClickListener(this); new GetAllStoreTask().execute(new u00_ApiConnector_store()); this.GetAllCustomerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { try { //Get the customer which was clicked. JSONObject customerClicked = jsonArray.getJSONObject(position); //Send Customer id Intent showDetails = new Intent(getApplicationContext(), f11_detail_bottom01.class); showDetails.putExtra("storeID", customerClicked.getInt("id")); showDetails.putExtra("storeTel", customerClicked.getString("storeTel")); startActivity(showDetails); } catch (JSONException e) { } } }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } public void setListAdapter(JSONArray jsonArray) { if(jsonArray == null){ this.GetAllCustomerListView.setEmptyView(findViewById(R.id.emptyElement)); } else { this.jsonArray = jsonArray; this.GetAllCustomerListView.setAdapter(new f01_adapter_menulike(this.getApplicationContext(), jsonArray, this, uid)); } } @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "f22_cat_bottom02 Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://dan.ndvor.com.dangol/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "f22_cat_bottom02 Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://dan.ndvor.com.dangol/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.back_button: finish(); break; } } private class GetAllStoreTask extends AsyncTask<u00_ApiConnector_store, Long, JSONArray> { @Override protected JSONArray doInBackground(u00_ApiConnector_store... params) { // it is executed on Background thread return params[0].GetAllListFromLikeTable(uid); } @Override protected void onPostExecute(JSONArray jsonArray) { setListAdapter(jsonArray); } } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.move_left_in_activity, R.anim.move_right_out_activity); } }
package Test; import java.util.PriorityQueue; /** * @author admin * @version 1.0.0 * @ClassName test1.java * @Description TODO * @createTime 2021年03月12日 15:41:00 */ public class test1 { class Solution { public int maxSumDivThree(int[] nums) { PriorityQueue<Integer> list1 = new PriorityQueue<>(); PriorityQueue<Integer> list2 = new PriorityQueue<>(); int total = 0; for (int i = 0; i < nums.length; i++) { int result = nums[i] % 3; if(result==1)list1.offer(nums[i]); if(result==2)list2.offer(nums[i]); total += nums[i]; } int result = total % 3; while(result!=0){ if(result==1){ if(list1.isEmpty() && list2.size()<2){ return 0; } int total1 = minus(list1,total); int total2 = minus(list2,minus(list2,total)); total = Math.max(total1,total2); } if(result==2){ if(list2.isEmpty() && list1.size()<2){ return 0; } int total1 = minus(list1,minus(list1,total)); int total2 = minus(list2,total); total = Math.max(total1,total2); } result = total % 3; } return total; } private int minus(PriorityQueue<Integer> list,int total){ if(list.isEmpty())return -1; total = total - list.poll(); return total; } } }
package com.gotkx.utils.random; import java.util.Random; /** * 生成一个随机四位数,每位数字不重复。 */ public class RandomNum { public static void main(String[] args) { generateNum(); } private static void generateNum() { Random random = new Random(); int[] arr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; StringBuffer stringBuffer = new StringBuffer(); int tmp = 0; while (stringBuffer.length() < 4) { tmp = random.nextInt(10);//0-9的随机数 if (arr[tmp] == 0) { stringBuffer.append(tmp); arr[tmp] = 1; } } System.out.println(stringBuffer); } }
package com.tencent.mm.boot.svg.a.a; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import android.os.Looper; import com.tencent.mm.svg.WeChatSVGRenderC2Java; import com.tencent.mm.svg.c; public final class adl extends c { private final int height = 90; private final int width = 90; protected final int b(int i, Object... objArr) { switch (i) { case 0: return 90; case 1: return 90; case 2: Canvas canvas = (Canvas) objArr[0]; Looper looper = (Looper) objArr[1]; Matrix f = c.f(looper); float[] e = c.e(looper); Paint i2 = c.i(looper); i2.setFlags(385); i2.setStyle(Style.FILL); Paint i3 = c.i(looper); i3.setFlags(385); i3.setStyle(Style.STROKE); i2.setColor(-16777216); i3.setStrokeWidth(1.0f); i3.setStrokeCap(Cap.BUTT); i3.setStrokeJoin(Join.MITER); i3.setStrokeMiter(4.0f); i3.setPathEffect(null); Paint a = c.a(i3, looper); a.setStrokeWidth(1.0f); canvas.save(); e = c.a(e, 1.0f, 0.0f, -166.0f, 0.0f, 1.0f, -265.0f); f.reset(); f.setValues(e); canvas.concat(f); canvas.save(); e = c.a(e, 1.0f, 0.0f, 166.0f, 0.0f, 1.0f, 265.0f); f.reset(); f.setValues(e); canvas.concat(f); Paint a2 = c.a(i2, looper); a2.setColor(838860800); canvas.save(); Paint a3 = c.a(a2, looper); Path j = c.j(looper); j.moveTo(45.0f, 0.0f); j.cubicTo(69.85281f, 0.0f, 90.0f, 20.147184f, 90.0f, 45.0f); j.cubicTo(90.0f, 69.85281f, 69.85281f, 90.0f, 45.0f, 90.0f); j.cubicTo(20.147184f, 90.0f, 0.0f, 69.85281f, 0.0f, 45.0f); j.cubicTo(0.0f, 20.147184f, 20.147184f, 0.0f, 45.0f, 0.0f); j.close(); canvas.drawPath(j, a3); canvas.restore(); canvas.save(); a3 = c.a(a, looper); a3.setColor(-1); a3.setStrokeWidth(6.0f); j = c.j(looper); j.moveTo(45.0f, 3.0f); j.cubicTo(68.19596f, 3.0f, 87.0f, 21.804039f, 87.0f, 45.0f); j.cubicTo(87.0f, 68.19596f, 68.19596f, 87.0f, 45.0f, 87.0f); j.cubicTo(21.804039f, 87.0f, 3.0f, 68.19596f, 3.0f, 45.0f); j.cubicTo(3.0f, 21.804039f, 21.804039f, 3.0f, 45.0f, 3.0f); j.close(); canvas.drawPath(j, a3); canvas.restore(); canvas.save(); a3 = c.a(i2, looper); a3.setColor(-1); j = c.j(looper); j.moveTo(57.0f, 42.0f); j.lineTo(63.43934f, 35.56066f); j.cubicTo(64.02512f, 34.974873f, 64.97488f, 34.974873f, 65.56066f, 35.56066f); j.cubicTo(65.841965f, 35.841965f, 66.0f, 36.223495f, 66.0f, 36.62132f); j.lineTo(66.0f, 53.37868f); j.cubicTo(66.0f, 54.207108f, 65.32843f, 54.87868f, 64.5f, 54.87868f); j.cubicTo(64.10217f, 54.87868f, 63.720646f, 54.720646f, 63.43934f, 54.43934f); j.lineTo(57.0f, 48.0f); j.lineTo(57.0f, 42.0f); j.close(); j.moveTo(26.208f, 33.0f); j.lineTo(51.792f, 33.0f); j.cubicTo(53.011444f, 33.0f, 54.0f, 33.988556f, 54.0f, 35.208f); j.lineTo(54.0f, 54.792f); j.cubicTo(54.0f, 56.011444f, 53.011444f, 57.0f, 51.792f, 57.0f); j.lineTo(26.208f, 57.0f); j.cubicTo(24.988556f, 57.0f, 24.0f, 56.011444f, 24.0f, 54.792f); j.lineTo(24.0f, 35.208f); j.cubicTo(24.0f, 33.988556f, 24.988556f, 33.0f, 26.208f, 33.0f); j.close(); WeChatSVGRenderC2Java.setFillType(j, 2); canvas.drawPath(j, a3); canvas.restore(); canvas.restore(); canvas.restore(); c.h(looper); break; } return 0; } }
/* * 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 classes; import Exceptions.AddPatientListException; import Exceptions.LoginFailedException; import Exceptions.LoginRegisteredException; import Exceptions.ProtocolSyntaxException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; /** * Do the communication with the server, receive and send messages from/to it * @author Lokisley Oliveira <lokisley at hotmail.com> */ public class MyThread extends Thread{ private Socket socket; private ObjectInputStream input; private ObjectOutputStream output; private MessageController mController = MessageController.getInstance(); public MyThread (Socket socket) throws IOException{ this.socket = socket; input = new ObjectInputStream(socket.getInputStream()); output = new ObjectOutputStream(socket.getOutputStream()); } /** * Keep the communication open to receive externals messages, treats it, and throw possibles exeptions, if necessary */ @Override public void run () { try { while (true) { boolean message = mController.getMessage((String)receiveMessage(), this); if (message){ sendMessage("ioth ok"); } } } catch (IOException ex) { System.out.println("A thread has closed his connection"); } catch (LoginFailedException ex) { try { sendMessage("ioth error login"); } catch (IOException ex1) { System.out.println("An unexpected error during the response"); } } catch (LoginRegisteredException ex) { try { sendMessage("ioth error register"); } catch (IOException ex1) { System.out.println("An unexpected error during the response"); } } catch (AddPatientListException ex) { try { sendMessage("ioth error addpatient"); } catch (IOException ex1) { System.out.println("An unexpected error during the response"); } } catch (ProtocolSyntaxException ex) { try { sendMessage("ioth error syntax"); } catch (IOException ex1) { System.out.println("An unexpected error during the response"); } } catch (ClassNotFoundException ex) { System.out.println("An unnexpected error occured"); } } public void sendMessage (Object obj) throws IOException { output.writeObject(obj); } public Object receiveMessage () throws IOException, ClassNotFoundException { return input.readObject(); } }
package com.noteshare.course.course.services.impl; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.noteshare.common.model.Page; import com.noteshare.common.utils.page.PageConstants; import com.noteshare.common.utils.page.PageUtil; import com.noteshare.course.CourseConstant; import com.noteshare.course.course.dao.CourseMapper; import com.noteshare.course.course.model.Course; import com.noteshare.course.course.services.CourseService; @Service public class CourseServiceImpl implements CourseService{ @Resource private CourseMapper courseMapper; @Override public Course selectByPrimaryKey(Integer id) { return courseMapper.selectByPrimaryKey(id); } @Override public void updateByPrimaryKeySelective(Course course) { courseMapper.updateByPrimaryKey(course); } @Override public void insertSelective(Course course) { courseMapper.insertSelective(course); } @Override public Page<Course> selectCourseListByPage(int currentPage, int startPageNumber, int endPageNumber,int size, String publish) { Page<Course> page = new Page<Course>(); //查询总数 HashMap<String,String> totalCondition = new HashMap<String,String>(); totalCondition.put("publish", publish); int total = courseMapper.selectCourseTotal(totalCondition); HashMap<String,Object> paramMap = PageUtil.getBaseParamMap(page,total,currentPage,size); paramMap.put("publish", publish); List<Course> list = courseMapper.selectCourseListByPage(paramMap); page.setList(list); PageUtil.setPage(page,currentPage, startPageNumber, endPageNumber,PageConstants.PAGEFLAGNUMBER,PageConstants.MAXPAGENUMBER); return page; } @Override public List<Course> selectCourseListByRecommend() { HashMap<String,Object> paraMap = new HashMap<String,Object>(); //是否发布 paraMap.put("publish", "Y"); //是否推荐 paraMap.put("recommend", "Y"); //查询多少条 paraMap.put("start", CourseConstant.COURSE_RECOMMEND_START); paraMap.put("size", CourseConstant.COURSE_RECOMMEND_END); return courseMapper.selectCourseListByPage(paraMap); } }
/* * Copyright (C) 2020-2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.services.txn.token; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INVALID_TOKEN_ID; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.OK; import com.hedera.mirror.web3.evm.store.Store; import com.hedera.services.store.models.Id; import com.hederahashgraph.api.proto.java.ResponseCodeEnum; import com.hederahashgraph.api.proto.java.TokenUnpauseTransactionBody; import com.hederahashgraph.api.proto.java.TransactionBody; /** * Copied Logic type from hedera-services. * <p> * Differences with the original: * 1. Use abstraction for the state by introducing {@link Store} interface * 2. Used token.setPaused instead of token.changePauseStatus (like in services) * 3. Used store.updateToken(token) instead of tokenStore.commitToken(token) (like in services) */ public class UnpauseLogic { public void unpause(final Id targetTokenId, final Store store) { /* --- Load the model objects --- */ var token = store.loadPossiblyPausedToken(targetTokenId.asEvmAddress()); /* --- Do the business logic --- */ var unpausedToken = token.setPaused(false); /* --- Persist the updated models --- */ store.updateToken(unpausedToken); } public ResponseCodeEnum validateSyntax(TransactionBody txnBody) { TokenUnpauseTransactionBody op = txnBody.getTokenUnpause(); if (!op.hasToken()) { return INVALID_TOKEN_ID; } return OK; } }
package com.lingnet.vocs.service.remoteDebug; import com.lingnet.common.service.BaseService; import com.lingnet.vocs.entity.OperatingParameter; /** * 设备远程调试 * @ClassName: RemoteDebugService * @Description: TODO * @author tangjw * @date 2017年6月2日 上午10:38:32 * */ public interface RemoteDebugService extends BaseService<OperatingParameter, String> { }
/* * 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 pe.gob.onpe.adan.dao.adan; import java.util.List; import pe.gob.onpe.adan.helper.Filtro; import pe.gob.onpe.adan.model.adan.Reporte; /** * * @author marrisueno */ public interface ReporteDao { Reporte findById(int id); List<Reporte> findAllReporte(); Reporte findByCodigo(String codigo); List execute(String sql, Filtro filter, String url); List execute(String sql, String url); }
package com.xj.mapper; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.xj.entity.LinkRoomUser; public interface LinkRoomUserMapper extends BaseMapper<LinkRoomUser> { }
/* * UCF COP3330 Fall 2021 Assignment 2 Solution * Copyright 2021 Maggie Perry */ /* Tax Calculator prompt for order amount orderAmount = nextDouble() prompt for state state = nextLine() if state = "WI" add tax at 5.5% Output total */ package exercise14; import java.text.NumberFormat; import java.util.Locale; import java.util.Scanner; public class Solution14 { private static final Scanner sc = new Scanner(System.in); static double orderAmount; static String state; static double tax; static double orderTotal; public static void main(String[] args) { System.out.println("What is the order amount?"); String orderAmt = sc.nextLine(); orderAmount = Math.ceil( Double.parseDouble(orderAmt) * 100) / 100; System.out.println("What is the state?"); state = sc.nextLine(); setTax(state); returnOrderTotal(); } private static void returnOrderTotal() { Locale usa = new Locale("en", "US"); NumberFormat dollarFormat = NumberFormat.getCurrencyInstance(usa); System.out.printf("The subtotal is %s.%n",dollarFormat.format(orderAmount)); if(tax != 0){ System.out.printf("The tax is %s.%n",dollarFormat.format(tax)); } orderTotal = orderAmount + tax; System.out.printf("The total is: %s.%n",dollarFormat.format(orderTotal)); } private static void setTax(String state) { if (state.equals("WI")) tax = Math.ceil(orderAmount * 5.5) / 100; else tax = 0; } }
package com.tencent.mm.plugin.appbrand.widget.input.autofill; import com.tencent.mm.plugin.appbrand.widget.input.z.c; class b$2 implements c { final /* synthetic */ b gKd; b$2(b bVar) { this.gKd = bVar; } public final void apy() { this.gKd.apY(); } }
package com.sales.mapper; import com.sales.entity.CustomerLevelEntity; import java.util.List; import java.util.Map; public interface CustomerLevelMapper { List<CustomerLevelEntity> findList(Map<String, Object> params); CustomerLevelEntity findInfo(Map<String, Object> params); Integer doInsert(CustomerLevelEntity customerLevelEntity); Integer doUpdate(CustomerLevelEntity customerLevelEntity); Integer doDelete(int customerLevelId); }
package calendar_test; import java.util.Calendar; /** * Description: * * @author Baltan * @date 2018/9/30 10:00 */ public class Test5 { public static void main(String[] args) { Calendar end = Calendar.getInstance(); end.set(Calendar.MONTH, Integer.valueOf("09") - 1); end.set(Calendar.DATE, 30); end.add(Calendar.DATE, 1); Calendar today = Calendar.getInstance(); System.out.println(today.before(end)); } }
package org.pajacyk.Zadanie1; import java.util.Random; public class Kostka { public static void main(String[] args) { System.out.println(kostka()); } public static int kostka() { Random r = new Random(); int x = r.nextInt(6); System.out.println(x); return x; } }
package org.slevin.util; import org.slevin.common.Emlak; public class EmlakQueryItem extends Emlak implements Cloneable{ String imageUrl; String description; public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
package com.espendwise.manta.web.validator; import com.espendwise.manta.spi.IAddress; import com.espendwise.manta.spi.IContact; import com.espendwise.manta.util.AppResourceHolder; import com.espendwise.manta.util.Constants; import com.espendwise.manta.util.arguments.Args; import com.espendwise.manta.util.alert.ArgumentedMessage; import com.espendwise.manta.util.alert.ArgumentedMessageImpl; import com.espendwise.manta.util.arguments.MessageI18nArgument; import com.espendwise.manta.util.validation.resolvers.AbstractAddressValidationCodeResolver; import com.espendwise.manta.util.validation.resolvers.AbstractContactValidationCodeResolver; import com.espendwise.manta.util.validation.*; import com.espendwise.manta.web.forms.AccountForm; import com.espendwise.manta.web.forms.AddressInputForm; import com.espendwise.manta.web.resolver.TextErrorWebResolver; import com.espendwise.manta.web.resolver.EmailAddressErrorWebResolver; import com.espendwise.manta.web.util.WebErrors; import org.apache.log4j.Logger; public class AccountFormValidator extends AbstractFormValidator{ private static final Logger logger = Logger.getLogger(AccountFormValidator.class); public AccountFormValidator() { super(); } @Override public ValidationResult validate(Object obj) { WebErrors errors = new WebErrors(); AccountForm valueObj = (AccountForm) obj; ValidationResult vr; TextValidator shortDescValidator = Validators.getTextValidator(Constants.VALIDATION_FIELD_CRITERIA.SHORT_DESC_LENGTH); vr = shortDescValidator.validate(valueObj.getAccountName(), new TextErrorWebResolver("admin.account.label.accountName")); if (vr != null) { errors.putErrors(vr.getResult()); } vr = shortDescValidator.validate(valueObj.getAccountStatus(), new TextErrorWebResolver("admin.account.label.status")); if (vr != null) { errors.putErrors(vr.getResult()); } vr = shortDescValidator.validate(valueObj.getAccountType(), new TextErrorWebResolver("admin.account.label.accountType")); if (vr != null) { errors.putErrors(vr.getResult()); } vr = shortDescValidator.validate(valueObj.getAccountBudgetType(), new TextErrorWebResolver("admin.account.label.budgetType")); if (vr != null) { errors.putErrors(vr.getResult()); } AccountBillingAddressValidationCodeResolver billingAddressWebErrorResolver = new AccountBillingAddressValidationCodeResolver(); AddressValidator addressValidator = Validators.getAddressValidator(isStateRequred(valueObj.getBillingAddress())); vr = addressValidator.validate(valueObj.getBillingAddress(), billingAddressWebErrorResolver); if (vr != null) { errors.putErrors(vr.getResult()); } AccountPrimaryContactValidationCodeResolver primaryContactWebErrorReslover = new AccountPrimaryContactValidationCodeResolver(); ContactValidator contactValidator = Validators.getContactValidator(isStateRequred(valueObj.getPrimaryContact().getAddress())); vr = contactValidator.validate(valueObj.getPrimaryContact(), primaryContactWebErrorReslover); if (vr != null) { errors.putErrors(vr.getResult()); } EmailAddressValidator emailValidator = Validators.getEmailAddressValidator(true); if (valueObj.getPrimaryContact().getEmail() != null) { vr = emailValidator.validate(valueObj.getPrimaryContact().getEmail(), new EmailAddressErrorWebResolver("admin.account.label.primaryContact.email")) ; if (vr != null) { errors.putErrors(vr.getResult()); } } return new MessageValidationResult(errors.get()); } private boolean isStateRequred(AddressInputForm billingAddress) { return AppResourceHolder .getAppResource() .getDbConstantsResource() .getIsStateRequiredForCountry(billingAddress.getCountryCd()); } private class AccountPrimaryContactValidationCodeResolver extends AbstractContactValidationCodeResolver { protected ArgumentedMessage isStatePrivinceMustBeEmpty(ValidationCode code) { return new ArgumentedMessageImpl("validation.web.error.variableMustBeEmpty", new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.address.state") ) ) ); } protected ArgumentedMessage isCityRangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.address.city") ) ), maxLength) ); } protected ArgumentedMessage isPostalCodeRangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.address.postalCode") ) ), maxLength) ); } protected ArgumentedMessage isStateRangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.address.state") ) ), maxLength) ); } protected ArgumentedMessage isFirstNameRangeOu(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.firstName") ) ), maxLength) ); } protected ArgumentedMessage isLastNameRangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.lastName") ) ), maxLength) ); } protected ArgumentedMessage isEmailRangeOu(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.email") ) ), maxLength) ); } protected ArgumentedMessage isFaxRangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.fax") ) ), maxLength) ); } protected ArgumentedMessage isMobileRangeOu(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.mobile") ) ), maxLength) ); } protected ArgumentedMessage isTelephoneRangeOu(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.telephone") ) ), maxLength) ); } protected ArgumentedMessage isAddress1RangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.address.address1") ) ), maxLength) ); } protected ArgumentedMessage isAddress2RangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.address.address2") ) ), maxLength) ); } protected ArgumentedMessage isAddress3RangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.address.address3") ) ), maxLength) ); } protected ArgumentedMessage isStateNotSet(ValidationCode code) { return new ArgumentedMessageImpl("validation.web.error.emptyValue", new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.primaryContact", Args.i18nTyped("admin.account.label.primaryContact.address.state") ) ) ); } @Override protected ArgumentedMessage isNotSet(String field, ValidationCode code) { if (IAddress.STATE_PROVINCE_CD.equalsIgnoreCase(field)) { return isStateNotSet(code); } return null; } @Override protected ArgumentedMessage isRangeOut(String field, ValidationCode code) { if (IAddress.ADDRESS1.equalsIgnoreCase(field)) { return isAddress1RangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IAddress.ADDRESS2.equalsIgnoreCase(field)) { return isAddress2RangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IAddress.ADDRESS3.equalsIgnoreCase(field)) { return isAddress3RangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IAddress.CITY.equalsIgnoreCase(field)) { return isCityRangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IAddress.POSTAL_CODE.equalsIgnoreCase(field)) { return isPostalCodeRangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IAddress.STATE_PROVINCE_CD.equalsIgnoreCase(field)) { return isStateRangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IContact.FIRST_NAME.equalsIgnoreCase(field)) { return isFirstNameRangeOu(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IContact.LAST_NAME.equalsIgnoreCase(field)) { return isLastNameRangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IContact.EMAIL.equalsIgnoreCase(field)) { return isEmailRangeOu(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IContact.FAX.equalsIgnoreCase(field)) { return isFaxRangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IContact.MOBILE.equalsIgnoreCase(field)) { return isMobileRangeOu(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IContact.TELEPHONE.equalsIgnoreCase(field)) { return isTelephoneRangeOu(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } return null; } @Override protected ArgumentedMessage isMustBeEmpty(String field, ValidationCode code) { if (IAddress.STATE_PROVINCE_CD.equalsIgnoreCase(field)) { return isStatePrivinceMustBeEmpty(code); } return null; } } private class AccountBillingAddressValidationCodeResolver extends AbstractAddressValidationCodeResolver { protected ArgumentedMessage isStatePrivinceMustBeEmpty(ValidationCode code) { return new ArgumentedMessageImpl("validation.web.error.variableMustBeEmpty", new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.state") ) ) ); } protected ArgumentedMessage isCityRangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped(new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.city") ) ), maxLength) ); } protected ArgumentedMessage isPostalCodeRangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped(new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.postalCode") ) ), maxLength) ); } protected ArgumentedMessage isStateRangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped(new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.state") ) ), maxLength) ); } protected ArgumentedMessage isAddress1RangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped( new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.address1") ) ), maxLength) ); } protected ArgumentedMessage isAddress2RangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped(new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.address2") ) ), maxLength) ); } protected ArgumentedMessage isAddress3RangeOut(ValidationCode code, String validationValue, Number maxLength) { return new ArgumentedMessageImpl("validation.web.error.stringRangeOut", Args.i18nTyped(new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.address3") ) ), maxLength) ); } protected ArgumentedMessage isCountryNotSet(ValidationCode code) { return new ArgumentedMessageImpl("validation.web.error.emptyValue", new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.country") ) ) ); } protected ArgumentedMessage isCityNotSet(ValidationCode code) { return new ArgumentedMessageImpl("validation.web.error.emptyValue", new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.city") ) ) ); } protected ArgumentedMessage isAddress1NotSet(ValidationCode code) { return new ArgumentedMessageImpl("validation.web.error.emptyValue", new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.address1") ) ) ); } protected ArgumentedMessage isStateNotSet(ValidationCode code) { return new ArgumentedMessageImpl("validation.web.error.emptyValue", new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.state") ) ) ); } protected ArgumentedMessage isPostalCodeNotSet(ValidationCode code) { return new ArgumentedMessageImpl("validation.web.error.emptyValue", new MessageI18nArgument( new ArgumentedMessageImpl( "admin.account.label.billingAddress", Args.i18nTyped("admin.account.label.billingAddress.address.postalCode") ) ) ); } @Override protected ArgumentedMessage isNotSet(String field, ValidationCode code) { if (IAddress.ADDRESS1.equalsIgnoreCase(field)) { return isAddress1NotSet(code); } else if (IAddress.CITY.equalsIgnoreCase(field)) { return isCityNotSet(code); } else if (IAddress.COUNTRY_CD.equalsIgnoreCase(field)) { return isCountryNotSet(code); } else if (IAddress.POSTAL_CODE.equalsIgnoreCase(field)) { return isPostalCodeNotSet(code); } else if (IAddress.STATE_PROVINCE_CD.equalsIgnoreCase(field)) { return isStateNotSet(code); } return null; } @Override protected ArgumentedMessage isRangeOut(String field, ValidationCode code) { if (IAddress.ADDRESS1.equalsIgnoreCase(field)) { return isAddress1RangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IAddress.ADDRESS2.equalsIgnoreCase(field)) { return isAddress2RangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IAddress.ADDRESS3.equalsIgnoreCase(field)) { return isAddress3RangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IAddress.CITY.equalsIgnoreCase(field)) { return isCityRangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IAddress.POSTAL_CODE.equalsIgnoreCase(field)) { return isPostalCodeRangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } else if (IAddress.STATE_PROVINCE_CD.equalsIgnoreCase(field)) { return isStateRangeOut(code, (String) code.getArguments()[1].get(), (Number) code.getArguments()[2].get()); } return null; } @Override protected ArgumentedMessage isMustBeEmpty(String field, ValidationCode code) { if (IAddress.STATE_PROVINCE_CD.equalsIgnoreCase(field)) { return isStatePrivinceMustBeEmpty(code); } return null; } } }
package javaPractice2; public class SumOfDigitsInANumber { public static void main(String[] args) { int num=12345; int sum=0; while(num>0){ sum= sum+num%10; num=num/10; }System.out.println(sum); } }
package com.basicNLP.classifier; public class ClassifiedDocument { String text; String category; public ClassifiedDocument(String category,String text) { this.text=text; this.category=category; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
package com.nosuchteam.mapper; import com.nosuchteam.bean.Order; import com.nosuchteam.bean.OrderExample; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; public interface OrderMapper { long countByExample(OrderExample example); int deleteByExample(OrderExample example); int deleteByPrimaryKey(String orderId); int insert(Order record); int insertSelective(Order record); List<Order> selectByExample(OrderExample example); Order selectByPrimaryKey(String orderId); int updateByExampleSelective(@Param("record") Order record, @Param("example") OrderExample example); int updateByExample(@Param("record") Order record, @Param("example") OrderExample example); int updateByPrimaryKeySelective(Order record); int updateByPrimaryKey(Order record); Order findOrderById(); List<Order> findOrderList(@Param("limit") Integer row, @Param("offset") Integer offset); @Select("select count(*) from `c_order`;") int findTotalOrder(); Order findOrder(String orderId); }
package com.example.retail.controllers.retailer.nonvegproducts_retailer; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/api/v1/retailer/nonVegProducts") @CrossOrigin(origins = "*") public class NonVegProductsRetailerController { }
import java.net.*; import java.util.Scanner; import java.io.*; public class Client { public static void main(String[] args) { int serverPort = 1234; String address = "127.0.0.1"; try { InetAddress ipAddress = InetAddress.getByName(address); Socket socket = new Socket (ipAddress, serverPort); InputStream inS = socket.getInputStream(); OutputStream outS = socket.getOutputStream(); DataInputStream in = new DataInputStream(inS); //Конвертация для упрощенной обработки текста. DataOutputStream out = new DataOutputStream(outS); String line = new String(); Scanner mail = new Scanner(System.in); while(true){ line = mail.nextLine(); out.writeUTF(line); out.flush(); line = in.readUTF(); System.out.println("Сообщение от сервера:" + line); } } catch (Exception e) { e.printStackTrace(); } } }
/* * #%L * Over-the-air deployment library * %% * Copyright (C) 2012 SAP AG * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.sap.prd.mobile.ios.ota.lib; import static com.sap.prd.mobile.ios.ota.lib.TestUtils.assertContains; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.velocity.exception.ResourceNotFoundException; import org.junit.Test; import com.sap.prd.mobile.ios.ota.lib.OtaHtmlGenerator.Parameters; public class OtaHtmlGeneratorTest { private final static String referer = "http://hostname:8080/path/MyApp.htm"; private final static String title = "MyApp"; private final static String checkIpaURL = "http://hostname:8080/path/MyApp.ipa"; private final static String bundleIdentifier = "com.sap.xyz.MyApp"; private final static String bundleVersion = "1.0.2"; private final static String otaClassifier = "otaClassifier"; private final static String ipaClassifier = "ipaClassifier"; private static final String plistServiceUrl = "http://ota-server:8080/OTAService/PLIST"; private static HashMap<String, String> initParams = new HashMap<String, String>(); @Test public void testCorrectValues() throws IOException { URL plistURL = OtaPlistGenerator.generatePlistRequestUrl(plistServiceUrl, referer, title, bundleIdentifier, bundleVersion, ipaClassifier, otaClassifier); String generated = OtaHtmlGenerator.getInstance().generate( new Parameters(referer, title, bundleIdentifier, plistURL, null, null, initParams)); assertContains(String.format("Install App: %s", title), generated); TestUtils.assertOtaLink(generated, plistURL.toString(), bundleIdentifier); Pattern checkIpaLinkPattern = Pattern.compile("<a class=\"button\" href='([^']+)'[^>]*>Install via iTunes</a>"); Matcher checkIpaLinkMatcher = checkIpaLinkPattern.matcher(generated); assertTrue("Ipa link not found", checkIpaLinkMatcher.find()); assertEquals(checkIpaURL, checkIpaLinkMatcher.group(1)); } @Test public void testAlternativeTemplateByResource() throws IOException { URL plistURL = OtaPlistGenerator.generatePlistRequestUrl(plistServiceUrl, referer, title, bundleIdentifier, bundleVersion, ipaClassifier, otaClassifier); String generated = OtaHtmlGenerator.getInstance("alternativeTemplate.html").generate( new Parameters(referer, title, bundleIdentifier, plistURL, null, null, initParams)); checkAlternativeResult(plistURL, generated); } @Test public void testAlternativeTemplateByFile() throws IOException { URL plistURL = OtaPlistGenerator.generatePlistRequestUrl(plistServiceUrl, referer, title, bundleIdentifier, bundleVersion, ipaClassifier, otaClassifier); File templateFile = new File("./src/test/resources/alternativeTemplate.html"); assertTrue("File does not exist at "+templateFile.getAbsolutePath(), templateFile.isFile()); String generated = OtaHtmlGenerator.getInstance(templateFile.getAbsolutePath()).generate( new Parameters(referer, title, bundleIdentifier, plistURL, null, null, initParams)); checkAlternativeResult(plistURL, generated); } private void checkAlternativeResult(URL plistURL, String generated) { assertContains("ALTERNATIVE HTML TEMPLATE", generated); assertContains(String.format("Install App: %s", title), generated); assertContains("<a href='itms-services:///?action=download-manifest&url="+plistURL+"'>OTA</a>", generated); assertContains("<a href='"+checkIpaURL+"'>IPA</a>", generated); } @Test public void testGenerateHtmlServiceUrl() throws MalformedURLException { URL url = new URL("http://apple-ota.wdf.sap.corp:1080/ota-service/HTML"); assertEquals( "http://apple-ota.wdf.sap.corp:1080/ota-service/HTML?" + "title=MyApp&bundleIdentifier=com.sap.myApp.XYZ&bundleVersion=3.4.5.6&" + "ipaClassifier=ipaClassifier&otaClassifier=otaClassifier", OtaHtmlGenerator.generateHtmlServiceUrl(url, "MyApp", "com.sap.myApp.XYZ", "3.4.5.6", ipaClassifier, otaClassifier).toExternalForm()); assertEquals( "http://apple-ota.wdf.sap.corp:1080/ota-service/HTML?" + "title=MyApp+With+Special%24_Char%26&bundleIdentifier=com.sap.myApp.XYZ&bundleVersion=3.4.5.6&" + "ipaClassifier=ipaClassifier&otaClassifier=otaClassifier", OtaHtmlGenerator.generateHtmlServiceUrl(url, "MyApp With Special$_Char&", "com.sap.myApp.XYZ", "3.4.5.6", ipaClassifier, otaClassifier) .toExternalForm()); assertEquals( "http://apple-ota.wdf.sap.corp:1080/ota-service/HTML?" + "title=MyApp&bundleIdentifier=com.sap.myApp.XYZ&bundleVersion=3.4.5.6", OtaHtmlGenerator.generateHtmlServiceUrl(url, "MyApp", "com.sap.myApp.XYZ", "3.4.5.6", null, null).toExternalForm()); assertEquals( "http://apple-ota.wdf.sap.corp:1080/ota-service/HTML?" + "title=MyApp&bundleIdentifier=com.sap.myApp.XYZ&bundleVersion=3.4.5.6&otaClassifier=otaClassifier", OtaHtmlGenerator.generateHtmlServiceUrl(url, "MyApp", "com.sap.myApp.XYZ", "3.4.5.6", null, otaClassifier).toExternalForm()); } public void getNewInstanceCorrectResource() throws FileNotFoundException { assertEquals(OtaHtmlGenerator.DEFAULT_TEMPLATE, OtaHtmlGenerator.getInstance(OtaHtmlGenerator.DEFAULT_TEMPLATE).template.getName()); } @Test public void getNewInstanceNull() throws FileNotFoundException { assertEquals(OtaHtmlGenerator.DEFAULT_TEMPLATE, OtaHtmlGenerator.getInstance(null).template.getName()); } @Test public void getNewInstanceEmpty() throws FileNotFoundException { assertEquals(OtaHtmlGenerator.DEFAULT_TEMPLATE, OtaHtmlGenerator.getInstance("").template.getName()); } @Test(expected = ResourceNotFoundException.class) public void getNewInstanceWrongResource() throws FileNotFoundException { assertEquals(OtaHtmlGenerator.DEFAULT_TEMPLATE, OtaHtmlGenerator.getInstance("doesnotexist.htm").template.getName()); } @Test public void getNewInstanceCorrectFile() throws FileNotFoundException { assertEquals("alternativeTemplate.html", OtaHtmlGenerator.getInstance(new File("./src/test/resources/alternativeTemplate.html").getAbsolutePath()).template.getName()); } @Test(expected = ResourceNotFoundException.class) public void getNewInstanceWrongFile() throws FileNotFoundException { assertEquals(OtaHtmlGenerator.DEFAULT_TEMPLATE, OtaHtmlGenerator.getInstance(new File("./doesnotexist.htm").getAbsolutePath()).template.getName()); } }
package hash; import org.assertj.core.api.Assertions; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class ClosedHashTest extends BaseTest { private ClosedHash closedHash; @Before public void setUp() { closedHash = new ClosedHash(); } @After public void tearDown() { closedHash = null; } private int hashFunction(String word) { return word.length() % BaseHash.DEFAULT_ITEMS_COUNT; } @Test public void shouldInsertASimpleValueTest() { String value = "test"; closedHash.add(value); Assertions.assertThat(closedHash.getPosition(value)).isEqualTo(hashFunction(value)); } @Test public void shouldInsertTwoValuesWithSameResultOfHashFunctionTest() { String value1 = "test", value2 = "abcd"; closedHash.add(value1); closedHash.add(value2); Assertions.assertThat(closedHash.getPosition(value1)).isEqualTo(hashFunction(value1)); Assertions.assertThat(closedHash.getPosition(value2)).isEqualTo(hashFunction(value2)); } @Test public void shouldInsertThreeValuesWithSameResultOfHashFunctionTest() { String value1 = "test", value2 = "abcd", value3 = "kjmn"; closedHash.add(value1); closedHash.add(value2); closedHash.add(value3); Assertions.assertThat(closedHash.getPosition(value1)).isEqualTo(hashFunction(value1)); Assertions.assertThat(closedHash.getPosition(value2)).isEqualTo(hashFunction(value2)); Assertions.assertThat(closedHash.getPosition(value3)).isEqualTo(hashFunction(value2)); } @Test public void shouldRemoveTwoValuesWithSameResultOfHashFunctionTest() { String value1 = "test", value2 = "abcd"; closedHash.add(value1); closedHash.add(value2); Assertions.assertThat(closedHash.getPosition(value1)).isEqualTo(hashFunction(value1)); Assertions.assertThat(closedHash.getPosition(value2)).isEqualTo(hashFunction(value2)); closedHash.delete(value1); Assertions.assertThat(closedHash.getPosition(value1)).isEqualTo(BaseHash.INVALID_POSITION); Assertions.assertThat(closedHash.getPosition(value2)).isEqualTo(hashFunction(value2)); closedHash.delete(value2); Assertions.assertThat(closedHash.getPosition(value1)).isEqualTo(BaseHash.INVALID_POSITION); Assertions.assertThat(closedHash.getPosition(value2)).isEqualTo(BaseHash.INVALID_POSITION); } }
package com.example.myreadproject8.Application; import android.util.Log; import com.example.myreadproject8.R; import com.example.myreadproject8.common.APPCONST; import com.example.myreadproject8.entity.Setting; import com.example.myreadproject8.enums.BookcaseStyle; import com.example.myreadproject8.enums.LocalBookSource; import com.example.myreadproject8.greendao.GreenDaoManager; import com.example.myreadproject8.greendao.entity.rule.BookSource; import com.example.myreadproject8.util.net.crawler.read.ReadCrawlerUtil; import com.example.myreadproject8.util.sharedpre.SharedPreUtils; import com.example.myreadproject8.util.utils.CacheHelper; import static com.example.myreadproject8.Application.App.getVersionCode; public class SysManager { private static Setting mSetting; /** * 获取设置 * * @return */ public static Setting getSetting() { if (mSetting != null) { return mSetting; } mSetting = (Setting) CacheHelper.readObject(APPCONST.FILE_NAME_SETTING); if (mSetting == null) { mSetting = getDefaultSetting(); saveSetting(mSetting); } return mSetting; } public static Setting getNewSetting() { Setting setting = (Setting) CacheHelper.readObject(APPCONST.FILE_NAME_SETTING); if (setting == null) { setting = getDefaultSetting(); saveSetting(setting); } return setting; } public static Setting getReadSetting() { Setting setting = (Setting) CacheHelper.readObject(APPCONST.FILE_NAME_READ_SETTING); setting = getDefaultSetting(); saveReadSetting(setting); return setting; } /** * 保存设置 * * @param setting */ public static void saveReadSetting(Setting setting) { CacheHelper.saveObject(setting, APPCONST.FILE_NAME_READ_SETTING); } /** * 保存设置 * * @param setting */ public static void saveSetting(Setting setting) { CacheHelper.saveObject(setting, APPCONST.FILE_NAME_SETTING); } /** * 默认设置 * * @return */ private static Setting getDefaultSetting() { Setting setting = new Setting(); setting.setDayStyle(true); setting.setBookcaseStyle(BookcaseStyle.listMode); setting.setNewestVersionCode(getVersionCode()); setting.setAutoSyn(false); setting.setMatchChapter(true); setting.setMatchChapterSuitability(0.7f); setting.setCatheGap(150); setting.setRefreshWhenStart(true); setting.setOpenBookStore(true); setting.setSettingVersion(APPCONST.SETTING_VERSION); setting.setHorizontalScreen(false); setting.initReadStyle(); setting.setCurReadStyleIndex(1); return setting; } public static void regetmSetting() { mSetting = (Setting) CacheHelper.readObject(APPCONST.FILE_NAME_SETTING); } /** * 重置设置 */ public static void resetSetting() { Setting setting = getSetting(); switch (setting.getSettingVersion()) { case 10: default: setting.initReadStyle(); setting.setCurReadStyleIndex(1); setting.setSharedLayout(true); Log.d("SettingVersion", "" + 10); case 11: Log.d("SettingVersion", "" + 11); case 12: Log.d("SettingVersion", "" + 12); } setting.setSettingVersion(APPCONST.SETTING_VERSION); saveSetting(setting); } public static void resetSource() { // BookSource source = new BookSource(); // source.setSourceEName("cangshu99");//这是内置书源标识,必填 // source.setSourceName("99藏书");//设置书源名称 // source.setSourceGroup("内置书源");//设置书源分组 // source.setEnable(true);//设置书源可用性 // source.setSourceUrl("com.example.myreadproject8.util.net.crawler.read.CansShu99ReadCrawler");//这是书源完整类路径,必填 // source.setOrderNum(0);//内置书源一般设置排序为0 // GreenDaoManager.getDaoSession().getBookSourceDao().insertOrReplace(source);//添加书源进数据库 } }
package com.zjw.myapplication.urls; /** * Created by Administrator on 2016/10/21. */ public class URLs { //http://v.juhe.cn/weixin/query?key=您申请的KEY public static final String getWeiXinUrl(int page){ String url="http://v.juhe.cn/weixin/query?key=7bf9c73f7db932e245ca1f2664745d4a&ps=10&pno="+page; return url; } }
package codility.splitarray; /** * * @author Julian */ public class Solution { public int solution(int X, int[] A) { int leftSame = 0; int rightSame = 0; int leftDiff = 0; int rightDiff = 0; int index = 0; for (int i = 0; i < A.length; i++) { if (A[i] == X) { leftSame += 1; } else { leftDiff += 1; } if (i > ((A.length - 1) - i)) { break; } if (A[(A.length - 1) - i] == X) { rightSame += 1; } else { rightDiff += 1; } if (leftSame == rightDiff) { index = i; } if (leftDiff == rightSame) { index = A.length - 1 - i; } } return index; } }
package dev.televex.fhgcore; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.List; /** * All code Copyright (c) 2015 by Eric_1299. All Rights Reserved. */ public class money implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (sender instanceof Player) { Player p = (Player) sender; if (args.length == 0) { p.sendMessage(tags.gtag + "You have " + getMoney(p) + " dollars."); return true; } else if (args.length == 2) { switch (args[0]) { case "set": if (p.isOp()) { int newbalance; try { newbalance = Integer.parseInt(args[1]); } catch (NumberFormatException e) { p.sendMessage(tags.etag + args[1] + " is not a valid integer."); return true; } if (newbalance >= 0) { setMoney(p, newbalance); p.sendMessage(tags.gtag + "New balance of " + newbalance + " set."); return true; } else { sendHelp(p); return true; } } else { p.sendMessage(tags.perm); return true; } case "withdraw": int withdrawamount; try { withdrawamount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { p.sendMessage(tags.etag + args[1] + " is not a valid integer."); return true; } if (withdrawamount > getMoney(p)) { p.sendMessage(tags.etag + "You don't have enough money!"); return true; } else { ItemStack paper = new ItemStack(Material.PAPER, 1); ItemMeta papermeta = paper.getItemMeta(); papermeta.setDisplayName("\u00A7f\u00A7lMoney Note"); List<String> lore = new ArrayList<>(); lore.add(0, "\u00A7f" + p.getName()); lore.add(1, "\u00A7f" + args[1]); papermeta.setLore(lore); paper.setItemMeta(papermeta); PlayerInventory pi = p.getInventory(); pi.addItem(paper); takeMoney(p, withdrawamount); return true; } case "help": sendHelp(p); return true; default: sendHelp(p); return true; } } else { sendHelp(p); return true; } } sender.sendMessage(tags.player); return true; } private void sendHelp(Player p) { p.sendMessage(tags.ptag + tags.pb + "Usage: /money"); p.sendMessage(tags.ptag + "/money set <amount>"); p.sendMessage(tags.ptag + "/money withdraw <amount>"); p.sendMessage(tags.ptag + "/money help"); } public static int getMoney(Player p) { return config.getInt("fhg.players." + p.getUniqueId() + ".money"); } public static void setMoney(Player p, int amount) { config.set("fhg.players." + p.getUniqueId() + ".money", amount); } public static void addMoney(Player p, int amount) { config.set("fhg.players." + p.getUniqueId() + ".money", getMoney(p) + amount); p.sendMessage(tags.gb + "+$" + amount); } public static void takeMoney(Player p, int amount) { config.set("fhg.players." + p.getUniqueId() + ".money", getMoney(p) - amount); p.sendMessage(tags.eb + "-$" + amount); } }
package com.jachin.shopping.service; import com.jachin.shopping.mapper.UserMapper; import com.jachin.shopping.po.User; import com.jachin.shopping.po.UserExample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class UserService { private static ApplicationContext ioc = new ClassPathXmlApplicationContext("classpath:spring.xml"); @Autowired private UserMapper userMapper = (UserMapper) ioc.getBean("userMapper"); // 用户登陆验证 public int login(User user){ UserExample userExample = new UserExample(); UserExample.Criteria criteria = userExample.createCriteria(); criteria.andAccountEqualTo(user.getAccount()); criteria.andPasswordEqualTo(user.getPassword()); List<User> list = userMapper.selectByExample(userExample); if(list.isEmpty()) return -1; return list.get(0).getUserid(); } // 用户查询信息 public User getUserInfo(int id){ return userMapper.selectByPrimaryKey(id); } // 用户修改信息 public void editUserInfo(User user){ userMapper.updateByPrimaryKeySelective(user); } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.frontend.client.panel.left; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.user.client.ui.StackLayoutPanel; import com.openkm.frontend.client.Main; import com.openkm.frontend.client.constants.ui.UIDesktopConstants; import com.openkm.frontend.client.constants.ui.UIDockPanelConstants; import com.openkm.frontend.client.extension.event.HasNavigatorEvent; import com.openkm.frontend.client.extension.event.handler.NavigatorHandlerExtension; import com.openkm.frontend.client.extension.event.hashandler.HasNavigatorHandlerExtension; public class ExtendedStackPanel extends StackLayoutPanel implements HasNavigatorEvent, HasNavigatorHandlerExtension { private boolean startupFinished = false; // to indicate process starting up has finished private boolean taxonomyVisible = false; private boolean categoriesVisible = false; private boolean metadataVisible = false; private boolean thesaurusVisible = false; private boolean templatesVisible = false; private boolean personalVisible = false; private boolean mailVisible = false; private boolean trashVisible = false; private int hiddenStacks = 8; private int stackIndex = 0; private List<NavigatorHandlerExtension> navHandlerExtensionList; public ExtendedStackPanel() { super(Unit.PX); navHandlerExtensionList = new ArrayList<NavigatorHandlerExtension>(); } @Override public void showWidget( int index ) { stackIndex = index; if (startupFinished) { changeView(index,true); } super.showWidget(index); } /** * setStartUpFinished */ public void setStartUpFinished() { startupFinished = true; } /** * Gets the stack index value * * @return The stack index value */ public int getStackIndex() { return indexCorrectedChangeViewIndex(stackIndex); } /** * Change the stack panel view * * @param index The new stack index selected * @param refresh Enables or disables refreshing */ private void changeView(int index, boolean refresh) { if (startupFinished) { // If there's folder creating or renaming must cancel it before changing view if (Main.get().activeFolderTree.isFolderCreating()) { Main.get().activeFolderTree.removeTmpFolderCreate(); } else if (Main.get().activeFolderTree.isFolderRenaming()) { Main.get().activeFolderTree.cancelRename(); } switch (indexCorrectedChangeViewIndex(index)) { case UIDesktopConstants.NAVIGATOR_TAXONOMY: Main.get().activeFolderTree = Main.get().mainPanel.desktop.navigator.taxonomyTree; Main.get().mainPanel.desktop.browser.fileBrowser.changeView(UIDesktopConstants.NAVIGATOR_TAXONOMY); Main.get().mainPanel.topPanel.toolBar.changeView(UIDesktopConstants.NAVIGATOR_TAXONOMY,UIDockPanelConstants.DESKTOP); if (refresh) { Main.get().activeFolderTree.forceSetSelectedPanel(); Main.get().activeFolderTree.refresh(true); // When opening a path document must not refreshing } Main.get().mainPanel.desktop.browser.tabMultiple.setVisibleButtons(true); break; case UIDesktopConstants.NAVIGATOR_TRASH: Main.get().activeFolderTree = Main.get().mainPanel.desktop.navigator.trashTree; Main.get().mainPanel.desktop.browser.fileBrowser.changeView(UIDesktopConstants.NAVIGATOR_TRASH); Main.get().mainPanel.topPanel.toolBar.changeView(UIDesktopConstants.NAVIGATOR_TRASH,UIDockPanelConstants.DESKTOP); if (refresh) { Main.get().activeFolderTree.forceSetSelectedPanel(); Main.get().activeFolderTree.refresh(true); // When opening a path document must not refreshing } Main.get().mainPanel.desktop.browser.tabMultiple.setVisibleButtons(false); break; case UIDesktopConstants.NAVIGATOR_CATEGORIES: Main.get().activeFolderTree = Main.get().mainPanel.desktop.navigator.categoriesTree; Main.get().mainPanel.desktop.browser.fileBrowser.changeView(UIDesktopConstants.NAVIGATOR_CATEGORIES); Main.get().mainPanel.topPanel.toolBar.changeView(UIDesktopConstants.NAVIGATOR_CATEGORIES,UIDockPanelConstants.DESKTOP); if (refresh) { Main.get().activeFolderTree.forceSetSelectedPanel(); Main.get().activeFolderTree.refresh(true); // When opening a path document must not refreshing } Main.get().mainPanel.desktop.browser.tabMultiple.setVisibleButtons(true); break; case UIDesktopConstants.NAVIGATOR_THESAURUS: Main.get().activeFolderTree = Main.get().mainPanel.desktop.navigator.thesaurusTree; Main.get().mainPanel.desktop.browser.fileBrowser.changeView(UIDesktopConstants.NAVIGATOR_THESAURUS); Main.get().mainPanel.topPanel.toolBar.changeView(UIDesktopConstants.NAVIGATOR_THESAURUS,UIDockPanelConstants.DESKTOP); if (refresh) { Main.get().activeFolderTree.forceSetSelectedPanel(); Main.get().activeFolderTree.refresh(true); // When opening a path document must not refreshing } Main.get().mainPanel.desktop.browser.tabMultiple.setVisibleButtons(true); break; case UIDesktopConstants.NAVIGATOR_METADATA: Main.get().activeFolderTree = Main.get().mainPanel.desktop.navigator.metadataTree; Main.get().mainPanel.desktop.browser.fileBrowser.changeView(UIDesktopConstants.NAVIGATOR_METADATA); Main.get().mainPanel.topPanel.toolBar.changeView(UIDesktopConstants.NAVIGATOR_METADATA,UIDockPanelConstants.DESKTOP); if (refresh) { Main.get().activeFolderTree.forceSetSelectedPanel(); Main.get().activeFolderTree.refresh(true); // When opening a path document must not refreshing } Main.get().mainPanel.desktop.browser.tabMultiple.setVisibleButtons(true); break; case UIDesktopConstants.NAVIGATOR_TEMPLATES: Main.get().activeFolderTree = Main.get().mainPanel.desktop.navigator.templateTree; Main.get().mainPanel.desktop.browser.fileBrowser.changeView(UIDesktopConstants.NAVIGATOR_TEMPLATES); Main.get().mainPanel.topPanel.toolBar.changeView(UIDesktopConstants.NAVIGATOR_TEMPLATES,UIDockPanelConstants.DESKTOP); if (refresh) { Main.get().activeFolderTree.forceSetSelectedPanel(); Main.get().activeFolderTree.refresh(true); // When opening a path document must not refreshing } Main.get().mainPanel.desktop.browser.tabMultiple.setVisibleButtons(true); break; case UIDesktopConstants.NAVIGATOR_PERSONAL: Main.get().activeFolderTree = Main.get().mainPanel.desktop.navigator.personalTree; Main.get().mainPanel.desktop.browser.fileBrowser.changeView(UIDesktopConstants.NAVIGATOR_PERSONAL); Main.get().mainPanel.topPanel.toolBar.changeView(UIDesktopConstants.NAVIGATOR_PERSONAL,UIDockPanelConstants.DESKTOP); if (refresh) { Main.get().activeFolderTree.forceSetSelectedPanel(); Main.get().activeFolderTree.refresh(true); // When opening a path document must not refreshing } Main.get().mainPanel.desktop.browser.tabMultiple.setVisibleButtons(true); break; case UIDesktopConstants.NAVIGATOR_MAIL: Main.get().activeFolderTree = Main.get().mainPanel.desktop.navigator.mailTree; Main.get().mainPanel.desktop.browser.fileBrowser.changeView(UIDesktopConstants.NAVIGATOR_MAIL); Main.get().mainPanel.topPanel.toolBar.changeView(UIDesktopConstants.NAVIGATOR_MAIL,UIDockPanelConstants.DESKTOP); if (refresh) { Main.get().activeFolderTree.forceSetSelectedPanel(); Main.get().activeFolderTree.refresh(true); // When opening a path document must not refreshing } Main.get().mainPanel.desktop.browser.tabMultiple.setVisibleButtons(true); break; } fireEvent(HasNavigatorEvent.STACK_CHANGED); } } /** * Show a stack * * @param index The new stack index selected * @param refresh Enables or disables refreshing */ public void showStack( int index, boolean refresh ) { stackIndex = correctedStackIndex(index); changeView(stackIndex,refresh); super.showWidget(stackIndex); } /** * isTaxonomyVisible * * @return */ public boolean isTaxonomyVisible() { return taxonomyVisible; } /** * isCategoriesVisible * * @return */ public boolean isCategoriesVisible() { return categoriesVisible; } /** * isMetadataVisible * * @return */ public boolean isMetadataVisible() { return metadataVisible; } /** * isThesaurusVisible * * @return */ public boolean isThesaurusVisible() { return thesaurusVisible; } /** * isTemplatesVisible * * @return */ public boolean isTemplatesVisible() { return templatesVisible; } /** * isPersonalVisible * * @return */ public boolean isPersonalVisible() { return personalVisible; } /** * isMailVisible * * @return */ public boolean isMailVisible() { return mailVisible; } /** * isTrashVisible * * @return */ public boolean isTrashVisible() { return trashVisible; } /** * showTaxonomy */ public void showTaxonomy() { hiddenStacks--; taxonomyVisible = true; } /** * showCategories * * @param */ public void showCategories() { hiddenStacks--; categoriesVisible = true; } /** * showMetadata * * @param */ public void showMetadata() { hiddenStacks--; metadataVisible = true; } /** * showThesaurus * */ public void showThesaurus() { hiddenStacks--; thesaurusVisible = true; } /** * showTemplates */ public void showTemplates() { hiddenStacks--; templatesVisible = true; } /** * showPersonal * * @param */ public void showPersonal() { hiddenStacks--; personalVisible = true; } /** * showMail * * @param */ public void showMail() { hiddenStacks--; mailVisible = true; } /** * showTrash */ public void showTrash() { hiddenStacks--; trashVisible = true; } /** * indexCorrectedChangeViewIndex * * Return index correction made depending visible panels * * @param index * @return */ public int indexCorrectedChangeViewIndex(int index) { int corrected = index; if (!taxonomyVisible && corrected>=UIDesktopConstants.NAVIGATOR_TAXONOMY) { corrected++; } if (!categoriesVisible && corrected>=UIDesktopConstants.NAVIGATOR_CATEGORIES) { corrected++; } if (!metadataVisible && corrected>=UIDesktopConstants.NAVIGATOR_METADATA) { corrected++; } if (!thesaurusVisible && corrected>=UIDesktopConstants.NAVIGATOR_THESAURUS) { corrected++; } if (!templatesVisible && corrected>=UIDesktopConstants.NAVIGATOR_TEMPLATES) { corrected++; } if (!personalVisible && corrected>=UIDesktopConstants.NAVIGATOR_PERSONAL) { corrected++; } if (!mailVisible && corrected>=UIDesktopConstants.NAVIGATOR_MAIL) { corrected++; } if (!trashVisible && corrected>=UIDesktopConstants.NAVIGATOR_TRASH) { corrected++; } return corrected; } /** * correctedStackIndex * * Return index correction, made depending visible panels * * @param index * @return */ private int correctedStackIndex(int index) { int corrected = index; if (!trashVisible && corrected>=UIDesktopConstants.NAVIGATOR_TRASH) { corrected--; } if (!mailVisible && corrected>=UIDesktopConstants.NAVIGATOR_MAIL) { corrected--; } if (!personalVisible && corrected>=UIDesktopConstants.NAVIGATOR_PERSONAL) { corrected--; } if (!thesaurusVisible && corrected>=UIDesktopConstants.NAVIGATOR_THESAURUS) { corrected--; } if (!templatesVisible && corrected>=UIDesktopConstants.NAVIGATOR_TEMPLATES) { corrected--; } if (!metadataVisible && corrected>=UIDesktopConstants.NAVIGATOR_METADATA) { corrected--; } if (!categoriesVisible && corrected>=UIDesktopConstants.NAVIGATOR_CATEGORIES) { corrected--; } if (!taxonomyVisible && corrected>=UIDesktopConstants.NAVIGATOR_TAXONOMY) { corrected--; } return corrected; } /** * getHiddenStacks * * @return */ public int getHiddenStacks() { return hiddenStacks; } @Override public void addNavigatorHandlerExtension(NavigatorHandlerExtension handlerExtension) { navHandlerExtensionList.add(handlerExtension); } @Override public void fireEvent(NavigatorEventConstant event) { for (Iterator<NavigatorHandlerExtension> it = navHandlerExtensionList.iterator(); it.hasNext();) { it.next().onChange(event); } } }
import java.util.*; /** * 1711. Count Good Meals * Medium * 可以先查到maxDeliciousness,优化pow数组大小 */ public class Solution { private List<Integer> twoPow; private static int mod = (int) 1e9 + 7; public Solution() { twoPow = new ArrayList<>(); for (int i = 21; i >= 0; i--) { twoPow.add(1 << i); } } public int countPairs(int[] deliciousness) { Map<Integer, Integer> count = new HashMap<>(); int total = 0; for (int d : deliciousness) { for (int p : twoPow) { if (p < d) { break; } total = (total + count.getOrDefault(p - d, 0)) % mod; } count.put(d, count.getOrDefault(d, 0) + 1); } return total; } public static void main(String[] args) { int[][] deliciousness = { { 1, 3, 5, 7, 9 }, { 1, 1, 1, 3, 3, 3, 7 }, { 149, 107, 1, 63, 0, 1, 6867, 1325, 5611, 2581, 39, 89, 46, 18, 12, 20, 22, 234 } }; Solution s = new Solution(); for (int[] d : deliciousness) { System.out.println(s.countPairs(d)); } } }
package au.edu.utas.propertyapp; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; /****************************************************************************** * KIT305 Mobile Application Development, The University of Tasmania. * * FILENAME: PropertyList.java * AUTHORS: Rainer Wasinger * * NOTE: ***THIS CLASS NEEDS MODIFIYING BY THE STUDENTS.*** * In particular, see the methods: . * * CLASS DESCRIPTION: * PropertyList. This activity class is responsible for presenting the user * with a list of property results (either to buy or to rent). * The associated GUI for PropertyList is contained inside propertylisting.xml * (as well as propertylistrow.xml). * * The activity retrieves boolean information as to whether it will be * displaying the buy or rent list from the Extras passed to it through an * Intent call. * * PropertyListAdapter. This is a custom Adapter class that bridges our * ListView and the data in the database. * *****************************************************************************/ public class PropertyList extends Activity { private static final String TAG = "PropertyList"; public static final String EXTRA_PROPERTY_ID="au.edu.utas.propertyapp.property_id"; public static final String EXTRA_TO_RENT="au.edu.utas.propertyapp.to_rent"; List<Property> mPropertyList = new ArrayList<Property>(); PropertyListAdapter mPropertyListAdapter = null; ListView mListView; PropertyDB mDb; Cursor cursor; /** * onCreate. Called when the activity is started. Also responsible for * setting the content view, and for loading up everything required to show * a PropertyList. */ @Override protected void onCreate(Bundle savedInstanceState) { String toRentStr; boolean toRent = false; //Contains whether the user is looking to 'buy' //or 'rent' a property. This information is //obtained from the Extras bundle. super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); //********************************************************************* //* TODO [05]: Set the Activity content from a layout resource, i.e. //* link the Activity to the XML GUI. See the onCreate method in //* PropertyDetails.java for an example on how this is done. //* //********************************************************************* setContentView(R.layout.propertylisting); //********************************************************************* /* Get Intent extra's */ //********************************************************************* //* TODO [06]: Insert Java code required to retrieve the Intent's //* Extras (in this case 'EXTRA_TO_RENT'), and store this in the //* local boolean variable 'toRent'. //* //********************************************************************* Bundle extras = getIntent().getExtras(); toRentStr = extras != null ? extras.getString(PropertyApp.EXTRA_TO_RENT) : null; toRent = Boolean.parseBoolean(toRentStr); //********************************************************************* mDb = new PropertyDB(this); mDb.open(toRent, false); // We let the system manage this cursor, so that the life // cycle of the cursor matches the life cycle of the activity that is // displaying the cursor's data. cursor = mDb.getCursorToThePropertyList(); startManagingCursor(cursor); mListView = (ListView) findViewById(R.id.propertyListings); // Create the custom PropertyListAdapter to bridge our ListView and // the data in the database. mPropertyListAdapter = new PropertyListAdapter(); retrievePropertiesFromDB(); mListView.setAdapter(mPropertyListAdapter); mListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> a, View v, int position, long id) { Log.d(TAG, "PropertyList.onItemClick()"); //************************************************************* //* TODO [07]: Insert Java code required to trigger the //* PropertyDetails Intent, and use the putExtra method to add //* Extra information to the Intent, namely the ID of the //* property to which the user is seeking more details (i.e. //* EXTRA_PROPERTY_ID). //* //************************************************************* Intent i = new Intent(PropertyList.this, PropertyDetails.class); Property item=(Property) mListView.getItemAtPosition(position); i.putExtra(PropertyList.EXTRA_PROPERTY_ID, item.getPropertyID()); i.putExtra(PropertyList.EXTRA_TO_RENT, PropertyApp.EXTRA_TO_RENT); startActivity(i); //************************************************************* } }); } // onCreate /** * retrievePropertiesFromDB. Performs all the actions required to start * showing a particular list. */ public void retrievePropertiesFromDB() { if (cursor != null) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { Property p = createPropertyFromCursor(cursor); mPropertyListAdapter.add(p); //NB: When we add a Property, we //need to add it to the ArrayAdapter via add() � the adapter //will, in turn, put it in the ArrayList. Otherwise, if we add //it straight to the ArrayList, the adapter will not know about //the added Property and therefore will not display it cursor.moveToNext(); } } } // retrievePropertiesFromDB /** * createPropertyFromCursor. Creates a property object from the given cursor. */ public Property createPropertyFromCursor(Cursor c) { if (c == null || c.isAfterLast() || c.isBeforeFirst()) { return null; } Property p = new Property(); p.setAddress(c.getString(c.getColumnIndex(PropertyDB.KEY_ADDRESS))); p.setDescription(c.getString(c.getColumnIndex(PropertyDB.KEY_DESCRIPTION))); p.setPropertyID(c.getString(c.getColumnIndex(PropertyDB.KEY_PROPERTY_ID))); p.setPrice(c.getString(c.getColumnIndex(PropertyDB.KEY_PRICE))); p.setType(c.getString(c.getColumnIndex(PropertyDB.KEY_TYPE))); p.setSuburb(c.getString(c.getColumnIndex(PropertyDB.KEY_SUBURB))); p.setRegion(c.getString(c.getColumnIndex(PropertyDB.KEY_REGION))); p.setBedrooms(c.getString(c.getColumnIndex(PropertyDB.KEY_BEDROOMS))); p.setBathrooms(c.getString(c.getColumnIndex(PropertyDB.KEY_BATHROOMS))); p.setCarSpaces(c.getString(c.getColumnIndex(PropertyDB.KEY_CARSPACES))); return p; } // createPropertyFromCursor /** * onDestroy. Called when the activity is destroyed. */ @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy"); mDb.close(); // Close the database to avoid memory leaks. } // onDestroy /** * PropertyListAdapter class. * * This is a custom Adapter that bridges our ListView and the data in the * database. * * @author Rainer Wasinger. */ class PropertyListAdapter extends ArrayAdapter<Property> { PropertyListAdapter() { super(PropertyList.this, android.R.layout.simple_list_item_1, mPropertyList); } /** * getView. Gets a view that represents a summary of this property. * Inflated from the propertylistrow.xml file into a real view. */ public View getView(int position, View row, ViewGroup parent) { TableLayout featureTable = null; TableRow tr = null; TextView label = null, value = null; LayoutInflater inflater=getLayoutInflater(); row = inflater.inflate(R.layout.propertylistrow, null); Property p = mPropertyList.get(position); ImageView photo = (ImageView) row.findViewById(R.id.propertyImage); photo.setImageResource(R.drawable.house); featureTable = (TableLayout) row.findViewById(R.id.summaryFeatureTable); if (!p.getPrice().equals("")) { tr = new TableRow(PropertyList.this); label = new TextView(PropertyList.this); value = new TextView(PropertyList.this); label.setText("Price:"); value.setText(p.getPrice()); tr.addView(label); tr.addView(value); featureTable.addView(tr); } if (!p.getSuburb().equals("")) { tr = new TableRow(PropertyList.this); label = new TextView(PropertyList.this); value = new TextView(PropertyList.this); label.setText("Suburb:"); value.setText(p.getSuburb()); tr.addView(label); tr.addView(value); featureTable.addView(tr); } if (!p.getBedrooms().equals("")) { tr = new TableRow(PropertyList.this); label = new TextView(PropertyList.this); value = new TextView(PropertyList.this); label.setText("Bedrooms:"); value.setText(p.getBedrooms()); tr.addView(label); tr.addView(value); featureTable.addView(tr); } if (!p.getBathrooms().equals("")) { tr = new TableRow(PropertyList.this); label = new TextView(PropertyList.this); value = new TextView(PropertyList.this); label.setText("Bathrooms:"); value.setText(p.getBathrooms()); tr.addView(label); tr.addView(value); featureTable.addView(tr); } if (!p.getCarSpaces().equals("")) { tr = new TableRow(PropertyList.this); label = new TextView(PropertyList.this); value = new TextView(PropertyList.this); label.setText("CarSpaces:"); value.setText(p.getCarSpaces()); tr.addView(label); tr.addView(value); featureTable.addView(tr); } TextView title = (TextView) row.findViewById(R.id.summaryTitle); title.setText(p.getAddress()); return(row); } //getView } //PropertyListAdapter class } // PropertyList class
package com.tencent.mm.app.plugin; import android.net.Uri; import android.os.Bundle; import com.tencent.mm.R; import com.tencent.mm.ac.d; import com.tencent.mm.ac.f; import com.tencent.mm.app.plugin.URISpanHandlerSet.BaseUriSpanHandler; import com.tencent.mm.app.plugin.URISpanHandlerSet.PRIORITY; import com.tencent.mm.app.plugin.URISpanHandlerSet.a; import com.tencent.mm.pluginsdk.s; import com.tencent.mm.pluginsdk.ui.applet.m; import com.tencent.mm.pluginsdk.ui.d.g; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.h; @a(vC = PRIORITY.LOW) class URISpanHandlerSet$DeeplinkUriSpanHandler extends BaseUriSpanHandler { final /* synthetic */ URISpanHandlerSet bAt; URISpanHandlerSet$DeeplinkUriSpanHandler(URISpanHandlerSet uRISpanHandlerSet) { this.bAt = uRISpanHandlerSet; super(uRISpanHandlerSet); } final m db(String str) { x.i("MicroMsg.URISpanHandlerSet", "DeeplinkUriSpanHandler getHrefFromUrl %s", new Object[]{str}); if (str.trim().toLowerCase().startsWith("weixin://")) { return new m(str, 30, null); } return null; } final int[] vB() { return new int[]{30}; } final boolean a(m mVar, g gVar) { String str; x.i("MicroMsg.URISpanHandlerSet", "DeeplinkUriSpanHandler handleSpanClick %d, %s", new Object[]{Integer.valueOf(mVar.type), mVar.url}); if (gVar != null) { str = (String) gVar.a(mVar); } else { str = null; } if (mVar.type != 30) { return false; } String oV = bi.oV(mVar.url); if (oV.startsWith("weixin://shieldBrandMsg/") || oV.startsWith("weixin://receiveBrandMsg/")) { if (bi.oW(str)) { x.e("MicroMsg.URISpanHandlerSet", "DeeplinkUriSpanHandler username is null"); return true; } d kH = f.kH(str); if (kH == null) { x.e("MicroMsg.URISpanHandlerSet", "DeeplinkUriSpanHandler BizInfo is null"); return true; } else if (oV.startsWith("weixin://shieldBrandMsg/")) { h.a(URISpanHandlerSet.a(this.bAt), R.l.temp_session_shield_biz_msg_tips, R.l.app_tip, R.l.temp_session_shield_biz_msg_confirm, R.l.cancel, new 1(this, kH, oV, str), null); } else if (oV.startsWith("weixin://receiveBrandMsg/")) { h.a(URISpanHandlerSet.a(this.bAt), R.l.temp_session_receive_biz_msg_tips, R.l.app_tip, R.l.temp_session_receive_biz_msg_confirm, R.l.cancel, new 2(this, kH, oV, str), null); } } else if (com.tencent.mm.pluginsdk.d.k(Uri.parse(oV))) { com.tencent.mm.pluginsdk.d.x(URISpanHandlerSet.a(this.bAt), str, oV); } else if (!oV.startsWith("weixin://receiveWeAppKFMsg")) { com.tencent.mm.pluginsdk.d.a(URISpanHandlerSet.a(this.bAt), oV, str, 1, oV, null); } else if (bi.oW(str)) { x.e("MicroMsg.URISpanHandlerSet", "DeeplinkUriSpanHandler username is null, handle the BUILTIN_RECEIVE_WEAPP_KFMSG , the herfUrl is %s", new Object[]{oV}); return true; } else { h.a(URISpanHandlerSet.a(this.bAt), R.l.app_brand_reveive_msg_title, R.l.app_tip, R.l.app_brand_reveive_msg_config, R.l.cancel, new 3(this, str), null); } return true; } final boolean a(String str, boolean z, s sVar, Bundle bundle) { if (bi.oW(str) || bundle == null) { boolean z2; String str2 = "MicroMsg.URISpanHandlerSet"; String str3 = "url is null ? %b, paramsBundle is null ? %b"; Object[] objArr = new Object[2]; if (str == null) { z2 = true; } else { z2 = false; } objArr[0] = Boolean.valueOf(z2); if (bundle == null) { z2 = true; } else { z2 = false; } objArr[1] = Boolean.valueOf(z2); x.e(str2, str3, objArr); return false; } else if (!com.tencent.mm.pluginsdk.d.k(Uri.parse(str))) { return false; } else { int i = bundle.getInt("key_scene", -1); x.d("MicroMsg.URISpanHandlerSet", "DeeplinkUriSpanHandler jump, %d, %s", new Object[]{Integer.valueOf(i), str}); if (i == -1) { i = 5; } com.tencent.mm.pluginsdk.d.a(URISpanHandlerSet.a(this.bAt), str, i, new 4(this, h.a(URISpanHandlerSet.a(this.bAt), "", true, null))); return true; } } }
package app2048; import java.awt.BorderLayout; import java.awt.event.KeyListener; import java.io.IOException; import java.awt.Container; import java.awt.Dimension; import java.awt.event.*; import java.awt.Color; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.LineBorder; import java.awt.GridLayout; import java.util.Random; public class App2048 extends JFrame implements KeyListener,ActionListener{ Gfield testlabel; Gfield[][] gamefield; JPanel MainPanel; JPanel GamePanel; JPanel ControlPanel; JPanel ResetPanel; public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } public App2048(String name) { super(name); } private static class Gfield extends JLabel { public Gfield(String text) { Border border1 = LineBorder.createBlackLineBorder(); this.setText(text); this.setHorizontalAlignment(CENTER); this.setBorder(border1); } private int CastInt() { if(this.getText()!="") this.Ival = Integer.parseInt(this.getText()); else this.Ival = 0; return this.Ival; } //public void setText(String text) { // this.setText(text); //this.ICol= bleach(Color.BLUE, Ival); //this.setForeground(this.ICol); //} int pozx; int pozy; int Ival; } private static class Gbutton extends JButton { public Gbutton(String text,App2048 frame) { this.setText(text); this.addActionListener(frame); } } private static void createAndShowGUI() { //Create and set up the window. App2048 frame = new App2048("app2048"); frame.setLocationRelativeTo(null); frame.MainPanel = new JPanel(); frame.GamePanel = new JPanel(); frame.ControlPanel = new JPanel(); frame.ResetPanel = new JPanel(); frame.getContentPane().add(frame.MainPanel); frame.MainPanel.setLayout(new GridLayout(3,1)); frame.MainPanel.add(frame.GamePanel); frame.MainPanel.add(frame.ControlPanel); frame.MainPanel.add(frame.ResetPanel); frame.GamePanel.setLayout(new GridLayout(4,4)); frame.ControlPanel.setLayout(new GridLayout(3,3)); frame.ResetPanel.setLayout(new GridLayout(1,1)); frame.gamefield = new Gfield[4][4]; for(int i=0;i<4;i++) for(int j=0;j<4;j++){ frame.gamefield[i][j] = new Gfield(""); frame.GamePanel.add(frame.gamefield[i][j]); } Gbutton buttonReset = new Gbutton("Reset",frame); frame.ResetPanel.add(buttonReset); Gbutton buttonP5 = new Gbutton("",frame); Gbutton buttonP4 = new Gbutton("",frame); Gbutton buttonP3 = new Gbutton("Rand",frame); Gbutton buttonP2 = new Gbutton("",frame); Gbutton buttonP1 = new Gbutton("",frame); Gbutton buttonU = new Gbutton("Up",frame); Gbutton buttonD = new Gbutton("Down",frame); Gbutton buttonR = new Gbutton("Right",frame); Gbutton buttonL = new Gbutton("Left",frame); frame.ControlPanel.add(buttonP1); frame.ControlPanel.add(buttonU); frame.ControlPanel.add(buttonP2); frame.ControlPanel.add(buttonL); frame.ControlPanel.add(buttonP3); frame.ControlPanel.add(buttonR); frame.ControlPanel.add(buttonP4); frame.ControlPanel.add(buttonD); frame.ControlPanel.add(buttonP5); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } private boolean ChceckEmpty(){ boolean foundEmpty = false; for(int i=0;i<4;i++) for(int j=0;j<4;j++){ if(gamefield[i][j].getText()=="") {foundEmpty = true; break;} //m++; } return foundEmpty; } public static Color bleachBlue(int amount) { Color NewColor = new Color(1, 1, 255); if(amount <64) NewColor = new Color(1, 1, 255-amount*7); if(amount >=64) NewColor = new Color(1, 255-(amount/64)*7, 1); return NewColor; } private void SetColorFields(){ for(int i=0;i<4;i++) for(int j=0;j<4;j++) if(gamefield[i][j].CastInt()!=0) gamefield[i][j].setForeground(bleachBlue(gamefield[i][j].CastInt())); } private void ResetFields(){ for(int i=0;i<4;i++) for(int j=0;j<4;j++){ gamefield[i][j].setText(""); gamefield[i][j].setForeground(Color.BLACK); } FillRandField(); } private void FillRandField(){ Random rand = new Random(); int n = rand.nextInt(16); int xPos = n/4; int yPos = n%4; if(ChceckEmpty()){ while (gamefield[xPos][yPos].getText() != ""){ n = rand.nextInt(16); xPos = n/4; yPos = n%4; } gamefield[xPos][yPos].setText("1"); gamefield[xPos][yPos].setForeground(Color.red); } } private void UpAndDown(String dir){ int[] tmp_arr = new int[4]; int[] arr_cnt = new int[4]; int j,k; System.out.println("---------"); if(dir=="Down") for(int a=0;a<4;a++)arr_cnt[a]=3; if(dir=="Up") for(int a=0;a<4;a++)arr_cnt[a]=0; for(int i=0;i<4;i++) { for(int a=0;a<4;a++)tmp_arr[a]=0; if(dir=="Down")j=3; else j=0; while((dir=="Down"&&j>0)||(dir=="Up"&&j<3)){ if(dir=="Down")k=j-1; else k=j+1; while((dir=="Down"&&k>=0)||(dir=="Up"&&k<=3)){ if(gamefield[j][i].CastInt()==gamefield[k][i].CastInt()||gamefield[k][i].CastInt()==0) { if(gamefield[j][i].CastInt()==gamefield[k][i].CastInt()){ tmp_arr[j]= gamefield[j][i].CastInt()+gamefield[k][i].CastInt(); gamefield[k][i].setText(""); break; } else tmp_arr[j]= gamefield[j][i].CastInt(); } else { tmp_arr[j] = gamefield[j][i].CastInt(); break; } if(dir=="Down")k--; else k++; } if(dir=="Down")j--; else j++; } System.out.println(""+tmp_arr[0]+tmp_arr[1]+tmp_arr[2]+tmp_arr[3]); if(dir=="Down") tmp_arr[0] = gamefield[0][i].CastInt(); else tmp_arr[3] = gamefield[3][i].CastInt(); if(dir=="Down")j=3; else j=0; while((dir=="Down"&&j>=0)||(dir=="Up"&&j<=3)){ while(arr_cnt[i]>=0&&arr_cnt[i]<=3){ if(tmp_arr[arr_cnt[i]]!=0) break; else if(dir=="Down")arr_cnt[i]--; else arr_cnt[i]++; } if(arr_cnt[i]>=0&&arr_cnt[i]<=3) { gamefield[j][i].setText(""+tmp_arr[arr_cnt[i]]); if(dir=="Down")arr_cnt[i]--; else arr_cnt[i]++; } else gamefield[j][i].setText(""); if(dir=="Down")j--; else j++; } } } private void ToTheSides(String dir){ int[] tmp_arr = new int[4]; int[] arr_cnt = new int[4]; int j,k; System.out.println("---------"); if(dir=="Right") for(int a=0;a<4;a++)arr_cnt[a]=3; if(dir=="Left") for(int a=0;a<4;a++)arr_cnt[a]=0; for(int i=0;i<4;i++) { for(int a=0;a<4;a++)tmp_arr[a]=0; if(dir=="Right")j=3; else j=0; while((dir=="Right"&&j>0)||(dir=="Left"&&j<3)){ if(dir=="Right")k=j-1; else k=j+1; while((dir=="Right"&&k>=0)||(dir=="Left"&&k<=3)){ if(gamefield[i][j].CastInt()==gamefield[i][k].CastInt()||gamefield[i][k].CastInt()==0) { if(gamefield[i][j].CastInt()==gamefield[i][k].CastInt()){ tmp_arr[j]= gamefield[i][j].CastInt()+gamefield[i][k].CastInt(); gamefield[i][k].setText(""); break; } else tmp_arr[j]= gamefield[i][j].CastInt(); } else { tmp_arr[j] = gamefield[i][j].CastInt(); break; } if(dir=="Right")k--; else k++; } if(dir=="Right")j--; else j++; } System.out.println(""+tmp_arr[0]+tmp_arr[1]+tmp_arr[2]+tmp_arr[3]); if(dir=="Right") tmp_arr[0] = gamefield[i][0].CastInt(); else tmp_arr[3] = gamefield[i][3].CastInt(); if(dir=="Right")j=3; else j=0; while((dir=="Right"&&j>=0)||(dir=="Left"&&j<=3)){ while(arr_cnt[i]>=0&&arr_cnt[i]<=3){ if(tmp_arr[arr_cnt[i]]!=0) break; else if(dir=="Right")arr_cnt[i]--; else arr_cnt[i]++; } if(arr_cnt[i]>=0&&arr_cnt[i]<=3) { gamefield[i][j].setText(""+tmp_arr[arr_cnt[i]]); if(dir=="Right")arr_cnt[i]--; else arr_cnt[i]++; } else gamefield[i][j].setText(""); if(dir=="Right")j--; else j++; } } } public void keyTyped(KeyEvent e) { System.out.print("DUPA"); } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void actionPerformed(ActionEvent e) { //Clear the text components. if(e.getActionCommand()=="Reset") ResetFields(); if(e.getActionCommand()=="Left" || e.getActionCommand()=="Right" || e.getActionCommand()=="Up" || e.getActionCommand()=="Down"|| e.getActionCommand()=="Rand"){ if(e.getActionCommand()=="Left" || e.getActionCommand()=="Right"){ ToTheSides(e.getActionCommand()); SetColorFields(); FillRandField(); } if(e.getActionCommand()=="Up" || e.getActionCommand()=="Down"){ UpAndDown(e.getActionCommand()); SetColorFields(); FillRandField(); } if(e.getActionCommand()=="Rand"){ SetColorFields(); FillRandField(); } } } ; }
package com.enat.sharemanagement.security.privilage; import com.enat.sharemanagement.utils.Common; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import javax.persistence.EntityNotFoundException; import java.util.List; @Service public class PrivilegeService implements Common<Privilege,Privilege,Long> { private final PrivilegeRepository privilegeRepository; public PrivilegeService(PrivilegeRepository privilegeRepository) { this.privilegeRepository = privilegeRepository; } @Override public Privilege store(Privilege privilege) { return privilegeRepository.save(privilege); } @Override public Iterable<Privilege> store(List<Privilege> t) { return null; } @Override public Privilege show(Long id) { return privilegeRepository.findById(id).orElseThrow(()->new EntityNotFoundException()); } @Override public Privilege update(Long id,Privilege privilege) { return null; } @Override public boolean delete(Long id) { return false; } @Override public Page<Privilege> getAll(Pageable pageable) { return privilegeRepository.findAllByDeletedAtNull(pageable); } }
package cn.e3mall.service.config.spring; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.jms.connection.SingleConnectionFactory; import org.springframework.jms.core.JmsTemplate; /** * spring配置activemq */ @PropertySource({"classpath:conf/resource.properties"}) @Configuration public class ActiveMQApplicationContextConfig { /** * 真正可以产生Connection对象的ConnectionFactory,由对应的JMS服务厂商提供 * @return */ @Bean public ActiveMQConnectionFactory activeMQConnectionFactory(){ ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(); activeMQConnectionFactory.setBrokerURL("tcp://47.93.38.3:61616"); return activeMQConnectionFactory; } /** * spring用于管理真正的ConnectionFactory的ConnectionFactory * @return */ @Bean public SingleConnectionFactory singleConnectionFactory(){ SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory(); ActiveMQConnectionFactory activeMQConnectionFactory = activeMQConnectionFactory(); singleConnectionFactory.setTargetConnectionFactory(activeMQConnectionFactory); return singleConnectionFactory; } /** * Spring提供的JMS工具类,可以用来消息发送,接收 * @return */ @Bean public JmsTemplate jmsTemplate(){ JmsTemplate jmsTemplate = new JmsTemplate(); SingleConnectionFactory connectionFactory = singleConnectionFactory(); /** * 这里对应的是Spring声明的connectionFactory */ jmsTemplate.setConnectionFactory(connectionFactory); return jmsTemplate; } /** * 队列目的地,点对点的 * @return */ @Bean public ActiveMQQueue activeMQQueue(){ ActiveMQQueue activeMQQueue = new ActiveMQQueue("spring-queue"); return activeMQQueue; } /** * 标题目的地,一对多的 * @return */ @Bean public ActiveMQTopic activeMQTopic(){ ActiveMQTopic activeMQTopic = new ActiveMQTopic("item-change-topic"); return activeMQTopic; } }
package chatroom.serializer; import chatroom.model.message.Message; import chatroom.model.message.MessageType; import chatroom.model.message.MessageTypeDictionary; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; /** * This handles mapping of of <code>byte</code>s to a corresponding * <code>MessageSerializer</code> and sending a message to the correct * serializer. * NOTE: this class only maps and sends the message of an MessageSerializer! It * DOES NOT serializer itself. */ public class Serializer { private final HashMap<Byte, MessageSerializer> serializerHashMap; public Serializer() { MessageTypeDictionary dict = new MessageTypeDictionary(); serializerHashMap = new HashMap<>(); serializerHashMap.put(dict.getByte(MessageType.PUBLICSERVERMSG), new PublicServerMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.PUBLICTEXTMSG), new PublicTextMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.TARGETTEXTMSG), new TargetedTextMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.LOGINMSG), new LoginMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.LOGOUTMSG), new LogoutMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.LOGINRESPONSEMSG), new LoginResponseSerializer()); serializerHashMap.put(dict.getByte(MessageType.TARGETSERVERMSG), new TargetedServerMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.ROOMLISTMSG), new RoomListMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.ROOMCHANGEREQMSG), new RoomChangeRequestMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.ROOMUSERLISTMSG), new UserListMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.WARNINGMSG), new WarningMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.SERVERUSERLISTMSG), new ServerUserListMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.ROOMCHANGERESPONSEMSG),new RoomChangeResponseMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.ROOMNAMEEDITMSG),new RoomNameEditMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.PRIVATEROOMSTARTREQMSG), new PrivateChatStartRequestMessageSerializer()); serializerHashMap.put(dict.getByte(MessageType.PRIVATEROOMENDREQMSG), new PrivateChatEndRequestMessageSerializer()); } /** * Sends a message to its corresponding Serializer * @param out the OutputStream of the client receiving the Message * @param m the Message being serialized */ public void serialize(OutputStream out, Message m) throws IOException{ serializerHashMap.get(m.getType()).serialize(out, m); } /** * Returns the message sent to the server by an client. * @param in the InputStream of the sender of the message * @param type the byte representing the type of message * @return the message being Sent * @throws IOException if issues appear with the in/output streams */ public Message deserialize(InputStream in, byte type) throws IOException{ return serializerHashMap.get(type).deserialize(in); } }
package simple.mvc.app.mapper.impl; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import simple.mvc.app.mapper.UserMapper; import simple.mvc.bean.UserBean; import simple.mvc.jpa.Role; import simple.mvc.jpa.User; import simple.mvc.repository.UserRepository; @Component public class UserMapperImpl implements UserMapper { @Autowired private UserRepository userRepo; @Override public UserBean getUserBeanByNameAndPassword(String username, String password) { User jpa = userRepo.getUserByUsernameAndPassword(username, password); if (null != jpa) { return new UserBean().setId(jpa.getId()) .setUsername(jpa.getUsername()) .setPassword(jpa.getPassword()) .setRoles(convertUserRolesToUserBeanRoles(jpa.getRoles())).setEnabled(jpa.getEnabled()); } else { return null; } } @Override public UserBean createUser(UserBean bean) { User jpa = new User(); jpa.setUsername(bean.getUsername()); jpa.setPassword(bean.getPassword()); jpa.setEnabled(true); User created = userRepo.createUser(jpa); List<Role> roles = new ArrayList<Role>(); for (String rolename : bean.getRoles()) { Role jpaRole = new Role(); jpaRole.setUser(created); jpaRole.setRole(rolename); roles.add(jpaRole); } userRepo.createRoles(roles); return converUserToBeanByUserId(created.getId()); } @Override public List<UserBean> getAllUsers() { List<UserBean> beans = new ArrayList<UserBean>(); for (User jpa : userRepo.getAllUsers()) { beans.add(new UserBean().setPassword(jpa.getPassword()) .setUsername(jpa.getUsername()) .setId(jpa.getId()) .setRoles(convertUserRolesToUserBeanRoles(jpa.getRoles())).setEnabled(jpa.getEnabled())); } return beans; } @Override public void deleteUser(UserBean bean) { // TODO Auto-generated method stub } @Override public UserBean updateUser(UserBean bean) { // TODO Auto-generated method stub return null; } @Override public List<String> convertUserRolesToUserBeanRoles(List<Role> roles) { List<String> roleNames = new ArrayList<String>(); for (Role role : roles) { roleNames.add(role.getRole()); } return roleNames; } @Override public UserBean converUserToBeanByUserId(Long id) { User jpa = userRepo.getUserById(id); if (null != jpa) { return new UserBean().setPassword(jpa.getPassword()) .setUsername(jpa.getUsername()) .setId(jpa.getId()) .setRoles(convertUserRolesToUserBeanRoles(jpa.getRoles())).setEnabled(jpa.getEnabled()); } else { return null; } } }
package edu.ycp.cs320.calculator.shared; public class RocketPadsPlayer { // Fields private RocketPadsLocation start, current; private RocketPadsDirection dir; // Constructor public RocketPadsPlayer() { start = RocketPadsGame.START_BLUE; current = start; dir = RocketPadsDirection.START_BLUE; } // Resets the player's location to his starting location. public void reset_location() { current.setX(start.getX()); current.setY(start.getY()); } public RocketPadsLocation getLocation() { return current; } public void setLocation(int x, int y) { current = new RocketPadsLocation(x,y); } public RocketPadsDirection getDirection() { return dir; } public void setDirection(RocketPadsDirection direction) { dir = direction; } }
package sys_bs.service; import java.util.List; import sys_bs.entity.ClassRoom; public interface ClassRoomService { /** * 登录 * @param code * @param password * @return */ public boolean login(String code, String password); /** * 查询 * @param account * @return */ public List<ClassRoom> listAccount(ClassRoom account); /** * 增加 * @param account * @return */ public boolean addClassRoom(ClassRoom account); /** * 删除 * @param account * @return */ public boolean deleteClassRoom(ClassRoom account); /** * 修改 * @param account * @return */ public boolean updateClassRoom(ClassRoom account); }
package BillApplication; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class BillStage extends Stage{ private Scene scene; private BorderPane root; private BillTop top; private BillCenter center; private BillBottom bottom; public BillStage() { buildUI(); setStage(); show(); } // private methods private void buildUI() { //root layout root = new BorderPane(); //Styling root root.setPadding(new Insets(30)); // children nodes //top top = new BillTop(); //center center = new BillCenter(); //Bottom bottom = new BillBottom(); // Adding children to root root.setTop(top); root.setCenter(center); root.setBottom(bottom); } private void setStage() { scene = new Scene(root, 1000 , 600); setScene(scene); setTitle("Facture :"); } }
package com.tencent.mm.plugin.webview.ui.tools; import android.widget.ImageView; import android.widget.TextView; final class SDKOAuthUI$a$a { ImageView fyC; TextView fyD; private SDKOAuthUI$a$a() { } /* synthetic */ SDKOAuthUI$a$a(byte b) { this(); } }
package com.tencent.mm.pluginsdk.ui; class AbstractVideoView$11 implements Runnable { final /* synthetic */ AbstractVideoView qED; AbstractVideoView$11(AbstractVideoView abstractVideoView) { this.qED = abstractVideoView; } public final void run() { if (this.qED.qEj != null && this.qED.qEj.getVisibility() != 8) { this.qED.qEj.setVisibility(8); } } }
package com.tfsis.server.responses; import java.io.InputStream; import fi.iki.elonen.NanoHTTPD.Response; public abstract class HttpResponseBase extends Response { protected HttpResponseBase(IStatus status, String mimeType, InputStream data, long totalBytes) { super(status, mimeType, data, totalBytes); } }
package com.paleimitations.schoolsofmagic.common.data.capabilities.quest_data; import com.paleimitations.schoolsofmagic.References; import com.paleimitations.schoolsofmagic.common.config.Config; import com.paleimitations.schoolsofmagic.common.data.capabilities.magic_data.IMagicData; import com.paleimitations.schoolsofmagic.common.data.capabilities.magic_data.MagicData; import com.paleimitations.schoolsofmagic.common.network.PacketHandler; import com.paleimitations.schoolsofmagic.common.network.UpdateMagicDataPacket; import com.paleimitations.schoolsofmagic.common.network.UpdateQuestDataPacket; import com.paleimitations.schoolsofmagic.common.quests.Quest; import com.paleimitations.schoolsofmagic.common.quests.Task; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.brewing.PlayerBrewedPotionEvent; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class QuestDataProvider implements ICapabilitySerializable<INBT> { @CapabilityInject(IQuestData.class) public static Capability<IQuestData> QUEST_DATA_CAPABILITY = null; private final LazyOptional<IQuestData> instance = LazyOptional.of(QUEST_DATA_CAPABILITY::getDefaultInstance); public static final ResourceLocation ID = new ResourceLocation(References.MODID, "quest_data"); public static final Direction DIRECTION = null; public static void register() { CapabilityManager.INSTANCE.register(IQuestData.class, new Capability.IStorage<IQuestData>(){ @Nullable @Override public INBT writeNBT(Capability<IQuestData> capability, IQuestData instance, Direction side) { return instance.serializeNBT(); } @Override public void readNBT(Capability<IQuestData> capability, IQuestData instance, Direction side, INBT nbt) { instance.deserializeNBT((CompoundNBT)nbt); } }, QuestData::new); } public static IQuestData getData(PlayerEntity player) { return player.getCapability(QuestDataProvider.QUEST_DATA_CAPABILITY).orElseThrow(IllegalStateException::new); } @Nonnull @Override public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { return cap == QUEST_DATA_CAPABILITY ? instance.cast() : LazyOptional.empty(); } @Override public INBT serializeNBT() { return QUEST_DATA_CAPABILITY.getStorage().writeNBT(QUEST_DATA_CAPABILITY, this.instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), DIRECTION); } @Override public void deserializeNBT(INBT nbt) { QUEST_DATA_CAPABILITY.getStorage().readNBT(QUEST_DATA_CAPABILITY, this.instance.orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")), DIRECTION, nbt); } @Mod.EventBusSubscriber(modid = References.MODID, bus = Mod.EventBusSubscriber.Bus.FORGE) public static class Events { @SubscribeEvent public static void onAttachCapabilities(AttachCapabilitiesEvent<Entity> event) { if (event.getObject() instanceof PlayerEntity) { event.addCapability(ID, new QuestDataProvider()); } } @SubscribeEvent public static void onClone(PlayerEvent.Clone event) { IQuestData original = event.getOriginal().getCapability(QUEST_DATA_CAPABILITY, null).orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")); IQuestData clone = event.getPlayer().getCapability(QUEST_DATA_CAPABILITY, null).orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")); clone.deserializeNBT(original.serializeNBT()); } @SubscribeEvent public static void onRespawn(PlayerEvent.PlayerRespawnEvent event) { if(event.getPlayer() instanceof ServerPlayerEntity) { if(Config.Common.SHOW_PACKET_MESSAGES.get()) System.out.println("Quest Data sent For: " + event.getPlayer().getGameProfile().getName() + ", To: all tracking, Reason: respawn"); IQuestData data = event.getPlayer().getCapability(QUEST_DATA_CAPABILITY, null).orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")); PacketHandler.sendToTracking(new UpdateQuestDataPacket(event.getPlayer().getId(), data.serializeNBT()), (ServerPlayerEntity) event.getPlayer()); } } @SubscribeEvent public static void joinGame(PlayerEvent.PlayerLoggedInEvent event) { if(event.getPlayer() instanceof ServerPlayerEntity) { if(Config.Common.SHOW_PACKET_MESSAGES.get()) System.out.println("Quest Data sent For: " + event.getPlayer().getGameProfile().getName()+", To: all tracking, Reason: join game"); IQuestData data = event.getPlayer().getCapability(QUEST_DATA_CAPABILITY, null).orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")); PacketHandler.sendToTracking(new UpdateQuestDataPacket(event.getPlayer().getId(), data.serializeNBT()), (ServerPlayerEntity) event.getPlayer()); } } @SubscribeEvent public static void changeDimEvent(PlayerEvent.PlayerChangedDimensionEvent event) { if(event.getPlayer() instanceof ServerPlayerEntity) { if(Config.Common.SHOW_PACKET_MESSAGES.get()) System.out.println("Quest Data sent For: " + event.getPlayer().getGameProfile().getName() + ", To: all tracking, Reason: dimension change"); IQuestData data = event.getPlayer().getCapability(QUEST_DATA_CAPABILITY, null).orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")); PacketHandler.sendToTracking(new UpdateQuestDataPacket(event.getPlayer().getId(), data.serializeNBT()), (ServerPlayerEntity) event.getPlayer()); } } @SubscribeEvent public static void startTracking(PlayerEvent.StartTracking event) { if(event.getPlayer() instanceof ServerPlayerEntity) { if(event.getTarget() instanceof PlayerEntity) { PlayerEntity target = (PlayerEntity) event.getTarget(); if(Config.Common.SHOW_PACKET_MESSAGES.get()) System.out.println("Quest Data sent For: " + target.getGameProfile().getName() + ", To: "+event.getPlayer().getGameProfile().getName()+", Reason: start tracking"); IQuestData data = event.getPlayer().getCapability(QUEST_DATA_CAPABILITY, null).orElseThrow(() -> new IllegalArgumentException("LazyOptional must not be empty!")); PacketHandler.sendTo(new UpdateQuestDataPacket(target.getId(), data.serializeNBT()), (ServerPlayerEntity) event.getPlayer()); } } } @SubscribeEvent public static void onUpdate(LivingEvent.LivingUpdateEvent event) { LivingEntity entity = event.getEntityLiving(); if(entity instanceof PlayerEntity) { LazyOptional<IQuestData> lazyOptional = entity.getCapability(QuestDataProvider.QUEST_DATA_CAPABILITY); if(lazyOptional.isPresent()) { IQuestData data = lazyOptional.orElseThrow(IllegalStateException::new); data.updateQuests((PlayerEntity) entity); } } } @SubscribeEvent public static void potionEvent(PlayerBrewedPotionEvent event) { PlayerEntity player = event.getPlayer(); LazyOptional<IQuestData> lazyOptional = player.getCapability(QuestDataProvider.QUEST_DATA_CAPABILITY); IQuestData data = lazyOptional.orElseThrow(IllegalStateException::new); for(Quest quest : data.getQuests()) { for(Task task : quest.tasks) { if(task.taskType == Task.EnumTaskType.POTION_BREW) { task.checkEvent(player, event); } } } } @SubscribeEvent public static void buildEvent(BlockEvent.EntityPlaceEvent event) { if(event.getEntity() instanceof PlayerEntity) { PlayerEntity player = (PlayerEntity) event.getEntity(); LazyOptional<IQuestData> lazyOptional = player.getCapability(QuestDataProvider.QUEST_DATA_CAPABILITY); IQuestData data = lazyOptional.orElseThrow(IllegalStateException::new); for(Quest quest : data.getQuests()) { for(Task task : quest.tasks) { if(task.taskType == Task.EnumTaskType.BUILD) { task.checkEvent(player, event); } } } } } } }