text
stringlengths
10
2.72M
package com.pago.core.quotes.config; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class SwaggerDetailsConfiguration { @JsonProperty private String title = "quotes"; @JsonProperty private String description = ""; @JsonProperty private String resourcePackage = "com.pago.core.quotes"; }
package org.CarRental.service.rental; import org.CarRental.model.Rental; import java.util.List; /** * Created by intelcan on 14.05.17. */ public interface RentalService { List<Rental> getAllRental(); Rental getRentalById(Long id); Rental createRental(Rental rental); void deleteRental(Long id); }
class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { for(int j = 0;j < n;j++) { nums1[m + j] = nums2[j]; sort(nums1, m + j); } } public int[] sort(int[] nums1,int p){ for(int k = p;k > 0;k--){ if(nums1[k] < nums1[k-1]){ int temp = nums1[k]; nums1[k] = nums1[k-1]; nums1[k-1] = temp; }else { break; } } return nums1; } } public class MyTest { public static void main(String[] args) { int []nums1 = {1,4,3,0,0,0}; int []nums2 = {2,5,6}; Solution sol = new Solution(); sol.merge(nums1,3,nums2,3); } }
package org.valdi.entities.disguise; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Set; import org.bukkit.Material; import org.valdi.entities.management.VersionHelper; /** * Represents a disguise as a falling block. * * @since 5.1.1 * @author RobinGrether */ public class FallingBlockDisguise extends ObjectDisguise { private Material material; private int data; private boolean onlyBlockCoordinates; /** * Creates an instance.<br> * The default material is {@link Material#STONE} * * @since 5.1.1 */ public FallingBlockDisguise() { this(Material.STONE); } /** * Creates an instance. * * @since 5.1.1 * @param material the material * @throws IllegalArgumentException if the material is not a block */ public FallingBlockDisguise(Material material) { this(material, 0); } /** * Creates an instance. * * @since 5.2.2 * @param material the material * @param data the block data * @throws IllegalArgumentException if the material is not a block, or if the data is negative */ public FallingBlockDisguise(Material material, int data) { this(material, data, false); } /** * Creates an instance. * * @since 5.4.1 * @param material the material * @param data the block data * @param onlyBlockCoordinates makes the disguise appear on block coordinates only, so it looks like an actual block that you can't target * @throws IllegalArgumentException if the material is not a block, or if the data is negative */ public FallingBlockDisguise(Material material, int data, boolean onlyBlockCoordinates) { super(DisguiseType.FALLING_BLOCK); if(!material.isBlock()) { throw new IllegalArgumentException("Material must be a block"); } if(INVALID_MATERIALS.contains(material)) { throw new IllegalArgumentException("Material is invalid! Disguise would be invisible."); } if(data < 0) { throw new IllegalArgumentException("Data must be positive"); } this.material = material; this.data = data; this.onlyBlockCoordinates = onlyBlockCoordinates; } /** * Gets the material. * * @since 5.1.1 * @return the material */ public Material getMaterial() { return material; } /** * Sets the material.<br> * This also resets the data to 0. * * @since 5.1.1 * @param material the material * @throws IllegalArgumentException if the material is not a block */ public void setMaterial(Material material) { if(!material.isBlock()) { throw new IllegalArgumentException("Material must be a block"); } if(INVALID_MATERIALS.contains(material)) { throw new IllegalArgumentException("Material is invalid! Disguise would be invisible."); } this.material = material; this.data = 0; } /** * Gets the block data. * * @since 5.2.2 * @return the block data */ public int getData() { return data; } /** * Sets the block data. * * @since 5.2.2 * @param data the block data */ public void setData(int data) { if(data < 0) { throw new IllegalArgumentException("Data must be positive"); } this.data = data; } /** * Indicates whether this disguise may appear only on block coordinates. * * @since 5.4.1 * @return <code>true</code>, if this disguise may appear only on block coordinates */ public boolean onlyBlockCoordinates() { return onlyBlockCoordinates; } /** * Sets whether this disguise may appear only on block coordinates. * * @since 5.4.1 * @param onlyBlockCoordinates makes this disguise appear on block coordinates only */ public void setOnlyBlockCoordinates(boolean onlyBlockCoordinates) { this.onlyBlockCoordinates = onlyBlockCoordinates; } /** * {@inheritDoc} */ public String toString() { return String.format("%s; material=%s; material-data=%s; %s", super.toString(), material.name().toLowerCase(Locale.ENGLISH).replace('_', '-'), data, onlyBlockCoordinates ? "block-coordinates" : "all-coordinates"); } /** * A set containing all invalid materials.<br> * These materials are <em>invalid</em> because the associated disguise would be invisible. * * @since 5.7.1 */ public static final Set<Material> INVALID_MATERIALS; static { Set<Material> tempSet = new HashSet<Material>(Arrays.asList(Material.AIR, Material.BARRIER, Material.BED_BLOCK, Material.CHEST, Material.COBBLE_WALL, Material.ENDER_CHEST, Material.ENDER_PORTAL, Material.LAVA, Material.MELON_STEM, Material.PISTON_MOVING_PIECE, Material.PORTAL, Material.PUMPKIN_STEM, Material.SIGN_POST, Material.SKULL, Material.STANDING_BANNER, Material.STATIONARY_LAVA, Material.STATIONARY_WATER, Material.TRAPPED_CHEST, Material.WALL_BANNER, Material.WALL_SIGN, Material.WATER)); if(VersionHelper.require1_9()) { tempSet.add(Material.END_GATEWAY); } if(VersionHelper.require1_10()) { tempSet.add(Material.STRUCTURE_VOID); } if(VersionHelper.require1_11()) { tempSet.addAll(Arrays.asList(Material.BLACK_SHULKER_BOX, Material.BLUE_SHULKER_BOX, Material.BROWN_SHULKER_BOX, Material.CYAN_SHULKER_BOX, Material.GRAY_SHULKER_BOX, Material.GREEN_SHULKER_BOX, Material.LIGHT_BLUE_SHULKER_BOX, Material.LIME_SHULKER_BOX, Material.MAGENTA_SHULKER_BOX, Material.ORANGE_SHULKER_BOX, Material.PINK_SHULKER_BOX, Material.PURPLE_SHULKER_BOX, Material.RED_SHULKER_BOX, Material.SILVER_SHULKER_BOX, Material.WHITE_SHULKER_BOX, Material.YELLOW_SHULKER_BOX)); } INVALID_MATERIALS = Collections.unmodifiableSet(tempSet); Set<String> parameterSuggestions = new HashSet<String>(); for(Material material : Material.values()) { if(material.isBlock() && !INVALID_MATERIALS.contains(material)) { parameterSuggestions.add(material.name().toLowerCase(Locale.ENGLISH).replace('_', '-')); } } Subtypes.registerParameterizedSubtype(FallingBlockDisguise.class, "setMaterial", "material", Material.class, Collections.unmodifiableSet(parameterSuggestions)); Subtypes.registerParameterizedSubtype(FallingBlockDisguise.class, "setData", "material-data", int.class); Subtypes.registerSubtype(FallingBlockDisguise.class, "setOnlyBlockCoordinates", true, "block-coordinates"); Subtypes.registerSubtype(FallingBlockDisguise.class, "setOnlyBlockCoordinates", false, "all-coordinates"); } }
package com.example.baoding6.myapplication; public class MessageActivity { }
/* * 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 analizador; import java.io.PrintStream; /** * * @author Neto */ public class Generador { public static final int ADD_OP = 1; public static final int SUBS_OPP = 2; public static final int ASSIG_OP = 3; public static final int IF = 4; public static final int ASIG = 5; public static final int GOTO = 6; public static final int LABEL = 7; public static final int PRINTLN = 8; public static final int GREATER_OP=9; public static final int LESS_OP=10; public static final int LESS_EQUAL_OP=11; public static final int GREATER_EQUAL_OP=12; public static final int EQUAL_OP=13; public static final int NOT_EQUAL_OP=14; public static final int NOT=15; public static final int AND=16; public static final int OR=17; public static final int READSTRING=18; public static final int READFEATVAL=19; public static final int GETFEATURES=20; public static final int PRINTGRAPH=21; public static final int GNGROUP=22; public static int contadorTemp = 0; public static int contadorEtiq = 0; protected static PrintStream out = System.out; public static String gc(int operacion, String arg1, String arg2, String resultado) { switch (operacion) { case ADD_OP: return " " + resultado + " = " + arg1 + " + " + arg2 + "\n"; case SUBS_OPP: return " " + resultado + " = " + arg1 + " - " + arg2 + "\n"; case ASSIG_OP: return " " + resultado + " = " + arg1 + "\n"; case IF: return " si " + arg1 + " falso salta " + resultado + "\n"; case GOTO: return "salta " + resultado + "\n"; case ASIG: return " " + resultado + " = " + arg1 + "\n"; case LABEL: return resultado + ":\n"; case PRINTLN: return " PRINTLN " + resultado + "\n"; case PRINTGRAPH: return " PRINTGRAPH " + resultado + "\n"; case GNGROUP: return " GENERATEGROUP " + resultado + "\n"; case GETFEATURES: return " GETFEATURES " + resultado + "\n"; case GREATER_OP: return " " + resultado + " = " + arg1 + " > " + arg2 + "\n"; case LESS_OP: return " " + resultado + " = " + arg1 + " < " + arg2 + "\n"; case LESS_EQUAL_OP: return " " + resultado + " = " + arg1 + " <= " + arg2 + "\n"; case GREATER_EQUAL_OP: return " " + resultado + " = " + arg1 + " >= " + arg2 + "\n"; case EQUAL_OP: return " " + resultado + " = " + arg1 + " == " + arg2 + "\n"; case NOT_EQUAL_OP: return " " + resultado + " = " + arg1 + " != " + arg2 + "\n"; case NOT: return " " + resultado + " = " + "NOT" + arg1 + arg2 + "\n"; case AND: return " " + resultado + " = " + arg1 + " && " + arg2 + "\n"; case OR: return " " + resultado + " = " + arg1 + " %% " + arg2 + "\n"; case READSTRING: return " " + resultado + " = InputString \n"; case READFEATVAL: return " " + resultado + " = InputInt \n"; default: return "Error en la generación de código\n"; } } public static String nuevaTemp() { return "t" + contadorTemp++; } public static String nuevaEtiq() { return "L" + contadorEtiq++; } }
package cn.edu.cqut.mapper; import cn.edu.cqut.entity.Cusflew; import cn.edu.cqut.entity.Record; import cn.edu.cqut.entity.Customer; import java.util.List; import org.apache.ibatis.annotations.Many; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.mapping.FetchType; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.toolkit.Constants; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * <p> * Mapper 接口 * </p> * * @author CQUT SE 2020 * @since 2020-06-11 */ public interface CusflewMapper extends BaseMapper<Cusflew> { /* * @Select("select * from Cusflew ${ew.customSqlSegment}")// * ${ew.customSqlSegment,sql语句的条件字段 * * @Results({ * * @Result(column = "cusNo", property = "cusNo"), * * @Result(column = "cusNo", property = "cusNo", many = @Many( select = * "cn.edu.cqut.mapper.CustomerMapper.selectOrderCustomerNoUpSixMonths", * fetchType = FetchType.EAGER)) }) public Page<Record> * selectRecordswithCusName( Page<Record> page, * * @Param(Constants.WRAPPER) QueryWrapper<Record> queryWrapper ); */ @Select("select * from customer where cusNo in (select orderCustomerNo from sales group by orderCustomerNo HAVING datediff(CURRENT_TIMESTAMP,max(orderTime))>180)") public List<Customer> selectOrCustomersOverSixMonths(); @Select("select * from cusflew where cusNo=#{cusNo}") public List<Cusflew> isExitCusNo(String cusNo); @Select("select * from (select * from customer where cusNo in (SELECT cusNo FROM cusflew where cfState='确定流失')) as lost ${ew.customSqlSegment}") public Page<Customer> selectLost( Page<Customer> page, @Param(Constants.WRAPPER) QueryWrapper<Customer> queryWrapper ); }
package edu.neu.ccis.cs5010.assignment7; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; public class SkiDataProcessor { private BlockingQueue<int[]> skierQueue; private BlockingQueue<Integer> liftQueue; private BlockingQueue<int[]> hourQueue; private Map<Integer, Skier> skierMap; private Map<Integer, Lift> liftMap; private Map<Integer, Hour> hourMap; public SkiDataProcessor() { this.skierMap = new HashMap<>(); this.liftMap = new TreeMap<>(); this.hourMap = new TreeMap<>(); this.skierQueue = new LinkedBlockingDeque<>(); this.liftQueue = new LinkedBlockingDeque<>(); this.hourQueue = new LinkedBlockingDeque<>(); } public void process(String file) { try { InputStream inputStream = new FileInputStream(file); Reader rder = new InputStreamReader(inputStream, "UTF-8"); BufferedReader reader = new BufferedReader(rder); String line = reader.readLine(); while((line = reader.readLine()) != null) { String[] args = line.split(","); int skierId = Integer.parseInt(args[2]); int liftId = Integer.parseInt(args[3]); int time = Integer.parseInt(args[4]); int section = getSection(time); checkSkier(skierId, liftId); checkLift(liftId); checkSection(section, liftId); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void process(String file, int flag) { try { InputStream inputStream = new FileInputStream(file); Reader rder = new InputStreamReader(inputStream, "UTF-8"); BufferedReader reader = new BufferedReader(rder); String line = reader.readLine(); while((line = reader.readLine()) != null) { String[] args = line.split(","); int skierId = Integer.parseInt(args[2]); int liftId = Integer.parseInt(args[3]); int time = Integer.parseInt(args[4]); int section = getSection(time); int[] array = new int[] {skierId, liftId}; int[] array2 = new int[] {section, liftId}; skierQueue.add(array); liftQueue.add(liftId); hourQueue.add(array2); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void output(int flag) { SkierThread skierThread = new SkierThread(skierQueue); Thread thread1 = new Thread(skierThread); LiftThread liftThread = new LiftThread(liftQueue); Thread thread2 = new Thread(liftThread); HourThread hourThread = new HourThread(hourQueue); Thread thread3 = new Thread(hourThread); Long time = System.currentTimeMillis(); thread1.start(); thread2.start(); thread3.start(); System.out.print("Concurrent Solution : " + (System.currentTimeMillis() - time) + " ms"); } public void output() { String skierHeader = "SkierID, Vertical"; String liftHeader = "LiftID, Number of Rides"; String hourHeader = "LiftID, Number of Rides"; Long time = System.currentTimeMillis(); outputSkier(skierHeader); outputLift(liftHeader); outputHour(hourHeader); System.out.println("Sequential Solution :" + (System.currentTimeMillis() - time) + " ms"); } private void outputSkier(String header) { File file = new File("skier.csv"); List<Map.Entry<Integer, Skier>> list = new ArrayList<>(skierMap.entrySet()); Collections.sort(list, new Comparator<Map.Entry<Integer, Skier>>() { @Override public int compare(Map.Entry<Integer, Skier> o1, Map.Entry<Integer, Skier> o2) { return o2.getValue().getVertical() - o1.getValue().getVertical(); } }); try { BufferedWriter writer = Files.newBufferedWriter(Paths.get(file.getPath())); writer.write(header); writer.write("\n"); Iterator<Map.Entry<Integer, Skier>> iterator = list.iterator(); int count = 0; while(iterator.hasNext()) { StringBuilder stringBuilder = new StringBuilder(); Map.Entry<Integer, Skier> entry = iterator.next(); int id = entry.getKey(); int vertical = entry.getValue().getVertical(); stringBuilder.append(id); stringBuilder.append(" "); stringBuilder.append(vertical); writer.write(stringBuilder.toString()); writer.write("\n"); count++; if(count == 100) break; } writer.close(); } catch (IOException e) { e.printStackTrace(); } } private void outputLift(String header) { File file = new File("lift.csv"); try { BufferedWriter writer = Files.newBufferedWriter(Paths.get(file.getPath())); writer.write(header); writer.write("\n"); Iterator<Map.Entry<Integer, Lift>> iterator = liftMap.entrySet().iterator(); while(iterator.hasNext()) { StringBuilder stringBuilder = new StringBuilder(); Map.Entry<Integer, Lift> entry = iterator.next(); int id = entry.getKey(); int rides = entry.getValue().getRides(); stringBuilder.append(id); stringBuilder.append(","); stringBuilder.append(rides); writer.write(stringBuilder.toString()); writer.write("\n"); } writer.close(); } catch (IOException e) { e.printStackTrace(); } } private void outputHour(String header) { File file = new File("hour.csv"); //List<Map.Entry<String, Hour>> list = new ArrayList<>(hourMap.entrySet()); Iterator<Map.Entry<Integer, Hour>> iterator = hourMap.entrySet().iterator(); try { BufferedWriter writer = Files.newBufferedWriter(Paths.get(file.getPath())); while(iterator.hasNext()) { Map.Entry<Integer, Hour> entry = iterator.next(); writer.write("Hour" + entry.getValue().getHour()); writer.write("\n"); writer.write(header); writer.write("\n"); Hour hour = entry.getValue(); Map<Integer, Integer> map = hour.getMap(); List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() { @Override public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return o2.getValue() - o1.getValue(); } }); int count = 0; Iterator<Map.Entry<Integer, Integer>> iterator1 = list.iterator(); while(iterator1.hasNext()) { Map.Entry<Integer, Integer> entry1 = iterator1.next(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(entry1.getKey()); stringBuilder.append(" "); stringBuilder.append(entry1.getValue()); writer.write(stringBuilder.toString()); writer.write("\n"); count++; if(count == 10) break; } writer.write("\n"); writer.write("\n"); } writer.close(); } catch (IOException e) { e.printStackTrace(); } } private void checkSkier(int skierId, int liftId) { if(skierMap.containsKey(skierId)) { Skier skier = skierMap.get(skierId); skier.increaseVertical(liftId); skierMap.put(skierId, skier); } else { Skier skier = new Skier(skierId); skier.increaseVertical(liftId); skierMap.put(skierId, skier); } } private void checkLift(int liftId) { if(liftMap.containsKey(liftId)) { Lift lift = liftMap.get(liftId); lift.addRide(); liftMap.remove(liftId); liftMap.put(liftId, lift); } else { Lift lift = new Lift(liftId); lift.addRide(); liftMap.put(liftId, lift); } } private void checkSection(int section, int liftId) { if(hourMap.containsKey(section)) { Hour hour = hourMap.get(section); hour.addLift(liftId); } else { Hour hour = new Hour(section); hour.addLift(liftId); hourMap.put(section, hour); } } private int getSection(int time) { if(time <= 60) { return 1; } else if(time <= 120) { return 2; } else if(time <= 180) { return 3; } else if(time <= 240) { return 4; } else if(time <= 300) { return 5; } else { return 6; } } public static void main(String[] args) { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); String line; if((line=bufferedReader.readLine()) != null) { SkiDataProcessor skiDataProcessor = new SkiDataProcessor(); skiDataProcessor.process(line); skiDataProcessor.output(); int concurrent = 1; skiDataProcessor.process(line, concurrent); skiDataProcessor.output(concurrent); } else { throw new NullPointerException(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package calTracker.demo.calTracker.Repos; import calTracker.demo.calTracker.Models.Snack; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface SnackRepo extends JpaRepository<Snack,Integer> { List<Snack> findByDate(String date); }
package com.csc.capturetool.myapplication.base; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import com.csc.capturetool.myapplication.http.listener.LifeCycleObserver; import com.csc.capturetool.myapplication.utils.DialogUtils; import com.csc.capturetool.myapplication.utils.PermissionUtils; /** * Created by SirdarYangK on 2018/11/2 * des: */ public abstract class BaseFragment<V, T extends BasePresenter<V>> extends Fragment { protected T mPresenter; private static final String STATE_SAVE_IS_HIDDEN = "state_save_is_hidden"; private LifeCycleObserver observer; private Dialog mIosLoading; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPresenter = createPresenter(); if (mPresenter != null) { mPresenter.attachView((V) this); } if (savedInstanceState != null) { boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN); FragmentTransaction ft = getFragmentManager().beginTransaction(); if (isSupportHidden) { ft.hide(this); } else { ft.show(this); } ft.commitAllowingStateLoss(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden()); } protected abstract T createPresenter(); @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults); super.onRequestPermissionsResult(requestCode, permissions, grantResults); } public void setFragmentLifeCycleObserver(LifeCycleObserver observer) { this.observer = observer; } @Override public void onDestroy() { super.onDestroy(); if (observer != null) { observer.onDestroy(); } } public void showProgressBar() { if (mIosLoading == null || !mIosLoading.isShowing()) { mIosLoading = DialogUtils.showIosLoading(getContext(), new DialogUtils.OnKeyBackListener() { @Override public void onKeyBack() { } }); } } public void dismissProgressBar() { if (mIosLoading != null && mIosLoading.isShowing()) { mIosLoading.dismiss(); } } }
package entity; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; public class Year extends Entity { public String name; public Year(ResultSet rs) throws SQLException { this.name = rs.getString(1); } public static List<Year> selectAllYears() throws SQLException { return Entity.select("SELECT * FROM Years;", Year::new); } }
/* * 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 agh.musicapplication.mappservices; import agh.musicapplication.mappdao.interfaces.MUserBandRepositoryInterface; import agh.musicapplication.mappmodel.MBand; import agh.musicapplication.mappmodel.MUser; import agh.musicapplication.mappservices.interfaces.BandFindServiceInterface; import com.google.common.collect.Lists; import java.util.List; import javax.inject.Inject; import javax.transaction.Transactional; import org.springframework.stereotype.Service; /** * * @author ag */ @Service @Transactional public class BandFindService implements BandFindServiceInterface { @Inject MUserBandRepositoryInterface ubri; @Override public List<MBand> findLatelyRatedBands(MUser user, int howMany) { List<MBand> allBands = ubri.getAllRatedBandsOfSomeUser(user); List<MBand> reversed = Lists.reverse(allBands); List<MBand> newList; if (reversed.size() >= 10) { newList = reversed.subList(0, 9); } else { newList = reversed.subList(0, reversed.size()); } return newList; } }
package kg02a; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Tweet2 { private int tweetNo; private String twitterID; private String name; private Date tweetTime; private String text; public Tweet2() { } public void setTweetNo(int tweetNo) { this.tweetNo = tweetNo; } public void setTwitterID(String twitterID) { this.twitterID = twitterID; } public void setName(String name) { this.name = name; } public void setTweetTime(Date tweetTime) { this.tweetTime = tweetTime; } public void setText(String text) { this.text = text; } public void setTweetTime(String tm) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm"); Date date = sdf.parse(tm); this.tweetTime = date; } catch (ParseException e) { e.printStackTrace(); } } public Date getTime() { return tweetTime; } public void printTweet() { System.out.println(tweetNo + ":" + twitterID + "(" + name + ")\n" + tweetTime + "\n" + text); } }
package com.mc.library.utils; import android.text.TextUtils; import android.view.Gravity; import android.widget.Toast; import com.mc.library.Library; /** * Created by dinghui on 2016/10/27. * Toast工具类 */ public class ToastUtil { private static Toast sToast; private static Toast sLongToast; private static Toast sCenterToast; private ToastUtil() { /* Cannot be instantiated! */ throw new UnsupportedOperationException("Cannot be instantiated!"); } public static void showToast(CharSequence text) { if (TextUtils.isEmpty(text)) return; if (sToast == null) { sToast = Toast.makeText(Library.sInstance, text, Toast.LENGTH_SHORT); } sToast.setText(text); sToast.show(); } public static void showLongToast(CharSequence text) { if (sLongToast == null) { sLongToast = Toast.makeText(Library.sInstance, text, Toast.LENGTH_LONG); } sLongToast.setText(text); sLongToast.show(); } public static void cancelToast() { if (sToast != null) { sToast.cancel(); } } public static void cancelLongToast() { if (sLongToast != null) { sLongToast.cancel(); } } public static void showCenterToast(CharSequence text) { if (TextUtils.isEmpty(text)) return; if (sCenterToast == null) { sCenterToast = Toast.makeText(Library.sInstance, text, Toast.LENGTH_LONG); sCenterToast.setGravity(Gravity.CENTER, sCenterToast.getXOffset() / 2, sCenterToast.getYOffset() / 2); } sCenterToast.show(); } }
package com.example.demo.model; public class NotificationEmail { }
package hr.bosak_turk.planetdemo.pojo; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; import hr.bosak_turk.planetdemo.pojo.Content; import hr.bosak_turk.planetdemo.pojo.Embedded; import hr.bosak_turk.planetdemo.pojo.Excerpt; import hr.bosak_turk.planetdemo.pojo.Title; public class Pojo implements Parcelable { @SerializedName("excerpt") @Expose private Excerpt excerpt; @SerializedName("id") @Expose private Integer id; @SerializedName("title") @Expose private Title title; @SerializedName("author") @Expose private Integer author; @SerializedName("date") @Expose private String date; @SerializedName("_embedded") @Expose private Embedded embedded; @SerializedName("categories") @Expose private List<Integer> categories; @SerializedName("status") @Expose private String status; @SerializedName("content") @Expose private Content content; @SerializedName("link") @Expose private String link; public String getLink() { return link; } public void setLink(String link) { this.link = link; } public Content getContent() { return content; } public void setContent(Content content) { this.content = content; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List<Integer> getCategories() { return categories; } public void setCategories(List<Integer> categories) { this.categories = categories; } public Embedded getEmbedded() { return embedded; } public void setEmbedded(Embedded embedded) { this.embedded = embedded; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Integer getAuthor() { return author; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Title getTitle() { return title; } public void setTitle(Title title) { this.title = title; } public Excerpt getExcerpt() { return excerpt; } protected Pojo(Parcel in) { excerpt = (Excerpt) in.readValue(Excerpt.class.getClassLoader()); id = in.readByte() == 0x00 ? null : in.readInt(); title = (Title) in.readValue(Title.class.getClassLoader()); author = in.readByte() == 0x00 ? null : in.readInt(); date = in.readString(); embedded = (Embedded) in.readValue(Embedded.class.getClassLoader()); if (in.readByte() == 0x01) { categories = new ArrayList<Integer>(); in.readList(categories, Integer.class.getClassLoader()); } else { categories = null; } status = in.readString(); content = (Content) in.readValue(Content.class.getClassLoader()); link = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeValue(excerpt); if (id == null) { dest.writeByte((byte) (0x00)); } else { dest.writeByte((byte) (0x01)); dest.writeInt(id); } dest.writeValue(title); if (author == null) { dest.writeByte((byte) (0x00)); } else { dest.writeByte((byte) (0x01)); dest.writeInt(author); } dest.writeString(date); dest.writeValue(embedded); if (categories == null) { dest.writeByte((byte) (0x00)); } else { dest.writeByte((byte) (0x01)); dest.writeList(categories); } dest.writeString(status); dest.writeValue(content); dest.writeString(link); } @SuppressWarnings("unused") public static final Parcelable.Creator<Pojo> CREATOR = new Parcelable.Creator<Pojo>() { @Override public Pojo createFromParcel(Parcel in) { return new Pojo(in); } @Override public Pojo[] newArray(int size) { return new Pojo[size]; } }; }
import java.util.Scanner; public class homework_3{ public static void main(String[] args){ System.out.println("name:cck, number:20151681310210"); System.out.println("welcome to java"); Scanner input = new Scanner(System.in); System.out.println("please enter a integer"); MyInteger test = new MyInteger(input.nextInt()); System.out.println("the test's value is "+test.get()); System.out.println("the test's value is Even? "+test.isEven()); System.out.println("the test's value is Odd? "+test.isOdd()); System.out.println("the test's value is Prime? "+test.isPrime()); int test1 = 5; System.out.println("5 is Even? "+test.isEven(test1)); System.out.println("5 is Odd? "+test.isOdd(test1)); System.out.println("5 is Prime? "+test.isPrime(test1)); MyInteger test2 = new MyInteger(5); System.out.println("5 is Even? "+test.isEven(test2)); System.out.println("5 is Odd? "+test.isOdd(test2)); System.out.println("5 is Prime? "+test.isPrime(test2)); System.out.println("is 5 equal with the test'value? "+test.equals(test1)); System.out.println("is 5 equal with the test'value? "+test.equals(test2)); char[] test3 = {'2','1','0','a'}; System.out.println("the test3 is "+test.parseInt(test3)); String test4 = 210+""; System.out.println("the test4 is "+test.parseInt(test4)); } } class MyInteger{ private int value; MyInteger(int save){ value = save; } int get(){ return value; } boolean isEven(){ if(value%2==0){ return true; }else{ return false; } } boolean isOdd(){ if(value%2!=0){ return true; }else{ return false; } } boolean isPrime(){ for(int i = 2;i<value;++i){ if(value%i==0){ return false; } } return true; } boolean isEven(int give){ if(give%2==0){ return true; }else{ return false; } } boolean isOdd(int give){ if(give%2!=0){ return true; }else{ return false; } } boolean isPrime(int give){ for(int i = 2;i<give;++i){ if(give%i==0){ return false; } } return true; } boolean isEven(MyInteger give){ if(give.value%2==0){ return true; }else{ return false; } } boolean isOdd(MyInteger give){ if(give.value%2!=0){ return true; }else{ return false; } } boolean isPrime(MyInteger give){ for(int i = 2;i<give.value;++i){ if(give.value%i==0){ return false; } } return true; } boolean equals(int give){ if(give==value){ return true; }else{ return false; } } boolean equals(MyInteger give){ if(give.value==value){ return true; }else{ return false; } } static int parseInt(char[] give){ int count = 0; for(; give [count]<='9'&&give[count]>='0';++count){ } int result = 0; for(int i=count,j=0;i>0;--i,++j){ int number = give[j]-'0'; result += number*Math.pow(10,i-1); } return result; } static int parseInt(String give){ int result = Integer.parseInt(give); return result; } }
/* * Copyright 2002-2019 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.http.converter; import java.io.IOException; import org.junit.jupiter.api.Test; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import static org.assertj.core.api.Assertions.assertThat; /** * Test-case for AbstractHttpMessageConverter. * * @author Arjen Poutsma * @author Rossen Stoyanchev */ public class HttpMessageConverterTests { @Test public void canRead() { MediaType mediaType = new MediaType("foo", "bar"); HttpMessageConverter<MyType> converter = new MyHttpMessageConverter<>(mediaType); assertThat(converter.canRead(MyType.class, mediaType)).isTrue(); assertThat(converter.canRead(MyType.class, new MediaType("foo", "*"))).isFalse(); assertThat(converter.canRead(MyType.class, MediaType.ALL)).isFalse(); } @Test public void canReadWithWildcardSubtype() { MediaType mediaType = new MediaType("foo"); HttpMessageConverter<MyType> converter = new MyHttpMessageConverter<>(mediaType); assertThat(converter.canRead(MyType.class, new MediaType("foo", "bar"))).isTrue(); assertThat(converter.canRead(MyType.class, new MediaType("foo", "*"))).isTrue(); assertThat(converter.canRead(MyType.class, MediaType.ALL)).isFalse(); } @Test public void canWrite() { MediaType mediaType = new MediaType("foo", "bar"); HttpMessageConverter<MyType> converter = new MyHttpMessageConverter<>(mediaType); assertThat(converter.canWrite(MyType.class, mediaType)).isTrue(); assertThat(converter.canWrite(MyType.class, new MediaType("foo", "*"))).isTrue(); assertThat(converter.canWrite(MyType.class, MediaType.ALL)).isTrue(); } @Test public void canWriteWithWildcardInSupportedSubtype() { MediaType mediaType = new MediaType("foo"); HttpMessageConverter<MyType> converter = new MyHttpMessageConverter<>(mediaType); assertThat(converter.canWrite(MyType.class, new MediaType("foo", "bar"))).isTrue(); assertThat(converter.canWrite(MyType.class, new MediaType("foo", "*"))).isTrue(); assertThat(converter.canWrite(MyType.class, MediaType.ALL)).isTrue(); } private static class MyHttpMessageConverter<T> extends AbstractHttpMessageConverter<T> { private MyHttpMessageConverter(MediaType supportedMediaType) { super(supportedMediaType); } @Override protected boolean supports(Class<?> clazz) { return MyType.class.equals(clazz); } @Override protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { throw new AssertionError("Not expected"); } @Override protected void writeInternal(T t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { throw new AssertionError("Not expected"); } } private static class MyType { } }
package ro.ase.cts.simpleFactory.program; import ro.ase.cts.simpleFactory.clase.FactoryPersonal; import ro.ase.cts.simpleFactory.clase.PersonalSpital; import ro.ase.cts.simpleFactory.clase.TipPersonal; public class Program { public static void main(String[]args) { FactoryPersonal factoryPersonal=new FactoryPersonal(); PersonalSpital asistent=factoryPersonal.createPersonal(TipPersonal.Asistent, "David"); PersonalSpital medic=factoryPersonal.createPersonal(TipPersonal.Medic, "Ioana"); System.out.println(asistent); System.out.println(medic); } }
package com.trump.auction.web.util; public enum EnumSmsCodeType { Register(1,"Register"), ForgetPwd(2,"ForgetPwd"), CheckPhone(3,"CheckPhone"), BindPhone(4,"BindPhone"), SmsLogin(5,"SmsLogin"); private final Integer type; public Integer getType() { return type; } private final String text; public String getText() { return text; } EnumSmsCodeType(Integer type,String text){ this.type = type; this.text = text; } public static String getTypeText(Integer type) { String text = null; for (EnumSmsCodeType codeType : values()) { if (type.equals(codeType.getType())) { text = codeType.getText(); break; } } return text; } }
package Section_1_3; /* ID: donggun1 LANG: JAVA TASK: milk2 */ //package Section_1_3; import java.io.*; import java.util.*; public class milk2 { public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub Scanner in = new Scanner(new FileReader(new File("milk2.in"))); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("milk2.out"))); int n = in.nextInt(); HashSet<Integer> allnums = new HashSet<Integer>(); int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for(int i = 0;i<n;i++) { int s = in.nextInt(); int e = in.nextInt(); min = Math.min(min, s); max = Math.max(max, e); for(int j = s;j<e;j++) { allnums.add(j); } } String turn = ""; for(int i =min;i<max;i++) { if(allnums.contains(i)) { turn+="1"; } else { turn+="0"; } } //System.out.println(turn); String[] ones = turn.split("0"); String[] zeroes = turn.split("1"); int continuous = 0; int idle = 0; for(int i = 0;i<ones.length;i++) { continuous = Math.max(continuous,ones[i].length()); } for(int i = 0;i<zeroes.length;i++) { idle = Math.max(idle, zeroes[i].length()); } out.println(continuous+" "+ idle); out.close(); } }
package com.whenling.castle.repo.domain; import java.util.List; import java.util.Set; public interface Tree<T extends Hierarchical<T>> { List<Node<T>> getRoots(); Set<T> getChecked(); void setChecked(Set<T> checked); boolean isCheckable(); boolean isExpandAll(); void makeCheckable(); void makeExpandAll(); Class<?> getNodeView(); void setNodeView(Class<?> viewClass); }
package com.tsuro.tile; import java.util.Set; import lombok.NonNull; /** * An IBoardState is one of: - {@link EmptySquare} - {@link TsuroTile} and represents a Tile for a * game. All implementations of this interface must be immutable. */ public interface ITile { /** * Returns a new instance of the Tile rotated by 90 degrees clockwise. * * @return new rotated tile by 90 degrees */ ITile rotate(); /** * Finds {@link Location} that's connected to the {@param start} {@link Location}. * * @param start {@link Location} you start query at * @return end {@link Location} connected to {@param start} */ Location internalConnection(@NonNull Location start); /** * Gets all the {@link Path}s within a {@link ITile}. * * @return a set of the {@link Path}s that this {@link ITile} contains */ Set<Path> getPaths(); /** * Determines if the given tile has all the same paths as this tile. The tiles are only strictly * equal if they're in the same orientation. * * @param o The other tile to compare to * @return Whether the tiles are strictly equal */ default boolean strictEqual(@NonNull ITile o) { return this.getPaths().equals(o.getPaths()); } /** * Two tiles are equal if they can be transformed into each other through rotation. */ @Override boolean equals(Object o); /** * Determines if this tile is empty. */ boolean isEmpty(); }
package com.book.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.book.DAO.BookDAO; import com.book.model.Book; public class EditBook extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String id = request.getParameter("id"); Book existingBook = BookDAO.getBookById(id); if (existingBook == null) { out.println("Not found book with id"); out.close(); return; } RequestDispatcher dispatcher = request.getRequestDispatcher("WEB-INF/Form.jsp"); request.setAttribute("book", existingBook); dispatcher.forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String id = request.getParameter("id"); String name = request.getParameter("name"); String author = request.getParameter("author"); Book updatedBook = new Book(name, author); int status = BookDAO.updateBook(id, updatedBook); if (status == 1) { response.sendRedirect("/Book/"); return; } out.println("Cannot add book"); out.close(); } public EditBook() { super(); } private static final long serialVersionUID = 1L; }
package dtioverlay.utils; import java.io.IOException; /** * Created by IntelliJ IDEA. * User: bennett * Date: Dec 6, 2005 * Time: 4:44:08 PM * To change this template use Options | File Templates. */ public class RGB { public byte r, g, b; public RGB(byte R, byte G, byte B) { r= R; g=G; b=B; } public static RGB read(LEFileReader fp) throws IOException { byte r,g,b; r = (byte)fp.readByte(); g = (byte)fp.readByte(); b = (byte)fp.readByte(); return new RGB(r,g,b); } }
package com.esrinea.dotGeo.tracking.service.component.sensorLiveFeed; import com.esrinea.dotGeo.tracking.model.component.sensorLiveFeed.dao.SensorLiveFeedDAO; import com.esrinea.dotGeo.tracking.model.component.sensorLiveFeed.entity.SensorLiveFeed; import com.esrinea.dotGeo.tracking.service.common.service.AbstractService; public class SensorLiveFeedServiceImpl extends AbstractService<SensorLiveFeed> implements SensorLiveFeedService { private SensorLiveFeedDAO sensorLiveFeedDAO; public SensorLiveFeedServiceImpl(SensorLiveFeedDAO sensorLiveFeedDAO) { super(sensorLiveFeedDAO); this.sensorLiveFeedDAO = sensorLiveFeedDAO; } @Override public SensorLiveFeed find(String sensorValue) { return sensorLiveFeedDAO.find(sensorValue); } }
package com.ifeng.recom.mixrecall.core.cache.preload; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.ifeng.recom.mixrecall.common.tool.ServiceLogUtil; import com.ifeng.recom.mixrecall.core.util.PreloadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * Created by liligeng on 2018/8/22. * lda topic缓存 */ public class LdaTopicCache { private static Logger logger = LoggerFactory.getLogger(LdaTopicCache.class); public static LoadingCache<String, List<String>> cache; private static int LDA_REDIS_DB = 4; static { initCache(); } public static void initCache() { cache = CacheBuilder .newBuilder() .concurrencyLevel(5) .expireAfterWrite(3, TimeUnit.HOURS) .initialCapacity(5000) .maximumSize(10000) .build(new CacheLoader<String, List<String>>() { @Override public List<String> load(String topic) throws Exception { long start = System.currentTimeMillis(); List<String> idList = PreloadUtils.getDocumentId(topic, LDA_REDIS_DB); long cost = System.currentTimeMillis() - start; if (cost > 50) { ServiceLogUtil.debug("lda-topic {} cost:{}", topic, cost); } if (idList == null) { return Collections.emptyList(); } else { return idList; } } } ); } public static Map<String, List<String>> getFromCache(Set<String> tags) { try { return cache.getAll(tags); } catch (ExecutionException e) { e.printStackTrace(); } return Collections.emptyMap(); } private static List<String> getFromCache(String docId) { try { return cache.get(docId); } catch (ExecutionException e) { e.printStackTrace(); } return null; } }
package Sekcja11.Lesson; public class Scope { public int publicVar = 0; private int privateVar = 1; public Scope(){ System.out.println(String.format("ScopeCheck created, publicVar = %s: privateVar = %s",publicVar, privateVar)); } public int getPrivateVar() { return privateVar; } public void timesTwo() { int privateVar = 2; for (int i = 0; i < 10; i++) { System.out.println(String.format("%s times two is %s",i,i * privateVar)); } } public class InnerClass { public int privateVar = 3; public InnerClass(){ System.out.println("InnerClass created, privateVar is " + privateVar); } public void timesTwo() { // int privateVar = 2; for (int i = 0; i < 10; i++) { System.out.println(String.format("%s times two is %s",i,i * privateVar)); } } } }
/* * Copyright 2002-2022 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.http.server.reactive; import java.net.URI; import reactor.core.publisher.Mono; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestTemplate; import org.springframework.web.testfixture.http.server.reactive.bootstrap.AbstractHttpHandlerIntegrationTests; import org.springframework.web.testfixture.http.server.reactive.bootstrap.HttpServer; import org.springframework.web.testfixture.http.server.reactive.bootstrap.JettyHttpServer; import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma */ class ErrorHandlerIntegrationTests extends AbstractHttpHandlerIntegrationTests { private final ErrorHandler handler = new ErrorHandler(); @Override protected HttpHandler createHttpHandler() { return handler; } @ParameterizedHttpServerTest void responseBodyError(HttpServer httpServer) throws Exception { startServer(httpServer); @SuppressWarnings("resource") RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(NO_OP_ERROR_HANDLER); URI url = URI.create("http://localhost:" + port + "/response-body-error"); ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @ParameterizedHttpServerTest void handlingError(HttpServer httpServer) throws Exception { startServer(httpServer); @SuppressWarnings("resource") RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(NO_OP_ERROR_HANDLER); URI url = URI.create("http://localhost:" + port + "/handling-error"); ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @ParameterizedHttpServerTest // SPR-15560 void emptyPathSegments(HttpServer httpServer) throws Exception { startServer(httpServer); @SuppressWarnings("resource") RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(NO_OP_ERROR_HANDLER); URI url = URI.create("http://localhost:" + port + "//"); ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); // Jetty 10+ rejects empty path segments, see https://github.com/eclipse/jetty.project/issues/6302, // but an application can apply CompactPathRule via RewriteHandler: // https://www.eclipse.org/jetty/documentation/jetty-11/programming_guide.php HttpStatus expectedStatus = (httpServer instanceof JettyHttpServer ? HttpStatus.BAD_REQUEST : HttpStatus.OK); assertThat(response.getStatusCode()).isEqualTo(expectedStatus); } private static class ErrorHandler implements HttpHandler { @Override public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { Exception error = new UnsupportedOperationException(); String path = request.getURI().getPath(); if (path.endsWith("response-body-error")) { return response.writeWith(Mono.error(error)); } else if (path.endsWith("handling-error")) { return Mono.error(error); } else { return Mono.empty(); } } } private static final ResponseErrorHandler NO_OP_ERROR_HANDLER = new ResponseErrorHandler() { @Override public boolean hasError(ClientHttpResponse response) { return false; } @Override public void handleError(ClientHttpResponse response) { } }; }
package com.zantong.mobilecttx.api; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Created by Administrator on 2016/4/19. */ public class OkHttpUtill { private static OkHttpUtill mInstance; private OkHttpClient mOkHttpClient; private Context mContext; private ActBackToUI mActBackToUI; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case 1: mActBackToUI.successDoInBack(msg.obj); // Toast.makeText(mContext, "请求成功!!", Toast.LENGTH_SHORT).show(); break; case 2: mActBackToUI.failDoInBack(msg.obj); } super.handleMessage(msg); } }; public OkHttpUtill(){ mOkHttpClient = new OkHttpClient(); } public static OkHttpUtill getInstance(){ if(mInstance == null){ synchronized (OkHttpUtill.class) { if(mInstance == null){ mInstance = new OkHttpUtill(); } } } return mInstance; } public OkHttpClient getOkHttpClient(){ return getInstance().mOkHttpClient; } public void sengGETOkHttpClient(final Context mContext, ActBackToUI mActBackToUI, String url ){ this.mActBackToUI = mActBackToUI; this.mContext = mContext; Request request = new Request.Builder() .url(url) .build(); OkHttpUtill.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Message message = new Message(); message.what = 2; message.obj = e; mHandler.sendMessage(message); } @Override public void onResponse(Call call, Response response) throws IOException { if(!response.isSuccessful()) throw new IOException("Unexpected code"+ response); // Toast.makeText(context, "请求成功!!!!", Toast.LENGTH_SHORT).show(); Log.e("why","请求成功!!!"); // mContext.getApplicationContext().runOnUiThread(new Runnable() { // @Override // public void run() { //// text.setText("请求成功"); // // } // }); Message message = new Message(); message.what=1; // Log.e("why",response.body().string()); String temp = response.body().string(); message.obj = temp; mHandler.sendMessage(message); } }); } // public interface ActBackToUI{ // public void doInBack(); // } }
package ua.shykun.springpayment; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringPaymentApplication { public static void main(String[] args) { SpringApplication.run(SpringPaymentApplication.class, args); } }
package DataStructures.trees; /** * Given the below binary tree.Find max path sum. 5 / \ 4 8 / / \ 11 16 4 / \ / \ 7 2 5 1 Paths are [ [5,4,11,7], [5,4,11,2], [5,8,16], [5,8,4,5], [5,8,4,1] ] So max is [5, 8, 6] **/ public class MaximumSumPath { public int maxSumPath(TreeNode root) { if (root == null) return 0; int left = maxSumPath(root.left); int right = maxSumPath(root.right); return root.val + Math.max(left, right); } public static void main(String a[]) { MaximumSumPath msum = new MaximumSumPath(); TreeNode root = new TreeNode(5, new TreeNode(4, new TreeNode(11, new TreeNode(7, null, null), new TreeNode(2, null, null)), null), new TreeNode(8, new TreeNode(16, null, null), new TreeNode(4, new TreeNode(5, null, null), new TreeNode(1, null, null)))); System.out.print(msum.maxSumPath(root)); } }
package br.com.murilokakazu.ec7.ftt.cefsa.domain.repository; import br.com.murilokakazu.ec7.ftt.cefsa.domain.model.Artist; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import java.util.UUID; public interface ArtistRepository extends JpaRepository<Artist, UUID>, JpaSpecificationExecutor<Artist> { }
package practico9; public class E5 { public static void main(String[] args) { int m = (int)(Math.random()*100); System.out.println(m); int contador =0; for (int i =0; i<=m;i++) { contador=contador+i; } System.out.println(contador); } }
package com.example.apiex.activities; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.util.Log; import com.example.apiex.R; import com.example.apiex.model.Post; import com.example.apiex.model.PostAdapter; import com.example.apiex.webservice.RetrofitPost; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class GetSimpleActivity extends AppCompatActivity { private List<Post> posts; private PostAdapter postAdapter; private RecyclerView posts_RCV; private LinearLayoutManager linearLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_get_simple); if(posts == null) posts = new ArrayList<>(); setupRecyclerView(); fetchPosts(); } private void fetchPosts(){ RetrofitPost.getService().postList().enqueue(new Callback<List<Post>>() { @Override public void onResponse(Call<List<Post>> call, Response<List<Post>> response) { posts.addAll(response.body()); postAdapter.notifyDataSetChanged(); } @Override public void onFailure(Call<List<Post>> call, Throwable t) { } }); } private void setupRecyclerView() { posts_RCV = findViewById(R.id.RCV_posts); Log.i("TAG", "setupRecyclerView: " + posts_RCV); linearLayoutManager = new LinearLayoutManager(this); postAdapter = new PostAdapter(posts); posts_RCV.setLayoutManager(linearLayoutManager); posts_RCV.setHasFixedSize(true); posts_RCV.setAdapter(postAdapter); } }
package org.coursera.algorithm.unionfind.canonicalelement; import org.coursera.algorithm.unionfind.WeightedQuickUnion; import static org.coursera.algorithm.Utils.assertEquals; public class CanonicalElement { public static void main(String[] args) { var uf = new WeightedQuickUnion(10); uf.union(0,1); uf.union(2,3); uf.union(4,5); uf.union(6,7); uf.union(8,9); uf.union(0,4); // 5 assertEquals(uf.find(1), 5); uf.union(1,6); assertEquals(uf.find(1), 7); assertEquals(uf.find(2), 3); assertEquals(uf.find(3), 3); assertEquals(uf.find(4), 7); assertEquals(uf.find(5), 7); assertEquals(uf.find(6), 7); assertEquals(uf.find(7), 7); assertEquals(uf.find(8), 9); assertEquals(uf.find(9), 9); } }
package projectImplementation; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.Scanner; public class MainClass { public static void main(String args[]) { Scanner scan = new Scanner(System.in); System.out.println("Enter your Name to open Account"); String name = scan.nextLine(); Random rand = new Random(); int accountNo = rand.nextInt(1000000); System.out.println("Enter Transaction PIN for your account"); int password = scan.nextInt(); Map<Integer, Account> map = new HashMap<Integer, Account>(); Account acc = new Account(accountNo, 0.00, name, password); map.put(accountNo, acc); while(true) { System.out.println("1.Account Details\n2.Deposit Amount\n3.Withdraw Amount\n4.Get Mini Statement\n5.Get PassBook\n6.Exit"); int choice = scan.nextInt(); switch(choice) { case 1: System.out.println("<<<Account Details>>>"); acc.getAccountDetails(); break; case 2: System.out.println("Enter Amount to be deposited : "); int amount =scan.nextInt(); acc.depositAmount(amount); break; case 3: System.out.println("Enter the amount : "); int amt = scan.nextInt(); acc.withdrawAmount(amt); break; case 4: acc.getMiniStatement(); break; case 5: acc.getPassBookStatement(); break; case 6: System.out.println("<><>EXITING<><>"); System.exit(0); } } } }
package com.staniul.teamspeak.modules.clientscommands; import com.staniul.teamspeak.commands.CommandResponse; import com.staniul.teamspeak.commands.Teamspeak3Command; import com.staniul.teamspeak.query.Client; import com.staniul.teamspeak.query.Query; import com.staniul.xmlconfig.CustomXMLConfiguration; import com.staniul.xmlconfig.annotations.UseConfig; import com.staniul.xmlconfig.annotations.WireConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @UseConfig("modules/jl.xml") public class JoinLink { @WireConfig private CustomXMLConfiguration config; private Query query; @Autowired public JoinLink(Query query) { this.query = query; } @Teamspeak3Command("!jl") public CommandResponse sendClientJoinLink (Client client, String params) { String message = "[URL]ts3server://" + config.getString("teamspeak[@addr]"); message += "?cid=" + client.getCurrentChannelId(); message += "".equals(params) ? "" : "&channel_password=" + params; message += "[/URL]"; return new CommandResponse(message); } }
package StellarisDK.GUI; import StellarisDK.FileClasses.Attitude; import StellarisDK.FileClasses.Helper.DataEntry; import StellarisDK.FileClasses.Helper.DataMap; import StellarisDK.FileClasses.Helper.EntryArrayList; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.TextField; public class AttitudeUI extends AbstractUI { @FXML private TextField type; @FXML private CheckBox attack; @FXML private CheckBox weaken; @FXML private CheckBox alliance; @FXML private CheckBox vassalize; @FXML private CheckBox trade; @FXML private CheckBox coexist; public AttitudeUI(Attitude obj) { init("FXML/attitudeFX.fxml"); window.setText("Attitude Editor"); this.obj = obj; } @Override public void load() { type.setText(obj.getFirstString(type.getId())); if (((DataEntry) obj.getFirstValue("behaviour")).getValue() instanceof DataMap) { DataMap temp = (DataMap) ((DataEntry) obj.getFirstValue("behaviour")).getValue(); if (temp.get(attack.getId()) != null && ((DataEntry) temp.getFirstValue(attack.getId())).getValue().toString().toLowerCase().equals("yes")) { attack.setSelected(true); } else { attack.setSelected(false); } if (temp.get(weaken.getId()) != null && ((DataEntry) temp.getFirstValue(weaken.getId())).getValue().toString().toLowerCase().equals("yes")) { weaken.setSelected(true); } else { weaken.setSelected(false); } if (temp.get(alliance.getId()) != null && ((DataEntry) temp.getFirstValue(alliance.getId())).getValue().toString().toLowerCase().equals("yes")) { alliance.setSelected(true); } else { alliance.setSelected(false); } if (temp.get(vassalize.getId()) != null && ((DataEntry) temp.getFirstValue(vassalize.getId())).getValue().toString().toLowerCase().equals("yes")) { vassalize.setSelected(true); } else { vassalize.setSelected(false); } if (temp.get(trade.getId()) != null && ((DataEntry) temp.getFirstValue(trade.getId())).getValue().toString().toLowerCase().equals("yes")) { trade.setSelected(true); } else { trade.setSelected(false); } if (temp.get(coexist.getId()) != null && ((DataEntry) temp.getFirstValue(coexist.getId())).getValue().toString().toLowerCase().equals("yes")) { coexist.setSelected(true); } else { coexist.setSelected(false); } } } @Override public Object save() { DataMap temp = (DataMap) ((DataEntry) obj.getFirstValue("behaviour")).getValue(); if (type.getText() == null || type.getText().equals("")) { obj.setValue(type.getId(), "Unnamed Object", true, 0); } else { obj.setValue(type.getId(), type.getText(), true, 0); } int size = 0; if (attack.isSelected()) { temp.put(attack.getId(), new EntryArrayList<>(new DataEntry<>(attack.getId(), "yes", size++, 1110))); } else { temp.remove(attack.getId()); } if (weaken.isSelected()) { temp.put(weaken.getId(), new EntryArrayList<>(new DataEntry<>(weaken.getId(), "yes", size++, 1110))); } else { temp.remove(weaken.getId()); } if (alliance.isSelected()) { temp.put(alliance.getId(), new EntryArrayList<>(new DataEntry<>(alliance.getId(), "yes", size++, 1110))); } else { temp.remove(alliance.getId()); } if (vassalize.isSelected()) { temp.put(vassalize.getId(), new EntryArrayList<>(new DataEntry<>(vassalize.getId(), "yes", size++, 1110))); } else { temp.remove(vassalize.getId()); } if (trade.isSelected()) { temp.put(trade.getId(), new EntryArrayList<>(new DataEntry<>(trade.getId(), "yes", size++, 1110))); } else { temp.remove(trade.getId()); } if (coexist.isSelected()) { temp.put(coexist.getId(), new EntryArrayList<>(new DataEntry<>(coexist.getId(), "yes", size++, 1110))); } else { temp.remove(coexist.getId()); } System.out.println(obj.export()); itemView.refresh(); return obj; } }
package no.nav.vedtak.felles.integrasjon.infotrygd.grunnlag.v1.respons; public record Inntektsperiode(InntektsperiodeKode kode, String termnavn) { }
package com.mastek.farmToShop.entities; public enum FarmType {DAIRY, MEAT, WHEAT, FRUIT, VEG, EGGS }
package evolutionYoutube; import com.vaadin.navigator.View; import com.vaadin.ui.Button; import com.vaadin.ui.UI; import database.BD_general; import com.vaadin.ui.Button.ClickEvent; public class Registrarse extends Registrarse_ventana implements View{ /** * */ private static final long serialVersionUID = 1L; public Invitado _unnamed_Invitado_; //public Enviar_Correo_Electronico _enviar_Correo_Electronico; public Registrarse() { registrarseBoton.addClickListener(new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { registrarse(); } }); cancelarBoton.addClickListener(new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { cancelar(); } }); } public void registrarse() { /*METODO QUE SE REGISTRA, CREA UNA BD GENERAL SIEMPRE PARA LLAMAR AL METODO DE LA INTERFAZ, *QUE A SU VEZ LLAMA AL METODO DE bd_especifica QUE SERA EL QUE REALICE LA ACCION *DE REGISTRARSE */ BD_general bd = new BD_general(); if(!(contrasenia.getValue().equals(confirmar.getValue())))return; try { bd.Registrarse(nombre.getValue(), apellidos.getValue(), apodo.getValue(), Integer.valueOf(edad.getValue()), email.getValue(), contrasenia.getValue(), confirmar.getValue()); } catch (NumberFormatException e) { e.printStackTrace(); } ((MyUI) UI.getCurrent()).invitado(); } public void cancelar() { ((MyUI) UI.getCurrent()).invitado(); } }
package com.arthur.leetcode; import org.omg.PortableInterceptor.INACTIVE; import java.sql.Array; import java.util.ArrayList; import java.util.Map; /** * @program: leetcode * @description: 打印从1到最大的n位数 * @title: JZoffer17 * @Author hengmingji * @Date: 2022/1/15 23:33 * @Version 1.0 */ public class JZoffer17 { public int[] printNumbers(int n) { int count = (int) (Math.pow(10, n) - 1); int[] ans = new int[count]; ans[0] = 1; for (int i = 1; i < count; i++) { ans[i] = ans[i - 1] + 1; } return ans; } }
package com.netcracker.DTO.mappers; import com.netcracker.DTO.InfoContentDTO; import com.netcracker.DTO.NotificationDTO; import com.netcracker.entities.InfoContent; import com.netcracker.entities.InfoMap; import com.netcracker.entities.Notification; import org.modelmapper.Converter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.persistence.Convert; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.stream.Collector; import java.util.stream.Collectors; @Component public class NotificationMapper extends AbstractMapper<Notification, NotificationDTO> { @Autowired private InfoContentMapper infoContentMapper; public NotificationMapper() { super(Notification.class, NotificationDTO.class); } @PostConstruct public void setupMapper () { Converter< Collection<InfoMap> , Collection<String> > convert = (ctg) -> { Collection<String> mapInfo = new LinkedList<>(); mapInfo.addAll( ctg.getSource() .stream() .map(x -> String.format("%s : %s", x.getInfoKey(), x.getInfoValue())) .collect(Collectors.toCollection(LinkedList::new)) ); return mapInfo; }; Converter<InfoContent, InfoContentDTO> converterInfo = ctg -> { InfoContentDTO infoContentDTO = infoContentMapper.toDto(ctg.getSource()); return infoContentDTO; }; mapper.typeMap(Notification.class, NotificationDTO.class).addMappings( mapper -> { mapper.using(convert).map(Notification::getTemplatevalues, NotificationDTO::setTemplatevalues); mapper.using(converterInfo).map(Notification::getInfoContent, NotificationDTO::setInfoContent); } ); } }
package en10; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * Created by C0116289 on 2017/06/26. */ public class Ex03 { public static void main(String[] args) { Map<String ,Integer> map=new TreeMap<>(); map.put("Cheeseburger",130); map.put("Teriyaki",320); map.put("B.L.T.",350); map.put("Humburger",100); map.put("Bigburger",380); map.put("French fries",270); Set<String> keys=map.keySet(); for (String key:keys ) { Integer value=map.get(key); System.out.println(key+", "+value); } } }
package models; import org.junit.*; import static org.junit.Assert.*; import org.sql2o.*; import java.util.Arrays; public class DepartmentTest { private Department testDepartment; @Rule public DatabaseRule database = new DatabaseRule(); @Before public void setUp() { testDepartment = new Department("Home"); } // @Test // public void Department_instantiatesCorrectly_true() { // assertTrue(testDepartment instanceof Department); // } // // @Test // public void getName_DepartmentInstantiatesWithName_Home() { // assertEquals("Home", testDepartment.getName()); // } // // @Test // public void all_returnsAllInstancesOfDepartment_true() { // Department firstDepartment = new Department("Home"); // firstDepartment.save(); // Department secondDepartment = new Department("Work"); // secondDepartment.save(); // assertTrue(Department.all().get(0).equals(firstDepartment)); // assertTrue(Department.all().get(1).equals(secondDepartment)); // } // // @Test // public void getId_categoriesInstantiateWithAnId_1() { // testDepartment.save(); // assertTrue(testDepartment.getId() > 0); // } // // @Test // public void find_returnsDepartmentWithSameId_secondDepartment() { // Department firstDepartment = new Department("Home"); // firstDepartment.save(); // Department secondDepartment = new Department("Work"); // secondDepartment.save(); // assertEquals(Department.find(secondDepartment.getId()), secondDepartment); // } // // @Test // public void getSections_initiallyReturnsEmptyList_ArrayList() { // assertEquals(0, testDepartment.getSections().size()); // } // // @Test // public void getSections_retrievesAllSectionsFromDatabase_SectionsList() { // Department myDepartment = new Department("Household chores"); // myDepartment.save(); // Section firstSection = new Section("Mow the lawn", myDepartment.getId()); // firstSection.save(); // Section secondSection = new Section("Do the dishes", myDepartment.getId()); // secondSection.save(); // Section[] Sections = new Section[] { firstSection, secondSection }; // assertTrue(myDepartment.getSections().containsAll(Arrays.asList(Sections))); // } // // @Test // public void find_returnsNullWhenNoSectionFound_null() { // assertNull(Department.find(999)); // } // // @Test // public void equals_returnsTrueIfNamesAretheSame() { // Department firstDepartment = new Department("Household chores"); // Department secondDepartment = new Department("Household chores"); // assertTrue(firstDepartment.equals(secondDepartment)); // } // // @Test // public void save_savesIntoDatabase_true() { // Department myDepartment = new Department("Household chores"); // myDepartment.save(); // assertTrue(Department.all().get(0).equals(myDepartment)); // } // // @Test // public void save_assignsIdToObject() { // Department myDepartment = new Department("Household chores"); //// myDepartment.save(); // Department savedDepartment = Department.class.get(0); // assertEquals(myDepartment.getId(), savedDepartment.getId()); // } // // @Test // public void save_savesDepartmentIdIntoDB_true() { // Department myDepartment = new Department("Household chores"); // myDepartment.save(); // Section mySection = new Section("Mow the lawn", myDepartment.getId()); // mySection.save(); // Section savedSection = Section.find(mySection.getId()); // assertEquals(savedSection.getDepartmentId(), myDepartment.getId()); // } }
public class Mayonesa extends IngredienteDecoradorTorta { Torta torta; public Mayonesa(Torta torta) { this.torta = torta; } public String getDescripcion() { return torta.getDescripcion() + ", Mayonesa"; } public double costo() { return 1.00 + torta.costo(); } }
package com.mycompany.gaviao.validate; import antlr.StringUtils; import com.mycompany.gaviao.model.Cliente; import com.mycompany.gaviao.utils.Message; public class ClienteValidate implements IValidate { public Message message = new Message(); public boolean validatePost(Object objCliente) { Cliente cliente = (Cliente) objCliente ; if(cliente.getNome().equals(null) || cliente.getNome().equals("")){ return false; } else if (cliente.getCpf().equals(null) || cliente.getCpf().equals("")){ return false; } else if (cliente.getRg().equals(null) || cliente.getRg().equals("")){ return false; } else if (!cliente.getCpf().matches("[0-9]{3}\\.?[0-9]{3}\\.?[0-9]{3}\\-?[0-9]{2}")){ message.renderMessage("Error", "O CPF deve conter 11 dígitos, sendo somente números"); return false; } else if(!cliente.getRg().matches("[0-9]{6}")){ message.renderMessage("Error", "O RG deve conter 6 digitos, sendo somente números"); return false; } return true; } @Override public boolean validateGet() { return false; } @Override public boolean validatePut(Object objCliente) { return true; } @Override public boolean validateDelete() { return false; } }
package com.test.shortest; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * 路径图 * @author YLine * * 2019年4月28日 下午5:23:07 */ public class PathGraph { private List<Vertex> vertextList; public PathGraph() { this.vertextList = new ArrayList<>(); } public void addVertex(int id) { vertextList.add(new Vertex(id)); } public void addEdge(int startIndex, int endIndex, int weight) { checkValid(startIndex); checkValid(endIndex); Vertex start = vertextList.get(startIndex); Vertex end = vertextList.get(endIndex); start.addEdge(new Edge(start, end, weight)); } private void checkValid(int index) { if (index < 0 || index >= vertextList.size()) { throw new IllegalAccessError("index outOfBoundException, index = " + index); } } public int getVertexSize() { return vertextList.size(); } public Vertex getVertex(int index) { checkValid(index); return vertextList.get(index); } public int indexOf(Vertex vertex) { if (null == vertex) { return -1; } return vertextList.indexOf(vertex); } /** * 边 */ public static class Edge { private Vertex start; // 边起始顶点,编号 private Vertex end; // 边终止顶点,编号 private int weight; // 权重 public Edge(Vertex start, Vertex end, int weight) { this.start = start; this.end = end; this.weight = weight; } public int getWeight() { return weight; } public Vertex getEndVertex() { return end; } } /** * 顶点 */ public static class Vertex { private int id; // 顶点编号 private List<Edge> edgeArray; public Vertex(int id) { this.id = id; this.edgeArray = new ArrayList<>(); } public void addEdge(Edge edge) { // 去重校验 for (Edge oldEdge : edgeArray) { if (oldEdge.end.id == edge.end.id) { throw new IllegalAccessError("edge double, end id = " + edge.end.id); } } // 添加内容 edgeArray.add(edge); } public int getEdgeSize() { return edgeArray.size(); } public Edge getEdge(int index) { return edgeArray.get(index); } public Iterator<Edge> iterator() { return edgeArray.iterator(); } public int getId() { return id; } } }
package slimeknights.tconstruct.common; /** * Sole purpose of this class is to have all mod entity IDs in one place so we don't assign them twice and conflict. */ public interface EntityIDs { int INDESTRUCTIBLE_ITEM = 0; int BLUESLIME = 1; int FANCY_FRAME = 2; int THROWBALL = 3; int ARROW = 10; int BOLT = 11; int SHURIKEN = 12; }
package org.beanone.xlogger.mock.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.beanone.xlogger.AbstractMethodLogger; import org.beanone.xlogger.LoggerLevel; import org.beanone.xlogger.LoggerSpec; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A reference implementation of the aspect used by the Unit tests. * * @author Hongyan Li * */ @Aspect public class MockMethodLogger extends AbstractMethodLogger { private static Logger LOGGER = LoggerFactory .getLogger(MockMethodLogger.class); public static Logger MOCK_LOGGER = Mockito.spy(LOGGER); /** * This pointcut represent the control flow of invoking any method of * classes in this package. */ @Pointcut("cflow(call(* org.beanone.xlogger.mock.aspect.*.*(..)))") public void inAspect() { } @Pointcut("within(*Test)") public void inTest() { } /** * An around advice to methods for logging of exception thrown from methods. * The default logging level is ERROR. A different advice can be defined to * use a different default logging level. More fine control on the logging * level can be achieved by annotating the method of concern with * {@link LoggerSpec}. * * @param point * the pointcut this advice is for. * @param t * the exception thrown by the method. */ @AfterThrowing(pointcut = "xloggerMock() && !inAspect() && !inFramework() && !trivial() && !inTest()", throwing = "t") public void logException(JoinPoint point, Throwable t) { handleThrows(point, t, null, LoggerLevel.ERROR); } /** * An around advice to methods for logging of access to methods. The default * logging level is TRACE. A different advice can be defined to use a * different default logging level. More fine control on the logging level * can be achieved by annotating the method of concern with * {@link LoggerSpec} . * * @param point * the pointcut this advice is for. * @return the result of invoking the advised method. * @throws Throwable * the exception thrown by the method advised. */ @Around("xloggerMock() && !inAspect() && !inFramework() && !trivial() && !inTest()") public Object logInvocation(ProceedingJoinPoint point) throws Throwable { return handle(point, LoggerLevel.TRACE); } /** * This pointcut represents the execution of any getter and setter method. */ @Pointcut("execution(* *..*.get*(..)) || execution(* *..*.set*(..)) || execution(* *..*.is*(..)) || execution(* *..*.add*(..))") public void trivial() { } /** * This pointcut represents the execution of any method of classes in the * mock package. */ @Pointcut("execution(* org.beanone.xlogger.mock.*.*(..))") public void xloggerMock() { } /** * return the mocked Logger so that we can count how many times the logging * method is invoked. */ @Override protected Logger getLogger(Class<?> clazz) { super.getLogger(clazz).trace("Test"); Mockito.when(MOCK_LOGGER.isTraceEnabled()).thenReturn(true); return MOCK_LOGGER; } }
package com.fsj.service; import java.util.List; import java.util.Map; import com.fsj.entity.Pricetrend; //价格走势业务逻辑接口 public interface PricetrendDAO { // 查询所有 public int queryAll(String hql, Map<String, Object> map); public List<Pricetrend> querypage(int pageNumber, int pageSize, String hql, Map<String, Object> map); // 价格走势注册 public boolean addPricetrend(Pricetrend pricetrend); // 价格走势更新 public boolean updatePricetrend(Pricetrend pricetrend); // 删除价格走势 public boolean deletePricetrend(int ptid); }
package persistent.wordpressautomation.PageObjects; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class Post { WebDriver driver; @FindBy(id="title") WebElement post_title; @FindBy(id="tinymce") WebElement desc_text; @FindBy(id="publish-button") WebElement btn_publish; public Post(WebDriver driver) { this.driver=driver; }// Post public EditPost Addnew_Post(String Title, String Desc) { // WebElement post_title =driver.findElement(By.id("title")); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); System.out.println("Inside Addnew_Post"); post_title.click(); post_title.sendKeys(Title); String Parenthandel= driver.getWindowHandle(); // WebElement frame=driver.findElement(By.id("edit-content_ifr")); driver.switchTo().frame("edit-content_ifr"); // WebElement desc_text=driver.findElement(By.id("tinymce")); desc_text.sendKeys(Desc); driver.switchTo().window(Parenthandel); // WebElement btn_publish=driver.findElement(By.id("publish-button")); btn_publish.click(); // return new Dashboard(driver); return PageFactory.initElements(driver, EditPost.class); }// Addnewpost }
/******************************************************************************* * Copyright 2014 See AUTHORS file. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 dk.sidereal.lumm.components.audio; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import dk.sidereal.lumm.architecture.Lumm; import dk.sidereal.lumm.architecture.LummObject; import dk.sidereal.lumm.architecture.concrete.ConcreteLummComponent; /** * Handles listening to audio coming from {@link AudioPlayer} instances, panning * the audio based on the position between the listener and the player. * * @author Claudiu Bele */ public class AudioListener extends ConcreteLummComponent { // region fields public static enum PanType { /** * Elements to the right of the listener are played on the right, * elements to the left are played on the left */ X_Axis, /** * Elements to the right of the listener are played on the left, * elements to the left are played on the right */ X_Axis_Reversed, /** * Elements above the listener are played on the left, elements below * the listener are played on the right */ Y_Axis, /** * Elements above the listener are played on the right, elements below * the listener are played on the left */ Y_Axis_Reversed } public static Sprite debugSpriteSource; private PanType pan; private float volumeRadius; private float maxVolumeRadius; private final Array<AudioClip> audioClips; /** Whether the listener is active or not */ private boolean isActive; private Vector3 prevPosition; /** * The active AudioListener. Only one will be available at any time. The * first listener that is created will be set as the active listener, and * the following listeners must call {@link #activate()}. */ private static AudioListener activeListener; /** * Audio clips that have {@link AudioClip#audioListenerInteraction} set to * {@link AudioClip.AudioListenerInteraction#Auto}, the target volume, pitch and * panning being updated whenever the active listener is called */ static Array<AudioClip> automaticAudioclips = new Array<AudioClip>(); // endregion fields // region constructors /** * Creates an audio listener component with a designated radius. * * @param obj * The object to add a the listener to * @param radius * The radius of the listener, beyond which audio clips * registered to this listener can't be heard anymore. Clips can * register to a listener using * {@link AudioClip#setAudioListenerInteraction(AudioClip.AudioListenerInteraction)} * and {@link AudioClip#setAudioListener(AudioListener)}. */ public AudioListener(LummObject obj, float radius) { this(obj, radius, 0); } /** * Creates an audio listener component with a designated radius. * * @param obj * The object to add a the listener to * @param radius * The radius of the listener, beyond which audio clips * registered to this listener can't be heard anymore. Clips can * register to a listener using * {@link AudioClip#setAudioListenerInteraction(AudioClip.AudioListenerInteraction)} * and {@link AudioClip#setAudioListener(AudioListener)}. * @param maxVolumeRadius * The radius of the listener, within which clips registered to * this listener have the listener-based volume multiplier set to * 1. */ public AudioListener(LummObject obj, float volumeRadius, float maxVolumeRadius) { super(obj); setDebugToggleKeys(Keys.SHIFT_LEFT, Keys.Z); prevPosition = new Vector3(object.position.get()); this.volumeRadius = volumeRadius; this.maxVolumeRadius = maxVolumeRadius; this.audioClips = new Array<AudioClip>(); if (AudioListener.activeListener == null) AudioListener.activeListener = this; this.pan = PanType.X_Axis; } @Override protected void initialiseClass() { if (!Lumm.debug.isEnabled()) return; if (debugSpriteSource == null) { debugSpriteSource = new Sprite( Lumm.assets.get(Lumm.assets.frameworkAssetsFolder + "AudioListener.png", Texture.class)); } } // endregion constructors // region methods @Override public void onDebug() { debugSpriteSource.setBounds(object.position.getX() - volumeRadius, object.position.getY() - volumeRadius, volumeRadius * 2, volumeRadius * 2); // debugSpriteSource.setBounds(0, 0, 100, 100); debugSpriteSource.draw(object.getSceneLayer().spriteBatch); } @Override public void onUpdate() { if (prevPosition.x != object.position.getX() || prevPosition.y != object.position.getY() || prevPosition.z != object.position.getZ()) { prevPosition.set(object.position.get()); updateAudioClips(); } } /** * Sets the volume radius beyond which an AudioSource's {@link AudioClip}s * that have the listener set to the instance that you are manipulating can * not be heard anymore. The overall system also contains functionality for * a radius within which sounds will be played at full volume. * <p> * From the end of the max volume radius (set via * {@link #setVolumeRadius(float)}) and this radius, volume will linearly * move from 100% to 0% listener-based volume, but that is a rough indicator * of the sound's volume, as it is also affected by the master volume, * channel volume and individual clip instance volume. * * @return the radius. Set in the constructor * {@link #setVolumeRadius(float)}. */ public float getVolumeRadius() { return volumeRadius; } /** * Sets the volume radius beyond which an AudioSource's {@link AudioClip}s * that have the listener set to the instance that you are manipulating can * not be heard anymore. The overall system also contains functionality for * a radius within which sounds will be played at full volume. * <p> * From the end of the max volume radius (set via * {@link #setVolumeRadius(float)}) and this radius, volume will linearly * move from 100% to 0% listener-based volume, but that is a rough indicator * of the sound's volume, as it is also affected by the master volume, * channel volume and individual clip instance volume. * * @param volumeRadius * The circle of radius */ public void setVolumeRadius(float volumeRadius) { boolean valueChanged = (this.volumeRadius != volumeRadius); this.volumeRadius = volumeRadius; if (valueChanged) updateAudioClips(); } /** * Returns the maximum volume radius, which represents the area around the * listener around which any {@link AudioClip}'s listener-based volume * multiplier is set to a maximum of 1 ( indicating full volume before the * other multipliers are applied. For more information on volume radius and * how the max volume radius works towards the linearly-decreasing of the * overall volume of audioclips check {@link #setVolumeRadius(float)} and * {@link #getVolumeRadius()}. */ public float getMaxVolumeRadius() { return maxVolumeRadius; } /** * Sets the maximum volume radius, which represents the area around the * listener around which any {@link AudioClip}'s listener-based volume * multiplier is set to a maximum of 1 ( indicating full volume before the * other multipliers are applied. For more information on volume radius and * how the max volume radius works towards the linearly-decreasing of the * overall volume of audioclips check {@link #setVolumeRadius(float)} and * {@link #getVolumeRadius()}. * * @param maxVolumeRadius * The radius around which clips tied to this listener are played * with a listener-based multiplyer of 1. */ public void setMaxVolumeRadius(float maxVolumeRadius) { boolean valueChanged = (this.maxVolumeRadius != maxVolumeRadius); this.maxVolumeRadius = maxVolumeRadius; if (valueChanged) updateAudioClips(); } /** * Returns the pan type that will be applied to clips that use a listener * and do not have a forced pan. By default it is set to * {@link PanType#X_Axis}. */ public PanType getPan() { return pan; } /** * Sets the pan type that will be applied to clips that use a listener and * do not have a forced pan. By default it is set to {@link PanType#X_Axis}. */ public void setPan(PanType pan) { this.pan = pan; updateAudioClips(); } /** * Returns the currently active listener. There can either be 0 or 1 * listeners active at any time. Sounds that are registered to listeners * will be played only if the listener they are tied to is active. * <p> * If an audio clip has the {@link AudioClip#getAudioListenerInteraction()} * set to {@link AudioClip.AudioListenerInteraction#Auto}, the clips will get their * volume and panning updated based on the active listener. * <p> * To activate the listener, call {@link #activate()}, which will deactivate * the previously-activated clip if there was any. * * @return The currently-active listener or null if no listener has been * activated. */ public static AudioListener getActiveListener() { return activeListener; } /** * Activates the listener and deactivates the previous active listener if * there is any, updating the target volume and pan for all clips that have * the listener set to any of the 2 listeners. * <p> * If an audio clip has the {@link AudioClip#getAudioListenerInteraction()} * set to {@link AudioClip.AudioListenerInteraction#Auto}, the clips will get their * volume and panning updated based on the active listener. **/ public void activate() { if (activeListener != null) { activeListener.isActive = false; activeListener.updateAudioClips(); } activeListener = this; this.isActive = true; this.updateAudioClips(); AudioListener.updateAutomaticAudioClips(); } /** * Returns whether the listener is the active listener. * <p> * For more information on active listeners, see * {@link AudioListener#getActiveListener()} and * {@link AudioListener#activate()}. */ public boolean isActive() { return isActive; } void addAudioClip(AudioClip clip) { if (!audioClips.contains(clip, true)) { audioClips.add(clip); clip.updateInternalData(); } } static void addAutomaticClip(AudioClip clip) { if (!automaticAudioclips.contains(clip, true)) { automaticAudioclips.add(clip); clip.updateInternalData(); } } void removeAudioClip(AudioClip clip) { int index = audioClips.indexOf(clip, true); if (index != -1) audioClips.removeIndex(index); } static void removeAutomaticAudioClip(AudioClip clip) { int index = automaticAudioclips.indexOf(clip, true); if (index != -1) automaticAudioclips.removeIndex(index); } private void updateAudioClips() { for (int i = 0; i < audioClips.size; i++) { if (audioClips.get(i).audioListenerInteraction == AudioClip.AudioListenerInteraction.Target) audioClips.get(i).updateInternalData(); } } static void updateAutomaticAudioClips() { for (int i = 0; i < automaticAudioclips.size; i++) { if (automaticAudioclips.get(i).audioListenerInteraction == AudioClip.AudioListenerInteraction.Auto) automaticAudioclips.get(i).updateInternalData(); } } // endregion methods }
import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.*; import java.net.*; import java.util.*; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.table.AbstractTableModel; public class NewJFrame111 extends javax.swing.JFrame { ArrayList<String> al = new ArrayList<>(); MyTableModel tm; NewJFrame4 obj1; public NewJFrame111() { // int i=0; setLayout(null); setVisible(true); initComponents(); setSize(500, 500); tm = new MyTableModel(); tb1.setModel(tm); } // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bt1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tb1 = new javax.swing.JTable(); bt2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); bt1.setText("DETECT HELPER SYSTEM"); bt1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bt1ActionPerformed(evt); } }); tb1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null}, {null}, {null}, {null} }, new String [] { "IP ADDRESSES" } )); jScrollPane1.setViewportView(tb1); bt2.setText("GET SCREEN"); bt2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bt2ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(29, 29, 29) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(bt1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(81, 81, 81) .addComponent(bt2, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(49, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(bt2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bt1, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(215, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents class MyTableModel extends AbstractTableModel { public String getColumnName(int col) { String name = "IP ADDRESS"; return name; } public int getRowCount() { return al.size(); } public int getColumnCount() { return 1; } public Object getValueAt(int row, int col) { return al.get(row); } } private void bt1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt1ActionPerformed String s = "192.168.43."; for (int i = 0; i <= 255; i++) { Client obj = new Client(s + i); bt1.setEnabled(false); } }//GEN-LAST:event_bt1ActionPerformed private void bt2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt2ActionPerformed if (tb1.getSelectedRow() == -1) { JOptionPane.showMessageDialog(this, "Select an IP ADDRESS first"); } else { obj1 = new NewJFrame4(); obj1.setVisible(true); PhotoClient pc = new PhotoClient(al.get(tb1.getSelectedRow())); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); obj1.setSize(d.width, d.height); obj1.jScrollPane3.setBounds(10, 10, d.width - 100, d.height - 100); // al.get(tb1.getSelectedRow()); } }//GEN-LAST:event_bt2ActionPerformed public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bt1; private javax.swing.JButton bt2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tb1; // End of variables declaration//GEN-END:variables public class PhotoClient implements Runnable { String ipaddress; PhotoClient(String ip) { ipaddress = ip; Thread t = new Thread(this); t.start(); } public void run() { try { Socket sock = new Socket(ipaddress, 9700); DataInputStream dis = new DataInputStream(sock.getInputStream()); DataOutputStream dos = new DataOutputStream(sock.getOutputStream()); int i = 0; File f = new File("e:\\Screenshots\\" + i + ".jpg"); while (true) { FileOutputStream fos = new FileOutputStream(f); double height = dis.readDouble(); double width = dis.readDouble(); System.out.println("Height of Screen" + height); System.out.println("Width of Screen" + width); long length = dis.readLong(); int l; int count = 0; byte b[] = new byte[10000]; while (true) { l = dis.read(b, 0, 10000); count = count + l; fos.write(b, 0, l); if (count == length) { break; } } dos.writeBytes("Received\r\n"); fos.close(); obj1.jLabel2.setPreferredSize(new Dimension((int) width, (int) height)); obj1.jLabel2.setIcon(new ImageIcon("f")); f.delete(); i++; } } catch (Exception ex) { ex.printStackTrace(); } } } public class Client implements Runnable { String ipaddress; Client(String ip) { ipaddress = ip; Thread t = new Thread(this); t.start(); } public void run() { try { Socket sock = new Socket(); sock.connect(new InetSocketAddress(ipaddress, 9900), 5000); DataInputStream dis = new DataInputStream(sock.getInputStream()); String s = dis.readLine(); al.add(ipaddress); tm.fireTableDataChanged(); System.out.println(ipaddress + ":" + s); } catch (Exception ex) { // ex.printStackTrace(); } } } public class NewJFrame4 extends javax.swing.JFrame implements MouseListener { public NewJFrame4() { initComponents(); setVisible(true); setSize(1366, 768); jLabel2.addMouseListener(this); } private void initComponents() { jScrollPane3 = new javax.swing.JScrollPane(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(null); jLabel2.setText("jLabel2"); jScrollPane3.setViewportView(jLabel2); getContentPane().add(jScrollPane3); jScrollPane3.setBounds(0, 0, 408, 300); pack(); } public javax.swing.JLabel jLabel2; public javax.swing.JScrollPane jScrollPane3; public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { e.getX(); e.getY(); System.out.println("X cordinates =" + e.getX()); System.out.println("Y cordinates =" + e.getY()); } public void mouseReleased(MouseEvent e) { e.getX(); e.getY(); System.out.println("X1 cordinates =" + e.getX()); System.out.println("Y1 cordinates =" + e.getY()); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } } }
package com.fasteque.pachubewidget; public class ParsedFeedData { private int id = -1; private String tag = ""; private String value = ""; private String unitSymbol = ""; private String unitName = ""; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getUnitSymbol() { return unitSymbol; } public void setUnitSymbol(String unitSymbol) { this.unitSymbol = unitSymbol; } public String getUnitName() { return unitName; } public void setUnitName(String unitName) { this.unitName = unitName; } }
package Model.Characters; import Model.Player; /** * This class creates a new Digger Character */ public class Digger extends Character { /** * <b>Constructor:</b> Constructs a new instance of Digger using super to initialize some ints and player and color * enum * <b>PostCondition:</b> Constructs a new Digger * @param player * @param color */ public Digger(Player player , CharacterColor color){ super(player , color, AreaToTakeTiles.AREA_LAST_CHOSEN_LOCATION, 2 , 3 ); } }
package com.example.socialctxt_alarm; import java.util.ArrayList; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.graphics.Typeface; import android.net.Uri; import android.provider.ContactsContract; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class BluetoothViewAdaptor extends BaseAdapter { private Context ctxt; public ArrayList<String> names = new ArrayList<String>(); public ArrayList<String> phn_num = new ArrayList<String>(); public BluetoothViewAdaptor(Context c) { // TODO put code here for getting contact's names from the // contentProvider and storing them in the list ctxt = c; int cnt =0; Uri uri = ContactsContract.Contacts.CONTENT_URI; String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }; String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + "1" + "'"; String[] selectionArgs = null; String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; Cursor cursor = ctxt.getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder); if (cursor != null) { while (cursor.moveToNext()) { String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); ContentResolver cr = c.getContentResolver(); Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null); while (pCur.moveToNext()) { String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); names.add(cnt, cursor.getString(cursor.getColumnIndex("display_name"))); phn_num.add(cnt, phone); cnt++; } } } } public int getCount() { return names.size(); } public Object getItem(int position) { return names.get(position); } public long getItemId(int position) { return position; } @Override public View getView(int position, View arg1, ViewGroup arg2) { TextView textView = new TextView(ctxt); textView.setText(names.get(position)); textView.setTextSize(20); textView.setTypeface(null,Typeface.BOLD); textView.setTextColor(-16777216); return textView; } }
package com.dream.the.code.droidswatch; import java.util.LinkedList; /** * This class is taken from https://github.com/bennapp/forwardBackwardChaining * * @author Ben Nappier ben2113 * */ public class Sentence{ public LinkedList<Operator> opList; public boolean impForm; public Sentence(LinkedList<Operator> opList, boolean impForm){ this.opList = opList; this.impForm = impForm; } public Sentence(){ this.opList = null; this.impForm = false; } }
package com.zhouqi.schedule.job.type.impl; import com.zhouqi.entity.CfgTask; import com.zhouqi.enums.Constants; import com.zhouqi.schedule.job.impl.task.TaskJobImpl; import org.quartz.JobBuilder; public class DoTaskExpressionImpl extends ISimpleJobExpression{ @Override public void build(JobBuilder builder, CfgTask task) { builder.ofType(TaskJobImpl.class); builder.usingJobData(Constants.Schedule.KEY_TASK_TYPE_CLASSNAME, task.getJobExpr()); } }
package ro.fr33styler.frconomy.account; import java.util.UUID; import org.bukkit.OfflinePlayer; public class Account { private UUID uuid; private String name; private double balance = 0.00; public boolean canReceive = true; public Account(UUID uuid, String name) { this.uuid = uuid; this.name = name; } public Account(OfflinePlayer player) { name = player.getName(); uuid = player.getUniqueId(); } public UUID getUUID() { return uuid; } public String getName() { return name; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public boolean canReceive() { return canReceive; } public void setReceive(boolean canReceive) { this.canReceive = canReceive; } }
package one; //+ -> zbrajanje // == public class StringDemo { public static void main(String[] args) { String ime = "Harun "; String prezime = "Bucalović"; String result = ime+prezime; System.out.println(result); String name1 = "Emir"; String name2 = new String("Emir"); String name3 = "Emir"; //== System.out.println(name1 == name3); } }
package com.crutchclothing.users.model; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.persistence.Transient; import com.crutchclothing.util.AddressType; @Entity @Table(name = "addresses", catalog = "crutch") public class Address implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private Integer id; private String firstName; private String lastName; private String company; private String address1; private String city; private String state; private String zipcode; private String address2; private String address3; private String shortName; private AddressType addressType; private Set<User> users = new HashSet<User>(); public Address(){ } public Address(String firstName, String lastName, String address1, String city, String state, String zipcode) { this.firstName = firstName; this.lastName = lastName; this.address1 = address1; this.city = city; this.state = state; this.zipcode = zipcode; } public Address(String firstName, String lastName, String address1, String address2, String city, String state, String zipcode) { this.firstName = firstName; this.lastName = lastName; this.address1 = address1; this.address2 = address2; this.city = city; this.state = state; this.zipcode = zipcode; } public Address(String firstName, String lastName, String address1, String address2, String address3, String city, String state, String zipcode) { this.firstName = firstName; this.lastName = lastName; this.address1 = address1; this.address2 = address2; this.address3 = address3; this.city = city; this.state = state; this.zipcode = zipcode; } @Id @Column(name = "address_id") @GeneratedValue(strategy = GenerationType.IDENTITY) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Column(name = "first_name") public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name = "last_name") public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Column(name="company") public String getCompany() { return this.company; } public void setCompany(String company) { this.company = company; } @Column(name = "address1") public String getAddress1() { return this.address1; } public void setAddress1(String address1) { this.address1 = address1; } @Column(name = "address2") public String getAddress2() { return this.address2; } public void setAddress2(String address2) { this.address2 = address2; } @Column(name = "address3") public String getAddress3() { return this.address3; } public void setAddress3(String address3) { this.address3 = address3; } @Column(name = "city") public String getCity() { return this.city; } public void setCity(String city) { this.city = city; } @Column(name = "state") public String getState() { return this.state; } public void setState(String state) { this.state = state; } @Column(name = "zipcode") public String getZipcode() { return this.zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }) @JoinTable(name = "user_addresses", joinColumns = { @JoinColumn(name = "address_id") }, inverseJoinColumns = { @JoinColumn(name = "username") }) public Set<User> getUsers() { return this.users; } public void setUsers(Set<User> users) { this.users = users; } @Enumerated(EnumType.STRING) @Column(name = "address_type") public AddressType getAddressType() { return this.addressType; } public void setAddressType(AddressType addressType) { this.addressType = addressType; } @Transient public String getShortName() { String firstName = capitalizeName(this.firstName); String lastInit = this.lastName.substring(0, 1).toUpperCase() + "."; this.shortName = (firstName + " " + lastInit); return this.shortName; } public void setShortName(String shortName) { this.shortName = shortName; } private String capitalizeName(String name) { String formattedName = name.substring(0,1).toUpperCase() + name.substring(1, name.length()).toLowerCase(); return formattedName; } }
/* * Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.webadmin.tprofile; import java.util.Collection; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.types.translation.ActionParameterDefinition; import com.vaadin.server.UserError; import com.vaadin.ui.ComboBox; /** * {@link ComboBox} based editor of all enumerated parameters. * @author K. Benedyczak */ public class BaseEnumActionParameterComponent extends ComboBox implements ActionParameterComponent { private UnityMessageSource msg; private ActionParameterDefinition desc; public BaseEnumActionParameterComponent(ActionParameterDefinition desc, UnityMessageSource msg, Collection<?> values) { for (Object o: values) addItem(o.toString()); String def = values.isEmpty() ? null : values.iterator().next().toString(); initCommon(desc, msg, def); } public BaseEnumActionParameterComponent(ActionParameterDefinition desc, UnityMessageSource msg, Object[] values) { for (Object o: values) addItem(o.toString()); String def = values.length == 0 ? null : values[0].toString(); initCommon(desc, msg, def); } protected final void initCommon(ActionParameterDefinition desc, UnityMessageSource msg, String def) { this.msg = msg; this.desc = desc; setNullSelectionAllowed(false); if (def != null) select(def); setRequired(true); setDescription(msg.getMessage(desc.getDescriptionKey())); setCaption(desc.getName() + ":"); } @Override public String getActionValue() { return (String) getValue(); } /** * Warning: The code copied to {@link AttributeActionParameterComponent#setActionValue(String)}. * It is hard to provide static method for this and Java as no multi inheritance. */ @Override public void setActionValue(String value) { if (!getItemIds().contains(value) && value != null) { String def = (String) getItemIds().iterator().next(); setComponentError(new UserError(msg.getMessage("TranslationProfileEditor.outdatedValue", value, def, desc.getName()))); setValidationVisible(true); value = def; } select(value); } }
package foo.bar.client.api; public class OnlineStore { public Products products() { return new Products(); } public class Products extends OnlineStoreRequest<foo.bar.client.json.entity.Products> { private static final String REST_PATH = "api/v{version}/products"; public Products() { super(OnlineStore.this, REST_PATH, foo.bar.client.json.entity.Products.class); } public Product list(String id) { return new Product(id); } public class Product extends OnlineStoreRequest<foo.bar.client.json.entity.Product> { private static final String REST_PATH = "api/v{version}/products/{id}"; private String id = ""; public Product(String id) { super(OnlineStore.this, REST_PATH, foo.bar.client.json.entity.Product.class); super.id = id; this.id = id; } public Attributes attributes() { Attributes result = new Attributes(); return result; } public class Attributes extends OnlineStoreRequest<foo.bar.client.json.entity.Attributes> { private static final String REST_PATH = "api/v{version}/products/{id}/attributes"; public Attributes() { super(OnlineStore.this, REST_PATH, foo.bar.client.json.entity.Attributes.class); super.id = Product.this.id; } public Attributes setValueOption(String valueOption) { super.put("value_type", valueOption); return this; } } } } public String getBaseUrl() { return "http://localhost:8083/rest-api-to-java-api/"; } }
package com.esum.comp.ws; import com.esum.common.exception.XTrusException; public class WsException extends XTrusException { public WsException(String code, String location, String message, Throwable cause) { super(code, location, message, cause); } public WsException(String location, String message, Throwable cause) { super(location, message, cause); } public WsException(String code, String location, String message) { super(code, location, message); } }
package org.example.common.captcha; import com.google.code.kaptcha.impl.DefaultKaptcha; import org.example.common.cache.CacheService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import sun.misc.BASE64Encoder; import javax.imageio.ImageIO; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Objects; import java.util.Optional; import java.util.UUID; @Service public class CaptchaServiceImpl implements CaptchaService { private static final Logger LOGGER = LoggerFactory.getLogger(CaptchaServiceImpl.class); @Autowired private CacheService cacheService; @Autowired private CaptchaSetting captchaSetting; @Autowired private DefaultKaptcha defaultKaptcha; @Override public Optional<CaptchaResponse> generateCaptcha() { RandomImage captcha = getRandom(); if (Objects.nonNull(captcha)) { String key = UUID.randomUUID().toString(); cacheService.set(key, captcha.getText().toLowerCase(), captchaSetting.getExpire()); return Optional.of(new CaptchaResponse(captcha.getImage(), key)); } return Optional.empty(); } @Override public CaptchaStatus validateCaptcha(CaptchaRequest request) { if (!cacheService.existKey(request.getKey())) { return CaptchaStatus.EXPIRED; } String captcha = (String) cacheService.get(request.getKey()); cacheService.remove(request.getKey()); if (request.getCaptcha().toLowerCase().equals(captcha)) { return CaptchaStatus.SUCCESS; } return CaptchaStatus.FAIL; } private RandomImage getRandom() { try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { String captcha = defaultKaptcha.createText(); ImageIO.write(defaultKaptcha.createImage(captcha), "png", os); return new RandomImage(captcha, new BASE64Encoder().encode(os.toByteArray())); } catch (IOException e) { LOGGER.error("get RandomImage fail", e); } return null; } }
package com.forfinance.web.controller.validator; import com.forfinance.dto.CustomerDTO; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; @Component public class CustomerValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return CustomerDTO.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "form.field.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "form.field.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "code", "form.field.required"); } }
package com.road_sidekiq.android.roadsidekiq.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.road_sidekiq.android.roadsidekiq.R; import com.road_sidekiq.android.roadsidekiq.utilities.GPSTracker; import com.road_sidekiq.android.roadsidekiq.utilities.MapRouting; /** * Created by rewin0087 on 4/18/15. */ public class LocationFragment extends BaseFragment { public static String TITLE = "MAP"; GoogleMap googleMap; MapView mapView; private GPSTracker gpsTracker; public static LocationFragment newInstance(int sectionNumber) { LocationFragment fragment = new LocationFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public LocationFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { context = getActivity().getApplicationContext(); rootView = inflater.inflate(R.layout.fragment_location, container, false); gpsTracker = new GPSTracker(context); if(gpsTracker.canGetLocation()) { MapsInitializer.initialize(getActivity()); mapView = (MapView) rootView.findViewById(R.id.map); mapView.onCreate(savedInstanceState); setUpMapIfNeeded(); } else { gpsTracker.showSettingsAlert(); } return rootView; } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (googleMap == null) { // Try to obtain the map from the SupportMapFragment. if (googleMap == null) { googleMap = ((MapView) rootView.findViewById(R.id.map)).getMap(); } // Check if we were successful in obtaining the map. if (googleMap != null) { setUpMap(); } } } @Override public void onResume() { super.onResume(); setUpMapIfNeeded(); } private void setUpMap() { CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(gpsTracker.getLatitude(), gpsTracker.getLongitude())); CameraUpdate zoom = CameraUpdateFactory.zoomTo(20); googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); googleMap.getUiSettings().setZoomGesturesEnabled(true); googleMap.getUiSettings().setZoomControlsEnabled(true); googleMap.moveCamera(center); googleMap.animateCamera(zoom); googleMap.addMarker(new MarkerOptions().position(new LatLng(gpsTracker.getLatitude(), gpsTracker.getLongitude())).title(gpsTracker.getAddressLine(context))); MapRouting mapRouting = new MapRouting(googleMap); LatLng origin = new LatLng(gpsTracker.getLatitude(), gpsTracker.getLongitude()); LatLng destination = new LatLng(14.5351, 120.9822); mapRouting.plot(origin, destination); } }
/* * (C) Copyright 2018 Fresher Academy. All Rights Reserved. * * @author viettn.admin * @date Apr 20, 2018 * @version 1.0 */ package edu.fa.pattern.factory; import edu.fa.model.Manager; import edu.fa.model.Programmer; import edu.fa.model.Tester; public class Application { public static void main(String[] args) { HrFactory hrFactory = new HrFactory(); Manager manager = (Manager) hrFactory.createEmployee("Manager"); Tester tester = (Tester) hrFactory.createEmployee("Tester"); Programmer programmer = (Programmer) hrFactory.createEmployee("Programmer"); manager.work(); tester.work(); programmer.work(); } }
package com.example.aizat.alarmclock.screen.main.first.wakeUp; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; import android.support.annotation.IntDef; import android.support.annotation.Nullable; import android.util.Log; import com.example.aizat.alarmclock.R; /** * Created by Aizat on 08.11.2017. */ public class RingtonePlayingService extends Service{ MediaPlayer media_song; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { String value = intent.getStringExtra("key"); if (value.equals("alarm on")) { media_song = MediaPlayer.create(this, R.raw.song); media_song.start(); }else { media_song.stop(); media_song.reset(); } return START_NOT_STICKY; } }
package com.logicbig.example; import javax.annotation.PostConstruct; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class TradeService { private HashMap<Long, Trade> trades = new HashMap<>(); @PostConstruct private void postConstruct () { //just populating with some dummy data //in real application will get the data from a database List<Currency> ccy = new ArrayList(Currency.getAvailableCurrencies()); ThreadLocalRandom rnd = ThreadLocalRandom.current(); for (int i = 1; i <= 10; i++) { Trade trade = new Trade(); trade.setTradeId(i); trade.setBuySell(Math.random() > 0.5 ? "Buy" : "Sell"); trade.setBuyCurrency(ccy.get(rnd.nextInt(0, ccy.size())) .getCurrencyCode()); trade.setSellCurrency(ccy.get(rnd.nextInt(0, ccy.size())) .getCurrencyCode()); trades.put((long) i, trade); } } public Trade getTradeById (long id) { return trades.get(id); } public List<Trade> getAllTrades () { return new ArrayList<>(trades.values()); } }
package com.bofsoft.laio.customerservice.DataClass.Order; import java.util.ArrayList; /** * Created by jason.xu on 2017/3/27. */ public class OrderList { private ArrayList<Order> OrderList = new ArrayList<Order>(); private Integer TotalCount; private boolean More; public ArrayList<Order> getOrderList() { return OrderList; } public void setOrderList(ArrayList<Order> orderList) { OrderList = orderList; } public Integer getTotalCount() { return TotalCount; } public void setTotalCount(Integer totalCount) { TotalCount = totalCount; } public boolean isMore() { return More; } public void setMore(boolean more) { More = more; } public static class Order { private Integer Id; private String Num; private String Name; private String View; private Integer GroupDM; private Integer OrderType; private Integer Status; private Integer StatusTrain; private Integer CanCancel; private Integer PayDeposit; private Integer StatusAppraise; private Integer StatusAccepted; private Integer RefundStatus; private String DeadTime; private String ConfirmTime; private ArrayList<OrderVasList> VasList = new ArrayList<>(); private String OrderTime; private String CoachName; private String CarType; private Double Deposit; private Double DealSum; private Integer RegType; private Integer TrainType; private Integer TestSubId; private String TestSub; private String CarModel; private String TrainStartTime; private String TrainEndTime; private String CustomerCode; private String BuyerName; private String BuyerTel; private String ProPicUrl; private Integer InviteCanRegister; public String getProPicUrl() { return ProPicUrl; } public void setProPicUrl(String proPicUrl) { ProPicUrl = proPicUrl; } public Integer getId() { return Id; } public void setId(Integer id) { Id = id; } public String getNum() { return Num; } public void setNum(String num) { Num = num; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getView() { return View; } public void setView(String view) { View = view; } public Integer getGroupDM() { return GroupDM; } public void setGroupDM(Integer groupDM) { GroupDM = groupDM; } public Integer getOrderType() { return OrderType; } public void setOrderType(Integer orderType) { OrderType = orderType; } public Integer getStatus() { return Status; } public void setStatus(Integer status) { Status = status; } public Integer getStatusTrain() { return StatusTrain; } public void setStatusTrain(Integer statusTrain) { StatusTrain = statusTrain; } public Integer getCanCancel() { return CanCancel; } public void setCanCancel(Integer canCancel) { CanCancel = canCancel; } public Integer getPayDeposit() { return PayDeposit; } public void setPayDeposit(Integer payDeposit) { PayDeposit = payDeposit; } public Integer getStatusAppraise() { return StatusAppraise; } public void setStatusAppraise(Integer statusAppraise) { StatusAppraise = statusAppraise; } public Integer getStatusAccepted() { return StatusAccepted; } public void setStatusAccepted(Integer statusAccepted) { StatusAccepted = statusAccepted; } public Integer getRefundStatus() { return RefundStatus; } public void setRefundStatus(Integer refundStatus) { RefundStatus = refundStatus; } public String getDeadTime() { return DeadTime; } public void setDeadTime(String deadTime) { DeadTime = deadTime; } public String getConfirmTime() { return ConfirmTime; } public void setConfirmTime(String confirmTime) { ConfirmTime = confirmTime; } public ArrayList<OrderVasList> getVasList() { return VasList; } public void setVasList(ArrayList<OrderVasList> vasList) { VasList = vasList; } public String getOrderTime() { return OrderTime; } public void setOrderTime(String orderTime) { OrderTime = orderTime; } public String getCoachName() { return CoachName; } public void setCoachName(String coachName) { CoachName = coachName; } public String getCarType() { return CarType; } public void setCarType(String carType) { CarType = carType; } public Double getDeposit() { return Deposit; } public void setDeposit(Double deposit) { Deposit = deposit; } public Double getDealSum() { return DealSum; } public void setDealSum(Double dealSum) { DealSum = dealSum; } public Integer getRegType() { return RegType; } public void setRegType(Integer regType) { RegType = regType; } public Integer getTrainType() { return TrainType; } public void setTrainType(Integer trainType) { TrainType = trainType; } public Integer getTestSubId() { return TestSubId; } public void setTestSubId(Integer testSubId) { TestSubId = testSubId; } public String getTestSub() { return TestSub; } public void setTestSub(String testSub) { TestSub = testSub; } public String getCarModel() { return CarModel; } public void setCarModel(String carModel) { CarModel = carModel; } public String getTrainStartTime() { return TrainStartTime; } public void setTrainStartTime(String trainStartTime) { TrainStartTime = trainStartTime; } public String getTrainEndTime() { return TrainEndTime; } public void setTrainEndTime(String trainEndTime) { TrainEndTime = trainEndTime; } public String getCustomerCode() { return CustomerCode; } public void setCustomerCode(String customerCode) { CustomerCode = customerCode; } public String getBuyerName() { return BuyerName; } public void setBuyerName(String buyerName) { BuyerName = buyerName; } public String getBuyerTel() { return BuyerTel; } public void setBuyerTel(String buyerTel) { BuyerTel = buyerTel; } public Integer getInviteCanRegister() { return InviteCanRegister; } public void setInviteCanRegister(Integer inviteCanRegister) { InviteCanRegister = inviteCanRegister; } } public static class OrderVasList { private String Id; private Integer VasType; private String Name; private Integer VasAmount; private Double VasPrice; public String getId() { return Id; } public void setId(String id) { Id = id; } public Integer getVasType() { return VasType; } public void setVasType(Integer vasType) { VasType = vasType; } public String getName() { return Name; } public void setName(String name) { Name = name; } public Integer getVasAmount() { return VasAmount; } public void setVasAmount(Integer vasAmount) { VasAmount = vasAmount; } public Double getVasPrice() { return VasPrice; } public void setVasPrice(Double vasPrice) { VasPrice = vasPrice; } public Double getVasTotal() { return VasTotal; } public void setVasTotal(Double vasTotal) { VasTotal = vasTotal; } private Double VasTotal; } }
package com.example.BSD; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import android.content.Context; import android.os.AsyncTask; import android.util.Log; public class DatabaseData extends AsyncTask<Void, Void, String> { private InputStream inputStream = null; private String result = ""; private Context c; public DatabaseData(Context c) { super(); this.c = c; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(Void... params) { //De url waar de totale data in json formaat in staat String url_select = "http://bsd.net76.net/db_verbinding/bsd_complete_data_extraction.php"; ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); try { // HttpClient is more then less deprecated. Need to change to URLConnection HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_select); httpPost.setEntity(new UrlEncodedFormEntity(param)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); // Read content & Log inputStream = httpEntity.getContent(); } catch (UnsupportedEncodingException e1) { Log.e("UnsupportedEncodingException", e1.toString()); e1.printStackTrace(); } catch (ClientProtocolException e2) { Log.e("ClientProtocolException", e2.toString()); e2.printStackTrace(); } catch (IllegalStateException e3) { Log.e("IllegalStateException", e3.toString()); e3.printStackTrace(); } catch (IOException e4) { Log.e("IOException", e4.toString()); e4.printStackTrace(); } // Convert response to string using String Builder try { BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8); StringBuilder sBuilder = new StringBuilder(); String line = null; while ((line = bReader.readLine()) != null) { sBuilder.append(line + "\n"); } inputStream.close(); result = sBuilder.toString(); } catch (Exception e) { Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString()); } //Delete analytics code uit de response result = result.substring(0, result.indexOf('<')); //Geef het resultaat terug return result; } @Override protected void onPostExecute(String result) { //Update de andere elementen uit de applicatie try { NieuwsDatabaseData.setup(c, result); CursussenDatabaseData.setup(c, result); } catch (JSONException e) { e.printStackTrace(); } NieuwsLijstFragment.refreshListview(); MainActivity.updateVakgebiedList(); super.onPostExecute(result); } }
package com.omg.omguw; import android.text.Spanned; /** * Stores data used to handle a post */ public class OMG { private String date; private Spanned content; private int ID; private String CommentURL; /** * Constructor * * @param date : The posting date * @param content : The content of the post * @param id : The ID of the post * @param commentURL : The URL to the post's comments */ public OMG(String date, Spanned content, int id, String commentURL) { super(); this.date = date; this.content = content; ID = id; CommentURL = commentURL; } //Accessors and mutators for class variables public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Spanned getContent() { return content; } public void setContent(Spanned content) { this.content = content; } public int getType() { return ID; } public void setType(int ID) { this.ID = ID; } public String getCommentURL() { return CommentURL; } public void setCommentURL(String commentURL) { CommentURL = commentURL; } }
package pers.mine.scratchpad.base; import java.util.stream.IntStream; /** * avoid getfield opcode * * @see String#trim() */ public class AvoidGetfieldOpcodeTest { private final long[] val = {0}; static { System.out.println("static init"); } { System.out.println("initX"); } public AvoidGetfieldOpcodeTest() { System.out.println("init"); } public void reset() { val[0] = 0; } public void changeVal() { for (int i = 0; i < 1000 * 1000 * 1000; i++) { val[0] += i; } } public void changeValLocal() { long[] val = this.val; for (int i = 0; i < 1000 * 1000 * 1000; i++) { val[0] += i; } } /** * 测试下来速度提升很轻微 */ public static void main(String[] args) { AvoidGetfieldOpcodeTest test = new AvoidGetfieldOpcodeTest(); long start = System.nanoTime(); IntStream.range(0, 100).forEach(i -> { test.reset(); test.changeValLocal(); }); System.out.println(System.nanoTime() - start); start = System.nanoTime(); IntStream.range(0, 100).forEach(i -> { test.reset(); test.changeVal(); }); System.out.println(System.nanoTime() - start); } }
package br.com.projetoSap; import java.util.ArrayList; import java.util.List; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @Configuration @EnableAsync @EnableScheduling @EnableJpaRepositories @EnableTransactionManagement @ComponentScan(basePackages = {"br.com.projetoSap"}) @EnableAutoConfiguration @SpringBootApplication @RestController public class ProjetoSapApplication { public static void main(String[] args) { SpringApplication.run(ProjetoSapApplication.class, args); } @RequestMapping(path="/contatos", method= RequestMethod.GET) public List<Contato> listar(){ List<Contato> contatos = new ArrayList<>(); Contato c = new Contato(); c.setNome("Teste"); contatos.add(c); return contatos; } }
package net.itcast.course.regex.basic.lesson2; public class DotMatchMind { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String dot = "."; String lineFeed = "\n"; if(regexMatch(lineFeed, dot)) { System.out.println("Dot can match LineFeed"); } else { System.out.println("Dot can not match LineFeed"); } } public static boolean regexMatch(String s, String regex) { return s.matches(regex); } }
package machine_learning; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class KDTree { // The inner node of kdtree. class KDTreeNode{ public KDTreeNode left = null; public KDTreeNode right = null; public double[] vec = null; public int split_dimension; public KDTreeNode(double[] v, int split) { this.vec = v; this.split_dimension = split; } @Override public String toString() { int len = vec.length; StringBuilder sb = new StringBuilder(); sb.append("("); for(int i=0;i<len;i++){ sb.append(vec[i]); if(i != len-1) sb.append(","); } sb.append(")"); return sb.toString(); } } // The data with an index. class Pair{ public int index; public double[] data_vector; public Pair(int i, int n) { index = i; data_vector = new double[n]; } } // The dimension of data. private int N; // The number of data entries. private int M; // DataSet. private List<Pair> dataSet; // RootNode. private KDTreeNode rootNode = null; /** * * @param data * @param split * @return */ private KDTreeNode buildTree(List<Pair> data, final int split){ if(data == null || data.size() == 0) return null; Comparator<Pair> comparator = new Comparator<Pair>(){ public int compare(Pair o1, Pair o2) { double v1 = o1.data_vector[split]; double v2 = o2.data_vector[split]; return v1<=v2?-1:1; } }; Collections.sort(data, comparator); int middle = data.size()/2; KDTreeNode root = new KDTreeNode(data.get(middle).data_vector, split); List<Pair> left_data = new ArrayList<Pair>(); List<Pair> right_data = new ArrayList<Pair>(); for(int i=0;i<middle;i++) left_data.add(data.get(i)); for(int i=middle+1;i<data.size();i++) right_data.add(data.get(i)); root.left = buildTree(left_data, (split+1)%N); root.right = buildTree(right_data, (split+1)%N); return root; } /** * */ public KDTree(double[][] data) { initTree(data); } /** * * @param data */ private void initTree(double[][] data){ this.M = data.length; this.N = data[0].length; this.dataSet = new ArrayList<Pair>(); for(int i=0;i<M;i++){ Pair p = new Pair(i, N); dataSet.add(p); for(int j=0;j<N;j++) p.data_vector[j] = data[i][j]; } rootNode = buildTree(dataSet, 0); } public double nearestDistance; public double[] nearestData; /** * * @Title: searchNearestRecursively * @Description: TODO * @param: @param vec * @param: @param root * @return: void * @throws */ private void searchNearestRecursively(double[] vec, KDTreeNode root){ if(root == null) return; int split = root.split_dimension; double dist = MatrixUtils.calcDist(vec, root.vec); if(dist<nearestDistance){ nearestDistance = dist; nearestData = root.vec; } if(vec[split]<=root.vec[split]) searchNearestRecursively(vec, root.left); else searchNearestRecursively(vec, root.right); if(Math.abs(vec[split]-root.vec[split])<nearestDistance){ if(vec[split]<=root.vec[split]) searchNearestRecursively(vec, root.right); else searchNearestRecursively(vec, root.left); } } /** * * @Title: searchNearest * @Description: TODO * @param: @param vec * @return: void * @throws */ public void searchNearest(double[] vec){ nearestDistance = Double.MAX_VALUE; nearestData = null; searchNearestRecursively(vec, rootNode); } /** * * @Title: getRootNode * @Description: TODO * @param: @return * @return: KDTreeNode * @throws * @author UncleLee */ public KDTreeNode getRootNode() { return rootNode; } public static void main(String[] args) { double[][] data = {{2., 0.}, {6.5,4.},{9.,6.},{4.,117.},{8.,5},{7.,2.}}; KDTree kd = new KDTree(data); double[] vec = {3,23}; kd.searchNearest(vec); double res = kd.nearestDistance; double[] d = kd.nearestData; System.out.println(res); for(int i=0;i<d.length;i++) System.out.print(" "+d[i]); } }
package Servlet; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; 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 javax.servlet.http.HttpSession; import value.CheckinValue; import connection.ConnectionClass; @WebServlet(name="Checkin",urlPatterns={"jsp/Checkin"}) public class Checkin extends HttpServlet { private static final long serialVersionUID = 1L; public Checkin() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); String kw= request.getParameter("sfcheckin"); ConnectionClass obj = new ConnectionClass(); Connection con = null; try { con = obj.getConnection(); } catch (Exception e1) { e1.printStackTrace(); } CheckinValue CheckinValue = new CheckinValue(); ArrayList<String> isbn = new ArrayList<String>(); ArrayList<String> fname = new ArrayList<String>(); ArrayList<String> lname = new ArrayList<String>(); ArrayList<String> checkoutBy = new ArrayList<String>(); try { PreparedStatement ps=con.prepareStatement("select b.isbn, b1.card_id, b1.last_name,b1.first_name from book_loans b, borrower b1 where ( b.Card_id=b1.Card_id AND b.Date_in IS NULL AND (b.isbn LIKE '%"+kw+"%' OR b1.card_id LIKE '%"+kw+"%' OR concat(b1.last_name,' ', b1.first_name) LIKE '%"+kw+"%'))"); System.out.println(ps); ResultSet rs=ps.executeQuery(); while(rs.next()) { isbn.add(rs.getString(1)); checkoutBy.add(rs.getString(2)); lname.add(rs.getString(3)); fname.add(rs.getString(4)); } if(isbn!=null & checkoutBy!=null & lname!=null & fname!=null ) { CheckinValue.setIsbn(isbn); CheckinValue.setCheckoutBy(checkoutBy); CheckinValue.setFName(fname); CheckinValue.setLName(lname); } if(CheckinValue!=null && !isbn.isEmpty()) { session.setAttribute("checkinvalues", CheckinValue); session.setAttribute("valcheckin", "present"); } else{ System.out.println("empty"); session.setAttribute("valcheckin", "empty"); } } catch (SQLException e) { e.printStackTrace(); } response.sendRedirect("jsp/index.jsp"); } }
package com.allure.service.constants; /** * Created by yann on 2017/8/12. */ public enum AuditStatus { Pending, Audited, Rejected }
package com.fang.controller; import java.awt.List; import java.util.ArrayList; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.fang.bean.LoginEnterIn; import com.fang.common.Identity; import com.fang.service.LoginService; @Controller @RequestMapping("/login") public class LoginController { @Autowired private LoginService loginService; @RequestMapping(value = "/login.do") public String Login(HttpServletRequest request, HttpServletResponse response) { // System.out.println("hash1:" + request.hashCode()); // System.out.println("response:" + response.hashCode()); Identity.getUser(); return "login"; } @RequestMapping(value = "/enter.do") @ResponseBody public String Enter(HttpServletRequest request, HttpServletResponse response, LoginEnterIn model) { loginService.login(request, response, model); // System.out.println("111111111111"); System.out.println("enter.do:" + model); System.out.println("enter.do:" + model.getEmail()); System.out.println("enter.do:" + model.getPassword()); System.out.println("enter.do:" + model.getPhone()); return "{\"success\":1}"; } }
package com.raymon.api.demo.leetcodedemo; /** * @author :raymon * @date :Created in 2019/7/22 13:28 * @description:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 * @modified By: * @version: 1.0$ */ public class FirstUniqChar { public static int firstUniqChar(String str){ int[] freq = new int[26]; for (int i = 0; i < str.length(); i++){ freq[str.charAt(i) - 'a']++; } for (int i = 0; i < str.length(); i++){ if (freq[str.charAt(i) - 'a'] == 1){ System.out.println(i); return i; } } return -1; } public static void main(String[] args) { String str = "loveleetcode"; firstUniqChar(str); } }
package com.git.cloud.taglib.dic; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletRequest; import javax.servlet.jsp.JspException; import org.apache.commons.beanutils.PropertyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.tags.RequestContextAwareTag; /** * @author wxg * */ public class DictionaryTag extends RequestContextAwareTag { private Logger logger = LoggerFactory.getLogger(this.getClass()); private IDictionaryTagDao dictionaryTagDao; private static final String _START_PAGE = "/pages/taglib/dic/start.jsp"; private static final String _END_PAGE = "/pages/taglib/dic/end.jsp"; private String name; // 字典项的CODE值 private String value; // 字典KIND private String kind; private boolean multiSelect; private boolean readOnly; private boolean onlyShow; private String showType; private String attr; private String id; // 值对象来源 private String source; // 静态字典 staticDic类似如"0:***;1:***;2:***" private String staticDic; // 直接使用sql构造字典,sql类似如"select ×× as CODE,×× as DETAIL,×× as REMARK from ××" private String sql; // 默认值 private String defaultValue; // 排序 private String order; // 是否可对select进行编辑 private boolean canEdit; private boolean newLine; //点击事件 private String click; //默认级联方法名 private String cascade; public boolean isNewLine() { return newLine; } public void setNewLine(boolean newLine) { this.newLine = newLine; } public boolean isCanEdit() { return canEdit; } public void setCanEdit(boolean canEdit) { this.canEdit = canEdit; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } public String getShowType() { return showType; } public void setShowType(String showType) { this.showType = showType; } public String getAttr() { return attr; } public void setAttr(String attr) { this.attr = attr; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getStaticDic() { return staticDic; } public void setStaticDic(String staticDic) { this.staticDic = staticDic; } @SuppressWarnings("unchecked") public int doStartTagInternal() throws JspException { ServletRequest request = pageContext.getRequest(); // String[] locations = { // "/config/spring/applicationContext-common-ds.xml", // "/config/spring/applicationContext-taglib.xml", // "/config/spring/applicationContext-common.xml" // }; // ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(locations); dictionaryTagDao = (IDictionaryTagDao) this.getRequestContext().getWebApplicationContext().getBean("dictionaryTagDao"); try { if (this.value != null) { if (this.source != null) { Object obj = request.getAttribute(this.source); if (obj == null) { obj = pageContext.getAttribute(this.source); } if (obj != null) { if (obj instanceof Map) { Map map = (Map) obj; this.value = (String) map.get(this.value); } else { this.value = (String) PropertyUtils.getNestedProperty(obj, this.value); } } } if (this.value == null) { this.value = this.defaultValue; } if (this.value == null) { this.value = ""; } } List list = new ArrayList(); if (this.kind != null) { List<DictionaryTag> resultList = dictionaryTagDao.getDicList(this); // if ("desc".equals(this.getOrder())) { // resultList = SortUtils.sortByProperty(resultList, "value", "desc"); // }else{ // resultList = SortUtils.sortByProperty(resultList, "value", "asc"); // } for(DictionaryTag obj:resultList){ Map dicMap = new HashMap(); dicMap.put("CODE", obj.getValue()); dicMap.put("DETAIL", obj.getName()); list.add(dicMap); } } else if (this.sql != null) { List<DictionaryTag> resultList = dictionaryTagDao.getDicListBySql(this.getSql()); if (this.order != null){ if ("desc".equals(this.getOrder())) { resultList = SortUtils.sortByProperty(resultList, "value", "desc"); }else{ resultList = SortUtils.sortByProperty(resultList, "value", "asc"); } } for(DictionaryTag obj:resultList){ Map dicMap = new HashMap(); dicMap.put("CODE", obj.getValue()); dicMap.put("DETAIL", obj.getName()); list.add(dicMap); } } else if (this.staticDic != null) { // 静态字典构造 list = new ArrayList(); String[] dic = this.staticDic.split(";"); for (int i = 0; i < dic.length; i++) { Map dicMap = new HashMap(); dicMap.put("CODE", dic[i].substring(0, dic[i].indexOf(":"))); dicMap.put("DETAIL", dic[i].substring(dic[i].indexOf(":") + 1)); list.add(dicMap); } } request.setAttribute("dt_dic", this); request.setAttribute("dt_list", list); pageContext.include(_START_PAGE); } catch (Exception e) { logger.error("异常exception",e); } return EVAL_PAGE; } public int doEndTag() throws JspException { try { pageContext.include(_END_PAGE); } catch (Exception e) { logger.error("异常exception",e); } return EVAL_PAGE; } public String getDefaultValue() { return defaultValue; } public boolean isMultiSelect() { return multiSelect; } public void setMultiSelect(boolean multiSelect) { this.multiSelect = multiSelect; } public boolean isOnlyShow() { return onlyShow; } public void setOnlyShow(boolean onlyShow) { this.onlyShow = onlyShow; } public boolean isReadOnly() { return readOnly; } public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public String getStartPage() { return _START_PAGE; } public String getEndPage() { return _END_PAGE; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getClick() { return click; } public void setClick(String click) { this.click = click; } public IDictionaryTagDao getDictionaryTagDao() { return dictionaryTagDao; } public void setDictionaryTagDao(IDictionaryTagDao dictionaryTagDao) { this.dictionaryTagDao = dictionaryTagDao; } public String getCascade() { return cascade; } public void setCascade(String cascade) { this.cascade = cascade; } }
package com.company.javasample; import static org.junit.Assert.*; import java.util.Arrays; import org.junit.Test; public class SubArrayLargestSumTest { int [][] testData = { {0, 1, 2, 3}, {3, 2, 1, 0}, {0, 0, 1, 0}, {-1, 1, 2, 3}, {-1, 1, 2, -2}, {-100, 100, -50, 50}, {-100, 100, -50, 50, 1}, {-1, 2, -3, 4, -5, 6} }; // int [][] testData = { // {-100, 100, -50, 50} // }; @Test public void testCalculate() { SubArrayLargestSum subArrayLargestSum = new SubArrayLargestSum(); for (int [] array : testData) { System.out.println(Arrays.toString(array) + " : " + subArrayLargestSum.calculate(array)); } } }
package com.socialmeeting.domain; public class Language { }
package com.infoworks.lab.rest.validation.CurrencyCode; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.Currency; public class CurrencyCodeConstraint implements ConstraintValidator<IsValidCurrencyCode, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) return false; if (!value.isEmpty()){ try { Currency currency = Currency.getInstance(value); return currency != null; } catch (Exception e) {} } return false; } }
package hu.mitro.webservice; import java.util.Date; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import hu.mitro.ejb.domain.ContractStub; import hu.mitro.ejb.exception.FacadeLayerException; @Path("/contract") public interface ContractRestService { @GET @Path("/car/{carlpn}") @Produces("application/json") ContractStub getContractByCar(@PathParam("carlpn") String licencePlateNumber) throws FacadeLayerException; @GET @Path("/client/{clientemail}") @Produces("application/json") List<ContractStub> getContractByClient(@PathParam("clientemail") String clientEmail) throws FacadeLayerException; @GET @Path("/contractid/{contractid}") @Produces("application/json") ContractStub getContractByContractId(@PathParam("contractid") String contractid) throws FacadeLayerException; @GET @Path("/date/{date}") @Produces("application/json") List<ContractStub> getContractByDate(@PathParam("date") Date date) throws FacadeLayerException; @GET @Path("/id/{id}") @Produces("application/json") ContractStub getContractById(@PathParam("id") String id) throws FacadeLayerException; @GET @Path("/list") @Produces("application/json") List<ContractStub> getContracts() throws FacadeLayerException; @POST @Path("/add") @Consumes("application/json") @Produces("application/json") ContractStub addContract(ContractStub contractStub) throws FacadeLayerException; @POST @Path("/update") @Consumes("application/json") @Produces("application/json") ContractStub updateContract(ContractStub contractStub) throws FacadeLayerException; @POST @Path("/remove") @Consumes("application/json") @Produces("application/json") ContractStub removeContract(ContractStub contractStub) throws FacadeLayerException; }
package validation; import javafx.scene.control.ComboBox; import validation.annotations.FXNotNull; import java.lang.reflect.Field; public class AnnotionHandle { public static void annotionHanle(Class<?> clazz){ Field[] fields = clazz.getDeclaredFields(); for (Field f:fields) if (f.isAnnotationPresent(FXNotNull.class)) { System.out.println(f); } } }
package com.test.pg.sampleapp; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Html; import android.view.KeyEvent; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import android.widget.Toast; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URLDecoder; public class PaymentActivity extends AppCompatActivity { ProgressBar pb; WebView webview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_payment); webview = findViewById(R.id.webview); pb = findViewById(R.id.progressBar); pb.setVisibility(View.VISIBLE); String calculatedHash= getIntent().getStringExtra("calculatedHash"); //Before initiating payment, you should calculate the hash for the payment request parameters. //Please refer to the integration documentation for more details. //Now again create a query string of the payment parameters with hash obtained from the previous activity. try{ StringBuffer requestParams=new StringBuffer("api_key="+URLDecoder.decode(SampleAppConstants.PG_API_KEY, "UTF-8")); requestParams.append("&amount="+URLDecoder.decode(SampleAppConstants.PG_AMOUNT, "UTF-8")); requestParams.append("&email="+URLDecoder.decode(SampleAppConstants.PG_EMAIL, "UTF-8")); requestParams.append("&name="+URLDecoder.decode(SampleAppConstants.PG_NAME, "UTF-8")); requestParams.append("&phone="+URLDecoder.decode(SampleAppConstants.PG_PHONE, "UTF-8")); requestParams.append("&order_id="+URLDecoder.decode(SampleAppConstants.PG_ORDER_ID, "UTF-8")); requestParams.append("&currency="+URLDecoder.decode(SampleAppConstants.PG_CURRENCY, "UTF-8")); requestParams.append("&description="+URLDecoder.decode(SampleAppConstants.PG_DESCRIPTION, "UTF-8")); requestParams.append("&city="+URLDecoder.decode(SampleAppConstants.PG_CITY, "UTF-8")); requestParams.append("&state="+URLDecoder.decode(SampleAppConstants.PG_STATE, "UTF-8")); requestParams.append("&address_line_1="+URLDecoder.decode(SampleAppConstants.PG_ADD_1, "UTF-8")); requestParams.append("&address_line_2="+URLDecoder.decode(SampleAppConstants.PG_ADD_2, "UTF-8")); requestParams.append("&zip_code="+URLDecoder.decode(SampleAppConstants.PG_ZIPCODE, "UTF-8")); requestParams.append("&country="+URLDecoder.decode(SampleAppConstants.PG_COUNTRY, "UTF-8")); requestParams.append("&return_url="+URLDecoder.decode(SampleAppConstants.PG_RETURN_URL, "UTF-8")); requestParams.append("&mode="+URLDecoder.decode(SampleAppConstants.PG_MODE, "UTF-8")); requestParams.append("&udf1="+URLDecoder.decode(SampleAppConstants.PG_UDF1, "UTF-8")); requestParams.append("&udf2="+URLDecoder.decode(SampleAppConstants.PG_UDF2, "UTF-8")); requestParams.append("&udf3="+URLDecoder.decode(SampleAppConstants.PG_UDF3, "UTF-8")); requestParams.append("&udf4="+URLDecoder.decode(SampleAppConstants.PG_UDF4, "UTF-8")); requestParams.append("&udf5="+URLDecoder.decode(SampleAppConstants.PG_UDF5, "UTF-8")); requestParams.append("&hash="+URLDecoder.decode(calculatedHash, "UTF-8")); webview.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { pb.setVisibility(View.GONE); if(url.equals(SampleAppConstants.PG_RETURN_URL)){ view.setVisibility(View.GONE); view.loadUrl("javascript:HtmlViewer.showHTML" + "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');"); } } @Override public void onPageStarted(WebView view, String url, Bitmap facIcon) { pb.setVisibility(View.VISIBLE); } }); WebSettings webSettings = webview.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); webSettings.setDomStorageEnabled(true); webview.addJavascriptInterface(new MyJavaScriptInterface(), "HtmlViewer"); //Not POST the query string obtained above to Payment Gateway's Payment API in a webview. webview.postUrl(SampleAppConstants.PG_HOSTNAME+"/v2/paymentrequest",requestParams.toString().getBytes()); }catch (Exception e){ StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String exceptionAsString = sw.toString(); Toast.makeText(getBaseContext(), exceptionAsString,Toast.LENGTH_SHORT).show(); } } class MyJavaScriptInterface { @JavascriptInterface public void showHTML(String html) { //On completion of the payment, the response from your WebServer's API will be obtained here. Intent intent=new Intent(getBaseContext(), ResponseActivity.class); intent.putExtra("payment_response", Html.fromHtml(html).toString()); startActivity(intent); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (webview.canGoBack()) { webview.goBack(); } else { finish(); } return true; } } return super.onKeyDown(keyCode, event); } }
import java.util.Arrays; /** * Created with IntelliJ IDEA. * User: dexctor * Date: 12-12-3 * Time: 下午7:33 * To change this template use File | Settings | File Templates. */ public class p2_2_21 { public static void main(String[] args) { int N = StdIn.readInt(); int[] list1 = new int[N]; int[] list2 = new int[N]; int[] list3 = new int[N]; for(int i = 0; i < N; ++i) { list1[i] = StdRandom.uniform(0, N); list2[i] = StdRandom.uniform(0, N); list3[i] = StdRandom.uniform(0, N); } Arrays.sort(list1); Arrays.sort(list2); Arrays.sort(list3); StdOut.println(Arrays.toString(list1)); StdOut.println(Arrays.toString(list2)); StdOut.println(Arrays.toString(list3)); int i = 0; int k = 0; int j = 0; while(true) { if(i >= list1.length || j >= list2.length || k >= list3.length) return; if(list1[i] == list2[j] && list1[i] == list3[k]) { StdOut.println(list1[i]); return; } if(list1[i] <= list2[j] && list1[i] <= list3[k]) i++; else if(list2[j] <= list1[i] && list2[j] <= list3[k]) j++; else k++; } } }
package Logica; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class FormatoFechas { private String fechaString; private String horaString; public FormatoFechas() { } public FormatoFechas(String fechaString, String horaString) { this.fechaString = fechaString; this.horaString = horaString; } public String getFechaString() { return fechaString; } public String getHoraString() { return horaString; } public void setFechaString(String fechaString) { this.fechaString = fechaString; } public void setHoraString(String horaString) { this.horaString = horaString; } public static Date convertirHoraStringADate (String horaStr) throws ParseException { String horaString = horaStr; SimpleDateFormat formatoHora = new SimpleDateFormat("HH:mm"); Date horaCompleta = new Date(); horaCompleta = formatoHora.parse(horaString); System.out.println("La hora es: " + horaCompleta); return horaCompleta; } public static synchronized java.util.Date deStringToDate(String fecha) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //formato guión año-mes-día Date fechaEnviar = null; try { fechaEnviar = df.parse(fecha); return fechaEnviar; } catch (ParseException ex) { return null; } } public static String DateAString(Date fecha){ SimpleDateFormat formatoFecha = new SimpleDateFormat("yyyy-MM-dd"); return formatoFecha.format(fecha); } public static String DateHoraAString(Date fecha){ SimpleDateFormat formatoFecha = new SimpleDateFormat("HH:mm"); return formatoFecha.format(fecha); } }
package br.com.fiap.fiapinteliBe21.repository; import org.springframework.data.jpa.repository.JpaRepository; import br.com.fiap.fiapinteliBe21.domain.FormItem; public interface FormItemRepository extends JpaRepository<FormItem, Long>{ }
package co.id.datascrip.mo_sam_div4_dts1.process; import android.app.ProgressDialog; import android.content.Context; import org.json.JSONObject; import java.util.ArrayList; import co.id.datascrip.mo_sam_div4_dts1.Function; import co.id.datascrip.mo_sam_div4_dts1.Global; import co.id.datascrip.mo_sam_div4_dts1.callback.CallbackKegiatan; import co.id.datascrip.mo_sam_div4_dts1.object.Kegiatan; import co.id.datascrip.mo_sam_div4_dts1.process.interfaces.IC_Kegiatan; import co.id.datascrip.mo_sam_div4_dts1.sqlite.KegiatanSQLite; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static co.id.datascrip.mo_sam_div4_dts1.Global.SISTEM; public class Process_Kegiatan { public static final String ACTION_CANCEL = "cancel"; public static final String ACTION_KETERANGAN = "keterangan"; public static final String ACTION_RESULT = "result"; public static final String ACTION_CHECK_IN = "in"; public static final String ACTION_CHECK_OUT = "out"; public static final String ACTION_REFRESH_TODAY = "refresh_today"; public static final String ACTION_REFRESH_DATE = "refresh_date"; private Context context; private ProgressDialog progressDialog; public Process_Kegiatan(Context context) { this.context = context; progressDialog = new ProgressDialog(context); progressDialog.setMessage("Loading..."); progressDialog.setCancelable(false); progressDialog.show(); } public void Post(final Kegiatan kegiatan, final CallbackKegiatan.CBPost CB) { IC_Kegiatan service = Global.CreateRetrofit(context).create(IC_Kegiatan.class); service.Post(makeJSON(kegiatan)).enqueue(new retrofit2.Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { String result = RetrofitResponse.getString(context, response); new Function(context).writeToText("Kegiatan->Post", result); Kegiatan kegiatan_ = kegiatan; kegiatan_ = RetrofitResponse.getIDKegiatan(kegiatan_, result); new KegiatanSQLite(context).Post(kegiatan_); CB.onCB(kegiatan_); progressDialog.dismiss(); } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function(context).writeToText("Kegiatan->Post", throwable.getMessage()); throwable.getCause(); progressDialog.dismiss(); } }); } public void Action(final Kegiatan kegiatan, final String action, final CallbackKegiatan.CBAction CB) { IC_Kegiatan IC = Global.CreateRetrofit(context).create(IC_Kegiatan.class); String json = makeJSON(action, kegiatan); switch (action) { case ACTION_CANCEL: IC.Cancel(json).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { String result = RetrofitResponse.getString(context, response); new Function(context).writeToText("Kegiatan->Action->" + action, result); if (RetrofitResponse.isSuccess(result)) new KegiatanSQLite(context).Cancel(kegiatan); CB.onCB(kegiatan); if (progressDialog != null) progressDialog.dismiss(); } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function(context).writeToText("Kegiatan->Action->" + action, throwable.getMessage()); throwable.getCause(); if (progressDialog != null) progressDialog.dismiss(); } }); break; case ACTION_KETERANGAN: IC.Keterangan(json).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { String result = RetrofitResponse.getString(context, response); new Function(context).writeToText("Kegiatan->Action->" + action, result); if (RetrofitResponse.isSuccess(result)) new KegiatanSQLite(context).Keterangan(kegiatan); CB.onCB(kegiatan); if (progressDialog != null) progressDialog.dismiss(); } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function(context).writeToText("Kegiatan->Action->" + action, throwable.getMessage()); throwable.getCause(); if (progressDialog != null) progressDialog.dismiss(); } }); break; case ACTION_RESULT: IC.Result(json).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { String result = RetrofitResponse.getString(context, response); new Function(context).writeToText("Kegiatan->Action->" + action, result); if (RetrofitResponse.isSuccess(result)) new KegiatanSQLite(context).Result(kegiatan); CB.onCB(kegiatan); if (progressDialog != null) progressDialog.dismiss(); } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function(context).writeToText("Kegiatan->Action->" + action, throwable.getMessage()); throwable.getCause(); if (progressDialog != null) progressDialog.dismiss(); } }); break; } } public void CheckInCheckOut(final Kegiatan kegiatan, final String action, final CallbackKegiatan.CBCheckInCheckOut CB) { IC_Kegiatan IC = Global.CreateRetrofit(context).create(IC_Kegiatan.class); String json = makeJSON(action, kegiatan); switch (action) { case ACTION_CHECK_IN: IC.CheckIn(SISTEM, json).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { String result = RetrofitResponse.getString(context, response); new Function(context).writeToText("Kegiatan->CheckInCheckOut->" + action, result); if (RetrofitResponse.isSuccess(result)) new KegiatanSQLite(context).Update(kegiatan); CB.onCB(kegiatan); if (progressDialog != null) progressDialog.dismiss(); } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function(context).writeToText("Kegiatan->CheckInCheckOut->" + action, throwable.getMessage()); throwable.getCause(); if (progressDialog != null) progressDialog.dismiss(); } }); break; case ACTION_CHECK_OUT: IC.CheckOut(json).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { String result = RetrofitResponse.getString(context, response); new Function(context).writeToText("Kegiatan->CheckInCheckOut->" + action, result); if (RetrofitResponse.isSuccess(result)) new KegiatanSQLite(context).Update(kegiatan); CB.onCB(kegiatan); if (progressDialog != null) progressDialog.dismiss(); } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function(context).writeToText("Kegiatan->CheckInCheckOut->" + action, throwable.getMessage()); throwable.getCause(); if (progressDialog != null) progressDialog.dismiss(); } }); break; } } public void Refresh(final String action, final String date, final CallbackKegiatan.CBRefresh CB) { IC_Kegiatan IC = Global.CreateRetrofit(context).create(IC_Kegiatan.class); String json = makeJSON(action, date); switch (action) { case ACTION_REFRESH_TODAY: IC.RefreshToday(SISTEM, json).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { String result = RetrofitResponse.getString(context, response); new Function(context).writeToText("Kegiatan->CheckInCheckOut->" + action, result); if (RetrofitResponse.isSuccess(result)) { ArrayList<Kegiatan> list_kegiatan = RetrofitResponse.getListKegiatan(result); new KegiatanSQLite(context).setStatus(list_kegiatan); CB.onCB(list_kegiatan); } if (progressDialog != null) progressDialog.dismiss(); } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function(context).writeToText("Kegiatan->CheckInCheckOut->" + action, throwable.getMessage()); throwable.getCause(); if (progressDialog != null) progressDialog.dismiss(); } }); break; case ACTION_REFRESH_DATE: IC.RefreshDate(SISTEM, json).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { String result = RetrofitResponse.getString(context, response); new Function(context).writeToText("Kegiatan->CheckInCheckOut->" + action, result); if (RetrofitResponse.isSuccess(result)) { ArrayList<Kegiatan> list_kegiatan = RetrofitResponse.getListKegiatan(result); new KegiatanSQLite(context).setStatus(list_kegiatan); CB.onCB(list_kegiatan); } if (progressDialog != null) progressDialog.dismiss(); } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function(context).writeToText("Kegiatan->CheckInCheckOut->" + action, throwable.getMessage()); throwable.getCause(); if (progressDialog != null) progressDialog.dismiss(); } }); break; } } private String makeJSON(Kegiatan kegiatan) { JSONObject json_kegiatan = new JSONObject(); JSONObject json = new JSONObject(); try { json_kegiatan.put("cust_code", kegiatan.getSalesHeader().getCustomer().getCode()); if (!kegiatan.getSalesHeader().getCustomer().getCode().contains("CUST")) json_kegiatan.put("cust_nav", kegiatan.getSalesHeader().getCustomer().getCode()); json_kegiatan.put("cust_name", kegiatan.getSalesHeader().getCustomer().getName()); json_kegiatan.put("lat", kegiatan.getSalesHeader().getCustomer().getLatitude()); json_kegiatan.put("lang", kegiatan.getSalesHeader().getCustomer().getLongitude()); json_kegiatan.put("bex_no", kegiatan.getBEX().getEmpNo()); json_kegiatan.put("bex_initial", kegiatan.getBEX().getInitial()); json_kegiatan.put("id", kegiatan.getID()); json_kegiatan.put("startDate", kegiatan.getStartDate()); json_kegiatan.put("endDate", kegiatan.getEndDate()); json_kegiatan.put("tipe", kegiatan.getTipe()); json_kegiatan.put("jenis", kegiatan.getJenis()); json_kegiatan.put("subject", kegiatan.getSubject()); json_kegiatan.put("cancel", kegiatan.getCancel()); json_kegiatan.put("cancel_reason", kegiatan.getReason()); json_kegiatan.put("keterangan", kegiatan.getKeterangan()); json_kegiatan.put("result", kegiatan.getResult()); json_kegiatan.put("resultDate", kegiatan.getResultDate()); json_kegiatan.put("checkIn", kegiatan.getCheckIn()); json.put("bex", Global.getBEX(context).getInitial()); json.put("data", json_kegiatan); } catch (Exception e) { return e.toString(); } return json.toString(); } private String makeJSON(String action, Kegiatan kegiatan) { JSONObject json = new JSONObject(); JSONObject json_kegiatan = new JSONObject(); try { switch (action) { case ACTION_CANCEL: json_kegiatan.put("id", kegiatan.getID()); json_kegiatan.put("cancel", kegiatan.getCancel()); json_kegiatan.put("reason", kegiatan.getReason()); break; case ACTION_KETERANGAN: json_kegiatan.put("id", kegiatan.getID()); json_kegiatan.put("keterangan", kegiatan.getKeterangan()); break; case ACTION_RESULT: json_kegiatan.put("id", kegiatan.getID()); json_kegiatan.put("result", kegiatan.getResult()); break; case ACTION_CHECK_IN: json_kegiatan.put("id", kegiatan.getID()); break; case ACTION_CHECK_OUT: json_kegiatan.put("id", kegiatan.getID()); break; } json.put("bex", Global.getBEX(context).getInitial()); json.put("data", json_kegiatan); } catch (Exception e) { // TODO: handle exception return e.toString(); } return json.toString(); } private String makeJSON(String action, String date) { JSONObject json = new JSONObject(); JSONObject json_kegiatan = new JSONObject(); try { switch (action) { case ACTION_REFRESH_TODAY: break; case ACTION_REFRESH_DATE: json_kegiatan.put("date", date); break; } json.put("bex", Global.getBEX(context).getInitial()); json.put("data", json_kegiatan); } catch (Exception e) { // TODO: handle exception return e.toString(); } return json.toString(); } }
package com.xwen.radiotest; import android.content.DialogInterface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; public class radioActivity extends AppCompatActivity { RadioButton r1 = null; RadioButton r2 = null; RadioButton r3 = null; RadioButton r4 = null; RadioGroup rr = null; Button sure1 = null; Button exit1 = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_radio); rr = (RadioGroup) findViewById(R.id.aa); r1 =(RadioButton) findViewById(R.id.a); r2 =(RadioButton) findViewById(R.id.b); r3 =(RadioButton) findViewById(R.id.c); r4 =(RadioButton) findViewById(R.id.d); r1.setClickable(true); sure1 =(Button) findViewById(R.id.sure); exit1 =(Button) findViewById(R.id.exit); sure1.setOnClickListener(new sure1()); exit1.setOnClickListener(new exit1()); } class sure1 implements OnClickListener{ @Override public void onClick(View v){ } } }
/** * The MIT License (MIT) * * Copyright (c) 2018 Paul Campbell * * 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 net.kemitix.dependency.digraph.maven.plugin; import lombok.Getter; import net.kemitix.node.Node; import javax.annotation.concurrent.Immutable; import java.util.HashSet; import java.util.Objects; import java.util.Set; /** * Defines a package. * * @author Paul Campbell (pcampbell@kemitix.net) */ @Immutable public final class PackageData { @Getter private final String name; private final Set<Node<PackageData>> uses = new HashSet<>(); private PackageData(final String name) { this.name = name; } /** * Static factory. * * @param name the name of the package * * @return new instance of PackageData */ static PackageData newInstance(final String name) { return new PackageData(name); } @Override @SuppressWarnings("magicnumber") public int hashCode() { int result = 17; result = 31 * result + Objects.hashCode(this.name); return result; } /** * Checks whether two {@code PackageData} objects are "equal". * * <p>They are considered to be equal if they have the same name.</p> * * @param obj the other object to compare against * * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise. */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof PackageData)) { return false; } final PackageData other = (PackageData) obj; return Objects.equals(this.name, other.name); } Set<Node<PackageData>> getUses() { return new HashSet<>(uses); } /** * Replace the set of packages used by this node. * * @param uses The new package used set */ void setUses(final Set<Node<PackageData>> uses) { this.uses.clear(); this.uses.addAll(uses); } /** * Notes that this package is a user of another package. * * @param packageDataNode the package that is used by this package */ void uses(final Node<PackageData> packageDataNode) { uses.add(packageDataNode); } }
package nesto.daggertaste.bean; import javax.inject.Inject; /** * Created on 2016/8/11. * By nesto */ public class Graph { @Inject NodeList nodeList; }
package gui; import java.awt.Color; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import control.CurrentCell; public class SlotLabel extends ColoredLabel implements MouseListener { private String cellRef; private CurrentCell currentCell; public SlotLabel(String cellRef, CurrentCell currentCell) { super(" ", Color.WHITE, RIGHT); this.cellRef = cellRef; this.currentCell = currentCell; addMouseListener(this); } @Override public void mouseClicked(MouseEvent e) { currentCell.setCellRef(cellRef); } public void setFocusColor() { setBackground(Color.YELLOW); } public void setNormalColor() { setBackground(Color.WHITE); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }
import java.util.Scanner; public class homework_16{ public static void main(String[] args){ System.out.println("name:cck, number:20151681310210"); System.out.println("welcome to java"); int count = 0; for(int i=0;count<10;++i){ if(i%2==0||i%3==0){ System.out.print(i+" "); ++count; } } System.out.println(); } }
public class Mot { protected String type; protected String value; public Mot(String val, String type) { this.value = val; this.type = type; } public String toString() { return this.type+ ": " +this.value; } public String getType() { return this.type; } }