text
stringlengths
10
2.72M
package com.mashibing.strategy; import com.mashibing.*; import java.awt.*; /** * @create: 2020-04-07 16:10 **/ public class FourDirFireStrategy implements FireStrategy { @Override public void fire(Tank tank) { for (Dir dir : Dir.values()) { int bX = tank.getPoint().x + tank.getWidth() / 2; int bY = tank.getPoint().y + tank.getHeight() / 2; new Bullet(new Point(bX, bY), dir, tank.group); } if ( tank.group == Group.GOOD ) new Thread(() -> new Audio("audio/tank_fire.wav").play()).start(); } }
package com.company; import javax.swing.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class Main { public static void main(String[] args) { new Main(); } public Main(){ KeyListener listener = new KeyListener() { @Override public void keyPressed(KeyEvent event) { if(event.getKeyChar()==KeyEvent.VK_W) { Contents.yV = -3; // Contents.xV = 0; event.consume(); } if(event.getKeyChar()==KeyEvent.VK_S){ Contents.yV = 3; // Contents.xV = 0; event.consume(); } if(event.getKeyChar()==KeyEvent.VK_A){ // Contents.yV = 0; Contents.xV = -3; event.consume(); } if(event.getKeyChar()==KeyEvent.VK_D){ // Contents.yV = 0; Contents.xV = 3; event.consume(); } if(event.getKeyChar()==KeyEvent.VK_SPACE){ event.consume(); } } @Override public void keyReleased(KeyEvent event) { if(event.getKeyChar()==KeyEvent.VK_W) { Contents.yV = 0; // Contents.xV = 0; event.consume(); } if(event.getKeyChar()==KeyEvent.VK_S){ Contents.yV = 0; // Contents.xV = 0; event.consume(); } if(event.getKeyChar()==KeyEvent.VK_A){ // Contents.yV = 0; Contents.xV = 0; event.consume(); } if(event.getKeyChar()==KeyEvent.VK_D){ // Contents.yV = 0; Contents.xV = 0; event.consume(); } } @Override public void keyTyped(KeyEvent event) { } }; JFrame frame = new JFrame(); frame.setTitle("Rabbit Holes - Can you find your way out ?"); frame.setSize(900, 600); frame.setLocation(100, 50); frame.addKeyListener(listener); frame.add(new Contents()); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
package com.fleet.security.service; import org.springframework.security.core.userdetails.UserDetailsService; /** * @author April Han */ public interface UserService extends UserDetailsService { }
package se.gareth.swm; import java.util.ArrayList; public class Vector2D { private static final String TAG = Vector2D.class.getName(); /* Constant direction definitions */ public static final double DIRECTION_LEFT = Math.PI; public static final double DIRECTION_RIGHT = 0.0; public static final double DIRECTION_UP = (Math.PI * 1.5); public static final double DIRECTION_DOWN = (Math.PI / 2.0); public static final double DIRECTION_180 = Math.PI; private boolean mMagnitudeValid, mDirectionValid; private double mX, mY; private double mMagnitude, mDirection; public Vector2D(double x, double y) { mX = x; mY = y; } public Vector2D() { mX = 0.0; mY = 0.0; mMagnitude = 0.0; mDirection = 0.0; mMagnitudeValid = true; mDirectionValid = true; } public void set(Vector2D vector) { mX = vector.mX; mY = vector.mY; mMagnitudeValid = vector.mMagnitudeValid; mDirectionValid = vector.mDirectionValid; mMagnitude = vector.mMagnitude; mDirection = vector.mDirection; } public void set(double x, double y) { mX = x; mY = y; mMagnitudeValid = false; mDirectionValid = false; } public void setX(double x) { mX = x; mMagnitudeValid = false; mDirectionValid = false; } public void setY(double y) { mY = y; mMagnitudeValid = false; mDirectionValid = false; } public void add(double x, double y) { mX += x; mY += y; mMagnitudeValid = false; mDirectionValid = false; } public void addX(double x) { mX += x; mMagnitudeValid = false; mDirectionValid = false; } public void addY(double y) { mY += y; mMagnitudeValid = false; mDirectionValid = false; } public void lookAt(double fromX, double fromY, double toX, double toY) { set(fromX - toX, fromY - toY); } public double getMagnitude() { if (!mMagnitudeValid) { mMagnitude = Math.sqrt(mX * mX + mY * mY); mMagnitudeValid = true; } return mMagnitude; } public double getDirection() { if (!mDirectionValid) { mDirection = (double)Math.atan2(mY, mX); mDirectionValid = true; } return mDirection; } public void setMagnitude(double magnitude) { double direction = getDirection(); mX = Math.cos(direction) * magnitude; mY = Math.sin(direction) * magnitude; mMagnitude = magnitude; mMagnitudeValid = true; } public void setDirection(double direction) { double magnitude = getMagnitude(); mX = Math.cos(direction) * magnitude; mY = Math.sin(direction) * magnitude; mDirection = direction; mDirectionValid = true; } public void setDirectionMagnitude(double direction, double magnitude) { mX = Math.cos(direction) * magnitude; mY = Math.sin(direction) * magnitude; mMagnitudeValid = true; mDirectionValid = true; mMagnitude = magnitude; mDirection = direction; } public void add(final Vector2D vector) { mX += vector.mX; mY += vector.mY; mMagnitudeValid = false; mDirectionValid = false; } public void add(final ArrayList<Vector2D> vectorList) { for (int i = 0; i < vectorList.size(); i ++) { final Vector2D vector = vectorList.get(i); mX += vector.mX; mY += vector.mY; } mMagnitudeValid = false; mDirectionValid = false; } public void mulAdd(final Vector2D vector, double multiplier) { mX += vector.mX * multiplier; mY += vector.mY * multiplier; mMagnitudeValid = false; mDirectionValid = false; } public void invert() { mX = -mX; mY = -mY; /* Add 180 degrees to the direction if valid */ if (mDirectionValid) mDirection += DIRECTION_180; /* Magnitude should be the same - leave valid if valid */ } public void multiplyMagnitude(double multiply) { mX *= multiply; mY *= multiply; if (mMagnitudeValid) mMagnitude *= multiply; /* Direction should be the same - leave valid if valid */ } public void divideMagnitude(double divider) { mX /= divider; mY /= divider; if (mMagnitudeValid) mMagnitude /= divider; /* Direction should be the same - leave valid if valid */ } public Vector2D getNormal() { return new Vector2D(-mY, mX); } /* * Limit the vector to a max length */ public void truncate(double maxLength) { double lengthSquared = mX * mX + mY * mY; if (lengthSquared > (maxLength * maxLength) && lengthSquared > 0) { double ratio = maxLength / getMagnitude(); multiplyMagnitude(ratio); } } public double getX() { return mX; } public double getY() { return mY; } @Override public String toString() { return "" + getClass() + " (" + mX + "," + mY + ")"; } }
/** * shopmobile for tpshop * ============================================================================ * ็‰ˆๆƒๆ‰€ๆœ‰ 2015-2099 ๆทฑๅœณๆœ่ฑน็ฝ‘็ปœ็ง‘ๆŠ€ๆœ‰้™ๅ…ฌๅธ๏ผŒๅนถไฟ็•™ๆ‰€ๆœ‰ๆƒๅˆฉใ€‚ * ็ฝ‘็ซ™ๅœฐๅ€: http://www.tp-shop.cn * โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€” * ่ฟ™ไธๆ˜ฏไธ€ไธช่‡ช็”ฑ่ฝฏไปถ๏ผๆ‚จๅช่ƒฝๅœจไธ็”จไบŽๅ•†ไธš็›ฎ็š„็š„ๅ‰ๆไธ‹ๅฏน็จ‹ๅบไปฃ็ ่ฟ›่กŒไฟฎๆ”นๅ’Œไฝฟ็”จ . * ไธๅ…่ฎธๅฏน็จ‹ๅบไปฃ็ ไปฅไปปไฝ•ๅฝขๅผไปปไฝ•็›ฎ็š„็š„ๅ†ๅ‘ๅธƒใ€‚ * ============================================================================ * Author: ้ฃž้พ™ wangqh01292@163.com * Date: @date 2015ๅนด10ๆœˆ27ๆ—ฅ ไธ‹ๅˆ9:14:42 * Description: ๆ”ถ่ดงๅœฐๅ€ model * @version V1.0 */ package com.tpshop.mallc.model.person; import com.tpshop.mallc.model.SPModel; import java.io.Serializable; /** * ๆ”ถ่ดงๅœฐๅ€ */ public class SPConsigneeAddress implements SPModel , Serializable { //ๅœฐๅ€ID String addressID; String userID; //ๆ”ถ่ดงไบบๅง“ๅ String consignee; //ๅ›ฝๅฎถๅท็  String country; //็œไปฝ String province; //ๅŸŽๅธ‚ๅท็  String city; //ๅŒบๅท็  String district; //้•‡/่ก—้“ String town; //่ฏฆ็ป†ๅœฐๅ€ String address; //็”ต่ฏ String mobile; //ๆ˜ฏๅฆ้ป˜่ฎคๅœฐๅ€ String isDefault; /********* ่ฎพ่ฎก้œ€่ฆ, ้ขๅค–ๆ–ฐๅขžๅญ—ๆฎต, ๆ•ฐๆฎๅบ“ไธๅญ˜ๅœจไปฅไธ‹ๅญ—ๆฎต *****************/ String fullAddress; //็œไปฝ String provinceLabel; //ๅŸŽๅธ‚ๅท็  String cityLabel; //ๅŒบๅท็  String districtLabel; //้•‡/่ก—้“ String townLabel; @Override public String[] replaceKeyFromPropertyName() { return new String[]{ "addressID","address_id", "fullAddress","full_address", "isDefault","is_default", "town","twon" }; } public String getAddressID() { return addressID; } public void setAddressID(String addressID) { this.addressID = addressID; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getConsignee() { return consignee; } public void setConsignee(String consignee) { this.consignee = consignee; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } public String getFullAddress() { return fullAddress; } public void setFullAddress(String fullAddress) { this.fullAddress = fullAddress; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } public String getProvinceLabel() { return provinceLabel; } public void setProvinceLabel(String provinceLabel) { this.provinceLabel = provinceLabel; } public String getCityLabel() { return cityLabel; } public void setCityLabel(String cityLabel) { this.cityLabel = cityLabel; } public String getDistrictLabel() { return districtLabel; } public void setDistrictLabel(String districtLabel) { this.districtLabel = districtLabel; } public String getTownLabel() { return townLabel; } public void setTownLabel(String townLabel) { this.townLabel = townLabel; } }
package java1.basic_algo; import java.util.ArrayList; import java.util.Scanner; /** * ์•Œ๊ณ ๋ฆฌ์ฆ˜๊ธฐ์ดˆ 100์ œ * 1๋ฒˆ ํ•™์ƒ์ด๋ฆ„ ์ €์žฅ * * ํ•™์ƒ์ •๋ณด๋“ค์„ ์ €์žฅํ•˜๊ณ  ํ•™์ƒ์ด๋ฆ„์œผ๋กœ ๊ฒ€์ƒ‰ํ–ˆ์„ ๋•Œ ํ•™๋ฒˆ์„ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑ * - Student ํด๋ž˜์Šค ์ƒ์„ฑ * - String name, no ๋ฅผ ๊ฐ€์ง (์ด๋ฆ„๊ณผ ํ•™๋ฒˆ) * * - ํ•™์ƒ๋“ค์„ ArrayList์— ์ €์žฅํ•œ ํ›„ * - ๊ณ„์† ๊ฒ€์ƒ‰์„ ํ•˜๊ฒ ๋А๋ƒ y -> ๋ฐ˜๋ณต * - ์ข…๋ฃŒํ•˜๊ณ  ์‹ถ์œผ๋ฉด n -> ํ”„๋กœ๊ทธ๋žจ ์ข…๋ฃŒ * * - ํ•™์ƒ์ด๋ฆ„์ด ์žˆ๋Š” ๊ฒฝ์šฐ ๊ทธ ํ•™์ƒ์˜ ํ•™๋ฒˆ์„ ์ถœ๋ ฅ * - ํ•™์ƒ ์ด๋ฆ„์ด ์—†์œผ๋ฉด ์—†๋Š” ํ•™์ƒ์ด๋ผ๊ณ  ์ถœ๋ ฅ */ public class StudentMain { public static void main (String[] args) { Student st1 = new Student("์†์˜ค๊ณต", "1682"); Student st2 = new Student("์ €ํŒ”๊ณ„", "1772"); Student st3 = new Student("์‚ฌ์˜ค์ •", "1813"); ArrayList<Student> list = new ArrayList<Student>(); list.add(st1); list.add(st2); list.add(st3); for(Student st : list) { System.out.println(st.getName()); System.out.println(st.getNo()); } Scanner scan = new Scanner(System.in, "euc-kr"); while( true ) { System.out.println("๊ฒ€์ƒ‰์„ ๊ณ„์† ํ•˜๋ ค๋ฉด y, ์ข…๋ฃŒํ•˜๋ ค๋ฉด n"); String input = scan.next(); if (input.equals("y")) { System.out.println("๊ฒ€์ƒ‰์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค."); String name = scan.next(); boolean flag = false; for(Student stu : list){ System.out.println("DEBUG >> " + stu.getName()); System.out.println("DEBUG2 >> " + name); System.out.println(stu.getName().equals(name)); if(stu.getName().equals(name)){ System.out.println("ํ•ด๋‹น ํ•™์ƒ์˜ ํ•™๋ฒˆ์€ :: "+ stu.getNo()+"์ž…๋‹ˆ๋‹ค."); flag = true; } } if (!flag){ System.out.println("ํ•ด๋‹น ํ•™์ƒ์ด ์กด์žฌํ•˜์ง€ ์•Š์Œ."); } }else if (input.equals("n")) { break; }else { System.out.println("y ๋˜๋Š” n์„ ์ž…๋ ฅํ•˜์„ธ์š”."); } } scan.close(); System.out.println("ํ”„๋กœ๊ทธ๋žจ์„ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค."); } }
package brunel.fyp.david.lightscamerahome; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.crystal.crystalrangeseekbar.interfaces.OnSeekbarFinalValueListener; import com.crystal.crystalrangeseekbar.widgets.BubbleThumbSeekbar; import com.google.android.gms.awareness.Awareness; import com.google.android.gms.common.api.GoogleApiClient; import java.io.OutputStreamWriter; import java.net.URL; import java.net.HttpURLConnection; import static android.content.Context.MODE_PRIVATE; /** * Created by David-Desktop on 16/02/2017. */ public class LightsFragment extends Fragment{ public static URL url; public static String urlString = "http://192.168.1.159/api/C5LnKqM9kTLY3QY-pAsQNf9BAvHs25asvmb0IzVL/lights/7/state"; public static HttpURLConnection httpCon; public static OutputStreamWriter out; public static double brightness; public static int colourValue; public static int saturation; public static String colour = ""; public static LightsFragment newInstance (int instance){ Bundle args = new Bundle(); args.putInt("argsInstance", instance); LightsFragment lightsFragment = new LightsFragment(); lightsFragment.setArguments(args); return lightsFragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ getActivity().setTitle("Lights"); //creating view View view = inflater.inflate(R.layout.fragment_lights, container, false); //creating seekbar final BubbleThumbSeekbar seekbar = (BubbleThumbSeekbar) view.findViewById(R.id.rangeSeekbar1); // set final value listener seekbar.setOnSeekbarFinalValueListener(new OnSeekbarFinalValueListener() { @Override public void finalValue(Number value) { brightness = value.intValue(); Log.d("CRS=>", String.valueOf(brightness)); //if slider = 0 turn lights off if (brightness == 0.0){ try { lightsOff(); } catch (Exception e) { e.printStackTrace(); } //else set lights to whatever value } else { try { lightsBrightness(); } catch (Exception e) { e.printStackTrace(); } } } }); //creating buttons and onClickListeners Button buttonLightsWarm = (Button) view.findViewById(R.id.buttonWarm); buttonLightsWarm.setOnClickListener(clickListener); Button buttonLightsCool = (Button) view.findViewById(R.id.buttonCool); buttonLightsCool.setOnClickListener(clickListener); // Button buttonWeather = (Button) view.findViewById(R.id.buttonWeather); // buttonWeather.setOnClickListener(clickListener); return view; } //switch case for OnClickListener public final View.OnClickListener clickListener = new View.OnClickListener(){ public void onClick(View view){ switch (view.getId()){ case R.id.buttonWarm: try { //setting values colourValue = 12828; saturation = 52; colour = "green"; //running method lightsColour(); } catch (Exception e) { e.printStackTrace(); } break; case R.id.buttonCool: try { colourValue = 38000; saturation = 100; colour = "white"; lightsColour(); } catch (Exception e) { e.printStackTrace(); } break; // case R.id.buttonWeather: // GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(LightsFragment.this) // .addApi(Awareness.API) // .build(); // mGoogleApiClient.connect(); // break; } } }; //connection method for creating PUT request and setting data type to JSON public void connection() throws Exception{ //new url based on local IP initialised earlier url = new URL(urlString); //new http connection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); //setting type of message httpCon.setRequestMethod("PUT"); httpCon.setRequestProperty("Content-Type", "application/json"); httpCon.setRequestProperty("Accept", "application/json"); out = new OutputStreamWriter( httpCon.getOutputStream()); } //lights brightness method public void lightsBrightness() throws Exception{ Thread thread = new Thread(new Runnable() { @Override public void run() { try { //creating connection to bridge connection(); //writing message out.write("{\"on\":true, \"bri\":"+ ((int) brightness)+"}"); //closing connection out.close(); System.err.println(httpCon.getResponseCode()); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } //lights off method public void lightsOff() throws Exception{ Thread thread = new Thread(new Runnable() { @Override public void run() { try { //creating connection to bridge connection(); //writing message out.write("{\"on\":false}"); //closing connection out.close(); System.err.println(httpCon.getResponseCode()); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } //lights colour method public void lightsColour() throws Exception{ Thread thread = new Thread(new Runnable() { @Override public void run() { try { //creating connection to bridge connection(); //writing message out.write("{\"sat\":"+saturation+", \"hue\":"+colourValue+"}"); //closing connection out.close(); System.err.println(httpCon.getResponseCode()); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } }
/* * This code is sample code, provided as-is, and we make no * warranties as to its correctness or suitability for * any purpose. * * We hope that it's useful to you. Enjoy. * Copyright LearningPatterns Inc. */ package com.javatunes.domain; import java.io.Serializable; import java.math.BigDecimal; public class ArtistPriceInfo implements Serializable { private static final long serialVersionUID = 1L; private String artist; private BigDecimal yourPrice; // Default constructor is required for an Entity or Embeddable class public ArtistPriceInfo() {} public ArtistPriceInfo( String artist, BigDecimal price) { this.artist = artist; this.yourPrice = price; } public BigDecimal getYourPrice() { return yourPrice; } public void setYourPrice(BigDecimal yourPrice) { this.yourPrice = yourPrice; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } public String toString() { return "artsit = " + getArtist() + ", yourPrice= " + getYourPrice(); } }
public class Player { // ph, mp, mana potions och hp potions public int hp = 100; //private public int mp = 100; //private public int mpPotions = 3; //private public int hpPotions = 3; //private // dรถd eller inte? public boolean isDead = false; //attackera (vilket ta MP) public void attack() { if(!isDead) { if (mp >= 25) { mp -= 25; System.out.println("Attacking!"); }else { System.out.println("Not enough MP :("); } }else { System.out.println("Your dead, silly"); } } // ta skada (vilket tar Hp) public void takeDamage() { hp -= 25; if (hp <= 0) { System.out.println("You died!"); isDead = true; }else { System.out.println("You took damage! "); } } // Refill player life public void useHpPotion() { if(hpPotions > 0) { System.out.println("You drank a hp potion"); hpPotions--, hp += 100; }else { System.out.println("Not enough hp potion"); } } // Refill player mana public void useMpPotion() { if(mpPotions > 0) { System.out.println("You drank a mp potion"); mpPotions--; mp += 100; }else { System.out.println("Not enough mp potion"); } } }
package servlets; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class LoginServlets extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(false); if (session == null) { String username = req.getParameter("username"); String password = req.getParameter("password"); if (username.equals("user01") && password.equals("123456")) { HttpSession newSession = req.getSession(); newSession.setAttribute("username", "user01"); resp.sendRedirect("/"); } } } }
package com.norana.numberplace.sudoku; /** * Container to ease passing around a tuple of two objects. This object provides * a sensible implementation of equals(), returning true if equals() is true on * each of the contained objects, */ public class Pair<K, V>{ private final K first; private final V second; /** * Constructor for a Pair. * * @param first The first object in the Pair * @param second The second object in the Pair */ public Pair(K first, V second){ this.first = first; this.second = second; } /** * Checks the two objects for equality by delegating to their respective * {@link Object#equals(Object)} methods. * * @param obj the {@link Pair} to which this one is to be checked for * equality * @return true if the underlying objects of the Pair are both * considered equal */ @Override public boolean equals(Object obj){ if (obj instanceof Pair){ Pair<?, ?> p = (Pair<?, ?>) obj; return p.getFirst().equals(first) && p.getSecond().equals(second); } else{ return false; } } /** * Computes a hash code using the hash codesof the underlying objects. * * @return a hash code of the Pair */ @Override public int hashCode(){ return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); } /** * String representation of this Pair. * The default first/second delimiter ", " is always used. * * @return String representation of this Pair */ @Override public String toString(){ String s = "("; s += first.toString(); s += ", "; s += second.toString(); s += ")"; return s; } /** * Gets the first object for this pair * * @return first object for this pair */ public K getFirst(){ return this.first; } /** * Gets the second object for this pair * * @return second object for this pair */ public V getSecond(){ return this.second; } }
package sample.model; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.layout.AnchorPane; import javafx.scene.text.Text; import java.io.DataInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Observable; import java.util.Observer; public class ThreadServerSocket implements Runnable{ ServerSocket serverSocket; ObservableList<Cliente> listaClientes; Text nameUser; Text points; AnchorPane anchorPane; public ThreadServerSocket(ServerSocket _servServerSocket, ObservableList<Cliente> listaClientes, Text _nameUser,Text _points,AnchorPane anchor){ this.serverSocket=_servServerSocket; this.listaClientes = listaClientes; this.nameUser=_nameUser; this.points=_points; this.anchorPane=anchor; } @Override public void run() { Cliente cliente; while (!serverSocket.isClosed()){ try { Socket socket = serverSocket.accept(); ObjectInputStream data = new ObjectInputStream(socket.getInputStream()); cliente = (Cliente) data.readObject(); Cliente finalCliente = cliente; Platform.runLater(() -> { nameUser.setText(finalCliente.getName()); anchorPane.setVisible(false); }); data.close(); System.out.println("entro en el hilo secundario"); }catch (Exception e){ System.out.println(e); } } } }
package com.unsee.gaia.web.template; public class BooleanDataFormat implements IDataFormat { @Override public String format(Object value) { if (value == null) return ""; if(value instanceof Integer) { return Integer.valueOf(value.toString()) != 0 ? "ๆ˜ฏ" : "ๅฆ"; } return Boolean.valueOf(value.toString()) ? "ๆ˜ฏ" : "ๅฆ"; } }
/** * */ package com.cms.cache; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.stereotype.Service; import com.cms.common.cache.ICacheService; /** * @author yange * @็ฑปๆ่ฟฐ ๏ผšๅ‘้€็Ÿญไฟก้ชŒ่ฏ็ ็ผ“ๅญ˜ * 2016ๅนด1ๆœˆ29ๆ—ฅ */ @Service("verifyCodeCache") public class VerifyCodeCache implements ICacheService { @Override public Map<String,Object> getCacheContext() { // TODO Auto-generated method stub return new ConcurrentHashMap<String ,Object>(); } @Override public long getCacheLiveTime() { // TODO Auto-generated method stub return 0; } }
package ejemplo; public class examen { }
package studentadmin; /** * Klasse die verantwoordelijk is voor een Opleiding * @author erwin */ public class Opleiding extends Leertraject implements Cloneable{ private double totStudiepunten = 0; /** * Constructor voor Oplieding * @param naam * @param totStudiepunten: totaal aantal studiepunten waaruit Opleiding bestaat */ public Opleiding(String naam, double totStudiepunten){ super(naam); this.totStudiepunten = totStudiepunten; } public double getTotStudiepunten() { return totStudiepunten; } public Object clone() throws CloneNotSupportedException{ return super.clone(); } }
package com.facebook.react.devsupport; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.Rect; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.widget.PopupWindow; import android.widget.TextView; import com.a; import com.facebook.common.e.a; import com.facebook.react.bridge.UiThreadUtil; import java.net.MalformedURLException; import java.net.URL; import java.util.Locale; public class DevLoadingViewController { private static final int COLOR_DARK_GREEN = Color.parseColor("#035900"); private static boolean sEnabled = true; private final Context mContext; private PopupWindow mDevLoadingPopup; public final TextView mDevLoadingView; private final ReactInstanceManagerDevHelper mReactInstanceManagerHelper; public DevLoadingViewController(Context paramContext, ReactInstanceManagerDevHelper paramReactInstanceManagerDevHelper) { this.mContext = paramContext; this.mReactInstanceManagerHelper = paramReactInstanceManagerDevHelper; this.mDevLoadingView = (TextView)((LayoutInflater)this.mContext.getSystemService("layout_inflater")).inflate(1980039168, null); } public static void setDevLoadingEnabled(boolean paramBoolean) { sEnabled = paramBoolean; } public void hide() { if (!sEnabled) return; UiThreadUtil.runOnUiThread(new Runnable() { public void run() { DevLoadingViewController.this.hideInternal(); } }); } public void hideInternal() { PopupWindow popupWindow = this.mDevLoadingPopup; if (popupWindow != null && popupWindow.isShowing()) { _lancet.com_ss_android_ugc_aweme_lancet_DebugCheckLancet_popupWindowDismiss(this.mDevLoadingPopup); this.mDevLoadingPopup = null; } } public void show() { if (!sEnabled) return; UiThreadUtil.runOnUiThread(new Runnable() { public void run() { DevLoadingViewController.this.showInternal(); } }); } public void showForRemoteJSEnabled() { showMessage(this.mContext.getString(1980104725), -1, COLOR_DARK_GREEN); } public void showForUrl(String paramString) { try { URL uRL = new URL(paramString); Context context = this.mContext; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(uRL.getHost()); stringBuilder.append(":"); stringBuilder.append(uRL.getPort()); showMessage(context.getString(1980104718, new Object[] { stringBuilder.toString() }), -1, COLOR_DARK_GREEN); return; } catch (MalformedURLException malformedURLException) { StringBuilder stringBuilder = new StringBuilder("Bundle url format is invalid. \n\n"); stringBuilder.append(malformedURLException.toString()); a.c("ReactNative", stringBuilder.toString()); return; } } public void showInternal() { boolean bool; PopupWindow popupWindow = this.mDevLoadingPopup; if (popupWindow != null && popupWindow.isShowing()) return; Activity activity = this.mReactInstanceManagerHelper.getCurrentActivity(); if (activity == null) { a.c("ReactNative", "Unable to display loading message because react activity isn't available"); return; } if (Build.VERSION.SDK_INT <= 19) { Rect rect = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); bool = rect.top; } else { bool = false; } this.mDevLoadingPopup = new PopupWindow((View)this.mDevLoadingView, -1, -2); this.mDevLoadingPopup.setTouchable(false); this.mDevLoadingPopup.showAtLocation(activity.getWindow().getDecorView(), 0, 0, bool); } public void showMessage(final String message, final int color, final int backgroundColor) { if (!sEnabled) return; UiThreadUtil.runOnUiThread(new Runnable() { public void run() { DevLoadingViewController.this.mDevLoadingView.setBackgroundColor(backgroundColor); DevLoadingViewController.this.mDevLoadingView.setText(message); DevLoadingViewController.this.mDevLoadingView.setTextColor(color); DevLoadingViewController.this.showInternal(); } }); } public void updateProgress(final String status, final Integer done, final Integer total) { if (!sEnabled) return; UiThreadUtil.runOnUiThread(new Runnable() { public void run() { StringBuilder stringBuilder = new StringBuilder(); String str = status; if (str == null) str = "Loading"; stringBuilder.append(str); if (done != null) { Integer integer = total; if (integer != null && integer.intValue() > 0) stringBuilder.append(a.a(Locale.getDefault(), " %.1f%% (%d/%d)", new Object[] { Float.valueOf(this.val$done.intValue() / this.val$total.intValue() * 100.0F), this.val$done, this.val$total })); } stringBuilder.append("โ€ฆ"); DevLoadingViewController.this.mDevLoadingView.setText(stringBuilder); } }); } class DevLoadingViewController {} } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\devsupport\DevLoadingViewController.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
public class paskaita { public static void main(String[] args) { int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for (int skaicius : numbers) { System.out.println("Masyvo elementas yra: " + skaicius); } String line = ""; for (int i=0; i<=10; i++ ) { System.out.println(line+="*"); } } }
package exceptionHandling; import java.util.Scanner; public class ExceptionHandling2 { public static void main(String []argh) { Scanner in = new Scanner(System.in); while(in.hasNextInt()) { int n = in.nextInt(); int p = in.nextInt(); myCalculator M = new myCalculator(); try { System.out.println(M.power(n,p)); } catch(Exception e) { System.out.println(e); } } } } class myCalculator { String power(int n, int p) throws Exception{ String output; double a = (double) n; double b = (double) p; if(a < 0 || b < 0){ throw new Exception("n and p should be non-negative"); } else{ Double out1 =(Math.pow(a, b)); Integer out2 = out1.intValue(); output = String.valueOf(out2); return output; } } }
package br.com.consultaws.resources; import java.sql.Date; 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 javax.ws.rs.core.MediaType; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import br.com.consultaws.control.AgendaMedicoControl; import br.com.consultaws.model.bean.ConsultaMarcada; import br.com.consultaws.util.Datas; @Path("/agenda") public class AgendaMedicoResource { @GET @Path("/selecionarPorId/{id}") @Produces(MediaType.APPLICATION_JSON) public String selecionarPorId(@PathParam("id") int id) { Gson gson = new GsonBuilder().setDateFormat(Datas.formatoDataBR).create(); return gson.toJson(new AgendaMedicoControl().selecionarPorId(id)); } @GET @Path("/listarPorSituacao/{situacao}") @Produces(MediaType.APPLICATION_JSON) public String listarPorSituacao(@PathParam("situacao") String situacao) { Gson gson = new GsonBuilder().setDateFormat(Datas.formatoDataBR).create(); JsonElement je = gson.toJsonTree(new AgendaMedicoControl().listarPorSituacao(situacao)); JsonObject jo = new JsonObject(); jo.add("agendas", je); return jo.toString(); } @GET @Path("/listarPorLocalAtendimento/{localAtendimento}") @Produces(MediaType.APPLICATION_JSON) public String listarPorLocalAtendimento(@PathParam("localAtendimento") int localAtendimento) { Gson gson = new GsonBuilder().setDateFormat(Datas.formatoDataBR).create(); JsonElement je = gson.toJsonTree(new AgendaMedicoControl().listarPorLocalAtendimento(localAtendimento)); JsonObject jo = new JsonObject(); jo.add("agendas", je); return jo.toString(); } @GET @Path("/listarPorMedico/{medico}") @Produces(MediaType.APPLICATION_JSON) public String listarPorMedico(@PathParam("medico") int medico) { Gson gson = new GsonBuilder().setDateFormat(Datas.formatoDataBR).create(); JsonElement je = gson.toJsonTree(new AgendaMedicoControl().listarPorMedico(medico)); JsonObject jo = new JsonObject(); jo.add("agendas", je); return jo.toString(); } @GET @Path("/listarPorData/{data}") @Produces(MediaType.APPLICATION_JSON) public String listarPorData(@PathParam("data") Date data) { Gson gson = new GsonBuilder().setDateFormat(Datas.formatoDataBR).create(); JsonElement je = gson.toJsonTree(new AgendaMedicoControl().listarPorData(data)); JsonObject jo = new JsonObject(); jo.add("agendas", je); return jo.toString(); } @POST @Path("/alterar") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String alterar(String consulta) { Gson gson = new GsonBuilder().setDateFormat(Datas.formatoDataEUA).create(); ConsultaMarcada consultaMarcada = gson.fromJson(consulta, ConsultaMarcada.class); return new Gson().toJson(new AgendaMedicoControl().alterar(consultaMarcada)); } }
package edu.curd.operation.student; import edu.curd.operation.*; import edu.curd.dto.GradesDTO; import edu.curd.dto.StudentGradesDTO; import edu.dbConnection.DatabaseConnection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; public class ManageStudentGrades implements JDBCOperation { @Override public void setContext(Properties properties) { this.contextProperties = properties; } private Properties contextProperties; public ManageStudentGrades(Properties contextProperties) { this.setContext(contextProperties); } @Override public List<Integer> create(List<JDBCDataObject> jdbcDataObjects) { if (jdbcDataObjects != null && jdbcDataObjects.isEmpty()) { return new ArrayList<>(); } List<Integer> returnKeys = new ArrayList<>(); Connection connection = DatabaseConnection.getConnection(contextProperties); PreparedStatement insertStatemtn = null; String insertSQL = "INSERT INTO `classroom_records`.`grades` (`enrollment_id`,`topic_id`,`score`) VALUES (?, ?, ?);"; try { connection.setAutoCommit(false); insertStatemtn = connection.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS); for (JDBCDataObject rawDTO : jdbcDataObjects) { GradesDTO attendance = (GradesDTO) rawDTO; insertStatemtn.setInt(1, attendance.getEnrollmentId()); insertStatemtn.setInt(2, attendance.getTopicId()); insertStatemtn.setString(3, attendance.getScore()); insertStatemtn.executeUpdate(); ResultSet rs = insertStatemtn.getGeneratedKeys(); if (rs.next()) { returnKeys.add(rs.getInt(1)); } connection.commit(); } } catch (SQLException e) { if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException sqlError) { Logger.getLogger(ManageStudentGrades.class.getName()).log(Level.SEVERE, "Error while performing the operation.", sqlError); } } } finally { if (insertStatemtn != null) { try { insertStatemtn.close(); } catch (SQLException ex) { } } if (connection != null) { try { connection.setAutoCommit(true); connection.close(); } catch (SQLException ex) { } } } return returnKeys; } @Override public List<Integer> update(List<JDBCDataObject> jdbcDataObjects) { return null; } @Override public List<Integer> delete(List<JDBCDataObject> jdbcDataObjects) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public List<JDBCDataObject> read(JDBCDataObject jdbcDataObjects) { if (jdbcDataObjects == null) { return new ArrayList<>(); } List<JDBCDataObject> returnObjects = new ArrayList<>(); Connection connection = DatabaseConnection.getConnection(contextProperties); PreparedStatement selectStatement = null; StringBuilder selectSQL = generateSelectStatment(jdbcDataObjects); try { selectStatement = connection.prepareStatement(selectSQL.toString()); ResultSet results = selectStatement.executeQuery(); while (results.next()) { returnObjects.add(new GradesDTO(results.getInt(1), results.getInt(2), results.getInt(3), results.getString(4), results.getString(5))); } } catch (SQLException e) { System.err.print("Erro while listing data."); } finally { if (selectStatement != null) { try { selectStatement.close(); } catch (SQLException ex) { } } if (connection != null) { try { connection.setAutoCommit(true); connection.close(); } catch (SQLException ex) { } } } return returnObjects; } private StringBuilder generateSelectStatment(JDBCDataObject jdbcDataObjects) { StringBuilder selectSQL = new StringBuilder("SELECT * FROM `classroom_records`.`grades` WHERE 1=1 "); GradesDTO gradeDTO = (GradesDTO) jdbcDataObjects; if (gradeDTO.getGradesId() > 0) { selectSQL.append(" AND ").append("grades_id=").append(gradeDTO.getGradesId()); } else { if (gradeDTO.getEnrollmentId() > 0) { selectSQL.append(" AND ").append("enrollment_id=").append(gradeDTO.getEnrollmentId()); } if (gradeDTO.getTopicId() > 0) { selectSQL.append(" AND ").append("topic_id=").append(gradeDTO.getTopicId()); } if (gradeDTO.getScore() != null) { selectSQL.append(" AND ").append("score=").append("'").append(gradeDTO.getScore().trim()).append("'"); } } return selectSQL; } public List<StudentGradesDTO> readGrades(int selectedClassId, int selectedExcercisesId, int selectedTopicId) { List<StudentGradesDTO> returnObjects = new ArrayList<>(); Connection connection = DatabaseConnection.getConnection(contextProperties); PreparedStatement selectStatement = null; String selectSQL = "select grades_id, concat(st.first_name, ' ',st.last_name), gr.score, gr.topic_id, en.enrollment_id from student st JOIN enrollment en on en.student_id = st.student_id JOIN class cl on cl.class_id=en.class_id JOIN exercises ex on ex.class_id =cl.class_id LEFT outer join grades gr on gr.enrollment_id=en.enrollment_id where cl.class_id=? and ex.exercises_id=?"; try { selectStatement = connection.prepareStatement(selectSQL); selectStatement.setInt(1, selectedClassId); selectStatement.setInt(2, selectedExcercisesId); ResultSet results = selectStatement.executeQuery(); while (results.next()) { // Check for Topic // grades_id, concat(st.first_name, ' ',st.last_name), gr.score, gr.topic_id //if (results.getInt(4) == 0 || results.getInt(4) == selectedTopicId) { returnObjects.add(new StudentGradesDTO(results.getInt(1), results.getString(2), results.getString(3), results.getInt(4), results.getInt(5))); // } } } catch (SQLException e) { System.err.print("Erro while listing data."); } finally { if (selectStatement != null) { try { selectStatement.close(); } catch (SQLException ex) { } } if (connection != null) { try { connection.setAutoCommit(true); connection.close(); } catch (SQLException ex) { } } } return returnObjects; } public boolean updateMarks(int gradesId, String newScore) { boolean isSuccess = false; Connection connection = DatabaseConnection.getConnection(contextProperties); PreparedStatement insertStatemtn = null; String insertSQL = "UPDATE `classroom_records`.`grades` SET `score` = ? WHERE `grades_id` = ?;"; try { connection.setAutoCommit(false); insertStatemtn = connection.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS); insertStatemtn.setString(1, newScore); insertStatemtn.setInt(2, gradesId); int count = insertStatemtn.executeUpdate(); if (count > 0) { isSuccess = true; } connection.commit(); } catch (SQLException e) { if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException sqlError) { Logger.getLogger(ManageStudentGrades.class.getName()).log(Level.SEVERE, "Error while performing the operation.", sqlError); } } } finally { if (insertStatemtn != null) { try { insertStatemtn.close(); } catch (SQLException ex) { } } if (connection != null) { try { connection.setAutoCommit(true); connection.close(); } catch (SQLException ex) { } } } return isSuccess; } public boolean insertMarks(int studentEnrollId, int selectedTopicId, String newScore) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
/* * 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 java1; import java.io.*; /** * * @author xubo */ public class floder { public static void main(String[] args) { File myDir = new File("C:\\Program Files"); System.out.print(myDir+(myDir.isDirectory()?"ๆ˜ฏ":"ไธๆ˜ฏ")+"ไธ€ไธช็›ฎๅฝ•"); } }
/* * 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 antrian.presenter; import antrian.listener.QueryInterface; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * * @author ZuhdanNur */ public class ViewPresenter implements QueryInterface { String code = ""; public String getCode() { return code; } @Override public void select(String table) { String sql = "SELECT id,no_antrian FROM "+table +" where finish = 1 order by id desc limit 1"; try ( Statement stmt = this.coon.createStatement(); ResultSet rs = stmt.executeQuery(sql)){ if(rs.next()){ code = rs.getString(2); } else { code = "Tidak Ada"; } } catch (SQLException e) { System.out.println(e.getMessage()); } } @Override public void insert(String table) { } @Override public int getLastRow(String table) { return 0; } Connection coon; public void setConnection(Connection connect) { this.coon = connect; } }
package com.github.manage.service.manage; import com.github.manage.entity.manage.ManageUser; import com.github.manage.form.RegisterForm; import com.github.manage.form.common.IdForm; import com.github.manage.form.user.UserListSearchForm; import com.github.manage.result.GeneralResult; /** * @ProjectName: spring-cloud-examples * @Package: com.github.manage.service.manage.user * @Description: ็”จๆˆทๆœๅŠกๆŽฅๅฃ * @Author: Vayne.Luo * @date 2018/12/18 */ public interface UserService { /** * ไฟๅญ˜็”จๆˆท * @param registerForm ็”จๆˆท่กจๅ• * @return */ GeneralResult addUser(RegisterForm registerForm); /** * ๆ นๆฎ็”จๆˆทๅๆŸฅ่ฏข็”จๆˆทไฟกๆฏ * @param username ็”จๆˆทๅ * @return */ ManageUser getUserInfoByName(String username); /** * ่Žทๅ–็”จๆˆทไฟกๆฏ๏ผˆๅŸบ็ก€ไฟกๆฏ+ๆƒ้™๏ผ‰ */ GeneralResult getUserInfo(); /** * ๆŸฅ่ฏขๅŽๅฐๆ‰€ๆœ‰็”จๆˆทๅˆ—่กจ * @param searchForm */ GeneralResult queryManageUserList(UserListSearchForm searchForm); /** * ็”จๆˆทไฟกๆฏ * @param idForm id */ GeneralResult queryUserDetailById(IdForm idForm); }
package com.example.mvpdemo0602.fragments; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.mvpdemo0602.R; import com.example.mvpdemo0602.base.BaseFragment; import com.example.mvpdemo0602.bean.Persion; import com.example.mvpdemo0602.db.DbManager; import com.example.mvpdemo0602.fragments.home.Type0ViewHolder; import com.example.mvpdemo0602.fragments.home.Type1ViewHolder; import com.example.mvpdemo0602.fragments.home.Type2ViewHolder; import com.example.mvpdemo0602.fragments.home.TypeViewHolder; import com.example.mvpdemo0602.global.MyApplication; import com.example.mvpdemo0602.greendao.PersionDao; import com.example.mvpdemo0602.utils.PrintLog; import com.example.mvpdemo0602.utils.TDevice; import com.example.mvpdemo0602.widgets.recyclerview.AbsViewHolder; import com.example.mvpdemo0602.widgets.recyclerview.MultiTypeAdapterImpl; import com.example.mvpdemo0602.widgets.recyclerview.ViewHolderCreator; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by Administrator on 2018/6/5. */ public class HomeFragment extends BaseFragment { @Bind(R.id.result) TextView tvHomeTitle; @Bind(R.id.rv_home_list_new_firmware_1) RecyclerView mNewFirmwareList; @Bind(R.id.divider) View divider; private ArrayList<String> strList = new ArrayList<>(); private static final String[] VIEW_TYPE = new String[]{"VIEW0", "VIEW1", "VIEW2", "VIEW3"}; private static final String[] TYPE = new String[]{"HEAD", "CONTENT", "FOOT"}; private int page_size = 20; private int page_num = 1; private int mViewType = 0; private int mType = 0; private int mDataCount = 1; private MultiTypeAdapterImpl mAdapter; // @Nullable // @Override // public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_home_1, null); // ButterKnife.bind(this, view); // // // return view; // } @Override protected int getLayoutId() { return R.layout.fragment_home_1; } @Override protected void initView(View view) { tvHomeTitle.setTextColor(Color.BLACK); tvHomeTitle.setText(TDevice.checkNetworkType(getActivity()) + "==="); LinearLayoutManager lm = new LinearLayoutManager(getApplication(), LinearLayoutManager.VERTICAL, false); mNewFirmwareList.setLayoutManager(lm); mNewFirmwareList.setItemAnimator(new DefaultItemAnimator()); mNewFirmwareList.addItemDecoration(new DividerItemDecoration(getApplication(), DividerItemDecoration.VERTICAL)); // addListData(); mAdapter = new MultiTypeAdapterImpl(); mAdapter.register(Type0ViewHolder.Data.class, Type0ViewHolder.class); mAdapter.register(Type1ViewHolder.Data.class, new ViewHolderCreator<Type1ViewHolder.Data, Type1ViewHolder>() { @Override public Type1ViewHolder create(ViewGroup parent) { final Type1ViewHolder viewHolder = new Type1ViewHolder(parent); viewHolder.setOnItemClickListener(new AbsViewHolder.OnItemClickListener<Type1ViewHolder.Data>() { @Override public boolean onClick(Type1ViewHolder.Data data) { MyApplication.showToast("Click Type1ViewHolder. data =" + viewHolder.getData()); return false; } }); return viewHolder; } @NonNull @Override public Class<Type1ViewHolder> getViewHolderClass() { return Type1ViewHolder.class; } }); mAdapter.register(Type2ViewHolder.Data.class, Type2ViewHolder.class); mAdapter.register(TypeViewHolder.Data.class, new ViewHolderCreator<TypeViewHolder.Data, TypeViewHolder>() { @Override public TypeViewHolder create(ViewGroup parent) { final TypeViewHolder typeViewHolder = new TypeViewHolder(parent); typeViewHolder.setOnItemClickListener(new TypeViewHolder.OnRecyclerViewItemClickListener() { @Override public void onClick(View view, TypeViewHolder.ViewName viewName, int position) { if (position ==1){ if (viewName == TypeViewHolder.ViewName.PRACTISE1){ MyApplication.showToast(">>>>>>>>>1"); PrintLog.i("abc==================>>>>>>>>>1"); }else if (viewName == TypeViewHolder.ViewName.PRACTISE2){ MyApplication.showToast(">>>>>>>>>2"); PrintLog.i("abc==================>>>>>>>>>2"); }else if (viewName == TypeViewHolder.ViewName.PRACTISE3){ MyApplication.showToast(">>>>>>>>>3"); PrintLog.i("abc==================>>>>>>>>>3"); } } } }); return typeViewHolder; } @NonNull @Override public Class<TypeViewHolder> getViewHolderClass() { return TypeViewHolder.class; } }); mNewFirmwareList.setAdapter(mAdapter); update(); } private static final int CONTENT = 1; private void addContnetData(Object data) { mAdapter.addItemByType(CONTENT, "String"); } public void setView0(View view) { mViewType = 0; update(); } public void setView1(View view) { mViewType = 1; update(); } public void setView2(View view) { mViewType = 2; update(); } public void setView3(View view) { mViewType = 3; update(); } public void setHead(View view) { mType = 0; update(); } public void setContent(View view) { mType = 1; update(); } public void setFoot(View view) { mType = 2; update(); } public void addOne(View view) { mDataCount = 1; update(); } public void addTwo(View view) { mDataCount = 2; update(); } public void addThree(View view) { mDataCount = 3; update(); } public void addFour(View view) { mDataCount = 4; update(); } public void addFive(View view) { mDataCount = 5; update(); } private void update() { tvHomeTitle.setText("ๆทปๅŠ " + mDataCount + "ไธช-->>" + VIEW_TYPE[mViewType] + "-->>ๅˆฐ" + TYPE[mType]); } private static int sIndex = 0; public void run(View view) { if (mType < 0 || mType > 3) { MyApplication.showToast("unknown type, Type = " + mType); return; } if (mViewType == 0) { if (mDataCount == 1) { sIndex++; final Object object = new Type0ViewHolder.Data(TYPE[mType] + ">>>Title--" + sIndex); mAdapter.addItemByType(mType, object); } else { final List<Object> list = new ArrayList<>(); for (int i = 0; i < mDataCount; i++) { sIndex++; list.add(new Type0ViewHolder.Data(TYPE[mType] + ">>>Title--" + sIndex)); } mAdapter.addAllItemByType(mType, list); } } else if (mViewType == 1) { sIndex++; final String content = "Content Content Content Content Content Content Content Content Content Content Content Content Content Content Content Content Content Content "; if (mDataCount == 1) { sIndex++; final Object object = new Type1ViewHolder.Data(TYPE[mType] + ">>>Title--" + sIndex, "Content"); mAdapter.addItemByType(mType, object); } else { final List<Object> list = new ArrayList<>(); for (int i = 0; i < mDataCount; i++) { sIndex++; list.add(new Type1ViewHolder.Data(TYPE[mType] + ">>>Title--" + sIndex, content)); } mAdapter.addAllItemByType(mType, list); } } else if (mViewType == 2) { sIndex++; final String content = "Content Content Content Content Content Content Content Content Content Content Content Content Content Content Content Content Content Content "; if (mDataCount == 1) { sIndex++; final Object object = new Type2ViewHolder.DataImpl(TYPE[mType] + ">>>Title--" + sIndex, "Content"); mAdapter.addItemByType(mType, object); } else { final List<Object> list = new ArrayList<>(); for (int i = 0; i < mDataCount; i++) { sIndex++; list.add(new Type2ViewHolder.DataImpl(TYPE[mType] + ">>>Title--" + sIndex, content)); } mAdapter.addAllItemByType(mType, list); } }else if (mViewType == 3) { if (mDataCount ==1&& mType == 0){ sIndex ++; final Object obj= new TypeViewHolder.DataImpl("ๅˆ—่กจ","ๆ•ฐๆฎ","ไปปๅŠก"); mAdapter.addItemByType(mType,obj); } }else { MyApplication.showToast("unknown view type, ViewType = " + mViewType); } } public void removeByType(View view) { mAdapter.removeAllItemByType(mType); } public void checkDataType(View view) { int count = 0; try { mAdapter.addItem(0, "Exception"); } catch (Exception e) { e.printStackTrace(); count++; } try { mAdapter.addItem(0, 0, "Exception"); } catch (Exception e) { e.printStackTrace(); count++; } try { mAdapter.addItem("Exception"); } catch (Exception e) { e.printStackTrace(); count++; } try { mAdapter.addItemByType(0, "Exception"); } catch (Exception e) { e.printStackTrace(); count++; } try { List<String> list = new ArrayList<>(); list.add("Exception"); mAdapter.addAllItem(0, list); } catch (Exception e) { e.printStackTrace(); count++; } try { List<String> list = new ArrayList<>(); list.add("Exception"); mAdapter.addAllItem(0, list); } catch (Exception e) { e.printStackTrace(); count++; } try { List<String> list = new ArrayList<>(); list.add("Exception"); mAdapter.addAllItem(0, 0, list); } catch (Exception e) { e.printStackTrace(); count++; } try { List<String> list = new ArrayList<>(); list.add("Exception"); mAdapter.addAllItem(list); } catch (Exception e) { e.printStackTrace(); count++; } try { List<String> list = new ArrayList<>(); list.add("Exception"); mAdapter.addAllItemByType(0, list); } catch (Exception e) { e.printStackTrace(); count++; } try { List<String> list = new ArrayList<>(); list.add("Exception"); mAdapter.addAllItem(list.toArray()); } catch (Exception e) { e.printStackTrace(); count++; } MyApplication.showToast("ๆฃ€ๆŸฅ" + (count == 10 ? "Success" : "Fail") + "๏ผŒๆต‹่ฏ•10ไธช๏ผŒๆ•่Žทๅˆฐ็ฑปๅž‹ๅผ‚ๅธธ" + count + "ไธชใ€‚"); } private void addListData() { PersionDao persionDao = DbManager.getDaoSession(getApplication()).getPersionDao(); List<Persion> list = persionDao.queryBuilder().build().list(); long count = persionDao.queryBuilder().count(); PrintLog.i("count===" + count + ",,size==" + list.size()); for (int i = 0; i < list.size(); i++) { Persion persion = list.get(i); strList.add(persion.getName() + "็š„็”ต่ฏ๏ผš" + persion.getNum()); } } @Override protected void initData() { } @Override public void onDestroyView() { super.onDestroyView(); // ButterKnife.unbind(this); ButterKnife.unbind(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO: inflate a fragment view View rootView = super.onCreateView(inflater, container, savedInstanceState); ButterKnife.bind(this, rootView); return rootView; } @OnClick({R.id.set_view0, R.id.set_view1, R.id.set_view2, R.id.set_view3, R.id.set_head, R.id.set_content, R.id.set_foot, R.id.check, R.id.add_one, R.id.add_two, R.id.add_three, R.id.add_four, R.id.add_five, R.id.remove, R.id.run}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.set_view0: setView0(view); break; case R.id.set_view1: setView1(view); break; case R.id.set_view2: setView2(view); break; case R.id.set_view3: setView3(view); break; case R.id.set_head: setHead(view); break; case R.id.set_content: setContent(view); break; case R.id.set_foot: setFoot(view); break; case R.id.check: checkDataType(view); break; case R.id.add_one: addOne(view); break; case R.id.add_two: addTwo(view); break; case R.id.add_three: addThree( view ); break; case R.id.add_four: addFour(view); break; case R.id.add_five: addFive(view); break; case R.id.remove: removeByType(view); break; case R.id.run: run(view); break; } } }
package NumberUtilitiesPkg; public class NU { }
package com.kobotan.android.Vshkole.activities; import android.app.DialogFragment; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import com.kobotan.android.Vshkole.R; import com.kobotan.android.Vshkole.billingClasses.AuthorizationInfo; import com.kobotan.android.Vshkole.database.DatabaseManager; import com.kobotan.android.Vshkole.networking.VshkoleRestClient; import com.kobotan.android.Vshkole.adapters.TabSwipeBookAdapter; import com.kobotan.android.Vshkole.entities.AnswerBook; import com.kobotan.android.Vshkole.entities.Book; import com.kobotan.android.Vshkole.entities.Entity; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Tracker; import com.google.gson.Gson; import com.kobotan.android.Vshkole.utils.Classะกrutch; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.viewpagerindicator.TabPageIndicator; import org.apache.http.Header; import org.json.JSONObject; public class BookActivity extends FragmentActivity { @InjectView(R.id.vpBookPager) ViewPager vpPager; @InjectView(R.id.tvTitleBook) TextView tvTitleBook; public DialogFragment dialogFragment; FragmentPagerAdapter adapterViewPager; TabPageIndicator titleIndicator; ProgressDialog progressDialog; GoogleAnalytics analytics; Tracker tracker; private int entityId; private boolean isBook; private int classId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); entityId = getIntent().getIntExtra("Id", 0); isBook = getIntent().getBooleanExtra("IsBook", false); classId = getIntent().getIntExtra("ClassId", -1); analytics = GoogleAnalytics.getInstance(this); tracker = analytics.newTracker(R.xml.global_tracker); progressDialog = new ProgressDialog(this); progressDialog.setMessage(getApplicationContext().getString(R.string.synchronization)); progressDialog.setCancelable(true); progressDialog.setCanceledOnTouchOutside(true); progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { progressDialog.dismiss(); BookActivity.this.finish(); } }); progressDialog.show(); boolean isOffline = getIntent().getBooleanExtra("IsOffline", false); if (isOffline) { fillFromDB(); } else { fillFields(); } } @Override protected void onStart() { super.onStart(); analytics.reportActivityStart(this); } @Override protected void onStop() { super.onStop(); analytics.reportActivityStop(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.common_menu, menu); MenuItem classTitle = menu.findItem(R.id.number_of_class); classTitle.setTitle(Classะกrutch.getRealClassName(classId) + " ะบะปะฐัั"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.backpack: Intent intent = new Intent(this, BackpackActivity.class); startActivity(intent); break; } return super.onOptionsItemSelected(item); } @OnClick(R.id.action_info) public void showInfoDialog() { TabSwipeBookAdapter tabSwipeBookAdapter = (TabSwipeBookAdapter) adapterViewPager; int index = vpPager.getCurrentItem(); dialogFragment = tabSwipeBookAdapter.getAdditInfoFragment(index); if (dialogFragment != null) { dialogFragment.setShowsDialog(true); dialogFragment.show(getFragmentManager(), "dialog"); } } @OnClick(R.id.rlBookTitle) public void goBack() { finish(); } private void fillFields() { RequestParams params = new RequestParams(); params.put("id", String.valueOf(entityId)); params.put("type", isBook ? "b" : "ab"); VshkoleRestClient.get("get_entity_by_id", params, new EntityResponseHandler()); } private boolean fillFromDB() { Entity entity = DatabaseManager.getInstance().getEntityById(entityId); if (entity != null) { initialize(entity); progressDialog.dismiss(); return true; } return false; } private class EntityResponseHandler extends JsonHttpResponseHandler { Entity entity; @Override public void onSuccess(int statusCode, Header[] headers, JSONObject json) { Gson gson = new Gson(); if (isBook) entity = gson.fromJson(json.toString(), Book.class); else entity = gson.fromJson(json.toString(), AnswerBook.class); if (entity.getOpposite() == null) { initialize(entity); progressDialog.dismiss(); return; } RequestParams params = new RequestParams(); params.put("id", String.valueOf(entity.getOpposite().getId())); params.put("type", !isBook ? "b" : "ab"); VshkoleRestClient.get("get_entity_by_id", params, new OppositeJsonHttpResponseHandler(entity)); } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) if (!isBook) { if (fillFromDB()) return; } Log.d("Error!!!", String.valueOf(statusCode)); Toast.makeText(getApplication(), getString(R.string.network_troubles), Toast.LENGTH_SHORT).show(); finish(); } } private class OppositeJsonHttpResponseHandler extends JsonHttpResponseHandler { private Entity entity; public OppositeJsonHttpResponseHandler(Entity entity) { this.entity = entity; } @Override public void onSuccess(JSONObject response) { super.onSuccess(response); Gson gson = new Gson(); Entity opposite; if (!isBook) opposite = gson.fromJson(response.toString(), Book.class); else opposite = gson.fromJson(response.toString(), AnswerBook.class); initialize(entity, opposite); } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) Log.d("Error!!!", String.valueOf(statusCode)); Toast.makeText(getApplication(), getString(R.string.network_troubles), Toast.LENGTH_SHORT).show(); finish(); } @Override public void onFinish() { super.onFinish(); progressDialog.dismiss(); } } private void initialize(Entity entity) { setContentView(R.layout.book_page); initializeAds(); ButterKnife.inject(BookActivity.this); tvTitleBook.setText(entity.getAuthors()); adapterViewPager = new TabSwipeBookAdapter(getSupportFragmentManager(), entity, isBook, BookActivity.this, classId); vpPager.setAdapter(adapterViewPager); titleIndicator = (TabPageIndicator) findViewById(R.id.bookTitles); titleIndicator.setViewPager(vpPager); if (isBook) titleIndicator.setCurrentItem(1); } private void initialize(Entity entity, Entity opposite) { setContentView(R.layout.book_page); initializeAds(); ButterKnife.inject(BookActivity.this); tvTitleBook.setText(entity.getAuthors()); adapterViewPager = new TabSwipeBookAdapter(getSupportFragmentManager(), entity, opposite, isBook, BookActivity.this, classId); vpPager.setAdapter(adapterViewPager); titleIndicator = (TabPageIndicator) findViewById(R.id.bookTitles); titleIndicator.setViewPager(vpPager); if (isBook) titleIndicator.setCurrentItem(1); } private void initializeAds() { AdView mAdView = (AdView) findViewById(R.id.adView); if (!AuthorizationInfo.isBought(getApplicationContext())) { AdRequest adRequest = new AdRequest.Builder() .build(); mAdView.loadAd(adRequest); }else{ mAdView.setVisibility(View.GONE); } } }
package room; import java.util.Random; import entity.*; /** * class important for the lessonroom and the labroom * @author Prod'homme * */ abstract class CourseRoom extends Room { //boolean to know if it's oop lesson/lab private boolean oop; //boolean to know if you can leave or not, depends on the oop course, if it's attended or not private boolean canExit; //constructor public CourseRoom(String description) { super(description); this.oop = false; } //getter and setter public void setOop(boolean oop){ this.oop = oop; } public boolean getOop(){ return this.oop; } /** * the command attendcourse is very important for the lab and lesson * @param player */ abstract void attendCourse(Player player); /** *method for update the lesson and lab room : random to know if it's a oop lesson/labsession or not */ public void update(){ int random = new Random().nextInt(3); if(random == 2){ this.setOop(true); }else{ this.setOop(false); } } }
package KidneyExchange; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; public class TestResults { private int numPairsOperated; private int numPairsTotal; private long runDuration; private List<List<Long>> roundDurations; private Stopwatch runWatch; private Stopwatch roundWatch; public TestResults( int numHospitals, int numRounds, int initialNumPairs ) { roundDurations = new ArrayList<>( numHospitals ); for( int iHospital = 0; iHospital < numHospitals; ++iHospital ) { roundDurations.add( new ArrayList<>( numRounds ) ); } numPairsTotal = initialNumPairs; runWatch = new Stopwatch(); roundWatch = new Stopwatch(); } public int getNumPairsOperated() { return numPairsOperated; } public int getNumPairsTotal() { return numPairsTotal; } public long getRunDuration() { return runDuration; } public List<List<Long>> getRoundDurations() { return roundDurations; } public double getOperationRate() { return (double)numPairsOperated / numPairsTotal; } public void incrementNumPairsOperated() { ++numPairsOperated; } public void incrementNumPairsTotal() { ++numPairsTotal; } public void startRun() { runWatch.start(); } public void stopRun() { runDuration = runWatch.stop(); } public void startRound() { roundWatch.start(); } public void stopRound( int hospitalId ) { roundDurations.get( hospitalId - 1 ).add( roundWatch.stop() ); } }
package com.virtusa.shoppersden.services; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @Service public class FileUploadService { public void uploadFile(MultipartFile file) { String folder = System.getProperty("user.dir")+"/src/main/resources/static/images/products/"; try { byte[] bytes=file.getBytes(); Path path=Paths.get(folder+file.getOriginalFilename()); Files.write(path, bytes); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } Controller code: @PostMapping("/addproduct") public String addProduct(@RequestParam MultipartFile imageURL) { fileUploadService.uploadFile(imageURL); }
package net.minecraft.network; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Maps; import java.util.Map; import javax.annotation.Nullable; import net.minecraft.network.handshake.client.C00Handshake; import net.minecraft.network.login.client.CPacketEncryptionResponse; import net.minecraft.network.login.client.CPacketLoginStart; import net.minecraft.network.login.server.SPacketDisconnect; import net.minecraft.network.login.server.SPacketEnableCompression; import net.minecraft.network.login.server.SPacketEncryptionRequest; import net.minecraft.network.login.server.SPacketLoginSuccess; import net.minecraft.network.play.client.CPacketAnimation; import net.minecraft.network.play.client.CPacketChatMessage; import net.minecraft.network.play.client.CPacketClickWindow; import net.minecraft.network.play.client.CPacketClientSettings; import net.minecraft.network.play.client.CPacketClientStatus; import net.minecraft.network.play.client.CPacketCloseWindow; import net.minecraft.network.play.client.CPacketConfirmTeleport; import net.minecraft.network.play.client.CPacketConfirmTransaction; import net.minecraft.network.play.client.CPacketCreativeInventoryAction; import net.minecraft.network.play.client.CPacketCustomPayload; import net.minecraft.network.play.client.CPacketEnchantItem; import net.minecraft.network.play.client.CPacketEntityAction; import net.minecraft.network.play.client.CPacketHeldItemChange; import net.minecraft.network.play.client.CPacketInput; import net.minecraft.network.play.client.CPacketKeepAlive; import net.minecraft.network.play.client.CPacketPlaceRecipe; import net.minecraft.network.play.client.CPacketPlayer; import net.minecraft.network.play.client.CPacketPlayerAbilities; import net.minecraft.network.play.client.CPacketPlayerDigging; import net.minecraft.network.play.client.CPacketPlayerTryUseItem; import net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock; import net.minecraft.network.play.client.CPacketRecipeInfo; import net.minecraft.network.play.client.CPacketResourcePackStatus; import net.minecraft.network.play.client.CPacketSeenAdvancements; import net.minecraft.network.play.client.CPacketSpectate; import net.minecraft.network.play.client.CPacketSteerBoat; import net.minecraft.network.play.client.CPacketTabComplete; import net.minecraft.network.play.client.CPacketUpdateSign; import net.minecraft.network.play.client.CPacketUseEntity; import net.minecraft.network.play.client.CPacketVehicleMove; import net.minecraft.network.play.server.SPacketAdvancementInfo; import net.minecraft.network.play.server.SPacketAnimation; import net.minecraft.network.play.server.SPacketBlockAction; import net.minecraft.network.play.server.SPacketBlockBreakAnim; import net.minecraft.network.play.server.SPacketBlockChange; import net.minecraft.network.play.server.SPacketCamera; import net.minecraft.network.play.server.SPacketChangeGameState; import net.minecraft.network.play.server.SPacketChat; import net.minecraft.network.play.server.SPacketChunkData; import net.minecraft.network.play.server.SPacketCloseWindow; import net.minecraft.network.play.server.SPacketCollectItem; import net.minecraft.network.play.server.SPacketCombatEvent; import net.minecraft.network.play.server.SPacketConfirmTransaction; import net.minecraft.network.play.server.SPacketCooldown; import net.minecraft.network.play.server.SPacketCustomPayload; import net.minecraft.network.play.server.SPacketCustomSound; import net.minecraft.network.play.server.SPacketDestroyEntities; import net.minecraft.network.play.server.SPacketDisconnect; import net.minecraft.network.play.server.SPacketDisplayObjective; import net.minecraft.network.play.server.SPacketEffect; import net.minecraft.network.play.server.SPacketEntity; import net.minecraft.network.play.server.SPacketEntityAttach; import net.minecraft.network.play.server.SPacketEntityEffect; import net.minecraft.network.play.server.SPacketEntityEquipment; import net.minecraft.network.play.server.SPacketEntityHeadLook; import net.minecraft.network.play.server.SPacketEntityMetadata; import net.minecraft.network.play.server.SPacketEntityProperties; import net.minecraft.network.play.server.SPacketEntityStatus; import net.minecraft.network.play.server.SPacketEntityTeleport; import net.minecraft.network.play.server.SPacketEntityVelocity; import net.minecraft.network.play.server.SPacketExplosion; import net.minecraft.network.play.server.SPacketHeldItemChange; import net.minecraft.network.play.server.SPacketJoinGame; import net.minecraft.network.play.server.SPacketKeepAlive; import net.minecraft.network.play.server.SPacketMaps; import net.minecraft.network.play.server.SPacketMoveVehicle; import net.minecraft.network.play.server.SPacketMultiBlockChange; import net.minecraft.network.play.server.SPacketOpenWindow; import net.minecraft.network.play.server.SPacketParticles; import net.minecraft.network.play.server.SPacketPlaceGhostRecipe; import net.minecraft.network.play.server.SPacketPlayerAbilities; import net.minecraft.network.play.server.SPacketPlayerListHeaderFooter; import net.minecraft.network.play.server.SPacketPlayerListItem; import net.minecraft.network.play.server.SPacketPlayerPosLook; import net.minecraft.network.play.server.SPacketRecipeBook; import net.minecraft.network.play.server.SPacketRemoveEntityEffect; import net.minecraft.network.play.server.SPacketResourcePackSend; import net.minecraft.network.play.server.SPacketRespawn; import net.minecraft.network.play.server.SPacketScoreboardObjective; import net.minecraft.network.play.server.SPacketSelectAdvancementsTab; import net.minecraft.network.play.server.SPacketServerDifficulty; import net.minecraft.network.play.server.SPacketSetExperience; import net.minecraft.network.play.server.SPacketSetPassengers; import net.minecraft.network.play.server.SPacketSetSlot; import net.minecraft.network.play.server.SPacketSignEditorOpen; import net.minecraft.network.play.server.SPacketSoundEffect; import net.minecraft.network.play.server.SPacketSpawnExperienceOrb; import net.minecraft.network.play.server.SPacketSpawnGlobalEntity; import net.minecraft.network.play.server.SPacketSpawnMob; import net.minecraft.network.play.server.SPacketSpawnObject; import net.minecraft.network.play.server.SPacketSpawnPainting; import net.minecraft.network.play.server.SPacketSpawnPlayer; import net.minecraft.network.play.server.SPacketSpawnPosition; import net.minecraft.network.play.server.SPacketStatistics; import net.minecraft.network.play.server.SPacketTabComplete; import net.minecraft.network.play.server.SPacketTeams; import net.minecraft.network.play.server.SPacketTimeUpdate; import net.minecraft.network.play.server.SPacketTitle; import net.minecraft.network.play.server.SPacketUnloadChunk; import net.minecraft.network.play.server.SPacketUpdateBossInfo; import net.minecraft.network.play.server.SPacketUpdateHealth; import net.minecraft.network.play.server.SPacketUpdateScore; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.network.play.server.SPacketUseBed; import net.minecraft.network.play.server.SPacketWindowItems; import net.minecraft.network.play.server.SPacketWindowProperty; import net.minecraft.network.play.server.SPacketWorldBorder; import net.minecraft.network.status.client.CPacketPing; import net.minecraft.network.status.client.CPacketServerQuery; import net.minecraft.network.status.server.SPacketPong; import net.minecraft.network.status.server.SPacketServerInfo; import org.apache.logging.log4j.LogManager; public enum EnumConnectionState { HANDSHAKING(-1) { EnumConnectionState(int $anonymous0) { registerPacket(EnumPacketDirection.SERVERBOUND, (Class)C00Handshake.class); } }, PLAY(0) { EnumConnectionState(int $anonymous0) { registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSpawnObject.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSpawnExperienceOrb.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSpawnGlobalEntity.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSpawnMob.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSpawnPainting.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSpawnPlayer.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketAnimation.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketStatistics.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketBlockBreakAnim.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketUpdateTileEntity.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketBlockAction.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketBlockChange.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketUpdateBossInfo.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketServerDifficulty.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketTabComplete.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketChat.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketMultiBlockChange.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketConfirmTransaction.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketCloseWindow.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketOpenWindow.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketWindowItems.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketWindowProperty.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSetSlot.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketCooldown.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketCustomPayload.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketCustomSound.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketDisconnect.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntityStatus.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketExplosion.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketUnloadChunk.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketChangeGameState.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketKeepAlive.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketChunkData.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEffect.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketParticles.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketJoinGame.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketMaps.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntity.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntity.S15PacketEntityRelMove.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntity.S17PacketEntityLookMove.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntity.S16PacketEntityLook.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketMoveVehicle.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSignEditorOpen.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketPlaceGhostRecipe.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketPlayerAbilities.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketCombatEvent.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketPlayerListItem.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketPlayerPosLook.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketUseBed.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketRecipeBook.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketDestroyEntities.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketRemoveEntityEffect.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketResourcePackSend.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketRespawn.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntityHeadLook.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSelectAdvancementsTab.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketWorldBorder.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketCamera.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketHeldItemChange.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketDisplayObjective.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntityMetadata.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntityAttach.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntityVelocity.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntityEquipment.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSetExperience.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketUpdateHealth.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketScoreboardObjective.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSetPassengers.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketTeams.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketUpdateScore.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSpawnPosition.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketTimeUpdate.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketTitle.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketSoundEffect.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketPlayerListHeaderFooter.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketCollectItem.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntityTeleport.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketAdvancementInfo.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntityProperties.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEntityEffect.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketConfirmTeleport.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketTabComplete.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketChatMessage.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketClientStatus.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketClientSettings.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketConfirmTransaction.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketEnchantItem.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketClickWindow.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketCloseWindow.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketCustomPayload.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketUseEntity.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketKeepAlive.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketPlayer.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketPlayer.Position.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketPlayer.PositionRotation.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketPlayer.Rotation.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketVehicleMove.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketSteerBoat.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketPlaceRecipe.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketPlayerAbilities.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketPlayerDigging.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketEntityAction.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketInput.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketRecipeInfo.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketResourcePackStatus.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketSeenAdvancements.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketHeldItemChange.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketCreativeInventoryAction.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketUpdateSign.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketAnimation.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketSpectate.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketPlayerTryUseItemOnBlock.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketPlayerTryUseItem.class); } }, STATUS(1) { EnumConnectionState(int $anonymous0) { registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketServerQuery.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketServerInfo.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketPing.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketPong.class); } }, LOGIN(2) { EnumConnectionState(int $anonymous0) { registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketDisconnect.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEncryptionRequest.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketLoginSuccess.class); registerPacket(EnumPacketDirection.CLIENTBOUND, (Class)SPacketEnableCompression.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketLoginStart.class); registerPacket(EnumPacketDirection.SERVERBOUND, (Class)CPacketEncryptionResponse.class); } }; private static final EnumConnectionState[] STATES_BY_ID; private static final Map<Class<? extends Packet<?>>, EnumConnectionState> STATES_BY_CLASS; private final int id; private final Map<EnumPacketDirection, BiMap<Integer, Class<? extends Packet<?>>>> directionMaps; static { STATES_BY_ID = new EnumConnectionState[4]; STATES_BY_CLASS = Maps.newHashMap(); byte b; int i; EnumConnectionState[] arrayOfEnumConnectionState; for (i = (arrayOfEnumConnectionState = values()).length, b = 0; b < i; ) { EnumConnectionState enumconnectionstate = arrayOfEnumConnectionState[b]; int j = enumconnectionstate.getId(); if (j < -1 || j > 2) throw new Error("Invalid protocol ID " + Integer.toString(j)); STATES_BY_ID[j - -1] = enumconnectionstate; for (EnumPacketDirection enumpacketdirection : enumconnectionstate.directionMaps.keySet()) { for (Class<? extends Packet<?>> oclass : (Iterable<Class<? extends Packet<?>>>)((BiMap)enumconnectionstate.directionMaps.get(enumpacketdirection)).values()) { if (STATES_BY_CLASS.containsKey(oclass) && STATES_BY_CLASS.get(oclass) != enumconnectionstate) throw new Error("Packet " + oclass + " is already assigned to protocol " + STATES_BY_CLASS.get(oclass) + " - can't reassign to " + enumconnectionstate); try { oclass.newInstance(); } catch (Throwable var10) { throw new Error("Packet " + oclass + " fails instantiation checks! " + oclass); } STATES_BY_CLASS.put(oclass, enumconnectionstate); } } b++; } } EnumConnectionState(int protocolId) { this.directionMaps = Maps.newEnumMap(EnumPacketDirection.class); this.id = protocolId; } protected EnumConnectionState registerPacket(EnumPacketDirection direction, Class<? extends Packet<?>> packetClass) { HashBiMap hashBiMap; BiMap<Integer, Class<? extends Packet<?>>> bimap = this.directionMaps.get(direction); if (bimap == null) { hashBiMap = HashBiMap.create(); this.directionMaps.put(direction, hashBiMap); } if (hashBiMap.containsValue(packetClass)) { String s = direction + " packet " + packetClass + " is already known to ID " + hashBiMap.inverse().get(packetClass); LogManager.getLogger().fatal(s); throw new IllegalArgumentException(s); } hashBiMap.put(Integer.valueOf(hashBiMap.size()), packetClass); return this; } public Integer getPacketId(EnumPacketDirection direction, Packet<?> packetIn) throws Exception { return (Integer)((BiMap)this.directionMaps.get(direction)).inverse().get(packetIn.getClass()); } @Nullable public Packet<?> getPacket(EnumPacketDirection direction, int packetId) throws InstantiationException, IllegalAccessException { Class<? extends Packet<?>> oclass = (Class<? extends Packet<?>>)((BiMap)this.directionMaps.get(direction)).get(Integer.valueOf(packetId)); return (oclass == null) ? null : oclass.newInstance(); } public int getId() { return this.id; } public static EnumConnectionState getById(int stateId) { return (stateId >= -1 && stateId <= 2) ? STATES_BY_ID[stateId - -1] : null; } public static EnumConnectionState getFromPacket(Packet<?> packetIn) { return STATES_BY_CLASS.get(packetIn.getClass()); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\EnumConnectionState.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.imooc.service; import com.imooc.pojo.SellerInfo; /** * @author ๅฎ‹ๅพท่ƒฝ * @date 2019ๅนด12ๆœˆ14ๆ—ฅ---ไธ‹ๅˆ 4:06 */ public interface SellerService { /** * ้€š่ฟ‡openidๆŸฅ่ฏขๅ–ๅฎถ็ซฏไฟกๆฏ * @param openid * @return */ SellerInfo findSellerInfoByOpenid(String openid); }
package vc.lang.types; import vc.lang.impl.EvaluationContext; import vc.lang.runtime.ExecException; public abstract class Box extends Token { @Override public void eval(EvaluationContext context) throws ExecException { context.getDataStack().push(this); } @Override public byte[] getSymbol() { return null; } public abstract Num toNum(EvaluationContext context) throws ExecException; public abstract Str toStr(EvaluationContext context) throws ExecException; public abstract Vec toVec(); public Box eq(Box other) { return new Num(sameValue(other) ? -1.0 : 0.0); } public boolean isTruth() { return true; } }
package com.github.hippo.callback; import com.github.hippo.bean.HippoRequest; import com.github.hippo.bean.HippoResponse; import com.github.hippo.exception.HippoServiceException; import com.github.hippo.netty.HippoClientBootstrap; import com.github.hippo.netty.HippoResultCallBack; /** * Created by wangjian on 17/10/24. */ public class CallAsync implements RemoteCallHandler { @Override public HippoResponse call(HippoClientBootstrap hippoClientBootstrap, HippoRequest hippoRequest, int timeOut) { try { ICallBack iCallBack = hippoRequest.getiCallBack(); if (iCallBack == null) { throw new HippoServiceException("callback ไธ่ƒฝไธบnull"); } return hippoClientBootstrap.sendWithCallBack(hippoRequest, timeOut); } finally { CallTypeHelper.SETTING.remove(); } } @Override public void back(HippoResultCallBack hippoResultCallBack, HippoResponse hippoResponse) { ICallBack callBack = hippoResultCallBack.getHippoRequest().getiCallBack(); if (hippoResponse.isError()) { callBack.onFailure(hippoResponse.getThrowable()); } else { callBack.onSuccess(hippoResponse.getResult()); } } }
package pl.finsys.aspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CustomerImpl implements Customer { private final static Logger logger = LoggerFactory.getLogger(CustomerImpl.class.getName()); public void addCustomer(){ logger.info("addCustomer() is running "); } public String addCustomerReturnValue(){ logger.info("addCustomerReturnValue() is running "); return "abc"; } public void addCustomerThrowException() throws Exception { logger.info("addCustomerThrowException() is running "); throw new Exception("Generic Error"); } public void addCustomerAround(String name){ logger.info("addCustomerAround() is running, args : " + name); } }
package so.ego.space.domains.project.application.dto; import lombok.Getter; import java.time.LocalDate; @Getter public class ProjectUpdateRequest { private Long id; private String name; private String content; private LocalDate start_date; private LocalDate end_date; private Long user_id; }
package no.nav.vedtak.felles.prosesstask.impl; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; import no.nav.vedtak.felles.prosesstask.UnittestRepositoryRule; import no.nav.vedtak.felles.prosesstask.api.ProsessTaskData; import no.nav.vedtak.felles.prosesstask.api.ProsessTaskRepository; import no.nav.vedtak.felles.prosesstask.api.ProsessTaskStatus; public class ProsessTaskRepositoryImplIT { private static final LocalDateTime Nร… = LocalDateTime.now().truncatedTo(ChronoUnit.MILLIS); private final LocalDateTime nesteKjรธringEtter = Nร….plusHours(1); private final AtomicLong ids= new AtomicLong(1); @Rule public UnittestRepositoryRule repoRule = new UnittestRepositoryRule(); private ProsessTaskRepository prosessTaskRepository; @Before public void setUp() throws Exception { ProsessTaskEventPubliserer prosessTaskEventPubliserer = Mockito.mock(ProsessTaskEventPubliserer.class); Mockito.doNothing().when(prosessTaskEventPubliserer).fireEvent(Mockito.any(ProsessTaskData.class), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); prosessTaskRepository = new ProsessTaskRepositoryImpl(repoRule.getEntityManager(), null, prosessTaskEventPubliserer); lagTestData(); } @Test public void test_ingen_match_innenfor_et_kjรธretidsintervall() throws Exception { List<ProsessTaskStatus> statuser = Arrays.asList(ProsessTaskStatus.values()); List<ProsessTaskData> prosessTaskData = prosessTaskRepository.finnAlle(statuser, Nร….minusHours(1), Nร…); Assertions.assertThat(prosessTaskData).isEmpty(); } @Test public void test_har_match_innenfor_et_kjรธretidsntervall() throws Exception { List<ProsessTaskStatus> statuser = Arrays.asList(ProsessTaskStatus.values()); List<ProsessTaskData> prosessTaskData = prosessTaskRepository.finnAlle(statuser, Nร….minusHours(2), Nร…); Assertions.assertThat(prosessTaskData).hasSize(1); Assertions.assertThat(prosessTaskData.get(0).getStatus()).isEqualTo(ProsessTaskStatus.FERDIG); } @Test public void test_ingen_match_for_angitt_prosesstatus() throws Exception { List<ProsessTaskStatus> statuser = Arrays.asList(ProsessTaskStatus.SUSPENDERT); List<ProsessTaskData> prosessTaskData = prosessTaskRepository.finnAlle(statuser, Nร….minusHours(2), Nร…); Assertions.assertThat(prosessTaskData).isEmpty(); } @Test public void test_skal_finne_tasks_som_matcher_angitt_sรธk() throws Exception { List<ProsessTaskStatus> statuser = Arrays.asList(ProsessTaskStatus.SUSPENDERT); List<ProsessTaskData> prosessTaskData = prosessTaskRepository.finnAlleForAngittSรธk(statuser, null, nesteKjรธringEtter, nesteKjรธringEtter, "fagsakId=1%behandlingId=2%"); Assertions.assertThat(prosessTaskData).hasSize(1); } @Test public void skal_finne_tasks_med_cron_expressions() { Map<ProsessTaskType, ProsessTaskEntitet> map = prosessTaskRepository.finnStatusForBatchTasks(); Assertions.assertThat(map).hasSize(2); } private void lagTestData() { ProsessTaskType taskType = new ProsessTaskType("hello.world"); ProsessTaskType taskType2 = new ProsessTaskType("hello.world2", "0 0 8 * * ?"); ProsessTaskType taskType3 = new ProsessTaskType("hello.world3", "0 0 8 * * ?"); lagre(taskType); lagre(taskType2); lagre(taskType3); flushAndClear(); lagre(lagTestEntitet(ProsessTaskStatus.FERDIG, Nร….minusHours(2), "hello.world")); lagre(lagTestEntitet(ProsessTaskStatus.VENTER_SVAR, Nร….minusHours(3), "hello.world")); lagre(lagTestEntitet(ProsessTaskStatus.FEILET, Nร….minusHours(4), "hello.world")); lagre(lagTestEntitet(ProsessTaskStatus.KLAR, Nร….minusHours(5), "hello.world")); lagre(lagTestEntitet(ProsessTaskStatus.SUSPENDERT, Nร….minusHours(6), "hello.world")); lagre(lagTestEntitet(ProsessTaskStatus.KLAR, Nร….minusHours(6), "hello.world2")); flushAndClear(); } private void flushAndClear() { var em = repoRule.getEntityManager(); em.flush(); em.clear(); } private void lagre(Object entity) { var em = repoRule.getEntityManager(); em.persist(entity); } private ProsessTaskEntitet lagTestEntitet(ProsessTaskStatus status, LocalDateTime sistKjรธrt, String taskType) { ProsessTaskData data = new ProsessTaskData(taskType); data.setPayload("payload"); data.setStatus(status); data.setSisteKjรธringServerProsess("prossess-123"); data.setSisteFeilKode("feilkode-123"); data.setSisteFeil("siste-feil"); data.setAntallFeiledeForsรธk(2); data.setBehandling(1L, 2L, "3"); data.setGruppe("gruppe"); data.setNesteKjรธringEtter(nesteKjรธringEtter); data.setPrioritet(2); data.setSekvens("123"); data.setId(ids.incrementAndGet()); if (sistKjรธrt != null) { data.setSistKjรธrt(sistKjรธrt); } ProsessTaskEntitet pte = new ProsessTaskEntitet(); return pte.kopierFraEksisterende(data); } }
package com.wukker.sb.eventconnectionfortopmobile.model; import com.wukker.sb.eventconnectionfortopmobile.model.Event; import java.io.Serializable; import java.util.ArrayList; /** * Created by sb on 02.11.15. */ public class Conference<T extends Base> extends Base implements Serializable { Long id; Long dateCreated; Long lastUpdated; Long dateStart; Long dateEnd; Boolean visible; String name; String brief; String url; ArrayList<Event> events; public Conference(long id, String name) { this.id = id; this.name = name; } public Conference(long id, long dateStart, long dateEnd, boolean visible, String name, String brief, String url, ArrayList<Event> events) { this.id = id; this.dateStart = dateStart; this.dateEnd = dateEnd; this.name = name; this.brief = brief; this.url = url; this.events = events; this.visible = visible; } public long getDateStart() { return dateStart; } public void setDateStart(long dateStart) { this.dateStart = dateStart; } public long getDateEnd() { return dateEnd; } public void setDateEnd(long dateEnd) { this.dateEnd = dateEnd; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBrief() { return brief; } public void setBrief(String brief) { this.brief = brief; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public ArrayList<Event> getAllEvents() { return events; } public void setAllEvents(ArrayList<Event> events) { this.events = events; } }
package com.tencent.mm.plugin.aa; import com.tencent.mm.bt.h.d; import com.tencent.mm.g.a.bo; import com.tencent.mm.g.a.bp; import com.tencent.mm.g.a.ml; import com.tencent.mm.g.a.mm; import com.tencent.mm.g.a.th; import com.tencent.mm.kernel.g; import com.tencent.mm.model.ar; import com.tencent.mm.model.p; import com.tencent.mm.plugin.messenger.foundation.a.n; import com.tencent.mm.plugin.messenger.foundation.a.o; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.b.c; import java.util.HashMap; public class b implements ar { private static HashMap<Integer, d> cVM; private c<mm> ezp = new 1(this); private c<ml> ezq = new 2(this); private c<bo> ezr = new 3(this); private c<bp> ezs = new 4(this); private n ezt = new 5(this); c<th> ezu = new 6(this); private com.tencent.mm.plugin.aa.a.b.d ezv; private com.tencent.mm.plugin.aa.a.b.b ezw; private static b VP() { return (b) p.v(b.class); } static { HashMap hashMap = new HashMap(); cVM = hashMap; hashMap.put(Integer.valueOf("AARecord".hashCode()), new 7()); cVM.put(Integer.valueOf("AAPayRecord".hashCode()), new 8()); } public final HashMap<Integer, d> Ci() { return cVM; } public static com.tencent.mm.plugin.aa.a.b.d VQ() { if (VP().ezv == null) { b VP = VP(); g.Ek(); VP.ezv = new com.tencent.mm.plugin.aa.a.b.d(g.Ei().dqq); } return VP().ezv; } public static com.tencent.mm.plugin.aa.a.b.b VR() { if (VP().ezw == null) { b VP = VP(); g.Ek(); VP.ezw = new com.tencent.mm.plugin.aa.a.b.b(g.Ei().dqq); } return VP().ezw; } public final void gi(int i) { } public final void bn(boolean z) { a.sFg.b(this.ezp); a.sFg.b(this.ezq); a.sFg.b(this.ezr); a.sFg.b(this.ezs); a.sFg.b(this.ezu); ((o) g.n(o.class)).getSysCmdMsgExtension().a("paymsg", this.ezt); } public final void bo(boolean z) { } public final void onAccountRelease() { a.sFg.c(this.ezp); a.sFg.c(this.ezq); a.sFg.c(this.ezr); a.sFg.c(this.ezs); a.sFg.c(this.ezu); ((o) g.n(o.class)).getSysCmdMsgExtension().b("paymsg", this.ezt); } }
package com.sarf.web; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.sarf.service.MemberService; import com.sarf.service.UserMailSendService; import com.sarf.vo.MemberVO; @Controller @RequestMapping("/member/*") public class MemberController { private static final Logger logger = LoggerFactory.getLogger(MemberController.class); @Inject MemberService service; // ๋ฉ”์ผ ๊ด€๋ จ @Inject UserMailSendService mailsender; // ์•”ํ˜ธํ™” ๊ธฐ๋Šฅ ์‚ฌ์šฉ @Inject BCryptPasswordEncoder pwdEncoder; boolean debug = true; // ํšŒ์›๊ฐ€์ž… get @RequestMapping(value = "join", method = RequestMethod.GET) public void getJoin() throws Exception{ // LOG if (debug) { logger.info("get join"); } } // ํšŒ์›๊ฐ€์ž… post @RequestMapping(value = "join", method = RequestMethod.POST) public String postJoin(MemberVO vo) throws Exception{ // LOG if (debug) { logger.info("~~~post join~~~"); } String inputPass = vo.getPw(); String pwd = pwdEncoder.encode(inputPass); vo.setPw(pwd); service.join(vo); return "main"; } // ๋กœ๊ทธ์ธ get @RequestMapping(value = "login", method = RequestMethod.GET) public void getLogin() throws Exception{ // LOG if (debug) { logger.info("~~~get login~~~"); } } // ๋กœ๊ทธ์ธ post @RequestMapping(value = "login", method = RequestMethod.POST) public String postLogin(MemberVO vo, HttpServletRequest req, RedirectAttributes rttr) throws Exception{ // LOG if (debug) { logger.info("~~~post login~~~"); } HttpSession session = req.getSession(); session.getAttribute("member"); // ์•„์ด๋””๊ฐ€ ์กด์žฌํ•˜๋Š” ์ง€ ํ™•์ธ MemberVO login = service.login(vo); if(login == null) { rttr.addFlashAttribute("idNull", true); return "redirect:login"; } boolean pwdMatch = pwdEncoder.matches(vo.getPw(), login.getPw()); if(login != null && pwdMatch == true) { session.setAttribute("logincheck", true); session.setAttribute("member", login); } else { //session.setAttribute("member", null); rttr.addFlashAttribute("msg", false); return "redirect:login"; } return "main"; } // ๋กœ๊ทธ์•„์›ƒ get @RequestMapping(value = "logout", method = RequestMethod.GET) public String getLogout(HttpSession session) throws Exception{ // LOG if (debug) { logger.info("~~~get logout~~~"); } session.invalidate(); return "redirect:/"; } // ํšŒ์› ์ •๋ณด ์ˆ˜์ • get @RequestMapping(value = "updatemember", method = RequestMethod.GET) public String getUpdateMember() throws Exception{ // LOG if (debug) { logger.info("~~~get updatemember~~~"); } return "member/updatemember"; } // ํšŒ์› ์ •๋ณด ์ˆ˜์ • post @RequestMapping(value = "updatemember", method = RequestMethod.POST) public String postUpdateMember(MemberVO vo, HttpSession session) throws Exception{ // LOG if (debug) { logger.info("~~~post updatemember~~~"); } String inputPass = vo.getPw(); String pwd = pwdEncoder.encode(inputPass); vo.setPw(pwd); service.updateMember(vo); session.invalidate(); return "redirect:/"; } // ํšŒ์› ํƒˆํ‡ด get @RequestMapping(value = "deletemember", method = RequestMethod.GET) public void getDeleteMember() throws Exception{ // LOG if (debug) { logger.info("~~~get deletemember~~~"); } } // ํšŒ์› ํƒˆํ‡ด post @RequestMapping(value = "deletemember", method = RequestMethod.POST) public String postDeleteMember(MemberVO vo, HttpSession session, RedirectAttributes rttr) throws Exception{ // LOG if (debug) { logger.info("~~~post deletemember~~~"); } // ์„ธ์…˜์— ์žˆ๋Š” member๋ฅผ ๊ฐ€์ ธ์™€ member ๋ณ€์ˆ˜์— ๋„ฃ์–ด์ค๋‹ˆ๋‹ค. MemberVO member = (MemberVO) session.getAttribute("member"); // ์„ธ์…˜์— ์žˆ๋Š” ๋น„๋ฐ€๋ฒˆํ˜ธ String sessionPass = member.getPw(); System.out.println("sessionpass~~~ " + sessionPass); // vo๋กœ ๋“ค์–ด์˜ค๋Š” ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์•”ํ˜ธํ™” String voPass = vo.getPw(); String pwd = pwdEncoder.encode(voPass); System.out.println("pwd~~~ " + pwd); if (!(pwdEncoder.matches(vo.getPw(), sessionPass))) { rttr.addFlashAttribute("msg", false); return "redirect:/member/deletemember"; } rttr.addFlashAttribute("deletemsg", false); service.deleteMember(vo); session.invalidate(); return "redirect:/"; } // ์•„์ด๋”” ์ฐพ๊ธฐ get @RequestMapping(value = "find_id", method = RequestMethod.GET) public void getFindId() throws Exception{ // LOG if (debug) { logger.info("~~~get find_id~~~"); } } // ์•„์ด๋”” ์ฐพ๊ธฐ ๊ฒฐ๊ณผ๊ฐ’ ์ถœ๋ ฅ @RequestMapping(value = "canuseid", method = RequestMethod.GET) public String canuseid(MemberVO vo, Model model) throws Exception{ // LOG if (debug) { logger.info("~~~get canuseid~~~"); } System.out.println(vo.getEmail() + "@@@@@@" + vo.getName()+ "@@@@@@"); MemberVO findid = service.findId(vo); if(findid == null) { model.addAttribute("find_id_chk", false); return "member/find_id_result"; }else { model.addAttribute("find_id_chk", true); model.addAttribute("find_id", findid); return "member/find_id_result"; } } // ๋น„๋ฐ€๋ฒˆํ˜ธ ์ฐพ๊ธฐ get @RequestMapping(value = "find_pw", method = RequestMethod.GET) public void getFindPw() throws Exception{ // LOG if (debug) { logger.info("~~~get find_pw~~~"); } } // ๋น„๋ฐ€๋ฒˆํ˜ธ ์ฐพ๊ธฐ post @RequestMapping(value = "find_pw", method = RequestMethod.POST) public String postFindPw(MemberVO vo, RedirectAttributes rttr, Model model, HttpServletRequest request) throws Exception{ // LOG if (debug) { logger.info("~~~post find_pw~~~"); } MemberVO findpw = service.findPw(vo); if(findpw == null) { rttr.addFlashAttribute("find_pw_msg", false); return "redirect:find_pw"; } // ๋น„๋ฐ€๋ฒˆํ˜ธ ์ด๋ฉ”์ผ ์ „์†ก ํ›„ ์ž„์‹œ ๋น„๋ฐ€๋ฒˆํ˜ธ ๋ฐ›์Œ String key = mailsender.mailSendWithUserKey(vo.getId(), vo.getEmail(), request); String pwd = pwdEncoder.encode(key); findpw.setPw(pwd); service.updateMember(findpw); rttr.addFlashAttribute("find_pw_msg", true); return "redirect:login"; } // ์•„์ด๋”” ์ค‘๋ณต ์ฒดํฌ get @RequestMapping(value = "idcheck", method = RequestMethod.GET) public String getidcheck(@RequestParam String id, Model model) throws Exception{ // LOG if (debug) { logger.info("~~~get idcheck~~~"); } String idcheck = service.idcheck(id); if(idcheck != null) { model.addAttribute("idcheck", false); return "member/idcheck"; }else { model.addAttribute("idcheck", true); return "member/idcheck"; } } // ์ด๋ฉ”์ผ ์ค‘๋ณต ์ฒดํฌ get @RequestMapping(value = "emailcheck", method = RequestMethod.GET) public String getemailcheck(@RequestParam String email, Model model) throws Exception{ // LOG if (debug) { logger.info("~~~get emailcheck~~~"); } System.out.println("์ด๋ฉ”์ผ~~~" + email); String emailcheck = service.emailcheck(email); System.out.println("@@@@@@@@@@" + emailcheck); if(emailcheck != null) { model.addAttribute("emailcheck", false); return "member/emailcheck"; }else { model.addAttribute("emailcheck", true); return "member/emailcheck"; } } // ํŒจ์Šค์›Œ๋“œ ์ฒดํฌ @ResponseBody @RequestMapping(value = "/passChk", method = RequestMethod.POST) public boolean passChk(MemberVO vo) throws Exception { MemberVO login = service.login(vo); boolean pwdChk = pwdEncoder.matches(vo.getPw(), login.getPw()); return pwdChk; } }
import java.util.*; public class balancedBracket { public static void main(String args[]) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); Stack<Character> st = new Stack<>(); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == '(' || ch == '{' || ch == '[') { st.push(ch); } else if (ch == ')') { boolean val = handleClosing(st, '('); if (val == false) { System.out.println(val); return; } } else if (ch == '}') { boolean val = handleClosing(st, '{'); if (val == false) { System.out.println(val); return; } } else if (ch == ']') { boolean val = handleClosing(st, '['); if (val == false) { System.out.println(val); return; } } } if (st.size() == 0) { //if stack size is zero after all pop and push , then its balanced bracket System.out.println(true); } else { System.out.println(false); } } public static boolean handleClosing(Stack<Character> st, char correspondingOpeningCharacter) { if (st.size() == 0) { // extra opening Bracket case return false; } else if (st.peek() != correspondingOpeningCharacter) { // peek k time iska counter part nhi mila return false; } else { st.pop(); return true; } } }
package uit.edu.vn.models; public class MaVachSanPham extends DanhSachKhuyenMaiSanPham{ private Integer id; private String MaVach; private Integer idNhaCungCap; private Integer SoLuong; private Integer SuDung; private Integer GiaBan; private String LanSuaCuoi; private Integer idNhanVien; private String GhiChuThayDoi; private Integer GiaNhap; private Integer HetBan; private Integer KhongTichluyDiem; private Integer idSanPhamCuaHang; private String NgayTao; public MaVachSanPham() { super(); // TODO Auto-generated constructor stub } public MaVachSanPham(String tenLoaiSanPham, Integer giaBanMoi) { super(tenLoaiSanPham, giaBanMoi); // TODO Auto-generated constructor stub } public MaVachSanPham(String tenLoaiSanPham, Integer giaBanMoi, Integer iDMaVach, Integer iDSanPhamCuaHang,Integer soLuong, Integer suDung, Integer giaBan) { super(tenLoaiSanPham, giaBanMoi); id =iDMaVach; idSanPhamCuaHang = iDSanPhamCuaHang; SoLuong = soLuong; SuDung = suDung; GiaBan = giaBan; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getMaVach() { return MaVach; } public void setMaVach(String maVach) { MaVach = maVach; } public Integer getIdNhaCungCap() { return idNhaCungCap; } public void setIdNhaCungCap(Integer idNhaCungCap) { this.idNhaCungCap = idNhaCungCap; } public Integer getSoLuong() { return SoLuong; } public void setSoLuong(Integer soLuong) { SoLuong = soLuong; } public Integer getSuDung() { return SuDung; } public void setSuDung(Integer suDung) { SuDung = suDung; } public Integer getGiaBan() { return GiaBan; } public void setGiaBan(Integer giaBan) { GiaBan = giaBan; } public String getLanSuaCuoi() { return LanSuaCuoi; } public void setLanSuaCuoi(String lanSuaCuoi) { LanSuaCuoi = lanSuaCuoi; } public Integer getIdNhanVien() { return idNhanVien; } public void setIdNhanVien(Integer idNhanVien) { this.idNhanVien = idNhanVien; } public String getGhiChuThayDoi() { return GhiChuThayDoi; } public void setGhiChuThayDoi(String ghiChuThayDoi) { GhiChuThayDoi = ghiChuThayDoi; } public Integer getGiaNhap() { return GiaNhap; } public void setGiaNhap(Integer giaNhap) { GiaNhap = giaNhap; } public Integer getHetBan() { return HetBan; } public void setHetBan(Integer hetBan) { HetBan = hetBan; } public Integer getKhongTichluyDiem() { return KhongTichluyDiem; } public void setKhongTichluyDiem(Integer khongTichluyDiem) { KhongTichluyDiem = khongTichluyDiem; } public Integer getIdSanPhamCuaHang() { return idSanPhamCuaHang; } public void setIdSanPhamCuaHang(Integer idSanPhamCuaHang) { this.idSanPhamCuaHang = idSanPhamCuaHang; } public String getNgayTao() { return NgayTao; } public void setNgayTao(String ngayTao) { NgayTao = ngayTao; } }
package com.tencent.mm.plugin.hp.c; import android.os.Build.VERSION; import android.util.Base64; import com.tencent.mm.ab.b; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.kernel.g; import com.tencent.mm.network.k; import com.tencent.mm.network.q; import com.tencent.mm.plugin.boots.a.c; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.protocal.c.bsw; import com.tencent.mm.protocal.c.bta; import com.tencent.mm.protocal.c.oo; import com.tencent.mm.protocal.c.op; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.ao; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.d; import com.tencent.mm.sdk.platformtools.x; import java.util.Collection; import java.util.LinkedList; import java.util.List; public final class a extends l implements k { private final b diG; private e diJ; String kmP; String kmQ; private LinkedList<bsw> kmR; private boolean kmS; com.tencent.mm.plugin.hp.d.b kmT; public a() { this("", "", null, false); } public a(String str, String str2, List<bsw> list) { this(str, str2, list, true); } private a(String str, String str2, List<bsw> list, boolean z) { String str3; Collection list2; this.kmR = new LinkedList(); this.kmS = true; com.tencent.mm.ab.b.a aVar = new com.tencent.mm.ab.b.a(); aVar.dIG = new oo(); aVar.dIH = new op(); aVar.uri = "/cgi-bin/micromsg-bin/checktinkerupdate"; aVar.dIF = 922; aVar.dII = 0; aVar.dIJ = 0; this.diG = aVar.KT(); if (z) { str3 = str2; } else { str = "tinker_id_" + com.tencent.mm.loader.stub.a.baseRevision(); str3 = com.tencent.mm.loader.stub.a.PATCH_REV == null ? "" : "tinker_id_" + com.tencent.mm.loader.stub.a.PATCH_REV; list2 = new LinkedList(); long j = 0; try { j = ((long) com.tencent.mm.kernel.a.Dz()) & 4294967295L; x.i("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", "uin is %s", new Object[]{bi.Xf(String.valueOf(j))}); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", e, "tinker patch manager get uin failed.", new Object[0]); } list2.add(do("code-version", d.CLIENT_VERSION)); list2.add(do("code-reversion", d.REV)); list2.add(do("sdk", String.valueOf(VERSION.SDK_INT))); list2.add(do("os-name", com.tencent.mm.protocal.d.qVK)); list2.add(do("device-brand", com.tencent.mm.protocal.d.qVH)); list2.add(do("device-name", com.tencent.mm.protocal.d.DEVICE_NAME)); list2.add(do("uin", String.valueOf(j))); list2.add(do("network", String.valueOf(ao.isWifi(ad.getContext()) ? 3 : 2))); List<com.tencent.mm.plugin.boots.a.a> aua = ((c) g.l(c.class)).aua(); if (aua != null) { for (com.tencent.mm.plugin.boots.a.a aVar2 : aua) { list2.add(do(Integer.toHexString(aVar2.field_key), String.valueOf(aVar2.field_dau))); } } } this.kmP = str; this.kmQ = str3; this.kmR.addAll(list2); this.kmS = z; } public final int getType() { return 922; } public final int a(com.tencent.mm.network.e eVar, e eVar2) { x.d("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", "doScene"); this.diJ = eVar2; oo ooVar = (oo) this.diG.dID.dIL; ooVar.rsP = this.kmP; ooVar.rsQ = this.kmQ; ooVar.rsR = this.kmR; if (this.kmS) { 1 1 = new 1(this, ooVar); String string = ad.getContext().getSharedPreferences("tinker_patch_share_config", 4).getString("tinker_node", ""); if (!bi.oW(string)) { try { op opVar = new op(); opVar.aG(Base64.decode(string.getBytes(), 0)); if (opVar.rsS != null) { if (com.tencent.mm.loader.stub.a.PATCH_REV == null) { string = ""; } else { string = "tinker_id_" + com.tencent.mm.loader.stub.a.PATCH_REV; } String str = "tinker_id_" + com.tencent.mm.loader.stub.a.baseRevision(); String string2 = ad.getContext().getSharedPreferences("tinker_patch_share_config", 4).getString("tinker_base_id", ""); com.tencent.mm.plugin.hp.d.b bVar = new com.tencent.mm.plugin.hp.d.b(opVar.rsS); x.i("Tinker.TinkerUtils", "LastResponse PID:%s current PID:%s last baseId:%s current baseId:%s", new Object[]{bVar.knj, string, string2, str}); if (!(bi.oW(bVar.knj) || bVar.knj.equalsIgnoreCase(string) || bi.oW(str) || !str.equalsIgnoreCase(string2))) { 1.a(true, bVar); } } } catch (Throwable e) { x.printErrStackTrace("Tinker.TinkerUtils", e, "parse tinker update Response failed.", new Object[0]); h.mEJ.a(614, 73, 1, false); } } 1.a(false, null); } return a(eVar, this.diG, this); } public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { x.i("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", "errType:%d errCode:%d errMsg:%s ", new Object[]{Integer.valueOf(i2), Integer.valueOf(i3), str}); if (i2 == 0 && i3 == 0) { op opVar = (op) ((b) qVar).dIE.dIL; bta bta = opVar.rsS; if (bta == null) { if (str.equalsIgnoreCase("no baseid matched")) { com.tencent.mm.plugin.hp.b.a.cJ(1, 0); } else if (str.equalsIgnoreCase("no update for this patch")) { com.tencent.mm.plugin.hp.b.a.cJ(2, 0); } else if (str.equalsIgnoreCase("no sutable patch available")) { com.tencent.mm.plugin.hp.b.a.cJ(3, 0); } else { com.tencent.mm.plugin.hp.b.a.cJ(5, 0); } if (this.kmT != null) { String str2 = com.tencent.mm.loader.stub.a.PATCH_REV == null ? "" : "tinker_id_" + com.tencent.mm.loader.stub.a.PATCH_REV; if (!(bi.oW(this.kmT.knj) || this.kmT.knj.equalsIgnoreCase(str2))) { int i4 = ad.getContext().getSharedPreferences("tinker_patch_share_config", 4).getInt("tinker_node_retry_time", 0); if (i4 >= 4) { com.tencent.mm.plugin.hp.tinker.g.at(ad.getContext(), ""); com.tencent.mm.plugin.hp.tinker.g.G(ad.getContext(), 0); x.i("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", "retry time over %d time, then clear node and count", new Object[]{Integer.valueOf(i4)}); h.mEJ.a(614, 74, 1, false); } else { new com.tencent.mm.plugin.hp.b.e(this.kmT).fL(this.kmS); h.mEJ.a(614, 70, 1, false); com.tencent.mm.plugin.hp.tinker.g.G(ad.getContext(), i4 + 1); x.d("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", "add retry time %d", new Object[]{Integer.valueOf(i4)}); } } } } else if (this.kmS) { try { com.tencent.mm.plugin.hp.tinker.g.at(ad.getContext(), new String(Base64.encode(opVar.toByteArray(), 0))); com.tencent.mm.plugin.hp.tinker.g.G(ad.getContext(), 0); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", e, "save node failed.", new Object[0]); h.mEJ.a(614, 72, 1, false); } x.d("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", "node is no empty. try to process"); com.tencent.mm.plugin.hp.d.b bVar = new com.tencent.mm.plugin.hp.d.b(bta); x.d("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", "node is no empty. new TinkerSyncResponse finish"); new com.tencent.mm.plugin.hp.b.e(bVar).fL(this.kmS); x.d("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", "node is no empty. end process"); com.tencent.mm.plugin.hp.b.a.cJ(4, 0); } else { x.i("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", "check from setting about ui. "); } } else { x.d("MicroMsg.Tinker.NetSceneCheckTinkerUpdate", "check tinker update failed."); com.tencent.mm.plugin.hp.b.a.cJ(5, i2); } this.diJ.a(i2, i3, str, this); } private static bsw do(String str, String str2) { bsw bsw = new bsw(); bsw.aAL = str; bsw.value = str2; return bsw; } }
package gr.athena.innovation.fagi.core.function.literal; import gr.athena.innovation.fagi.core.function.IFunction; import gr.athena.innovation.fagi.core.normalizer.AdvancedGenericNormalizer; import gr.athena.innovation.fagi.core.normalizer.BasicGenericNormalizer; import gr.athena.innovation.fagi.core.similarity.WeightedSimilarity; import gr.athena.innovation.fagi.exception.ApplicationException; import gr.athena.innovation.fagi.model.NormalizedLiteral; import gr.athena.innovation.fagi.model.WeightedPairLiteral; import gr.athena.innovation.fagi.specification.Configuration; import java.util.Locale; import org.apache.commons.lang3.StringUtils; import org.apache.jena.rdf.model.Literal; import org.apache.logging.log4j.LogManager; import gr.athena.innovation.fagi.core.function.IFunctionThreeLiteralStringParameters; /** * Class for evaluating similarity between two literals given a threshold. * * @author nkarag */ public class IsSameCustomNormalize implements IFunction, IFunctionThreeLiteralStringParameters { private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger(IsSameCustomNormalize.class); /** * Compares the two literals and returns true if they are same. If the standard equals is not true, it normalizes * the literals using s simple normalization process and re-checks. If all the above fail, the two literals are * normalized further using the AdvancedGenericNormalizer. If the final similarity is above the threshold the method * returns true. * * @param literalA the literal A. * @param literalB the literal B. * @param threshold the similarity threshold. The threshold is not localized and it accepts only dot as decimal. * point. * @return true if the similarity of the literals is above the provided threshold. */ @Override public boolean evaluate(Literal literalA, Literal literalB, String threshold) { if(literalA == null || literalB == null){ return false; } String literalStringA = literalA.getString(); String literalStringB = literalB.getString(); if(StringUtils.isBlank(literalStringA) || StringUtils.isBlank(literalStringB)){ return false; } double thrs = 0; if(!StringUtils.isBlank(threshold)){ try { thrs = Double.parseDouble(threshold); if(thrs < 0 || thrs > 1){ throw new ApplicationException("Threshold out of range [0,1]: " + threshold); } } catch(NumberFormatException ex){ throw new ApplicationException("Cannot parse threshold as a double number: " + threshold); } } if (literalA.equals(literalB)) { return true; } Locale locale = Configuration.getInstance().getLocale(); BasicGenericNormalizer normalizer = new BasicGenericNormalizer(); NormalizedLiteral normA = normalizer.getNormalizedLiteral(literalStringA, literalStringB, locale); NormalizedLiteral normB = normalizer.getNormalizedLiteral(literalStringB, literalStringA, locale); if (normA.getNormalized().equals(normB.getNormalized())) { return true; } AdvancedGenericNormalizer advancedNormalizer = new AdvancedGenericNormalizer(); WeightedPairLiteral weightedPair = advancedNormalizer.getWeightedPair(normA, normB, locale); String simName = Configuration.getInstance().getSimilarity(); double result = WeightedSimilarity.computeDSimilarity(weightedPair, simName); return result > thrs; } @Override public String getName() { String className = this.getClass().getSimpleName().toLowerCase(); return className; } }
import java.util.Scanner; public class TesteFibonacci { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Digite a posiรงรฃo do termo desejado: "); System.out.println("O termo desejado รฉ: " + Fibonacci.calcular(Integer.parseInt(input.next()))); } }
package com.tencent.mm.plugin.webwx.a; import com.tencent.mm.ab.b; import com.tencent.mm.ab.b.a; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.network.k; import com.tencent.mm.network.q; import com.tencent.mm.protocal.c.uu; import com.tencent.mm.protocal.c.uv; import com.tencent.mm.sdk.platformtools.x; public final class d extends l implements k { final b dZf; private e diJ; public d(String str) { a aVar = new a(); uu uuVar = new uu(); uv uvVar = new uv(); aVar.dIG = uuVar; aVar.dIH = uvVar; aVar.uri = "/cgi-bin/micromsg-bin/extdeviceloginconfirmget"; aVar.dIF = 971; aVar.dII = 0; aVar.dIJ = 0; this.dZf = aVar.KT(); uuVar.rya = str; x.d("MicroMsg.NetSceneExtDeviceLoginConfirmGet", "[oneliang][NetSceneExtDeviceLoginConfirmGet]loginUrl:%s", new Object[]{str}); } public final int getType() { return 971; } public final int a(com.tencent.mm.network.e eVar, e eVar2) { this.diJ = eVar2; return a(eVar, this.dZf, this); } public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { x.d("MicroMsg.NetSceneExtDeviceLoginConfirmGet", "onGYNetEnd errType:" + i2 + " errCode:" + i3 + " errMsg:" + str); this.diJ.a(i2, i3, str, this); } }
package com.example.dou.mysale; /** * Created by Dou on 2016/4/27. */ public class Order { private String mProject; //ๆ—ถ้—ดๆš‚ๆ—ถไธ็กฎๅฎš็”จDATE่ฟ˜ๆ˜ฏSTRING๏ผŒๅ…ˆ็”จstring๏ผ› private String mDate; public Order(String first,String second){ mProject = first; mDate = second; } public String getProject() { return mProject; } public String getDate() { return mDate; } public void setProject(String project) { mProject = project; } public void setDate(String date) { mDate = date; } }
package deors.demos.java.pipeline; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.time.Duration; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.openqa.selenium.By; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.ie.InternetExplorerOptions; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.safari.SafariOptions; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HelloServiceIntegrationTest { private static final Logger logger = LoggerFactory.getLogger(HelloServiceIntegrationTest.class); protected static boolean RUN_HTMLUNIT; protected static boolean RUN_IE; protected static boolean RUN_FIREFOX; protected static boolean RUN_CHROME; protected static boolean RUN_EDGE; protected static boolean RUN_SAFARI; protected static String SELENIUM_HUB_URL; protected static String TARGET_SERVER_URL; @BeforeAll public static void initEnvironment() { RUN_HTMLUNIT = getConfigurationProperty("RUN_HTMLUNIT", "test.run.htmlunit", true); logger.info("running the tests in HtmlUnit: " + RUN_HTMLUNIT); RUN_IE = getConfigurationProperty("RUN_IE", "test.run.ie", false); logger.info("running the tests in Internet Explorer: " + RUN_IE); RUN_FIREFOX = getConfigurationProperty("RUN_FIREFOX", "test.run.firefox", false); logger.info("running the tests in Firefox: " + RUN_FIREFOX); RUN_CHROME = getConfigurationProperty("RUN_CHROME", "test.run.chrome", false); logger.info("running the tests in Chrome: " + RUN_CHROME); RUN_EDGE = getConfigurationProperty("RUN_EDGE", "test.run.edge", false); logger.info("running the tests in Edge: " + RUN_EDGE); RUN_SAFARI = getConfigurationProperty("RUN_SAFARI", "test.run.safari", false); logger.info("running the tests in Safari: " + RUN_SAFARI); SELENIUM_HUB_URL = getConfigurationProperty( "SELENIUM_HUB_URL", "test.selenium.hub.url", "http://localhost:4444/wd/hub"); logger.info("using Selenium hub at: " + SELENIUM_HUB_URL); TARGET_SERVER_URL = getConfigurationProperty( "TARGET_SERVER_URL", "test.target.server.url", "http://localhost:8080/"); logger.info("using target server at: " + TARGET_SERVER_URL); } private static String getConfigurationProperty(String envKey, String sysKey, String defValue) { String retValue = defValue; String envValue = System.getenv(envKey); String sysValue = System.getProperty(sysKey); // system property prevails over environment variable if (sysValue != null) { retValue = sysValue; } else if (envValue != null) { retValue = envValue; } return retValue; } private static boolean getConfigurationProperty(String envKey, String sysKey, boolean defValue) { boolean retValue = defValue; String envValue = System.getenv(envKey); String sysValue = System.getProperty(sysKey); // system property prevails over environment variable if (sysValue != null) { retValue = Boolean.parseBoolean(sysValue); } else if (envValue != null) { retValue = Boolean.parseBoolean(envValue); } return retValue; } @Test public void testHtmlUnit() throws MalformedURLException, IOException { Assumptions.assumeTrue(RUN_HTMLUNIT); logger.info("executing test in htmlunit"); WebDriver driver = null; try { driver = new HtmlUnitDriver(true); testAll(driver, TARGET_SERVER_URL); } finally { if (driver != null) { driver.quit(); } } } @Test public void testIE() throws MalformedURLException, IOException { Assumptions.assumeTrue(RUN_IE); logger.info("executing test in internet explorer"); WebDriver driver = null; try { Capabilities browser = new InternetExplorerOptions(); driver = new RemoteWebDriver(new URL(SELENIUM_HUB_URL), browser); testAll(driver, TARGET_SERVER_URL); } finally { if (driver != null) { driver.quit(); } } } @Test public void testFirefox() throws MalformedURLException, IOException { Assumptions.assumeTrue(RUN_FIREFOX); logger.info("executing test in firefox"); WebDriver driver = null; try { Capabilities browser = new FirefoxOptions(); driver = new RemoteWebDriver(new URL(SELENIUM_HUB_URL), browser); testAll(driver, TARGET_SERVER_URL); } finally { if (driver != null) { driver.quit(); } } } @Test public void testChrome() throws MalformedURLException, IOException { Assumptions.assumeTrue(RUN_CHROME); logger.info("executing test in chrome"); WebDriver driver = null; try { Capabilities browser = new ChromeOptions(); driver = new RemoteWebDriver(new URL(SELENIUM_HUB_URL), browser); testAll(driver, TARGET_SERVER_URL); } finally { if (driver != null) { driver.quit(); } } } @Test public void testEdge() throws MalformedURLException, IOException { Assumptions.assumeTrue(RUN_EDGE); logger.info("executing test in edge"); WebDriver driver = null; try { Capabilities browser = new EdgeOptions(); driver = new RemoteWebDriver(new URL(SELENIUM_HUB_URL), browser); testAll(driver, TARGET_SERVER_URL); } finally { if (driver != null) { driver.quit(); } } } @Test public void testSafari() throws MalformedURLException, IOException { Assumptions.assumeTrue(RUN_SAFARI); logger.info("executing test in safari"); WebDriver driver = null; try { Capabilities browser = new SafariOptions(); driver = new RemoteWebDriver(new URL(SELENIUM_HUB_URL), browser); testAll(driver, TARGET_SERVER_URL); } finally { if (driver != null) { driver.quit(); } } } private void testAll(WebDriver driver, String baseUrl) { testHelloGreeting(driver, baseUrl); testHelloWithNameGreeting(driver, baseUrl); } private void testHelloGreeting(WebDriver driver, String baseUrl) { WebElement body = (new WebDriverWait(driver, Duration.ofSeconds(10))).until( d -> { d.get(baseUrl + "hello"); return d.findElement(By.xpath("/html/body")); }); assertEquals("Hello!", body.getText(), "HelloGreeting service should respond with 'Hello!' greeting"); } private void testHelloWithNameGreeting(WebDriver driver, String baseUrl) { WebElement body = (new WebDriverWait(driver, Duration.ofSeconds(10))).until( d -> { d.get(baseUrl + "hello/James"); return d.findElement(By.xpath("/html/body")); }); assertEquals("Hello!, James", body.getText(), "HelloGreeting service should respond with 'Hello!' greeting"); } }
package materialdesign.practice.com.recyclerfragment.Util; public class ModelClass { String name; String title; String descp; String link; String time; public ModelClass() { } public ModelClass(String name, String title, String descp, String link, String time) { this.name = name; this.title = title; this.descp = descp; this.link = link; this.time = time; } public String getName() { return name; } public void setName(String name) { name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescp() { return descp; } public void setDescp(String descp) { this.descp = descp; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } }
// Sun Certified Java Programmer // Chapter 2, P169 package self_test_15; class A { }
package corgi.hub.core.mqtt.event; /** * Created by Terry LIANG on 2016/12/27. */ public class MqttPubRelEvent extends BaseEvent implements MqttEvent { //Optional attribute, available only fo QoS 1 and 2 private int msgId; public int getMsgId() { return msgId; } public void setMsgId(int msgId) { this.msgId = msgId; } }
package eiti.sag.facebookcrawler.accessor.jsoup.extractor; import eiti.sag.facebookcrawler.model.Education; import eiti.sag.facebookcrawler.model.Experience; import eiti.sag.facebookcrawler.model.Work; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.List; import static java.util.stream.Collectors.toList; public class ExperienceExtractor implements DocumentExtractor<Experience> { @Override public Experience extract(Document document) { List<Education> education = extractEducation(document); List<Work> works = extractWorks(document); return new Experience(works, education); } private List<Education> extractEducation(Document page) { String cssQuery = "div[data-pnref='edu'] " + "ul.uiList.fbProfileEditExperiences._4kg._4ks > " + "li.experience"; return extractEducation(page.select(cssQuery)); } private List<Education> extractEducation(Elements elements) { return elements.stream() .map(this::extractEducation) .collect(toList()); } private Education extractEducation(Element element) { Element a = element.select("div[class='_2lzr _50f5 _50f7'] a").get(0); String name = a.text(); String link = a.attr("href"); return new Education(name, extractInfo(element), link); } private String extractInfo(Element e) { Elements elements = e.select("div[class='fsm fwn fcg']"); if(elements.isEmpty()) return null; return elements.get(0).text(); } private List<Work> extractWorks(Document page) { String cssQuery = "div[data-pnref='work'] " + "ul.uiList.fbProfileEditExperiences._4kg._4ks > " + "li.experience"; Elements elements = page.select(cssQuery); return extractWorks(elements); } private List<Work> extractWorks(Elements elements) { return elements.stream() .map(this::extractWork) .collect(toList()); } private Work extractWork(Element element) { Element a = element.select("div[class='_2lzr _50f5 _50f7'] a").get(0); String name = a.text(); String link = a.attr("href"); return new Work(name, extractInfo(element), link); } }
package acs.restController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import acs.boundary.ElementBoundary; import acs.boundary.ElementIdBoundary; import acs.logic.ExtendedElementService; @RestController public class ElementRelatedController { private ExtendedElementService extendedElementService; @Autowired public void setExtendedElementService(ExtendedElementService extendedElementService) { this.extendedElementService = extendedElementService; } @RequestMapping(path = "/acs/elements/{managerDomain}/{managerEmail}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public ElementBoundary createNewElement(@RequestBody ElementBoundary newElementBoundary, @PathVariable("managerDomain") String managerDomain, @PathVariable("managerEmail") String managerEmail) { return this.extendedElementService.create(managerDomain, managerEmail, newElementBoundary); } @RequestMapping(path = "/acs/elements/{managerDomain}/{managerEmail}/{elementDomain}/{elementId}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) public void updateElement(@RequestBody ElementBoundary elementBoundary, @PathVariable("managerDomain") String managerDomain, @PathVariable("managerEmail") String managerEmail, @PathVariable("elementDomain") String elementDomain, @PathVariable("elementId") String elementId) { this.extendedElementService.update(managerDomain, managerEmail,elementDomain, elementId, elementBoundary); } @RequestMapping(path = "/acs/elements/{userDomain}/{userEmail}/{elementDomain}/{elementId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ElementBoundary getElement(@PathVariable("userDomain") String userDomain, @PathVariable("userEmail") String userEmail, @PathVariable("elementDomain") String elementDomain, @PathVariable("elementId") String elementId) { return this.extendedElementService.getSpecificElement(userDomain, userEmail, elementDomain, elementId); } @RequestMapping(path = "/acs/elements/{userDomain}/{userEmail}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ElementBoundary[] getAllElements( @PathVariable("userDomain") String userDomain, @PathVariable("userEmail") String userEmail, @RequestParam(name = "size", required = false, defaultValue = "10") int size, @RequestParam(name = "page", required = false, defaultValue = "0") int page) { return this.extendedElementService.getAll(userDomain, userEmail, size, page).toArray(new ElementBoundary[0]); } @RequestMapping( path = "/acs/elements/{managerDomain}/{managerEmail}/{elementDomain}/{elementId}/children", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) public void bindExistingElementToAnExistingChildElement(@RequestBody ElementIdBoundary elementIdBoundary, @PathVariable("managerDomain") String managerDomain, @PathVariable("managerEmail") String managerEmail, @PathVariable("elementDomain") String elementDomain, @PathVariable("elementId") String elementId) {//TODO path variable this.extendedElementService.bindExistingElementToAnExistingChildElement(managerDomain, managerEmail, elementDomain, elementId, elementIdBoundary); } @RequestMapping( path = "/acs/elements/{userDomain}/{userEmail}/{elementDomain}/{elementId}/children", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ElementBoundary[] getAllChildrenOfAnExistingElement( @PathVariable("userDomain") String userDomain, @PathVariable("userEmail") String userEmail, @PathVariable("elementDomain") String elementDomain, @PathVariable("elementId") String elementId, @RequestParam(name = "size", required = false, defaultValue = "10") int size, @RequestParam(name = "page", required = false, defaultValue = "0") int page) {//TODO need to fix the service! ElementBoundary[] children = this.extendedElementService.getAllChildrenOfAnExistingElement(userDomain, userEmail, elementDomain, elementId, size, page); if(children != null) { return children; }else { return new ElementBoundary[0]; } } @RequestMapping( path = "/acs/elements/{userDomain}/{userEmail}/{elementDomain}/{elementId}/parents", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ElementBoundary[] getAnArrayWithElementParent( @PathVariable("userDomain") String userDomain, @PathVariable("userEmail") String userEmail, @PathVariable("elementDomain") String elementDomain, @PathVariable("elementId") String elementId, @RequestParam(name = "size", required = false, defaultValue = "10") int size, @RequestParam(name = "page", required = false, defaultValue = "0") int page) { ElementBoundary[] parents = this.extendedElementService.getAnArrayWithElementParent(userDomain, userEmail, elementDomain, elementId, size, page); if(parents != null) { return parents; }else { return new ElementBoundary[0]; } } @RequestMapping(path = "/acs/elements/{userDomain}/{userEmail}/search/byName/{name}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ElementBoundary[] SearchElementByName( @PathVariable("userDomain") String userDomain, @PathVariable("userEmail") String userEmail, @PathVariable("name") String name, @RequestParam(name = "size", required = false, defaultValue = "10") int size, @RequestParam(name = "page", required = false, defaultValue = "0") int page) { return this.extendedElementService.getAllByName(userDomain, userEmail, name, size, page); } @RequestMapping(path = "/acs/elements/{userDomain}/{userEmail}/search/byType/{type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ElementBoundary[] SearchElementByType( @PathVariable("userDomain") String userDomain, @PathVariable("userEmail") String userEmail, @PathVariable("type") String type, @RequestParam(name = "size", required = false, defaultValue = "10") int size, @RequestParam(name = "page", required = false, defaultValue = "0") int page) { return this.extendedElementService.getAllByType(userDomain, userEmail, type, size, page); } @RequestMapping(path = "/acs/elements/{userDomain}/{userEmail}/search/near/{lat}/{lng}/{distance}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ElementBoundary[] SearchElementByLocation( @PathVariable("userDomain") String userDomain, @PathVariable("userEmail") String userEmail, @PathVariable("lat") double lat, @PathVariable("lng") double lng, @PathVariable("distance") double distance, @RequestParam(name = "size", required = false, defaultValue = "10") int size, @RequestParam(name = "page", required = false, defaultValue = "0") int page) { return this.extendedElementService.getAllByLocation(userDomain, userEmail, lat, lng, distance, size, page); } }
/* * Davis Odom * 9/1/15 * Tests the various account classes */ public class Program { public static void main(String[] args){ Account a1 = new Account(); SavingsAccount a2 = new SavingsAccount(); CheckingAccount a3 = new CheckingAccount(); //describe the accounts System.out.println(a1); System.out.println(a2); System.out.println(a3); } }
/** * NAME: Darren Yeung * PID: A15943292 * EMAIL: dyeung@ucsd.edu * This file is MyDeque.java. It contains the single class MyDeque . */ /** * This is the class MyDeque which is a generic class. It implements the * DequeInterface. It has four instance varaibles. One is the back end * data structure which is the array, one size, and front and rear is used * to keep track of the index of the front and the rear. * @param <E> */ public class MyDeque<E> implements DequeInterface<E>{ Object[] data; int size; int rear; int front; /** * This is the constructor for MyDeque. It takes in the initialcapacity * and initiates data to that number. * @param initialCapacity The initialcapacity the user wants their Deque to be. */ public MyDeque(int initialCapacity){ if(initialCapacity < 0){ throw new IllegalArgumentException(); } this.data = new Object[initialCapacity]; this.size = 0; this.rear = 0; this.front = 0; } /** * This method returns the size of the Deque (not the capacity, the * amount of elements) * @return the size of the Deque */ public int size(){ return this.size; } /** * This method doubles the capacity of the deque, makes front start from 0, * and rear start from size -1. If capacity was at 0, we make the capacity 10 * and move on with our lives. */ public void expandCapacity(){ if(this.data.length == 0){ this.data = new Object[10]; }else{ Object[] newArray = new Object[this.data.length * 2]; int newArrayCurrent = 0; //keeps track of newarray index if(this.front > this.rear){ //goes from front to end for(int i = this.front; i < this.data.length; i++){ newArray[newArrayCurrent] = this.data[i]; newArrayCurrent++; } //then to 0 to rear for(int j = 0; j <= this.rear; j++){ newArray[newArrayCurrent] = this.data[j]; newArrayCurrent++; } this.data = newArray; this.front = 0; this.rear = this.size -1; }else if(this.front < this.rear){ //goes from front to rear for(int i = this.front; i <= this.rear; i++){ newArray[newArrayCurrent] = this.data[i]; newArrayCurrent++; } this.front = 0; this.rear = this.size -1; this.data = newArray; // only way to fall into this else is if size is 0 // if size is 1 }else{ //makes data double its length only if(this.size == 0){ this.rear = 0; this.front = 0; this.data = newArray; }else{ // if size is 1, then just trasfer one element newArray[0] = this.data[this.front]; this.rear = 0; this.front = 0; this.data = newArray; } } } } /** * This method adds an element the front of the deque * @param the element the user wants to add to the front */ public void addFirst(E element){ if(element == null){ throw new NullPointerException(); } if(this.size == this.data.length){ this.expandCapacity(); } if(this.size == 0){ this.data[0] = element; }else if(this.front == 0){ this.data[this.data.length -1] = element; this.front = this.data.length -1; }else{ this.data[this.front - 1] = element; this.front --; } this.size ++; } /** * This method adds an element to the back of the deque * @param element the user wants to add to the back */ public void addLast(E element){ if(element == null){ throw new NullPointerException(); } if(this.size == this.data.length){ this.expandCapacity(); } if(this.size == 0){ this.data[0] = element; }else if(this.rear == this.data.length -1){ this.data[0] = element; this.rear = 0; }else{ this.data[this.rear + 1] = element; this.rear++; } this.size++; } /** * This element removes the element in the front of the * deque * @return element that was removed */ public E removeFirst(){ if(this.size == 0){ return null; } E stored = (E)this.data[this.front]; if(this.front == this.data.length -1){ this.data[front] = null; this.size--; this.front = 0; }else{ this.data[front] = null; this.size--; if(this.size == 0){ return stored; }else{ this.front++; } } if(this.size == 0){ this.rear = 0; } return stored; } /** * This method removes an element from behind. * @return element that was removed */ public E removeLast(){ if(this.size == 0){ return null; } E stored = (E)this.data[this.rear]; if(this.rear == 0){ this.data[this.rear] = null; this.size--; if(this.size == 0){ return stored; }else{ this.rear = this.data.length -1; } }else{ this.data[this.rear] = null; this.rear --; this.size--; } if(this.size == 0){ this.front = 0; } return stored; } /** * This method returns the first element without * making changes to the deque * @return element in the front of the deque */ public E peekFirst(){ if(this.size == 0){ return null; }else{ return (E)this.data[this.front]; } } /** * This method returns the last element without * making changes to the deque * @return element in the back of the deque */ public E peekLast(){ if(this.size == 0){ return null; }else{ return (E)this.data[this.rear]; } } }
package com.globomart.catalog.service; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.stereotype.Component; import com.globomart.catalog.defs.SearchType; import com.globomart.catalog.exceptions.GloboMartException; import com.globomart.catalog.models.Product; /** * BusinessLayer for CatalogService * * @author Suresh Bojjam * */ @Component public interface CatalogService { public List<Product> listProducts(); public Product addProduct(Product product); public void removeProduct(Long productId); public List<Product> searchProducsts(String queryString,SearchType searchType) throws GloboMartException; public Page<Product> searchProducts(String queryString,SearchType searchType,int page_no,int page_size); }
package cn.uway.cache; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.slf4j.Logger; import cn.uway.config.LogMgr; import cn.uway.config.SystemConfig; import cn.uway.file.FileGenerator; import cn.uway.util.FileUtil; import cn.uway.util.StringUtil; import cn.uway.util.TimeUtil; /** * ๆ–‡ไปถ็ผ“ๅญ˜ๆœ‰ไธคไธช๏ผšไธ€ๆ˜ฏokๆ–‡ไปถ็›ฎๅฝ•๏ผˆๅฝ“็›ฎๅฝ•ๅšๅฎŒๅŽ๏ผŒๅŠ ไธŠ.ok็š„ๅŽ็ผ€๏ผŒๆ ‡่ฎฐไฝœ็”จ)๏ผŒไบŒๆ˜ฏlogๆ–‡ไปถ * * @author yuy @ 29 May, 2014 */ public class FileCache extends AbstractCache { private static final Logger LOGGER = LogMgr.getInstance().getSystemLogger(); public static String path = "./cache"; // dataTime็š„ๆ—ฅๅฟ—๏ผŒๆญฃๅœจ่ฎฐๅฝ•ๆ‰€ๆœ‰ๆ–‡ไปถ public static String tmpSmallExdName = ".log.tmp"; // dataTime็š„ๆ—ฅๅฟ—๏ผŒๅทฒ่ฎฐๅฝ•ๅฎŒๆ‰€ๆœ‰ๆ–‡ไปถ public static String smallExdName = ".log"; // ๆฏๅคฉ็š„ๆ—ฅๅฟ—็›ฎๅฝ•๏ผŒ่กจ็คบๅทฒๅฎŒๆˆ public static String exdName = ".ok"; // ๆฏๅคฉ็š„ๆ—ฅๅฟ—่ฎฐๅฝ•๏ผŒ่กจ็คบๆญฃๅœจ็”Ÿๆˆ public static String tmpExdName = ".tmp"; // ๆฏๆฌกๅŠ ่ฝฝๅ‡ ไธชๆ—ถ้—ด็‚น public static int times = 5; public FileGenerator fileWriter; public List<String> fileList; public Date startTime; public Date endTime; public static int filePeriod = Integer.parseInt(SystemConfig.getInstance().getFileGeneratePeriod()); public FileCache(Date startTime, Date endTime) { this.startTime = startTime; this.endTime = endTime; } public FileCache(String dateString) { fileWriter = new FileGenerator(path + "/" + dateString.substring(0, 8) + tmpExdName, dateString + tmpSmallExdName); } // ๅขžๅŠ ไธ€ๆกๆ–‡ไปถ่ฎฐๅฝ• public void add(String filename) { fileWriter.write((filename + "\n").getBytes()); } public void addByBatch(List<String> list) { if (list == null || list.size() == 0) return; for (String str : list) { fileWriter.write((str + "\n").getBytes()); } } // ่Žทๅ–ๆœ€่ฟ‘็š„dataTime(ๆ—ถ้—ดไป“ไฟƒ๏ผŒๆœ‰็‚นไนฑ๏ผŒไปฅๅŽๆ…ขๆ…ขไผ˜ๅŒ–ๅง) public synchronized List<Date> handleDataTime(List<String> fileList, Date dateTime_) throws Exception { if (fileList == null || fileList.size() == 0) return null; List<Date> dateTimeList = new ArrayList<Date>(); if (dateTime_ != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(dateTime_); dateTimeList.add(calendar.getTime()); for (int n = 0; n < times; n++) { calendar.add(Calendar.MINUTE, filePeriod); // ๅฆ‚ๆžœ่ถ…่ฟ‡ๅฝ“ๅ‰ๆ—ถ้—ด๏ผŒๆ‰“ไฝ if (calendar.getTime().getTime() >= new Date().getTime()) break; dateTimeList.add(calendar.getTime()); } return dateTimeList; } // ๅ…ˆๆŽ’ๅบ ๅขžๅบ sortDirs(); // ๅŽๅŽป้ๅކ for (String file : fileList) { // ๆฃ€ๆŸฅไธ‹ๆ˜ฏๅฆ่ถ…่ฟ‡7ๅคฉ๏ผŒๆ˜ฏ๏ผŒๅˆ ้™คใ€‚่ถ็€่ฟ™ไธชๆœบไผšๆŠŠๆดปๅนฒไบ† if (file.endsWith(exdName)) { String name = file.substring(0, file.indexOf(".")); Date time = TimeUtil.getyyyyMMddHHmmssDate(name); int days = (int) (new Date().getTime() - time.getTime()) / 1000 / 60 / 60 / 24; if (days >= 7) new File(file).delete(); } // ๅˆคๆ–ญๆ˜ฏๅฆๅญ˜ๅœจtmpๆ–‡ไปถๅคน if (file.endsWith(tmpExdName)) { String patternTime = StringUtil.getPattern(file, "\\d{8}"); Date currentDataTime = TimeUtil.getyyyyMMddDate(patternTime); // ไธŽไปปๅŠกๅผ€ๅง‹ๆ—ถ้—ดๆฏ”่พƒ String dataStr = TimeUtil.getDateString_yyyyMMdd(startTime); if (currentDataTime.getTime() < TimeUtil.getyyyyMMddDate(dataStr).getTime()) { continue; } if ((endTime != null && currentDataTime.getTime() > endTime.getTime())) { continue; } // String dateStr = file.substring(0, file.lastIndexOf(".")); List<String> smalllist = FileUtil.getFileNames(file, "*" + smallExdName + "*"); if (smalllist.size() == 0) continue; // ๅ€’ๅบ sortSmallFiles(smalllist); for (String f : smalllist) { // ๅˆคๆ–ญsmallๆ–‡ไปถไธญๆ˜ฏๅฆๅญ˜ๅœจtmpๆ–‡ไปถ if (f.endsWith(tmpSmallExdName)) { String name = f.substring(FileUtil.getLastSeparatorIndex(f) + 1); name = name.substring(0, name.indexOf(".")); dateTimeList.add(TimeUtil.getyyyyMMddHHmmssDate(name)); // ๅŠ ่ฝฝๅˆฐๅ†…ๅญ˜ไธญ BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(f)); String line = null; while ((line = reader.readLine()) != null) { MemoryCache.hasDoneFileSet.add(line); } } catch (Exception e) { LOGGER.debug("่ฏปๅ–ๆ–‡ไปถ" + f + "ๅ‡บ้”™", e); } finally { reader.close(); } } } int c = 24 * 60 / filePeriod; String lastSmallFile = smalllist.get(smalllist.size() - 1); // ๆ—ขๅญ˜ๅœจ.tmp๏ผŒๆœ€ๅŽไธ€ไธชsmallๆ–‡ไปถไนŸๆ˜ฏ.log๏ผŒadd่ฏฅๆ–‡ไปถ็š„ไธ‹ไธชๆ—ถ้—ด็‚น if (dateTimeList.size() > 0 && lastSmallFile.endsWith(smallExdName)) { String name = lastSmallFile.substring(FileUtil.getLastSeparatorIndex(lastSmallFile) + 1); name = name.substring(0, name.indexOf(".")); Date date = TimeUtil.getyyyyMMddHHmmssDate(name); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int day = calendar.get(Calendar.DAY_OF_MONTH); calendar.add(Calendar.MINUTE, filePeriod); // ๅŒไธ€ๅคฉ if (calendar.get(Calendar.DAY_OF_MONTH) != day) { continue; } // ๅฆ‚ๆžœ่ถ…่ฟ‡ๅฝ“ๅ‰ๆ—ถ้—ด๏ผŒๆ‰“ไฝ if (calendar.getTime().getTime() >= new Date().getTime()) continue; dateTimeList.add(calendar.getTime()); } // ไธๅญ˜ๅœจ.tmp๏ผŒไฝ†ๆ˜ฏ่ฟ˜ๆฒกๅšๅฎŒ๏ผŒๆ‰พๅˆฐๆœ€่ฟ‘ไธ€ไธชๆ–‡ไปถ็š„ๆ—ถ้—ด๏ผŒๅŠ filePeriod if (dateTimeList.size() == 0 && smalllist.size() < c) { String lastFile = smalllist.get(smalllist.size() - 1); String name = lastFile.substring(FileUtil.getLastSeparatorIndex(lastFile) + 1); name = name.substring(0, name.indexOf(".")); Date dateTime = TimeUtil.getyyyyMMddHHmmssDate(name); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateTime); int day = calendar.get(Calendar.DAY_OF_MONTH); // ๅŠ filePeriod calendar.add(Calendar.MINUTE, filePeriod); // ๅŒไธ€ๅคฉ if (calendar.get(Calendar.DAY_OF_MONTH) != day) { continue; } // ๅฆ‚ๆžœ่ถ…่ฟ‡ๅฝ“ๅ‰ๆ—ถ้—ด๏ผŒๆ‰“ไฝ if (calendar.getTime().getTime() >= new Date().getTime()) continue; dateTimeList.add(calendar.getTime()); for (int n = 0; n < times; n++) { calendar.add(Calendar.MINUTE, filePeriod); if (calendar.get(Calendar.DAY_OF_MONTH) != day) { break; } // ๅฆ‚ๆžœ่ถ…่ฟ‡ๅฝ“ๅ‰ๆ—ถ้—ด๏ผŒๆ‰“ไฝ if (calendar.getTime().getTime() >= new Date().getTime()) break; dateTimeList.add(calendar.getTime()); } } // ๅ‘็Žฐ้ƒฝๆ˜ฏlog็š„๏ผŒไธ”ๆ•ฐ้‡ไธบ24*60/filePeriod๏ผŒๅˆ™่กจๆ˜ŽๅšๅฎŒไบ†๏ผŒๆŠŠ็ˆถ็›ฎๅฝ•ๆ”นไธบokใ€‚่ถ็€่ฟ™ไธชๆœบไผšๆŠŠๆดปๅนฒไบ† if (dateTimeList.size() == 0 && smalllist.size() == c) { File parentFile = new File(path + "/" + file); parentFile.renameTo(new File(path + "/" + file.replace(tmpExdName, exdName))); } // ๅฆ‚ๆžœๅทฒ็ปๆœ‰ไบ†dataTime๏ผŒๅ…ˆ้€€ๅ‡บ๏ผŒๅšๅฎŒๅ†่ฏด if (dateTimeList.size() > 0) { break; } } } // ๅ…จ้ƒจokๆ–‡ไปถๅคน๏ผŒๆ‰พๅˆฐๆœ€่ฟ‘ไธ€ไธช if (dateTimeList.size() == 0) { String lastFile = fileList.get(fileList.size() - 1); String name = lastFile.substring(FileUtil.getLastSeparatorIndex(lastFile) + 1); name = name.substring(0, name.indexOf(".")); Date dateTime = TimeUtil.getyyyyMMddDate(name); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateTime); List<String> smalllist = FileUtil.getFileNames(lastFile, "*" + smallExdName + "*"); // ไธๆ˜ฏ็ฉบ็›ฎๅฝ• ๅŠ 1ๅคฉ if (smalllist.size() > 0) { calendar.add(Calendar.DAY_OF_MONTH, 1); } while (calendar.getTime().getTime() < startTime.getTime()) { calendar.add(Calendar.MINUTE, filePeriod); } if (calendar.getTime().getTime() >= new Date().getTime()) return dateTimeList; dateTimeList.add(calendar.getTime()); for (int n = 0; n < times; n++) { calendar.add(Calendar.MINUTE, filePeriod); // ๅฆ‚ๆžœ่ถ…่ฟ‡ๅฝ“ๅ‰ๆ—ถ้—ด๏ผŒๆ‰“ไฝ if (calendar.getTime().getTime() >= new Date().getTime()) break; dateTimeList.add(calendar.getTime()); } } return dateTimeList; } // ็›ฎๅฝ•ๆŽ’ๅบ ๅขžๅบ public void sortDirs() throws ParseException { int n = 0; while (true) { int count = 0; for (int m = n + 1; m < fileList.size(); n++, m++) { String file = fileList.get(n); String name = file.substring(FileUtil.getLastSeparatorIndex(file) + 1); name = name.substring(0, name.indexOf(".")); Date date = TimeUtil.getyyyyMMddDate(name); String file_ = fileList.get(m); String name_ = file_.substring(FileUtil.getLastSeparatorIndex(file_) + 1); name_ = name_.substring(0, name_.indexOf(".")); Date date_ = TimeUtil.getyyyyMMddDate(name_); if (date.after(date_)) { fileList.set(n, file_); fileList.set(m, file); count++; } } if (count == 0) break; n = 0; } } /** * logๆ–‡ไปถๆŽ’ๅบ ๅขžๅบ * * @param fileList * @throws ParseException */ public static void sortSmallFiles(List<String> fileList) throws ParseException { int n = 0; while (true) { int count = 0; for (int m = n + 1; m < fileList.size(); n++, m++) { String file = fileList.get(n); String name = file.substring(FileUtil.getLastSeparatorIndex(file) + 1); name = name.substring(0, name.indexOf(".")); Date date = TimeUtil.getyyyyMMddHHmmssDate(name); String file_ = fileList.get(m); String name_ = file_.substring(FileUtil.getLastSeparatorIndex(file_) + 1); name_ = name_.substring(0, name_.indexOf(".")); Date date_ = TimeUtil.getyyyyMMddHHmmssDate(name_); if (date.after(date_)) { fileList.set(n, file_); fileList.set(m, file); count++; } } if (count == 0) break; n = 0; } LOGGER.debug("ๆŽ’ๅบๅŽ็š„ๆ—ฅๅฟ—ๆ–‡ไปถ"); for (String str : fileList) { LOGGER.debug("ๆ—ฅๅฟ—ๆ–‡ไปถ๏ผš" + str); } } // ไธ‹่ฝฝๅŽไฟฎๆ”นๅŽ็ผ€ๅ public void reName() { fileWriter.reFileName(tmpSmallExdName, smallExdName); } public List<String> listFile() { fileList = new ArrayList<String>(); fileList.addAll(ListFile(tmpExdName)); fileList.addAll(ListFile(exdName)); return fileList; } public static List<String> ListFile(String filter) { return FileUtil.getDirNames(path, filter); } public void close() { try { fileWriter.close(); } catch (IOException e) { } } /** * @param args */ public static void main(String[] args) { File dir = new File("/home/yuy/my/cache"); // File[] list = dir.listFiles(); // for (File file : list) { // System.out.println(file.getName()); // } List<String> lis = FileUtil.getDirNames(dir.getAbsolutePath(), "*.tmp"); for (String file : lis) { System.out.println(file); } } }
package com.alonemusk.medicalapp.ui.Search; import java.util.List; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; @Dao public interface SearchDao { @Insert void insert(SearchMedicine searchMedicine); @Update void update(SearchMedicine searchMedicine); @Delete void delete(SearchMedicine searchMedicine); @Query("DELETE FROM medicine_table") void deleteAll(); @Query("SELECT * FROM medicine_table") LiveData<List<SearchMedicine>> getAllNote(); @Query("SELECT * FROM medicine_table WHERE name LIKE :name") List<SearchMedicine> search(String name); }
/** * This is a straightforward implementation of the cache L2, contains the classes * and the utilities needed to provide the cache service. */ package l2_servers;
package br.com.zup.zupacademy.daniel.mercadolivre.produto; import br.com.zup.zupacademy.daniel.mercadolivre.categoria.CategoriaResponse; import br.com.zup.zupacademy.daniel.mercadolivre.produto.caracteristicaProduto.CaracteristicaProdutoResponse; import br.com.zup.zupacademy.daniel.mercadolivre.produto.opiniaoProduto.OpiniaoProdutoRepository; import br.com.zup.zupacademy.daniel.mercadolivre.produto.opiniaoProduto.OpiniaoProdutoResponse; import br.com.zup.zupacademy.daniel.mercadolivre.produto.opiniaoProduto.OpinioesProduto; import br.com.zup.zupacademy.daniel.mercadolivre.produto.perguntaProduto.PerguntaProdutoRepository; import br.com.zup.zupacademy.daniel.mercadolivre.produto.perguntaProduto.PerguntaProdutoResponse; import java.math.BigDecimal; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class ProdutoResponse { private List<String> linksFotos; private String nome; private BigDecimal valor; private CategoriaResponse categoria; private Integer quantidade; private Set<CaracteristicaProdutoResponse> caracteristicas; private String descricao; private Double mediaNotas; private Integer numeroDeNotas; private Set<OpiniaoProdutoResponse> opinioes; private Set<PerguntaProdutoResponse> perguntas; public ProdutoResponse(Produto produto, OpiniaoProdutoRepository opiniaoProdutoRepository, PerguntaProdutoRepository perguntaProdutoRepository) { OpinioesProduto opinioesProduto = new OpinioesProduto(opiniaoProdutoRepository.findByProduto(produto)); this.linksFotos = produto.linksFotos(); this.nome = produto.getNome(); this.valor = produto.getValor(); this.categoria = new CategoriaResponse(produto.getCategoria()); this.quantidade = produto.getQuantidade(); this.caracteristicas = produto.getCaracteristicas().stream().map(CaracteristicaProdutoResponse::new).collect(Collectors.toSet()); this.descricao = produto.getDescricao(); this.mediaNotas = opinioesProduto.media(); this.numeroDeNotas = opinioesProduto.getNumeroDeNotas(); this.opinioes = opinioesProduto.getOpinioesResponse(); this.perguntas = perguntaProdutoRepository.findByProduto(produto).stream().map(PerguntaProdutoResponse::new).collect(Collectors.toSet()); } public List<String> getLinksFotos() { return linksFotos; } public String getNome() { return nome; } public BigDecimal getValor() { return valor; } public Set<CaracteristicaProdutoResponse> getCaracteristicas() { return caracteristicas; } public String getDescricao() { return descricao; } public Double getMediaNotas() { return mediaNotas; } public Integer getNumeroDeNotas() { return numeroDeNotas; } public Set<OpiniaoProdutoResponse> getOpinioes() { return opinioes; } public Set<PerguntaProdutoResponse> getPerguntas() { return perguntas; } public CategoriaResponse getCategoria() { return categoria; } public Integer getQuantidade() { return quantidade; } }
package com.tencent.mm.plugin.wallet_core.b; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.wallet_core.ui.WalletBaseUI; class a$1 implements OnClickListener { final /* synthetic */ WalletBaseUI peV; final /* synthetic */ a piU; a$1(a aVar, WalletBaseUI walletBaseUI) { this.piU = aVar; this.peV = walletBaseUI; } public final void onClick(DialogInterface dialogInterface, int i) { this.piU.b(this.peV, this.piU.jfZ); if (this.peV.bbR()) { this.peV.finish(); } WalletBaseUI.cDI(); } }
package com.simple.base.components.user.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.simple.base.components.user.entity.UserClientInfo; public interface UserClientInfoRepository extends JpaRepository<UserClientInfo, Long> { }
package edu.nju.web.controller.api; import edu.nju.logic.service.QuestionService; import edu.nju.logic.service.RelationService; import edu.nju.logic.vo.QuestionApiVO; import edu.nju.web.config.HostConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; /** * ๅฏนๅค–ๆไพ›็š„api */ @Controller @RequestMapping("/api") public class ApiController { @Autowired private RelationService relationService; @Autowired private QuestionService questionService; @Autowired private HostConfig hostConfig; @RequestMapping(value = "/relation/ppt/{id}", method = RequestMethod.GET) @ResponseBody Map<String, Object> getPPTRelation(@PathVariable long id){ Map<String,Object> map = new HashMap<>(); map.put("pptId",id); map.put("wikiIds", relationService.getRelatedWikiByDoc(id)); map.put("questionIds", relationService.getRelatedQuestionByDoc(id)); return map; } @RequestMapping(value = "/relation/wiki/{id}",method = RequestMethod.GET) @ResponseBody Map<String, Object> getWikiRelation(@PathVariable long id){ Map<String, Object> map = new HashMap<>(); map.put("wikiId", id); map.put("pptIds", relationService.getRelatedDocByWiki(id)); map.put("questionIds", relationService.getRelatedQuestionByWiki(id)); return map; } @RequestMapping(value = "/ask",method = RequestMethod.GET) @ResponseBody String askQuestionByWiki(@RequestParam("wikiId")String wikiId) { return hostConfig.getIpAddress()+":"+hostConfig.getPort()+"/ask?wikiId="+wikiId; } @RequestMapping(value = "/question",method = RequestMethod.GET) @ResponseBody QuestionApiVO getQuestionById(@RequestParam("id")String id){ return questionService.getApiQuestion(Long.valueOf(id)); } }
package prj.betfair.api.accounts.datatypes; import prj.betfair.api.accounts.datatypes.ApplicationSubscription; import java.util.Date; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /*** Application subscription details */ @JsonDeserialize(builder=ApplicationSubscription.Builder.class) public class ApplicationSubscription { private final String clientReference; private final Date expiredDateTime; private final Date expiryDateTime; private final Date cancellationDateTime; private final Date createdDateTime; private final String subscriptionToken; private final String subscriptionStatus; private final Date activationDateTime; private final String vendorClientId; public ApplicationSubscription(Builder builder){ this.clientReference = builder.clientReference; this.expiredDateTime = builder.expiredDateTime; this.expiryDateTime = builder.expiryDateTime; this.cancellationDateTime = builder.cancellationDateTime; this.createdDateTime = builder.createdDateTime; this.subscriptionToken = builder.subscriptionToken; this.subscriptionStatus = builder.subscriptionStatus; this.activationDateTime = builder.activationDateTime; this.vendorClientId = builder.vendorClientId; } /** * @return subscriptionToken Application key identifier */ public String getSubscriptionToken() { return this.subscriptionToken; } /** * @return expiryDateTime Subscription Expiry date */ public Date getExpiryDateTime() { return this.expiryDateTime; } /** * @return expiredDateTime Subscription Expired date */ public Date getExpiredDateTime() { return this.expiredDateTime; } /** * @return createdDateTime Subscription Create date */ public Date getCreatedDateTime() { return this.createdDateTime; } /** * @return activationDateTime Subscription Activation date */ public Date getActivationDateTime() { return this.activationDateTime; } /** * @return cancellationDateTime Subscription Cancelled date */ public Date getCancellationDateTime() { return this.cancellationDateTime; } /** * @return subscriptionStatus Subscription status */ public String getSubscriptionStatus() { return this.subscriptionStatus; } /** * @return clientReference Client reference */ public String getClientReference() { return this.clientReference; } /** * @return vendorClientId Vendor client Id */ public String getVendorClientId() { return this.vendorClientId; } public static class Builder { private String clientReference; private Date expiredDateTime; private Date expiryDateTime; private Date cancellationDateTime; private Date createdDateTime; private String subscriptionToken; private String subscriptionStatus; private Date activationDateTime; private String vendorClientId; /** * @param subscriptionToken : Application key identifier */ public Builder(@JsonProperty("subscriptionToken") String subscriptionToken) { this.subscriptionToken = subscriptionToken; } public Builder withClientReference(String clientReference) { this.clientReference = clientReference; return this; } public Builder withExpiredDateTime(Date expiredDateTime) { this.expiredDateTime = expiredDateTime; return this; } public Builder withExpiryDateTime(Date expiryDateTime) { this.expiryDateTime = expiryDateTime; return this; } public Builder withCancellationDateTime(Date cancellationDateTime) { this.cancellationDateTime = cancellationDateTime; return this; } public Builder withCreatedDateTime(Date createdDateTime) { this.createdDateTime = createdDateTime; return this; } public Builder withSubscriptionToken(String subscriptionToken) { this.subscriptionToken = subscriptionToken; return this; } public Builder withSubscriptionStatus(String subscriptionStatus) { this.subscriptionStatus = subscriptionStatus; return this; } public Builder withActivationDateTime(Date activationDateTime) { this.activationDateTime = activationDateTime; return this; } public Builder setVendorClientId(String vendorClientId) { this.vendorClientId = vendorClientId; return this; } public ApplicationSubscription build(){ return new ApplicationSubscription(this); } } }
package com.joshua.addressbook.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.joshua.addressbook.entity.PriceByQuantity; @Repository public interface PricesByQuantityRepository extends JpaRepository<PriceByQuantity, Integer> { }
package web; import dao.SaleDAOInterface; import dao.SaleDatabase; import domain.Sale; import org.jooby.Jooby; import org.jooby.Status; public class SaleModule extends Jooby { SaleDAOInterface saleDao = new SaleDatabase(); public SaleModule(SaleDAOInterface saleDao) { post("/api/sales", (req, rsp) -> { Sale sale = req.body().to(Sale.class); System.out.println(sale); saleDao.save(sale); rsp.status(Status.CREATED); }); } }
package ca.antonious.habittracker.views; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import ca.antonious.habittracker.R; /** * Created by George on 2016-09-03. */ public class EditTextFragment extends DialogFragment { private EditText editText; private OnConfirmListener onConfirmListener; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { super.onCreateDialog(savedInstanceState); View view = LayoutInflater.from(getActivity()).inflate(R.layout.set_text_dialog, null); editText = (EditText) view.findViewById(R.id.text_input); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity()) .setTitle("Name") .setView(view) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setPositiveButton("Set", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dispatchOnConfirm(editText.getText().toString()); } }); return alertDialogBuilder.show(); } public OnConfirmListener getOnConfirmListener() { return onConfirmListener; } public void setOnConfirmListener(OnConfirmListener onConfirmListener) { this.onConfirmListener = onConfirmListener; } public void dispatchOnConfirm(String text) { if (getOnConfirmListener() != null) { getOnConfirmListener().onConfirm(text); } } public interface OnConfirmListener { void onConfirm(String text); } }
/* * Copyright 2014 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.dsl.jms; import java.util.concurrent.Executor; import javax.jms.ConnectionFactory; import org.springframework.beans.DirectFieldAccessor; import org.springframework.integration.jms.AbstractJmsChannel; import org.springframework.integration.jms.config.JmsChannelFactoryBean; import org.springframework.jms.listener.AbstractMessageListenerContainer; import org.springframework.jms.listener.DefaultMessageListenerContainer; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.util.ErrorHandler; /** * @author Artem Bilan */ public class JmsMessageChannelSpec<S extends JmsMessageChannelSpec<S>> extends JmsPollableMessageChannelSpec<S> { private Integer cacheLevel; JmsMessageChannelSpec(ConnectionFactory connectionFactory) { super(new JmsChannelFactoryBean(true), connectionFactory); } public S containerType(Class<? extends AbstractMessageListenerContainer> containerType) { this.jmsChannelFactoryBean.setContainerType(containerType); return _this(); } public S concurrentConsumers(int concurrentConsumers) { this.jmsChannelFactoryBean.setConcurrentConsumers(concurrentConsumers); return _this(); } public S maxSubscribers(int maxSubscribers) { this.jmsChannelFactoryBean.setMaxSubscribers(maxSubscribers); return _this(); } public S autoStartup(boolean autoStartup) { this.jmsChannelFactoryBean.setAutoStartup(autoStartup); return _this(); } public S phase(int phase) { this.jmsChannelFactoryBean.setPhase(phase); return _this(); } public S errorHandler(ErrorHandler errorHandler) { this.jmsChannelFactoryBean.setErrorHandler(errorHandler); return _this(); } public S exposeListenerSession(boolean exposeListenerSession) { this.jmsChannelFactoryBean.setExposeListenerSession(exposeListenerSession); return _this(); } public S acceptMessagesWhileStopping(boolean acceptMessagesWhileStopping) { this.jmsChannelFactoryBean.setAcceptMessagesWhileStopping(acceptMessagesWhileStopping); return _this(); } public S idleTaskExecutionLimit(int idleTaskExecutionLimit) { this.jmsChannelFactoryBean.setIdleTaskExecutionLimit(idleTaskExecutionLimit); return _this(); } public S maxMessagesPerTask(int maxMessagesPerTask) { this.jmsChannelFactoryBean.setMaxMessagesPerTask(maxMessagesPerTask); return _this(); } public S recoveryInterval(long recoveryInterval) { this.jmsChannelFactoryBean.setRecoveryInterval(recoveryInterval); return _this(); } public S taskExecutor(Executor taskExecutor) { this.jmsChannelFactoryBean.setTaskExecutor(taskExecutor); return _this(); } public S transactionManager(PlatformTransactionManager transactionManager) { this.jmsChannelFactoryBean.setTransactionManager(transactionManager); return _this(); } public S transactionName(String transactionName) { this.jmsChannelFactoryBean.setTransactionName(transactionName); return _this(); } public S transactionTimeout(int transactionTimeout) { this.jmsChannelFactoryBean.setTransactionTimeout(transactionTimeout); return _this(); } /** * @param cacheLevel the value for {@code DefaultMessageListenerContainer.cacheLevel} * @return the current {@link org.springframework.integration.dsl.channel.MessageChannelSpec} * @see org.springframework.jms.listener.DefaultMessageListenerContainer#CACHE_AUTO etc. */ public S cacheLevel(Integer cacheLevel) { this.cacheLevel = cacheLevel; return _this(); } @Override protected AbstractJmsChannel doGet() { AbstractJmsChannel jmsChannel = super.doGet(); if (this.cacheLevel != null) { DirectFieldAccessor dfa = new DirectFieldAccessor(jmsChannel); Object container = dfa.getPropertyValue("container"); if (container instanceof DefaultMessageListenerContainer) { ((DefaultMessageListenerContainer) container).setCacheLevel(this.cacheLevel); } } return jmsChannel; } }
package carage.engine; import org.lwjgl.util.vector.Matrix4f; import carage.engine.utils.ShaderProgram; import carage.engine.utils.Texture; public interface Renderable { public VertexArrayObject getVAO(); public int getVAOId(); public boolean hasIBO(); public IndexBufferObject getIBO(); public int getIBOId(); public boolean hasTexture(); public Texture getTexture(); public int getTextureId(); public Matrix4f getTransformationMatrix(); public void applyTransformationsToMatrix(Matrix4f modelMatrix); public void setMaterial(Material material); public boolean hasMaterial(); public Material getMaterial(); public ShaderProgram getShader(); }
package design.mode.decorator.pancake; public class SausagePancakeDecorator extends Pancake { private Pancake pancake; public SausagePancakeDecorator(Pancake pancake) { this.pancake = pancake; } @Override public String getDesc() { return pancake.getDesc() + "ๅŠ 1ๆ น้ฆ™่‚ "; } @Override public double getPrice() { return pancake.getPrice() + 4; } }
package voetbalvereniging; import java.util.ArrayList; public class Maffia { ArrayList<Omkoopbaar> omkoopbaren = new ArrayList<>(); void recruteren(Omkoopbaar okb) { omkoopbaren.add(okb); try { okb.omkopen(3, "geef geld"); }catch(Exception e) { System.out.println("Doodschieten"); } } }
package Aula11; public class PratoDieta extends Prato{ private double maxProteinas; public PratoDieta (String aNome, double aMaxProteinas) { super (aNome); this.maxProteinas = aMaxProteinas; } @Override public double getMaxProteinas() { return maxProteinas; } @Override public boolean equals(Object obj) { return (super.equals(obj) && this.maxProteinas== ((PratoDieta) obj).getMaxProteinas()); } @Override public String toString() { return "Dieta (" + this.maxProteinas + "Calorias) " + super.toString(); } }
package collection; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class AddressBookMain { public void add(int hno,HashMap<Integer,AddressBook> hmap,AddressBook addressBook){ //HashMap<Integer,AddressBook> hmap=new HashMap<>(); hmap.put(hno,addressBook); // for (Map.Entry<Integer,AddressBook> obj:hmap.entrySet() // ) { // System.out.println(obj.getKey()); // AddressBook a=obj.getValue(); // System.out.println(a.name+a.age+a.Address); // } //display(hmap); } public void display(HashMap<Integer,AddressBook> hmap){ for (Map.Entry<Integer,AddressBook> obj:hmap.entrySet()) { System.out.println(obj.getKey()); AddressBook a=obj.getValue(); System.out.println("Name :"+a.name+"Age :"+a.age+"Address :"+a.Address); } } public void remove(int hno,HashMap<Integer,AddressBook> hmap){ hmap.remove(hno); } public void display(int hno,HashMap<Integer,AddressBook> hmap){ for (Map.Entry<Integer,AddressBook> obj:hmap.entrySet()) { if(hno==obj.getKey()){ System.out.println(obj.getKey()); AddressBook a=obj.getValue(); System.out.println("Name :"+a.name+"Age :"+a.age+"Address :"+a.Address); } } } public static void main(String[] args) { int hno; int i=0; AddressBookMain addressBookMain=new AddressBookMain(); HashMap<Integer,AddressBook> hmap=new HashMap<>(); do{ AddressBook addressBook=new AddressBook(); System.out.println("1 : Add \n2 : Delete \n3 : Search"); Scanner scan=new Scanner(System.in); int option=scan.nextInt(); if(option==1){ System.out.println("Enter house number:"); hno=scan.nextInt(); System.out.println("Enter name:"); addressBook.name=scan.next(); System.out.println("Enter Address:"); addressBook.Address=scan.next(); System.out.println("Enter Age:"); addressBook.age=scan.nextInt(); addressBookMain.add(hno,hmap,addressBook); } if(option==2){ System.out.println("Enter house number:"); hno=scan.nextInt(); if(hmap.containsKey(hno)){ addressBookMain.remove(hno,hmap); addressBookMain.display(hmap); } } if(option==3){ System.out.println("Enter house number:"); hno=scan.nextInt(); if(hmap.containsKey(hno)){ addressBookMain.display(hno,hmap); } } System.out.println("0 for continue, 10 for stop"); i=scan.nextInt(); }while (i==0); } }
package com.hehe.integration.user; import com.hehe.integration.common.R; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/user/*") public class UserController { @Autowired UserService userService; @GetMapping("list") public R list() { try { return R.isOk().data(userService.list()); } catch (Exception e) { return R.isFail(e); } } }
/* * @project: (Sh)ower (R)econstructing (A)pplication for (M)obile (P)hones * @version: ShRAMP v0.0 * * @objective: To detect extensive air shower radiation using smartphones * for the scientific study of ultra-high energy cosmic rays * * @institution: University of California, Irvine * @department: Physics and Astronomy * * @author: Eric Albin * @email: Eric.K.Albin@gmail.com * * @updated: 3 May 2019 */ /** * The classes in this package work as a team to assemble a capture request with optimal settings * for this application, given the choices determined in the sci.crayfis.shramp.camera2.characteristics * package. */ package sci.crayfis.shramp.camera2.requests;
package easy; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class AverageofLevelsinBinaryTree { public List<Double> averageOfLevels(TreeNode root) { List<Double> result = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while(!queue.isEmpty()){ long sum = 0; long size = queue.size(); Queue<TreeNode> temp = new LinkedList<>(); for(int i=0; i<size; i++){ TreeNode treeNode = queue.remove(); sum += treeNode.val; if(treeNode.left != null){ temp.add(treeNode.left); } if(treeNode.right != null){ temp.add(treeNode.right); } } queue = temp; result.add(sum * 1.0 / size); } return result; } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
package com.fnsvalue.skillshare.daoimpl; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fnsvalue.skillshare.dao.ApplyDAO; import com.fnsvalue.skillshare.mapper.ApplyMapper; @Component public class ApplyDAOImpl implements ApplyDAO { @Autowired private SqlSession sqlSession; public int applyAdd(int APPLY_NO_PK, String USER_TB_USER_ID_PK, int BOARD_TB_BOARD_NO_PK) { int result; ApplyMapper applyMapper = sqlSession.getMapper(ApplyMapper.class); result=applyMapper.applyAdd(APPLY_NO_PK, USER_TB_USER_ID_PK, BOARD_TB_BOARD_NO_PK); return result; } public ArrayList<HashMap> applyView(int BOARD_TB_BOARD_NO_PK) { ArrayList<HashMap> result; ApplyMapper applyMapper = sqlSession.getMapper(ApplyMapper.class); result=applyMapper.applyView(BOARD_TB_BOARD_NO_PK); return result; } public int applyAgree(int APPLY_NO_PK) { int result; ApplyMapper applyMapper = sqlSession.getMapper(ApplyMapper.class); result=applyMapper.applyAgree(APPLY_NO_PK); return result; } public int applyCount(int BOARD_TB_BOARD_NO_PK,String USER_TB_USER_ID_PK) { int result; ApplyMapper applyMapper = sqlSession.getMapper(ApplyMapper.class); result=applyMapper.applyCount(BOARD_TB_BOARD_NO_PK,USER_TB_USER_ID_PK); return result; } public int applyDisAgree(int APPLY_NO_PK) { int result; ApplyMapper applyMapper = sqlSession.getMapper(ApplyMapper.class); result=applyMapper.applyDisAgree(APPLY_NO_PK); return result; } public int applyDelete(String USER_TB_USER_ID_PK, int BOARD_TB_BOARD_NO_PK) { int result; ApplyMapper applyMapper = sqlSession.getMapper(ApplyMapper.class); result=applyMapper.applyDelete(USER_TB_USER_ID_PK, BOARD_TB_BOARD_NO_PK); return result; } public ArrayList<HashMap> applyPerView(String USER_TB_USER_ID_PK, int PAGE_START, int PERPAGE_NUM) { ArrayList<HashMap> result; ApplyMapper applyMapper = sqlSession.getMapper(ApplyMapper.class); result=applyMapper.applyPerView(USER_TB_USER_ID_PK, PAGE_START, PERPAGE_NUM); return result; } public int countPaging() { int result; ApplyMapper applyMapper = sqlSession.getMapper(ApplyMapper.class); result=applyMapper.countPaging(); return result; } public int applyAgreeDelete(int APPLY_NO_PK) { int result; ApplyMapper applyMapper = sqlSession.getMapper(ApplyMapper.class); result=applyMapper.applyAgreeDelete(APPLY_NO_PK); return result; } @Override public String applyGetId(String USER_TB_USER_ID_PK, int BOARD_TB_BOARD_NO_PK) { ApplyMapper applyMapper = sqlSession.getMapper(ApplyMapper.class); System.out.println(USER_TB_USER_ID_PK +" / "+BOARD_TB_BOARD_NO_PK); return applyMapper.applyGetId(USER_TB_USER_ID_PK,BOARD_TB_BOARD_NO_PK); } }
package com.stack.geeks.practice; public class MaxOfMinForEveryWindowSize { public static void main(String[] args) { int[] arr1 = {10, 20, 30, 50, 10, 70, 30}; maxOfMinForEveryWindowSize(arr1); int[] arr2 = {10, 20, 30}; maxOfMinForEveryWindowSize(arr2); } private static void maxOfMinForEveryWindowSize(int[] arr) { System.out.println(); int[] temp = new int[arr.length]; int max = Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { temp[i] = arr[i]; max = max>temp[i] ? max:temp[i]; } System.out.print(max + " "); for (int i = 1; i < arr.length; i++) { max = Integer.MIN_VALUE; for (int j=0; j<arr.length; j++){ if((j + i) >= arr.length){ break; } temp[j] = temp[j] > arr[j+i]? arr[j+i] : temp[j]; max = max>temp[j] ? max:temp[j]; } System.out.print(max + " "); } } }
/** * */ package ru.kfu.itis.issst.corpus.utils; /** * Marker interface for Enums that define possible key set of attributes. * * @author Rinat Gareev (Kazan Federal University) * */ public interface DocumentAttributeKey { }
package com.orangehrmlive.demo.utils; import com.orangehrmlive.demo.annotations.Steps; import com.orangehrmlive.demo.pages.Page; import com.orangehrmlive.demo.testdata.JobTitle; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; import java.lang.reflect.Field; public abstract class PageSteps { protected WebDriver driver; public PageSteps() { } public boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } public void user_is_logged_in() { Assert.assertTrue("User isn't logged in", isElementPresent(By.id("welcome"))); } }
package com.pollitosSimulation.logic.entity; /** * * @author Duvis Gรณmez && Martin Vivanco * @version 2.0 */ public class Plato { private String nombre; private int calificacion; private int porcentajeGanancia; private double ganancia; private int precio; /** * crea un plato con los parametros ingresados * * @param nombre Nombre del plato * @param calificacion Calificaciรณn del plato * @param porcentajeGanancia Porcentaje de ganancias del plato * @param precio precio del plato */ public Plato(String nombre, int calificacion, int porcentajeGanancia, int precio) { this.nombre = nombre; this.calificacion = calificacion; this.porcentajeGanancia = porcentajeGanancia; this.ganancia = (precio * porcentajeGanancia) / 100; this.precio = precio; } /** * se sobreescribe el metodo equals para comparar los platos por el nombre * * @param obj objeto a comparar * @return true si tienen el mismo nombre, false en caso contrario */ @Override public boolean equals(Object obj) { return nombre.equals(((Plato) obj).nombre); } /** * muestra el nombre del plato y entre parentesis la calificaciรณn * * @return */ @Override public String toString() { return nombre + " (" + calificacion + ")"; } // Mรฉtodos getters y setters ------ /** * @return Mรฉtodo que obtiene el valor de la propiedad nombre. */ public String getNombre() { return nombre; } /** * @param Mรฉtodo que asigna el valor de la propiedad nombre. */ public void setNombre(String nombre) { this.nombre = nombre; } /** * @return Mรฉtodo que obtiene el valor de la propiedad calificacion. */ public int getCalificacion() { return calificacion; } /** * @param Mรฉtodo que asigna el valor de la propiedad calificacion. */ public void setCalificacion(int calificacion) { this.calificacion = calificacion; } /** * @return Mรฉtodo que obtiene el valor de la propiedad porcentajeGanancia. */ public int getPorcentajeGanancia() { return porcentajeGanancia; } /** * @param Mรฉtodo que asigna el valor de la propiedad porcentajeGanancia. */ public void setPorcentajeGanancia(int porcentajeGanancia) { this.porcentajeGanancia = porcentajeGanancia; } /** * @return Mรฉtodo que obtiene el valor de la propiedad ganancia. */ public double getGanancia() { return ganancia; } /** * @param Mรฉtodo que asigna el valor de la propiedad ganancia. */ public void setGanancia(double ganancia) { this.ganancia = ganancia; } /** * @return Mรฉtodo que obtiene el valor de la propiedad precio. */ public int getPrecio() { return precio; } /** * @param Mรฉtodo que asigna el valor de la propiedad precio. */ public void setPrecio(int precio) { this.precio = precio; } }
package com.example.java.array; import org.junit.Test; public class ArrayInitializer { @Test public void create() { //ๅˆ›ๅปบๆ•ฐ็ป„็š„ๅŸบๆœฌๆ–นๅผ int[] abc = {1, 3}; abc = new int[0]; abc = new int[]{1, 3, 5}; } }
//package com.sprmvc.web.acontrollers; // //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.ComponentScan; //import org.springframework.context.annotation.Configuration; //import org.springframework.web.bind.annotation.RequestMethod; //import org.springframework.web.servlet.mvc.method.RequestMappingInfo; //import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; // //import java.lang.reflect.Method; // //@Configuration //@ComponentScan("com.sprmvc.web.acontrollers") //public class WebConfig { // //// @Autowired //// public void setHandlerMapping(RequestMappingHandlerMapping mapping, UserHandler handler) //// throws NoSuchMethodException { //// //// RequestMappingInfo info = RequestMappingInfo //// .paths("/user/{id}").methods(RequestMethod.GET).build(); //// //// Method method = UserHandler.class.getMethod("getUser", Long.class); //// //// mapping.registerMapping(info, handler, method); //// } //}
// Sun Certified Java Programmer // Chapter 1, P31 // Declarations and Access Control package cert; //Cloo and Roo are in the same package class Cloo extends Roo //Still OK, superclass Roo is public { public void testCloo() { System.out.println(doRooThings()); //Compiler error! } }
package com.hubrick.repository.impl; import com.hubrick.service.FileService; import com.hubrick.model.Employee; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import java.io.FileNotFoundException; import java.util.List; import java.util.Optional; @RunWith(MockitoJUnitRunner.class) public class EmployeeRepositoryTest { private EmployeeRepository employeeRepository; private FileService fileService = FileService.getInstance(); @Before public void setUp() throws Exception { this.employeeRepository = EmployeeRepository.getInstance(fileService); } @Test public void getInstanceValidateSingletonWithSuccess() { EmployeeRepository employeeRepository0 = EmployeeRepository.getInstance(fileService); EmployeeRepository employeeRepository1 = EmployeeRepository.getInstance(fileService); Assert.assertThat(employeeRepository0, CoreMatchers.is(CoreMatchers.equalTo(employeeRepository1))); } @Test public void findAllWithSuccess() { List<Employee> employees = employeeRepository.findAll(); Assert.assertThat(employees, CoreMatchers.notNullValue()); Assert.assertThat(employees.size(), CoreMatchers.is(100)); } @Test public void findAllThrowsFileNotFound() throws Exception { FileService fileServiceMock = Mockito.mock(FileService.class); EmployeeRepository employeeRepositoryMock = Mockito.mock(EmployeeRepository.class); Mockito.when(fileServiceMock.readFile("data/employees.csv")).thenThrow(FileNotFoundException.class); List<Employee> departments = employeeRepositoryMock.findAll(); Assert.assertThat(departments, CoreMatchers.notNullValue()); Assert.assertThat(departments.size(), CoreMatchers.is(0)); } @Test public void findOne() { Optional<Employee> employee = employeeRepository.findOne(1); Assert.assertThat(employee.get(), CoreMatchers.notNullValue()); } @Test public void findOneNotFound() { Optional<Employee> employee = employeeRepository.findOne(1421); Assert.assertThat(employee.isPresent(), CoreMatchers.is(false)); } }
package egg.project000.controlers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import egg.project000.models.Patient; import egg.project000.service.PatientService; import io.javalin.Javalin; import io.javalin.http.Handler; public class PatientControler implements ControlerHeader { private static final Logger aLogger = LoggerFactory.getLogger(PatientControler.class); private PatientService aPatientService = new PatientService(); private Handler insertPatient = ctx -> { Patient p = ctx.bodyAsClass(Patient.class); aLogger.info("printing the patient passed to controller's insert method" + p.toString()); // Once again, requires Jackson Databind to work properly // Save the new User in the DB p = aPatientService.insert(p); ctx.json(p); // Send back the registered User with the updated ID ctx.status(201); // 201 Created MDC.clear(); }; private Handler findAll = ctx -> { ctx.json(aPatientService.findAll()); ctx.status(200); MDC.clear(); }; /** * snippit from ctx.pathParam("String"); * Gets a path param by name (ex: pathParam("param"). * * Ex: If the handler path is /users/:user-id, * and a browser GETs /users/123, * pathParam("user-id") will return "123" */ private Handler findByName = ctx ->{ // String nameString = ctx.pathParam("name"); ctx.json(aPatientService.findPatientByName(ctx.pathParam("name"))); ctx.status(200); }; @Override public void addRoutes(Javalin aJavalinObj) { aLogger.info("'addRoutes' method has been accessed; 874 i am a potato."); aJavalinObj.post("/patients/new", this.insertPatient); aJavalinObj.get("/patients", this.findAll); aJavalinObj.get("/patients/:name", this.findByName); } }
/* < ํƒ‘ - ๋ฌธ์ œ ์„ค๋ช…> ์ˆ˜ํ‰ ์ง์„ ์— ํƒ‘ N๋Œ€๋ฅผ ์„ธ์› ์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  ํƒ‘์˜ ๊ผญ๋Œ€๊ธฐ์—๋Š” ์‹ ํ˜ธ๋ฅผ ์†ก/์ˆ˜์‹ ํ•˜๋Š” ์žฅ์น˜๋ฅผ ์„ค์น˜ํ–ˆ์Šต๋‹ˆ๋‹ค. ๋ฐœ์‚ฌํ•œ ์‹ ํ˜ธ๋Š” ์‹ ํ˜ธ๋ฅผ ๋ณด๋‚ธ ํƒ‘๋ณด๋‹ค ๋†’์€ ํƒ‘์—์„œ๋งŒ ์ˆ˜์‹ ํ•ฉ๋‹ˆ๋‹ค. ๋˜ํ•œ, ํ•œ ๋ฒˆ ์ˆ˜์‹ ๋œ ์‹ ํ˜ธ๋Š” ๋‹ค๋ฅธ ํƒ‘์œผ๋กœ ์†ก์‹ ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ๋†’์ด๊ฐ€ 6, 9, 5, 7, 4์ธ ๋‹ค์„ฏ ํƒ‘์ด ์™ผ์ชฝ์œผ๋กœ ๋™์‹œ์— ๋ ˆ์ด์ € ์‹ ํ˜ธ๋ฅผ ๋ฐœ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋ฉด, ํƒ‘์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์‹ ํ˜ธ๋ฅผ ์ฃผ๊ณ ๋ฐ›์Šต๋‹ˆ๋‹ค. ๋†’์ด๊ฐ€ 4์ธ ๋‹ค์„ฏ ๋ฒˆ์งธ ํƒ‘์—์„œ ๋ฐœ์‚ฌํ•œ ์‹ ํ˜ธ๋Š” ๋†’์ด๊ฐ€ 7์ธ ๋„ค ๋ฒˆ์งธ ํƒ‘์ด ์ˆ˜์‹ ํ•˜๊ณ , ๋†’์ด๊ฐ€ 7์ธ ๋„ค ๋ฒˆ์งธ ํƒ‘์˜ ์‹ ํ˜ธ๋Š” ๋†’์ด๊ฐ€ 9์ธ ๋‘ ๋ฒˆ์งธ ํƒ‘์ด, ๋†’์ด๊ฐ€ 5์ธ ์„ธ ๋ฒˆ์งธ ํƒ‘์˜ ์‹ ํ˜ธ๋„ ๋†’์ด๊ฐ€ 9์ธ ๋‘ ๋ฒˆ์งธ ํƒ‘์ด ์ˆ˜์‹ ํ•ฉ๋‹ˆ๋‹ค. ๋†’์ด๊ฐ€ 9์ธ ๋‘ ๋ฒˆ์งธ ํƒ‘๊ณผ ๋†’์ด๊ฐ€ 6์ธ ์ฒซ ๋ฒˆ์งธ ํƒ‘์ด ๋ณด๋‚ธ ๋ ˆ์ด์ € ์‹ ํ˜ธ๋Š” ์–ด๋–ค ํƒ‘์—์„œ๋„ ์ˆ˜์‹ ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. < ์ž…์ถœ๋ ฅ ์˜ˆ > heights[6,9,5,7,4] -> return [0,0,2,2,4] heights[3,9,9,3,5,7,2] -> [0,0,0,3,3,3,6] heights[1,5,3,6,7,6,5] -> [0,0,2,0,0,5,6] */ import java.util.Arrays; public class no42588 { public static void main(String[] args) { // TODO Auto-generated method stub int[] heights = {1, 5, 3, 6, 7, 6, 5}; System.out.println(Arrays.toString(solution(heights))); } public static int[] solution(int[] heights) { int[] answer = new int[heights.length]; answer[0] = 0; for (int i = heights.length - 1; i > 0; i--) { answer[i] = 0; for (int j = i - 1; j >= 0; j--) { if (heights[j] > heights[i]) { answer[i] = j + 1; break; } } } return answer; } }
package com.github.ezauton.core.utils; import java.util.concurrent.TimeUnit; /** * A clock based off of {@link RealClock} but is warped */ public class TimeWarpedClock implements Clock { private final double speedMultiplier; private final RealClock realClock; private long startTime; private long timeStartedAt; public TimeWarpedClock(double speedMultiplier, long startTime) { realClock = RealClock.CLOCK; this.speedMultiplier = speedMultiplier; this.startTime = startTime; timeStartedAt = System.currentTimeMillis(); } public TimeWarpedClock(double speedMultiplier) { this(speedMultiplier, System.currentTimeMillis()); } public double getSpeed() { return speedMultiplier; } public long getStartTime() { return startTime; } @Override public long getTime() { long realDt = realClock.getTime() - timeStartedAt; return (long) (realDt * speedMultiplier + startTime); } @Override public void scheduleAt(long millis, Runnable runnable) { double realDt = (millis - getTime()) / speedMultiplier; realClock.scheduleIn((long) realDt, TimeUnit.MILLISECONDS, runnable); } @Override public void sleep(long dt, TimeUnit timeUnit) throws InterruptedException { Thread.sleep((long) (timeUnit.toMillis(dt) / speedMultiplier)); } }
package chat.signa.net.pingfang.logging.net; import android.util.Log; import com.squareup.okhttp.Callback; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.IOException; /** * Created by gongguopei87@gmail.com on 2015/9/18. */ public class HttpBaseCallback implements Callback{ @Override public void onFailure(Request request, IOException e) { Log.d("HttpBaseCallback",e.getMessage()); } @Override public void onResponse(Response response) throws IOException { } }
package com.smartwerkz.bytecode.classfile; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collections; import java.util.List; import com.smartwerkz.bytecode.primitives.JavaClassReference; import com.smartwerkz.bytecode.primitives.JavaInteger; import com.smartwerkz.bytecode.primitives.JavaObject; import com.smartwerkz.bytecode.vm.Frame; import com.smartwerkz.bytecode.vm.RuntimeDataArea; import com.smartwerkz.bytecode.vm.VirtualMachine; /** * Represents a java.lang.Class of an array such as "byte[].class" * * @author mhaller */ public class PrimitiveClassfile implements Classfile { private final String clazzName; private JavaClassReference javaClassReference; public PrimitiveClassfile(String clazzName) { this.clazzName = clazzName; javaClassReference = new JavaClassReference(this); } @Override public JavaClassReference getAsJavaClassReference() { return javaClassReference; } @Override public String getThisClassName() { return this.clazzName; } @Override public Methods getMethods(VirtualMachine vm) { return new Methods(clazzName, getConstantPool(), createEmptyStream()); } public JavaObject getDefaultValue() { return new JavaInteger(0); } @Override public ConstantPool getConstantPool() { return new EmptyConstantPool(); } @Override public Fields getFields() { return new Fields(getConstantPool(), createEmptyStream()); } private static DataInputStream createEmptyStream() { ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(out); try { dos.writeShort(0); } catch (IOException e) { throw new RuntimeException(e); } return new DataInputStream(new ByteArrayInputStream(out.toByteArray())); } @Override public String getSuperClassName() { return "java/lang/Object"; } @Override public ClassAccessFlags getAccessFlags() { return new ClassAccessFlags(0); } @Override public boolean isInstanceOf(RuntimeDataArea rda, Frame frame, String className) { if (clazzName.equals(className)) { return true; } return false; } @Override public List<Classfile> getParentClasses(RuntimeDataArea rda, Frame frame) { return Collections.singletonList(rda.vm().classes().objectClass()); } @Override public Attributes getAttributes() { return null; } }
package jonstewardappreciation.cs160.berkeley.edu; import java.util.ArrayList; import android.app.Activity; //import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; public class Hub extends Activity { protected static ListView lv1; protected static ArrayList<Comment> comments = new ArrayList(); private Context v; private void loadThreads() { /** * * Database * * **/ //Open the database DBAdapter1 db1 = FamilyWhiteboard.db.open(); // //Insert a post (String title, String content, int priority, String author) // db1.insertPost("title1", "content1", 1, "simran"); // db1.insertPost("title2", "content2", 1, "someoneElse"); // This is a really stupid way of doing this, but whatever. if (db1.getAllTopics().moveToFirst() == false) { long id = db1.insertPost("Hey", "content", 1, "John"); db1.insertPost("Test Thread", "content", 2, "Steven"); db1.insertPost("Emergency", "content", 3, "Alex"); db1.insertPost("Hi", "content", 2, "Courtney"); db1.insertPost("Sup", "content", 1, "Simi"); } //Get all posts Log.w("Clear", "Clearing comments"); comments.clear(); Cursor c = db1.getAllTopics(); startManagingCursor(c); while (c.moveToNext()) { int id = c.getInt(c.getColumnIndex("id")); String title = c.getString(c.getColumnIndex("title")); String content = c.getString(c.getColumnIndex("content")); int priority = c.getInt(c.getColumnIndex("priority")); String author = c.getString(c.getColumnIndex("author")); Log.w("Post", "" + id + " " + title + " " + content + " " + priority + " " + author); comments.add(new Comment(id, author, title, priority)); } //Close the database db1.close(); } @Override public void onCreate(Bundle icicle) { v = this; loadThreads(); super.onCreate(icicle); setContentView(R.layout.hub); lv1 = (ListView) findViewById(R.id.ListView01); // By using setAdpater method in listview we an add string array in // list. HubAdapter adapt = new HubAdapter(this, R.layout.list_item, comments); lv1.setAdapter(adapt); lv1.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { SharedPreferences settings = getSharedPreferences(Settings.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); //editor.putInt("topic", comments.get(position).id); Intent myIntent = new Intent(v, ViewThread.class); myIntent.putExtra("topic", comments.get(position).id); startActivityForResult(myIntent, 0); } }); Button down = (Button) findViewById(R.id.ScrollDown); down.setOnClickListener(new OnClickListener() { public void onClick(View v) { // scroll up int newY = lv1.getScrollY() + 50; newY = newY <= lv1.getBottom() ? newY : lv1.getBottom(); lv1.scrollTo(0, newY); } }); Button up = (Button) findViewById(R.id.ScrollUp); up.setOnClickListener(new OnClickListener() { public void onClick(View v) { // scroll down int newY = lv1.getScrollY() - 50; newY = newY >= 0 ? newY : 0; lv1.scrollTo(0, newY); } }); Button closeButton = (Button) this.findViewById(R.id.createThread); closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View vi) { Intent myIntent = new Intent(v, AddComment.class); startActivityForResult(myIntent, 0); } }); Button settings = (Button) this.findViewById(R.id.Settings); settings.setOnClickListener(new OnClickListener() { @Override public void onClick(View vi) { Intent myIntent = new Intent(v, Settings.class); startActivityForResult(myIntent, 0); } }); Button logout = (Button) this.findViewById(R.id.LogOut); logout.setOnClickListener(new OnClickListener() { @Override public void onClick(View vi) { finish(); } }); } public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case (0): { if (resultCode == Activity.RESULT_OK) { HubAdapter adapt = new HubAdapter(v, R.layout.list_item, comments); lv1.setAdapter(adapt); Toast.makeText(v, "cancelIcon", Toast.LENGTH_SHORT).show(); } break; } } } private class HubAdapter extends ArrayAdapter<Comment> { private ArrayList<Comment> items; public HubAdapter(Context context, int textViewResourceId, ArrayList<Comment> items) { super(context, textViewResourceId, items); this.items = items; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.list_item, null); } Comment o = items.get(position); if (o != null) { TextView tt = (TextView) v.findViewById(R.id.Hub_Name); TextView bt = (TextView) v.findViewById(R.id.TextView02); ImageView userimg = (ImageView) v.findViewById(R.id.userimg); ImageView img = (ImageView) v.findViewById(R.id.Hub_Priority); if (tt != null) { tt.setText("" + o.getName()); } if (bt != null) { bt.setText("" + o.getComment()); } if (img != null) { switch (o.getPriority()) { default: img.setImageResource(R.drawable.priority_1); break; case 2: img.setImageResource(R.drawable.priority_2); break; case 3: img.setImageResource(R.drawable.priority_3); break; } } if (userimg != null) { String name = o.getName(); if(name.equals("Alex")) { userimg.setImageResource(R.drawable.dogone); } else if(name.equals("Simi")) { userimg.setImageResource(R.drawable.userimg); } else if(name.equals("John")) { userimg.setImageResource(R.drawable.giraffe); } else if(name.equals("Steven")) { userimg.setImageResource(R.drawable.bear); } else if(name.equals("Courtney")) { userimg.setImageResource(R.drawable.horse); } } } return v; } } }
package especificacao; import static org.junit.Assert.assertEquals; import modelo.GeradorDeCodigos; import modelo.Livro; import modelo.TipoLivro; import org.junit.Before; import org.junit.Test; public class DoGeradorDeCodigosSemLevarEmConsideracaoQuantidadeDeExemplares { GeradorDeCodigos gerador; @Before public void geradorDeCodigos() { gerador = new GeradorDeCodigos(); } @Test public void gerandoCodigoAlfaNumericoDeAcordoComGenero() { // dado que TipoLivro livroDeTerror = new Livro(); livroDeTerror.adicionarGenero("Terror"); // quando gerador.gerarCodigoAlfabeticoPara(livroDeTerror); // entao assertEquals("TER0001", gerador.informarCodigo()); assertEquals("TER0001", livroDeTerror.mostrarCodigo()); } @Test public void gerandoCodigoAlfabeticoDeAcordoComGenero2() { // dado que TipoLivro livroDeAdiministracao = new Livro(); livroDeAdiministracao.adicionarGenero("Administraรงรฃo"); GeradorDeCodigos gerador = new GeradorDeCodigos(); // quando gerador.gerarCodigoAlfabeticoPara(livroDeAdiministracao); // entao assertEquals("ADM0001", gerador.informarCodigo()); assertEquals("ADM0001", livroDeAdiministracao.mostrarCodigo()); } @Test public void gerandoCodigoAlfabeticoDeAcordoComGenero3() { // dado que TipoLivro livroDeFiccao = new Livro(); livroDeFiccao.adicionarGenero("Ficรงรฃo"); GeradorDeCodigos gerador = new GeradorDeCodigos(); // quando gerador.gerarCodigoAlfabeticoPara(livroDeFiccao); // entao assertEquals("FIC0001", gerador.informarCodigo()); assertEquals("FIC0001", livroDeFiccao.mostrarCodigo()); } }
package com.example.moi.exerciceimage; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.media.MediaPlayer; import android.support.constraint.ConstraintLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * @author Yacine * @since 2018 * MainActivity manages the main activity, selecting the mood, the button's access of add comment, and the button's access of the historic activity. */ public class MainActivity extends AppCompatActivity { @BindView(R.id.image1) ImageView image1; @BindView(R.id.bt_history) ImageView bt_history; @BindView(R.id.bt_addNote) ImageView bt_addNote; @BindView(R.id.mybackground) ConstraintLayout mybackground; @BindView(R.id.btShare) Button btShare; int[] mood = new int[]{ R.drawable.smiley_sad, R.drawable.smiley_disappointed, R.drawable.smiley_normal, R.drawable.smiley_happy, R.drawable.smiley_super_happy }; int[] backgroundColor = new int[]{ R.color.faded_red, R.color.warm_grey, R.color.cornflower_blue_65, R.color.light_sage, R.color.banana_yellow, R.color.gris_perle, }; String[] stringMoodList = new String[]{ "trรจs mauvaise humeur :(", "plutรดt mauvaise humeur :/", "neutre :|", "plutรดt joyeux :)", "trรจs joyeux :D" }; int[] soundList = new int[]{ R.raw.c3_1, R.raw.c4_2, R.raw.c5_3, R.raw.c6_4, R.raw.c7_5 }; int currentSmile = 3; int currentBackgroundColor = 3; MediaPlayer mplayer; private SharedPreferences mPref; private SharedPreferences.Editor mEdit; Button bt_cancel; Button bt_ok; EditText et_comment; String comment; TextView tv_comment; String dateKey; Dialog myDialog; @SuppressLint("ClickableViewAccessibility") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); myDialog = new Dialog(this); myDialog.setContentView(R.layout.activity_image2); bt_cancel = myDialog.findViewById(R.id.bt_cancel); bt_ok = myDialog.findViewById(R.id.bt_ok); et_comment = myDialog.findViewById(R.id.et_comment); tv_comment = myDialog.findViewById(R.id.tv_comment); SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.FRANCE); Date today = new Date(); dateKey = dateFormat.format(today); mPref = getSharedPreferences("preferences", MODE_PRIVATE); loadPreferences(); shareButtonColor(); mybackground.setOnTouchListener(new OnSwipeTouchListener(this) { @Override public void onSwipeDown() { smileDown(); savePreferences(); shareButtonColor(); } @Override public void onSwipeUp() { smileUp(); savePreferences(); shareButtonColor(); } }); } /** * share * Method for get the mood of the day and share it */ @OnClick(R.id.btShare) public void share() { String sharedMood = ""; Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); currentSmile = mPref.getInt("smilevalue" + dateKey, 3); for (int i = 0; i < 5; i++) { if (currentSmile == i) { sharedMood = stringMoodList[i]; } } sendIntent.putExtra(Intent.EXTRA_TEXT, "Voici mon humeur du jour: " + sharedMood); sendIntent.setType("text/plain"); startActivity(sendIntent); } /** * note * Method to display a dialog window * that integrates a save preferences for save the comment */ @OnClick(R.id.bt_addNote) public void note() { myDialog.show(); bt_cancel.setOnClickListener(v -> myDialog.cancel()); bt_ok.setOnClickListener(v -> { // save comment comment = et_comment.getText().toString(); mEdit = mPref.edit(); mEdit.putString("comment" + dateKey, comment); mEdit.apply(); myDialog.cancel(); }); } /** * history * Method intent for start a new activity (HistoricActivity) */ @OnClick(R.id.bt_history) public void history() { Intent historyIntent = new Intent(this, HistoricActivity.class); startActivity(historyIntent); } public void setCurrentSound() { mplayer = MediaPlayer.create(this, soundList[currentSmile]); } /** * savePreferences * Method for save the smilevalue and colorvalue to the preferences */ public void savePreferences() { mPref = getSharedPreferences("preferences", MODE_PRIVATE); mEdit = mPref.edit(); mEdit.putInt("smilevalue" + dateKey, currentSmile); mEdit.putInt("backcolorvalue" + dateKey, currentBackgroundColor); mEdit.apply(); } /** * loadPreferences * Method for load the smilevalue and colorvalue that are saved in shared preferences */ public void loadPreferences() { currentSmile = mPref.getInt("smilevalue" + dateKey, 3); image1.setImageResource(mood[currentSmile]); currentBackgroundColor = mPref.getInt("backcolorvalue" + dateKey, 3); mybackground.setBackgroundResource(backgroundColor[currentBackgroundColor]); mplayer = MediaPlayer.create(this, soundList[currentSmile]); } public void setCurrentbackgroundcolor() { mybackground.setBackgroundResource(backgroundColor[currentBackgroundColor]); } public void setCurrentsmile() { image1.setImageResource(mood[currentSmile]); } /** * smileUp * Method for slide up (mood), synchronise mood with background's color */ public void smileUp() { if (currentSmile == 4 && currentBackgroundColor == 4) { Toast.makeText(this, "รŠtes-vous vraiment si heureux que รงa ?", Toast.LENGTH_SHORT).show(); return; } mplayer.release(); currentBackgroundColor++; currentSmile++; setCurrentsmile(); setCurrentbackgroundcolor(); setCurrentSound(); mplayer.start(); } /** * smileDown * Method for slide down (mood), synchronise the mood with the background's color */ public void smileDown() { if (currentSmile == 0 && currentBackgroundColor == 0) { Toast.makeText(this, "รŠtes-vous vraiment si triste que รงa ?", Toast.LENGTH_SHORT).show(); return; } mplayer.release(); currentSmile--; currentBackgroundColor--; setCurrentbackgroundcolor(); setCurrentsmile(); setCurrentSound(); mplayer.start(); } /** * shareButtonColor * Method for synchronise the button's color with the background's color */ public void shareButtonColor() { for (int i = 0; i < 5; i++) { if (currentBackgroundColor == i) { btShare.setBackgroundResource(backgroundColor[i]); } } } }
package com.souptik.estore.orderservice.command.rest; import java.util.UUID; import javax.validation.Valid; import org.axonframework.commandhandling.gateway.CommandGateway; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.souptik.estore.orderservice.command.commands.CreateOrderCommand; import com.souptik.estore.orderservice.core.models.OrderStatus; @RestController @RequestMapping("/orders") public class OrderCommandController { private final CommandGateway commandGateway; public OrderCommandController(CommandGateway commandGateway) { this.commandGateway = commandGateway; } @PostMapping public String createOrder(@Valid @RequestBody OrderCreateRest model) { CreateOrderCommand command = CreateOrderCommand.builder().orderId(UUID.randomUUID().toString()) .addressId(model.getAddressId()) .orderStatus(OrderStatus.CREATED) .productId(model.getProductId()) .quantity(model.getQuantity()) .userId("27b95829-4f3f-4ddf-8983-151ba010e35b") .build(); return commandGateway.sendAndWait(command); } }
package com.tantransh.workshopapp.login; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.tantransh.workshopapp.R; import com.tantransh.workshopapp.appdata.AppConstants; import com.tantransh.workshopapp.appdata.AppPreferences; import com.tantransh.workshopapp.appdata.Validator; import com.tantransh.workshopapp.home.DashboardActivity; import com.tantransh.workshopapp.requestadapter.LoginRequestAdapter; import java.util.Objects; public class LoginActivity extends AppCompatActivity { private TextView userIdET,passwordET; private BroadcastReceiver receiver; private AppPreferences ap; private CoordinatorLayout parentLayout; private LinearLayout pdBack; private LoginRequestAdapter requestAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ap = AppPreferences.getInstance(this); initViews(); receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { System.out.println("Received action : "+intent.getAction()); switch (Objects.requireNonNull(intent.getAction())){ case AppConstants.ACTION_LOGIN_SUCCESS: startActivity(new Intent(context, DashboardActivity.class)); break; case AppConstants.ACTION_LOGIN_FAILED: Snackbar.make(parentLayout,"Invalid UserId or Password...!",Snackbar.LENGTH_LONG).show(); break; case AppConstants.ACTION_LOGIN_ERROR: Snackbar.make(parentLayout,"Something went wrong...!",Snackbar.LENGTH_LONG).show(); break; case AppConstants.ACTION_CONNECTION_ERROR: Snackbar.make(parentLayout,"Connection Error. Please try again...!",Snackbar.LENGTH_LONG).show(); break; case AppConstants.ACTION_SERVER_ERROR: Snackbar.make(parentLayout,"Server Error...!",Snackbar.LENGTH_LONG).show(); break; } pdBack.setVisibility(View.GONE); } }; registerReceiver(receiver,new IntentFilter(AppConstants.ACTION_LOGIN_SUCCESS)); registerReceiver(receiver,new IntentFilter(AppConstants.ACTION_LOGIN_FAILED)); registerReceiver(receiver,new IntentFilter(AppConstants.ACTION_LOGIN_ERROR)); registerReceiver(receiver,new IntentFilter(AppConstants.ACTION_CONNECTION_ERROR)); registerReceiver(receiver,new IntentFilter(AppConstants.ACTION_SERVER_ERROR)); } private void initViews() { userIdET = findViewById(R.id.userIdET); passwordET = findViewById(R.id.passwordET); parentLayout = findViewById(R.id.parentLayout); pdBack = findViewById(R.id.pdLO); pdBack.setVisibility(View.GONE); } public void login(View view){ String userId = userIdET.getText().toString(); String password = passwordET.getText().toString(); if(Validator.isValidString(userId,password)){ pdBack.setVisibility(View.VISIBLE); requestAdapter = LoginRequestAdapter.getInstance(this); requestAdapter.login(userId,password); } else{ Snackbar.make(parentLayout,"Please provide UserId and Password",Snackbar.LENGTH_LONG).show(); } } @Override public void onBackPressed() { } @Override protected void onPause() { try{ unregisterReceiver(receiver); } catch (Exception ex){ ex.printStackTrace(); } super.onPause(); } @Override protected void onResume() { super.onResume(); registerReceiver(receiver,new IntentFilter(AppConstants.ACTION_LOGIN_SUCCESS)); registerReceiver(receiver,new IntentFilter(AppConstants.ACTION_LOGIN_FAILED)); registerReceiver(receiver,new IntentFilter(AppConstants.ACTION_LOGIN_ERROR)); registerReceiver(receiver,new IntentFilter(AppConstants.ACTION_CONNECTION_ERROR)); registerReceiver(receiver,new IntentFilter(AppConstants.ACTION_SERVER_ERROR)); } }
import java.util.Scanner; public class Problem3_17 // { public static void main(String[] args) { int computer = (int)(Math.random() * 3); Scanner input = new Scanner(System.in); // Prompt the user to enter a guess System.out.print("Enter a user guess : scissor (0) , rock(1), paper(2) :"); int user = input.nextInt(); System.out.print("The computer is "); switch (computer) { case 0: System.out.print("scissor."); break; case 1: System.out.print("rock."); break; case 2: System.out.print("paper."); break; } System.out.print("You are "); switch (user) { case 0: System.out.print("scissor."); break; case 1: System.out.print("rock."); break; case 2: System.out.print("paper."); break; } // Display result if (computer == user) { System.out.print(" too . It is a draw "); } else System.out.print((user == 0 && computer == 1) || (user == 1 && computer == 2) || (user == 2 && computer == 0) ? " you loose" : " you win"); } }
package com.beiyelin.addressservice.service; import com.beiyelin.commonsql.jpa.BaseDomainCRUDService; import com.beiyelin.addressservice.entity.Province; import java.util.List; /** * @Description: * @Author: newmann * @Date: Created in 22:30 2018-02-11 */ public interface ProvinceService extends BaseDomainCRUDService<Province> { List<Province> findAllByCountryIdOrderByCode(String countryId); }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final /** * RTransportationTime generated by hbm2java */ public class RTransportationTime implements java.io.Serializable { private RTransportationTimeId id; public RTransportationTime() { } public RTransportationTime(RTransportationTimeId id) { this.id = id; } public RTransportationTimeId getId() { return this.id; } public void setId(RTransportationTimeId id) { this.id = id; } }
package net.liuzd.spring.boot.v2.domain; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @JacksonXmlRootElement(localName = "User") public class User { @JacksonXmlProperty(localName = "name") private String name; @JacksonXmlProperty(localName = "age") private Integer age; }
package com.twoyears44.myclass; import android.content.Context; import android.content.SharedPreferences; /** * Created by twoyears44 on 16/4/27. */ public class BCUser { private String nickname; private String udid; private boolean isSync; @SuppressWarnings("unused") private BCUser() { } public BCUser(String nickname, String udid, boolean isSync) { this.nickname = nickname; this.udid = udid; this.isSync = isSync; } static public BCUser getWithPrefs() { Context context = BCApplication.getContext(); SharedPreferences prefs = context.getSharedPreferences("userInfo",Context.MODE_PRIVATE); String nickname = prefs.getString("nickname", null); String udid = prefs.getString("udid", null); boolean isSync = prefs.getBoolean("is_sync", false); if (isSync != false && nickname != null && udid != null) return new BCUser(nickname,udid,isSync); else return null; } public boolean saveToPrefs() { Context context = BCApplication.getContext(); SharedPreferences prefs = context.getSharedPreferences("userInfo",Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putString("nickname", nickname); editor.putString("udid", udid); editor.putBoolean("is_sync", isSync); boolean success = editor.commit(); return success; } public String getNickname() { return nickname; } public String getUdid() { return udid; } public boolean getIsSync() { return isSync; } }