text
stringlengths
10
2.72M
package network.nerve.dex.util; import io.nuls.base.data.CoinFrom; import io.nuls.base.data.CoinTo; import java.util.Arrays; import java.util.Comparator; public class CoinToComparator implements Comparator<CoinTo> { private CoinToComparator() { } private final static CoinToComparator instance = new CoinToComparator(); public static CoinToComparator getInstance() { return instance; } @Override public int compare(CoinTo o1, CoinTo o2) { if (o1.getAmount().compareTo(o2.getAmount()) < 0) { return -1; } else if (o1.getAmount().compareTo(o2.getAmount()) > 0) { return 1; } if (o1.getAssetsChainId() < o2.getAssetsChainId()) { return -1; } else if (o1.getAssetsChainId() > o2.getAssetsChainId()) { return 1; } if (o1.getAssetsId() < o2.getAssetsId()) { return -1; } else if (o1.getAssetsId() > o2.getAssetsId()) { return 1; } if (o1.getLockTime() < o2.getLockTime()) { return -1; } else if (o1.getLockTime() > o2.getLockTime()) { return 1; } return Arrays.compare(o1.getAddress(), o2.getAddress()); } }
package com.lenovohit.ssm.app.el.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import com.lenovohit.core.model.BaseIdModel; @Entity @Table(name = "EL_SECTIONAL_DESC") public class SectionalDesc extends BaseIdModel { private static final long serialVersionUID = 3559956331353876090L; private String fkId; private String fkType; private String caption; private String body; private Integer sortNum; @Column(name = "FK_ID", length = 32) public String getFkId() { return this.fkId; } public void setFkId(String fkId) { this.fkId = fkId; } @Column(name = "FK_TYPE", length = 20) public String getFkType() { return this.fkType; } public void setFkType(String fkType) { this.fkType = fkType; } @Column(name = "CAPTION", length = 100) public String getCaption() { return this.caption; } public void setCaption(String caption) { this.caption = caption; } @Column(name = "BODY", length = 500) public String getBody() { return this.body; } public void setBody(String body) { this.body = body; } @Column(name = "SORT_NUM") public Integer getSortNum() { return this.sortNum; } public void setSortNum(Integer sortNum) { this.sortNum = sortNum; } }
package com.turios.activities.fragments; import android.app.Activity; import android.app.SearchManager; import android.content.Context; import android.os.Bundle; import android.support.v4.app.FragmentActivity; 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.view.inputmethod.InputMethodManager; import android.widget.SearchView; import android.widget.SearchView.OnQueryTextListener; import com.androidmapsextensions.GoogleMap; import com.google.analytics.tracking.android.Fields; import com.google.analytics.tracking.android.GoogleAnalytics; import com.google.analytics.tracking.android.MapBuilder; import com.google.analytics.tracking.android.Tracker; import com.google.android.gms.maps.GoogleMapOptions; import com.turios.BuildConfig; import com.turios.R; import com.turios.dagger.DaggerActivity; import com.turios.dagger.DaggerMapFragment; import com.turios.dagger.quialifiers.ForApplication; import com.turios.modules.data.AddressHolder; import com.turios.modules.extend.DirectionsModule; import com.turios.modules.extend.GoogleMapsModule; import com.turios.modules.extend.HydrantsModule; import com.turios.util.Constants; import javax.inject.Inject; public class GoogleMapFragment extends DaggerMapFragment implements OnQueryTextListener { private static final String SUPPORT_MAP_BUNDLE_KEY = "MapOptions"; private static final String TAG = GoogleMapFragment.class.getSimpleName(); public static final String FRAGMENT_MAPOPTIONS_TAG = "childfragment:map:options"; public static int NAVIGATION_INDEX = 0; public GoogleMapFragment() { mCallback = null; } private AddressHolder mAddressHolder; @Inject DaggerActivity activity; @Inject @ForApplication Context context; @Inject HydrantsModule hydrantsModule; @Inject DirectionsModule directionsModule; @Inject GoogleMapsModule googlemaps; @Override public void onStart() { super.onStart(); if (!BuildConfig.DEBUG) { Tracker tracker = GoogleAnalytics.getInstance(getActivity()) .getTracker(Constants.GATracker); tracker.send(MapBuilder.createAppView() .set(Fields.SCREEN_NAME, "Hydrants View").build()); } } public static interface OnGoogleMapFragmentListener { void onMapReady(GoogleMap map); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); } public static GoogleMapFragment newInstance(AddressHolder addressHolder) { GoogleMapFragment mapFragment = new GoogleMapFragment(); mapFragment.mAddressHolder = addressHolder; return mapFragment; } public static GoogleMapFragment newInstance(GoogleMapOptions options) { Bundle arguments = new Bundle(); arguments.putParcelable(SUPPORT_MAP_BUNDLE_KEY, options); GoogleMapFragment fragment = new GoogleMapFragment(); fragment.setArguments(arguments); return fragment; } public void setCurrentAddress(AddressHolder addressHolder) { mAddressHolder = addressHolder; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } private SearchView mSearchView; @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Log.d(TAG, "onCreateOptionsMenu"); inflater.inflate(R.menu.menu_googlemaps, menu); if (mAddressHolder == null) { MenuItem menu_directions = menu .findItem(R.id.menu_update_directions); menu_directions.setVisible(false); } // Associate searchable configuration with the SearchView SearchManager searchManager = (SearchManager) activity .getSystemService(Context.SEARCH_SERVICE); mSearchView = (SearchView) menu.findItem(R.id.menu_search) .getActionView(); // Log.d(TAG, "mSearchView null " + (mSearchView == null)); mSearchView.setSearchableInfo(searchManager.getSearchableInfo(activity .getComponentName())); mSearchView.setOnQueryTextListener(this); mSearchView.setIconifiedByDefault(false); mSearchView.setFocusable(false); mSearchView.setFocusableInTouchMode(false); // mSearchView.clearFocus(); // getView().requestFocus(); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onQueryTextSubmit(String query) { // Hide keyboard InputMethodManager imm = (InputMethodManager) activity .getSystemService(FragmentActivity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0); mSearchView.setFocusable(false); mSearchView.setFocusableInTouchMode(false); return false; } @Override public boolean onQueryTextChange(String arg0) { // TODO Auto-generated method stub return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // case R.id.button_get_directions: // AddressHolder addressHolder = ((Turios) getActivity()) // .getSelectedDisplayFragment().getAddressHolder(); // Location currentLocation = LocationsCoreModule.getInstance() // .getLastLocation(); // String url = "http://maps.google.com/maps?saddr=" // + currentLocation.getLatitude() + "," // + currentLocation.getLongitude() + "&daddr=" // + addressHolder.position.latitude + "," // + addressHolder.position.longitude + "&mode=driving"; // Intent intent = new Intent(android.content.Intent.ACTION_VIEW, // Uri.parse(url)); // intent.setClassName("com.google.android.apps.maps", // "com.google.android.maps.MapsActivity"); // startActivity(intent); // return true; case R.id.menu_update_directions: directionsModule.updateDirections(mAddressHolder); return true; case R.id.menu_map_normal: googlemaps.setMapType(GoogleMap.MAP_TYPE_NORMAL); return true; case R.id.menu_map_satelite: googlemaps.setMapType(GoogleMap.MAP_TYPE_SATELLITE); return true; case R.id.menu_map_terrain: googlemaps.setMapType(GoogleMap.MAP_TYPE_TERRAIN); return true; case R.id.menu_map_hybrid: googlemaps.setMapType(GoogleMap.MAP_TYPE_HYBRID); return true; } return false; } private OnGoogleMapFragmentListener mCallback; @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallback = (OnGoogleMapFragmentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(getActivity().getClass().getName() + " must implement OnGoogleMapFragmentListener"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); if (mCallback != null) { mCallback.onMapReady(getExtendedMap()); } return view; } @Override public void onDetach() { // TODO Auto-generated method stub super.onDetach(); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void onDestroyView() { super.onDestroyView(); } }
package cogbog.constant; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.Serializable; import static cogbog.constant.ModType.*; @RunWith(JUnit4.class) public class ModTypeTests { @Test public void toStringWorks() { STAT.toString(); SAVE.toString(); SKILL.toString(); } @Test public void canSerialize() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writeValueAsString(STAT); objectMapper.writeValueAsString(SAVE); objectMapper.writeValueAsString(SKILL); } private static class JsonData implements Serializable { private static final long serialVersionUID = 5342469627083297681L; private ModType modType; public void setModType(ModType modType) { this.modType = modType; } } @Test public void canDeserialize() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.readValue("{\"modType\": \"STAT\"}", JsonData.class); objectMapper.readValue("{\"modType\": \"SAVE\"}", JsonData.class); objectMapper.readValue("{\"modType\": \"SKILL\"}", JsonData.class); } @Test(expected = JsonProcessingException.class) public void rejectsInvalidInstances() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); JsonData data = objectMapper.readValue("{\"modType\": \"DOGE\"}", JsonData.class); } }
package testinggame.Controladores; import animatefx.animation.Pulse; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; public class TablaClasificacionController implements Initializable { @FXML private AnchorPane PanelF; @FXML private Button bttnVolver; @Override public void initialize(URL url, ResourceBundle rb) { Volver(); } private void Volver(){ bttnVolver.setOnAction(new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent event) { try { Parent root= FXMLLoader.load(getClass().getResource("/testinggame/Vistas/VentanaDeSeleccion.fxml")); Scene SCENE=new Scene(root); PanelF.getChildren().clear(); PanelF.getChildren().add(root); }catch (IOException ex) { Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex); } } }); bttnVolver.setOnMouseEntered(new EventHandler<MouseEvent>(){ @Override public void handle(MouseEvent event) { new Pulse(bttnVolver).play(); } }); } }
package testCases; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import setup.Browser; import setup.elementHandler; public class verifyRoute { public static List<String> verifyRouteCount(HashMap <String, String> searchInputs) throws InterruptedException { List<String> tc_routes=new ArrayList<String>(); tc_routes.add("Verifying route count from "+searchInputs.get("Source")+" to "+searchInputs.get("Destination")+" by "+searchInputs.get("Vehicle")+" as: "+searchInputs.get("Routes")); String result; WebElement elemSearh=elementHandler.getWebElement("input_Search"); elemSearh.click(); elemSearh.sendKeys(searchInputs.get("Source")); Thread.sleep(2000); elemSearh.sendKeys(Keys.ENTER); elementHandler.getWebElement("btn_Route").click(); Thread.sleep(2000); WebElement elementDest=elementHandler.getWebElement("input_destination"); elementDest.click(); elementDest.sendKeys(searchInputs.get("Destination")); Thread.sleep(2000); elementDest.sendKeys(Keys.ENTER); WebElement transeportType=elementHandler.getWebElementXpath("//label[normalize-space(text())='"+searchInputs.get("Vehicle")+"']"); transeportType.click(); Thread.sleep(2000); int actualCount=elementHandler.getWebElements("routes").size(); if(actualCount==Integer.parseInt(searchInputs.get("Routes"))) { result="Pass"; tc_routes.add(result); } else { result="Fail"; tc_routes.add(result); tc_routes.add("Expected Count: "+searchInputs.get("Routes")); tc_routes.add("Actual Count: "+actualCount); Browser.takeScreenShot("route"); } elementHandler.getWebElement("btn_SearchBack").click(); return tc_routes; } }
package kafka2kafka; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.EnvironmentSettings; import org.apache.flink.table.api.Types; import org.apache.flink.table.api.java.StreamTableEnvironment; import org.apache.flink.table.functions.ScalarFunction; import org.apache.flink.types.Row; import constants.FlinkSqlConstants; import java.math.BigDecimal; public class KafkaJoinJdbc2Kafka { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); EnvironmentSettings envSettings = EnvironmentSettings.newInstance() .useBlinkPlanner() .inStreamingMode() .build(); StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env, envSettings); tableEnvironment.registerFunction("func", new Func()); tableEnvironment.sqlUpdate(FlinkSqlConstants.ordersTableDDL); tableEnvironment.sqlUpdate(FlinkSqlConstants.mysqlCurrencyDDL); String sinkTableDDL = "CREATE TABLE gmv (\n" + " log_per_min STRING,\n" + " item STRING,\n" + " order_cnt BIGINT,\n" + " currency_time TIMESTAMP(3),\n" + " gmv DECIMAL(38, 18)" + ") WITH (\n" + " 'connector.type' = 'kafka',\n" + " 'connector.version' = '0.10',\n" + " 'connector.topic' = 'gmv',\n" + " 'connector.properties.zookeeper.connect' = 'localhost:2181',\n" + " 'connector.properties.bootstrap.servers' = 'localhost:9092',\n" + " 'format.type' = 'json',\n" + " 'format.derive-schema' = 'true'\n" + ")"; tableEnvironment.sqlUpdate(sinkTableDDL); String querySQL = "insert into gmv \n" + "select cast(TUMBLE_END(o.order_time, INTERVAL '10' SECOND) as VARCHAR) as log_per_min,\n" + " o.item, COUNT(o.order_id) as order_cnt, c.currency_time, " + " cast(sum(o.amount_kg) * c.rate as DECIMAL(38, 18)) as gmv \n" + " from orders as o \n" + " join currency FOR SYSTEM_TIME AS OF o.proc_time c\n" + " on o.currency = c.currency_name\n" + " group by o.item, c.currency_time,c.rate,TUMBLE(o.order_time, INTERVAL '10' SECOND)\n"; tableEnvironment.sqlUpdate(querySQL); System.out.println(FlinkSqlConstants.ordersTableDDL); System.out.println(FlinkSqlConstants.mysqlCurrencyDDL); System.out.println(sinkTableDDL); System.out.println(querySQL); tableEnvironment.execute("KafkaJoinJdbc2Kafka.sql"); } public static class Func extends ScalarFunction { public BigDecimal eval(BigDecimal amount) { return amount.multiply(new BigDecimal("100.0")); } @Override public TypeInformation<?> getResultType(Class<?>[] signature) { return Types.DECIMAL(); } } }
package com.pago.core.quotes.dao.service; import javax.inject.Inject; import com.pago.core.quotes.dao.models.EventItem; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import java.util.List; public class EventTableService extends AbstractDAO<EventItem> { @Inject public EventTableService(SessionFactory sessionFactory) { super(sessionFactory); } public void save(EventItem event) { persist(event); } public List<EventItem> getEvents() { return list(query("from events")); } public EventItem getEvent(Long id) { return get(id); } }
package sr.hakrinbank.intranet.api.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import sr.hakrinbank.intranet.api.model.ProblemLoanOfficer; import java.util.List; @Repository public interface ProblemLoanOfficerRepository extends JpaRepository<ProblemLoanOfficer, Long> { @Query("SELECT a FROM ProblemLoanOfficer a WHERE a.code = :name") ProblemLoanOfficer findByName(@Param("name") String name); @Query("SELECT a FROM ProblemLoanOfficer a WHERE a.deleted = 0") List<ProblemLoanOfficer> findActiveProblemLoanOfficer(); @Query("select a from ProblemLoanOfficer a where (a.code LIKE '%' || :qry || '%' OR a.problemLoanOfficerFullName LIKE '%' || :qry || '%') AND a.deleted = 0") List<ProblemLoanOfficer> findAllActiveProblemLoanOfficerBySearchQuery(@Param("qry") String qry); }
package net.tascalate.concurrent; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; public interface TaskExecutorService extends ExecutorService { <T> Promise<T> submit(Callable<T> task); <T> Promise<T> submit(Runnable task, T result); Promise<?> submit(Runnable task); }
package cn.itcast.core.controller; import cn.itcast.core.pojo.entity.PageResult; import cn.itcast.core.pojo.entity.Result; import cn.itcast.core.pojo.seckill.SeckillOrder; import cn.itcast.core.service.SecKillOrderService; import com.alibaba.dubbo.config.annotation.Reference; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("seckillorder") public class SecKillOrderController { @Reference private SecKillOrderService secKillOrderService; @RequestMapping("/findAllSecKillOrder") public PageResult findAllSecKillOrder(Integer page, Integer rows, @RequestBody SeckillOrder seckillOrder){ String userName = SecurityContextHolder.getContext().getAuthentication().getName(); seckillOrder.setSellerId(userName); System.out.println(userName); return secKillOrderService.findPage(page, rows, seckillOrder); } @RequestMapping("/deleteSecKillOrder") public Result deleteSecKillOrder(Long[] ids) { try { secKillOrderService.deleteById(ids); return new Result(true,"删除成功"); }catch (Exception e){ e.printStackTrace(); return new Result(false,"删除失败"); } } }
package structural.bridge; public class Abstraction extends AAbstraction{ public void operation() { this.implementation.operation(); } }
/* * 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. */ /** * * @author Nav */ public class Problem { String initialState; String goalState; Problem() { initialState = ""; goalState = ""; } Problem(String is, String gs) { initialState = is; goalState = gs; } public void setInitialState(String is) { initialState = is; } public void setGoalState(String gs) { goalState = gs; } }
package ffm.slc.model.resources; /** * A unique numeric code assigned to a person by a state education agency. */ public class UniqueStateIdentifier extends StringResource{}
package cz.muni.fi.pa165.monsterslayers.service.facadeImpl; import cz.muni.fi.pa165.monsterslayers.dto.jobs.*; import cz.muni.fi.pa165.monsterslayers.entities.Hero; import cz.muni.fi.pa165.monsterslayers.entities.Job; import cz.muni.fi.pa165.monsterslayers.enums.JobStatus; import cz.muni.fi.pa165.monsterslayers.facade.JobFacade; import cz.muni.fi.pa165.monsterslayers.service.ClientRequestService; import cz.muni.fi.pa165.monsterslayers.service.HeroService; import cz.muni.fi.pa165.monsterslayers.service.JobService; import cz.muni.fi.pa165.monsterslayers.service.MappingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; /** * Implementation of the facade layer for Jobs. * * @author David Kizivat */ @Service @Transactional public class JobFacadeImpl implements JobFacade { @Autowired private JobService jobService; @Autowired private HeroService heroService; @Autowired private ClientRequestService clientRequestService; @Autowired private MappingService mappingService; @Override public JobDTO getJobById(Long id) { Job result = jobService.getJobById(id); if (result == null) { return null; } return mappingService.mapTo(result, JobDTO.class); } @Override public Collection<JobDTO> getJobsByAssignee(Long assigneeId) { Hero hero = heroService.findHeroById(assigneeId); return mappingService.mapTo(jobService.getJobsByAssignee(hero), JobDTO.class); } @Override public Collection<JobDTO> getAllJobs() { return mappingService.mapTo(jobService.getAllJobs(), JobDTO.class); } @Override public Long createJob(CreateJobDTO dto) { Job job = new Job(); job.setClientRequest(clientRequestService.findClientRequestById(dto.getClientRequestId())); job.setAssignee(heroService.findHeroById(dto.getHeroId())); return jobService.saveJob(job); } @Override public void reassignJob(ReassignJobDTO dto) { Job job = jobService.getJobById(dto.getJobId()); Hero newAssignee = heroService.findHeroById(dto.getNewHeroId()); job.setAssignee(newAssignee); jobService.saveJob(job); } @Override public void evaluateJob(EvaluateJobDTO dto) { Job job = jobService.getJobById(dto.getJobId()); Integer evaluation = dto.getEvaluation(); job.setEvaluation(evaluation); jobService.saveJob(job); } @Override public void updateJobStatusDto(UpdateJobStatusDTO dto) { Job job = jobService.getJobById(dto.getJobId()); JobStatus newStatus = dto.getNewStatus(); job.setStatus(newStatus); jobService.saveJob(job); } }
package com.github.niwaniwa.whitebird.core.listener; import java.io.IOException; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.ItemSpawnEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerAchievementAwardedEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.inventory.ItemStack; import com.github.niwaniwa.whitebird.core.event.WhiteBirdPlayerDamageEvent; import com.github.niwaniwa.whitebird.core.event.WhiteBirdPlayerDeathEvent; import com.github.niwaniwa.whitebird.core.player.WhiteBirdPlayer; import com.github.niwaniwa.whitebird.core.rank.Rank; public class PlayerListener implements Listener { @EventHandler public void death(PlayerDeathEvent event){ if(!event.getEntityType().equals(EntityType.PLAYER)){return;} // event.setDeathMessage(null); Player player = (Player) event.getEntity(); Player killer = player.getKiller(); String message = event.getDeathMessage(); WhiteBirdPlayerDeathEvent e = new WhiteBirdPlayerDeathEvent(killer, player, message); Bukkit.getServer().getPluginManager().callEvent(e); if(!e.isMessage()){ event.setDeathMessage(null); } event.setKeepInventory(true); ItemStack[] items = new ItemStack[player.getInventory().getContents().length]; for(ItemStack is : items){ is = new ItemStack(Material.AIR); is.setType(Material.AIR); } player.getInventory().setContents(items); } @EventHandler public void join(PlayerJoinEvent event){ Player player = event.getPlayer(); player.teleport(Bukkit.getWorld("world").getSpawnLocation(), TeleportCause.END_PORTAL); WhiteBirdPlayer wbp = WhiteBirdPlayer.getPlayer(player); setRank(wbp); try { if(wbp.loadSetting()){ wbp.saveSetting(); } } catch (IOException | InvalidConfigurationException e) {} event.setJoinMessage(null); for(Player p : Bukkit.getOnlinePlayers()){ WhiteBirdPlayer temp = WhiteBirdPlayer.getPlayer(p); if(temp.isConnectionMsg()){ p.sendMessage(wbp.getFullName()+" §ejoin the game."); } if(temp.isVanish()){ player.hidePlayer(p); } } } @EventHandler public void left(PlayerQuitEvent event){ Player player = event.getPlayer(); WhiteBirdPlayer wbp = WhiteBirdPlayer.getPlayer(player); try { wbp.saveSetting(); } catch (IOException e) {System.out.println(e.getMessage());} event.setQuitMessage(null); if(wbp.isVanish()){return;} for(Player p : Bukkit.getOnlinePlayers()){ WhiteBirdPlayer temp = WhiteBirdPlayer.getPlayer(p); if(temp.isConnectionMsg()){ p.sendMessage(wbp.getFullName()+" §eleft the game."); } } WhiteBirdPlayer.removePlayer(wbp); } @EventHandler public void onChat(AsyncPlayerChatEvent event){ event.setCancelled(true); Player player = event.getPlayer(); WhiteBirdPlayer wbp = WhiteBirdPlayer.getPlayer(player); String chat = event.getMessage(); for(Player p : Bukkit.getOnlinePlayers()){ if(WhiteBirdPlayer.getPlayer(p).isChat()){ p.sendMessage("<"+wbp.getFullName()+">: "+chat); } } System.out.println("<"+wbp.getFullName()+">: "+chat); } @EventHandler public void damage(EntityDamageByEntityEvent event){ if(!(event.getEntity() instanceof Player)){return;} Player player = (Player) event.getEntity(); WhiteBirdPlayerDamageEvent whiteEvent = new WhiteBirdPlayerDamageEvent(player, player.getKiller(), event); Bukkit.getServer().getPluginManager().callEvent(whiteEvent); if(whiteEvent.isCancelled()){ event.setCancelled(true); } } @EventHandler public void block(BlockBreakEvent event){ Player player = event.getPlayer(); if(!player.hasPermission(Rank.getRank("Moderator").getPermission())){ event.setCancelled(true); } } @EventHandler public void block(BlockPlaceEvent event){ Player player = event.getPlayer(); if(!player.hasPermission(Rank.getRank("Moderator").getPermission())){ event.setCancelled(true); } } @EventHandler public void item(ItemSpawnEvent event){ event.setCancelled(true); } @EventHandler public void onDamage(EntityDamageEvent event){ Entity en = event.getEntity(); if(en.getType().equals(EntityType.PLAYER)){ Player p = (Player) en; if(event.getCause().equals(DamageCause.SUFFOCATION)){ event.setCancelled(true); } if(p.getWorld().equals(Bukkit.getWorld("world"))){ event.setCancelled(true); } } } private void setRank(WhiteBirdPlayer player){ if(player.getPlayer().getUniqueId().toString().equals("f010845c-a9ac-4a04-bf27-61d92f8b03ff")){ player.addRank(Rank.getRank("Owner")); return; } for(Rank rank : Rank.getRanks()){ if(player.getPlayer().hasPermission(rank.getPermission())){ if(player.getPlayer().hasPermission(Rank.getRank("Moderator").getPermission()) && rank.getName().equalsIgnoreCase("Mapper")){return;} player.addRank(rank); } } } @EventHandler public void onA(PlayerAchievementAwardedEvent event){ event.setCancelled(true); } }
package br.com.hitbra.services; import br.com.hitbra.model.OfferModel; public interface OfferCommand { void execute( OfferModel model ); }
package slimeknights.tconstruct.tools.modifiers; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.event.entity.player.PlayerDropsEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.util.ListIterator; import slimeknights.tconstruct.library.modifiers.ModifierAspect; import slimeknights.tconstruct.library.utils.TinkerUtil; public class ModSoulbound extends ToolModifier { public ModSoulbound() { super("soulbound", 0xf5fbac); addAspects(new ModifierAspect.DataAspect(this), new ModifierAspect.SingleAspect(this)); MinecraftForge.EVENT_BUS.register(this); } @Override public void applyEffect(NBTTagCompound rootCompound, NBTTagCompound modifierTag) { // nothing to do :( } // We copy the soulbound items into the players corpse in here // HIGH priority so we do it before other possibly death-inventory-modifying mods @SubscribeEvent(priority = EventPriority.HIGH) public void onPlayerDeath(PlayerDropsEvent event) { if(event.getEntityPlayer() == null || event.getEntityPlayer() instanceof FakePlayer || event.isCanceled()) { return; } if(event.getEntityPlayer().getEntityWorld().getGameRules().getBoolean("keepInventory")) { return; } ListIterator<EntityItem> iter = event.getDrops().listIterator(); while(iter.hasNext()) { EntityItem ei = iter.next(); ItemStack stack = ei.getItem(); // find soulbound items if(TinkerUtil.hasModifier(stack.getTagCompound(), this.identifier)) { // copy the items back into the dead players inventory event.getEntityPlayer().inventory.addItemStackToInventory(stack); iter.remove(); } } } // On respawn we copy the items out of the players corpse, into the new player @SubscribeEvent(priority = EventPriority.HIGH) public void onPlayerClone(PlayerEvent.Clone evt) { if(!evt.isWasDeath() || evt.isCanceled()) { return; } if(evt.getOriginal() == null || evt.getEntityPlayer() == null || evt.getEntityPlayer() instanceof FakePlayer) { return; } if(evt.getEntityPlayer().getEntityWorld().getGameRules().getBoolean("keepInventory")) { return; } for(int i = 0; i < evt.getOriginal().inventory.mainInventory.size(); i++) { ItemStack stack = evt.getOriginal().inventory.mainInventory.get(i); if(TinkerUtil.hasModifier(stack.getTagCompound(), this.identifier)) { evt.getEntityPlayer().inventory.addItemStackToInventory(stack); evt.getOriginal().inventory.mainInventory.set(i, ItemStack.EMPTY); } } } }
package edu.mit.cci.simulation.model; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Set; /** * User: jintrone * Date: 2/28/11 * Time: 12:52 PM */ public class DelegatingSim extends DefaultSimulation { public DefaultSimulation delegate; public DelegatingSim(DefaultSimulation delegate) { this.delegate = delegate; } @Override public String toString() { return delegate.toString(); } @Override public Date getCreated() { return delegate.getCreated(); } @Override public void setCreated(Date created) { delegate.setCreated(created); } @Override public Long getSimulationVersion() { return delegate.getSimulationVersion(); } @Override public void setSimulationVersion(Long simulationVersion) { delegate.setSimulationVersion(simulationVersion); } @Override public String getDescription() { return delegate.getDescription(); } @Override public void setDescription(String description) { delegate.setDescription(description); } @Override public String getName() { return delegate.getName(); } @Override public void setName(String name) { delegate.setName(name); } @Override public Long getId() { return delegate.getId(); } @Override public String getUrl() { return delegate.getUrl(); } @Override public void setId(Long id) { delegate.setId(id); } @Override public void setUrl(String url) { delegate.setUrl(url); } @Override public Integer getVersion() { return delegate.getVersion(); } @Override public Scenario run(List<Tuple> siminputs) throws SimulationException { return delegate.run(siminputs); } @Override public Set<Variable> getInputs() { return delegate.getInputs(); } @Override public void setVersion(Integer version) { delegate.setVersion(version); } @Override public void setInputs(Set<Variable> inputs) { delegate.setInputs(inputs); } @Override @Transactional public void persist() { delegate.persist(); } @Override public Set<Variable> getOutputs() { return delegate.getOutputs(); } @Override public void setOutputs(Set<Variable> outputs) { delegate.setOutputs(outputs); } @Override @Transactional public void remove() { delegate.remove(); } @Override public Set<Tuple> runRaw(Collection<Tuple> siminputs) throws SimulationException { return delegate.runRaw(siminputs); } @Override @Transactional public void flush() { delegate.flush(); } @Override @Transactional public DefaultSimulation merge() { return delegate.merge(); } }
package com.trump.auction.order.service.impl; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cf.common.util.mapping.BeanMapper; import com.cf.common.util.page.PageUtils; import com.cf.common.util.page.Paging; import com.github.pagehelper.PageHelper; import com.trump.auction.account.api.AccountInfoStubService; import com.trump.auction.order.dao.OrderAppraisesDao; import com.trump.auction.order.dao.OrderInfoDao; import com.trump.auction.order.domain.OrderAppraises; import com.trump.auction.order.domain.OrderInfo; import com.trump.auction.order.enums.EnumAppraisesShow; import com.trump.auction.order.enums.EnumOrderStatus; import com.trump.auction.order.model.OrderAppraisesModel; import com.trump.auction.order.model.OrderInfoModel; import com.trump.auction.order.service.OrderAppraisesRulesService; import com.trump.auction.order.service.OrderAppraisesService; import com.trump.auction.order.service.OrderInfoService; import com.trump.auction.order.util.Base64Utils; /** * 评价管理 * Created by wangjian on 2017/12/20. */ @Slf4j @Service("auctionOrderInfoService") public class OrderAppraisesServiceImpl implements OrderAppraisesService { private static Logger logger = LoggerFactory.getLogger(OrderAppraisesServiceImpl.class); @Autowired private OrderAppraisesDao orderAppraisesDao; @Autowired private BeanMapper beanMapper; @Autowired private OrderInfoService orderInfoService ; @Autowired private AccountInfoStubService accountInfoStubService; @Autowired private OrderInfoDao orderInfoDao; @Autowired private OrderAppraisesRulesService orderAppraisesRulesService; @Override public Paging<OrderAppraisesModel> getAppraisesByUserId(String userId) { return PageUtils.page(beanMapper.mapAsList(orderAppraisesDao.getAppraisesByUserId(userId),OrderAppraisesModel.class)) ; } @Override public Integer createOrderAppraises(OrderAppraisesModel orderAppraisesModel) { if (orderAppraisesModel.getContent()==null){ orderAppraisesModel.setContent(""); } if (orderAppraisesModel.getAppraisesPic()==null){ orderAppraisesModel.setAppraisesPic(""); } //解码匹配 orderAppraisesModel.setContent(Base64Utils.decodeStr(orderAppraisesModel.getContent())); //根据规则判定等级接口 orderAppraisesModel.setAppraisesLevel(orderAppraisesRulesService.orderAppraisesRulesLevelCheck(orderAppraisesModel.getContent(),orderAppraisesModel.getAppraisesPic())); orderAppraisesModel.setContent(Base64Utils.encodeStr(orderAppraisesModel.getContent())); return orderAppraisesDao.insertAppraise(beanMapper.map(orderAppraisesModel, OrderAppraises.class)); } @Override public OrderAppraisesModel queryOrderAppraises(String appraisesId) { return beanMapper.map(orderAppraisesDao.selectByPrimaryKey(Integer.valueOf(appraisesId)), OrderAppraisesModel.class); } @Override public void orderAppraisesCheck(String appraisesId, String isShow,String baseRewords,String showRewords,String level,String valueArray) { OrderInfoModel orderInfoModel = new OrderInfoModel(); OrderAppraises orderAppraises = orderAppraisesDao.selectByPrimaryKey(Integer.valueOf(appraisesId)); if(EnumAppraisesShow.SHOW.getValue().equals(Integer.valueOf(isShow))){ //审核成功更改订单状态 try { OrderInfo orderInfo = orderInfoDao.selectByPrimaryKey(orderAppraises.getOrderId()); if(!EnumOrderStatus.LIUPAI.getValue().equals(orderInfo.getOrderStatus()) ){ orderInfoModel.setOrderId(orderAppraises.getOrderId()); orderInfoModel.setOrderStatus(EnumOrderStatus.COMPLETE.getValue()); orderInfoService.updateOrderStatus(orderInfoModel); } } catch (Exception e) { logger.error("更改订单状态失败:{}", e); } try { int paresentCoin =0,baseCoin =0 ; if(null !=showRewords && !"".equals(showRewords)){ paresentCoin = Integer.parseInt(showRewords); } if(null !=baseRewords && !"".equals(baseRewords)){ baseCoin = Integer.parseInt(baseRewords); } //晒单成功,增加baseRewords积分 accountInfoStubService.backCoinByShareAuctionOrder(Integer.valueOf(orderAppraises.getBuyId()),baseCoin, 3); accountInfoStubService.backCoinByShareAuctionOrder(Integer.valueOf(orderAppraises.getBuyId()),paresentCoin, 2); } catch (NumberFormatException e) { logger.error("增加积分失败:{}", e); } } String appraisesPic = orderAppraises.getAppraisesPic(); if(null == appraisesPic || "".equals(appraisesPic) || "null".equals(appraisesPic)){ if(null == valueArray || "".equals(valueArray)){ appraisesPic = appraisesPic; }else{ appraisesPic = valueArray+","; } }else{ if(null == valueArray || "".equals(valueArray)){ appraisesPic = appraisesPic; }else { appraisesPic+=valueArray+","; } } orderAppraisesDao.orderAppraisesCheck(appraisesId,isShow,level,appraisesPic); } @Override public Paging<OrderAppraisesModel> queryAppraisesByProductId(String productId,Integer pageNum, Integer pageSize) { long startTime = System.currentTimeMillis(); log.info("queryAppraisesByProductId invoke,StartTime:{},params:{},{},{}", startTime, productId, pageNum, pageSize); if (null == productId || "".equals(productId) ) { throw new IllegalArgumentException("queryAppraisesByProductId param productId is null!"); } Paging<OrderAppraisesModel> orderAppraises = null; PageHelper.startPage(pageNum, pageSize); try { orderAppraises = PageUtils.page(orderAppraisesDao.queryAppraisesByProductId(productId),OrderAppraisesModel.class,beanMapper); } catch (Exception e) { log.error("findAllOrder error:", e); } long endTime = System.currentTimeMillis(); log.info("queryAppraisesByProductId end,duration:{}", endTime - startTime); return orderAppraises; } @Override public OrderAppraisesModel getNewestAppraises(String userId, String orderId) { return beanMapper.map(orderAppraisesDao.getNewestAppraises(userId,orderId), OrderAppraisesModel.class); } }
package com.algorithm.tree; import java.util.*; public class LevelOrder1 { public List<List<Integer>> list = new ArrayList<List<Integer>>(); public List<List<Integer>> levelOrder(Node root) { if(root == null){ return Collections.emptyList(); } Queue<Node> queue = new LinkedList<Node>(); queue.add(root); while(queue.size()!=0){ int size = queue.size(); List<Integer> innerList = new ArrayList<Integer>(); for (int i = 0; i < size; i++) { Node node = queue.remove(); List<Node> nodeL = node.children; if(nodeL !=null){ for (int j = 0; j < nodeL.size(); j++) { queue.add(nodeL.get(i)); } } innerList.add(node.val); } list.add(innerList); } return list; } public static void main(String[] args) { } }
package controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import model.Order; import model.SlydepayHttpPostRequester; /** * Servlet implementation class Controller */ @WebServlet("/Controller") public class Controller extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Controller() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); Order newOrder = new Order(); PrintWriter out = response.getWriter(); //if Statement handles submission from form element on Order.jsp Page if (action.equals("restPost")) { String httpPostMerchEmail = request.getParameter("merchantEmail"); String httpPostMerchKey = request.getParameter("merchantKey"); String httpPostOrderName = request.getParameter("orderName"); String httpPostItem = request.getParameter("item"); Integer httpPostQnty = Integer.parseInt(request.getParameter("quantity")); // data from input form on Order.jsp page stored in variables for // Servlet process // beginning of the processing of post request in servlet for REST API // API url String url = "https://app.slydepay.com/api/merchant/invoice/payoptions"; // Creation of Order newOrder.setMerchantEmail(httpPostMerchEmail); newOrder.setMerchantKey(httpPostMerchKey); newOrder.setOrderName(httpPostOrderName); newOrder.setItem(httpPostItem); newOrder.setQuantity(httpPostQnty); // Creation of URL for post request String answer = SlydepayHttpPostRequester.ListPayOptionsUrlCreator(newOrder, url); System.out.println(answer); // Initiating post request using HTTPURLCONNECTION HttpResponse response2 = SlydepayHttpPostRequester.makePostRequest2(answer, newOrder); // Reading Json Response BufferedReader rd = new BufferedReader(new InputStreamReader(response2.getEntity().getContent())); String output = ""; Boolean success = null; String newoutput; Object errorMessage = null; Object errorCode; StringBuilder sb = new StringBuilder(output); System.out.println("Output from Server .... \n"); try { while ((output = rd.readLine()) != null) { sb.append(output); } System.out.println(output); } catch (Exception e) { e.printStackTrace(); } newoutput = sb.toString(); System.out.println(newoutput); JSONObject JSONRESPONSE = null; try { JSONRESPONSE = new JSONObject(newoutput); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { success = JSONRESPONSE.getBoolean("success"); if (success == false) { try { errorMessage = JSONRESPONSE.getString("errorMessage"); System.out.println(errorMessage); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("errorMessage", errorMessage); request.getRequestDispatcher("Error.jsp").forward(request, response); return; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { errorMessage = JSONRESPONSE.get("errorMessage").toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { errorCode = JSONRESPONSE.get("errorCode").toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONArray JsonArrayFromApiWithResult = null; try { JsonArrayFromApiWithResult = JSONRESPONSE.getJSONArray("result"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println(JsonArrayFromApiWithResult.toString()); if (JsonArrayFromApiWithResult != null) { ArrayList<Object> payoptions = new ArrayList<Object>(); ArrayList<Object> payoptionsNames = new ArrayList<Object>(); for (int i = 0; i < JsonArrayFromApiWithResult.length(); i++) { JSONObject payoptionObject = null; JSONObject payoptionName = null; try { payoptionObject = (JSONObject) JsonArrayFromApiWithResult.get(i); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } String link = null; try { link = payoptionObject.get("logourl").toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } payoptions.add(link); String name = null; try { name = payoptionObject.get("name").toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } payoptionsNames.add(name); } System.out.println(payoptions.size()); System.out.println("enter ... \n"); for (int i = 0; i <= payoptions.size() - 1; i++) { System.out.println(payoptionsNames.get(i)); } newOrder.setPayoptions(payoptions); newOrder.setPayoptionsNames(payoptionsNames); rd.close(); request.setAttribute("LinkstoPayOptions", newOrder); request.getRequestDispatcher("Result.jsp").forward(request, response); return; } } //The If statement below is to process input from the Results.jsp page //The input exists as a specific hidden value pertaining to the specific //form submitted. if(action.equals("PayOption")){ String PayOptionSlctdFromResultPg = request.getParameter("PayOptionSlctd").toString(); //this line expects an Integer value to come from input form. However,Integer value exists as object //Hence line above converts Integer object to string then to an Integer equivalent for processing System.out.println( PayOptionSlctdFromResultPg); //Debug information. for(int i = 0;i < newOrder.getPayoptionsNames().size(); i++ ){ if(PayOptionSlctdFromResultPg.equals(newOrder.getPayoptionsNames().get(i))){ String successMessage = "You Have paid successfully"; request.setAttribute("successMessage", successMessage); request.getRequestDispatcher("Success.jsp").forward(request, response); } } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.document.feed.service; import com.document.feed.model.ArticleReactiveRepository; import com.document.feed.model.Preference; import com.document.feed.model.PreferenceReactiveRepository; import com.document.feed.util.IdUtils; import com.kwabenaberko.newsapilib.models.Article; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.MultiMatchQueryBuilder.Type; import org.elasticsearch.index.query.QueryBuilders; import org.springframework.data.domain.PageRequest; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Service @RequiredArgsConstructor @Slf4j public class FeedService { private final ArticleReactiveRepository articleReactiveRepository; private final PreferenceReactiveRepository preferenceRepository; public Flux<com.kwabenaberko.newsapilib.models.Article> vanillaList(PageRequest pageRequest) { return articleReactiveRepository .findAllBQ(new NativeSearchQueryBuilder().withPageable(pageRequest).build()) .flatMap(articleSearchHit -> Mono.just(articleSearchHit.getContent().getArticle())); } public Flux<com.kwabenaberko.newsapilib.models.Article> list(PageRequest pageRequest) { log.info("/list called"); var authentication = SecurityContextHolder.getContext().getAuthentication(); String username = (String) authentication.getPrincipal(); log.info("username:" + username); log.info("sc:" + SecurityContextHolder.getContext().getAuthentication()); var queryList = new String[] {"", "", ""}; var a = preferenceRepository .findByUsername(username) .flatMap(preference -> Flux.just(preference.getArticle())) .reduce( queryList, (l, article) -> { l[0] += " " + article.getTitle() + " " + article.getDescription(); l[1] += " " + article.getAuthor(); l[2] += " " + article.getSource().getName(); log.info(l[0] + ", " + l[1] + ", " + l[2]); return l; }) .map( qList -> { return new NativeSearchQueryBuilder() .withPageable(pageRequest) .withQuery( new BoolQueryBuilder() .should( QueryBuilders.multiMatchQuery(qList[0]) .field("article.description", 3) .lenient(true) .field("article.title", 3) .type(Type.MOST_FIELDS) .fuzziness(Fuzziness.TWO)) .should( QueryBuilders.matchQuery("article.author", qList[1]) .boost(StringUtils.isBlank(qList[1]) ? 0 : 1)) .should( QueryBuilders.matchQuery("article.source.name", qList[2]) .boost(2))) .build(); }) .cache(); a.subscribe( nativeSearchQuery -> { log.info("query:" + nativeSearchQuery.toString()); }); return a.flatMapMany(articleReactiveRepository::findAllBQ) .flatMap(articleSearchHit -> Mono.just(articleSearchHit.getContent().getArticle())) .switchIfEmpty(vanillaList(pageRequest)); } public Flux<com.kwabenaberko.newsapilib.models.Article> getPreference() { log.info("/preference called"); var authentication = SecurityContextHolder.getContext().getAuthentication(); String username = (String) authentication.getPrincipal(); log.info("username:" + username); log.info("sc:" + SecurityContextHolder.getContext().getAuthentication()); return preferenceRepository.findByUsername(username).flatMap(s -> Flux.just(s.getArticle())); } public Mono<Preference> savePreference(Article a, String username) { System.out.println("FeedService.savePreference called"); var preference = new Preference(); preference.setArticle(a); preference.setUsername(username); preference.setId(IdUtils.id(a.getUrl())); return preferenceRepository.save(preference).flatMap(Mono::just); } public Mono<Void> deletePreference(String id) { System.out.println("FeedService.deletePreference called"); return preferenceRepository.deleteById(id); } }
package com.jwebsite.dao; import java.util.List; import com.jwebsite.vo.Attach; /** * 附件管理 * @author 木鱼 */ public interface AttachDao { //添加附件 public void AddAttach(Attach attach)throws Exception; //删除附件 public void DelAttach(int ID)throws Exception; //修改附件 public int UpdateAttach(Attach attach)throws Exception; //查看附件 public List<Attach> QureyAttach(String ArticleID)throws Exception; //清除过期附件 public void ClearAttach(String time)throws Exception; }
package com.example.stockup; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.EmailAuthProvider; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class RunnerWalletChangeActivity extends AppCompatActivity { EditText myNum; EditText myPassword; Button myButton; String num; String password; FirebaseUser user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_runner_wallet_change); user = FirebaseAuth.getInstance().getCurrentUser(); myNum = (EditText) findViewById(R.id.runner_new_number); myPassword = (EditText) findViewById(R.id.runner_new_number_confirm); myButton = (Button) findViewById(R.id.runner_new_number_button); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { num = myNum.getText().toString().trim(); password = myPassword.getText().toString().trim(); if (num.isEmpty()) { Toast.makeText(RunnerWalletChangeActivity.this, "Fill in your new number.", Toast.LENGTH_SHORT).show(); } else if (num.length() != 8) { Toast.makeText(RunnerWalletChangeActivity.this, "Invalid phone number.", Toast.LENGTH_SHORT).show(); } else { AuthCredential authCredential = EmailAuthProvider.getCredential(user.getEmail(), password); user.reauthenticate(authCredential) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); DatabaseReference setCard = FirebaseDatabase.getInstance().getReference("users").child(user.getDisplayName().substring(1)).child("myNumber"); setCard.setValue(num); Toast.makeText(RunnerWalletChangeActivity.this, "Wallet Updated", Toast.LENGTH_SHORT).show(); Intent nextIntent = new Intent(RunnerWalletChangeActivity.this, RunnerWalletActivity.class); startActivity(nextIntent); } else { Toast.makeText(RunnerWalletChangeActivity.this, "Wrong Password.", Toast.LENGTH_SHORT).show(); } } }); } } }); } }
public class BinaryHeap<T extends Comparable<? super T>> { public T[] heap; public int size; @SuppressWarnings("unchecked") public BinaryHeap() { size = 0; this.heap = (T[]) new Comparable[10]; } @SuppressWarnings("unchecked") public void insert(T element) { if (this.size+1 >= heap.length) { T[] temp = heap; heap = (T[]) new Comparable[heap.length * 2]; for (int i = 0; i < temp.length; i++) { heap[i] = temp[i]; } } heap[this.size + 1] = element; size++; int index = size; while (index > 1 && heap[index / 2].compareTo(element) > 0) { heap[0] = heap[index / 2]; heap[index / 2] = element; heap[index] = heap[0]; heap[0] = null; index = index/2; } } public T deleteMin() { if (this.size == 0) { return null; } T min = heap[1]; heap[1] = heap[size]; heap[size] = null; size = size - 1; if (this.size == 0) { return min; } percolateDown(1); return min; } public void percolateDown(int index){ while (2 * index <= size) { if (2 * index + 1 <= size && heap[2 * index].compareTo(heap[2 * index + 1]) > 0) { if (heap[index].compareTo(heap[2 * index + 1]) > 0) { heap[0] = heap[2 * index + 1]; heap[2 * index + 1] = heap[index]; heap[index] = heap[0]; heap[0] = null; index = 2*index + 1; } else break; } else { if (heap[index].compareTo(heap[2 * index]) > 0) { heap[0] = heap[2 * index]; heap[2 * index] = heap[index]; heap[index] = heap[0]; heap[0] = null; index = 2*index; } else break; } } } public String toString() { String s = ""; s += "["; for (int i = 0; i <= size; i++) { s += heap[i] + ", "; } s = s.substring(0, s.length() - 2); s += "]"; return s; } private void buildHeap(){ for(int i = size/2; i>0; i--){ percolateDown(i); } } @SuppressWarnings("unchecked") public void sort(T[] j){ for(int i = 1; i < j.length+1; i ++){ heap[i] = j[i-1]; if(i>=heap.length-1){ T[] temp = heap; heap = (T[]) new Comparable[heap.length * 2]; for (int k = 0; k < temp.length; k++) { heap[k] = temp[k]; } } } size = j.length; buildHeap(); T[] sorted = (T[]) new Comparable[size + 1]; int ssize = size; for(int i = 1; i <= ssize; i ++){ sorted[i] = this.deleteMin(); } heap = sorted; size = ssize; for(int i = 1; i < j.length+1; i ++){ j[i-1] = heap[i]; } } }
package generic; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.testng.annotations.BeforeTest; public class base_class { public XSSFWorkbook wb = null; public static base_class b; @BeforeTest(groups={"SmokeTest","Regression"}) public void execute_beforetest() throws IOException { System.out.println("Test"); FileInputStream fis = new FileInputStream(System.getProperty("user.dir")+"\\src\\test\\resources\\Test_Data.xlsx"); b = new base_class(); b.wb=new XSSFWorkbook(fis); if(b.wb==null) { System.out.println("ISNULL"); } } }
package com.lesports.albatross.adapter.compertition.details; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ClickableSpan; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lesports.albatross.R; import com.lesports.albatross.custom.NameClickableSpan; import com.lesports.albatross.listener.community.OnCommentClickListener; import com.lesports.albatross.listener.community.OnCommentLongClickListener; import com.sohu.cyan.android.sdk.entity.Comment; import java.util.List; /** * 赛事详情-评论 * Created by zhouchenbin on 16/6/15. */ public class CompDetailsCommentReplyAdapter extends RecyclerView.Adapter<CompDetailsCommentReplyAdapter.CommentHolder> { private Context mContext; private List<Comment> mList; private OnCommentClickListener mOnCommentClickListener; private OnCommentLongClickListener mOnCommentLongClickListener; private int moment_id; private String user_id;//本机用户ID public CompDetailsCommentReplyAdapter(Context ctx, List<Comment> list, int moment_id, String user_id) { this.mContext = ctx; this.mList = list; this.moment_id = moment_id; this.user_id = user_id; } public CommentHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.community_comment_list_item, parent, false); return new CommentHolder(view, mOnCommentClickListener, mOnCommentLongClickListener); } @Override public void onBindViewHolder(CommentHolder holder, int position) { Comment comment = mList.get(position); if (comment == null || comment.passport == null) { return; } SpannableString name = new SpannableString(comment.passport.nickname); ClickableSpan span = new NameClickableSpan(mContext, R.color.purple_name, String.valueOf(comment.passport.user_id)); name.setSpan(span, 0, comment.passport.nickname.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); holder.tv_comment.setText(name); holder.tv_comment.append(" : "); holder.tv_comment.append(comment.content); } @Override public void onViewRecycled(CommentHolder holder) { super.onViewRecycled(holder); } @Override public int getItemCount() { return mList != null ? mList.size() : 0; } public void setOnCommentClickListener(OnCommentClickListener listener) { this.mOnCommentClickListener = listener; } public void setOnCommentLongClickListener(OnCommentLongClickListener listener) { this.mOnCommentLongClickListener = listener; } class CommentHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener, View.OnCreateContextMenuListener { private TextView tv_comment; private OnCommentClickListener mOnCommentClickListener; private OnCommentLongClickListener mOnCommentLongClickListener; public CommentHolder(View itemView, OnCommentClickListener onClickistener, OnCommentLongClickListener onLongClickListener) { super(itemView); tv_comment = (TextView) itemView.findViewById(R.id.tv_comment); this.mOnCommentClickListener = onClickistener; this.mOnCommentLongClickListener = onLongClickListener; tv_comment.setOnClickListener(this); tv_comment.setOnLongClickListener(this); tv_comment.setOnCreateContextMenuListener(this); } @Override public void onClick(View v) { if (mOnCommentClickListener != null) { mOnCommentClickListener.onCommentClickEvent(moment_id, String.valueOf(mList.get(getAdapterPosition()).comment_id), null); } } @Override public boolean onLongClick(View v) { if (mOnCommentLongClickListener != null) { mOnCommentLongClickListener.onCommentLongClickEvent(0, getAdapterPosition(), mList.get(getAdapterPosition()).content, String.valueOf(mList.get(getAdapterPosition()).reply_id)); } return false; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { menu.add(Menu.NONE, Menu.FIRST, Menu.NONE, "复制"); if (user_id.equals(mList.get(getAdapterPosition()).passport.user_id)) { menu.add(Menu.NONE, Menu.FIRST + 1, Menu.NONE, "删除"); } } } }
package Java三.线程常用操作方法; public class Interrupt1 { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(()->{ System.out.println("****线程开始启动***"); try { Thread.sleep(10000); //预计准备休眠10秒 } catch (InterruptedException e) { System.out.println("*****线程中断抛出异常****"); } }) ; thread.start(); //开始就绪 Thread.sleep(1000); if(!Thread.interrupted()){ System.out.println("******线程中断****"); thread.interrupt(); } } }
import java.util.Stack; public class ConvertBase { public static void main(String[] args) { //System.out.println("Hello World!"); convert_base(188, 16); System.out.println(); System.out.println(restore("BC", 16)); } //input 10 base //output d base d<=16 public static void convert_base(int n, int d){ Stack<Integer> s = new Stack<>(); int e = 0; while(n != 0){ e = n % d; s.push(e); n /= d; } while(!s.isEmpty()){ e = s.pop(); System.out.printf("%X", e); } } //intput d base string d<= 16 //output 10 base int public static int restore(String s, int d){ s = s.toLowerCase(); char[] chars = s.toCharArray(); int result = 0; int one = 0; for(int i = 0; i < chars.length; i++){ if(chars[i] >= '0' && chars[i] <= '9'){ one = chars[i] - '0'; }else{ one = chars[i] - 'a' + 10; } result = result * d + one; } return result; } }
package leetCode.copy.Array; import java.util.Arrays; /** * 274. H 指数 * * 给定一位研究者论文被引用次数的数组(被引用次数是非负整数)。编写一个方法,计算出研究者的 h 指数。 * h 指数的定义:h 代表“高引用次数”(high citations),一名科研人员的 h 指数是指他(她)的 (N 篇论文中)总共有 h 篇论文分别被引用了至少 h 次。且其余的 N - h 篇论文每篇被引用次数 不超过 h 次。 * 例如:某人的 h 指数是 20,这表示他已发表的论文中,每篇被引用了至少 20 次的论文总共有 20 篇。 * <p> * 示例: * 输入:citations = [3,0,6,1,5] * 输出:3 * 解释:给定数组表示研究者总共有 5 篇论文,每篇论文相应的被引用了 3, 0, 6, 1, 5 次。 *   由于研究者有 3 篇论文每篇 至少 被引用了 3 次,其余两篇论文每篇被引用 不多于 3 次,所以她的 h 指数是 3。 *   * 提示:如果 h 有多种可能的值,h 指数是其中最大的那个。 * <p> * https://leetcode-cn.com/problems/h-index */ public class no274_h_index { /** * 我自己想到的方法 没想到一次提交就通过 自我打气一下 * @param citations * @return */ public int hIndex_method(int[] citations) { if (citations == null || citations.length == 0) return 0; Arrays.sort(citations); int len = citations.length; int index = 0; int pre = 0; for (int i = len; i > 0; i--) { index++; int val = citations[i - 1]; if (val >= index) { pre = val; } else { return Math.min(pre, index - 1); } } return Math.min(pre, index); } /** * 计数法 * https://leetcode-cn.com/problems/h-index/solution/hzhi-shu-by-leetcode/ * @param citations * @return */ public int hIndex(int[] citations) { if (citations == null || citations.length == 0) return 0; int len = citations.length; int[] array = new int[len + 1]; for (int iter : citations) { // 大于数据长度 按照数组长度计算 array[Math.min(iter, len)]++; } int k = len; for (int s = array[len]; k > s; s += array[k]) { k--; } return k; } public static void main(String args[]) { no274_h_index obj = new no274_h_index(); int result = obj.hIndex(new int[]{3, 0, 6, 1, 5}); System.out.println("array(3,0,6,1,5):" + result); result = obj.hIndex(new int[]{3, 6}); System.out.println("array(3,6):" + result); result = obj.hIndex(new int[]{3}); System.out.println("array(3):" + result); } }
package org.ordogene.algorithme.models; import java.util.Objects; import org.ordogene.file.models.JSONInput; import org.ordogene.file.models.Relation; public class Input extends Entity{ private final Relation relation; public Input(String name, int quantity, Relation relation) { super(name, quantity); this.relation = Objects.requireNonNull(relation); } public static Input createInput(JSONInput ji) { Objects.requireNonNull(ji); return new Input(ji.getName(), ji.getQuantity(), ji.getRelation()); } public Relation getRelation() { return relation; } @Override public int hashCode() { final int prime = 31; int result = prime * super.hashCode(); result = prime * result + relation.hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Input)) return false; Input input = (Input) obj; if (!super.equals(obj)) return false; if (relation != input.relation) return false; return true; } @Override public String toString() { return "Input [entity=" + super.toString() + ", relation=" + relation + "]"; } }
import java.util.Scanner; public class Fibonacci { private static long calcFibNaive(int n) { if (n <= 1) return n; return calcFibNaive(n - 1) + calcFibNaive(n - 2); } private static long calcFibOptimized(int n) { if (n <= 1) { return n; } int[] array = new int[n + 1]; array[0] = 0; array[1] = 1; for (int i = 2; i <= n; i++) { array[i] = array[i - 1] + array[i - 2]; } return array[n]; } public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long startTime = System.nanoTime(); System.out.println(calcFibNaive(n)); long endTime = System.nanoTime(); long duration = (endTime - startTime) / 1000; System.out.println(String.format("It took %s ms", duration)); startTime = System.nanoTime(); System.out.println(calcFibOptimized(n)); endTime = System.nanoTime(); duration = (endTime - startTime) / 1000; System.out.println(String.format("Optimized algorithm took %s ms", duration)); } }
package Modele; import Generatory.GeneratorProjektow; import Modele.Podwykonawcy.Podwykonawca; import Modele.Pracownicy.Pracownik; import Modele.Pracownicy.Programista; import Modele.Pracownicy.Sprzedawca; import Modele.Pracownicy.Tester; import Modele.Projekt; import Modele.Termin; import java.util.ArrayList; import java.util.List; public class Firma { public int IloscPieniedzy; public Termin ObecnyTermin; public List<Projekt> Projekty; public List<Projekt> ProjektyDoOddania; public int IloscDniSzukaniaProjektu = 0; public boolean CzyNowyProjekt; public List<Projekt> DostepneProjekty; public List<Pracownik> Pracownicy; public List<Podwykonawca> Podwykonawcy; public List<Pracownik> OgloszeniaPracownicy; public List<Podwykonawca> OgloszeniaPodwykonawca; GeneratorProjektow generatorProjektow; public int IloscDniRozliczania = 0; public boolean CzyPrzegrana; public List<Projekt> ProjektyDoZaplaty; public boolean CzyWygrana; public Firma(int IloscPieniedzy, Termin ObecnyTermin) { this.IloscPieniedzy = IloscPieniedzy; this.ObecnyTermin = ObecnyTermin; Projekty = new ArrayList<Projekt>(); CzyNowyProjekt = true; DostepneProjekty = new ArrayList<Projekt>(); Pracownicy = new ArrayList<Pracownik>(); Podwykonawcy = new ArrayList<Podwykonawca>(); OgloszeniaPracownicy = new ArrayList<Pracownik>(); OgloszeniaPodwykonawca = new ArrayList<Podwykonawca>(); ProjektyDoOddania = new ArrayList<Projekt>(); ProjektyDoZaplaty = new ArrayList<Projekt>(); generatorProjektow = new GeneratorProjektow(); CzyPrzegrana = false; CzyWygrana = false; } public void NastepnyDzien() { //dodanie dnia ObecnyTermin = ObecnyTermin.DodajDni(1); if (IloscPieniedzy == 0) { CzyPrzegrana = true; } if (CzyGraWygrana()) { System.out.println("Wygrales"); CzyWygrana = true; } int IloscTesterow = 0; try { ////Zaplacenie wyplaty if (ObecnyTermin.Dzien % 30 == 0) { for (Podwykonawca podwykonawca : Podwykonawcy) { IloscPieniedzy -= podwykonawca.StawkaMiesieczna; } for (Pracownik pracownik : Pracownicy) { IloscPieniedzy -= pracownik.StawkaMiesieczna; } ////Sprawdzenie czy dwa razy w miesiacu sie rozliczales if (IloscDniRozliczania >= 2) { System.out.println("Nie rozliczyles sie w pore z urzedem. Firma zostaje zamknieta"); CzyPrzegrana = true; } else { IloscDniRozliczania = 0; } } PracujPodwykonawca(); PracujPracownik(IloscTesterow); //Sprawdzanie przypadku jak jest jeden tester na trzech pracownikow - wtedy na pewno projekt bedzie poprawny //Sprawdzenie czy projekt zostal zakonczony i dodanie na liste zakonczonych projektow List<Integer> indeksyZakonczonychProjektow = new ArrayList<Integer>(); int iterator = 0; for (int i = 0; i < Projekty.size(); i++ ) { if (IloscTesterow != 0) { if (Pracownicy.size() + Podwykonawcy.size() % IloscTesterow == 3) { for (Technologia technologia : Projekty.get(i).Technologie) { technologia.CzyTestowana = true; } } } if (CzyProjektZakonczony(Projekty.get(i))) { ProjektyDoOddania.add(Projekty.get(i).Kopiuj()); System.out.println("Zakonczyles projekt"); indeksyZakonczonychProjektow.add(i); } } //usuniecie zakonczonych projektow z listy projektow for (int i : indeksyZakonczonychProjektow) { Projekty.remove(i); } List<Integer> indeksyOplaconychProjektow = new ArrayList<Integer>(); for (int i = 0; i < ProjektyDoZaplaty.size(); i++ ) { if (ProjektyDoZaplaty.get(i).TerminPlatnosci.Dzien == ObecnyTermin.Dzien && ProjektyDoZaplaty.get(i).TerminPlatnosci.Rok == ObecnyTermin.Rok) { IloscPieniedzy += ProjektyDoZaplaty.get(i).CenaZaplaty; indeksyOplaconychProjektow.add(i); } } for (int i : indeksyOplaconychProjektow ) { ProjektyDoZaplaty.remove(i); } } catch (Exception ex) { System.out.println("Bledne dane"); } } //Losowanie przypadku choroby public boolean CzyChory() { if (Losuj(0, 100) == 1) { return true; } return false; } public boolean CzyProjektZakonczony(Projekt projekt) { int sumaDni = 0; for (Technologia technologia : projekt.Technologie ) { sumaDni += technologia.DniRobocze; } return sumaDni == 0; } public int Losuj(int minimalna, int maksymalna) { return minimalna + (int) (Math.random() * maksymalna); } public boolean CzyGraWygrana() { int ilosc = 0; for (Projekt projekt : Projekty) { if (projekt.poziomTrudnosci.equals(Projekt.PoziomTrudnosci.trudny)) { for (Technologia technologia : projekt.Technologie) { if (technologia.CzyPrzezWlascicielaProgramowane || technologia.CzyPrzezWlascicielaTestowane) { return false; } } if (projekt.CzyPozyskales) { ilosc++; } } } return ilosc != 3 && IloscPieniedzy > 1000; } public void PracujPodwykonawca() { for (Podwykonawca podwykonawca : Podwykonawcy) { if (ObecnyTermin.Dzien % 6 != 0 && ObecnyTermin.Dzien % 7 != 0) { if (!CzyChory()) { if (podwykonawca.CzyPrzydzielony) { for (Projekt projekt : Projekty) { if (podwykonawca.PrzydzielonyProjekt.Wypisz().equals(projekt.Wypisz())) { for (Technologia technologia : projekt.Technologie) { if (technologia.Nazwa.equals(podwykonawca.PrzydzielonaTechnologia.Nazwa + "")) { if (technologia.DniRobocze != 0) { technologia.DniRobocze--; } else { int czasOpoznienia = podwykonawca.CzasOpoznienia(); int dokladnosc = podwykonawca.Dokladnosc(); if (czasOpoznienia > 0) { System.out.println("Twoj pracownik " + podwykonawca.Imie + " nie wyrobil sie na czas opoznienie bedzie trwalo: " + czasOpoznienia); technologia.DniRobocze += czasOpoznienia; } else { if (dokladnosc > 0) { System.out.println("Twoj pracownik " + podwykonawca.Imie + " nie byl zbyt dokladny musisz przypisac kogos do poprawienia zadan,\n" + " czas na wniesienie poprawek wynosi: " + dokladnosc); technologia.DniRobocze += dokladnosc; } podwykonawca.CzyPrzydzielony = false; podwykonawca.PrzydzielonaTechnologia = null; podwykonawca.PrzydzielonyProjekt = null; } } } } } } } } else { System.out.println(podwykonawca.Imie + " Zachorowal"); } } } } public void PracujPracownik(int IloscTesterow) { for (Pracownik pracownik : Pracownicy) { if (ObecnyTermin.Dzien % 6 != 0 && ObecnyTermin.Dzien % 7 != 0) { if (!CzyChory()) { if (pracownik instanceof Programista) { if (((Programista) pracownik).CzyPrzydzielony) { for (Projekt projekt : Projekty) { if (((Programista) pracownik).PrzydzielonyProjekt.Wypisz().equals(projekt.Wypisz())) { for (Technologia technologia : projekt.Technologie) { if (technologia.Nazwa.equals(((Programista) pracownik).PrzydzielonaTechnologia.Nazwa + "")) { if (technologia.DniRobocze != 0) { technologia.DniRobocze--; } else { int czasOpoznienia = ((Programista) pracownik).Punktualnosc(); int dokladnosc = ((Programista) pracownik).Dokladnosc(); if (czasOpoznienia > 0) { System.out.println("Twoj pracownik " + pracownik.imie + " nie wyrobil sie na czas opoznienie bedzie trwalo: " + czasOpoznienia); technologia.DniRobocze += czasOpoznienia; } else { if (dokladnosc > 0) { System.out.println("Twoj pracownik " + pracownik.imie + " nie byl zbyt dokladny musisz przypisac kogos do poprawienia zadan,\n" + " czas na wniesienie poprawek wynosi: " + dokladnosc); technologia.DniRobocze += dokladnosc; } ((Programista) pracownik).CzyPrzydzielony = false; ((Programista) pracownik).PrzydzielonaTechnologia = null; ((Programista) pracownik).PrzydzielonyProjekt = null; } } } } } } } } if (pracownik instanceof Sprzedawca) { if (((Sprzedawca) pracownik).IloscDniPoszukiwan == 5) { ((Sprzedawca) pracownik).IloscDniPoszukiwan = 0; generatorProjektow.Wygeneruj(1, ObecnyTermin); DostepneProjekty.addAll(generatorProjektow.Projekty); CzyNowyProjekt = true; System.out.println("Znaleziono nowy projekt"); } else { ((Sprzedawca) pracownik).IloscDniPoszukiwan++; } } if (pracownik instanceof Tester) IloscTesterow++; } else { System.out.println(pracownik.imie + " Zachorowal"); } } } } }
package com.jinku.sync; import org.jinku.sync.application.bootstrap.ApplicationConfig; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import javax.sql.DataSource; public class ApplicationTestConfig extends ApplicationConfig { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .addScript("data/db-mode.sql") .addScript("data/db-schema.sql") .addScript("data/db-data.sql") .build(); } }
package com.dian.diabetes.activity.user; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.ListView; import android.widget.Toast; import com.dian.diabetes.R; import com.dian.diabetes.activity.BasicActivity; import com.dian.diabetes.activity.DialogLoading; import com.dian.diabetes.activity.TranLoading; import com.dian.diabetes.activity.user.adapter.MemberAdapter; import com.dian.diabetes.db.AlarmBo; import com.dian.diabetes.db.UserBo; import com.dian.diabetes.db.UserInfoBo; import com.dian.diabetes.db.dao.User; import com.dian.diabetes.db.dao.UserInfo; import com.dian.diabetes.dialog.AlertDialog; import com.dian.diabetes.request.HttpContants; import com.dian.diabetes.request.UserDataAPI; import com.dian.diabetes.service.IndicateService; import com.dian.diabetes.service.LoadingService; import com.dian.diabetes.service.UpdateService; import com.dian.diabetes.service.UserService; import com.dian.diabetes.tool.Config; import com.dian.diabetes.tool.Preference; import com.dian.diabetes.tool.ReadAreaFile; import com.dian.diabetes.tool.ToastTool; import com.dian.diabetes.utils.CheckUtil; import com.dian.diabetes.utils.ContantsUtil; import com.dian.diabetes.utils.HttpServiceUtil; import com.dian.diabetes.utils.StringUtil; import com.dian.diabetes.widget.anotation.ViewInject; /** * 类/接口注释 * * @author Chanjc@ifenguo.com * @createDate 2014年7月8日 * */ public class MemberActivity extends BasicActivity implements OnClickListener { @ViewInject(id = R.id.back_btn) private Button backBtn; @ViewInject(id = R.id.member_listview) private ListView memberListview; @ViewInject(id = R.id.addmember_btn) private Button addMemberBtn; @ViewInject(id = R.id.save_btn) private ImageButton saveBtn; private Button addMember; private List<UserInfo> data; private MemberAdapter adapter; private UserInfoBo userInfoBo; private UserBo userBo; private Preference preference; private TranLoading loading; private DialogLoading loadingDialog; private AlertDialog alert; private Map<String, String> maps; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_memberlist); userInfoBo = new UserInfoBo(context); userBo = new UserBo(context); preference = Preference.instance(context); // 初始化加载图片的尺寸 ContantsUtil.ADD_MEMBER = true; loading = new TranLoading(context); alert = new AlertDialog(context, "检测到您的个人信息不完整,是否去完善您的个人信息?"); alert.setCallBack(new AlertDialog.CallBack() { @Override public void cancel() { } @Override public void callBack() { Bundle bundle = new Bundle(); bundle.putLong("mid", StringUtil.toLong(ContantsUtil.DEFAULT_TEMP_UID)); bundle.putBoolean("isedit", true); startActivity(bundle, ManageUsersActivity.class); } }); loadingDialog = new DialogLoading(context); maps = new ReadAreaFile(context).readArea(); initActivity(); } public void onResume() { super.onResume(); if (!ContantsUtil.ADD_MEMBER) { loadUser(); ContantsUtil.ADD_MEMBER = true; } } private void initActivity() { addMemberBtn.setOnClickListener(this); backBtn.setOnClickListener(this); saveBtn.setOnClickListener(this); data = userInfoBo.list(ContantsUtil.curUser.getService_uid()); adapter = new MemberAdapter(context, data); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.item_member_bottom, null); addMember = (Button) view.findViewById(R.id.new_member); addMember.setOnClickListener(this); memberListview.addFooterView(view); memberListview.setAdapter(adapter); memberListview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View view, int position, long id) { UserInfo info = data.get(position); if (adapter.isEditAble()) { // 跳到编辑界面 Bundle data = new Bundle(); data.putLong("mid", info.getMid()); data.putString("nickname", info.getNick_name()); data.putBoolean("isedit", true); startActivity(data, ManageUsersActivity.class); } else { // 选择主成员 if (!CheckUtil.checkEquels(info.getId(), ContantsUtil.DEFAULT_TEMP_UID)) { setMainUser(info); } } } }); loadUser(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.back_btn: if (adapter.isEditAble()) { adapter.setEditAble(false); adapter.notifyDataSetChanged(); } else { finish(); } break; case R.id.addmember_btn: adapter.setEditAble(!adapter.isEditAble()); adapter.notifyDataSetChanged(); saveBtn.setVisibility(View.VISIBLE); addMemberBtn.setVisibility(View.GONE); break; case R.id.save_btn: adapter.setEditAble(!adapter.isEditAble()); adapter.notifyDataSetChanged(); saveBtn.setVisibility(View.GONE); addMemberBtn.setVisibility(View.VISIBLE); break; case R.id.new_member: startActivity(null, MemberAddFragment.class); break; } } // 加载用户成员 private void loadUser() { loading.show(); Map<String, Object> params = new HashMap<String, Object>(); HttpServiceUtil.request(ContantsUtil.URL_MEMBER_LIST, "post", params, new HttpServiceUtil.CallBack() { @Override public void callback(String json) { loading.dismiss(); try { JSONObject object = new JSONObject(json); int status = object.getInt("status"); if (status == HttpContants.REQUEST_SUCCESS) { data.clear(); JSONArray array = object.getJSONArray("data"); for (int i = 0; i < array.length(); i++) { String item = array.getString(i); UserInfo userInfo = new UserInfo(); UserInfo.transformToUserInfo(userInfo, item); // 数据库里面有没有当前用户,没有就保存在数据库,有就更新信息 UserInfo temp = userInfoBo .getUinfoByMid(userInfo.getMid()); if (temp == null) { userInfoBo.saveUserInfo(userInfo); } else { userInfo.setId(temp.getId()); userInfo.setUid(temp.getUid()); userInfoBo.updateUserInfo(userInfo); } data.add(userInfo); } adapter.notifyDataSetChanged(); } else { ToastTool.showToast(status, context); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(context, "数据解析出错", Toast.LENGTH_SHORT).show(); } } }); } private void setMainUser(final UserInfo info) { loadingDialog.show(); loadingDialog.setDialogLabel("正在切换用户主成员"); Map<String, Object> map = new HashMap<String, Object>(); map.put("mid", info.getMid()); HttpServiceUtil.request( ContantsUtil.HOST + HttpContants.URL_SET_MASTER, HttpContants.REQUEST_MOTHOD, map, new HttpServiceUtil.CallBack() { @Override public void callback(String json) { loadingDialog.dismiss(); try { JSONObject object = new JSONObject(json); int status = object.getInt("status"); if (status == HttpContants.REQUEST_SUCCESS) { // mid preference.putLong(Preference.USER_ID, info.getMid()); ContantsUtil.DEFAULT_TEMP_UID = info.getMid() + ""; ContantsUtil.curInfo = info; ContantsUtil.MAIN_UPDATE = false; // 更新到user表中,存在修改,不存在插入 User user = new User(); User temp = ContantsUtil.curUser; // ContantsUtil.curUser中的phone、uid跟切换的成员是一样的,所以直接在里面取 user.setPhone(temp.getPhone()); user.setService_uid(temp.getService_uid()); user.setNick_name(info.getNick_name()); user.setService_mid(ContantsUtil.DEFAULT_TEMP_UID); UserService uService = new UserService(); ContantsUtil.curUser = new UserBo(context) .saveUserServer(uService .convertUserTo(user)); // 用户uid和sessionId不变 Config.startUpdate(); // 同步数据,包括更新家庭成员列表 loadingDialog.show(); MyThread myThread = new MyThread(); new Thread(myThread).start(); } else { ToastTool.showToast(status, context); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } public void deleteMember(final int position, final UserInfo info) { Map<String, Object> map = new HashMap<String, Object>(); map.put("mid", info.getMid()); setDialogLabel(getText(R.string.deleting_user).toString()); loading.show(); UserDataAPI.delMember(map, context, new HttpServiceUtil.CallBack() { @Override public void callback(String json) { loading.hide(); try { JSONObject obejct = new JSONObject(json); int status = obejct.getInt("status"); if (status == HttpContants.REQUEST_SUCCESS) { // 从数据库删除 data.remove(position); userInfoBo.deleteUserInfo(info); adapter.notifyDataSetChanged(); ToastTool.showMemberStatus( HttpContants.DEL_USER_SUCCESS, context); } else { ToastTool.showToast(status, context); } } catch (JSONException e) { e.printStackTrace(); } } }); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: setDialogLabel("正在合并用户设置数据"); break; case 2: setDialogLabel("正在合并血糖数据"); break; case 3: setDialogLabel("数据同步完成"); // 启动当前用户闹钟系统 new AlarmBo(context).setNextAlarm( ContantsUtil.DEFAULT_TEMP_UID, ContantsUtil.curUser.getService_uid()); loadingDialog.dismiss(); ContantsUtil.MAIN_UPDATE = false; // 更新成员列表视图 adapter.notifyDataSetChanged(); if (CheckUtil.isNull(ContantsUtil.curInfo.getSex()) || ContantsUtil.curInfo.getSex() == -1) { alert.show(); } break; case 4: setDialogLabel("正在同步本地用户设置数据"); break; case 5: setDialogLabel("正在同步本地血糖数据"); break; case 6: setDialogLabel("正在同步本地监测计划数据"); break; case 7: setDialogLabel("正在系统数据"); break; case 8: setDialogLabel("正在饮食数据"); break; case 9: setDialogLabel("正在运动数据"); break; case 10: setDialogLabel("正在用药数据"); break; case 11: setDialogLabel("正在同步本地饮食数据"); break; case 12: setDialogLabel("正在同步本地运动数据"); break; case 13: setDialogLabel("正在同步本地用药数据"); break; case 16: setDialogLabel("同步用户信息成功"); break; case 17: loading.dismiss(); Toast.makeText(context, "同步用户信息失败,请稍后再试", Toast.LENGTH_SHORT) .show(); break; } } }; private void setDialogLabel(String label) { if (loadingDialog == null) { loadingDialog = new DialogLoading(context); } loadingDialog.setDialogLabel(label); } /** * 同步服务端数据 */ public class MyThread implements Runnable { public void run() { IndicateService.initIndicate(getApplicationContext(), ContantsUtil.DEFAULT_TEMP_UID); // 从服务器获取数据更新 Map<String, Object> map = new HashMap<String, Object>(); map.put("mid", ContantsUtil.DEFAULT_TEMP_UID); String result = HttpServiceUtil.post(ContantsUtil.HOST + HttpContants.URL_MEMBER_GETONE, map); if (!CheckUtil.isNull(result)) { boolean state = loadUserInfo(result); if (!state) { handler.sendEmptyMessage(17); return; } else { handler.sendEmptyMessage(16); } } // 如果登陆之前未联网先同步系统参数 if (!ContantsUtil.isSycnSystem) { handler.sendEmptyMessage(7); Map<String, Object> params = new HashMap<String, Object>(); params.put("timestamp", preference.getLong(Preference.SYS_UPDATE_TIME)); result = HttpServiceUtil.post(ContantsUtil.PRED_UPDATE, params); LoadingService.sycnData(preference, context, result); ContantsUtil.isSycnSystem = true; } // 判断是否有未同步数据 UpdateService uService = new UpdateService(context, userBo); if (preference.getBoolean(Preference.HAS_UPDATE)) { handler.sendEmptyMessage(4); uService.updateUserProperty(); handler.sendEmptyMessage(5); uService.updateDiabetes(); handler.sendEmptyMessage(6); uService.updateAlarm(); handler.sendEmptyMessage(11); uService.updateEat(); handler.sendEmptyMessage(12); uService.updateSport(); handler.sendEmptyMessage(13); uService.updateMedicine(); handler.sendEmptyMessage(15); uService.updateIndicates(); preference.putBoolean(Preference.HAS_UPDATE, false); Config.stopUpdate(); } // load用户自定义设置 LoadingService service = new LoadingService(context, userBo); handler.sendEmptyMessage(1); service.loadingUserSet(); handler.sendEmptyMessage(2); service.loadingDbtData(); handler.sendEmptyMessage(3); service.loadingEatData(); handler.sendEmptyMessage(8); service.loadingSportData(); handler.sendEmptyMessage(9); service.loadingMedicineData(); handler.sendEmptyMessage(10); service.loadingIndicateData(); handler.sendEmptyMessage(14); // 刷新配置 Config.loadUserSet(context); } } private boolean loadUserInfo(String json) { JSONObject data; try { data = new JSONObject(json); int status = data.getInt("status"); if (CheckUtil.checkStatusOk(status)) { UserInfo userInfo = new UserInfo(); UserInfo.transformToUserInfo(userInfo, data.getString("data")); // 数据库里面有没有当前用户,没有就保存在数据库,有就更新信息 UserInfo temp = userInfoBo.getUinfoByMid(userInfo.getMid()); if (temp == null) { userInfoBo.saveUserInfo(userInfo); } else { userInfo.setId(temp.getId()); userInfo.setUid(temp.getUid()); userInfoBo.updateUserInfo(userInfo); } ContantsUtil.curInfo = userInfo; return true; } else { return false; } } catch (JSONException e) { e.printStackTrace(); } return false; } public Map<String, String> getMaps() { return maps; } }
package com.example.myokhttp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.IOException; import java.io.StringReader; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private Button btn_okhttp,btn_pull,btn_sax,btn_josnobject,btn_gson; private TextView tv_okhttp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_okhttp = findViewById(R.id.btn_okhttp); btn_pull = findViewById(R.id.btn_pull); btn_sax = findViewById(R.id.btn_sax); tv_okhttp = findViewById(R.id.tv_okhttp); btn_josnobject = findViewById(R.id.btn_josnobject); btn_gson = findViewById(R.id.btn_gson); String resdata ="<apps>\n" + " <app>\n" + " <id>1<id>\n" + " <name>map1<name>\n" + " <version>1.0<version>\n" + " </app>\n" + " <app>\n" + " <id>2<id>\n" + " <name>map2<name>\n" + " <version>2.0<version>\n" + " </app>\n" + " <app>\n" + " <id>3<id>\n" + " <name>map3<name>\n" + " <version>3.0<version>\n" + " </app>\n" + "</apps>"; btn_gson.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { Gson gson = new Gson(); List<App> list = gson.fromJson(resdata,new TypeToken<List<App>>(){}.getType()); for (App app : list) { String id = app.getId(); String name = app.getName(); String version = app.getVersion(); Log.d("gson", "从这开始" + id + name + version); } } }).start(); } }); btn_josnobject.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { //1.request.uri("...json") try { JSONArray jsonArray = new JSONArray(resdata); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String id = jsonObject.getString("id"); String name = jsonObject.getString("name"); String version = jsonObject.getString("version"); Log.d("json", "从这开始" + id + name + version); } } catch (JSONException e) { e.printStackTrace(); } } }).start(); } }); btn_sax.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { SAXParserFactory factory = SAXParserFactory.newInstance(); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); MyContentHandler handler = new MyContentHandler(); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(new StringReader(resdata))); } catch (Exception e) { e.printStackTrace(); } } }).start(); } }); btn_pull.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(new StringReader(resdata)); int enventype = parser.getEventType(); String id = ""; String name = ""; String version = ""; while (enventype != XmlPullParser.END_DOCUMENT){ String nodename = parser.getName(); switch (enventype){ case XmlPullParser.START_TAG: if("id".equals(nodename)){ id = parser.nextText(); }else if("name".equals(nodename)){ name = parser.nextText(); }else if("verison".equals(nodename)){ version = parser.nextText(); } break; case XmlPullParser.END_TAG: if("app".equals(nodename)){ Log.d("TAG", "从这开始" + id + name + version); } break; } enventype = parser.next(); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } }); btn_okhttp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { OkHttpClient okHttpClient = new OkHttpClient(); RequestBody body = new FormBody.Builder() .add("name","admin") .add("password","111") .build(); Request request = new Request.Builder() .url("http://www.baidu.com") .post(body) .build(); Response response = okHttpClient.newCall(request).execute(); String data = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { tv_okhttp.setText(data); } }); } catch (IOException e) { e.printStackTrace(); } } }).start(); } }); } }
package com.cbsystematics.edu.eshop.entities; import lombok.*; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Data @EqualsAndHashCode(callSuper = true) @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "roles") public class Role extends AbstractEntity { @Column(unique = true, nullable = false) private String name; }
/** * 53. Maximum Subarray * Created by mengwei on 2019/9/3. */ public class MaximumSubarray { /** * 第一种方法 * 动态规划的是首先对数组进行遍历,当前最大连续子序列和为 sum,结果为 ans * 如果 sum > 0,则说明 sum 对结果有增益效果,则 sum 保留并加上当前遍历数字 * 如果 sum <= 0,则说明 sum 对结果无增益效果,需要舍弃,则 sum 直接更新为当前遍历数字 * 每次比较 sum 和 ans的大小,将最大值置为ans,遍历结束返回结果 * 参考:https://leetcode-cn.com/problems/two-sum/solution/hua-jie-suan-fa-53-zui-da-zi-xu-he-by-guanpengchn/ * @param nums * @return */ public int maxSubArray(int[] nums) { int ans = nums[0]; int sum = 0; for(int num: nums) { if(sum > 0) { sum += num; } else { sum = num; } ans = Math.max(ans, sum); } return ans; } /** * 第二种方法 分治法 * * 参考https://www.cnblogs.com/grandyang/p/4377150.html * @param nums * @return */ public int maxSubArray2(int[] nums) { if (nums.length == 0) { return 0; } return helper(nums, 0, nums.length - 1); } public int helper(int[] nums, int left, int right) { if (left >= right) { return nums[left]; } int mid = left + (right - left) / 2; int lmax = helper(nums, left, mid - 1); int rmax = helper(nums, mid + 1, right); int mmax = nums[mid], t = mmax; for (int i = mid - 1; i >= left; --i) { t += nums[i]; mmax = Math.max(mmax, t); } t = mmax; for (int i = mid + 1; i <= right; ++i) { t += nums[i]; mmax = Math.max(mmax, t); } return Math.max(mmax, Math.max(lmax, rmax)); } public static void main(String[] args) { int[] nums = new int[]{-2,1,-3,4,-1,2,1,-5,4}; int i = new MaximumSubarray().maxSubArray2(nums); System.out.println("args = [" + i + "]"); } }
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Created by nsp on 2015/10/25. */ public class TestMemento extends JFrame{ public static void main(String[] args) { new TestMemento(); } private JButton saveBtn, undoBtn, redoBtn; private JTextArea theArticle = new JTextArea(40, 60); CareTaker careTaker = new CareTaker(); Originator originator = new Originator(); int savedFiles = 0, currentArticle = 0; public TestMemento() { this.setSize(750,780); this.setTitle("Memento Design Pattern"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel1 = new JPanel(); panel1.add(new JLabel("Article")); panel1.add(this.theArticle); ButtonListener saveListener = new ButtonListener(); ButtonListener undoListener = new ButtonListener(); ButtonListener redoListener = new ButtonListener(); this.saveBtn = new JButton("Save"); this.saveBtn.addActionListener(saveListener); this.undoBtn = new JButton("Undo"); this.undoBtn.addActionListener(undoListener); this.redoBtn = new JButton("Redo"); this.redoBtn.addActionListener(redoListener); panel1.add(saveBtn); panel1.add(undoBtn); panel1.add(redoBtn); this.add(panel1); this.setVisible(true); } class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == saveBtn) { String textInTextArea = theArticle.getText(); originator.set(textInTextArea); careTaker.addMemento(originator.storeInMemento()); savedFiles++; currentArticle++; System.out.println("Save files " + savedFiles); undoBtn.setEnabled(true); } else if (e.getSource() == undoBtn) { if (currentArticle >= 1) { currentArticle--; String textBoxString = originator.storeFromMemento(careTaker.getMemento(currentArticle)); theArticle.setText(textBoxString); redoBtn.setEnabled(true); } else { undoBtn.setEnabled(false); } } else if (e.getSource() == redoBtn) { if (savedFiles > currentArticle + 1) { currentArticle++; String textBoxString = originator.storeFromMemento(careTaker.getMemento(currentArticle)); theArticle.setText(textBoxString); undoBtn.setEnabled(true); if (currentArticle >= savedFiles) { redoBtn.setEnabled(false); } } else { redoBtn.setEnabled(false); } } } } }
package heylichen.alg.graph.tasks; public interface CC { boolean connected(int v, int w); int getComponentsCount(); int getComponentId(int v); }
package model; import java.util.LinkedList; import java.util.List; public class Pair { public int Lid ; //存储L中id位的pair信息 List<LatticeNode> pair = new LinkedList<>(); public int getLid() { return Lid; } public void setLid(int lid) { Lid = lid; } public List<LatticeNode> getPair() { return pair; } public void setPair(List<LatticeNode> pair) { this.pair = pair; } public void removePair(Pair pair){ for(int i = 0 ; i< this.getPair().size();i++){ for(LatticeNode p :pair.getPair()) if(this.getPair().get(i).getId()==p.getId()) this.getPair().remove(i); } } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.util; import java.math.BigDecimal; import java.math.BigInteger; import java.text.NumberFormat; import java.util.Locale; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Harrop * @author Juergen Hoeller */ class NumberUtilsTests { @Test void parseNumber() { String aByte = "" + Byte.MAX_VALUE; String aShort = "" + Short.MAX_VALUE; String anInteger = "" + Integer.MAX_VALUE; String aLong = "" + Long.MAX_VALUE; String aFloat = "" + Float.MAX_VALUE; String aDouble = "" + Double.MAX_VALUE; assertThat(NumberUtils.parseNumber(aByte, Byte.class)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aShort, Short.class)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE)); assertThat(NumberUtils.parseNumber(anInteger, Integer.class)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aLong, Long.class)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aFloat, Float.class)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aDouble, Double.class)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test void parseNumberUsingNumberFormat() { NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); String aByte = "" + Byte.MAX_VALUE; String aShort = "" + Short.MAX_VALUE; String anInteger = "" + Integer.MAX_VALUE; String aLong = "" + Long.MAX_VALUE; String aFloat = "" + Float.MAX_VALUE; String aDouble = "" + Double.MAX_VALUE; assertThat(NumberUtils.parseNumber(aByte, Byte.class, nf)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aShort, Short.class, nf)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE)); assertThat(NumberUtils.parseNumber(anInteger, Integer.class, nf)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aFloat, Float.class, nf)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test void parseNumberRequiringTrim() { String aByte = " " + Byte.MAX_VALUE + " "; String aShort = " " + Short.MAX_VALUE + " "; String anInteger = " " + Integer.MAX_VALUE + " "; String aLong = " " + Long.MAX_VALUE + " "; String aFloat = " " + Float.MAX_VALUE + " "; String aDouble = " " + Double.MAX_VALUE + " "; assertThat(NumberUtils.parseNumber(aByte, Byte.class)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aShort, Short.class)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE)); assertThat(NumberUtils.parseNumber(anInteger, Integer.class)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aLong, Long.class)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aFloat, Float.class)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aDouble, Double.class)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test void parseNumberRequiringTrimUsingNumberFormat() { NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); String aByte = " " + Byte.MAX_VALUE + " "; String aShort = " " + Short.MAX_VALUE + " "; String anInteger = " " + Integer.MAX_VALUE + " "; String aLong = " " + Long.MAX_VALUE + " "; String aFloat = " " + Float.MAX_VALUE + " "; String aDouble = " " + Double.MAX_VALUE + " "; assertThat(NumberUtils.parseNumber(aByte, Byte.class, nf)).as("Byte did not parse").isEqualTo(Byte.valueOf(Byte.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aShort, Short.class, nf)).as("Short did not parse").isEqualTo(Short.valueOf(Short.MAX_VALUE)); assertThat(NumberUtils.parseNumber(anInteger, Integer.class, nf)).as("Integer did not parse").isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).as("Long did not parse").isEqualTo(Long.valueOf(Long.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aFloat, Float.class, nf)).as("Float did not parse").isEqualTo(Float.valueOf(Float.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).as("Double did not parse").isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test void parseNumberAsHex() { String aByte = "0x" + Integer.toHexString(Byte.valueOf(Byte.MAX_VALUE)); String aShort = "0x" + Integer.toHexString(Short.valueOf(Short.MAX_VALUE)); String anInteger = "0x" + Integer.toHexString(Integer.MAX_VALUE); String aLong = "0x" + Long.toHexString(Long.MAX_VALUE); String aReallyBigInt = "FEBD4E677898DFEBFFEE44"; assertByteEquals(aByte); assertShortEquals(aShort); assertIntegerEquals(anInteger); assertLongEquals(aLong); assertThat(NumberUtils.parseNumber("0x" + aReallyBigInt, BigInteger.class)).as("BigInteger did not parse").isEqualTo(new BigInteger(aReallyBigInt, 16)); } @Test void parseNumberAsNegativeHex() { String aByte = "-0x80"; String aShort = "-0x8000"; String anInteger = "-0x80000000"; String aLong = "-0x8000000000000000"; String aReallyBigInt = "FEBD4E677898DFEBFFEE44"; assertNegativeByteEquals(aByte); assertNegativeShortEquals(aShort); assertNegativeIntegerEquals(anInteger); assertNegativeLongEquals(aLong); assertThat(NumberUtils.parseNumber("-0x" + aReallyBigInt, BigInteger.class)).as("BigInteger did not parse").isEqualTo(new BigInteger(aReallyBigInt, 16).negate()); } @Test void convertDoubleToBigInteger() { Double decimal = 3.14d; assertThat(NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)).isEqualTo(new BigInteger("3")); } @Test void convertBigDecimalToBigInteger() { String number = "987459837583750387355346"; BigDecimal decimal = new BigDecimal(number); assertThat(NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)).isEqualTo(new BigInteger(number)); } @Test void convertNonExactBigDecimalToBigInteger() { BigDecimal decimal = new BigDecimal("987459837583750387355346.14"); assertThat(NumberUtils.convertNumberToTargetClass(decimal, BigInteger.class)).isEqualTo(new BigInteger("987459837583750387355346")); } @Test void parseBigDecimalNumber1() { String bigDecimalAsString = "0.10"; Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class); assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test void parseBigDecimalNumber2() { String bigDecimalAsString = "0.001"; Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class); assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test void parseBigDecimalNumber3() { String bigDecimalAsString = "3.14159265358979323846"; Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class); assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test void parseLocalizedBigDecimalNumber1() { String bigDecimalAsString = "0.10"; NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH); Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat); assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test void parseLocalizedBigDecimalNumber2() { String bigDecimalAsString = "0.001"; NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH); Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat); assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test void parseLocalizedBigDecimalNumber3() { String bigDecimalAsString = "3.14159265358979323846"; NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH); Number bigDecimal = NumberUtils.parseNumber(bigDecimalAsString, BigDecimal.class, numberFormat); assertThat(bigDecimal).isEqualTo(new BigDecimal(bigDecimalAsString)); } @Test void parseOverflow() { String aLong = "" + Long.MAX_VALUE; String aDouble = "" + Double.MAX_VALUE; assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Byte.class)); assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Short.class)); assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Integer.class)); assertThat(NumberUtils.parseNumber(aLong, Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aDouble, Double.class)).isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test void parseNegativeOverflow() { String aLong = "" + Long.MIN_VALUE; String aDouble = "" + Double.MIN_VALUE; assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Byte.class)); assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Short.class)); assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Integer.class)); assertThat(NumberUtils.parseNumber(aLong, Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); assertThat(NumberUtils.parseNumber(aDouble, Double.class)).isEqualTo(Double.valueOf(Double.MIN_VALUE)); } @Test void parseOverflowUsingNumberFormat() { NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); String aLong = "" + Long.MAX_VALUE; String aDouble = "" + Double.MAX_VALUE; assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Byte.class, nf)); assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Short.class, nf)); assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Integer.class, nf)); assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).isEqualTo(Double.valueOf(Double.MAX_VALUE)); } @Test void parseNegativeOverflowUsingNumberFormat() { NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); String aLong = "" + Long.MIN_VALUE; String aDouble = "" + Double.MIN_VALUE; assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Byte.class, nf)); assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Short.class, nf)); assertThatIllegalArgumentException().isThrownBy(() -> NumberUtils.parseNumber(aLong, Integer.class, nf)); assertThat(NumberUtils.parseNumber(aLong, Long.class, nf)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); assertThat(NumberUtils.parseNumber(aDouble, Double.class, nf)).isEqualTo(Double.valueOf(Double.MIN_VALUE)); } @Test void convertToInteger() { assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(-1), Integer.class)).isEqualTo(Integer.valueOf(-1)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(0), Integer.class)).isEqualTo(Integer.valueOf(0)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(1), Integer.class)).isEqualTo(Integer.valueOf(1)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MAX_VALUE + 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MIN_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Integer.MIN_VALUE - 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((long) -1, Integer.class)).isEqualTo(Integer.valueOf(-1)); assertThat(NumberUtils.convertNumberToTargetClass(0L, Integer.class)).isEqualTo(Integer.valueOf(0)); assertThat(NumberUtils.convertNumberToTargetClass(1L, Integer.class)).isEqualTo(Integer.valueOf(1)); assertThat(NumberUtils.convertNumberToTargetClass(Long.valueOf(Integer.MAX_VALUE), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((long) (Integer.MAX_VALUE + 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((long) Integer.MIN_VALUE, Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((long) (Integer.MIN_VALUE - 1), Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(-1, Integer.class)).isEqualTo(Integer.valueOf(-1)); assertThat(NumberUtils.convertNumberToTargetClass(0, Integer.class)).isEqualTo(Integer.valueOf(0)); assertThat(NumberUtils.convertNumberToTargetClass(1, Integer.class)).isEqualTo(Integer.valueOf(1)); assertThat(NumberUtils.convertNumberToTargetClass(Integer.MAX_VALUE, Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Integer.MAX_VALUE + 1, Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Integer.MIN_VALUE, Integer.class)).isEqualTo(Integer.valueOf(Integer.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Integer.MIN_VALUE - 1, Integer.class)).isEqualTo(Integer.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((short) -1, Integer.class)).isEqualTo(Integer.valueOf(-1)); assertThat(NumberUtils.convertNumberToTargetClass((short) 0, Integer.class)).isEqualTo(Integer.valueOf(0)); assertThat(NumberUtils.convertNumberToTargetClass((short) 1, Integer.class)).isEqualTo(Integer.valueOf(1)); assertThat(NumberUtils.convertNumberToTargetClass(Short.MAX_VALUE, Integer.class)).isEqualTo(Integer.valueOf(Short.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((short) (Short.MAX_VALUE + 1), Integer.class)).isEqualTo(Integer.valueOf(Short.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Short.MIN_VALUE, Integer.class)).isEqualTo(Integer.valueOf(Short.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((short) (Short.MIN_VALUE - 1), Integer.class)).isEqualTo(Integer.valueOf(Short.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((byte) -1, Integer.class)).isEqualTo(Integer.valueOf(-1)); assertThat(NumberUtils.convertNumberToTargetClass((byte) 0, Integer.class)).isEqualTo(Integer.valueOf(0)); assertThat(NumberUtils.convertNumberToTargetClass((byte) 1, Integer.class)).isEqualTo(Integer.valueOf(1)); assertThat(NumberUtils.convertNumberToTargetClass(Byte.MAX_VALUE, Integer.class)).isEqualTo(Integer.valueOf(Byte.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((byte) (Byte.MAX_VALUE + 1), Integer.class)).isEqualTo(Integer.valueOf(Byte.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Byte.MIN_VALUE, Integer.class)).isEqualTo(Integer.valueOf(Byte.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((byte) (Byte.MIN_VALUE - 1), Integer.class)).isEqualTo(Integer.valueOf(Byte.MAX_VALUE)); assertToNumberOverflow(Long.MAX_VALUE + 1, Integer.class); assertToNumberOverflow(Long.MIN_VALUE - 1, Integer.class); assertToNumberOverflow(BigInteger.valueOf(Integer.MAX_VALUE).add(BigInteger.ONE), Integer.class); assertToNumberOverflow(BigInteger.valueOf(Integer.MIN_VALUE).subtract(BigInteger.ONE), Integer.class); assertToNumberOverflow(new BigDecimal("18446744073709551611"), Integer.class); } @Test void convertToLong() { assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(-1), Long.class)).isEqualTo(Long.valueOf(-1)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(0), Long.class)).isEqualTo(Long.valueOf(0)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(1), Long.class)).isEqualTo(Long.valueOf(1)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MAX_VALUE), Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MAX_VALUE + 1), Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MIN_VALUE), Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(BigInteger.valueOf(Long.MIN_VALUE - 1), Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((long) -1, Long.class)).isEqualTo(Long.valueOf(-1)); assertThat(NumberUtils.convertNumberToTargetClass(0L, Long.class)).isEqualTo(Long.valueOf(0)); assertThat(NumberUtils.convertNumberToTargetClass(1L, Long.class)).isEqualTo(Long.valueOf(1)); assertThat(NumberUtils.convertNumberToTargetClass(Long.MAX_VALUE, Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Long.MAX_VALUE + 1, Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Long.MIN_VALUE, Long.class)).isEqualTo(Long.valueOf(Long.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Long.MIN_VALUE - 1, Long.class)).isEqualTo(Long.valueOf(Long.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(-1, Long.class)).isEqualTo(Long.valueOf(-1)); assertThat(NumberUtils.convertNumberToTargetClass(0, Long.class)).isEqualTo(Long.valueOf(0)); assertThat(NumberUtils.convertNumberToTargetClass(1, Long.class)).isEqualTo(Long.valueOf(1)); assertThat(NumberUtils.convertNumberToTargetClass(Integer.MAX_VALUE, Long.class)).isEqualTo(Long.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Integer.MAX_VALUE + 1, Long.class)).isEqualTo(Long.valueOf(Integer.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Integer.MIN_VALUE, Long.class)).isEqualTo(Long.valueOf(Integer.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Integer.MIN_VALUE - 1, Long.class)).isEqualTo(Long.valueOf(Integer.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((short) -1, Long.class)).isEqualTo(Long.valueOf(-1)); assertThat(NumberUtils.convertNumberToTargetClass((short) 0, Long.class)).isEqualTo(Long.valueOf(0)); assertThat(NumberUtils.convertNumberToTargetClass((short) 1, Long.class)).isEqualTo(Long.valueOf(1)); assertThat(NumberUtils.convertNumberToTargetClass(Short.MAX_VALUE, Long.class)).isEqualTo(Long.valueOf(Short.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((short) (Short.MAX_VALUE + 1), Long.class)).isEqualTo(Long.valueOf(Short.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Short.MIN_VALUE, Long.class)).isEqualTo(Long.valueOf(Short.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((short) (Short.MIN_VALUE - 1), Long.class)).isEqualTo(Long.valueOf(Short.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((byte) -1, Long.class)).isEqualTo(Long.valueOf(-1)); assertThat(NumberUtils.convertNumberToTargetClass((byte) 0, Long.class)).isEqualTo(Long.valueOf(0)); assertThat(NumberUtils.convertNumberToTargetClass((byte) 1, Long.class)).isEqualTo(Long.valueOf(1)); assertThat(NumberUtils.convertNumberToTargetClass(Byte.MAX_VALUE, Long.class)).isEqualTo(Long.valueOf(Byte.MAX_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((byte) (Byte.MAX_VALUE + 1), Long.class)).isEqualTo(Long.valueOf(Byte.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass(Byte.MIN_VALUE, Long.class)).isEqualTo(Long.valueOf(Byte.MIN_VALUE)); assertThat(NumberUtils.convertNumberToTargetClass((byte) (Byte.MIN_VALUE - 1), Long.class)).isEqualTo(Long.valueOf(Byte.MAX_VALUE)); assertToNumberOverflow(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE), Long.class); assertToNumberOverflow(BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE), Long.class); assertToNumberOverflow(new BigDecimal("18446744073709551611"), Long.class); } private void assertLongEquals(String aLong) { assertThat(NumberUtils.parseNumber(aLong, Long.class)).as("Long did not parse").isEqualTo(Long.MAX_VALUE); } private void assertIntegerEquals(String anInteger) { assertThat(NumberUtils.parseNumber(anInteger, Integer.class)).as("Integer did not parse").isEqualTo(Integer.MAX_VALUE); } private void assertShortEquals(String aShort) { assertThat(NumberUtils.parseNumber(aShort, Short.class)).as("Short did not parse").isEqualTo(Short.MAX_VALUE); } private void assertByteEquals(String aByte) { assertThat(NumberUtils.parseNumber(aByte, Byte.class)).as("Byte did not parse").isEqualTo(Byte.MAX_VALUE); } private void assertNegativeLongEquals(String aLong) { assertThat(NumberUtils.parseNumber(aLong, Long.class)).as("Long did not parse").isEqualTo(Long.MIN_VALUE); } private void assertNegativeIntegerEquals(String anInteger) { assertThat(NumberUtils.parseNumber(anInteger, Integer.class)).as("Integer did not parse").isEqualTo(Integer.MIN_VALUE); } private void assertNegativeShortEquals(String aShort) { assertThat(NumberUtils.parseNumber(aShort, Short.class)).as("Short did not parse").isEqualTo(Short.MIN_VALUE); } private void assertNegativeByteEquals(String aByte) { assertThat(NumberUtils.parseNumber(aByte, Byte.class)).as("Byte did not parse").isEqualTo(Byte.MIN_VALUE); } private void assertToNumberOverflow(Number number, Class<? extends Number> targetClass) { String msg = "overflow: from=" + number + ", toClass=" + targetClass; assertThatIllegalArgumentException().as(msg).isThrownBy(() -> NumberUtils.convertNumberToTargetClass(number, targetClass)) .withMessageEndingWith("overflow"); } }
package gov.gtas.parsers.redisson.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @Configuration @EnableScheduling @ComponentScan("gov.gtas.parsers.redisson") @PropertySource("classpath:commonservices.properties") @PropertySource(value = "file:${catalina.home}/conf/application.properties", ignoreResourceNotFound = true) public class RedisLoaderConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { scheduledTaskRegistrar.setScheduler(taskExecutor()); } @Bean(destroyMethod = "shutdown") public Executor taskExecutor() { return Executors.newScheduledThreadPool(30); } }
/* * Copyright (C) 2018 The Android Open Source Project * * 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. */ import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.invoke.VarHandle; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { private static final int ITERATIONS = 100; private static final VarHandle widgetIdVarHandle; public static native int getHotnessCounter(Class<?> cls, String methodName); public static class Widget { public Widget(int id) { this.id = id; } int getId() { return id; } int id; } static { try { widgetIdVarHandle = MethodHandles.lookup().findVarHandle(Widget.class, "id", int.class); } catch (Exception e) { throw new Error(e); } } private static void assertEquals(int i1, int i2) { if (i1 == i2) { return; } throw new AssertionError("assertEquals i1: " + i1 + ", i2: " + i2); } private static void assertEquals(Object o, Object p) { if (o == p) { return; } if (o != null && p != null && o.equals(p)) { return; } throw new AssertionError("assertEquals: o1: " + o + ", o2: " + p); } private static void fail() { System.out.println("fail"); Thread.dumpStack(); } private static void fail(String message) { System.out.println("fail: " + message); Thread.dumpStack(); } private static void testMethodHandleCounters() throws Throwable { for (int i = 0; i < ITERATIONS; ++i) { // Regular MethodHandle invocations MethodHandle mh = MethodHandles.lookup() .findConstructor( Widget.class, MethodType.methodType(void.class, int.class)); Widget w = (Widget) mh.invoke(3); w = (Widget) mh.invokeExact(3); assertEquals(0, getHotnessCounter(MethodHandle.class, "invoke")); assertEquals(0, getHotnessCounter(MethodHandle.class, "invokeExact")); // Reflective MethodHandle invocations String[] methodNames = {"invoke", "invokeExact"}; for (String methodName : methodNames) { Method invokeMethod = MethodHandle.class.getMethod(methodName, Object[].class); MethodHandle instance = MethodHandles.lookup() .findVirtual( Widget.class, "getId", MethodType.methodType(int.class)); try { invokeMethod.invoke(instance, new Object[] {new Object[] {}}); fail(); } catch (InvocationTargetException ite) { assertEquals(ite.getCause().getClass(), UnsupportedOperationException.class); } } assertEquals(0, getHotnessCounter(MethodHandle.class, "invoke")); assertEquals(0, getHotnessCounter(MethodHandle.class, "invokeExact")); } System.out.println("MethodHandle OK"); } private static void testVarHandleCounters() throws Throwable { Widget w = new Widget(0); for (int i = 0; i < ITERATIONS; ++i) { // Regular accessor invocations widgetIdVarHandle.set(w, i); assertEquals(i, widgetIdVarHandle.get(w)); assertEquals(0, getHotnessCounter(VarHandle.class, "set")); assertEquals(0, getHotnessCounter(VarHandle.class, "get")); // Reflective accessor invocations for (String accessorName : new String[] {"get", "set"}) { Method setMethod = VarHandle.class.getMethod(accessorName, Object[].class); try { setMethod.invoke(widgetIdVarHandle, new Object[] {new Object[0]}); fail(); } catch (InvocationTargetException ite) { assertEquals(ite.getCause().getClass(), UnsupportedOperationException.class); } } assertEquals(0, getHotnessCounter(VarHandle.class, "set")); assertEquals(0, getHotnessCounter(VarHandle.class, "get")); } System.out.println("VarHandle OK"); } public static void main(String[] args) throws Throwable { System.loadLibrary(args[0]); testMethodHandleCounters(); testVarHandleCounters(); } }
package com.medic.medicapp; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; 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.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; import static com.medic.medicapp.MainActivity.USERS; import static com.medic.medicapp.MainActivity.id; import static com.medic.medicapp.MainActivity.mPatientsReference; import static com.medic.medicapp.MainActivity.mUsersReference; public class AllPatientsListActivity extends AppCompatActivity { //Esta clase se encarga de la visualización de la lista de pacientes del sistema private PatientAdapter mAdapter; RecyclerView mRecyclerView; private ChildEventListener mChildEventListener; private TextView mNoPatientsTextView; private List<Patient> patientList; private static final String LOGTAG = "AllPatientsListActivity"; private final String patients = "patients"; private String patientDni; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_all_patients_list); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_add); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Prior to add the new patient, we check if the patient //is already registered in the system AlertDialog.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder = new AlertDialog.Builder(AllPatientsListActivity.this, R.style.MyDialogTheme); } else { builder = new AlertDialog.Builder(AllPatientsListActivity.this); } LayoutInflater li = LayoutInflater.from(getBaseContext()); final View dialogView = li.inflate(R.layout.pop_up_add_patient_dni, null); final EditText input = (EditText) dialogView.findViewById(R.id.et_dni); builder.setTitle(R.string.add_patient) .setMessage(R.string.add_dni_message) .setView(dialogView) .setPositiveButton(R.string.accept_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { patientDni = input.getText().toString(); if(dniValid(patientDni)){ mPatientsReference.child(patientDni).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ //The patient exists Toast.makeText(getBaseContext(),"El paciente ya está registrado en el sistema", Toast.LENGTH_LONG).show(); }else{ //The patient needs to be added to the registry Intent addPatientIntent = new Intent(getBaseContext(), AddPatientActivity.class); addPatientIntent.putExtra(Intent.EXTRA_TEXT, patientDni); startActivity(addPatientIntent); } } @Override public void onCancelled(DatabaseError databaseError) { } }); }else{ Toast.makeText(getBaseContext(),"El dni introducido no es válido", Toast.LENGTH_LONG).show(); } } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }) .setIcon(R.mipmap.heartbeat) .show(); } }); mNoPatientsTextView = (TextView) findViewById(R.id.tv_no_patients); mRecyclerView = (RecyclerView) this.findViewById(R.id.recyclerViewPatients); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); patientList = new ArrayList<>(); mAdapter = new PatientAdapter(this, patientList); mRecyclerView.setAdapter(mAdapter); mChildEventListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { getList(dataSnapshot); } public void onChildChanged(DataSnapshot dataSnapshot, String s) { updateList(dataSnapshot); } public void onChildRemoved(DataSnapshot dataSnapshot) { } public void onChildMoved(DataSnapshot dataSnapshot, String s) { } public void onCancelled(DatabaseError databaseError) { } }; mPatientsReference.addChildEventListener(mChildEventListener); } private void updateList(DataSnapshot dataSnapshot) { mNoPatientsTextView.setVisibility(View.GONE); mPatientsReference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Log.e(LOGTAG, "updateList: onDataChange: dataSnapshot" + dataSnapshot); patientList = new ArrayList<>(); for(DataSnapshot snapshot : dataSnapshot.getChildren()) { Patient patient = snapshot.getValue(Patient.class); patientList.add(patient); } mAdapter = new PatientAdapter(getBaseContext(), patientList); mRecyclerView.setAdapter(mAdapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void getList(DataSnapshot dataSnapshot) { mNoPatientsTextView.setVisibility(View.GONE); Patient patient = dataSnapshot.getValue(Patient.class); patientList.add(patient); mAdapter = new PatientAdapter(this, patientList); mRecyclerView.setAdapter(mAdapter); } private boolean dniValid(String patientDni) { if(patientDni.length() == 9){ for(int i = 0; i<patientDni.length()-1; i++){ //Si los 8 primeros caracteres no son números devuelve false if(!Character.isDigit(patientDni.charAt(i))){ return false; } } if(!Character.isLetter(patientDni.charAt(patientDni.length()-1))){ //Si el último caracter no es una letra devuelve false (dni no válido) return false; }else{ return true; } } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { /* Use AppCompatActivity's method getMenuInflater to get a handle on the menu inflater */ MenuInflater inflater = getMenuInflater(); /* Use the inflater's inflate method to inflate our menu layout to this menu */ inflater.inflate(R.menu.menu_user_my_account, menu); /* Return true so that the menu is displayed in the Toolbar */ return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int userID = id; int id = item.getItemId(); switch (id){ case R.id.action_my_account: Intent intent = new Intent(this, UserAccountActivity.class); startActivity(intent); return true; case R.id.action_logout: Toast.makeText(getBaseContext(),"Cerrando sesión:" , Toast.LENGTH_SHORT).show(); FirebaseAuth.getInstance().signOut(); startActivity(new Intent(getBaseContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP )); return true; } return super.onOptionsItemSelected(item); } //Este método se llama si esta actividad se pausa o se reinicia. @Override protected void onResume() { super.onResume(); } }
package com.apon.taalmaatjes.backend.api.returns.mapper; import com.apon.taalmaatjes.backend.api.returns.VolunteerInstanceReturn; import com.apon.taalmaatjes.backend.database.generated.tables.pojos.VolunteerinstancePojo; public class VolunteerInstanceMapper { private VolunteerInstanceReturn volunteerInstanceReturn; public VolunteerInstanceMapper() { volunteerInstanceReturn = new VolunteerInstanceReturn(); } public VolunteerInstanceMapper(VolunteerInstanceReturn volunteerInstanceReturn) { this.volunteerInstanceReturn = volunteerInstanceReturn; } public VolunteerInstanceReturn getVolunteerInstanceReturn() { return volunteerInstanceReturn; } public VolunteerinstancePojo getPojo(Integer volunteerId, Integer volunteerInstanceId) { VolunteerinstancePojo volunteerinstancePojo = new VolunteerinstancePojo(); volunteerinstancePojo.setVolunteerid(volunteerId); volunteerinstancePojo.setVolunteerinstanceid(volunteerInstanceId); volunteerinstancePojo.setExternalidentifier(volunteerInstanceReturn.getExternalIdentifier()); volunteerinstancePojo.setDatestart(volunteerInstanceReturn.getDateStart()); volunteerinstancePojo.setDateend(volunteerInstanceReturn.getDateEnd()); return volunteerinstancePojo; } public void setVolunteerInstance(VolunteerinstancePojo volunteerinstancePojo) { volunteerInstanceReturn.setExternalIdentifier(volunteerinstancePojo.getExternalidentifier()); volunteerInstanceReturn.setDateStart(volunteerinstancePojo.getDatestart()); volunteerInstanceReturn.setDateEnd(volunteerinstancePojo.getDateend()); } }
package leapmidi; import com.leapmotion.leap.Frame; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Observable; /** * A Control is a CC channel and a Transform. */ public class Control { private Transform transform; private MIDIAddress address; private String name; private int value; private List<ControlObserver> obesrvers; public Control(String name, MIDIAddress address, Transform transform) { if (address == null) address = new MIDIAddress(1, 1); this.address = address; this.transform = transform; this.name = name; this.obesrvers = new ArrayList<ControlObserver>(); } public void setValue(int newValue) { newValue = Math.max(0, Math.min(newValue, MIDIInterface.MIDI_MAXVAL)); if (this.value != newValue) { value = newValue; notifyObservers(); } } public String getName() { return name; } public void setName(String name) { if (!name.equals(this.name)) { this.name = name; notifyObservers(); } } private void notifyObservers() { for (ControlObserver co : this.obesrvers) { co.onControlChange(this); } } public void setAddress(MIDIAddress address) { this.address = address; } public MIDIAddress getMIDIAddress() { return this.address; } public void acceptFrame(Frame frame) { int newValue = transform.getValue(frame); if (newValue != -1) this.setValue(newValue); } public int getValue() { return value; } public void addObserver(ControlObserver controlObserver) { this.obesrvers.add(controlObserver); } }
package com.unicom.patrolDoor.controller; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.unicom.patrolDoor.entity.User; import com.unicom.patrolDoor.entity.Vote; import com.unicom.patrolDoor.entity.VoteLog; import com.unicom.patrolDoor.service.UserService; import com.unicom.patrolDoor.service.VoteLogService; import com.unicom.patrolDoor.service.VoteService; import com.unicom.patrolDoor.utils.Result; import com.unicom.patrolDoor.utils.ResultCode; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.text.SimpleDateFormat; import java.util.*; /** * @Author wrk * @Date 2021/6/15 15:21 */ //@CrossOrigin(origins = "*", maxAge = 300) @RestController @RequestMapping("/vote") public class VoteController { private static final Logger log = LogManager.getLogger(QuestionController.class); @Resource private VoteService voteService; @Resource private VoteLogService voteLogService; @Resource private UserService userService; //添加投票 @RequestMapping(value = "/add", method = RequestMethod.POST) @ResponseBody public Result add(@RequestBody Map<Object, Object> map) { log.info("------------------/vote/add-------------begin---------"); Result result = new Result(); Vote vote = new Vote(); if (map.get("theme") != null && !(map.get("theme").equals(""))) { vote.setTheme(map.get("theme").toString()); } else { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("主题不能为空"); return result; } if (map.get("option") != null && !(map.get("option").equals(""))) { List<String> strings = (List<String>) map.get("option"); if (strings.size() == 0) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("选项不能为空"); return result; } StringBuffer buffer = new StringBuffer(); StringBuffer subscript = new StringBuffer(); for (int i = 0; i < strings.size(); i++) { buffer.append(strings.get(i) + ","); subscript.append((i + 1) + ","); } vote.setOpt(buffer.toString().substring(0, buffer.toString().length() - 1)); vote.setSubscript(subscript.toString().substring(0, subscript.toString().length() - 1)); } else { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("选项不能为空"); return result; } if (map.get("userId") != null && !(map.get("userId").equals(""))) { vote.setUserId(Integer.parseInt(map.get("userId").toString())); } else { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("主题不能为空"); return result; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String time = df.format(new Date()); vote.setCreateTime(time); if (map.get("startNow") != null && !(map.get("startNow").equals(""))) { if (Integer.parseInt(map.get("startNow").toString()) == 1) { vote.setBeginTime(time); vote.setVoteStatus(3); } else { vote.setBeginTime(map.get("beginTime").toString()); } } if (map.get("endTime") != null && !(map.get("endTime").equals(""))) { vote.setEndTime(map.get("endTime").toString()); } vote.setCreateTime(time); try { voteService.insert(vote); result.setCode(ResultCode.SUCCESS); result.setMessage("添加成功"); log.info("------------------/vote/add-------------end---------"); } catch (Exception e) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("添加失败"); log.info("------------------/vote/add-------------end---------"); } return result; } //查看投票 @RequestMapping(value = "/select", method = RequestMethod.POST) @ResponseBody public Result select(@RequestBody Map<Object, Object> map) { log.info("------------------/vote/select-------------begin---------"); Result result = new Result(); List<Map<Object, Object>> mapList = new ArrayList<>(); try { Vote vote = voteService.selectById(Integer.parseInt(map.get("id").toString())); if (StringUtils.isNotBlank(vote.getOpt())) { String[] strings = vote.getOpt().split(","); if (strings.length > 0) { for (int i = 0; i < strings.length; i++) { Map optMap = new HashMap(); optMap.put("subscript", (i + 1));//标识 optMap.put("option", strings[i]);//选项 List<VoteLog> list = voteLogService.selectByOptionAndVoteId(Integer.parseInt(map.get("id").toString()), String.valueOf(i + 1)); if (list.size() > 0) { optMap.put("optionNum", list.size());//选项 投票数量 } else { optMap.put("optionNum", 0); } mapList.add(optMap); } } } User user = userService.selectUserById(Integer.parseInt(map.get("userId").toString())); if ((vote.getUserId() == Integer.parseInt(map.get("userId").toString())) || user.getIsNo() == 1) { if (vote.getVoteStatus() == 3) { vote.setEndStop(1); } else { vote.setEndStop(0); } } else { vote.setEndStop(0); } vote.setList(mapList); result.setCode(ResultCode.SUCCESS); result.setMessage("查看成功"); log.info("------------------/vote/select-------------end---------"); result.setData(vote); } catch (Exception e) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("查看失败"); log.info("------------------/vote/select-------------end---------"); } return result; } //查看投票列表 @RequestMapping(value = "/selectList", method = RequestMethod.POST) @ResponseBody public Result selectList(@RequestBody Map<Object, Object> map) { log.info("------------------/vote/selectList-------------begin---------"); Result result = new Result(); //判断是不是有已经过期的投票 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String nowTime = simpleDateFormat.format(new Date()); try { voteService.updateVoteStatuByTime(nowTime); }catch (Exception e){ log.info("------------------/vote/selectList-------------修改投票状态失败---------------"); } List<Map<Object, Object>> mapList = new ArrayList<>(); String theme = ""; String userName = ""; String beginTime = ""; String endTime = ""; Integer pageNo = 1; Integer pageNum = 10; String voteStatus = ""; if (map.get("pageNo") != null && !(map.get("pageNo").equals(""))) { pageNo = Integer.parseInt(map.get("pageNo").toString()); } if (map.get("pageNum") != null && !(map.get("pageNum").equals(""))) { pageNum = Integer.parseInt(map.get("pageNum").toString()); } if (map.get("theme") != null && !(map.get("theme").equals(""))) { theme = map.get("theme").toString(); } if (map.get("userName") != null && !(map.get("userName").equals(""))) { userName = map.get("userName").toString(); } if (map.get("beginTime") != null && !(map.get("beginTime").equals(""))) { beginTime = map.get("beginTime").toString(); } if (map.get("endTime") != null && !(map.get("endTime").equals(""))) { endTime = map.get("endTime").toString(); } if (map.get("voteStatus") != null && !(map.get("voteStatus").equals(""))) { voteStatus = map.get("voteStatus").toString(); } PageHelper.startPage(pageNo, pageNum); try { mapList = voteService.selectList(theme, userName, beginTime, endTime, voteStatus); if (mapList.size() > 0) { for (Map m : mapList) { User user = userService.selectUserById(Integer.parseInt(map.get("userId").toString())); if ((Integer.parseInt(m.get("userId").toString()) == user.getId()) || user.getIsNo() == 1) { //添加一个删除的按钮 前提当前投票的创建人和当前登陆人是同一个 或者是当前登陆人是超级管理员 m.put("delete", 1); } else { m.put("delete", 0); } /** * 获取当前时间 * 当前时间<投票开始时间 将投票状态修改成------未开始 * 当前时间>投票时间的结束时间 将投票状态修改成------已结束 * 投票开始时间<当前时间<投票结束时间 Or 或者是投票开始时间<当前时间并且结束时间是空------进行中 */ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String time = df.format(new Date()); //当前时间<投票开始时间------未开始 if (timeCompare(time, m.get("beginTime").toString()) < 0) { voteService.updateVoteStatusById(2, Integer.parseInt(m.get("id").toString())); } if (m.get("endTime") != null && !(m.get("endTime").equals(""))) { //当前时间>投票时间的结束时间------已结束 if (timeCompare(time, m.get("endTime").toString()) > 0) { voteService.updateVoteStatusById(4, Integer.parseInt(m.get("id").toString())); } //投票开始时间<当前时间<投票结束时间------进行中 if (timeCompare(time, m.get("beginTime").toString()) > 0 && timeCompare(time, m.get("endTime").toString()) < 0) { voteService.updateVoteStatusById(3, Integer.parseInt(m.get("id").toString())); } } else { m.put("endTime", ""); // //结束时间是空并且投票开始时间<当前时间 // if (timeCompare(time, m.get("beginTime").toString()) > 0) { // voteService.updateVoteStatusById(3, Integer.parseInt(m.get("id").toString())); // } } } } PageInfo<Map<Object, Object>> pageInfo = new PageInfo<>(mapList); result.setCode(ResultCode.SUCCESS); result.setMessage("查看成功"); result.setData(pageInfo); log.info("------------------/vote/selectList-------------end---------"); } catch (Exception e) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("查看失败"); log.info("------------------/vote/selectList-------------end---------"); } return result; } //点击立即结束 @RequestMapping(value = "/endNow", method = RequestMethod.POST) @ResponseBody public Result endNow(@RequestBody Map<Object, Object> map) { log.info("------------------/vote/endNow-------------begin---------"); Result result = new Result(); Vote vote = new Vote(); if (map.get("id") == null || map.get("id").equals("")) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("立即结束失败"); log.info("------------------/vote/endNow-------------end---------"); return result; } else { vote.setId(Integer.parseInt(map.get("id").toString())); } vote.setVoteStatus(4); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String time = df.format(new Date()); vote.setEndTime(time); try { voteService.updateVote(vote); result.setCode(ResultCode.SUCCESS); result.setMessage("立即结束成功"); log.info("------------------/vote/endNow-------------end---------"); } catch (Exception e) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("立即结束失败"); log.info("------------------/vote/endNow-------------end---------"); } return result; } //删除投票 @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public Result delete(@RequestBody Map<Object, Object> map) { log.info("------------------/vote/delete-------------begin---------"); Result result = new Result(); try { voteService.updateVoteStatusById(1, Integer.parseInt(map.get("id").toString())); result.setCode(ResultCode.SUCCESS); result.setMessage("删除成功"); log.info("------------------/vote/delete-------------end---------"); } catch (Exception e) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("删除失败"); log.info("------------------/vote/delete-------------end---------"); } return result; } //点击投票按钮 @RequestMapping(value = "/newVoting", method = RequestMethod.POST) @ResponseBody public Result newVoting(@RequestBody Map<Object, Object> map) { log.info("------------------/vote/newVoting-------------begin---------"); Result result = new Result(); VoteLog voteLog = new VoteLog(); if (map.get("voteId") == null || (map.get("voteId").equals(""))) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("投票失败"); log.info("------------------/vote/newVoting-------------end---------"); return result; } else { voteLog.setVoteId(Integer.parseInt(map.get("voteId").toString())); } if (map.get("userId") == null || (map.get("userId").equals(""))) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("投票失败"); log.info("------------------/vote/newVoting-------------end---------"); return result; } else { voteLog.setUserId(Integer.parseInt(map.get("userId").toString())); } if (map.get("option") == null || (map.get("option").equals(""))) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("投票失败"); log.info("------------------/vote/newVoting-------------end---------"); return result; } else { voteLog.setOpt(map.get("option").toString()); } List<VoteLog> list = voteLogService.selectByVoteIdAndUserId(Integer.parseInt(map.get("voteId").toString()), Integer.parseInt(map.get("userId").toString())); if (list.size() > 0) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("投票失败,只能投票一次"); log.info("------------------/vote/newVoting-------------end---------"); return result; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 voteLog.setVoteTime(df.format(new Date())); try { voteLogService.insert(voteLog); result.setCode(ResultCode.SUCCESS); result.setMessage("投票成功"); log.info("------------------/vote/newVoting-------------end---------"); } catch (Exception e) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("投票失败"); log.info("------------------/vote/newVoting-------------end---------"); } return result; } //历史记录 @RequestMapping(value = "/history", method = RequestMethod.POST) @ResponseBody public Result history(@RequestBody Map<Object, Object> map) { log.info("------------------/vote/history-------------begin---------"); Result result = new Result(); List<Map<Object, Object>> mapList = new ArrayList<>(); String theme = ""; String beginTime = ""; String endTime = ""; String voteStatus = ""; Integer pageNo = 1; Integer pageNum = 10; if (map.get("pageNo") != null && !(map.get("pageNo").equals(""))) { pageNo = Integer.parseInt(map.get("pageNo").toString()); } if (map.get("pageNum") != null && !(map.get("pageNum").equals(""))) { pageNum = Integer.parseInt(map.get("pageNum").toString()); } if (map.get("theme") != null && !(map.get("theme").equals(""))) { theme = map.get("theme").toString(); } if (map.get("beginTime") != null && !(map.get("beginTime").equals(""))) { beginTime = map.get("beginTime").toString(); } if (map.get("endTime") != null && !(map.get("endTime").equals(""))) { endTime = map.get("endTime").toString(); } if (map.get("voteStatus") != null && !(map.get("voteStatus").equals(""))) { voteStatus = map.get("voteStatus").toString(); } if (map.get("userId") == null || (map.get("userId").equals(""))) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("查看失败"); log.info("------------------/vote/history-------------end---------"); return result; } PageHelper.startPage(pageNo, pageNum); try { mapList = voteService.selectHistoryList(theme, Integer.parseInt(map.get("userId").toString()), beginTime, endTime, voteStatus); if (mapList.size() > 0) { for (Map m : mapList) { if (Integer.parseInt(m.get("voteStatus").toString()) != 1) {//1:已经删除 User user = userService.selectUserById(Integer.parseInt(map.get("userId").toString())); if ((Integer.parseInt(m.get("userId").toString()) == user.getId()) || user.getIsNo() == 1) { //添加一个删除的按钮 前提当前投票的创建人和当前登陆人是同一个 或者是当前登陆人是超级管理员 m.put("delete", 1); } else { m.put("delete", 0); } /** * 获取当前时间 * 当前时间<投票开始时间 将投票状态修改成------未开始 * 当前时间>投票时间的结束时间 将投票状态修改成------已结束 * 投票开始时间<当前时间<投票结束时间 Or 或者是投票开始时间<当前时间并且结束时间是空------进行中 */ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String time = df.format(new Date()); //当前时间<投票开始时间------未开始 if (timeCompare(time, m.get("beginTime").toString()) < 0) { voteService.updateVoteStatusById(2, Integer.parseInt(m.get("id").toString())); } if (m.get("endTime") != null && !(m.get("endTime").equals(""))) { //当前时间>投票时间的结束时间------已结束 if (timeCompare(time, m.get("endTime").toString()) > 0) { voteService.updateVoteStatusById(4, Integer.parseInt(m.get("id").toString())); } //投票开始时间<当前时间<投票结束时间------进行中 if (timeCompare(time, m.get("beginTime").toString()) > 0 && timeCompare(time, m.get("endTime").toString()) < 0) { voteService.updateVoteStatusById(3, Integer.parseInt(m.get("id").toString())); } } else { m.put("endTime", ""); // //结束时间是空并且投票开始时间<当前时间 // if (timeCompare(time, m.get("beginTime").toString()) > 0) { // voteService.updateVoteStatusById(3, Integer.parseInt(m.get("id").toString())); // } } } } } PageInfo<Map<Object, Object>> pageInfo = new PageInfo<>(mapList); result.setCode(ResultCode.SUCCESS); result.setMessage("查看成功"); result.setData(pageInfo); log.info("------------------/vote/history-------------end---------"); } catch (Exception e) { result.setCode(ResultCode.INTERNAL_SERVER_ERROR); result.setMessage("查看失败"); log.info("------------------/vote/history-------------end---------"); } return result; } //时间比较 public static Integer timeCompare(String timeA, String timeB) { int res = timeA.compareTo(timeB); if (res > 0) { res = 1; } if (res < 0) { res = -1; } if (res == 0) { res = 0; } return res; } }
package com.alibaba.druid.bvt.pool; import java.sql.Connection; import java.sql.PreparedStatement; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.pool.DruidDataSource; public class DruidDataSourceTest1 extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mock:xxx"); dataSource.setTestOnBorrow(false); } protected void tearDown() throws Exception { dataSource.close(); } public void test_oracle() throws Exception { dataSource.setOracle(true); dataSource.init(); Exception error = null; try { dataSource.setOracle(false); } catch (IllegalStateException e) { error = e; } Assert.assertNotNull(error); } public void test_transactionQueryTimeout() throws Exception { dataSource.setTransactionQueryTimeout(123456); Assert.assertEquals(123456, dataSource.getTransactionQueryTimeout()); } public void test_dupCloseLogEnable() throws Exception { Assert.assertFalse(dataSource.isDupCloseLogEnable()); dataSource.setDupCloseLogEnable(true); Assert.assertTrue(dataSource.isDupCloseLogEnable()); } public void test_getClosedPreparedStatementCount() throws Exception { Assert.assertEquals(0, dataSource.getClosedPreparedStatementCount()); Assert.assertEquals(0, dataSource.getPreparedStatementCount()); Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement("select 1"); stmt.close(); Assert.assertEquals(1, dataSource.getPreparedStatementCount()); Assert.assertEquals(1, dataSource.getClosedPreparedStatementCount()); } public void test_getDriverMajorVersion() throws Exception { Assert.assertEquals(-1, dataSource.getDriverMajorVersion()); dataSource.init(); Assert.assertEquals(0, dataSource.getDriverMajorVersion()); } public void test_getDriverMinorVersion() throws Exception { Assert.assertEquals(-1, dataSource.getDriverMinorVersion()); dataSource.init(); Assert.assertEquals(0, dataSource.getDriverMinorVersion()); } public void test_getExceptionSorterClassName() throws Exception { Assert.assertNull(dataSource.getExceptionSorterClassName()); } }
package by.htp.airline10.main; /*10. Создать класс Airline, спецификация которого приведена ниже. Определить конструкторы, set- и get- методы и метод toString(). Создать второй класс, агрегирующий массив типа Airline, с подходящими конструкторами и методами. Задать критерии выбора данных и вывести эти данные на консоль. Airline: пункт назначения, номер рейса, тип самолета, время вылета, дни недели. Найти и вывести: a) список рейсов для заданного пункта назначения; b) список рейсов для заданного дня недели; c) список рейсов для заданного дня недели, время вылета для которых больше заданного. */ public class Airline { private String destination; private int numberFlight; private String typePlane; private int hour; private int min; private String daysOfTheWeek; public Airline(String destination, int numberFlight, String typePlane, int hour, int min, String daysOfTheWeek) { this.destination = destination; this.numberFlight = numberFlight; this.typePlane = typePlane; this.hour = hour; this.min = min; this.daysOfTheWeek = daysOfTheWeek; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public int getNumberFlight() { return numberFlight; } public void setNumberFlight(int numberFlight) { this.numberFlight = numberFlight; } public String getTypePlane() { return typePlane; } public void setTypePlane(String typePlane) { this.typePlane = typePlane; } public int getHour() { return hour; } public void setHour(int hour) { this.hour = hour; } public int getMin() { return min; } public void setMin(int min) { this.min = min; } public String getDaysOfTheWeek() { return daysOfTheWeek; } public void setDaysOfTheWeek(String daysOfTheWeek) { this.daysOfTheWeek = daysOfTheWeek; } @Override public String toString() { return "Airline [ Destination : " + destination + ", Number Flight : " + numberFlight + ", Type Plane : " + typePlane + ", Hour : " + hour + ", Min : " + min + ", Days of the week : " + daysOfTheWeek + " ]"; } }
package com.oup.model; import lombok.Getter; import lombok.Setter; import javax.xml.bind.annotation.XmlElement; @Getter @Setter public class JournalEntryCreateRequest { @XmlElement MessageHeader MessageHeader; @XmlElement JournalEntry JournalEntry; }
package com.digiburo.spring.demo.mvc.domain; import org.springframework.stereotype.Component; import java.util.UUID; @Component public class DemoBean { public String toString() { return(arg3 + ":" + arg2 + ":" + arg1); } public void setArg1(int arg) { arg1 = arg; } public void setArg2(String arg) { arg2 = arg; } private int arg1; private String arg2; private UUID arg3 = UUID.randomUUID(); }
/* * Copyright 2008-2018 shopxx.net. All rights reserved. * Support: localhost * License: localhost/license * FileId: pChw8iHWExlpqgmXacC/4d2MrWKcwxvS */ package net.bdsc.service; import net.bdsc.Page; import net.bdsc.Pageable; import net.bdsc.entity.Member; import net.bdsc.entity.MemberDepositLog; /** * Service - 会员预存款记录 * * @author 好源++ Team * @version 6.1 */ public interface MemberDepositLogService extends BaseService<MemberDepositLog, Long> { /** * 查找会员预存款记录分页 * * @param member * 会员 * @param pageable * 分页信息 * @return 会员预存款记录分页 */ Page<MemberDepositLog> findPage(Member member, Pageable pageable); }
package com.cuisine.restaurant; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; @WebServlet("/restaurant/resdetail") public class ResDetail extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String id = request.getParameter("id"); Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://dev.notepubs.com:9898/cuisine?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC"; Connection connection = DriverManager.getConnection(url, "cuisine", "12345"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select * from restaurantDetail where id = " + id); List<Data> list = new ArrayList<>(); while (resultSet.next()) { Data data = new Data(); data.setId(resultSet.getInt(1)); data.setName(resultSet.getString(2)); data.setAddress(resultSet.getString(3)); data.setPhone(resultSet.getString(4)); data.setOpeningHours(resultSet.getString(5)); data.setBreakingHours(resultSet.getString(6)); data.setHallCleanness(resultSet.getDouble(7)); data.setToiletCleaness(resultSet.getDouble(8)); data.setParkinglot(resultSet.getDouble(9)); data.setAvg(resultSet.getDouble(10)); list.add(data); } response.setCharacterEncoding("UTF-8"); response.setContentType("text/; charset=UTF-8"); //request.getRequestDispatcher("/WEB-INF/view/restaurant/detail.jsp").forward(request, response); // response.sendRedirect("/WEB-INF/view/restaurant/detail.jsp"); response.getWriter().write(new Gson().toJson(list)); } catch (SQLException e) { System.out.println("SQLException: " + e); } catch (ClassNotFoundException e) { System.out.println("ClassNotFoundException: " + e); } } public class Data { int id; String name; String address; String phone; String openingHours; String breakingHours; double hallCleanness; double toiletCleaness; double parkinglot; double avg; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getOpeningHours() { return openingHours; } public void setOpeningHours(String openingHours) { this.openingHours = openingHours; } public String getBreakingHours() { return breakingHours; } public void setBreakingHours(String breakingHours) { this.breakingHours = breakingHours; } public double getHallCleanness() { return hallCleanness; } public void setHallCleanness(double hallCleanness) { this.hallCleanness = hallCleanness; } public double getToiletCleaness() { return toiletCleaness; } public void setToiletCleaness(double toiletCleaness) { this.toiletCleaness = toiletCleaness; } public double getParkinglot() { return parkinglot; } public void setParkinglot(double parkinglot) { this.parkinglot = parkinglot; } public double getAvg() { return avg; } public void setAvg(double avg) { this.avg = avg; } } }
package lambda; class Person{ String name; Person(String name){ this.name = name; } public String getName() { return name; } } public class LambdaDemo { static Person person = new Person("zhangsy"); public static void main (String[] args){ final int a = 0; // 在匿名內部類中需要被使用的變量,一定要是final修飾的 String name = person.getName(); // 或者是要effectively final修飾的 (既定事實的final) // name = name+"1"; 這是錯誤的用法, 因為在下面的匿名內部類或者lambda表達式中使用了這個變量 Thread first = new Thread(new Runnable() { @Override public void run() { System.out.println(a); System.out.println(name); System.out.println("hello world"); } }); Thread second = new Thread(()->{ int x = a; for (int i = 0; i < 10; i++){ x += i; } System.out.println(name); //這就是“閉包”的概念 System.out.println(x); }); first.start(); second.start(); } }
package simpledb; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; public class AggregatorIteratorNoGroup implements DbIterator { private Iterator<Tuple> iter; private boolean isOpen; private TupleDesc tdes; private Set<Tuple> set; private int gbfield; private Type gbfieldtype; public AggregatorIteratorNoGroup(Set<Tuple> set, int gbfield, Type gbfieldtype){ this.set = set; isOpen = false; this.gbfield = gbfield; this.gbfieldtype = gbfieldtype; //create tupledesc Type typeArr[] = new Type[]{gbfieldtype}; String fieldArr[] = new String[]{"GfroupBy"}; tdes = new TupleDesc(typeArr, fieldArr); } public void open() throws DbException, TransactionAbortedException{ iter = set.iterator(); isOpen = true; } public boolean hasNext() throws DbException, TransactionAbortedException{ if(isOpen == false) throw new IllegalStateException(); return iter.hasNext(); } public Tuple next() throws DbException, TransactionAbortedException, NoSuchElementException { if(hasNext() == false) throw new NoSuchElementException(); if(isOpen == false) throw new IllegalStateException(); return iter.next(); } public void rewind() throws DbException, TransactionAbortedException{ if(isOpen == false) throw new IllegalStateException(); open(); } public TupleDesc getTupleDesc(){ //System.out.println("Here???"); return tdes; } public void close(){ isOpen = false; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.support; import java.lang.reflect.Method; import java.security.ProtectionDomain; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.LogFactory; import org.springframework.core.DecoratingClassLoader; import org.springframework.core.OverridingClassLoader; import org.springframework.core.SmartClassLoader; import org.springframework.lang.Nullable; import org.springframework.util.ReflectionUtils; /** * Special variant of an overriding ClassLoader, used for temporary type * matching in {@link AbstractApplicationContext}. Redefines classes from * a cached byte array for every {@code loadClass} call in order to * pick up recently loaded types in the parent ClassLoader. * * @author Juergen Hoeller * @since 2.5 * @see AbstractApplicationContext * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#setTempClassLoader */ class ContextTypeMatchClassLoader extends DecoratingClassLoader implements SmartClassLoader { static { ClassLoader.registerAsParallelCapable(); } @Nullable private static final Method findLoadedClassMethod; static { // Try to enable findLoadedClass optimization which allows us to selectively // override classes that have not been loaded yet. If not accessible, we will // always override requested classes, even when the classes have been loaded // by the parent ClassLoader already and cannot be transformed anymore anyway. Method method = null; try { method = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class); ReflectionUtils.makeAccessible(method); } catch (Throwable ex) { // Typically a JDK 9+ InaccessibleObjectException... // Avoid through JVM startup with --add-opens=java.base/java.lang=ALL-UNNAMED LogFactory.getLog(ContextTypeMatchClassLoader.class).debug( "ClassLoader.findLoadedClass not accessible -> will always override requested class", ex); } findLoadedClassMethod = method; } /** Cache for byte array per class name. */ private final Map<String, byte[]> bytesCache = new ConcurrentHashMap<>(256); public ContextTypeMatchClassLoader(@Nullable ClassLoader parent) { super(parent); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return new ContextOverridingClassLoader(getParent()).loadClass(name); } @Override public boolean isClassReloadable(Class<?> clazz) { return (clazz.getClassLoader() instanceof ContextOverridingClassLoader); } @Override public Class<?> publicDefineClass(String name, byte[] b, @Nullable ProtectionDomain protectionDomain) { return defineClass(name, b, 0, b.length, protectionDomain); } /** * ClassLoader to be created for each loaded class. * Caches class file content but redefines class for each call. */ private class ContextOverridingClassLoader extends OverridingClassLoader { public ContextOverridingClassLoader(ClassLoader parent) { super(parent); } @Override protected boolean isEligibleForOverriding(String className) { if (isExcluded(className) || ContextTypeMatchClassLoader.this.isExcluded(className)) { return false; } if (findLoadedClassMethod != null) { ClassLoader parent = getParent(); while (parent != null) { if (ReflectionUtils.invokeMethod(findLoadedClassMethod, parent, className) != null) { return false; } parent = parent.getParent(); } } return true; } @Override protected Class<?> loadClassForOverriding(String name) throws ClassNotFoundException { byte[] bytes = bytesCache.get(name); if (bytes == null) { bytes = loadBytesForClass(name); if (bytes != null) { bytesCache.put(name, bytes); } else { return null; } } return defineClass(name, bytes, 0, bytes.length); } } }
package com.desarollounder.undermetal; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import java.util.Timer; import java.util.TimerTask; public class ActivityMain extends AppCompatActivity { private static final long SPLASH_SCREEN_DELAY = 3000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); ImageView imgInicio = (ImageView) findViewById(R.id.imgInicio); Animation animation = AnimationUtils.loadAnimation(this,R.anim.fade_in); imgInicio.setAnimation(animation); TimerTask task = new TimerTask() { @Override public void run() { Intent mainIntent = new Intent().setClass(getApplicationContext(),ActivityDrawer.class); startActivity(mainIntent); finish(); } }; Timer timer = new Timer(); timer.schedule(task, SPLASH_SCREEN_DELAY); } }
package factorymethod2; /** * The BankABC_SavingsAccountProduct este concrete product care este * definita prin abestractizare de care BankAccountProduct. The * BankABC_SavingsAccountProduct va fi creata de catre factory method * si instanta clasei va fi returnata de catre factory class * BankAccountProduct prin abstractizare. * * * */ public class BankXYZ_ChequeAccountProduct extends BankAccountProduct { private double accountBalance = 0.00; public BankXYZ_ChequeAccountProduct() { System.out.println("Bank XYZ - Cheque Account : Creating account."); } // no-arg constructor public void depositMoney(double depositAmount) { accountBalance += depositAmount; System.out.println("Bank XYZ - Cheque Account : Deposit money " + depositAmount); } // method depositMoney public void displayBalance() { System.out.println("Bank XYZ - Cheque Account : Acount Balance " + accountBalance); } // method displayBalance public void withdrawMoney(double withdrawAmount) { accountBalance -= withdrawAmount; System.out.println("Bank XYZ - Cheque Account : Withdraw money " + withdrawAmount); } // method withdrawMoney } // class BankXYZ_ChequeAccountProduct
package com.example.isvirin.storeclient.presentation.view.fragment; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RelativeLayout; import com.example.isvirin.storeclient.R; import com.example.isvirin.storeclient.presentation.internal.di.components.BrandComponent; import com.example.isvirin.storeclient.presentation.model.BrandModel; import com.example.isvirin.storeclient.presentation.presenter.BrandsByCategoryPresenter; import com.example.isvirin.storeclient.presentation.view.BrandListView; import com.example.isvirin.storeclient.presentation.view.adapter.BrandsAdapter; import com.example.isvirin.storeclient.presentation.view.adapter.CommonLayoutManager; import java.util.Collection; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class BrandListFragment extends BaseFragment implements BrandListView { public interface BrandListListener { void onBrandClicked(final BrandModel brandModel); } @Inject BrandsByCategoryPresenter brandsByCategoryPresenter; @Inject BrandsAdapter brandsAdapter; @Bind(R.id.rv_brands) RecyclerView rv_brands; @Bind(R.id.rl_progress) RelativeLayout rl_progress; @Bind(R.id.rl_retry) RelativeLayout rl_retry; @Bind(R.id.bt_retry) Button bt_retry; private BrandListFragment.BrandListListener brandListListener; public BrandListFragment() { setRetainInstance(true); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof BrandListFragment.BrandListListener) { this.brandListListener = (BrandListFragment.BrandListListener) activity; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getComponent(BrandComponent.class).inject(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View fragmentView = inflater.inflate(R.layout.fragment_brand_list, container, false); ButterKnife.bind(this, fragmentView); setupRecyclerView(); return fragmentView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); this.brandsByCategoryPresenter.setView(this); if (savedInstanceState == null) { this.loadBrandList(); } } @Override public void onResume() { super.onResume(); this.brandsByCategoryPresenter.resume(); } @Override public void onPause() { super.onPause(); this.brandsByCategoryPresenter.pause(); } @Override public void onDestroyView() { super.onDestroyView(); rv_brands.setAdapter(null); ButterKnife.unbind(this); } @Override public void onDestroy() { super.onDestroy(); this.brandsByCategoryPresenter.destroy(); } @Override public void onDetach() { super.onDetach(); this.brandListListener = null; } @Override public void showLoading() { this.rl_progress.setVisibility(View.VISIBLE); this.getActivity().setProgressBarIndeterminateVisibility(true); } @Override public void hideLoading() { this.rl_progress.setVisibility(View.GONE); this.getActivity().setProgressBarIndeterminateVisibility(false); } @Override public void showRetry() { this.rl_retry.setVisibility(View.VISIBLE); } @Override public void hideRetry() { this.rl_retry.setVisibility(View.GONE); } public void renderBrandList(Collection<BrandModel> brandModelCollection) { if (brandModelCollection != null) { this.brandsAdapter.setBrandsCollection(brandModelCollection); } } public void viewBrand(BrandModel brandModel) { if (this.brandListListener != null) { this.brandListListener.onBrandClicked(brandModel); } } @Override public void showError(String message) { this.showToastMessage(message); } @Override public Context context() { return this.getActivity().getApplicationContext(); } private void setupRecyclerView() { this.brandsAdapter.setOnItemClickListener(onItemClickListener); this.rv_brands.setLayoutManager(new CommonLayoutManager(context())); this.rv_brands.setAdapter(brandsAdapter); } private void loadBrandList() { this.brandsByCategoryPresenter.initialize(); } @OnClick(R.id.bt_retry) void onButtonRetryClick() { BrandListFragment.this.loadBrandList(); } private BrandsAdapter.OnItemClickListener onItemClickListener = new BrandsAdapter.OnItemClickListener() { public void onBrandItemClicked(BrandModel brandModel) { if (BrandListFragment.this.brandsByCategoryPresenter != null && brandModel != null) { BrandListFragment.this.brandsByCategoryPresenter.onBrandClicked(brandModel); } } }; }
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.user.endpoint.impl; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.wso2.carbon.identity.user.endpoint.dto.UsernameUpdateRequestDTO; import org.wso2.carbon.identity.user.endpoint.util.Utils; import org.wso2.carbon.identity.user.rename.core.dto.StatusDTO; import org.wso2.carbon.identity.user.rename.core.dto.UserDTO; import org.wso2.carbon.identity.user.rename.core.exception.UsernameUpdateClientException; import org.wso2.carbon.identity.user.rename.core.exception.UsernameUpdateException; import org.wso2.carbon.identity.user.rename.core.internal.service.impl.UsernameUpdateServiceImpl; import static org.mockito.ArgumentMatchers.any; /** * Test class that include unit test cases for UpdateUsernameApiServiceImpl */ public class UpdateUsernameApiServiceImplTest { private static final String ERROR_MSG = "error"; private static final String ERROR_CODE = "10001"; private MockedStatic<Utils> mockedUtils; @Mock private UsernameUpdateServiceImpl usernameUpdateService; @Mock private StatusDTO statusDTO; @Mock private UsernameUpdateRequestDTO usernameUpdateRequestDTO; @InjectMocks private UpdateUsernameApiServiceImpl usernameApiService; @BeforeMethod public void setUp() { MockitoAnnotations.openMocks(this); mockedUtils = Mockito.mockStatic(Utils.class); } @AfterMethod public void tearDown() { mockedUtils.close(); } @Test public void testSuccessStatusOfUpdateUsername() throws Exception { mockedUtils.when(Utils::getUsernameUpdateService).thenReturn(usernameUpdateService); Mockito.when(usernameUpdateService.updateUsername(any(UserDTO.class))).thenReturn(statusDTO); Assert.assertEquals(usernameApiService.updateUsernamePut(usernameUpdateRequestDTO).getStatus(), 200); } @Test public void testBadRequestStatusOfUpdateUsername() throws Exception { mockedUtils.when(Utils::getUsernameUpdateService).thenReturn(usernameUpdateService); Mockito.when(usernameUpdateService.updateUsername(any(UserDTO.class))).thenThrow( new UsernameUpdateClientException (ERROR_MSG, ERROR_CODE, UsernameUpdateClientException.ErrorType.BAD_REQUEST)); // The test method executes the lines but does not throw the 400 code. Assert.assertEquals(usernameApiService.updateUsernamePut(usernameUpdateRequestDTO).getStatus(), 200); } @Test public void testNotAcceptableStatusOfUpdateUsername() throws Exception { mockedUtils.when(Utils::getUsernameUpdateService).thenReturn(usernameUpdateService); Mockito.when(usernameUpdateService.updateUsername(any(UserDTO.class))).thenThrow( new UsernameUpdateClientException (ERROR_MSG, ERROR_CODE, UsernameUpdateClientException.ErrorType.NOT_ACCEPTABLE)); // The test method executes the lines but does not throw the 406 code. Assert.assertEquals(usernameApiService.updateUsernamePut(usernameUpdateRequestDTO).getStatus(), 200); } @Test public void testNotFoundStatusOfUpdateUsername() throws Exception { mockedUtils.when(Utils::getUsernameUpdateService).thenReturn(usernameUpdateService); Mockito.when(usernameUpdateService.updateUsername(any(UserDTO.class))).thenThrow( new UsernameUpdateClientException (ERROR_MSG, ERROR_CODE, UsernameUpdateClientException.ErrorType.NOT_FOUND)); // The test method executes the lines but does not throw the 404 code. Assert.assertEquals(usernameApiService.updateUsernamePut(usernameUpdateRequestDTO).getStatus(), 200); } @Test public void testServerErrorStatusOfUpdateUsername() throws Exception { mockedUtils.when(Utils::getUsernameUpdateService).thenReturn(usernameUpdateService); Mockito.when(usernameUpdateService.updateUsername(any(UserDTO.class))).thenThrow(new UsernameUpdateException (ERROR_MSG, ERROR_CODE)); // The test method executes the lines but does not throw the 500 code. Assert.assertEquals(usernameApiService.updateUsernamePut(usernameUpdateRequestDTO).getStatus(), 200); } @Test public void testUnexpectedServerErrorStatusOfUpdateUsername() throws Exception { mockedUtils.when(Utils::getUsernameUpdateService).thenReturn(usernameUpdateService); Mockito.when(usernameUpdateService.updateUsername(any(UserDTO.class))).thenThrow( new RuntimeException(ERROR_MSG)); // The test method executes the lines but does not throw the 500 code. Assert.assertEquals(usernameApiService.updateUsernamePut(usernameUpdateRequestDTO).getStatus(), 200); } }
package com.lti.inheritance; class Parent{ private int xfac=100; void google(){ System.out.println("Google.com"); } public int getXfac(){ return xfac; } } class Child extends Parent{ void yahoo(){ System.out.println("Yahoo.com"); } void google(){ System.out.println("Google.com extended in child");//This is overridden method //Overloading is changing the signature. Overriding is not changing the signature but keeping it same in //Subclass } } public class InheritanceDemo { public static void main(String args[]){ Child c=new Child(); System.out.println(c.getXfac());//WE are able to access this because, although the variable is private, //The getter method is a public one. This also shows the concept of encapsulation c.google(); c.yahoo();//The child class inherits all that is there } } class DemoforObjectClass{ public static void main(String args[]){ int num1=100; int num2=100; if(num1==num2){ System.out.println("matching");//We will get the same for if int or string or new String(){This is a class}; } else{ System.out.println("Not matching"); } int n=100; String s=new Integer(n).toString(); //First we have made into an Integer object, which is called wrapper and then we convert to a string object } }
/* * 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.xag.xtra.trial; import javax.inject.Named; /** * * @author agunga */ @Named("myAnotherEvent") public class AnotherEvent implements EventResource { @Override public String takeAction() { return "At takeAction()"; } }
package com.yamblz.uioptimizationsample; import android.app.Application; /** * Created by i-sergeev on 01.07.16 */ public class SampleApplication extends Application { }
package org.giveback.problems.readcsvsaveremote; public final class CsvContent { private final String content; private final String path; public CsvContent(String content, String path) { this.content = content; this.path = path; } public String getContent() { return content; } public String getPath() { return path; } }
package cn.v5cn.v5cms.controller; import cn.v5cn.v5cms.entity.Site; import cn.v5cn.v5cms.service.SiteService; import cn.v5cn.v5cms.util.PropertyUtils; import cn.v5cn.v5cms.util.SystemUtils; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.coobird.thumbnailator.Thumbnails; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.List; import java.util.Map; import static cn.v5cn.v5cms.util.MessageSourceHelper.getMessage; /** * Created by ZYW on 2014/8/13. */ @Controller @RequestMapping("/manager/tpl") public class TemplateController { private static final Logger LOGGER = LoggerFactory.getLogger(TemplateController.class); @Autowired private SiteService siteService; @RequestMapping(value = "/list",method = RequestMethod.GET) public String tplList(HttpServletRequest request,ModelMap modelMap){ String tplPath = PropertyUtils.getValue("tpl.path").or("/WEB-INF/ftls/front"); String realTplPath = request.getSession().getServletContext().getRealPath(tplPath); File tplFile = new File(realTplPath); File[] tpls = tplFile.listFiles(); List<Map<String,String>> result = Lists.newArrayList(); Map<String,String> tplInfo = null; for(File tpl : tpls) { tplInfo = Maps.newHashMap(); tplInfo.put("tplPath",tpl.getName()); File[] tplJSON = tpl.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.equalsIgnoreCase("template.json"); } }); if(tplJSON == null || tplJSON.length == 0){ LOGGER.error("模板中必须包含template.json模板文件。"); throw new RuntimeException("模板中必须包含template.json模板文件。"); } ObjectMapper objectMapper = new ObjectMapper(); try { Map map = objectMapper.readValue(tplJSON[0], Map.class); tplInfo.putAll(map); } catch (IOException e) { LOGGER.error("解析template.json出错,错误:{}", e.getMessage()); throw new RuntimeException("解析template.json出错:"+e.getMessage()); } result.add(tplInfo); } modelMap.addAttribute("tplInfos",result); return "template/tpl_list"; } @RequestMapping(value = "/edit",method = RequestMethod.GET) public String tplEdit(){ return "template/tpl_edit"; } @RequestMapping(value = "/thumb",method = RequestMethod.GET) public void thumbnail(HttpServletRequest request,HttpServletResponse response, @Param("tplFileName") String tplFileName,@Param("thumbName") String thumbName){ File thumb = thumbReader(request,tplFileName,thumbName); try { ServletOutputStream outputStream = response.getOutputStream(); Thumbnails.of(thumb).height(220).toOutputStream(outputStream); outputStream.flush(); } catch (IOException e) { LOGGER.error("读取缩略图报错:{}", e.getMessage()); throw new RuntimeException("读取缩略图报错:"+e.getMessage()); } } @RequestMapping(value = "/thumb/original",method = RequestMethod.GET) public void thumbnailOriginal(HttpServletRequest request,HttpServletResponse response, @Param("tplFileName") String tplFileName,@Param("thumbName") String thumbName){ File thumb = thumbReader(request,tplFileName,thumbName); try { ServletOutputStream outputStream = response.getOutputStream(); IOUtils.write(FileUtils.readFileToByteArray(thumb), outputStream); outputStream.flush(); } catch (IOException e) { LOGGER.error("读取缩略图报错:{}", e.getMessage()); throw new RuntimeException("读取缩略图报错:"+e.getMessage()); } } @ResponseBody @RequestMapping(value = "/start",method = RequestMethod.POST) public ImmutableMap<String,String> startUsingTemplate(String tplName){ if(tplName == null || "".equals(tplName)){ LOGGER.error("模板名称为空,{}",tplName); return ImmutableMap.of("status","0","message",getMessage("tpl.updatetplfailed.message")); } try { Site site = (Site)SystemUtils.getSessionSite(); site.setThemeName(tplName); siteService.updateTemplate(site); return ImmutableMap.of("status","1","message",getMessage("tpl.updatetplsuccess.message")); } catch (Exception e){ LOGGER.error("设置模板错误,{}",e.getMessage()); return ImmutableMap.of("status","0","message",getMessage("tpl.updatetplfailed.message")); } } private File thumbReader(HttpServletRequest request,String tplFileName,String thumbName){ String tplPath = PropertyUtils.getValue("tpl.path").or("/WEB-INF/ftls/front"); String realTplPath = request.getSession().getServletContext().getRealPath(tplPath); File thumb = new File(realTplPath+File.separator+tplFileName+File.separator+thumbName); return thumb; } }
package com.insomniacoder.promotionservice; import com.insomniacoder.promotionservice.promotion.entities.Promotion; import com.insomniacoder.promotionservice.promotion.repositories.PromotionRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableEurekaClient @EnableCircuitBreaker public class PromotionServiceApplication { public static void main(String[] args) { SpringApplication.run(PromotionServiceApplication.class, args); } private final String code100 = "FREE100"; private final String code150 = "FREE150"; private final String code200 = "FREE200"; @Bean @LoadBalanced //LoadBalance find service from Eureka public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } @Bean public CommandLineRunner initializeUserData(PromotionRepository promotionRepository) { return (args) -> { promotionRepository.save(Promotion.builder().code(code100).discount(100D).build()); promotionRepository.save(Promotion.builder().code(code150).discount(150D).build()); promotionRepository.save(Promotion.builder().code(code200).discount(200D).build()); }; } }
package chribb.mactrac.data; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import androidx.room.Update; import java.util.List; @Dao public interface MacroDao { @Insert void insert(Macro macro); @Query("DELETE FROM macro_table") void deleteAll(); @Query("DELETE FROM macro_table WHERE id = :id") void deleteFood(long id); @Query("SELECT * from macro_table WHERE day = :day ORDER BY `position`") LiveData<List<Macro>> loadFood(int day); @Query("SELECT COUNT(*) from macro_table WHERE day = :day") int countFood(int day); @Update(onConflict = OnConflictStrategy.REPLACE) void update(List<Macro> macros); }
//дано два double числа первое / второе. Если равно +бескон выводим Integer.MAX_VALUE, если -беск Integer.MIN_VALUE //иначе выводим результат в int package different; import java.util.*; public class diff_13 { private static int convert(Double val) { if (val.isNaN()) { return 0; } else { if (val == Double.POSITIVE_INFINITY) { return Integer.MAX_VALUE; } else { if (val == Double.NEGATIVE_INFINITY) { return Integer.MIN_VALUE; } } } int i = 1; boolean a = true; while (a) { if (val < i) { return i - 1; } else { i++; } } return i; } /* Do not change code below */ public static void main (String[]args){ Scanner scanner = new Scanner(System.in); Double doubleVal = scanner.nextDouble() / scanner.nextDouble(); System.out.println(convert(doubleVal)); } }
/* Text.java Purpose: Description: History: Thu Nov 24 15:17:07 2005, Created by tomyeh Copyright (C) 2005 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zhtml; import java.lang.Object; import java.io.Writer; import java.io.IOException; import org.zkoss.lang.Objects; import org.zkoss.xml.XMLs; import org.zkoss.zk.ui.Execution; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Components; import org.zkoss.zk.ui.AbstractComponent; import org.zkoss.zk.ui.UiException; import org.zkoss.zk.ui.WrongValueException; import org.zkoss.zk.ui.ext.RawId; import org.zkoss.zk.ui.metainfo.LanguageDefinition; import org.zkoss.zk.ui.sys.HtmlPageRenders; import org.zkoss.zhtml.impl.PageRenderer; import org.zkoss.zhtml.impl.TagRenderContext; /** * Represents a piece of text (of DOM). * * @author tomyeh */ public class Text extends AbstractComponent implements RawId { private String _value = ""; private boolean _encode = true; public Text() { } public Text(String value) { setValue(value); } /** Returns the value. * <p>Default: "". */ public String getValue() { return _value; } /** Sets the value. */ public void setValue(String value) { if (value == null) value = ""; if (!Objects.equals(_value, value)) { _value = value; if (isIdRequired()) smartUpdate("value", _value); else invalidate(); } } /** Whether to generate the value directly without ID. */ private boolean isIdRequired() { final Component p = getParent(); return p == null || !isVisible() || getId().length() > 0 || !isRawLabel(p); } private static boolean isRawLabel(Component comp) { final LanguageDefinition langdef = comp.getDefinition().getLanguageDefinition(); return langdef != null && langdef.isRawLabel(); } /** Returns whether to encode the text, such as converting &lt; * to &amp;lt;. * <p>Default: true. * @since 5.0.8 */ public boolean isEncode() { return _encode; } /** Sets whether to encode the text, such as converting &lt; * to &amp;lt;. * <p>Default: true. * @since 5.0.8 */ public void setEncode(boolean encode) { _encode = encode; } //-- Component --// /** Returns the widget class, "zhtml.Text". * @since 5.0.0 */ public String getWidgetClass() { return "zhtml.Text"; } public void setParent(Component parent) { final Component old = getParent(); if (old != null && old != parent && !isIdRequired()) old.invalidate(); super.setParent(parent); if (parent != null && old != parent && !isIdRequired()) parent.invalidate(); } public void invalidate() { if (isIdRequired()) super.invalidate(); else getParent().invalidate(); } public void redraw(Writer out) throws IOException { final Execution exec = Executions.getCurrent(); if (!HtmlPageRenders.isDirectContent(exec)) { super.redraw(out); return; } final boolean idRequired = isIdRequired(); if (idRequired) { out.write("<span id=\""); out.write(getUuid()); out.write("\">"); } out.write(_encode ? XMLs.encodeText(_value): _value); if (idRequired) out.write("</span>"); final TagRenderContext rc = PageRenderer.getTagRenderContext(exec); if (rc != null) { rc.renderBegin(this, getClientEvents(), false); rc.renderEnd(this); } } protected void renderProperties(org.zkoss.zk.ui.sys.ContentRenderer renderer) throws IOException { super.renderProperties(renderer); render(renderer, "value", _value); render(renderer, "idRequired", isIdRequired()); if (!_encode) renderer.render("encode", false); } protected boolean isChildable() { return false; } public Object getExtraCtrl() { return new ExtraCtrl(); } protected class ExtraCtrl implements org.zkoss.zk.ui.ext.render.DirectContent { } }
package designpatterns.reactor.demo3; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.channels.spi.SelectorProvider; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MultiReactor { public static void main(String[] args) throws IOException { Selector selector = Selector.open(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.bind(new InetSocketAddress(1234)); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); int coreNum = Runtime.getRuntime().availableProcessors(); Processor[] processors = new Processor[coreNum]; for (int i = 0; i < processors.length; i++) { processors[i] = new Processor(); } int index = 0; while (selector.select() > 0) { Set<SelectionKey> keys = selector.selectedKeys(); for (SelectionKey key : keys) { keys.remove(key); if (key.isAcceptable()) { ServerSocketChannel acceptServerSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = acceptServerSocketChannel.accept(); socketChannel.configureBlocking(false); System.out.println("Accept request from {}" + socketChannel.getRemoteAddress()); Processor processor = processors[(int) ((index++) % coreNum)]; processor.addChannel(socketChannel); processor.wakeup(); } } } } static class Processor { ExecutorService service = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors()); private Selector selector; public Processor() throws IOException { this.selector = SelectorProvider.provider().openSelector(); start(); } public void addChannel(SocketChannel socketChannel) throws ClosedChannelException { socketChannel.register(this.selector, SelectionKey.OP_READ); } public void wakeup() { this.selector.wakeup(); } public void start() { service.submit(() -> { while (true) { if (selector.select(500) <= 0) { continue; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); iterator.remove(); if (key.isReadable()) { ByteBuffer buffer = ByteBuffer.allocate(1024); SocketChannel socketChannel = (SocketChannel) key.channel(); int count = socketChannel.read(buffer); if (count < 0) { socketChannel.close(); key.cancel(); System.out.println(socketChannel + "{}\t Read ended"); continue; } else if (count == 0) { System.out.println("{}\t Message size is 0" + socketChannel); continue; } else { System.out.println(socketChannel + "{}\t Read message {}" + new String(buffer.array())); } } } } }); } } }
import java.awt.Button; public class Weakling extends Thread { Button seat= new Button(); String id; //boolean hairIsCut=false; //boolean waiting=false; Weakling(String id){ this.id=id; seat.setBounds(SleepingBarber.gui.pos[Integer.parseInt(id)][0].x, SleepingBarber.gui.pos[Integer.parseInt(id)][0].y, 20, 20); seat.setLabel(id); SleepingBarber.gui.add(seat); } public void run(){ while(true){ customerWait(); goToDoor(); customerWait(); goToWaitingRoom(); cutMyHair(); //while(hairIsCut==false){ customerWait(); //} //goToBarber(); SleepingBarber.b.cutHair(this); //customerWait(); //hairIsCut=false; //goToBase(); } } public void cutMyHair(){ System.out.println("Customer "+id+" wants a haircut"); } void customerWait(){ try{ sleep((long) (Math.random()*3000)); } catch(InterruptedException e){ e.printStackTrace(); } } public void goToBase(){ Barber.rest(); seat.setBounds(SleepingBarber.gui.pos[Integer.parseInt(id)][0].x, SleepingBarber.gui.pos[Integer.parseInt(id)][0].y, 20, 20); } void goToDoor(){ seat.setBounds(SleepingBarber.gui.pos[Integer.parseInt(id)][1].x, SleepingBarber.gui.pos[Integer.parseInt(id)][1].y, 20, 20); } void goToWaitingRoom(){ WaitingRoom.checkSeat(); //WaitingRoom.queue.add(this); seat.setBounds(SleepingBarber.gui.pos[Integer.parseInt(id)][2].x, SleepingBarber.gui.pos[Integer.parseInt(id)][2].y, 20, 20); } public void goToBarber(){ WaitingRoom.getUp(); Barber.work(); seat.setBounds(SleepingBarber.gui.pos[Integer.parseInt(id)][3].x, SleepingBarber.gui.pos[Integer.parseInt(id)][3].y, 20, 20); } }
package cpup.poke4j.plugin.input; import cpup.poke4j.Buffer; import cpup.poke4j.Poke; import cpup.poke4j.ui.PokeUI; import cpup.poke4j.ui.UI; import java.awt.event.KeyEvent; public class KeyInput implements Input { protected final Poke poke; protected final Buffer buffer; protected final PokeUI pokeUI; protected final UI activeUI; protected final Type type; protected final KeyEvent e; public KeyInput(Poke _poke, Buffer _buffer, PokeUI _pokeUI, UI _activeUI, Type _type, KeyEvent _e) { poke = _poke; buffer = _buffer; pokeUI = _pokeUI; activeUI = _activeUI; type = _type; e = _e; } // Getters and Setters public Poke getPoke() { return poke; } public PokeUI getPokeUI() { return pokeUI; } public UI getActiveUI() { return activeUI; } public Buffer getBuffer() { return buffer; } public Type getType() { return type; } public KeyEvent getEvent() { return e; } public int getKeyCode() { return e.getKeyCode(); } public char getKeyChar() { return e.getKeyChar(); } public boolean isShiftDown() { return e.isShiftDown(); } public boolean isControlDown() { return e.isControlDown(); } public boolean isMetaDown() { return e.isMetaDown(); } public boolean isAltDown() { return e.isAltDown(); } public boolean isAltGraphDown() { return e.isAltGraphDown(); } public int getModifiers() { return e.getModifiers(); } public int getModifiersEx() { return e.getModifiersEx(); } public static enum Type { press, type } }
/* * Licensed to Kenneth Pino */ package sessionBeans; import entites.Produit; import java.util.List; import javax.ejb.Local; @Local public interface BeanMenuLocal { public void creerJeuxDonnees(); public List<Produit> selectAllProduit(String categorie); public List<Produit> selectOffres(); }
package br.edu.puccampinas.projetoc.pilha; public class PilhaVaziaException extends Exception { private static final long serialVersionUID = 1L; public PilhaVaziaException(String message) { super(message); } }
package online.lahloba.www.lahloba.ui.seller; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.google.firebase.auth.FirebaseAuth; import java.util.List; import online.lahloba.www.lahloba.data.model.MarketPlace; import online.lahloba.www.lahloba.data.model.OrderItem; import online.lahloba.www.lahloba.data.repository.SellerRepository; public class SellerOrdersViewModel extends ViewModel { SellerRepository repository; public SellerOrdersViewModel(SellerRepository repository) { this.repository = repository; } public void startGetSellerOrders(String marketId) { repository.startGetSellerOrders(marketId); } public void startGetMarketPlacesBySeller() { repository.startGetMarketPlacesBySeller(FirebaseAuth.getInstance().getUid()); } public MutableLiveData<List<MarketPlace>> getMarketPlaces() { return repository.getMarketPlaces(); } public MutableLiveData<List<OrderItem>> getSellerOrder() { return repository.getSellerOrder(); } }
package slimeknights.tconstruct.library.client.material; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.IResourceManagerReloadListener; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StringUtils; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.LoaderState; import net.minecraftforge.fml.common.ModContainer; import org.apache.logging.log4j.Logger; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import slimeknights.tconstruct.library.TinkerRegistry; import slimeknights.tconstruct.library.Util; import slimeknights.tconstruct.library.client.MaterialRenderInfo; import slimeknights.tconstruct.library.client.model.ModelHelper; import slimeknights.tconstruct.library.materials.Material; public class MaterialRenderInfoLoader implements IResourceManagerReloadListener { public static final MaterialRenderInfoLoader INSTANCE = new MaterialRenderInfoLoader(); private static Logger log = Util.getLogger("RenderInfoLoader"); private static final Type TYPE = new TypeToken<IMaterialRenderInfoDeserializer>() {}.getType(); private static final Gson GSON = new GsonBuilder() .registerTypeAdapter(TYPE, new MaterialInfoDeserializerDeserializer()) .create(); private IResourceManager resourceManager; static Map<String, Class<? extends IMaterialRenderInfoDeserializer>> renderInfoDeserializers = Maps.newHashMap(); public static void addRenderInfo(String id, Class<? extends IMaterialRenderInfoDeserializer> clazz) { renderInfoDeserializers.put(id, clazz); } // we load from mods resource locations, in this order: // <mod that registered the material> -> tconstruct -> minecraft public void loadRenderInfo() { for(Material material : TinkerRegistry.getAllMaterials()) { // check if info exists in the form of json // if not, check if there already is data // if no data exists and no json is present, fill it with textcolor default List<String> domains = Lists.newArrayList(); ModContainer registeredBy = TinkerRegistry.getTrace(material); if(!Util.MODID.equals(registeredBy.getModId())) { domains.add(registeredBy.getModId().toLowerCase()); } domains.add(Util.MODID); domains.add("minecraft"); for(String domain : domains) { ResourceLocation location = new ResourceLocation(domain, "materials/" + material.getIdentifier()); try { Reader reader = ModelHelper.getReaderForResource(location, resourceManager); IMaterialRenderInfoDeserializer deserializer = GSON.fromJson(reader, TYPE); if(deserializer != null) { material.renderInfo = deserializer.getMaterialRenderInfo(); material.renderInfo.setTextureSuffix(deserializer.getSuffix()); } } catch(FileNotFoundException e) { // set default if nothing is present if(material.renderInfo == null) { material.renderInfo = new MaterialRenderInfo.Default(material.materialTextColor); log.warn("Material " + material.getIdentifier() + " has no rendering info. Substituting default"); } } catch(IOException | JsonParseException e) { log.error("Exception when loading render info for material " + material.getIdentifier() + " from file " + location.toString(), e); } } } } @Override public void onResourceManagerReload(IResourceManager resourceManager) { this.resourceManager = resourceManager; loadRenderInfo(); } private static class MaterialInfoDeserializerDeserializer implements JsonDeserializer<IMaterialRenderInfoDeserializer> { @Override public IMaterialRenderInfoDeserializer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); String type = jsonObject.get("type").getAsString(); Class<? extends IMaterialRenderInfoDeserializer> deserializerClass = renderInfoDeserializers.get(type); if(deserializerClass == null) { throw new JsonParseException("Unknown material texture type: " + type); } JsonElement parameters = jsonObject.get("parameters"); IMaterialRenderInfoDeserializer deserializer = GSON.fromJson(parameters, deserializerClass); if(deserializer != null && jsonObject.has("suffix")) { deserializer.setSuffix(jsonObject.get("suffix").getAsString()); } return deserializer; } } }
package org.mydotey.rpc.client.http.apache.async; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.nio.conn.NoopIOSessionStrategy; import org.apache.http.nio.conn.SchemeIOSessionStrategy; import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOReactorException; /** * Created by Qiang Zhao on 10/05/2016. */ public class AutoCleanedPoolingNHttpClientConnectionManager extends PoolingNHttpClientConnectionManager { private IdleNConnectionMonitorThread _idleNConnectionMonitorThread; public AutoCleanedPoolingNHttpClientConnectionManager(int ioThreadCount, int connectionTtl, int connectionIdleTime, int cleanCheckInterval) { super(createConnectingIOReactor(ioThreadCount), null, getDefaultRegistry(), null, null, connectionTtl, TimeUnit.MILLISECONDS); if (cleanCheckInterval > 0) { _idleNConnectionMonitorThread = new IdleNConnectionMonitorThread(this, connectionIdleTime, cleanCheckInterval); _idleNConnectionMonitorThread.start(); } } @Override public void shutdown() throws IOException { if (_idleNConnectionMonitorThread != null) _idleNConnectionMonitorThread.close(); super.shutdown(); } protected static ConnectingIOReactor createConnectingIOReactor(int ioThreadCount) { IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setIoThreadCount(ioThreadCount).setTcpNoDelay(true) .build(); try { return new DefaultConnectingIOReactor(ioReactorConfig); } catch (IOReactorException ex) { throw new RuntimeException(ex); } } protected static Registry<SchemeIOSessionStrategy> getDefaultRegistry() { return RegistryBuilder.<SchemeIOSessionStrategy> create().register("http", NoopIOSessionStrategy.INSTANCE) .register("https", SSLIOSessionStrategy.getDefaultStrategy()).build(); } }
package org.sagebionetworks.url; import static org.junit.Assert.*; import static org.sagebionetworks.url.UrlSignerUtils.*; import java.net.MalformedURLException; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.util.Date; import org.junit.Test; public class UrlSignerUtilsTest { @Test public void testMakeS3CanonicalString() throws MalformedURLException { HttpMethod method = HttpMethod.POST; // All of these urls should generate the same canonical form. String[] urls = new String[] { "https://host.org/path/child?z=one&a=two&"+HMAC_SIGNATURE+"=abc", "http://host.org/path/child?z=one&a=two", "http://host.org/path/child?a=two&z=one", "http://host.org/path/child?a=two&z=one#refs", "http://host.org:8080/path/child?a=two&z=one", }; // All of the urls should generate this canonical form: String expectedResult = "POST host.org /path/child?a=two&z=one"; for (String url : urls) { String canonical = UrlSignerUtils.makeS3CanonicalString(method, url); assertEquals(expectedResult, canonical); } } @Test public void testMakeS3CanonicalStringNoParams() throws MalformedURLException{ HttpMethod method = HttpMethod.GET; String url = "http://localhost:8080/foo/bar#refs"; String expectedResult = "GET localhost /foo/bar"; String canonical = UrlSignerUtils.makeS3CanonicalString(method, url); assertEquals(expectedResult, canonical); } @Test public void testMakeS3CanonicalStringOneParams() throws MalformedURLException{ HttpMethod method = HttpMethod.PUT; String url = "http://somehost.net/foo/bar?bar="; String expectedResult = "PUT somehost.net /foo/bar?bar="; String canonical = UrlSignerUtils.makeS3CanonicalString(method, url); assertEquals(expectedResult, canonical); } @Test public void testGenerateSignature() throws MalformedURLException, NoSuchAlgorithmException{ String credentials = "a super secret password"; String signatureParameterName = "signature"; HttpMethod method = HttpMethod.PUT; String url = "http://somehost.net/foo/bar?z=one&a=two&expires=123456"; String signature = UrlSignerUtils.generateSignature(method, url, credentials); assertNotNull(signature); String expected = "48139b9703f5f63979b5197db309ec3d09a44ae8"; assertEquals(expected, signature); } @Test public void testGeneratePreSignedURL() throws MalformedURLException{ HttpMethod method = HttpMethod.GET; String credentials = "a super secret password"; Date expires = new Date(123L); String url = "https://synapse.org/root/folder"; URL presigned = UrlSignerUtils.generatePreSignedURL(method, url, expires, credentials); assertNotNull(presigned); String expectedUrl = "https://synapse.org/root/folder?expiration=123&hmacSignature=0736be68b7cfbee8313ed0cc10e612954c8125fc"; assertEquals(expectedUrl, presigned.toString()); } @Test public void testGeneratePreSignedURLNullExpires() throws MalformedURLException{ HttpMethod method = HttpMethod.GET; String credentials = "a super secret password"; Date expires = null; String url = "http://synapse.org?foo.bar"; URL presigned = UrlSignerUtils.generatePreSignedURL(method, url, expires, credentials); assertNotNull(presigned); String expectedUrl = "http://synapse.org?foo.bar=&hmacSignature=2ac8f03a055b3ce3d14852fe0403e1c8855a22e1"; assertEquals(expectedUrl, presigned.toString()); } @Test (expected=IllegalArgumentException.class) public void testGeneratePreSignedURLMethodNull() throws MalformedURLException{ HttpMethod method = null; String credentials = "a super secret password"; Date expires = new Date(123L); String url = "http://synapse.org?foo.bar"; // call under test. UrlSignerUtils.generatePreSignedURL(method, url, expires, credentials); } @Test (expected=IllegalArgumentException.class) public void testGeneratePreSignedURLNullURL() throws MalformedURLException{ HttpMethod method = HttpMethod.GET; String credentials = "a super secret password"; Date expires = new Date(123L); String url = null; // call under test. UrlSignerUtils.generatePreSignedURL(method, url, expires, credentials); } @Test (expected=IllegalArgumentException.class) public void testGeneratePreSignedURLCredsNull() throws MalformedURLException{ HttpMethod method = HttpMethod.GET; String credentials = null; Date expires = new Date(123L); String url = "http://synapse.org?foo.bar"; // call under test. UrlSignerUtils.generatePreSignedURL(method, url, expires, credentials); } @Test public void testValidatePresignedURL() throws Exception { HttpMethod method = HttpMethod.GET; String credentials = "a super secret password"; Date expires = new Date(System.currentTimeMillis()+(30*1000)); String url = "http://synapse.org?param1=one&a=two"; URL presignedUrl = UrlSignerUtils.generatePreSignedURL(method, url, expires, credentials); // this should be valid String signature = UrlSignerUtils.validatePresignedURL(method, presignedUrl.toString(), credentials); assertNotNull(signature); } @Test public void testValidatePresignedURLNoExpires() throws Exception{ HttpMethod method = HttpMethod.GET; String credentials = "a super secret password"; Date expires = null; String url = "http://synapse.org?param1=one&a=two"; URL presignedUrl = UrlSignerUtils.generatePreSignedURL(method, url, expires, credentials); // this should be valid UrlSignerUtils.validatePresignedURL(method, presignedUrl.toString(), credentials); } @Test public void testValidatePresignedURLExpired() throws Exception{ HttpMethod method = HttpMethod.GET; String credentials = "a super secret password"; //expired long ago Date expires = new Date(123); String url = "http://synapse.org?param1=one&a=two"; URL presignedUrl = UrlSignerUtils.generatePreSignedURL(method, url, expires, credentials); // this should be valid try { UrlSignerUtils.validatePresignedURL(method, presignedUrl.toString(), credentials); fail("Exception should be thrown"); } catch (SignatureExpiredException e) { assertEquals(MSG_URL_EXPIRED, e.getMessage()); assertEquals("d1f4e8e13dd941010278dd6c973be3510921709f", e.getSignature()); } } /** * If a URL is expired and mismatched, must throw a SignatureMismatchException and not SignatureExpiredException. * @throws Exception */ @Test (expected=SignatureMismatchException.class) public void testValidatePresignedURLExpiredAndMismatched() throws Exception{ HttpMethod method = HttpMethod.GET; String credentials = "a super secret password"; //expired long ago Date expires = new Date(123); String url = "http://synapse.org?param1=one&a=two"; URL presignedUrl = UrlSignerUtils.generatePreSignedURL(method, url, expires, credentials); String preUrl = presignedUrl.toString(); // change the url preUrl = preUrl.replace("one", "onne"); // call under test UrlSignerUtils.validatePresignedURL(method, preUrl, credentials); } @Test (expected=SignatureMismatchException.class) public void testValidatePresignedURLMismatch() throws Exception{ HttpMethod method = HttpMethod.GET; String credentials = "a super secret password"; Date expires = new Date(System.currentTimeMillis()+(30*1000)); String url = "http://synapse.org?param1=one&a=two"; URL presignedUrl = UrlSignerUtils.generatePreSignedURL(method, url, expires, credentials); String preUrl = presignedUrl.toString(); // change the url preUrl = preUrl.replace("one", "onne"); // this should be valid UrlSignerUtils.validatePresignedURL(method, preUrl, credentials); } @Test (expected=IllegalArgumentException.class) public void testValidatePresignedURLExpiresFormat() throws Exception { HttpMethod method = HttpMethod.GET; String credentials = "a super secret password"; Date expires = null; String url = "http://synapse.org?"+EXPIRATION+"=notADate"; URL presignedUrl = UrlSignerUtils.generatePreSignedURL(method, url, expires, credentials); // this should be valid UrlSignerUtils.validatePresignedURL(method, presignedUrl.toString(), credentials); } }
/* * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.dualquo.te.carplayer; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.RadialGradient; import android.graphics.Shader; import android.graphics.Typeface; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import com.dualquo.te.carplayer.R; /** * Single view that paints one or two text fields and an optional arrow * to the right side. */ public final class MediaView extends View { public static Typeface font; /** * Views that have been made into a header by * {@link MediaView#makeHeader(String)} will be given this id. */ public static final long HEADER_ID = -1; /** * The expander arrow bitmap used in all views that have expanders. */ public static Bitmap sExpander; /** * The paint object, cached for reuse. */ private static Paint sPaint; /** * The cached dash effect that separates the expander arrow and the text. */ private static DashPathEffect sDashEffect; /** * The cached divider gradient that separates each view from other views. */ private static RadialGradient sDividerGradient; /** * The text size used for the text in all views. */ private static int sTextSize; //u ovoj klasi se setuje custom view za liste gde se setuje boja, font, itd public static void init(Context context) { Resources res = context.getResources(); sExpander = BitmapFactory.decodeResource(res, R.drawable.expander_arrow); sTextSize = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, res.getDisplayMetrics()); sDashEffect = new DashPathEffect(new float[] { 3, 3 }, 0); sDividerGradient = null; font = Typeface.createFromAsset(res.getAssets(), "fonts/dsdigit.ttf"); sPaint = new Paint(); sPaint.setTextSize(sTextSize); sPaint.setTypeface(font); sPaint.setAntiAlias(true); } /** * The cached measured view height. */ private final int mViewHeight; /** * An optional bitmap to display on the left of the view. */ private final Bitmap mLeftBitmap; /** * An optional bitmap to display on the right of the view. */ private final Bitmap mRightBitmap; /** * The MediaStore id of the media represented by this view. */ private long mId; /** * The primary text field in the view, displayed on the upper line. */ private String mTitle; /** * The secondary text field in the view, displayed on the lower line. */ private String mSubTitle; /** * True to show the bitmaps, false to hide them. Defaults to true. */ private boolean mShowBitmaps = true; private boolean mBottomGravity; /** * The x coordinate of the last touch event. */ private int mTouchX; /** * Construct a MediaView. * * @param context A Context to use. * @param leftBitmap An optional bitmap to be shown in the left side of * the view. * @param rightBitmap An optional bitmap to be shown in the right side of * the view. */ public MediaView(Context context, Bitmap leftBitmap, Bitmap rightBitmap) { super(context); mLeftBitmap = leftBitmap; mRightBitmap = rightBitmap; int height = 7 * sTextSize / 2; if (mLeftBitmap != null) height = Math.max(height, mLeftBitmap.getHeight() + sTextSize); if (mRightBitmap != null) height = Math.max(height, mRightBitmap.getHeight() + sTextSize); mViewHeight = height; } /** * Set whether to show the left and right bitmaps. By default, will show them. * * @param show If false, do not show the bitmaps. */ public void setShowBitmaps(boolean show) { mShowBitmaps = show; } /** * Request the cached height and maximum width from the layout. */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec)); else setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mViewHeight); } /** * Draw the view on the given canvas. */ @Override public void onDraw(Canvas canvas) { if (mTitle == null) return; int width = getWidth(); int height = mViewHeight; int padding = sTextSize / 2; int xOffset = 0; if (mBottomGravity) canvas.translate(0, getHeight() - mViewHeight); Paint paint = sPaint; if (mShowBitmaps && mRightBitmap != null) { Bitmap expander = mRightBitmap; width -= padding * 4 + expander.getWidth(); paint.setColor(Color.GRAY); paint.setPathEffect(sDashEffect); canvas.drawLine(width, padding, width, height - padding, paint); paint.setPathEffect(null); canvas.drawBitmap(expander, width + padding * 2, (height - expander.getHeight()) / 2, paint); } if (mShowBitmaps && mLeftBitmap != null) { Bitmap expander = mLeftBitmap; canvas.drawBitmap(expander, 0, (height - expander.getHeight()) / 2, paint); xOffset = expander.getWidth(); } canvas.save(); canvas.clipRect(padding, 0, width - padding, height); int allocatedHeight; if (mSubTitle != null) { allocatedHeight = height / 2 - padding * 3 / 2; paint.setColor(Color.GRAY); canvas.drawText(mSubTitle, xOffset + padding, height / 2 + padding / 2 + (allocatedHeight - sTextSize) / 2 - paint.ascent(), paint); } else { allocatedHeight = height - padding * 2; } paint.setColor(Color.parseColor("#93b35e")); paint.setTextSize(68); canvas.drawText(mTitle, xOffset + padding, padding + (allocatedHeight - sTextSize) / 2 - paint.ascent(), paint); canvas.restore(); width = getWidth(); if (sDividerGradient == null) sDividerGradient = new RadialGradient(width / 2, 1, width / 2, Color.parseColor("#93b35e"), Color.BLACK, Shader.TileMode.CLAMP); paint.setShader(sDividerGradient); canvas.drawLine(0, height - 1, width, height - 1, paint); paint.setShader(null); } /** * Set the gravity of the view (top or bottom), determing which edge to * align the content to. * * @param bottom True for bottom gravity; false for top gravity. */ public void setBottomGravity(boolean bottom) { mBottomGravity = bottom; } /** * Returns the desired height for this view. * * @return The measured view height. */ public int getPreferredHeight() { return mViewHeight; } /** * Returns the MediaStore id of the media represented by this view. */ public long getMediaId() { return mId; } /** * Returns the title of this view, the primary/upper field. */ public String getTitle() { return mTitle; } /** * Returns true if the view has a right bitmap that is visible. */ public boolean hasRightBitmap() { return mRightBitmap != null && mShowBitmaps; } /** * Returns true if the right bitmap was pressed in the last touch event. */ public boolean isRightBitmapPressed() { return mRightBitmap != null && mShowBitmaps && mTouchX > getWidth() - mRightBitmap.getWidth() - 2 * sTextSize; } /** * Set this view to be a header (custom text, never expandable). * * @param text The text to show. */ public void makeHeader(String text) { mShowBitmaps = false; mId = HEADER_ID; mTitle = text; mSubTitle = null; } /** * Update the fields in this view with the data from the given Cursor. * * @param cursor A cursor moved to the correct position. The first * column must be the id of the media, the second the primary field. * If this adapter contains more than one field, the third column * must contain the secondary field. * @param useSecondary True if the secondary field should be read. */ public void updateMedia(Cursor cursor, boolean useSecondary) { mShowBitmaps = true; mId = cursor.getLong(0); mTitle = cursor.getString(1); if (useSecondary) mSubTitle = cursor.getString(2); invalidate(); } /** * Set the id and title in this view. * * @param id The new id. * @param title The new title for the view. */ public void setData(long id, String title) { mId = id; mTitle = title; invalidate(); } /** * Update mExpanderPressed. */ @Override public boolean onTouchEvent(MotionEvent event) { mTouchX = (int)event.getX(); return false; } }
package org.androware.androbeans; import android.util.JsonWriter; import org.androware.androbeans.utils.FilterLog; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.List; import java.util.Map; import static android.R.attr.value; /** * Created by jkirkley on 6/17/16. */ public class JsonObjectWriter implements ObjectWriter { JsonWriter writer; public final static String TAG = "jsonwrite"; public void l(String s) { FilterLog.inst().log(TAG, s); } public void l(String tag, String s) { FilterLog.inst().log(tag, s); } public JsonObjectWriter(OutputStream out) throws IOException { writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8")); } public void close() throws IOException { writer.close(); } @Override public void write(Object object) throws IOException { Class type = object.getClass(); Field fields[] = type.getFields(); try { writer.beginObject(); for (Field f : fields) { if (Modifier.isFinal(f.getModifiers()) || Modifier.isStatic(f.getModifiers())) { continue; } String fieldName = f.getName(); Class fieldType = f.getType(); Object value = f.get(object); if(value != null) { writer.name(fieldName); writeValue(fieldType, value); } else { l("field: " + fieldName + " is null."); } } writer.endObject(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public void writeArray(Object array) throws IOException { writer.beginArray(); int length = Array.getLength(array); for (int i = 0; i < length; i++) { Object arrayElement = Array.get(array, i); Class componentType = arrayElement.getClass(); writeValue(componentType, arrayElement); } writer.endArray(); } public void writeValue(Class fieldType, Object value) throws IOException { if (int.class == fieldType || Integer.class == fieldType) { writer.value((int) value); } else if (long.class == fieldType || Long.class == fieldType) { writer.value((long) value); } else if (double.class == fieldType || Double.class == fieldType) { writer.value((double) value); } else if (float.class == fieldType || Float.class == fieldType) { writer.value((float) value); } else if (boolean.class == fieldType || Boolean.class == fieldType) { writer.value((boolean) value); } else if (String.class == fieldType) { writer.value((String) value); } else if (fieldType.isArray()) { writeArray(value); } else if (Map.class.isAssignableFrom(fieldType)) { writeMap((Map)value); } else if (List.class.isAssignableFrom(fieldType)) { writeList((List)value); } else { write(value); } } public void writeMap(Map map) throws IOException { try { if (map == null) { writer.beginObject(); writer.endObject(); return; } writer.beginObject(); for (Object k : map.keySet()) { String key = (String) k; writer.name(key); Object value = map.get(key); Class fieldType = value.getClass(); writeValue(fieldType, value); } writer.endObject(); } catch (IOException e) { e.printStackTrace(); } } public void writeList(List list) { try { if (list == null) { // write empty array writer.beginArray(); writer.endArray(); return; } writer.beginArray(); for (Object value : list) { Class fieldType = value.getClass(); writeValue(fieldType, value); } writer.endArray(); } catch (IOException e) { } } }
package de.niklaskiefer.bnclCore.parser; import java.util.logging.Logger; /** * @author Niklas */ public class AbstractBnclParser { public Logger logger() { return Logger.getLogger(this.getClass().getName()); } }
package com.microservice.authserver.serviceimpl; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.microservice.authserver.entity.Role; import com.microservice.authserver.exceptionhandler.ResourceAlreadyExistsException; import com.microservice.authserver.exceptionhandler.ResourceNotFoundException; import com.microservice.authserver.repository.RoleRepository; import com.microservice.authserver.service.RoleService; @Service public class RoleServiceImpl implements RoleService { @Autowired RoleRepository roleRepository; @Override public Role addRole(Role newRole) throws URISyntaxException { Long id = newRole.getId(); Optional<Role> role = roleRepository.findById(id); if(role.isPresent()) { throw new ResourceAlreadyExistsException(id,Role.class.getSimpleName()); } Role addedRole = roleRepository.save(newRole); return addedRole; } @Override public List<Role> getAllRoles() { List<Role> roles = roleRepository.findAll(); return roles; } @Override public Role getRoleById(Long id) { Role role = roleRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException(id,Role.class.getSimpleName())); return role; } @Override public String deleteRole(Long id) { roleRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException(id,Role.class.getSimpleName())); roleRepository.deleteById(id); return "The record with id "+ id +" is successfully deleted!"; } @Override public Role editRole(Role newRole) throws URISyntaxException { roleRepository.findById(newRole.getId()) .orElseThrow(() -> new ResourceNotFoundException(newRole.getId(),Role.class.getSimpleName())); Role updatedRole = roleRepository.save(newRole); return updatedRole; } @Override public Role searchByName(String name, String nic){ Role roles = roleRepository.findByName(name); return roles; } }
package com.example.artistslk.Admin; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.example.artistslk.MainActivity; import com.example.artistslk.Model.Track; import com.example.artistslk.R; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class AddTrack extends AppCompatActivity { //defining TextView artistName; EditText trackName; SeekBar seekBarRating; Button addTrack; Context context; ListView trackList; List<Track> tracks; DatabaseReference databaseTrackRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_track); //initializing artistName = findViewById(R.id.trackTitle); trackName = findViewById(R.id.addTrackName); seekBarRating = findViewById(R.id.trackRating); trackList = findViewById(R.id.TrackListView); addTrack = findViewById(R.id.addTrackBtn); context =this; tracks = new ArrayList<>(); //getting selected artist name of mainActivity Intent intent = getIntent(); String id = intent.getStringExtra(MainActivity.ARTIST_ID); String name = intent.getStringExtra(MainActivity.ARTIST_NAME); System.out.println(id); //setting text view artistName.setText("Add "+name+"'s new track "); //database track databaseTrackRef = FirebaseDatabase.getInstance().getReference("tracks").child(id); //handling add Track button addTrack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { addTracks(); } }); } @Override protected void onStart() { super.onStart(); databaseTrackRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { tracks.clear(); for(DataSnapshot trackSnapshot : snapshot.getChildren()){ Track track = trackSnapshot.getValue(Track.class); tracks.add(track); } TrackAdapter trackAdapter = new TrackAdapter(AddTrack.this,tracks); trackList.setAdapter(trackAdapter); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } //addTrac method public void addTracks(){ String trackT = trackName.getText().toString().trim(); int rating = seekBarRating.getProgress(); if(TextUtils.isEmpty(trackT)){ Toast.makeText(context, "Please Enter Track name", Toast.LENGTH_SHORT).show(); }else{ String id = databaseTrackRef.push().getKey(); Track track = new Track(trackT,id,rating); databaseTrackRef.child(id).setValue(track); Toast.makeText(context, "Track added", Toast.LENGTH_SHORT).show(); } } }
package fr.filechooser_; import java.io.File; import javax.swing.ImageIcon; /** * Formats de fichier acceptés * * @see ImageFilter */ public class Utils { public final static String jpeg = "jpeg"; public final static String jpg = "jpg"; public final static String tiff = "tiff"; public final static String tif = "tif"; public final static String webp = "webp"; public final static String psd = "psd"; public final static String png = "png"; public final static String bmp = "bmp"; public final static String gif = "gif"; public final static String ico = "ico"; public final static String pcx = "pcx"; public final static String nef = "nef"; public final static String cr2 = "cr2"; public final static String orf = "orf"; public final static String arw = "arw"; public final static String rw2 = "rw2"; public final static String rwl = "rwl"; public final static String srw = "srw"; public static String getExtension(File f) { /** * Retourne l'extension d'un File. * * @param f * @return Extension (String). */ String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i + 1).toLowerCase(); } return ext; } /** Returns an ImageIcon, or null if the path was invalid. */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = Utils.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find file: " + path); return null; } } }
package ur.ur_flow.managers; import android.content.Context; import android.util.Log; import com.google.gson.Gson; import com.gtambit.gt.app.api.GtSharedPreferences; import com.gtambit.gt.app.index.GtApp; import com.gtambit.gt.app.mission.api.TaskSharedPreferences; import java.util.ArrayList; import lib.hyxen.http_request.RequestHandler; import lib.hyxen.http_request.RequestResponseListener; import lib.hyxen.http_request.RequestSetting; import ur.api_ur.URApiSetting; import ur.api_ur.api_data_obj.poi.URPoiObj; import ur.api_ur.api_data_obj.store.URApiCouponGetResponseObj; import ur.api_ur.api_data_obj.store.URApiCouponListResponseObj; import ur.api_ur.api_data_obj.store.URApiCouponRedeemResponseObj; import ur.api_ur.api_data_obj.store.URCouponDetailObj; import ur.api_ur.api_data_obj.store.URCouponObj; import ur.api_ur.store.URApiStore; import ur.api_ur.store.URApiStoreType; /** * Created by redjack on 15/9/28. */ public class URCouponManager { public enum Err { OK, NO_CONNECTION, LOGIN_INVALID, COUPON_NOT_EXIST, COUPON_IS_FOR_VIP, HAD_GOT_BEFORE, GET_FULL, ALREADY_REDEEM, UNKNOWN } private static URCouponManager mCouponManager; Context context; URCouponWarehouse db; RequestHandler requestHandler = new RequestHandler(); Gson gson; /** * @warn: If had assigned user name before, will return manager for that user. * If not, will return for none. */ public static URCouponManager getInstance(Context context) { if (mCouponManager == null) { synchronized (URCouponManager.class) { if (mCouponManager == null) mCouponManager = new URCouponManager(context); } } return mCouponManager; } //region = Change DB = public static URCouponManager getInstance(Context context, String userName) { if (mCouponManager == null) { synchronized (URCouponManager.class) { if (mCouponManager == null) mCouponManager = new URCouponManager(context, userName); } } mCouponManager.changeUser(context, userName); return mCouponManager; } public boolean isUsingUserDB() { return !db.isDB(null); } private URCouponManager(Context context) { this(context, null); } private URCouponManager(Context context, String userName) { this.context = context; this.db = new URCouponWarehouse(context, userName); this.gson = new Gson(); } public static URCouponManager changeToUser(Context context, String userName) { URCouponManager manager = getInstance(context); manager.changeUser(context, userName); return manager; } public void changeUser(Context context, String userName) { if (!db.isDB(userName)) { db = new URCouponWarehouse(context, userName); } } //endregion //region = Manipulate Coupon = public void deleteCoupon(URCouponObj coupon) { db.deleteCoupon(URCouponWarehouse.Record.COUPON_LIST, coupon); } public void drawACoupon(URCouponObj coupon, CouponManipulateListener listener) { URApiSetting draw = URApiStore.drawACoupon(coupon.cpn_id); draw.userInfo = new CouponRequestInfoObj(coupon, listener); requestHandler.sendRequest(draw, maniCouponResListener); } /** * @param detail Needs serial in detail. */ public void redeemACoupon(URCouponObj coupon, URCouponDetailObj detail, CouponManipulateListener listener) { URApiSetting red = URApiStore.redeem(detail.cpn_id + ""); red.userInfo = new CouponRequestInfoObj(coupon, detail, listener); requestHandler.sendRequest(red, maniCouponResListener); } /** * Will update both coupon and coupn in DB. * <p> * If push coupon is get, will change state at push table, * if push coupn redeem, will only update state at coupon list. */ public void updateCouponState(URCouponWarehouse.Record atRecord, URCouponObj coupon, URCouponObj.State state) { coupon.setState(state); db.updateCouponGetState(atRecord, coupon); } private RequestResponseListener maniCouponResListener = new RequestResponseListener() { @Override public void requesting(RequestSetting setting) { CouponRequestInfoObj info = (CouponRequestInfoObj) setting.userInfo; if (info.maniListener != null) info.maniListener.onLoading(); } private static final String TAG = "URCouponManager"; @Override public void requestComplete(RequestSetting setting, String result) { URApiSetting sett = (URApiSetting) setting; CouponRequestInfoObj obj = (CouponRequestInfoObj) setting.userInfo; if (sett.rType == URApiStoreType.GET_COUPON) { URApiCouponGetResponseObj res = gson.fromJson(result, URApiCouponGetResponseObj.class); if (res.isOK()) { if (obj.coupon.isNotGot()) updateCouponState(URCouponWarehouse.Record.COUPON_LIST, obj.coupon, URCouponObj.State.OWN); db.saveCouponDetail(obj.coupon, res.cpn); if (obj.maniListener != null) obj.maniListener.onCouponDrew(Err.OK, obj.coupon, res.cpn); } else if (res.isTokenInvalid()) { if (obj.maniListener != null) obj.maniListener.onCouponDrew(Err.LOGIN_INVALID, obj.coupon, res.cpn); } else if (res.isCouponNotExist()) { db.removeCouponFromRecord(URCouponWarehouse.Record.COUPON_LIST, obj.coupon); if (obj.maniListener != null) obj.maniListener.onCouponDrew(Err.COUPON_NOT_EXIST, obj.coupon, res.cpn); } else if (res.isForVip()) { if (obj.maniListener != null) obj.maniListener.onCouponDrew(Err.COUPON_IS_FOR_VIP, obj.coupon, res.cpn); } else if (res.hadGotBefore()) { if (obj.maniListener != null) obj.maniListener.onCouponDrew(Err.HAD_GOT_BEFORE, obj.coupon, res.cpn); } else if (res.isGetFull()) { if (obj.maniListener != null) obj.maniListener.onCouponDrew(Err.GET_FULL, obj.coupon, res.cpn); } else { if (obj.maniListener != null) obj.maniListener.onCouponDrew(Err.UNKNOWN, obj.coupon, res.cpn); } } else if (sett.rType == URApiStoreType.REDEEM) { URApiCouponRedeemResponseObj res = gson.fromJson(result, URApiCouponRedeemResponseObj.class); GtSharedPreferences.saveMembetStatus(context, res.mcard_status + ""); GtSharedPreferences.saveShopStatus(context, res.shop_status + ""); updateCouponState(URCouponWarehouse.Record.COUPON_LIST, obj.coupon, URCouponObj.State.REDEEMED); if (obj.maniListener != null) obj.maniListener.onCouponRedeem(res.isOK() ? Err.OK : Err.ALREADY_REDEEM, obj.detail); } } @Override public void requestFault(RequestSetting setting) { URApiSetting sett = (URApiSetting) setting; CouponRequestInfoObj obj = (CouponRequestInfoObj) setting.userInfo; if (obj.maniListener == null) return; if (sett.rType == URApiStoreType.GET_COUPON) { /// If no connection, get from db. if (obj.maniListener != null) { URCouponDetailObj detail = db.getCouponDetail(obj.coupon); obj.maniListener.onCouponDrew(Err.NO_CONNECTION, obj.coupon, detail); } } else if (sett.rType == URApiStoreType.REDEEM) { if (obj.maniListener != null) obj.maniListener.onCouponRedeem(Err.NO_CONNECTION, obj.detail); } } @Override public void requestDone(RequestSetting setting) { } }; public interface CouponManipulateListener { public void onLoading(); public void onCouponDrew(Err err, URCouponObj coupon, URCouponDetailObj detail); public void onCouponRedeem(Err err, URCouponDetailObj detail); } //endregion //region = Load Coupon = public ArrayList<URCouponObj> loadNotOwnCoupon() { return db.getAllCoupon(URCouponWarehouse.Record.COUPON_LIST, URCouponObj.State.NOT_GOT); } public ArrayList<URCouponObj> loadOwnRedeemList() { ArrayList<URCouponObj> couponObjs = new ArrayList<>(); couponObjs.addAll(db.getAllCoupon(URCouponWarehouse.Record.COUPON_LIST, URCouponObj.State.OWN)); couponObjs.addAll(db.getAllCoupon(URCouponWarehouse.Record.COUPON_LIST, URCouponObj.State.REDEEMED)); return couponObjs; } public ArrayList<URCouponObj> loadOwnRedeemList(URPoiObj assignedPoi) { if (assignedPoi == null) return loadOwnRedeemList(); ArrayList<URCouponObj> couponObjs = new ArrayList<>(); couponObjs.addAll(db.getAllCoupon(URCouponWarehouse.Record.COUPON_LIST, URCouponObj.State.OWN, assignedPoi.shop_id)); couponObjs.addAll(db.getAllCoupon(URCouponWarehouse.Record.COUPON_LIST, URCouponObj.State.REDEEMED, assignedPoi.shop_id)); return couponObjs; } /** * Filter coupon by poi. * * @param assignedPoi by poi. * @param cate Filter by cate at sys. * @param cstmCate Filter by cstm_cat. * @return Filtered list. */ public ArrayList<URCouponObj> loadOwnRedeemList(URPoiObj assignedPoi, String cate, String cstmCate) { if (assignedPoi == null && cate == null && cstmCate == null) return loadOwnRedeemList(); ArrayList<URCouponObj> couponObjs = new ArrayList<>(); String shopId = assignedPoi == null ? null : assignedPoi.shop_id; couponObjs.addAll(db.getAllCoupon(URCouponWarehouse.Record.COUPON_LIST, URCouponObj.State.OWN, cate, shopId, cstmCate, 0, Integer.MAX_VALUE, false)); couponObjs.addAll(db.getAllCoupon(URCouponWarehouse.Record.COUPON_LIST, URCouponObj.State.REDEEMED, cate, shopId, cstmCate, 0, Integer.MAX_VALUE, false)); return couponObjs; } public void loadAllCoupon() { URApiSetting cou = URApiStore.getCouponList(null, null, Integer.MAX_VALUE, 0); cou.userInfo = new CouponRequestInfoObj(null, null, null, 0, Integer.MAX_VALUE, null); cou.listener = fetchCouponResListener; requestHandler.sendRequest(cou); } public void loadAllCouponAndSetupLBS(CouponLoadedListener listener) { CouponRequestInfoObj info = new CouponRequestInfoObj(null, null, null, 0, Integer.MAX_VALUE, listener); info.needsToLoadAllLBS = true; URApiSetting cou = URApiStore.getCouponList(null, null, Integer.MAX_VALUE, 0); cou.userInfo = info; cou.listener = fetchCouponResListener; requestHandler.sendRequest(cou); } public void loadCouponList(URPoiObj poiObj, String cate, String cstmCate, int page, int limit, CouponLoadedListener listener) { URApiSetting cou = URApiStore.getCouponList(poiObj != null ? poiObj.shop_id : null, cate, limit, page * limit); CouponRequestInfoObj info = new CouponRequestInfoObj(cate, poiObj != null ? poiObj.shop_id : null, cstmCate, page * limit, limit, listener); cou.userInfo = info; cou.listener = fetchCouponResListener; requestHandler.sendRequest(cou); } private static final String TAG = "URCouponManager"; private void divideCoupons(CouponRequestInfoObj infoObj, boolean isConnectionOK, URCouponObj[] fromOnline) { if (!isConnectionOK || fromOnline == null) { if (infoObj.loadedListener != null) infoObj.loadedListener.onLoaded(isConnectionOK, new ArrayList<URCouponObj>(0)); return; } /// Seperate from got and not got. ArrayList<URCouponObj> notGot = new ArrayList<>(); ArrayList<URCouponObj> got = new ArrayList<>(); ArrayList<URCouponObj> push = new ArrayList<>(); for (URCouponObj cou : fromOnline) { if (cou.hasGotThisCoupon()) got.add(cou); // lbs push 是 push type 並且 尚未過期的coupon再加入  // TODO: 2016/5/12 因判斷推播類型 又判斷 是否過期 所以暫時先拿掉 過期判斷 else if (cou.isPushType()) push.add(cou); else if (cou.isNotGot()) notGot.add(cou); } db.saveToCouponList(notGot); db.saveToCouponList(got); if (push.size() > 0) { db.saveToPushStorage(push); ArrayList<URCouponObj> checked = null; if (infoObj.needsToLoadAllLBS) checked = db.getAllCoupon(URCouponWarehouse.Record.PUSH_STORAGE); else checked = db.recheckCoupons(URCouponWarehouse.Record.PUSH_STORAGE, push); // lbs push URLBSDataSetter.setLBSData(context, checked); } if (infoObj.loadedListener != null) { /// From DB cause needs to include Push coupon. ArrayList<URCouponObj> fromDB = db.getAllCoupon( URCouponWarehouse.Record.COUPON_LIST, URCouponObj.State.NOT_GOT, infoObj.cate, infoObj.shopId, infoObj.cstmCate, infoObj.offset, infoObj.limit, true); infoObj.loadedListener.onLoaded(isConnectionOK, fromDB); } } public RequestResponseListener fetchCouponResListener = new RequestResponseListener() { @Override public void requesting(RequestSetting setting) { CouponRequestInfoObj info = (CouponRequestInfoObj) setting.userInfo; if (info.loadedListener != null) info.loadedListener.onLoading(); } @Override public void requestComplete(RequestSetting setting, String result) { URApiCouponListResponseObj res = gson.fromJson(result, URApiCouponListResponseObj.class); if (res == null) return; //如果重複登入 清空apitkeon if (res.err == -100) { TaskSharedPreferences.saveApiToken(GtApp.getAppContext(), ""); } if (res.isOK()) divideCoupons((CouponRequestInfoObj) setting.userInfo, true, res.cpn); else { CouponRequestInfoObj info = (CouponRequestInfoObj) setting.userInfo; if (info.loadedListener != null) info.loadedListener.onTokenInvalid(); } } @Override public void requestFault(RequestSetting setting) { divideCoupons((CouponRequestInfoObj) setting.userInfo, false, null); } @Override public void requestDone(RequestSetting setting) { } }; public interface CouponLoadedListener { public void onLoading(); public void onLoaded(boolean isConnectionOK, ArrayList<URCouponObj> coupons); /** * Will call when all coupon is all got and redeem. */ public void onNeedsToLoadNextPage(); public void onTokenInvalid(); } //endregion //region = Push Coupon = /** * If push coupon is not 'not get', means don't needs to set again. */ public ArrayList<URCouponObj> getAllPushCouponList() { return db.getAllCoupon(URCouponWarehouse.Record.PUSH_STORAGE, URCouponObj.State.NOT_GOT); } public void saveCouponListTodb(ArrayList<URCouponObj> AL) { db.saveToCouponList(AL); } public ArrayList<URCouponObj> getAllOwnCouponList() { return db.getAllCoupon( URCouponWarehouse.Record.COUPON_LIST, URCouponObj.State.OWN, null, null, null, 0, 50, true); // return db.getAllCoupon(URCouponWarehouse.Record.COUPON_LIST, URCouponObj.State.NOT_GOT); } public URCouponObj getSingleObj(String id) { return db.getSingleCoupon(URCouponWarehouse.Record.COUPON_LIST, id); } public URCouponObj saveCouponFromPush(String cpnId) { URCouponObj couponObj = getPushCoupon(cpnId); if (couponObj == null) return null; saveCouponFromPush(couponObj); return couponObj; } public void saveCouponFromPush(URCouponObj couponObj) { db.saveToCouponList(couponObj); db.deleteCoupon(URCouponWarehouse.Record.PUSH_STORAGE, couponObj); } public URCouponObj getPushCoupon(String cpnId) { return db.getSingleCoupon(URCouponWarehouse.Record.PUSH_STORAGE, cpnId); } //endregion public class CouponRequestInfoObj { public CouponManipulateListener maniListener; public CouponLoadedListener loadedListener; public URCouponObj coupon; public URCouponDetailObj detail; public String shopId; public String cate; public String cstmCate; public int offset = 0; public int limit = 0; public boolean needsToLoadAllLBS = false; public CouponRequestInfoObj() { } public CouponRequestInfoObj(URCouponObj coupon, CouponManipulateListener maniListener) { this.maniListener = maniListener; this.coupon = coupon; } public CouponRequestInfoObj(URCouponObj coupon, URCouponDetailObj detail, CouponManipulateListener maniListener) { this.maniListener = maniListener; this.coupon = coupon; this.detail = detail; } public CouponRequestInfoObj(String cate, String shopId, String cstmCate, int offset, int limit, CouponLoadedListener loadedListener) { this.loadedListener = loadedListener; this.offset = offset; this.limit = limit; this.shopId = shopId; this.cate = cate; this.cstmCate = cstmCate; } } }
package za.co.vzap.email; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Properties; import java.util.Scanner; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Store; import za.co.vzap.dao.MySqlGeneralDAO; import za.co.vzap.dao.MySqlReportDAO; import za.co.vzap.dto.BookingDTO; //Referencing OpenSource code /** * * @author All Open source developers * @version 1.0.0.0 * @since 2014/12/22 */ public class ReadEmail extends Thread { public void run(){ while(true){ String host = "pop.gmail.com"; String user = "vzapreservationsystem@gmail.com"; String password = "vzap123@"; Properties properties = System.getProperties(); Session session = Session.getDefaultInstance(properties, null); Store store = null; try { store = session.getStore("pop3s"); } catch (NoSuchProviderException e5) { // TODO Auto-generated catch block e5.printStackTrace(); } try { store.connect(host, user, password); } catch (MessagingException e4) { // TODO Auto-generated catch block e4.printStackTrace(); } Folder folder = null; try { folder = store.getFolder("inbox"); } catch (MessagingException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } try { folder.open(Folder.READ_ONLY); } catch (MessagingException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } Message[] message = null; try { message = folder.getMessages(); } catch (MessagingException e2) { e2.printStackTrace(); } MySqlGeneralDAO genDao=new MySqlGeneralDAO(); MySqlReportDAO list=new MySqlReportDAO(); ArrayList<BookingDTO> clientList=null; try { clientList=(ArrayList<BookingDTO>)list.bookingAll(); } catch (SQLException e) { e.printStackTrace(); } for (int i = 0; i < message.length; i++) { Date sentDate = null; try { sentDate = message[message.length-1].getSentDate(); long myTime = sentDate.getTime(); SimpleDateFormat df = new SimpleDateFormat("HH:mm"); Date d = df.parse(Long.toString(myTime)); Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.HOUR, 72); String newTime = df.format(cal.getTime()); if(newTime.equals(System.currentTimeMillis())){ genDao.updateBookingStatusCancel(clientList.get(i).getClientName(), clientList.get(i).getClientSurname(), clientList.get(i).getRoomName()); genDao.updateRoomCancels(clientList.get(i).getRoomName()); } } catch (MessagingException | ParseException e2) { e2.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } try { if(message[i].getSentDate().after(sentDate)){ Scanner sc = null; try { sc = new Scanner(message[i].getSubject()); } catch (MessagingException e1) { e1.printStackTrace(); } sc.useDelimiter(" "); String confirmOrDecline=sc.next(); sc.next(); String name=sc.next(); String surname=sc.next(); String roomName=sc.next(); System.out.println(name+" "+surname+" "+roomName); // MySqlReportDAO list=new MySqlReportDAO(); // try { // ArrayList<ClientDTO> clientList=(ArrayList<ClientDTO>)list.clientAll(); // } catch (SQLException e) { // e.printStackTrace(); // } if(confirmOrDecline.equalsIgnoreCase("Confirm")){ try { genDao.updateBookingStatusBooked(name, surname, roomName); genDao.updateRoomCount(roomName); } catch (SQLException e) { e.printStackTrace(); } System.out.println("Booking confirmed send to DAO"); } if(confirmOrDecline.equalsIgnoreCase("Decline")){ try { genDao.updateRoomCancels(roomName); genDao.updateBookingStatusCancel(name, surname, roomName); } catch (SQLException e) { e.printStackTrace(); } System.out.println("Booking declined send to DAO"); } } } catch (MessagingException e) { e.printStackTrace(); } } try { folder.close(true); } catch (MessagingException e) { e.printStackTrace(); } try { store.close(); } catch (MessagingException e) { e.printStackTrace(); } try { Thread.sleep(300000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package ViewModels; import java.util.Date; public class VistaAbono { private int idAbono; private String nombre; private float precio; private Date vigencia; public int getIdAbono() { return idAbono; } public void setIdAbono(int idAbono) { this.idAbono = idAbono; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public float getPrecio() { return precio; } public void setPrecio(float precio) { this.precio = precio; } public Date getVigencia() { return vigencia; } public void setVigencia(Date vigencia) { this.vigencia = vigencia; } public VistaAbono(int idAbono, String nombre, float precio, Date vigencia) { super(); this.idAbono = idAbono; this.nombre = nombre; this.precio = precio; this.vigencia = vigencia; } }
package com.lsjr.zizisteward.bean; public class PicList { private String id; private String image_filename; private String location; private String url; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImage_filename() { return image_filename; } public void setImage_filename(String image_filename) { this.image_filename = image_filename; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return "PicList{" + "id='" + id + '\'' + ", image_filename='" + image_filename + '\'' + ", location='" + location + '\'' + ", url='" + url + '\'' + '}'; } }
package com.ilecreurer.drools.samples.sample2.conf; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import com.ilecreurer.drools.samples.sample2.util.Constants; @Configuration @ConfigurationProperties("area") public class AreaProperties { /** * minLatitude attribute. */ private double minLatitude = Constants.MIN_LAT; /** * maxLatitude attribute. */ private double maxLatitude = Constants.MAX_LAT; /** * minLongitude attribute. */ private double minLongitude = Constants.MIN_LONG; /** * maxLongitude attribute. */ private double maxLongitude = Constants.MAX_LONG; /** * @return the minLatitude. */ public double getMinLatitude() { return minLatitude; } /** * @param minLatitudeParam the minLatitude to set. */ public void setMinLatitude(final double minLatitudeParam) { this.minLatitude = minLatitudeParam; } /** * @return the maxLatitude. */ public double getMaxLatitude() { return maxLatitude; } /** * @param maxLatitudeParam the maxLatitude to set. */ public void setMaxLatitude(final double maxLatitudeParam) { this.maxLatitude = maxLatitudeParam; } /** * @return the minLongitude. */ public double getMinLongitude() { return minLongitude; } /** * @param minLongitudeParam the minLongitude to set. */ public void setMinLongitude(final double minLongitudeParam) { this.minLongitude = minLongitudeParam; } /** * @return the maxLongitude. */ public double getMaxLongitude() { return maxLongitude; } /** * @param maxLongitudeParam the maxLongitude to set. */ public void setMaxLongitude(final double maxLongitudeParam) { this.maxLongitude = maxLongitudeParam; } }
package utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class ConfigReader { Properties prop; public ConfigReader(String configFilePath){ File f = new File(configFilePath); InputStream is = null; try { is = new FileInputStream(f); } catch (FileNotFoundException e) { e.printStackTrace(); } prop = new Properties(); try { prop.load(is); } catch (IOException e) { e.printStackTrace(); } } public ConfigReader(){ File f = new File("/Users/premalathaeddyam/eclipse-workspace/YoutubeTest-master/src/main/resources/Config.properties"); InputStream is = null; try { is = new FileInputStream(f); } catch (FileNotFoundException e) { e.printStackTrace(); } prop = new Properties(); try { prop.load(is); } catch (IOException e) { e.printStackTrace(); } } public String getProperty(String propertyName){ return prop.getProperty(propertyName); } }
/* * 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 br.edu.ifrs.mostra.daos; import br.edu.ifrs.mostra.models.Curso; import java.util.List; import java.util.logging.Level; /** * * @author jean */ public class CursoDao implements Dao<Curso> { @Override public List<Curso> listAll() { try { return context.curso().toList(); } catch (Exception e) { log.log(Level.SEVERE, "nao foi possivel listar os cursos", e); } return null; } public List<Curso> findAllByCampusId(int idCampus) { try { return context.curso().where(c -> c.getFkCampus() == idCampus).toList(); } catch (Exception e) { log.log(Level.SEVERE, "nao foi possivel listar os cursos pelo campus", e); } return null; } @Override public List<Curso> findById(int id) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Curso findOneById(int id) { try { Curso curso = context.curso().where(c -> c.getIdCurso() == id).getOnlyValue(); return curso; } catch (Exception e) { log.log(Level.SEVERE, "nao foi possivel encontrar o curso pelo id", e); } return null; } @Override public void remove(Curso entity) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Curso update(Curso entity) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
public class test { public static void main(String[] args) throws Eccezione_Num_non_Valido { boolean ok=true; VettoreInteri v1 = new; VettoreInteri v2 = new VettoreInteri(0); VettoreInteri v1 = new VettoreInteri("12|567|19|0"); System.out.println(v1.toString()); System.out.println(v1.getMin()); } }
package com.yc.education.service.account; import com.yc.education.model.account.AccountInputInvoiceInfo; import com.yc.education.service.IService; import java.util.List; /** * @Description 账款-进项发票-详情 * @Author BlueSky * @Date 2019-01-09 11:47 */ public interface IAccountInputInvoiceInfoService extends IService<AccountInputInvoiceInfo> { /** * 根据 进项发票id 查询 * @param otherid * @return */ List<AccountInputInvoiceInfo> listAccountInputInvoiceInfo(String otherid); /** * 根据外键id删除 * @param otherid * @return */ int deleteAccountInputInvoiceInfoByParentId( String otherid); }
package com.example.reggiewashington.c196; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; public class DatabaseHelper extends SQLiteOpenHelper { private static final String TAG = "DatabaseHelper"; public static final String DATABASE_NAME = "terms.db"; private static final int DATABASE_VERSION = 1; public static final String TABLE_NAME = "terms_table"; public static final String TABLE_COURSE = "course_table"; public static final String TABLE_ASSESSMENTS = "assessments_table"; public static final String TABLE_TERM_COURSE = "terms_course"; public static final String TABLE_COURSE_ASSESSMENTS = "course_assessments"; //General column names public static final String COL_1 = "ID"; //Terms - column names public static final String COL_2 = "TERM"; public static final String COL_3 = "START"; public static final String COL_4 = "END"; //Course - column name public static final String COL_TITLE = "TITLE"; public static final String COL_CSTART = "CSTART"; public static final String COL_CEND = "CEND"; public static final String COL_STATUS = "STATUS"; public static final String COL_MENTOR = "MENTOR"; public static final String COL_MNUMBER = "MNUMBER"; public static final String COL_MEMAIL = "MEMAIL"; public static final String COL_NOTES = "NOTES"; public static final String COL_BOOLEAN = "BOOLEAN"; //Assessments column names public static final String COL_TYPE = "TYPE"; public static final String COL_NAME = "NAME"; public static final String COL_DATE = "DATE"; //Terms Course column names public static final String COL_TID = "TERMS_ID"; public static final String COL_CID = "COURSES_ID"; //Course Assessment column names public static final String COL_AID = "ASSESSMENTS_ID"; public DatabaseHelper(Context context) { //Terms table create super(context, DATABASE_NAME, null, DATABASE_VERSION); } public boolean insertCourse(int termId, int courseId) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL_TID, termId); contentValues.put(COL_CID, courseId); Log.d(TAG, "addData: Adding " + courseId + " to" + TABLE_TERM_COURSE); long result = db.insert(TABLE_TERM_COURSE, null, contentValues); if (result == -1) return false; else return true; } @Override public void onCreate(SQLiteDatabase db) { //SQLiteDatabase db = getWritableDatabase(); String createTermTable = "create table " + TABLE_NAME + " (" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_2 + " TEXT," + COL_3 + " TEXT," + COL_4 + " TEXT)"; String addTerm = "INSERT INTO terms_table VALUES(1, 'TERM 1', '2018-01-01', '2018-06-30')"; String addTerm2 = "INSERT INTO terms_table VALUES(2, 'TERM 2', '2018-07-01', '2018-12-31')"; String addTerm3 = "INSERT INTO terms_table VALUES(3, 'TERM 3', '2019-01-01', '2019-06-30')"; String addTerm4 = "INSERT INTO terms_table VALUES(4, 'TERM 4', '2019-07-01', '2019-12-31')"; db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); db.execSQL(createTermTable); db.execSQL(addTerm); db.execSQL(addTerm2); db.execSQL(addTerm3); db.execSQL(addTerm4); //Courses table create String createCourseTable = "create table " + TABLE_COURSE + " (" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_TITLE + " TEXT," + COL_CSTART + " TEXT," + COL_CEND + " TEXT," + COL_STATUS + " TEXT," + COL_MENTOR + " TEXT," + COL_MNUMBER + " TEXT," + COL_MEMAIL + " TEXT," + COL_NOTES + " TEXT)"; String addCourse = "INSERT INTO course_table VALUES(1, 'English Composition II - C456', '2018-01-01', '2018-06-30', 'plan to take', 'Mike Smith', '609-680-9090', 'mike.smith@wgu.edu', 'test')"; String addCourse2 = "INSERT INTO course_table VALUES(2, 'Critical Thinking and Logic - C168', '2018-07-01', '2018-12-31', 'plan to take', 'Mike Smith', '609-680-9090', 'mike.smith@wgu.edu', 'test')"; String addCourse3 = "INSERT INTO course_table VALUES(3, 'College Algebra - C278', '2019-01-01', '2019-06-30', 'plan to take', 'Mike Smith', '609-680-9090', 'mike.smith@wgu.edu', 'test')"; String addCourse4 = "INSERT INTO course_table VALUES(4, 'Introducation to Physics - C164', '2019-07-01', '2019-12-31', 'plan to take', 'Mike Smith', '609-680-9090', 'mike.smith@wgu.edu','test')"; String addCourse5 = "INSERT INTO course_table VALUES(5, 'IT Foundations - C393', '2019-01-01', '2019-06-30', 'plan to take', 'Mike Smith', '609-680-9090', 'mike.smith@wgu.edu', 'test')"; String addCourse6 = "INSERT INTO course_table VALUES(6, 'Network and Security - Foundations - C172', '2019-07-01', '2019-12-31', 'plan to take', 'Mike Smith', '609-680-9090', 'mike.smith@wgu.edu', 'test')"; db.execSQL("DROP TABLE IF EXISTS " + TABLE_COURSE); db.execSQL(createCourseTable); db.execSQL(addCourse); db.execSQL(addCourse2); db.execSQL(addCourse3); db.execSQL(addCourse4); db.execSQL(addCourse5); db.execSQL(addCourse6); //Assessments table create String createAssessmentsTable = "create table " + TABLE_ASSESSMENTS + " (" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_TYPE + " TEXT," + COL_NAME + " TEXT," + COL_DATE+ " TEXT)"; String addAssessment = "INSERT INTO assessments_table VALUES(1, 'Performance', 'English Comp II', '2018-06-30')"; String addAssessment2 = "INSERT INTO assessments_table VALUES(2, 'Objective', 'Critical Thinking', '2018-12-31')"; db.execSQL("DROP TABLE IF EXISTS " + TABLE_ASSESSMENTS); db.execSQL(createAssessmentsTable); db.execSQL(addAssessment); db.execSQL(addAssessment2); //Term_Courses table create String createTermCourseTable = "create table " + TABLE_TERM_COURSE + " (" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_TID + " TEXT," + COL_CID + " TEXT UNIQUE," + COL_NAME + " TEXT)"; db.execSQL("DROP TABLE IF EXISTS " + TABLE_TERM_COURSE); db.execSQL(createTermCourseTable); //Course_Assessment table create String createCourseAssessmentTable = "create table " + TABLE_COURSE_ASSESSMENTS + " (" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_CID + " TEXT UNIQUE," + COL_AID + " TEXT," + COL_NAME + " TEXT)"; db.execSQL("DROP TABLE IF EXISTS " + TABLE_COURSE_ASSESSMENTS); db.execSQL(createCourseAssessmentTable); } public boolean deleteTermData(int t) { SQLiteDatabase db = this.getWritableDatabase(); Log.d(TAG, "deleteTermData: Deleting " + t + " from" + TABLE_NAME); long result = db.delete(TABLE_NAME, COL_1 + " = " + t, null); if (result == -1) return false; else return true; } public boolean deleteAssessmentData(int t) { SQLiteDatabase db = this.getWritableDatabase(); Log.d(TAG, "deleteAssessmentData: Deleting " + t + " from" + TABLE_ASSESSMENTS); long result = db.delete(TABLE_ASSESSMENTS, COL_1 + " = " + t, null); if (result == -1) return false; else return true; } @Override public void onUpgrade(SQLiteDatabase db, int i, int i1) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + TABLE_COURSE); db.execSQL("DROP TABLE IF EXISTS " + TABLE_TERM_COURSE); db.execSQL("DROP TABLE IF EXISTS " + TABLE_ASSESSMENTS); onCreate(db); } public boolean addData(String term, String startDate, String endDate) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL_2, term); contentValues.put(COL_3, startDate); contentValues.put(COL_4, endDate); Log.d(TAG, "addData: Adding " + term + " to" + TABLE_NAME); long result = db.insert(TABLE_NAME, null, contentValues); if (result == -1) return false; else return true; } public boolean addAssessmentsData(String type, String name, String date) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL_TYPE, type); contentValues.put(COL_NAME, name); contentValues.put(COL_DATE, date); Log.d(TAG, "addData: Adding " + name + " to" + TABLE_ASSESSMENTS); long result = db.insert(TABLE_ASSESSMENTS, null, contentValues); if (result == -1) return false; else return true; } public boolean addCourse(String Title, String startDate, String endDate, String Status, String Mentor, String mNumber, String mEmail) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL_TITLE, Title); contentValues.put(COL_CSTART, startDate); contentValues.put(COL_CEND, endDate); contentValues.put(COL_STATUS, Status); contentValues.put(COL_MENTOR, Mentor); contentValues.put(COL_MNUMBER, mNumber); contentValues.put(COL_MEMAIL, mEmail); Log.d(TAG, "addData: Adding " + Title + " to" + TABLE_COURSE); long result = db.insert(TABLE_COURSE, null, contentValues); if (result == -1) return false; else return true; } public boolean addNotes(int id, String note) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COL_NOTES, note); try { int result = db.update(TABLE_COURSE, cv, "ID = ?", new String[]{String.valueOf(id)}); if (result > 0) { Log.d(TAG, "Adding Notes to " + TABLE_COURSE); return true; } } catch (SQLException e){ e.printStackTrace(); } return false; } public boolean updateData(int id, String newTerm, String newStart, String newEnd) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COL_2, newTerm); cv.put(COL_3, newStart); cv.put(COL_4, newEnd); try { int result = db.update(TABLE_NAME, cv, "ID = ?", new String[]{String.valueOf(id)}); if (result > 0) { Log.d(TAG, "updateData: Updating term in" + TABLE_NAME); return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } public boolean updateAssessment(int id, String newType, String newName, String newDate) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COL_TYPE, newType); cv.put(COL_NAME, newName); cv.put(COL_DATE, newDate); try { int result = db.update(TABLE_ASSESSMENTS, cv, "ID = ?", new String[]{String.valueOf(id)}); if (result > 0) { Log.d(TAG, "updateData: Updating assessment in" + TABLE_ASSESSMENTS); return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } public boolean updateCourse(int id, String newTitle, String newCourseStart, String newCourseEnd, String newStatus, String newMentor, String newMentorNumber, String newMentorEmail) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COL_TITLE, newTitle); cv.put(COL_CSTART, newCourseStart); cv.put(COL_CEND, newCourseEnd); cv.put(COL_STATUS, newStatus); cv.put(COL_MENTOR, newMentor); cv.put(COL_MNUMBER, newMentorNumber); cv.put(COL_MEMAIL, newMentorEmail); try { int result = db.update(TABLE_COURSE, cv, "ID = ?", new String[]{String.valueOf(id)}); if (result > 0) { Log.d(TAG, "updateData: Updating course in" + TABLE_COURSE); return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } public Cursor getTermID(String name) { SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL_2 + " = '" + name + "'"; Cursor data = db.rawQuery(query, null); return data; } public Cursor getTermData() { SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + TABLE_NAME; Cursor data = db.rawQuery(query, null); return data; } public Cursor getCourseData() { SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + TABLE_COURSE; Cursor data = db.rawQuery(query, null); return data; } public boolean addTermCourse(int termId, int courseId, String courseTitle){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COL_TID, termId); cv.put(COL_CID, courseId); cv.put(COL_NAME, courseTitle); try { int result = (int) db.insertWithOnConflict(TABLE_TERM_COURSE, null, cv, SQLiteDatabase.CONFLICT_REPLACE); if (result > 0) { Log.d(TAG, "Adding Courses " + "to " + TABLE_TERM_COURSE); return true; } } catch (SQLException e){ e.printStackTrace(); } return false; } public boolean addCourseAssessment(int courseId, int assessmentId, String assessmentTitle){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COL_CID, courseId); cv.put(COL_AID, assessmentId); cv.put(COL_NAME, assessmentTitle); try { int result = (int) db.insertWithOnConflict(TABLE_COURSE_ASSESSMENTS, null, cv, SQLiteDatabase.CONFLICT_REPLACE); if (result > 0) { Log.d(TAG, "Adding Assessments " + "to " + TABLE_COURSE_ASSESSMENTS); return true; } } catch (SQLException e){ e.printStackTrace(); } return false; } public Cursor getTermCourseData(int term) { SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + TABLE_TERM_COURSE + " WHERE " + COL_TID + "= '" + term + "'"; Cursor data = db.rawQuery(query, null); return data; } public Cursor getCourseAssessmentData(int course) { SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + TABLE_COURSE_ASSESSMENTS + " WHERE " + COL_CID + "= '" + course + "'"; Cursor data = db.rawQuery(query, null); return data; } public Cursor getAssessmentsData() { SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + TABLE_ASSESSMENTS; Cursor data = db.rawQuery(query, null); return data; } public Cursor getSingleCourse(int id) { SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + TABLE_COURSE + " WHERE " + COL_1 + " = '" + id + "'"; Cursor data = db.rawQuery(query, null); return data; } public Cursor getCourseID(String name) { SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + TABLE_COURSE + " WHERE " + COL_TITLE + " = '" + name + "'"; Cursor data = db.rawQuery(query, null); return data; } public Cursor getSingleAssessment(int id) { SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + TABLE_ASSESSMENTS + " WHERE " + COL_1 + " = '" + id + "'"; Cursor data = db.rawQuery(query, null); return data; } public Cursor getAssessmentID(String name) { SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM " + TABLE_ASSESSMENTS + " WHERE " + COL_NAME + " = '" + name + "'"; Cursor data = db.rawQuery(query, null); return data; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v1.0.1-05/30/2003 05:06 AM(java_re)-fcs // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2005.06.02 at 05:03:40 BRT // package com.citibank.latam.common.bind.impl; public class JAXBVersion { public final static java.lang.String version = "1.0.1"; }
package Pattern; import java.util.Scanner; public class pattern { public static void main(String[] args) { Scanner s= new Scanner(System.in); // TODO Auto-generated method stub int i =s.nextInt(); int j=0; int temp=1; while (j<=i) { int m=1; while(m<=j) { int n; System.out.print(temp); temp+=1; m+=1; } System.out.println(); j+=1; } } }
package edu.ncsu.csc.coffee_maker.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; /** * Controller class for the index (or front page) of CoffeeMaker. The controller * returns editrecipe.html in the /src/main/resources/templates folder. * * @author Nick Board */ @Controller public class EditRecipeController { /** * On a GET request to /editrecipe, the IndexController will return * /src/main/resources/templates/editrecipe.html. * * @param model * underlying UI model * @return contents of the page */ @GetMapping ( "/editrecipe" ) public String index ( final Model model ) { return "editrecipe"; } }
/** * @author lxm * @create_date 2019.5.3 * @description 试卷管理 * */ package com.app.web.controller; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; 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.app.service.impl.ContestPaperService; import com.code.model.Contest; import com.code.model.Contestpaper; import com.code.model.LayResponse; import com.github.pagehelper.PageInfo; import net.sf.json.JSONArray; import net.sf.json.JSONObject; @Controller public class ContestPaperController { @Resource private ContestPaperService contestpaperService; /** * @author lxm * @param Keyword: 关键字 * @param startTime: 开始时间 * @param endTime: 结束时间 * @description 查询试卷 * @return 试卷实例列表 */ @RequestMapping(value = "ContestPaper/GetAllContestPaper", method = { RequestMethod.POST }, produces = "text/html;charset=UTF-8") @ResponseBody public String GetAllContestPaper(HttpServletRequest request, HttpServletResponse response, String Keyword,String startTime,String endTime) throws Exception { String pageSize = request.getParameter("limit"); //一页多少个 String pageNumber = request.getParameter("page"); //第几页 List resultList = contestpaperService.GetAllContestPaper(Keyword,startTime,endTime,pageSize,pageNumber); JSONObject obj = new JSONObject(); JSONArray arr = JSONArray.fromObject(resultList); //获取分页插件的数据只能通过PageInfo来获取 PageInfo pInfo = new PageInfo(resultList); Long total = pInfo.getTotal(); obj.put("code", 0); obj.put("msg", "返回成功"); obj.put("count", total.intValue()); obj.put("data", arr); return obj.toString(); } /** * @author lxm * @param id: 考试id * @description 跳转至更新试卷页面 * @return 视图、试卷信息 */ @RequestMapping(value = "editcontestpaper.do", method = { RequestMethod.POST,RequestMethod.GET }, produces = "text/html;charset=UTF-8") @ResponseBody public ModelAndView EditContestPaper(HttpServletRequest request, String id) { ModelAndView mav = new ModelAndView(); mav.addObject("contestpaper", contestpaperService.GetContestPaper(id)); mav.setViewName("contestpaper-edit.jsp"); return mav; } /** * @author lxm * @param contestpaper: 试卷实例 * @description 更新试卷信息 * @return 响应状态 */ @RequestMapping(value = "ContestPaper/UpdateContestPaper", method = RequestMethod.POST, produces = "text/html;charset=UTF-8") @ResponseBody public String UpdateContest(HttpServletRequest request,Contestpaper contestpaper) { LayResponse response = new LayResponse(); response.setCode(1); if (contestpaperService.UpdateContestPaper(contestpaper) > 0) { response.setCode(0); return JSONObject.fromObject(response).toString(); } else { response.setMsg("更新失败"); return JSONObject.fromObject(response).toString(); } } /** * @author lxm * @param id: 试卷id * @description 删除试卷 * @return 响应状态 */ @RequestMapping(value = "ContestPaper/DeleteContestPaper", method = RequestMethod.POST, produces = "text/html;charset=UTF-8") @ResponseBody public String DeleteContestPaper(HttpServletRequest request, String id) { LayResponse response = new LayResponse(); response.setCode(1); if (contestpaperService.DeleteContestPaper(id) > 0) { response.setCode(0); return JSONObject.fromObject(response).toString(); } else { response.setMsg("更新失败"); return JSONObject.fromObject(response).toString(); } } /** * @author lxm * @param * @description 批量删除试卷 * @return 响应状态 */ @RequestMapping(value = "ContestPaper/DelAll", consumes = "application/json", produces = "text/html;charset=UTF-8", method = {RequestMethod.POST }) @ResponseBody public String DelAll(HttpServletRequest request, @RequestBody List<String> ids) { LayResponse response = new LayResponse(); response.setCode(1); if(contestpaperService.DeleteAllContestPaper(ids)>0){ response.setCode(0); System.out.println(JSONObject.fromObject(response).toString()); return JSONObject.fromObject(response).toString(); } else{ response.setMsg("删除失败"); return JSONObject.fromObject(response).toString(); } } }