text
stringlengths
10
2.72M
package ArraysJavaListsAutoboxingUnboxing.Autoboxing.Challenge; import java.util.ArrayList; import java.util.Objects; public class Bank { private String name; private ArrayList<Branch> branches; public Bank(String name) { this.name = name; this.branches = new ArrayList<>(); } boolean createBranch(String branchName) { if (findBranch(branchName) == null) { this.branches.add(new Branch(branchName)); return true; } return false; } boolean addCustomerToBranch(String branchName, String customerName, double initialAmount) { Branch existingBranch = findBranch(branchName); if (existingBranch != null) { return existingBranch.addCustomer(customerName, initialAmount); } return false; } boolean addTransactionToExistingCustomer(String branchName, String customerName, double amount) { Branch existingBranch = findBranch(branchName); if (existingBranch != null) { return existingBranch.addCustomerTransaction(customerName, amount); } return false; } boolean listCustomers(String branchName, boolean transactions) { Branch desiredBranch = findBranch(branchName); if (desiredBranch != null) { int count = 1; ArrayList<Customer> customersInBranch = desiredBranch.getCustomers(); System.out.println("Customer details for Branch: " + desiredBranch.getName()); for (Customer branchCustomer : customersInBranch) { System.out.println("Customer name: "+ "[" + count + "]" + branchCustomer.getName()); if (transactions) { ArrayList<Double> customerTransactions = branchCustomer.getTransactions(); int transactionCount = 1; System.out.println("All transactions: "); for (Double customerTransaction : customerTransactions) { System.out.println("["+ transactionCount + "] with an amount of: " + customerTransaction); transactionCount++; } } count++; } } return false; } private Branch findBranch(String branchName) { for (Branch existingBranch : this.branches) { if (existingBranch.getName().equals(branchName)) { return existingBranch; } } return null; } @Deprecated private Branch findBranch(Branch desiredBranch) { String desiredBranchName = desiredBranch.getName(); if (desiredBranchName != null) { return findBranch(desiredBranchName); } return null; } public ArrayList<Branch> getBranches() { return branches; } public String getName() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Bank bank = (Bank) o; return name.equals(bank.name) && branches.equals(bank.branches); } @Override public int hashCode() { return Objects.hash(name, branches); } }
// Generated from SchemeExpr.g4 by ANTLR 4.2 import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor; /** * This class provides an empty implementation of {@link SchemeExprVisitor}, * which can be extended to create a visitor which only needs to handle a subset * of the available methods. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ public class SchemeExprBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements SchemeExprVisitor<T> { /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitWhilel(@NotNull SchemeExprParser.WhilelContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitArithRator(@NotNull SchemeExprParser.ArithRatorContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitBooleanl(@NotNull SchemeExprParser.BooleanlContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitLetvardecl(@NotNull SchemeExprParser.LetvardeclContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitDoublel(@NotNull SchemeExprParser.DoublelContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitPrintl(@NotNull SchemeExprParser.PrintlContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitRelationalRator(@NotNull SchemeExprParser.RelationalRatorContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitBooleanRator(@NotNull SchemeExprParser.BooleanRatorContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitDefl(@NotNull SchemeExprParser.DeflContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitProgl(@NotNull SchemeExprParser.ProglContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitBeginl(@NotNull SchemeExprParser.BeginlContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitAppl(@NotNull SchemeExprParser.ApplContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitIdl(@NotNull SchemeExprParser.IdlContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitFunl(@NotNull SchemeExprParser.FunlContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitLetl(@NotNull SchemeExprParser.LetlContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitIfl(@NotNull SchemeExprParser.IflContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitCalll(@NotNull SchemeExprParser.CalllContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitRator(@NotNull SchemeExprParser.RatorContext ctx) { return visitChildren(ctx); } }
/* * Copyright 2009 Kjetil Valstadsve * * 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 vanadis.remoting; import vanadis.core.collections.Generic; import vanadis.core.lang.EqHc; import vanadis.core.lang.ToString; import java.lang.reflect.Method; import java.util.*; class TypeEnumerator { private final Method[] methods; private final String type; private final int length; private static void addExtendedInterfacesTo(Class<?> type, Set<Method> methods) { Class<?>[] interfaces = type.getInterfaces(); if (interfaces != null && interfaces.length > 0) { for (Class<?> other : interfaces) { methods.addAll(methodsOf(other)); addExtendedInterfacesTo(other, methods); } } } private static Method[] sortedMethodList(Set<Method> set) { List<Method> list = Generic.list(set); Collections.sort(list, new MethodComparator()); return list.toArray(new Method[list.size()]); } private static Collection<Method> methodsOf(Class<?> type) { return Arrays.asList(type.getMethods()); } TypeEnumerator(Class<?> type) { this.type = type.getName(); this.methods = sortedMethodList(methodSet(type)); this.length = methods.length; } private static Set<Method> methodSet(Class<?> type) { Set<Method> methods = Generic.set(); methods.addAll(methodsOf(type)); addExtendedInterfacesTo(type, methods); return methods; } public int indexOf(Method method) { for (int i = 0; i < length; i++) { if (methods[i].equals(method)) { return i; } } throw new IllegalArgumentException("Method not enumerated: " + method); } public Method method(int index) { return methods[validIndex(index, length)]; } public static int validIndex(int index, int length) { if (index < 0) { throw new IllegalArgumentException("Invalid index: " + index); } if (index < length) { return index; } throw new IllegalArgumentException("Invalid index, length was " + length + ": " + index); } @Override public String toString() { return ToString.of(this, "type", type, "#methods", methods.length); } @Override public boolean equals(Object o) { TypeEnumerator enumerator = EqHc.retyped(this, o); return enumerator == this || enumerator != null && EqHc.eq(type, enumerator.type); } @Override public int hashCode() { return EqHc.hc(type); } }
/* */ package datechooser.autorun; /* */ /* */ import datechooser.beans.DateChooserBean; /* */ import datechooser.beans.customizer.DateChooserCustomizer; /* */ import datechooser.beans.customizer.PropertyDescriptorsHolder; /* */ import java.beans.BeanDescriptor; /* */ import java.beans.BeanInfo; /* */ import java.beans.PropertyChangeEvent; /* */ import java.beans.PropertyChangeListener; /* */ import java.io.File; /* */ import javax.swing.BorderFactory; /* */ import javax.swing.JComponent; /* */ import javax.swing.JPanel; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public abstract class ConfigBean /* */ extends JPanel /* */ implements PropertyChangeListener /* */ { /* */ public static final String OK = "ok"; /* */ private DateChooserBean bean; /* */ private DateChooserCustomizer customizer; /* */ private File file; /* */ private boolean saved; /* */ /* */ protected ConfigBean(DateChooserBean bean, DateChooserCustomizer customizer) /* */ { /* 44 */ setFile(null); /* 45 */ setBean(bean); /* 46 */ setCustomizer(customizer); /* 47 */ getCustomizer().setObject(getBean()); /* 48 */ getCustomizer().addPropertyChangeListener(this); /* 49 */ setSaved(true); /* */ /* 51 */ setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5)); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public String toString() /* */ { /* 60 */ return getBeanInfo().getBeanDescriptor().getDisplayName(); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public void propertyChange(PropertyChangeEvent evt) /* */ { /* 70 */ setSaved(false); /* 71 */ if ((getBean() instanceof JComponent)) { /* 72 */ ((JComponent)getBean()).repaint(); /* */ } /* */ } /* */ /* */ protected DateChooserBean getBean() { /* 77 */ return this.bean; /* */ } /* */ /* */ private void setBean(DateChooserBean bean) { /* 81 */ this.bean = bean; /* */ } /* */ /* */ protected DateChooserCustomizer getCustomizer() { /* 85 */ return this.customizer; /* */ } /* */ /* */ private void setCustomizer(DateChooserCustomizer customizer) { /* 89 */ this.customizer = customizer; /* */ } /* */ /* */ protected BeanInfo getBeanInfo() { /* 93 */ return getCustomizer().getBeanInfo(); /* */ } /* */ /* */ /* */ /* */ /* */ public String getBeanDisplayName() /* */ { /* */ try /* */ { /* 103 */ return getBeanInfo().getBeanDescriptor().getDisplayName(); /* */ } catch (NullPointerException ex) {} /* 105 */ return "?"; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public String writeToFile(File file) /* */ { /* 116 */ setFile(file); /* 117 */ setSaved(true); /* 118 */ return getCustomizer().getHolder().writeToFile(file); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public String readFromFile(File file) /* */ { /* 128 */ setFile(file); /* 129 */ setSaved(true); /* 130 */ return getCustomizer().getHolder().readFromFile(file); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public abstract String getFileExt(); /* */ /* */ /* */ /* */ /* */ /* */ public File getFile() /* */ { /* 146 */ return this.file; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public void setFile(File file) /* */ { /* 155 */ this.file = file; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public boolean isSaved() /* */ { /* 164 */ return this.saved; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public void setSaved(boolean saved) /* */ { /* 173 */ this.saved = saved; /* */ } /* */ } /* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/autorun/ConfigBean.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
package jsonparsing.util; public class SlowAndAccurateHash { }
package main; public class Clock { String date; String parameter; public Clock(String date, String parameter) { this.date = date; this.parameter = parameter; } }
package lingkaran; public class tabung extends hitungLingkaran { public static double luas, volume; private double tinggi; public tabung (double jarijari, double tinggi){ super(jarijari); this.tinggi = tinggi; } public tabung (int jarijari2, double tinggi){ super(jarijari2); this.tinggi = tinggi; } public static double getVolume() { return volume; } //OVERLOADING public void hitungVolume(double jarijari){ volume = Math.PI*Math.pow(getJarijari(),2)*tinggi; } public void hitungVolume(int jarijari2){ volume = 22.0/7.0*Math.pow(getJarijari2(),2)*tinggi; } @Override public double menghitungLuas() { luas = 2*Math.PI*getJarijari()*(getJarijari() + tinggi); return luas; } }
package org.buaa.ly.MyCar.entity.deserilizer; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import java.lang.reflect.Type; import java.util.List; public class ListInteger2StringDeserializer implements ObjectDeserializer { @Override public <T> T deserialze(DefaultJSONParser defaultJSONParser, Type type, Object o) { List<Integer> insurance = defaultJSONParser.parseArray(Integer.class); return (T) JSON.toJSONString(insurance); } @Override public int getFastMatchToken() { return JSONToken.LBRACKET; } }
package arenaworker.lib; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import arenaworker.Base; import arenaworker.ObjRectangle; public class Grid { private double g; // optimization private ConcurrentHashMap<String, Set<Base>> objects = new ConcurrentHashMap<>(); public Grid(double size, int divisions) { this.g = divisions / size; } public void update(Base obj) { if (obj instanceof ObjRectangle) { ObjRectangle o = (ObjRectangle)obj; if (!obj.grids.equals(getGridsObjRectangleIsIn(o.position, o.scale))) { remove(o); insert(o); } } else { if (!obj.grids.equals(getGridsObjCircleIsIn(obj.position, obj.radius))) { remove(obj); insert(obj); } } } public void insert(Base obj) { if (obj instanceof ObjRectangle) { ObjRectangle o = (ObjRectangle)obj; obj.grids = getGridsObjRectangleIsIn(o.position, o.scale); } else { obj.grids = getGridsObjCircleIsIn(obj.position, obj.radius); } for (String grid : obj.grids) { if (objects.containsKey(grid)) { objects.get(grid).add(obj); } else { Set<Base> temp = ConcurrentHashMap.newKeySet(); temp.add(obj); objects.put(grid, temp); } } } public void remove(Base obj) { for (Iterator<String> i = obj.grids.iterator(); i.hasNext();) { objects.get(i.next()).remove(obj); } // for (String grid : obj.grids) { // objects.get(grid).remove(obj); // } obj.grids.clear(); } Set<Base> retrievedObjects = Collections.newSetFromMap(new ConcurrentHashMap<Base, Boolean>()); public Set<Base> retrieve(Vector2 pos, double radius) { retrievedObjects.clear(); Set<String> grids = getGridsObjCircleIsIn(pos, radius); for (String grid : grids) { if (objects.containsKey(grid)) { retrievedObjects.addAll(objects.get(grid)); } } return retrievedObjects; } public Set<Base> retrieve(Vector2 pos, Vector2 scale) { retrievedObjects.clear(); Set<String> grids = getGridsObjRectangleIsIn(pos, scale); for (String grid : grids) { if (objects.containsKey(grid)) { retrievedObjects.addAll(objects.get(grid)); } } return retrievedObjects; } private Set<String> getGridsObjCircleIsIn(Vector2 pos, double radius) { Set<String> grids = new HashSet<>(); int[] min = positionToGrid(pos.x - radius, pos.y - radius); int[] max = positionToGrid(pos.x + radius, pos.y + radius); for (int x = min[0]; x <= max[0]; x++) { for (int y = min[1]; y <= max[1]; y++) { grids.add(x + "_" + y); } } return grids; } private Set<String> getGridsObjRectangleIsIn(Vector2 pos, Vector2 scale) { Set<String> grids = new HashSet<>(); // https://stackoverflow.com/questions/622140/calculate-bounding-box-coordinates-from-a-rotated-rectangle // TODO: remove rotation part to make faster - boxes are never rotated double x1 = -scale.x / 2; double x2 = scale.x / 2; double x3 = scale.x / 2; double x4 = -scale.x / 2; double y1 = scale.y / 2; double y2 = scale.y / 2; double y3 = -scale.y / 2; double y4 = -scale.y / 2; // rotation = 0 always double x11 = x1 * Math.cos(0) + y1 * Math.sin(0); double y11 = -x1 * Math.sin(0) + y1 * Math.cos(0); double x21 = x2 * Math.cos(0) + y2 * Math.sin(0); double y21 = -x2 * Math.sin(0) + y2 * Math.cos(0); double x31 = x3 * Math.cos(0) + y3 * Math.sin(0); double y31 = -x3 * Math.sin(0) + y3 * Math.cos(0); double x41 = x4 * Math.cos(0) + y4 * Math.sin(0); double y41 = -x4 * Math.sin(0) + y4 * Math.cos(0); double xMin = Math.min(Math.min(x11, x21), Math.min(x31, x41)); double xMax = Math.max(Math.max(x11, x21), Math.max(x31, x41)); double yMin = Math.min(Math.min(y11, y21), Math.min(y31, y41)); double yMax = Math.max(Math.max(y11, y21), Math.max(y31, y41)); int[] min = positionToGrid(pos.x + xMin, pos.y + yMin); int[] max = positionToGrid(pos.x + xMax, pos.y + yMax); for (int x = min[0]; x <= max[0]; x++) { for (int y = min[1]; y <= max[1]; y++) { grids.add(x + "_" + y); } } return grids; } private int[] positionToGrid(double x, double y) { return new int[]{(int)Math.round(g * x), (int)Math.round(g * y)}; } }
package com.tencent.mm.plugin.mmsight.ui; import android.os.Bundle; import android.widget.TextView; import com.tencent.mm.compatible.util.e; import com.tencent.mm.plugin.mmsight.api.MMSightRecordView; import com.tencent.mm.plugin.w.a; import com.tencent.mm.plugin.w.a.d; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.ui.MMActivity; public class MMSightRecordViewTestUI extends MMActivity { private MMSightRecordView fOq; private int fbk = 720; private float fbl = 0.67f; public void onCreate(Bundle bundle) { super.onCreate(bundle); setBackBtn(new 1(this)); this.fOq = (MMSightRecordView) findViewById(d.record_view); this.fOq.setDisplayRatio(this.fbl); this.fOq.setPreviewSizeLimit(this.fbk); this.fOq.setVideoPara$2e715812(100000); this.fOq.setVideoFilePath(e.bnE + "mmsighttest.mp4"); this.fOq.setClipPictureSize(true); this.fOq.setClipVideoSize(true); this.fOq.leB.ZX(); this.fOq.setFlashMode(3); this.fOq.setFrameDataCallback(new 2(this)); this.fOq.leB.startPreview(); this.fOq.leB.ZS(); findViewById(d.take_picture_btn).setOnClickListener(new 3(this)); findViewById(d.start_record_btn).setOnClickListener(new 4(this)); ah.i(new 5(this, (TextView) findViewById(d.debug_info)), 1000); findViewById(d.switch_camera_btn).setOnClickListener(new 6(this)); } protected void onDestroy() { super.onDestroy(); this.fOq.leB.release(); } protected final int getLayoutId() { return a.e.mmsight_record_view_testui; } }
package com.elvarg.world.content; import java.util.ArrayList; import java.util.List; import com.elvarg.definitions.ItemDefinition; import com.elvarg.util.Misc; import com.elvarg.world.content.Dueling.DuelState; import com.elvarg.world.entity.impl.player.Player; import com.elvarg.world.model.Item; import com.elvarg.world.model.PlayerStatus; import com.elvarg.world.model.SecondsTimer; import com.elvarg.world.model.container.ItemContainer; import com.elvarg.world.model.container.StackType; import com.elvarg.world.model.container.impl.Inventory; /** * Handles the entire trading system. * Should be dupe-free. * * @author Swiffy */ public class Trading { //Interface data private static final int INTERFACE = 3323; public static final int CONTAINER_INTERFACE_ID = 3415; private static final int CONTAINER_INTERFACE_ID_2 = 3416; public static final int CONTAINER_INVENTORY_INTERFACE = 3321; public static final int INVENTORY_CONTAINER_INTERFACE = 3322; private static final int CONFIRM_SCREEN_INTERFACE = 3443; //Frames data private static final int TRADING_WITH_FRAME = 3417; private static final int STATUS_FRAME_1 = 3431; private static final int STATUS_FRAME_2 = 3535; private static final int ITEM_LIST_1_FRAME = 3557; private static final int ITEM_LIST_2_FRAME = 3558; private static final int ITEM_VALUE_1_FRAME = 24209; private static final int ITEM_VALUE_2_FRAME = 24210; //Nonstatic private final Player player; private final ItemContainer container; private Player interact; private TradeState state = TradeState.NONE; //Delays!! private SecondsTimer button_delay = new SecondsTimer(); private SecondsTimer request_delay = new SecondsTimer(); //The possible states during a trade private enum TradeState { NONE, REQUESTED_TRADE, TRADE_SCREEN, ACCEPTED_TRADE_SCREEN, CONFIRM_SCREEN, ACCEPTED_CONFIRM_SCREEN; } //Constructor public Trading(Player player) { this.player = player; //The container which will hold all our offered items. this.container = new ItemContainer(player) { @Override public StackType stackType() { return StackType.DEFAULT; } @Override public ItemContainer refreshItems() { player.getPacketSender().sendInterfaceSet(INTERFACE, CONTAINER_INVENTORY_INTERFACE); player.getPacketSender().sendItemContainer(container, CONTAINER_INTERFACE_ID); player.getPacketSender().sendItemContainer(player.getInventory(), INVENTORY_CONTAINER_INTERFACE); player.getPacketSender().sendItemContainer(interact.getTrading().getContainer(), CONTAINER_INTERFACE_ID_2); interact.getPacketSender().sendItemContainer(player.getTrading().getContainer(), CONTAINER_INTERFACE_ID_2); return this; } @Override public ItemContainer full() { getPlayer().getPacketSender().sendMessage("You cannot trade more items."); return this; } @Override public int capacity() { return 28; } }; } public void requestTrade(Player t_) { if(state == TradeState.NONE || state == TradeState.REQUESTED_TRADE) { if(player.getDueling().inDuel()) { player.getPacketSender().sendMessage("You cannot trade during a duel!"); return; } //Make sure to not allow flooding! if(!request_delay.finished()) { int seconds = request_delay.secondsRemaining(); player.getPacketSender().sendMessage("You must wait another "+(seconds == 1 ? "second" : ""+seconds+" seconds")+" before sending more trade requests."); return; } //The other players' current trade state. final TradeState t_state = t_.getTrading().getState(); //Should we initiate the trade or simply send a request? boolean initiateTrade = false; //Update this instance... this.setInteract(t_); this.setState(TradeState.REQUESTED_TRADE); //Check if target requested a trade with us... if(t_state == TradeState.REQUESTED_TRADE) { if(t_.getTrading().getInteract() != null && t_.getTrading().getInteract() == player) { initiateTrade = true; } } //Initiate trade for both players with eachother? if(initiateTrade) { player.getTrading().initiateTrade(); t_.getTrading().initiateTrade(); } else { player.getPacketSender().sendMessage("You've sent a trade request to "+t_.getUsername()+"."); t_.getPacketSender().sendMessage(player.getUsername() + ":tradereq:"); } //Set the request delay to 2 seconds at least. request_delay.start(2); } else { player.getPacketSender().sendMessage("You cannot do that right now."); } } public void initiateTrade() { //Update statuses player.setStatus(PlayerStatus.TRADING); player.getTrading().setState(TradeState.TRADE_SCREEN); //Update strings on interface player.getPacketSender().sendString(TRADING_WITH_FRAME, "Trading with: @whi@"+interact.getUsername()); player.getPacketSender().sendString(STATUS_FRAME_1, "").sendString(STATUS_FRAME_2, "Are you sure you want to make this trade?") .sendString(ITEM_VALUE_1_FRAME, "0 bm").sendString(ITEM_VALUE_2_FRAME, "0 bm"); //Reset container container.resetItems(); //Refresh and send container... container.refreshItems(); } public void closeTrade() { if(state != TradeState.NONE) { //Cache the current interact final Player interact_ = interact; //Return all items... for(Item t : container.getValidItems()) { container.switchItem(player.getInventory(), t.copy(), false, false); } //Refresh inventory player.getInventory().refreshItems(); //Reset all attributes... resetAttributes(); //Send decline message player.getPacketSender().sendMessage("Trade declined."); player.getPacketSender().sendInterfaceRemoval(); //Reset trade for other player aswell (the cached interact) if(interact_ != null) { if(interact_.getStatus() == PlayerStatus.TRADING) { if(interact_.getTrading().getInteract() != null && interact_.getTrading().getInteract() == player) { interact_.getPacketSender().sendInterfaceRemoval(); } } } } } public void acceptTrade() { //Validate this trade action.. if(!validate(player, interact, PlayerStatus.TRADING, new TradeState[]{TradeState.TRADE_SCREEN, TradeState.ACCEPTED_TRADE_SCREEN, TradeState.CONFIRM_SCREEN, TradeState.ACCEPTED_CONFIRM_SCREEN})) { return; } //Check button delay... if(!button_delay.finished()) { return; } //Cache the interact... final Player interact_ = interact; //Interact's current trade state. final TradeState t_state = interact_.getTrading().getState(); //Check which action to take.. if(state == TradeState.TRADE_SCREEN) { //Verify that the interact can receive all items first.. int slotsNeeded = 0; for(Item t : container.getValidItems()) { slotsNeeded += t.getDefinition().isStackable() && interact.getInventory().contains(t.getId()) ? 0 : 1; } int freeSlots = interact.getInventory().getFreeSlots(); if(slotsNeeded > freeSlots) { player.getPacketSender().sendMessage("").sendMessage("@or3@"+interact.getUsername()+" will not be able to hold that item.") .sendMessage("@or3@They have "+freeSlots+" free inventory slot" + (freeSlots == 1 ? "." : "s.")); interact.getPacketSender().sendMessage("Trade cannot be accepted, you don't have enough free inventory space."); return; } //Both are in the same state. Do the first-stage accept. setState(TradeState.ACCEPTED_TRADE_SCREEN); //Update status... player.getPacketSender().sendString(STATUS_FRAME_1, "Waiting for other player.."); interact_.getPacketSender().sendString(STATUS_FRAME_1, ""+player.getUsername()+" has accepted."); //Check if both have accepted.. if(state == TradeState.ACCEPTED_TRADE_SCREEN && t_state == TradeState.ACCEPTED_TRADE_SCREEN) { //Technically here, both have accepted. //Go into confirm screen! player.getTrading().confirmScreen(); interact_.getTrading().confirmScreen(); } } else if(state == TradeState.CONFIRM_SCREEN) { //Both are in the same state. Do the second-stage accept. setState(TradeState.ACCEPTED_CONFIRM_SCREEN); //Update status... player.getPacketSender().sendString(STATUS_FRAME_2, "Waiting for "+interact_.getUsername()+"'s confirmation.."); interact_.getPacketSender().sendString(STATUS_FRAME_2, ""+player.getUsername()+" has accepted. Do you wish to do the same?"); //Check if both have accepted.. if(state == TradeState.ACCEPTED_CONFIRM_SCREEN && t_state == TradeState.ACCEPTED_CONFIRM_SCREEN) { //Give items to both players... for(Item item : interact_.getTrading().getContainer().getValidItems()) { player.getInventory().add(item); } for(Item item : player.getTrading().getContainer().getValidItems()) { interact_.getInventory().add(item); } //Reset attributes for both players... player.getTrading().resetAttributes(); interact_.getTrading().resetAttributes(); //Send interface removal for both players... player.getPacketSender().sendInterfaceRemoval(); interact_.getPacketSender().sendInterfaceRemoval(); //Send successful trade message! player.getPacketSender().sendMessage("Trade accepted!"); interact_.getPacketSender().sendMessage("Trade accepted!"); } } button_delay.start(1); } private void confirmScreen() { //Update state player.getTrading().setState(TradeState.CONFIRM_SCREEN); //Send new interface player.getPacketSender().sendInterfaceSet(CONFIRM_SCREEN_INTERFACE, CONTAINER_INVENTORY_INTERFACE); player.getPacketSender().sendItemContainer(player.getInventory(), INVENTORY_CONTAINER_INTERFACE); //Send new interface frames String this_items = listItems(container); String interact_item = listItems(interact.getTrading().getContainer()); player.getPacketSender().sendString(ITEM_LIST_1_FRAME, this_items); player.getPacketSender().sendString(ITEM_LIST_2_FRAME, interact_item); } //Deposit or withdraw an item.... public void handleItem(int id, int amount, int slot, ItemContainer from, ItemContainer to) { if(player.getInterfaceId() == INTERFACE) { //Validate this trade action.. if(!validate(player, interact, PlayerStatus.TRADING, new TradeState[]{TradeState.TRADE_SCREEN, TradeState.ACCEPTED_TRADE_SCREEN})) { return; } //Check if the trade was previously accepted (and now modified)... boolean modified = false; if(state == TradeState.ACCEPTED_TRADE_SCREEN) { state = TradeState.TRADE_SCREEN; modified = true; } if(interact.getTrading().getState() == TradeState.ACCEPTED_TRADE_SCREEN) { interact.getTrading().setState(TradeState.TRADE_SCREEN); modified = true; } if(modified) { player.getPacketSender().sendString(STATUS_FRAME_1, "@red@TRADE MODIFIED!"); interact.getPacketSender().sendString(STATUS_FRAME_1, "@red@TRADE MODIFIED!"); } //Handle the item switch.. if(state == TradeState.TRADE_SCREEN && interact.getTrading().getState() == TradeState.TRADE_SCREEN) { //Check if the item is in the right place if(from.getItems()[slot].getId() == id) { //Make sure we can fit that amount in the trade if(from instanceof Inventory) { if(!ItemDefinition.forId(id).isStackable()) { if(amount > container.getFreeSlots()) { amount = container.getFreeSlots(); } } } if(amount <= 0) { return; } final Item item = new Item(id, amount); //Do the switch! if(item.getAmount() == 1) { from.switchItem(to, item, slot, false, true); } else { from.switchItem(to, item, false, true); } //Update value frames for both players String plr_value = container.getTotalValue(); String other_plr_value = interact.getTrading().getContainer().getTotalValue(); player.getPacketSender().sendString(ITEM_VALUE_1_FRAME, Misc.insertCommasToNumber(plr_value) + " bm"); player.getPacketSender().sendString(ITEM_VALUE_2_FRAME, Misc.insertCommasToNumber(other_plr_value) + " bm"); interact.getPacketSender().sendString(ITEM_VALUE_1_FRAME, Misc.insertCommasToNumber(other_plr_value) + " bm"); interact.getPacketSender().sendString(ITEM_VALUE_2_FRAME, Misc.insertCommasToNumber(plr_value) + " bm"); } } else { player.getPacketSender().sendInterfaceRemoval(); } } } public void resetAttributes() { //Reset trade attributes setInteract(null); setState(TradeState.NONE); //Reset player status if it's trading. if(player.getStatus() == PlayerStatus.TRADING) { player.setStatus(PlayerStatus.NONE); } //Reset container.. container.resetItems(); //Send the new empty container to the interface //Just to clear the items there. player.getPacketSender().sendItemContainer(container, CONTAINER_INTERFACE_ID); } public static String listItems(ItemContainer items) { String string = ""; int item_counter = 0; List<Item> list = new ArrayList<Item>(); loop1: for(Item item : items.getValidItems()) { //Make sure the item isn't already in the list. for(Item item_ : list) { if(item_.getId() == item.getId()) { continue loop1; } } list.add(new Item(item.getId(), items.getAmount(item.getId()))); } for(Item item : list) { if(item_counter > 0) { string += "\\n"; } string += item.getDefinition().getName().replaceAll("_", " "); String amt = "" + Misc.format(item.getAmount()); if (item.getAmount() >= 1000000000) { amt = "@gre@" + (item.getAmount() / 1000000000) + " billion @whi@(" + Misc.format(item.getAmount()) + ")"; } else if (item.getAmount() >= 1000000) { amt = "@gre@" + (item.getAmount() / 1000000) + " million @whi@(" + Misc.format(item.getAmount()) + ")"; } else if(item.getAmount() >= 1000) { amt = "@cya@" + (item.getAmount() / 1000) + "K @whi@(" + Misc.format(item.getAmount()) + ")"; } string += " x @red@" + amt; item_counter++; } if(item_counter == 0) { string = "Absolutely nothing!"; } return string; } /** * Validates a player. Basically checks that all specified params add up. * @param player * @param interact * @param playerStatus * @param duelStates * @return */ private static boolean validate(Player player, Player interact, PlayerStatus playerStatus, TradeState... tradeState) { //Verify player... if(player == null || interact == null) { return false; } //Make sure we have proper status if(player.getStatus() != playerStatus) { return false; } //Make sure we're interacting with eachother if(interact.getStatus() != playerStatus) { return false; } if(player.getTrading().getInteract() == null || player.getTrading().getInteract() != interact) { return false; } if(interact.getTrading().getInteract() == null || interact.getTrading().getInteract() != player) { return false; } //Make sure we have proper duel state. boolean found = false; for(TradeState duelState : tradeState) { if(player.getTrading().getState() == duelState) { found = true; break; } } if(!found) { return false; } //Do the same for our interact found = false; for(TradeState duelState : tradeState) { if(interact.getTrading().getState() == duelState) { found = true; break; } } if(!found) { return false; } return true; } public TradeState getState() { return state; } public void setState(TradeState state) { this.state = state; } public SecondsTimer getButtonDelay() { return button_delay; } public Player getInteract() { return interact; } public void setInteract(Player interact) { this.interact = interact; } public ItemContainer getContainer() { return container; } }
package database.jdbc.main; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import database.jdbc.util.DBHandler; public class ScrollResultSet { /** * @param args * @throws SQLException */ public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = DBHandler.OpenConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String sql = "select id, name, email from emp order by id"; rs = stmt.executeQuery(sql); // 跳到结果集第二十条 rs.absolute(20); System.out.println(rs.getInt("id") + " " + rs.getString("name")); // 相对当前位置向前跳5条 rs.relative(-5); System.out.println(rs.getInt("id") + " " + rs.getString("name")); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } finally{ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { DBHandler.closeConnection(conn); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package com.pangpang6.books.base.lambda; import org.junit.Test; import java.util.function.ObjDoubleConsumer; /** * Created by jiangjiguang on 2018/1/2. */ public class ObjDoubleConsumerTest { @Test public void acceptTest() { ObjDoubleConsumer<String> i = (s, d) -> System.out.println(s + d); i.accept("123", 0.333); } }
package com.example.demo.service.test2.imp; import com.example.demo.entity.test2.User2; import com.example.demo.mapper.test2.User2Dao; import com.example.demo.service.test2.User2Service; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service("user2Service") public class User2ServiceImp implements User2Service { @Resource private User2Dao user2Dao; @Override public int saveToDb2(User2 user2) { return user2Dao.saveToDb2(user2); } }
package com.example.namtn.gihng.Retrofit.RetrofitRespone; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class ResponeRSItems { @SerializedName("data") @Expose private ArrayList<ResponeRSItems> rsItemsArrayList; public ArrayList<ResponeRSItems> getRsItemsArrayList() { return rsItemsArrayList; } public void setRsItemsArrayList(ArrayList<ResponeRSItems> rsItemsArrayList) { this.rsItemsArrayList = rsItemsArrayList; } }
package fr.lteconsulting; public class Exercice { private String intitule; private String sujet; public Exercice( String intitule, String sujet ) { this.intitule = intitule; this.sujet = sujet; } public String getIntitule() { return intitule; } public void setIntitule( String intitule ) { this.intitule = intitule; } public String getSujet() { return sujet; } public void setSujet( String sujet ) { this.sujet = sujet; } }
package com.eCommerce.eComApp.controller; import com.eCommerce.eComApp.model.Client; import com.eCommerce.eComApp.repository.ClientRepository; import com.eCommerce.eComApp.service.ClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/") public class ClientController { @Autowired private ClientRepository clientRepo; @Autowired private ClientService clientService; @GetMapping("/clients") public List<Client> getAllClients(){ return clientService.getAllClients(); } @PostMapping("/clients") public void createClient(@RequestBody Client client){ clientService.createClient(client); } @GetMapping("/clients/{id}") public Client getClientById(@PathVariable("id") String id ){ return clientService.getClientById(id); } @PutMapping("/clients/{id}") public void updateById(@PathVariable("id") String id ,@RequestBody Client newClient){ clientService.updateById(id,newClient); } @PutMapping("/clients") @ResponseStatus(HttpStatus.OK) public ResponseEntity<Client> identify(@RequestBody Client client){ Client identified = null; if(client.getEmail()!=null && !client.getEmail().isEmpty()) identified = clientService.identifyByEmail(client.getEmail(),client.getPassword()); else if(client.getUserName()!=null && !client.getUserName().isEmpty()) identified = clientService.identifyByUserName(client.getUserName(),client.getPassword()); if(identified != null){ return new ResponseEntity<Client>(identified,HttpStatus.ACCEPTED); }else return new ResponseEntity<>(HttpStatus.NOT_FOUND); } @DeleteMapping("/clients/{id}") public void deleteById(@PathVariable("id") String id ) { clientService.deleteById(id); } }
package com.philippe.app.service.futures; import org.junit.jupiter.api.Test; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class SquareCalculatorTest { @Test public void toDemo() throws InterruptedException, ExecutionException { Future<Integer> future = new SquareCalculator().calculate(10); while(!future.isDone()) { System.out.println("Calculating..."); Thread.sleep(300); } Integer result = future.get(); System.out.println("result is " + result); // get() has an overloaded version that takes a timeout and a TimeUnit as arguments: future.get(500, TimeUnit.MILLISECONDS); } }
package pl.com.garage.dao; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import pl.com.garage.model.Client; import pl.com.garage.service.ClientService; import java.util.List; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring.xml") public class git ClientDaoImplTest { @Autowired private ClientService clientService; @Autowired private JdbcTemplate jdbcTemplate; @Before public void before() { jdbcTemplate.execute("truncate client"); } @Test public void shouldAddClient() throws Exception { //given //when clientService.addClient("Kamil", "Alfa"); //then Long countCliens = jdbcTemplate.queryForObject("select count(*) from client where name like ?", Long.class, "Kamil"); Assertions.assertThat(countCliens).isEqualTo(1); } @Test public void shouldFindClientById() throws Exception { //given clientService.addClient("Kamila", "Alfa"); Integer id = jdbcTemplate.queryForObject("select max(id) from client", Integer.class); //when Client outPutClient = clientService.findClient(id); //then Assertions.assertThat(outPutClient.getId()).isEqualTo(id); Assertions.assertThat(outPutClient.getName()).isEqualTo("Kamila"); } @Test public void shouldUpdateClient() throws Exception { //given clientService.addClient("Kamila", "Alfa"); //when clientService.updateClient("Kamila", "Ford"); //then String updateEvidence = jdbcTemplate.queryForObject("SELECT model FROM client WHERE name = ?", String.class, "Kamila"); Assertions.assertThat(updateEvidence).isEqualTo("Ford"); } @Test public void shouldDelateClient() throws Exception { //given clientService.addClient("Kamil", "Alfa"); clientService.addClient("Asia", "Omega"); //when clientService.delateClient("Kamil"); Integer countClients = jdbcTemplate.queryForObject("SELECT count(*) FROM client", Integer.class); //then Assertions.assertThat(countClients).isEqualTo(1); } @Test public void shouldFindAllClients() throws Exception { //then clientService.addClient("Kamila", "Alfa"); //when List<Client> outPutClientList = clientService.findAllClient(); //given Assertions.assertThat(outPutClientList.size()).isEqualTo(1); } }
package com.lubarov.daniel.nagger.messages.s2c; public class S2cJumpToAlertMessage { public String alertUuid; }
package com.leo.pattern.gs; import java.util.concurrent.Callable; public abstract class GuardedAction<V> implements Callable<V> { protected final StatusMoitor moitor; public GuardedAction(StatusMoitor moitor) { this.moitor = moitor; } }
/** * Nguru Ian Davis * 15059844 */ public class Crew extends Passenger { public static final String CAPTAIN = "Captain"; public static final String FIRST_OFFICER = "First Officer"; public static final String CABIN_CREW = "Cabin Crew"; //static Strings that hold the crew type private String position ; /** * Constructor to be used to create objects of Crew type */ public Crew( int passengerNumberStart, String fName, String lName, double w, double lugg, String pos) { super(passengerNumberStart, fName, lName, w, lugg); //gets the properties from the passenger class if(pos.equals(null)) { System.out.println("Please enter position"); } if (pos.equalsIgnoreCase(CAPTAIN)) { position = Crew.CAPTAIN; } else if (pos.equalsIgnoreCase(FIRST_OFFICER)) { position = Crew.FIRST_OFFICER; } else if (pos.equalsIgnoreCase(CABIN_CREW)) { position = Crew.CABIN_CREW; } else { System.out.println("Crew member's position not defined ( " + getPassNum() + " )"); //checks that only the allowed crew type are added } } /** * return the position of the crew member */ public String getCrew() { return position; } /** * set the position of the crew member */ public void setCrew(String pos) { if(pos.equals(null)) { System.out.println("Please enter position"); } if (pos.equalsIgnoreCase(CAPTAIN)) { position = Crew.CAPTAIN; } else if (pos.equalsIgnoreCase(FIRST_OFFICER)) { position = Crew.FIRST_OFFICER; } else if (pos.equalsIgnoreCase(CABIN_CREW)) { position = Crew.CABIN_CREW; } else { System.out.println("Not a type of crew."); //makes sure that the crew position that is to be passed is of the 3 that are allowed } } /** * overrides the toString from the Passenger class adding the position of the crew member */ @Override public String toString() { String string = super.toString(); return string + " Crew Type: " + getCrew(); } }
package com.hesoyam.pharmacy.feedback.dto; public class ComplaintCreatedResponseDTO { private Long id; private String entityName; private String body; public ComplaintCreatedResponseDTO(){ //Empty ctor for JSON serializer } public ComplaintCreatedResponseDTO(Long id, String entityName, String body) { this.id = id; this.entityName = entityName; this.body = body; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEntityName() { return entityName; } public void setEntityName(String entityName) { this.entityName = entityName; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } }
/* 1: */ package com.kaldin.user.register.dao.impl; /* 2: */ /* 3: */ import com.kaldin.user.register.dao.TechInfoInterface; /* 4: */ import com.kaldin.user.register.dto.TechInfoDTO; /* 5: */ import com.kaldin.user.register.hibernate.TechInfoHibernate; /* 6: */ import java.util.List; /* 7: */ /* 8: */ public class TechInfoImplementor /* 9: */ implements TechInfoInterface /* 10: */ { /* 11:10 */ TechInfoHibernate hiber = new TechInfoHibernate(); /* 12: */ /* 13: */ public boolean save(TechInfoDTO dtoObj) /* 14: */ { /* 15:12 */ if (this.hiber.save(dtoObj)) { /* 16:13 */ return true; /* 17: */ } /* 18:15 */ return false; /* 19: */ } /* 20: */ /* 21: */ public boolean delete(TechInfoDTO dtoObj) /* 22: */ { /* 23:21 */ if (this.hiber.delete(dtoObj)) { /* 24:22 */ return true; /* 25: */ } /* 26:24 */ return false; /* 27: */ } /* 28: */ /* 29: */ public List<?> show() /* 30: */ { /* 31:29 */ List<?> listObj = this.hiber.show(); /* 32:30 */ return listObj; /* 33: */ } /* 34: */ /* 35: */ public List<?> getTechnology(int userId) /* 36: */ { /* 37:35 */ return this.hiber.getTechnology(userId); /* 38: */ } /* 39: */ /* 40: */ public List<?> getTechRecord(int candId) /* 41: */ { /* 42:38 */ return this.hiber.getTechRecord(candId); /* 43: */ } /* 44: */ /* 45: */ public String getJSONTList(List dtoList) /* 46: */ { /* 47:43 */ return this.hiber.getJSONTList(dtoList); /* 48: */ } /* 49: */ /* 50: */ public String getJSONTList() /* 51: */ { /* 52:46 */ return this.hiber.getJSONTList(); /* 53: */ } /* 54: */ /* 55: */ public boolean editTechnology(TechInfoDTO techInfodto) /* 56: */ { /* 57:50 */ return this.hiber.editTechnology(techInfodto); /* 58: */ } /* 59: */ /* 60: */ public List<?> getTechnologyList(int companyid) /* 61: */ { /* 62:54 */ return this.hiber.getTechnologyList(companyid); /* 63: */ } /* 64: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.user.register.dao.impl.TechInfoImplementor * JD-Core Version: 0.7.0.1 */
//Servlet służący do dodania folderu package vs.api.serlvets; import vs.api.helpers.FoldersController; import vs.api.helpers.InitializerSessionObject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @WebServlet("/AddDirectoryServlet") public class AddDirectoryServlet extends HttpServlet { HttpSession _session; FoldersController _folderController; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { _session = request.getSession(); String id = InitializerSessionObject.initialize(_session.getAttribute("id")); String currentPath = InitializerSessionObject.initialize(_session.getAttribute("folderPath")); String folderName = InitializerSessionObject.initialize(request.getParameter("folderName")); _folderController = new FoldersController(id, currentPath); _folderController.addFolder(folderName); response.sendRedirect("mainpage.jsp"); } }
package com.tt.miniapp.business.component.video.fullscreen; import com.tt.miniapp.base.MiniAppContext; import com.tt.miniapp.page.AppbrandSinglePage; import com.tt.miniapp.page.AppbrandViewWindowBase; public class SwipeBackTransaction extends FullScreenTransaction { private boolean mDisableGesture; public SwipeBackTransaction(MiniAppContext paramMiniAppContext) { super(paramMiniAppContext); } public void enterFullScreen() { AppbrandSinglePage appbrandSinglePage = getCurrentPage(); if (appbrandSinglePage == null) return; AppbrandViewWindowBase appbrandViewWindowBase = appbrandSinglePage.getHost(); if (appbrandViewWindowBase == null) return; if (appbrandViewWindowBase.isDragEnabled()) { appbrandViewWindowBase.setDragEnable(false); this.mDisableGesture = true; } } public void exitFullScreen() { if (!this.mDisableGesture) return; AppbrandSinglePage appbrandSinglePage = getCurrentPage(); if (appbrandSinglePage == null) return; AppbrandViewWindowBase appbrandViewWindowBase = appbrandSinglePage.getHost(); if (appbrandViewWindowBase == null) return; appbrandViewWindowBase.setDragEnable(true); this.mDisableGesture = false; } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\business\component\video\fullscreen\SwipeBackTransaction.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.pangpang6.utils.config; /** * Created by jiangjg on 2017/6/7. */ public interface ConfigManager { /** * Get the config instance for the namespace specified. * @param namespace the namespace * @return the config instance for the namespace */ public Config getConfig(String namespace); /** * Get the config file instance for the namespace specified. * @param namespace the namespace * @param configFileFormat the config file format * @return the config file instance for the namespace */ public ConfigFile getConfigFile(String namespace, ConfigFileFormat configFileFormat); }
package com.ssafy.day23; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /* ACMICPC 문제 번호 : 17070 문제 제목 : 파이프 옮기기 1 풀이 날짜 : 2020-09-23 Solved By Reamer */ public class acm_17070 { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int N = Integer.parseInt(br.readLine()); int[][] map = new int[N][N]; for (int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine()); for (int j = 0; j < N; j++) { map[i][j] = Integer.parseInt(st.nextToken()); } } int[][][] dp = new int[N][N][3]; dp[0][1][0] = 1; for (int i = 0; i < N; i++) { for (int j = 1; j < N; j++) { if(map[i][j]==1) continue; for (int k = 0; k < 3; k++) { switch (k) { case 0: dp[i][j][k] += dp[i][j - 1][0] + dp[i][j - 1][1]; break; case 1: if (i - 1 >= 0) { if (map[i - 1][j] == 0 && map[i][j - 1] == 0) { dp[i][j][k] += dp[i - 1][j - 1][0] + dp[i - 1][j - 1][1] + dp[i - 1][j - 1][2]; } } break; case 2: if (i - 1 >= 0) dp[i][j][k] += dp[i - 1][j][1] + dp[i - 1][j][2]; break; } } } } int sum = 0; for (int i = 0; i < 3; i++) { sum += dp[N - 1][N - 1][i]; } System.out.println(sum); } }
public class FollowPathRobot2 { private RobotCommunication robotcomm; // communication drivers /** * Create a robot connected to host "host" at port "port" * @param host normally http://127.0.0.1 * @param port normally 50000 */ public FollowPathRobot2(String host, int port) { robotcomm = new RobotCommunication(host, port); } public static void main(String[] args) throws Exception { ReadPath readPath = new ReadPath(args[0]); //int pathsize = readPath.PathSize(); Position[] path = readPath.GetPath(); System.out.println("position " + path[0].getX() + "," + path[0].getY()); System.out.println("Creating Robot"); FollowPathRobot2 robot = new FollowPathRobot2("http://127.0.0.1", 50000); // robot.run(path, pathsize); } public void run(Position[] path, int pathSize) throws Exception{ System.out.println("Creating response"); LocalizationResponse lr = new LocalizationResponse(); System.out.println("Creating request"); DifferentialDriveRequest dr = new DifferentialDriveRequest(); System.out.println("path size "+pathSize); for(int i =0; i < pathSize; i++){ robotcomm.getResponse(lr); Position robotsPosition = new Position(lr.getPosition()[0], lr.getPosition()[1]); if (robotsPosition.getDistanceTo(path[i])< 0.3) { System.out.println("distance " +robotsPosition.getDistanceTo(path[i])); if(lr.getHeadingAngle() - robotsPosition.getBearingTo(path[1]) > 0.2 || robotsPosition.getBearingTo(path[1])- lr.getHeadingAngle() > 0.2){ dr.setLinearSpeed(0); robotcomm.putRequest(dr); rotateRobot(i, robotsPosition, dr, lr, path); dr.setLinearSpeed(0.3); robotcomm.putRequest(dr); } else{ dr.setLinearSpeed(0.3); dr.setAngularSpeed(0); robotcomm.putRequest(dr); } } else { dr.setLinearSpeed(0.3); dr.setAngularSpeed(0); robotcomm.putRequest(dr); } } } public void rotateRobot(int i, Position robotsPosition, DifferentialDriveRequest dr, LocalizationResponse lr, Position[] path)throws Exception{ /*double bearingPoint = robotsPosition.getBearingTo(path[i]); System.out.println(lr.getHeadingAngle()- bearingPoint); if ((bearingPoint + Math.PI) > (lr.getHeadingAngle() + Math.PI)){ if ((lr.getHeadingAngle()-bearingPoint )< Math.PI) { TurnLeft(lr,dr,bearingPoint); } else{ TurnRight(lr,dr,bearingPoint); } } else if((bearingPoint - lr.getHeadingAngle()) < Math.PI){ if((bearingPoint - lr.getHeadingAngle()) < Math.PI){ TurnRight(lr,dr,bearingPoint); } else{ TurnLeft(lr,dr,bearingPoint); } } if (lr.getHeadingAngle()-bearingPoint > 0){ TurnRight(lr,dr,bearingPoint); } else { TurnLeft(lr,dr,bearingPoint); }*/ } public void TurnRight(LocalizationResponse lr, DifferentialDriveRequest dr, double bearingPoint)throws Exception{ while ((lr.getHeadingAngle()- bearingPoint) < 0){ dr.setAngularSpeed(-0.3); robotcomm.putRequest(dr); robotcomm.getResponse(lr); } dr.setAngularSpeed(0); robotcomm.putRequest(dr); } public void TurnLeft(LocalizationResponse lr, DifferentialDriveRequest dr, double bearingPoint)throws Exception{ while (bearingPoint > lr.getHeadingAngle()){ dr.setAngularSpeed(0.3); robotcomm.putRequest(dr); robotcomm.getResponse(lr); } dr.setAngularSpeed(0); robotcomm.putRequest(dr); } }
package biz.mydailyhoroscope; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Color; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.appbrain.AppBrain; import com.facebook.ads.AdSize; import com.facebook.ads.AdView; import com.facebook.ads.InterstitialAd; import com.firebase.jobdispatcher.FirebaseJobDispatcher; import com.firebase.jobdispatcher.GooglePlayDriver; import com.firebase.jobdispatcher.Job; import com.firebase.jobdispatcher.Lifetime; import com.firebase.jobdispatcher.RetryStrategy; import com.firebase.jobdispatcher.Trigger; import com.google.firebase.analytics.FirebaseAnalytics; import net.lucode.hackware.magicindicator.MagicIndicator; import net.lucode.hackware.magicindicator.ViewPagerHelper; import net.lucode.hackware.magicindicator.buildins.UIUtil; import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView; import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView; import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView; import java.text.SimpleDateFormat; import java.util.Calendar; import butterknife.BindView; import butterknife.ButterKnife; /** * @author Dominik Erbsland * @since 2012, 2018 */ public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private static final String TAG = MainActivity.class.getSimpleName(); @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.tv_zodiac_sign) TextView zodiacSignMain; @BindView(R.id.img_zodiac_sign) ImageView ivZodiacSign; @BindView(R.id.drawer_layout) DrawerLayout mDrawerLayout; @BindView(R.id.nav_view) NavigationView navigationView; @BindView(R.id.viewpager) ViewPager mPager; @BindView(R.id.indicator) MagicIndicator indicator; @BindView(R.id.banner_container) LinearLayout facebookBanner; private AdView adView; private SharedPreferences prefs; private Editor editor; private int daysOffset = 0; boolean isFromNotificationBar; private HoroscopeFragmentAdapter mHoroscopeAdapter; private ActionBarDrawerToggle actionBarDrawerToggle; private InterstitialAd interstitialAd; private String[] daysOfTheWeek; private Typeface robotoTypefaceBold; private SimpleDateFormat formatter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ButterKnife.bind(this); init(); initFacebookAds(); initialisePaging(); zodiacSignMain.setTypeface(robotoTypefaceBold); actionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close); mDrawerLayout.addDrawerListener(actionBarDrawerToggle); mDrawerLayout.closeDrawers(); mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); actionBarDrawerToggle.syncState(); navigationView.setNavigationItemSelectedListener(this); isFromNotificationBar = getIntent().getBooleanExtra("fromNotificationBar", false); // Reset visible page to "today" at first run editor.putInt(Helpers.PREFERENCES_PAGE_SELECTED, -(Helpers.MAX_DAY_OFFSET_VALUE)); editor.apply(); // Deleting Icon in Notification Bar (if visible) NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancelAll(); if (prefs.getBoolean(Helpers.PREFERENCES_IS_FIRST_RUN, true)) { editor.putBoolean(Helpers.HAS_NOTIFICATION_ALREADY_DISPLAYED_KEY, true); editor.putBoolean(Helpers.PREFERENCES_IS_FIRST_RUN, false); editor.apply(); Helpers.preBirthdatePicker(this, prefs, false); } else { // Birthdate is set if ((prefs.getInt(Helpers.PREFERENCES_BIRTH_DAY, -1) != -1) && (prefs.getInt(Helpers.PREFERENCES_BIRTH_MONTH, -1) != -1)) { int newZodiac = Helpers.getZodiacSign(MainActivity.this, prefs.getInt(Helpers.PREFERENCES_BIRTH_DAY, -1), prefs.getInt(Helpers.PREFERENCES_BIRTH_MONTH, -1)); zodiacSignMain.setText(newZodiac); ivZodiacSign.setImageResource(Helpers.getZodiacSignMainGraphic(newZodiac)); // if (isFromNotificationBar == false) { // if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) != prefs.getInt(Helpers.PREFERENCES_HOUR, 24)) { // alarm.setAlarm(this); // } // } } else { Helpers.preBirthdatePicker(this, prefs, false); } } if (!prefs.getBoolean(Helpers.PREFERENCES_HAS_AGREED_TERMS_AND_CONDITIONS, false)) { Helpers.privacyPolicy(this, editor); } launchBackgroundJob(); } private void init() { prefs = getSharedPreferences(Helpers.PREFERENCES_FILE, MODE_PRIVATE); editor = prefs.edit(); // Initialize the Tracking Utils TrackingUtils.getInstance().init(this); robotoTypefaceBold = Typeface.createFromAsset(getAssets(), "Roboto-Bold.ttf"); formatter = new java.text.SimpleDateFormat("EEEE"); // Wochentag ausgeschrieben AppBrain.init(this); if (mToolbar != null) { setSupportActionBar(mToolbar); } getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); daysOfTheWeek = new String[7]; // [6] = today Calendar cal2 = Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, -6); daysOfTheWeek[0] = formatter.format(cal2.getTime()); Calendar cal3 = Calendar.getInstance(); cal3.add(Calendar.DAY_OF_MONTH, -5); daysOfTheWeek[1] = formatter.format(cal3.getTime()); Calendar cal4 = Calendar.getInstance(); cal4.add(Calendar.DAY_OF_MONTH, -4); daysOfTheWeek[2] = formatter.format(cal4.getTime()); Calendar cal5 = Calendar.getInstance(); cal5.add(Calendar.DAY_OF_MONTH, -3); daysOfTheWeek[3] = formatter.format(cal5.getTime()); Calendar cal6 = Calendar.getInstance(); cal6.add(Calendar.DAY_OF_MONTH, -2); daysOfTheWeek[4] = formatter.format(cal6.getTime()); daysOfTheWeek[5] = getString(R.string.yesterday); daysOfTheWeek[6] = getString(R.string.today); } /** * Launches a repeating background task to notify the user about the new horoscope once a day (if not disabled) */ private void launchBackgroundJob() { FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this)); Bundle myExtrasBundle = new Bundle(); myExtrasBundle.putInt("task_id", 3); Job myJob = dispatcher.newJobBuilder() .setService(MyJobService.class) .setTag("notify_new_horoscope") .setRecurring(true) .setTrigger(Trigger.executionWindow(0, 60)) .setLifetime(Lifetime.FOREVER) .setReplaceCurrent(true) .setRetryStrategy(RetryStrategy.DEFAULT_LINEAR) .setExtras(myExtrasBundle) .build(); dispatcher.mustSchedule(myJob); } private void initFacebookAds() { // Banner adView = new AdView(this, Helpers.FACEBOOK_AUDIENCE_NETWORK_NATIVE_BANNER_ID, AdSize.BANNER_HEIGHT_50); facebookBanner.addView(adView); adView.loadAd(); // Interstitial interstitialAd = new InterstitialAd(this, Helpers.FACEBOOK_AUDIENCE_NETWORK_INTERSTITIAL_ID); interstitialAd.loadAd(); } @Override public void finish() { ViewGroup view = (ViewGroup) getWindow().getDecorView(); view.removeAllViews(); super.finish(); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); // Only gets executed if relevant settings have been changed if (prefs.getBoolean(Helpers.PREFERENCES_HAVE_CHANGED, false)) { editor.putBoolean(Helpers.PREFERENCES_HAVE_CHANGED, false); editor.commit(); if ((prefs.getInt(Helpers.PREFERENCES_BIRTH_DAY, -1) != -1) && (prefs.getInt(Helpers.PREFERENCES_BIRTH_MONTH, -1) != -1)) { int newZodiac = Helpers.getZodiacSign(MainActivity.this, prefs.getInt(Helpers.PREFERENCES_BIRTH_DAY, -1), prefs.getInt(Helpers.PREFERENCES_BIRTH_MONTH, -1)); zodiacSignMain.setText(newZodiac); ivZodiacSign.setImageResource(Helpers.getZodiacSignMainGraphic(newZodiac)); initialisePaging(); } else { Helpers.preBirthdatePicker(this, prefs, false); } } } private void initialisePaging() { try { mHoroscopeAdapter = new HoroscopeFragmentAdapter(getSupportFragmentManager(), daysOfTheWeek); mPager.setAdapter(mHoroscopeAdapter); int pageSelected = prefs.getInt(Helpers.PREFERENCES_PAGE_SELECTED, mHoroscopeAdapter.getCount() - 1); if (pageSelected > mHoroscopeAdapter.getCount() - 1) { pageSelected = mHoroscopeAdapter.getCount() - 1; // Today } mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { daysOffset = Helpers.positionSwitch(position); if (daysOffset == -1) { // SHOW INTERSTITIAL BEFORE YESTERDAY'S HOROSCOPE interstitialAd.show(); } } @Override public void onPageScrollStateChanged(int state) { } }); CommonNavigator commonNavigator = new CommonNavigator(this); commonNavigator.setSkimOver(true); commonNavigator.setAdapter(new CommonNavigatorAdapter() { @Override public int getCount() { return MainActivity.this.daysOfTheWeek == null ? 0 : MainActivity.this.daysOfTheWeek.length; } @Override public IPagerTitleView getTitleView(Context context, final int index) { SimplePagerTitleView clipPagerTitleView = new ColorTransitionPagerTitleView(context); clipPagerTitleView.setText(MainActivity.this.daysOfTheWeek[index]); clipPagerTitleView.setNormalColor(Color.parseColor("#88ffffff")); // White transparent clipPagerTitleView.setSelectedColor(Color.WHITE); clipPagerTitleView.setTextSize(20f); clipPagerTitleView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPager.setCurrentItem(index); } }); return clipPagerTitleView; } @Override public IPagerIndicator getIndicator(Context context) { LinePagerIndicator indicator = new LinePagerIndicator(context); indicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT); indicator.setYOffset(UIUtil.dip2px(context, 3)); indicator.setColors(Color.WHITE); // Indicator Line return indicator; } }); indicator.setNavigator(commonNavigator); mPager.setCurrentItem(pageSelected); ViewPagerHelper.bind(indicator, mPager); } catch (Exception e2) { Log.e(MainActivity.class.getSimpleName(), getPackageName() + "/" + getTitle() + "... " + e2.getMessage()); } } @Override public void onBackPressed() { AppBrain.getAds().shouldShowInterstitial(this); finish(); } @Override protected void onDestroy() { if (adView != null) { adView.destroy(); } if (interstitialAd != null) { interstitialAd.destroy(); } super.onDestroy(); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); Bundle bundle = new Bundle(); bundle.putInt(FirebaseAnalytics.Param.ITEM_ID, id); bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "navigation_drawer"); mDrawerLayout.closeDrawers(); editor.putInt(Helpers.PREFERENCES_SELECTED_DRAWER_FRAGMENT_ID, id); editor.commit(); switch (id) { case R.id.nav_birthdate: Helpers.preBirthdatePicker(this, prefs, true); bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "nav_birthdate"); break; case R.id.nav_time: Helpers.alertTimeSetttings(this, prefs); bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "nav_time"); break; case R.id.nav_sound: Helpers.soundSetttings(this, prefs); bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "nav_sound"); break; case R.id.nav_more: bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "nav_more"); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(FlavorValues.DEVELOPER_LINK)); startActivity(intent); break; case R.id.nav_terms: bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "nav_terms"); Helpers.privacyPolicy(this, editor); break; case R.id.nav_about: bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "nav_about"); Helpers.about(this); break; } FirebaseAnalytics.getInstance(this).logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle); return false; } }
package org.config.spring; /** * Created by yangyu on 2016/6/13. */ import java.io.IOException; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; public class JavaApiSample implements Watcher { private static final int SESSION_TIMEOUT = 30000; // private static final String CONNECTION_STRING = "test.zookeeper.connection_string:2181"; private static final String CONNECTION_STRING = "10.31.72.73:2181"; // private static final String CONNECTION_STRING = "127.0.0.1:2181"; private static final String ZK_PATH = "/yang"; private static final String JDBC_DATA = "jdbc.driverClassName#com.mysql.jdbc.Driver#" + "jdbc.url#jdbc:mysql://10.31.73.48:3306/hue?user=hue_user&password=hue_test&useUnicode=true&characterEncoding=UTF8#" + "jdbc.username#hue_user#" + "jdbc.password#hue_test#" + "jdbc.initialPoolSize#10#" + "jdbc.minPoolSize#2#" + "jdbc.maxPoolSize#30#"; private ZooKeeper zk = null; private CountDownLatch connectedSemaphore = new CountDownLatch( 1 ); /** * 鍒涘缓ZK杩炴帴 * @param connectString ZK鏈嶅姟鍣ㄥ湴鍧�垪琛� * @param sessionTimeout Session瓒呮椂鏃堕棿 */ public void createConnection( String connectString, int sessionTimeout ) { this.releaseConnection(); try { zk = new ZooKeeper( connectString, sessionTimeout, this ); connectedSemaphore.await(); } catch ( InterruptedException e ) { System.out.println( "杩炴帴鍒涘缓澶辫触锛屽彂鐢�InterruptedException" ); e.printStackTrace(); } catch ( IOException e ) { System.out.println( "杩炴帴鍒涘缓澶辫触锛屽彂鐢�IOException" ); e.printStackTrace(); } } /** * 鍏抽棴ZK杩炴帴 */ public void releaseConnection() { if ( this.zk != null ) { try { this.zk.close(); } catch ( InterruptedException e ) { // ignore e.printStackTrace(); } } } /** * 鍒涘缓鑺傜偣 * @param path 鑺傜偣path * @param data 鍒濆鏁版嵁鍐呭 * @return */ public boolean createPath( String path, String data ) { try { this.zk.create( path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT ); // System.out.println( "鑺傜偣鍒涘缓鎴愬姛, Path: "+ this.zk.create( path,data.getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL )+ ", content: " + data ); } catch ( KeeperException e ) { System.out.println( "鑺傜偣鍒涘缓澶辫触锛屽彂鐢烱eeperException" ); e.printStackTrace(); } catch ( InterruptedException e ) { System.out.println( "鑺傜偣鍒涘缓澶辫触锛屽彂鐢�InterruptedException" ); e.printStackTrace(); } return true; } /** * 璇诲彇鎸囧畾鑺傜偣鏁版嵁鍐呭 * @param path 鑺傜偣path * @return */ public String readData( String path ) { try { System.out.println( "鑾峰彇鏁版嵁鎴愬姛锛宲ath锛�"+ path ); return new String( this.zk.getData( path, false, null ) ); } catch ( KeeperException e ) { System.out.println( "璇诲彇鏁版嵁澶辫触锛屽彂鐢烱eeperException锛宲ath: " + path ); e.printStackTrace(); return ""; } catch ( InterruptedException e ) { System.out.println( "璇诲彇鏁版嵁澶辫触锛屽彂鐢�InterruptedException锛宲ath: " + path ); e.printStackTrace(); return ""; } } /** * 鏇存柊鎸囧畾鑺傜偣鏁版嵁鍐呭 * @param path 鑺傜偣path * @param data 鏁版嵁鍐呭 * @return */ public boolean writeData( String path, String data ) { try { System.out.println( "鏇存柊鏁版嵁鎴愬姛锛宲ath锛"+ path + ", stat: " + this.zk.setData( path, data.getBytes(), -1 ) ); } catch ( KeeperException e ) { System.out.println( "鏇存柊鏁版嵁澶辫触锛屽彂鐢烱eeperException锛宲ath: " + path ); e.printStackTrace(); } catch ( InterruptedException e ) { System.out.println( "鏇存柊鏁版嵁澶辫触锛屽彂鐢�InterruptedException锛宲ath: " + path ); e.printStackTrace(); } return false; } /** * 鍒犻櫎鎸囧畾鑺傜偣 * @param path 鑺傜偣path */ public void deleteNode( String path ) { try { this.zk.delete( path, -1 ); System.out.println( "鍒犻櫎鑺傜偣鎴愬姛锛宲ath锛�"+ path ); } catch ( KeeperException e ) { System.out.println( "鍒犻櫎鑺傜偣澶辫触锛屽彂鐢烱eeperException锛宲ath: " + path ); e.printStackTrace(); } catch ( InterruptedException e ) { System.out.println( "鍒犻櫎鑺傜偣澶辫触锛屽彂鐢�InterruptedException锛宲ath: " + path ); e.printStackTrace(); } } public static void main( String[] args ) { JavaApiSample sample = new JavaApiSample(); sample.createConnection( CONNECTION_STRING, SESSION_TIMEOUT ); // if ( sample.createPath( ZK_PATH, "鎴戞槸鑺傜偣鍒濆鍐呭" ) ) { sample.createPath( ZK_PATH, JDBC_DATA); System.out.println("鏁版嵁鍐呭: " + sample.readData(ZK_PATH) + "\n" ); // System.out.println( "鏁版嵁鍐呭: " + sample.readData( ZK_PATH ) + "\n" ); // sample.writeData( ZK_PATH, "鏇存柊鍚庣殑鏁版嵁" ); // System.out.println( "鏁版嵁鍐呭: " + sample.readData( ZK_PATH ) + "\n" ); // sample.deleteNode( ZK_PATH ); // } // sample.releaseConnection(); } /** * 鏀跺埌鏉ヨ嚜Server鐨刉atcher閫氱煡鍚庣殑澶勭悊銆� */ public void process( WatchedEvent event ) { System.out.println( "鏀跺埌浜嬩欢閫氱煡锛"+ event.getState() +"\n" ); if ( KeeperState.SyncConnected == event.getState() ) { connectedSemaphore.countDown(); } } }
package com.rishi.baldawa.iq; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MaxProfitFromStocksSingleTransactionTest { @Test public void maxProfit() throws Exception { assertEquals(new MaxProfitFromStocksSingleTransaction().maxProfit(new int[]{7, 1, 5, 3, 6, 4}), 5); } }
/* * To change this li @Override public int getWidth(ImageObserver observer) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public int getHeight(ImageObserver observer) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public ImageProducer getSource() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Graphics getGraphics() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Object getProperty(String name, ImageObserver observer) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } cense header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package BankSystem; /** * * @author iktakhairul */ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.*; import java.util.Random; import javax.swing.JOptionPane; public class AboutMe extends javax.swing.JFrame { Connection conn; ResultSet rs; PreparedStatement pst; /** * Creates new form AccountResister */ public AboutMe() { super("AboutMe"); initComponents(); conn=javaconnect.ConnecrDb(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { AboutMe = new javax.swing.JPanel(); jTextField2 = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jButton5 = new javax.swing.JButton(); quita = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jTextField4 = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jTextField5 = new javax.swing.JTextField(); jTextField6 = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jTextField7 = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jTextField8 = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jTextField9 = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField11 = new javax.swing.JTextField(); jTextField12 = new javax.swing.JTextField(); jTextField13 = new javax.swing.JTextField(); jTextField14 = new javax.swing.JTextField(); jTextField15 = new javax.swing.JTextField(); jTextField16 = new javax.swing.JTextField(); jTextField17 = new javax.swing.JTextField(); jTextField18 = new javax.swing.JTextField(); jPanel4 = new javax.swing.JPanel(); jTextField10 = new javax.swing.JTextField(); jPanel5 = new javax.swing.JPanel(); jLabel11 = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem4 = new javax.swing.JMenuItem(); jMenuItem5 = new javax.swing.JMenuItem(); jMenuItem6 = new javax.swing.JMenuItem(); jMenuItem7 = new javax.swing.JMenuItem(); jMenuItem12 = new javax.swing.JMenuItem(); jMenuItem8 = new javax.swing.JMenuItem(); jMenuItem13 = new javax.swing.JMenuItem(); jMenuItem11 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(204, 204, 204)); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setPreferredSize(new java.awt.Dimension(1400, 800)); setSize(new java.awt.Dimension(1378, 750)); getContentPane().setLayout(null); AboutMe.setBackground(new java.awt.Color(0, 0, 0)); AboutMe.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 153, 51), 3, true), "About Me", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Lucida Grande", 1, 24), new java.awt.Color(0, 255, 255))); // NOI18N AboutMe.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jTextField2.setEditable(false); jTextField2.setBackground(new java.awt.Color(0,0,0,0)); jTextField2.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jTextField2.setForeground(new java.awt.Color(51, 255, 51)); jTextField2.setText("Devoloper Profile and Information"); jTextField2.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jTextField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField2ActionPerformed(evt); } }); AboutMe.add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(31, 38, 350, 30)); jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/ikta.jpg"))); // NOI18N AboutMe.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 40, 190, 280)); jLabel2.setBackground(new java.awt.Color(0, 0, 0)); jLabel2.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Name"); jLabel2.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel2.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel2.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(107, 91, 105, 36)); jLabel3.setBackground(new java.awt.Color(0, 0, 0)); jLabel3.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Facebook"); jLabel3.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel3.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel3.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(107, 313, 105, 31)); jLabel4.setBackground(new java.awt.Color(0, 0, 0)); jLabel4.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("Student ID"); jLabel4.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel4.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel4.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(107, 142, 105, 31)); jTextField3.setEditable(false); jTextField3.setBackground(new java.awt.Color(0, 0, 0)); jTextField3.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField3.setForeground(new java.awt.Color(255, 255, 255)); jTextField3.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField3.setText("Computer Science"); jTextField3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); AboutMe.add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 231, 275, 36)); jButton5.setBackground(new java.awt.Color(0, 204, 204)); jButton5.setText("jButton5"); AboutMe.add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 100, 1, 380)); quita.setBackground(new java.awt.Color(0, 0, 0)); quita.setForeground(new java.awt.Color(0, 255, 255)); quita.setText("Exit"); quita.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { quitaActionPerformed(evt); } }); AboutMe.add(quita, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 510, 98, -1)); jButton1.setBackground(new java.awt.Color(0, 0, 0)); jButton1.setForeground(new java.awt.Color(0, 255, 255)); jButton1.setText("Contact Me"); AboutMe.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(690, 510, 106, -1)); jButton2.setBackground(new java.awt.Color(0, 0, 0)); jButton2.setForeground(new java.awt.Color(0, 255, 255)); jButton2.setText("Back"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); AboutMe.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 510, 105, -1)); jButton4.setBackground(new java.awt.Color(0, 204, 204)); AboutMe.add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 280, 820, 1)); jTextField4.setEditable(false); jTextField4.setBackground(new java.awt.Color(0, 0, 0)); jTextField4.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField4.setForeground(new java.awt.Color(255, 255, 255)); jTextField4.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField4.setText("Shah Md. Iktakhairul Islam"); jTextField4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); jTextField4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField4ActionPerformed(evt); } }); AboutMe.add(jTextField4, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 92, 275, 36)); jLabel5.setBackground(new java.awt.Color(0, 0, 0)); jLabel5.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("Department"); jLabel5.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel5.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel5.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(107, 236, 105, 31)); jTextField5.setEditable(false); jTextField5.setBackground(new java.awt.Color(0, 0, 0)); jTextField5.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField5.setForeground(new java.awt.Color(255, 255, 255)); jTextField5.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField5.setText("171-15-8606"); jTextField5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); jTextField5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField5ActionPerformed(evt); } }); AboutMe.add(jTextField5, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 140, 275, 35)); jTextField6.setEditable(false); jTextField6.setBackground(new java.awt.Color(0, 0, 0)); jTextField6.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField6.setForeground(new java.awt.Color(255, 255, 255)); jTextField6.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField6.setText("www.facebook.com/iktakhairul"); jTextField6.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); AboutMe.add(jTextField6, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 308, 275, 36)); jLabel6.setBackground(new java.awt.Color(0, 0, 0)); jLabel6.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("GitHub"); jLabel6.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel6.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel6.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(107, 359, 105, 31)); jTextField7.setEditable(false); jTextField7.setBackground(new java.awt.Color(0, 0, 0)); jTextField7.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField7.setForeground(new java.awt.Color(255, 255, 255)); jTextField7.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField7.setText("https://github.com/iktakhairul"); jTextField7.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); AboutMe.add(jTextField7, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 356, 275, 32)); jLabel7.setBackground(new java.awt.Color(0, 0, 0)); jLabel7.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 255, 255)); jLabel7.setText("Phone"); jLabel7.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel7.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel7.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(109, 403, 105, 31)); jTextField8.setEditable(false); jTextField8.setBackground(new java.awt.Color(0, 0, 0)); jTextField8.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField8.setForeground(new java.awt.Color(255, 255, 255)); jTextField8.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField8.setText("01683201359"); jTextField8.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); AboutMe.add(jTextField8, new org.netbeans.lib.awtextra.AbsoluteConstraints(232, 402, 273, 32)); jLabel8.setBackground(new java.awt.Color(0, 0, 0)); jLabel8.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel8.setForeground(new java.awt.Color(255, 255, 255)); jLabel8.setText("University"); AboutMe.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(107, 187, 105, 31)); jTextField9.setEditable(false); jTextField9.setBackground(new java.awt.Color(0, 0, 0)); jTextField9.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField9.setForeground(new java.awt.Color(255, 255, 255)); jTextField9.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField9.setText("Daffodill International University"); jTextField9.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); AboutMe.add(jTextField9, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 187, 275, 31)); jLabel10.setBackground(new java.awt.Color(0, 0, 0)); jLabel10.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel10.setForeground(new java.awt.Color(255, 255, 255)); jLabel10.setText("Nike Name"); jLabel10.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jLabel10.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel10.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel10.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(546, 94, 105, 31)); jLabel12.setBackground(new java.awt.Color(0, 0, 0)); jLabel12.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel12.setForeground(new java.awt.Color(255, 255, 255)); jLabel12.setText("Batch"); jLabel12.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jLabel12.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel12.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel12.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(546, 142, 105, 31)); jLabel13.setBackground(new java.awt.Color(0, 0, 0)); jLabel13.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel13.setForeground(new java.awt.Color(255, 255, 255)); jLabel13.setText("Skills"); jLabel13.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jLabel13.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel13.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel13.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(546, 187, 105, 31)); jLabel14.setBackground(new java.awt.Color(0, 0, 0)); jLabel14.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel14.setForeground(new java.awt.Color(255, 255, 255)); jLabel14.setText("NID"); jLabel14.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jLabel14.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel14.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel14.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(546, 233, 105, 31)); jLabel15.setBackground(new java.awt.Color(0, 0, 0)); jLabel15.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel15.setForeground(new java.awt.Color(255, 255, 255)); jLabel15.setText("Blood Group"); jLabel15.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jLabel15.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel15.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel15.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(546, 310, 105, 31)); jLabel16.setBackground(new java.awt.Color(0, 0, 0)); jLabel16.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel16.setForeground(new java.awt.Color(255, 255, 255)); jLabel16.setText("Date of Birth"); jLabel16.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jLabel16.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel16.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel16.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(546, 356, 105, 31)); jLabel17.setBackground(new java.awt.Color(0, 0, 0)); jLabel17.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel17.setForeground(new java.awt.Color(255, 255, 255)); jLabel17.setText("Country"); jLabel17.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jLabel17.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel17.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel17.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(546, 402, 105, 31)); jLabel18.setBackground(new java.awt.Color(0, 0, 0)); jLabel18.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel18.setForeground(new java.awt.Color(255, 255, 255)); jLabel18.setText("Gmail"); jLabel18.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jLabel18.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel18.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel18.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel18, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 450, 105, 31)); jLabel19.setBackground(new java.awt.Color(0, 0, 0)); jLabel19.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel19.setForeground(new java.awt.Color(255, 255, 255)); jLabel19.setText("Address"); jLabel19.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jLabel19.setMaximumSize(new java.awt.Dimension(67, 17)); jLabel19.setMinimumSize(new java.awt.Dimension(67, 17)); jLabel19.setPreferredSize(new java.awt.Dimension(67, 17)); AboutMe.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(545, 450, 100, 31)); jTextField1.setEditable(false); jTextField1.setBackground(new java.awt.Color(0, 0, 0)); jTextField1.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField1.setForeground(new java.awt.Color(255, 255, 255)); jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField1.setText("iktakhairul@gmail.com"); jTextField1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); jTextField1.setPreferredSize(new java.awt.Dimension(242, 21)); AboutMe.add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 450, 273, 32)); jTextField11.setEditable(false); jTextField11.setBackground(new java.awt.Color(0, 0, 0)); jTextField11.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField11.setForeground(new java.awt.Color(255, 255, 255)); jTextField11.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField11.setText("Ikta"); jTextField11.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); jTextField11.setPreferredSize(new java.awt.Dimension(242, 21)); AboutMe.add(jTextField11, new org.netbeans.lib.awtextra.AbsoluteConstraints(669, 94, 265, 32)); jTextField12.setEditable(false); jTextField12.setBackground(new java.awt.Color(0, 0, 0)); jTextField12.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField12.setForeground(new java.awt.Color(255, 255, 255)); jTextField12.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField12.setText("46th"); jTextField12.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); jTextField12.setPreferredSize(new java.awt.Dimension(242, 21)); AboutMe.add(jTextField12, new org.netbeans.lib.awtextra.AbsoluteConstraints(669, 142, 265, 32)); jTextField13.setEditable(false); jTextField13.setBackground(new java.awt.Color(0, 0, 0)); jTextField13.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField13.setForeground(new java.awt.Color(255, 255, 255)); jTextField13.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField13.setText("0123456789"); jTextField13.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); jTextField13.setPreferredSize(new java.awt.Dimension(242, 21)); AboutMe.add(jTextField13, new org.netbeans.lib.awtextra.AbsoluteConstraints(669, 233, 265, 32)); jTextField14.setEditable(false); jTextField14.setBackground(new java.awt.Color(0, 0, 0)); jTextField14.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField14.setForeground(new java.awt.Color(255, 255, 255)); jTextField14.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField14.setText("Dhalapara,Tangail"); jTextField14.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); jTextField14.setPreferredSize(new java.awt.Dimension(242, 21)); AboutMe.add(jTextField14, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 450, 265, 32)); jTextField15.setEditable(false); jTextField15.setBackground(new java.awt.Color(0, 0, 0)); jTextField15.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField15.setForeground(new java.awt.Color(255, 255, 255)); jTextField15.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField15.setText("Bangladesh"); jTextField15.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); jTextField15.setPreferredSize(new java.awt.Dimension(242, 21)); AboutMe.add(jTextField15, new org.netbeans.lib.awtextra.AbsoluteConstraints(669, 402, 265, 32)); jTextField16.setEditable(false); jTextField16.setBackground(new java.awt.Color(0, 0, 0)); jTextField16.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField16.setForeground(new java.awt.Color(255, 255, 255)); jTextField16.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField16.setText("26-02-1997"); jTextField16.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); jTextField16.setPreferredSize(new java.awt.Dimension(242, 21)); AboutMe.add(jTextField16, new org.netbeans.lib.awtextra.AbsoluteConstraints(669, 356, 265, 32)); jTextField17.setEditable(false); jTextField17.setBackground(new java.awt.Color(0, 0, 0)); jTextField17.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField17.setForeground(new java.awt.Color(255, 255, 255)); jTextField17.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField17.setText("O+"); jTextField17.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); jTextField17.setPreferredSize(new java.awt.Dimension(242, 21)); AboutMe.add(jTextField17, new org.netbeans.lib.awtextra.AbsoluteConstraints(669, 310, 265, 32)); jTextField18.setEditable(false); jTextField18.setBackground(new java.awt.Color(0, 0, 0)); jTextField18.setFont(new java.awt.Font("Lucida Grande", 1, 15)); // NOI18N jTextField18.setForeground(new java.awt.Color(255, 255, 255)); jTextField18.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField18.setText("Java, C, Kali Linux"); jTextField18.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 102))); jTextField18.setPreferredSize(new java.awt.Dimension(242, 21)); AboutMe.add(jTextField18, new org.netbeans.lib.awtextra.AbsoluteConstraints(669, 187, 265, 32)); getContentPane().add(AboutMe); AboutMe.setBounds(220, 150, 1180, 570); jPanel4.setBackground(new java.awt.Color(0, 0, 0)); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 153, 153), 3, true), "My Comments", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Lucida Grande", 1, 24), new java.awt.Color(102, 255, 0))); // NOI18N jTextField10.setEditable(false); jTextField10.setBackground(new java.awt.Color(0,0,0,0) ); jTextField10.setForeground(new java.awt.Color(204, 204, 204)); jTextField10.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField10.setText("@2018Iktakhairul"); jTextField10.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jTextField10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField10ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(16, Short.MAX_VALUE) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(14, 14, 14)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(648, Short.MAX_VALUE) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(15, 15, 15)) ); getContentPane().add(jPanel4); jPanel4.setBounds(0, 0, 220, 720); jPanel5.setBackground(new java.awt.Color(0, 0, 0)); jPanel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jLabel11.setBackground(new java.awt.Color(0, 0, 0)); jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/AboutMe.jpg"))); // NOI18N jLabel11.setText("jLabel11"); jLabel11.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 153, 51), 3, true), "Humpty-Dumpty Bank Limited", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.ABOVE_BOTTOM, new java.awt.Font("Lucida Grande", 1, 60), new java.awt.Color(102, 255, 153))); // NOI18N javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 1178, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) ); getContentPane().add(jPanel5); jPanel5.setBounds(218, 0, 1180, 152); jMenuBar1.setBackground(new java.awt.Color(51, 51, 51)); jMenuBar1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jMenuBar1.setForeground(new java.awt.Color(204, 204, 204)); jMenu1.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.background")); jMenu1.setText(" Menu"); jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem1.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background")); jMenuItem1.setText(" Create Account"); jMenuItem1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)); jMenuItem1.setPreferredSize(new java.awt.Dimension(180, 18)); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem2.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background")); jMenuItem2.setText(" WithDraw"); jMenuItem2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)); jMenuItem2.setPreferredSize(new java.awt.Dimension(180, 18)); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem3.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background")); jMenuItem3.setText(" Diposite"); jMenuItem3.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)); jMenuItem3.setPreferredSize(new java.awt.Dimension(180, 18)); jMenu1.add(jMenuItem3); jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem4.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background")); jMenuItem4.setText(" Balance"); jMenuItem4.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)); jMenuItem4.setPreferredSize(new java.awt.Dimension(180, 18)); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem4ActionPerformed(evt); } }); jMenu1.add(jMenuItem4); jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem5.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background")); jMenuItem5.setText(" Transfer Money"); jMenuItem5.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)); jMenuItem5.setPreferredSize(new java.awt.Dimension(180, 18)); jMenuItem5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem5ActionPerformed(evt); } }); jMenu1.add(jMenuItem5); jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem6.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background")); jMenuItem6.setText(" Change PIN"); jMenuItem6.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)); jMenuItem6.setPreferredSize(new java.awt.Dimension(180, 18)); jMenuItem6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem6ActionPerformed(evt); } }); jMenu1.add(jMenuItem6); jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem7.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background")); jMenuItem7.setText(" Home"); jMenuItem7.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)); jMenuItem7.setPreferredSize(new java.awt.Dimension(180, 18)); jMenuItem7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem7ActionPerformed(evt); } }); jMenu1.add(jMenuItem7); jMenuItem12.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem12.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background")); jMenuItem12.setText(" Delete Account"); jMenuItem12.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)); jMenuItem12.setPreferredSize(new java.awt.Dimension(180, 18)); jMenuItem12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem12ActionPerformed(evt); } }); jMenu1.add(jMenuItem12); jMenuItem8.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem8.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background")); jMenuItem8.setText(" Profile"); jMenuItem8.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)); jMenuItem8.setPreferredSize(new java.awt.Dimension(180, 18)); jMenuItem8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem8ActionPerformed(evt); } }); jMenu1.add(jMenuItem8); jMenuItem13.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, java.awt.event.InputEvent.META_MASK)); jMenuItem13.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background")); jMenuItem13.setText(" Help"); jMenuItem13.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)); jMenuItem13.setPreferredSize(new java.awt.Dimension(180, 18)); jMenuItem13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem13ActionPerformed(evt); } }); jMenu1.add(jMenuItem13); jMenuItem11.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, java.awt.event.InputEvent.META_MASK)); jMenuItem11.setBackground(javax.swing.UIManager.getDefaults().getColor("CheckBox.background")); jMenuItem11.setText(" Exit"); jMenuItem11.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)); jMenuItem11.setPreferredSize(new java.awt.Dimension(180, 18)); jMenuItem11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem11ActionPerformed(evt); } }); jMenu1.add(jMenuItem11); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); setBounds(0, 0, 1400, 822); }// </editor-fold>//GEN-END:initComponents private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField5ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField5ActionPerformed private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField4ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: BankMenu ob = new BankMenu(); setVisible(false); ob.setVisible(true); }//GEN-LAST:event_jButton2ActionPerformed private void quitaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitaActionPerformed // TODO add your handling code here: Home ob = new Home(); setVisible(false); ob.setVisible(true); }//GEN-LAST:event_quitaActionPerformed private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField2ActionPerformed private void jTextField10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField10ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField10ActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed // TODO add your handling code here: AccountResister ob = new AccountResister(); setVisible(false); ob.setVisible(true); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed // TODO add your handling code here: WithDraw ob = new WithDraw(); setVisible(false); ob.setVisible(true); }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed // TODO add your handling code here: Balance ob = new Balance(); setVisible(false); ob.setVisible(true); }//GEN-LAST:event_jMenuItem4ActionPerformed private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed // TODO add your handling code here: TransferMoney ob = new TransferMoney(); setVisible(false); ob.setVisible(true); }//GEN-LAST:event_jMenuItem5ActionPerformed private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed // TODO add your handling code here: ChangePIN ob = new ChangePIN(); setVisible(false); ob.setVisible(true); }//GEN-LAST:event_jMenuItem6ActionPerformed private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed // TODO add your handling code here: Home ob = new Home(); setVisible(false); ob.setVisible(true); }//GEN-LAST:event_jMenuItem7ActionPerformed private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed // TODO add your handling code here: Profile ob = new Profile(); setVisible(false); ob.setVisible(true); }//GEN-LAST:event_jMenuItem8ActionPerformed private void jMenuItem11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem11ActionPerformed // TODO add your handling code here: System.exit(0); }//GEN-LAST:event_jMenuItem11ActionPerformed private void jMenuItem12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem12ActionPerformed // TODO add your handling code here: DeleteAccount ob = new DeleteAccount(); setVisible(false); ob.setVisible(true); }//GEN-LAST:event_jMenuItem12ActionPerformed private void jMenuItem13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem13ActionPerformed // TODO add your handling code here: Help obh1 = new Help(); setVisible(false); obh1.setVisible(true); }//GEN-LAST:event_jMenuItem13ActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel AboutMe; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JMenu jMenu1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem11; private javax.swing.JMenuItem jMenuItem12; private javax.swing.JMenuItem jMenuItem13; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem4; private javax.swing.JMenuItem jMenuItem5; private javax.swing.JMenuItem jMenuItem6; private javax.swing.JMenuItem jMenuItem7; private javax.swing.JMenuItem jMenuItem8; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField10; private javax.swing.JTextField jTextField11; private javax.swing.JTextField jTextField12; private javax.swing.JTextField jTextField13; private javax.swing.JTextField jTextField14; private javax.swing.JTextField jTextField15; private javax.swing.JTextField jTextField16; private javax.swing.JTextField jTextField17; private javax.swing.JTextField jTextField18; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField7; private javax.swing.JTextField jTextField8; private javax.swing.JTextField jTextField9; private javax.swing.JButton quita; // End of variables declaration//GEN-END:variables }
package com.sporsimdi.action.facade; import java.util.List; import com.sporsimdi.model.entity.WebIletisim; import com.sporsimdi.model.type.Status; public interface WebIletisimFacade { public WebIletisim findById(long id); public List<WebIletisim> getAll(); public void persist(WebIletisim WebIletisim); public List<WebIletisim> getByStatus(Status status); public void remove(long id); public List<WebIletisim> listByModelId(Long modelId); }
package org.example.broker.core.service.broker.message; import lombok.RequiredArgsConstructor; import org.example.broker.api.domain.Client; import org.example.broker.api.domain.Message; import org.example.broker.core.converter.ClientConverter; import org.example.broker.core.converter.MessageConverter; import org.example.broker.core.repository.ClientRepository; import org.example.broker.core.repository.MessageRepository; import org.example.broker.core.service.broker.publisher.MessagePublisher; import org.example.broker.core.validator.MessageValidator; import org.example.broker.core.validator.ValidationException; import org.example.broker.core.validator.ValidationResult; import org.springframework.stereotype.Service; import java.util.Set; import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class BrokerMessageServiceImpl implements BrokerMessageService { private final ClientRepository clientRepository; private final MessageRepository messageRepository; private final MessageValidator messageValidator; private final ClientConverter clientConverter; private final MessageConverter messageConverter; @Override public void publish(MessagePublisher messagePublisher, String topic, Message message) { final ValidationResult validationResult = this.messageValidator.validate(message); if (!validationResult.isValid()) { throw new ValidationException(validationResult.getErrors()); } messageRepository.save(messageConverter.toEntity(message, topic)); final Set<Client> clients = clientRepository.findAllByTopic(topic).stream() .map(clientConverter::fromEntity) .collect(Collectors.toUnmodifiableSet()); messagePublisher.publishMessage(clients, message.getContent()); } }
package com.root.mssm.List.List.suggestionlist; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class SuggestionList { @SerializedName("status") @Expose private String status; @SerializedName("search_result") @Expose private List<SearchResult> searchResult = null; @SerializedName("search_cat") @Expose private List<SearchCat> searchCat = null; @SerializedName("search_sub") @Expose private List<SearchSub> searchSub = null; @SerializedName("search_child") @Expose private List<SearchChild> searchChild = null; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List<SearchResult> getSearchResult() { return searchResult; } public void setSearchResult(List<SearchResult> searchResult) { this.searchResult = searchResult; } public List<SearchCat> getSearchCat() { return searchCat; } public void setSearchCat(List<SearchCat> searchCat) { this.searchCat = searchCat; } public List<SearchSub> getSearchSub() { return searchSub; } public void setSearchSub(List<SearchSub> searchSub) { this.searchSub = searchSub; } public List<SearchChild> getSearchChild() { return searchChild; } public void setSearchChild(List<SearchChild> searchChild) { this.searchChild = searchChild; } }
package com.polytech.epulapp.tpandroidpolytech.services; import android.graphics.Bitmap; import android.os.AsyncTask; import android.widget.ImageView; import com.polytech.epulapp.tpandroidpolytech.models.Beer; import java.lang.ref.WeakReference; import java.net.URL; /** * Created by Epulapp on 29/12/2017. */ public class ThumbnailDownloadTask extends AsyncTask<URL, Void,Bitmap> { private final WeakReference<ImageView> imageViewReference; private Beer beer; public int progresspercent; public ThumbnailDownloadTask(ImageView thbView, Beer b) { imageViewReference = new WeakReference<ImageView>(thbView); this.beer = b; } @Override protected Bitmap doInBackground(URL... urls) { return Downloader.DownloadBitmap(urls[0]); } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } @Override protected void onPostExecute(Bitmap bitmap) { if (isCancelled()) { bitmap = null; } ImageView imageView = imageViewReference.get(); if (imageView != null) { if (bitmap != null) { imageView.setImageBitmap(bitmap); beer.setBeerThumbnail(bitmap); } } } private void setProgressPercent(int percent) { this.progresspercent = percent; } }
package com.ojas.rpo.security.entity; import org.codehaus.jackson.map.annotate.JsonView; import com.ojas.rpo.security.JsonViews; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import java.util.Date; /** * JPA Annotated Pojo that represents a blog post. * * @author Philip W. Sorst <philip@sorst.net> */ @Table(name="skill") @javax.persistence.Entity public class Skill implements Entity { @Id @GeneratedValue private Long id; @Column private Date date; @Column(unique=true) private String skillName; @Column private Boolean flag; public Boolean getFlag() { return flag; } public void setFlag(Boolean flag) { this.flag = flag; } public Skill() { this.date = new Date(); } @JsonView(JsonViews.Admin.class) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @JsonView(JsonViews.User.class) public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } @JsonView(JsonViews.User.class) public String getSkillName() { return skillName; } public void setSkillName(String skillName) { this.skillName = skillName; } @Override public String toString() { return String.format("Skill[%d, %s]", this.id,this.date, this.skillName); } }
package es.maltimor.genericRest; import java.util.Map; import javax.ws.rs.core.UriInfo; import es.maltimor.genericUser.User; /* * Esta clase es la que centraliza la seguridad de todo el servicio rest, delegara en GenericMapperInfoTable * la implementacion para poder definir la seguridad a nivel individual de tabla */ public class GenericSecurityDaoImpl implements GenericSecurityDao { private GenericMapperInfo info; public boolean canSelect(User user, String table, String filter,UriInfo ui) throws Exception { GenericMapperInfoTable infoT = info.getInfoTable(table); return infoT.getSecResolver().canSelect(user, table, infoT, filter); } public boolean canGetById(User user, String table, Object id,UriInfo ui) throws Exception { GenericMapperInfoTable infoT = info.getInfoTable(table); return infoT.getSecResolver().canGetById(user, table, infoT, id); } public boolean canInsert(User user, String table, Map<String, Object> data,UriInfo ui) throws Exception { GenericMapperInfoTable infoT = info.getInfoTable(table); return infoT.getSecResolver().canInsert(user, table, infoT, data); } public boolean canUpdate(User user, String table, Object id, Map<String, Object> data,UriInfo ui) throws Exception { GenericMapperInfoTable infoT = info.getInfoTable(table); return infoT.getSecResolver().canUpdate(user, table, infoT, id, data); } public boolean canDelete(User user, String table, Object id,UriInfo ui) throws Exception { GenericMapperInfoTable infoT = info.getInfoTable(table); return infoT.getSecResolver().canDelete(user, table, infoT, id); } public boolean canExecute(User user, String table, Map<String, Object> data,UriInfo ui) throws Exception { GenericMapperInfoTable infoT = info.getInfoTable(table); return infoT.getSecResolver().canExecute(user, table, infoT, data); } public GenericMapperInfo getInfo() { return info; } public void setInfo(GenericMapperInfo info) { this.info = info; } }
package com.wt.jiaduo.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.wt.jiaduo.dto.jpa.XiaomaiCongaibingBingqingpucha; public interface XiaomaiCongaibingBingqingpuchaDao extends JpaRepository<XiaomaiCongaibingBingqingpucha, Integer> { }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.test.util.browser; import org.chromium.base.ThreadUtils; import org.chromium.chrome.browser.EmptyTabObserver; import org.chromium.chrome.browser.Tab; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content_public.browser.LoadUrlParams; /** * Monitors that a Tab starts loading and stops loading a URL. */ public class TabLoadObserver extends EmptyTabObserver implements Criteria { private boolean mTabLoadStarted; private boolean mTabLoadStopped; public TabLoadObserver(final Tab tab, final String url) { tab.addObserver(this); ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { tab.loadUrl(new LoadUrlParams(url)); } }); } @Override public void onLoadStarted(Tab tab) { mTabLoadStarted = true; } @Override public void onLoadStopped(Tab tab) { mTabLoadStopped = true; } @Override public boolean isSatisfied() { return mTabLoadStarted && mTabLoadStopped; } }
package com.voksel.electric.pc.config; import com.voksel.electric.pc.component.AbstractMenuLoader; import com.voksel.electric.pc.component.MenuTreeItem; import com.voksel.electric.pc.security.AuthenticationService; import org.springframework.beans.factory.annotation.Autowired; import java.util.Collection; public class ApplicationMenuLoader extends AbstractMenuLoader{ @Autowired AuthenticationService authService; @Override protected Collection<MenuTreeItem> initializeMenuItems() { return authService.loadMenuItems(); } @Override public Collection<MenuTreeItem> loadByRole(String s) { return authService.loadMenuItemsByRole(s); } @Override public void afterPropertiesSet() throws Exception { } }
package com.julien.hansab.repository; import com.julien.hansab.domain.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.stereotype.Repository; @Repository public interface UsersRepository extends JpaRepository<User, Long>, QuerydslPredicateExecutor<User> { }
package enthu_l; public class e_1334{ public static void main(String args[] ){ A b = new B("good bye"); } } class A{ A() { this("hello", " world"); } A(String s) { System.out.println(s); } A(String s1, String s2){ this(s1 + s2); } } class B extends A{ B(){ super("good bye"); }; B(String s){ super(s, " world"); } B(String s1, String s2){ this(s1 + s2 + " ! "); } }
package me.buildcarter8.FreedomOpMod.Commands; import java.util.Arrays; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import me.buildcarter8.FreedomOpMod.FOPM_PluginLog; import me.buildcarter8.FreedomOpMod.FOPM_AdministratorList; import me.buildcarter8.FreedomOpMod.Main; public class Command_fopm extends FOPM_Command { private final Main plugin; public Command_fopm(Main plugin) { super("fopm", "fopm", "The main FOPM command.", PERM_MESSAGE, Arrays.asList("fom")); this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (args.length == 0) { sender.sendMessage(ChatColor.AQUA + "======" + ChatColor.GREEN + "FreedomOpMod" + ChatColor.AQUA + "======"); sender.sendMessage(ChatColor.GREEN + "Version " + Main.VERSION); sender.sendMessage(ChatColor.GREEN + "Created by buildcarter8 (Chief of Development Operations)"); sender.sendMessage(ChatColor.AQUA + "====================================================="); return true; } else if (args.length == 1) { if (args[0].equalsIgnoreCase("reload")) { if (!FOPM_AdministratorList.isUserAdmin(sender)) { msgNoPerms(sender); return true; } sender.sendMessage(ChatColor.GRAY + "Reloading FOPM"); try { Bukkit.getPluginManager().disablePlugin(plugin); Bukkit.getPluginManager().enablePlugin(plugin); } catch (Exception ex) { FOPM_PluginLog.severe(ex); } sender.sendMessage(ChatColor.GRAY + "FOPM reloaded. Check logs to see if there are any issues."); return true; } } return true; } }
package com.example.lib; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.graphics.Color; import android.os.Bundle; import android.view.Gravity; import android.view.ViewGroup; import android.widget.TextView; import com.example.lib.node.PageNode; import java.util.List; public class PathInfoActivity extends AppCompatActivity { private RecyclerView recyclerView; NodePath nodePath = NodePath.getInstance(); PageNode[] pageNodes = new PageNode[nodePath.nodeQueue.size()]; private List<PageNode> pageNodePath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_path_info); pageNodePath = PageNodeManager.getInstance().getPageNodePath(); recyclerView = findViewById(R.id.recycle_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(new RecyclerView.Adapter() { @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { TextView textView = new TextView(PathInfoActivity.this); textView.setGravity(Gravity.CENTER); RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200); textView.setBackgroundColor(Color.GRAY); layoutParams.topMargin = 20; textView.setLayoutParams(layoutParams); return new RecyclerView.ViewHolder(textView) { }; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { TextView tv = (TextView) holder.itemView; tv.setText(pageNodePath.get(position).name); } @Override public int getItemCount() { return pageNodePath.size(); } }); } }
package main; import java.awt.image.BufferedImage; public class DefaultShirt extends Shirt { public static BufferedImage Dfile; static { try { Dfile = javax.imageio.ImageIO.read(new java.io.File("pxl.bmp")); } catch (java.io.IOException e) { } } public DefaultShirt() { super(15, Dfile); } }
package br.corp.bonus630.controleremoto; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.util.Log; public class Server { int ip; int port = 13579; HttpRequestAsyncTask teste; public static String url; private ArrayList<String> listaIPs; public Server(Context contexto) { WifiManager wifiManager = (WifiManager) contexto.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ip = wifiInfo.getIpAddress(); this.ip = ip; } public ArrayList<String> getIPList() { ArrayList<String> urlList= new ArrayList<String>(); for(int i = 0;i<256;i++) { String strIP = String.format("http://%d.%d.%d.%d:%d/", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff), (i),port); //Log.e("ip",String.valueOf(ip & 0xff)); urlList.add(strIP); } return urlList; } //public class ServerDetail() //{ //} }
package com.crewmaker.controller; import com.crewmaker.dto.response.UserProfileDetails; import com.crewmaker.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/userProfile") public class UserProfileController { @Autowired private UserRepository userRepository; @GetMapping("/{username}") public UserProfileDetails getUserProfiles(@PathVariable String username) { return userRepository.findByUsernameUserProfile(username); } }
package specification; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; /** * Created by Tomas Hanus on 2/21/2015. */ @XmlAccessorType(XmlAccessType.NONE) public class ItemProcessor { @XmlAttribute private String ref; @XmlElement private Properties properties; ItemProcessor() { } ItemProcessor(String id) { if (id == null) this.ref = ""; else this.ref = id + "_ItemProcessor"; } public String getRef() { return ref; } public void setRef(String ref) { this.ref = ref; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } }
/* * [y] hybris Platform * * Copyright (c) 2000-2016 SAP SE * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with SAP Hybris. */ package com.cnk.travelogix.core.flightview.fnbclient.dto; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; /** * */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public class UpdateDeliverUrlRequest { @JsonProperty("DeliveryUrl") protected String deliveryUrl; /** * @return the deliveryUrl */ @JsonIgnore public String getDeliveryUrl() { return deliveryUrl; } /** * @param deliveryUrl * the deliveryUrl to set */ @JsonIgnore public void setDeliveryUrl(String deliveryUrl) { this.deliveryUrl = deliveryUrl; } }
package org.henix.workshop.qlearn.ai; import org.henix.workshop.qlearn.concepts.CellState; import org.henix.workshop.qlearn.concepts.Grid; import org.henix.workshop.qlearn.concepts.Move; import org.henix.workshop.qlearn.concepts.Token; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; public class QTable { private Map<StateAction, Float> valueByStateAction = new ConcurrentHashMap<>(20000); public Float getValueFor(CellState[][] gridState, Move playerMove){ StateAction sa = StateAction.from(gridState, playerMove); return valueByStateAction.getOrDefault(sa, 0.0f); } public Move findBestMove(CellState[][] gridState, List<Move> allMoves){ Move firstMove = allMoves.get(0); if (allMoves.size() == 1) return firstMove; SubjectiveState[] state = SubjectiveState.buildFlatArrayFrom(gridState, firstMove.token); Float max = Float.NEGATIVE_INFINITY; Move best = firstMove; for (Move m : allMoves){ StateAction sa = new StateAction(state, m.x*Grid.SIZE_Y+m.y); Float mValue = valueByStateAction.getOrDefault(sa, 0.0f); if (mValue > max){ max = mValue; best = m; } } return best; } public Float findBestValue(CellState[][] gridState, List<Move> allMoves){ Move best = findBestMove(gridState, allMoves); return valueByStateAction.getOrDefault(StateAction.from(gridState, best), 0.0f); } public void assignValueFor(CellState[][] gridState, Move playerMove, Float value){ StateAction sa = StateAction.from(gridState, playerMove); valueByStateAction.put(sa, value); } static final class StateAction{ public final SubjectiveState[] state; public final int action; StateAction(SubjectiveState[] state, int action) { this.state = state; this.action = action; } static StateAction from(CellState[][] gridState, Move playerMove){ SubjectiveState[] state = SubjectiveState.buildFlatArrayFrom(gridState, playerMove.token); int action = playerMove.x * Grid.SIZE_Y + playerMove.y; return new StateAction(state, action); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StateAction that = (StateAction) o; return action == that.action && Arrays.equals(state, that.state); } @Override public int hashCode() { int result = Objects.hash(action); result = 31 * result + Arrays.hashCode(state); return result; } } enum SubjectiveState{ MINE, OPPONENT, NEUTRAL; // The player token is the reference here, signaling which state will be her (SubjState.MINE), // those of her opponent (SubState.OPPONENT), or neutral. static SubjectiveState[] buildFlatArrayFrom(CellState[][] gridState, Token playerToken){ SubjectiveState[] state = new SubjectiveState[9]; int index = 0; for (int x=0; x< Grid.SIZE_X; x++) for (int y=0; y< Grid.SIZE_Y; y++){ CellState gridstate = gridState[x][y]; if (gridstate == CellState.EMPTY) state[index] = SubjectiveState.NEUTRAL; else if (gridstate.matches(playerToken)) state[index] = SubjectiveState.MINE; else state[index] = SubjectiveState.OPPONENT; index++; } return state; } } }
package visao; import java.awt.Color; import java.awt.Font; import java.awt.Toolkit; import java.util.Collections; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import dados.Cidade; import dao.PrefeitoDAO; import ordenacao.OrdenaLegenda; import ordenacao.OrdenaNome; import servicos.Validacao; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; @SuppressWarnings("serial") public class TelaListar extends JFrame { private JPanel contentPane; private JTable tableCadastros; public TelaListar(Cidade eleicao) { PrefeitoDAO prefeitoDao = new PrefeitoDAO(); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (Validacao.validaCadastrarOutraCidade()) { eleicao.getPrefeitos().removeAll(eleicao.getPrefeitos()); TelaCadastroCidade telaCadastroCidade = new TelaCadastroCidade(); telaCadastroCidade.setVisible(true); dispose(); } else { if (Validacao.validaSair()) { System.exit(0); } } } }); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); setTitle("Lista de candidatos"); setBounds(100, 100, 530, 390); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); setLocationRelativeTo(null); contentPane.setBackground(Color.WHITE); setIconImage(Toolkit.getDefaultToolkit().getImage("img\\icone.png")); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(12, 71, 492, 230); contentPane.add(scrollPane); tableCadastros = new JTable(); tableCadastros.setModel(new DefaultTableModel(new Object[][] {}, new String[] { "Nome", "Partido", "Legenda" })); scrollPane.setViewportView(tableCadastros); JLabel lblCidade = new JLabel("Cidade:"); lblCidade.setFont(new Font("Tahoma", Font.PLAIN, 20)); lblCidade.setBounds(12, 12, 125, 22); contentPane.add(lblCidade); JButton btnVoltar = new JButton("Voltar"); btnVoltar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(!TelaPesquisar.pesquisa) { TelaMenuPrincipal telaMenuPrincipal = new TelaMenuPrincipal(eleicao); telaMenuPrincipal.setVisible(true); } dispose(); } }); btnVoltar.setBounds(393, 317, 89, 23); contentPane.add(btnVoltar); JLabel lblNomeCidade = new JLabel(eleicao.getNomeCidade().toString()); lblNomeCidade.setFont(new Font("Tahoma", Font.PLAIN, 16)); lblNomeCidade.setBounds(12, 45, 170, 28); contentPane.add(lblNomeCidade); if (!TelaPesquisar.pesquisa) { prefeitoDao.retornarLista(eleicao); listar(eleicao, 1); } } public void listar(Cidade eleicao, int opc) { int aux = 0; switch (opc) { case 1: OrdenaLegenda ordenaLegenda = new OrdenaLegenda(); Collections.sort(eleicao.getPrefeitos(), ordenaLegenda); for (aux = 0; aux < eleicao.quantidadePrefeitos(); aux++) { Object dados[] = { eleicao.getPrefeitos().get(aux).getNome().toUpperCase(), eleicao.getPrefeitos().get(aux).getPartidoAssociado().toUpperCase(), eleicao.getPrefeitos().get(aux).getNumeroLegenda() }; ((DefaultTableModel) tableCadastros.getModel()).addRow(dados); } break; case 2: String str = "candidato"; boolean encontrado = false; OrdenaNome ordenaNome = new OrdenaNome(); Collections.sort(eleicao.getPrefeitos(), ordenaNome); for (aux = 0; aux < eleicao.quantidadePrefeitos(); aux++) { Object dados[] = { eleicao.getPrefeitos().get(aux).getNome().toUpperCase(), eleicao.getPrefeitos().get(aux).getPartidoAssociado().toUpperCase(), eleicao.getPrefeitos().get(aux).getNumeroLegenda() }; ((DefaultTableModel) tableCadastros.getModel()).addRow(dados); setVisible(true); encontrado = true; } if (encontrado == false) { JOptionPane.showMessageDialog(null, "Nenhum dado encontrado!", "Falha", JOptionPane.INFORMATION_MESSAGE); } if (eleicao.getPrefeitos().size() > 1) { str = "candidatos"; } JLabel lblQuantidade = new JLabel(eleicao.getPrefeitos().size() + " " + str); lblQuantidade.setBounds(12, 317, 89, 23); contentPane.add(lblQuantidade); } } }
/* * 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 pizza; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.security.*; import java.math.*; /** * * @author fefes */ public class Login { static int idfunc; static int tipoFunc; public Connection conn; Login(){ } public int FazerLogin(int id, String senhaM){ int res = 0; idfunc = id; try { String myDriver = "org.gjt.mm.mysql.Driver"; String myUrl = "jdbc:mysql://localhost/pizzaria"; Class.forName(myDriver); Connection conn = DriverManager.getConnection(myUrl, "root", ""); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(senhaM.getBytes(),0,senhaM.length()); String senhaMD5 = new BigInteger(1,m.digest()).toString(16); String query = "SELECT * FROM loginfuncionario WHERE idfunc = "+id+""; Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(query); rs.next(); if((rs.getInt("idfunc") == id) &&(rs.getString("senha").equals(senhaMD5))){ tipoFunc = rs.getInt("tipo"); if(rs.getInt("tipo") == 1){ res = 1; } else if(rs.getInt("tipo") == 2){ res = 2; } else if(rs.getInt("tipo") == 3){ res = 3; } else{ res = 0; System.out.print("Erro, tipo invalido para esse sistema!"); } } rs.close(); } catch (Exception e) { System.err.println("Erro! "); System.err.println(e.getMessage()); } return res; } }
package com.giga.controller; import com.giga.entity.BlogEntry; import com.giga.service.IBlogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RequestMapping("/blog/api") @RestController @CrossOrigin public class BlogRestController { @Autowired IBlogService blogService; @GetMapping("/list") @ResponseBody public ResponseEntity<List<BlogEntry>> find() { return new ResponseEntity<>(blogService.display(), HttpStatus.ACCEPTED); } @GetMapping("/small-list") public ResponseEntity<Page<BlogEntry>> findPage(Pageable pageable) { return new ResponseEntity<>(blogService.display(pageable), HttpStatus.ACCEPTED); } @GetMapping("/findByCategory/{id}") public ResponseEntity<List<BlogEntry>> findByCategory(@PathVariable Integer id) { return new ResponseEntity<>(blogService.findByCategoryId(id), HttpStatus.ACCEPTED); } @PostMapping("/create") public ResponseEntity<Void> createEntry(@RequestBody BlogEntry blogEntry) { blogService.create(blogEntry); return new ResponseEntity<>(HttpStatus.CREATED); } }
package appcom.example.ejerciciovero; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.EditText; import android.widget.TextView; public class datosCliente extends AppCompatActivity { private EditText a, b, c, d; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.datos_cliente); a = (EditText) findViewById(R.id.uno); b = (EditText) findViewById(R.id.dos); c = (EditText) findViewById(R.id.tres); d = (EditText) findViewById(R.id.cuatro); mostrarDatos(); } public void mostrarDatos() { Bundle data = getIntent().getExtras(); String as = data.getString("nombre"); String bs = data.getString("apellidoP"); String cs = data.getString("apellidoM"); String ds = data.getString("correo"); a.setText("" + as); b.setText("" + bs); c.setText("" + cs); d.setText("" + ds); } }
package com.coinhunter.core.domain.value; import org.apache.commons.lang3.StringUtils; import org.springframework.util.CollectionUtils; import java.util.List; public enum CryptoCurrency { BTC, ETH, DASH, LTC, ETC, XRP, BCH, XMR, ZEC, QTUM, BTG, EOS, ICX, VEN, TRX, ELF, MITH, MCO, OMG, KNC, GNT, HSR, ZIL, ETHOS, PAY, WAX, POWR, LRC, GTO, STEEM, STRAT, ZRX, REP, AE, XEM, SNT, ADA; public static List<CryptoCurrency> getAllCurrencies() { return CollectionUtils.arrayToList(CryptoCurrency.values()); } public static CryptoCurrency of(String currencyType) { if (StringUtils.isEmpty(currencyType)) { return BTC; } currencyType = currencyType.toUpperCase(); return CryptoCurrency.valueOf(currencyType); } }
/** * */ package org.giftwrapping.core.service.impl; import java.util.List; import org.giftwrapping.core.DAO.GiftWrapDAO; import org.giftwrapping.core.enums.GiftWrapType; import org.giftwrapping.core.model.GiftWrapOptionModel; import org.giftwrapping.core.service.GiftWrapService; import org.springframework.beans.factory.annotation.Required; /** * @author hemantyadav01 * */ public class GiftWrapServiceImpl implements GiftWrapService { private GiftWrapDAO giftWrapDAO; /* * (non-Javadoc) * * @see org.giftwrapping.core.service.GiftWrapService#getGiftWrap() */ @Override public List<GiftWrapOptionModel> getAllGiftWrap() { // XXX Auto-generated method stub return giftWrapDAO.findGiftOptions(); } /* * (non-Javadoc) * * @see org.giftwrapping.core.service.GiftWrapService#getGiftWrapForType(org.giftwrapping.core.enums.GiftWrapType) */ @Override public List<GiftWrapOptionModel> getAllGiftWrapForType(final GiftWrapType type) { // XXX Auto-generated method stub return giftWrapDAO.findGiftOptionsByType(type); } @Required public void setGiftWrapDAO(final GiftWrapDAO giftWrapDAO) { this.giftWrapDAO = giftWrapDAO; } }
package baekjoon.divide_conquer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Test_1780 { static int minusOneCount = 0; static int zeroCount = 0; static int oneCount = 0; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[][] field = new int[n][n]; for (int i=0; i < n; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); for (int j=0; j<n; j++) { field[i][j] = Integer.parseInt(st.nextToken()); } } countNumbers(field, n, 0, 0); System.out.println(minusOneCount); System.out.println(zeroCount); System.out.println(oneCount); } static void countNumbers(int[][] field, int n, int x, int y) { if (isAllSame(field, n, x, y)) { int criteria = field[y][x]; if (criteria == -1) { minusOneCount++; }else if (criteria == 0) { zeroCount++; }else { oneCount++; } return; } countNumbers(field, n/3, x, y); countNumbers(field, n/3, x+n/3, y); countNumbers(field, n/3, x+(n/3 * 2), y); countNumbers(field, n/3, x, y+n/3); countNumbers(field, n/3, x+n/3, y+n/3); countNumbers(field, n/3, x+(n/3 * 2), y+n/3); countNumbers(field, n/3, x, y+(n/3 * 2)); countNumbers(field, n/3, x+n/3, y+(n/3 * 2)); countNumbers(field, n/3, x+(n/3 * 2), y+(n/3 * 2)); } static boolean isAllSame(int[][] field, int n, int x, int y) { int criteria = field[y][x]; for (int i = y; i < y + n; i++) { for (int j = x; j < x + n; j++) { if (field[i][j] != criteria) { return false; } } } return true; } }
package com.guilhermefgl.spring.crudproduto.models.repositories; import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.guilhermefgl.spring.crudproduto.models.Produto; import com.guilhermefgl.spring.crudproduto.models.repositories.ProdutoRepository; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") public class ProdutoRepositoryTest { @Autowired private ProdutoRepository produtoRepository; private static final String PRODUTO_NOME = "Produto Teste"; private static final String PRODUTO_NOME_FILHO = "Produto Filho Teste"; @Before public void setUp() throws Exception { Produto produto = new Produto(); produto.setNome(PRODUTO_NOME); produto.setDescricao("produto de teste"); produtoRepository.save(produto); Produto produtoFilho = new Produto(); produtoFilho.setNome(PRODUTO_NOME_FILHO); produtoFilho.setDescricao("produto de teste para associacao n para 1"); produtoFilho.setProdutoPai(produtoRepository.findByIdProduto(2)); produtoRepository.save(produtoFilho); } @After public final void tearDown() { produtoRepository.deleteAll(); } @Test public void findAllTest() { List<Produto> produtos = produtoRepository.findAll(); assertEquals(2, produtos.size()); } }
package com.rudecrab.demo.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author RC * @description 自定义参数校验错误码和错误信息注解 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) // 表明该注解只能放在类的字段上 public @interface ExceptionCode { // 响应码code int value() default 10000; // 响应信息msg String message() default "参数校验错误"; }
/* * @version 1.0 * @author PSE group */ package kit.edu.pse.goapp.server.servlets; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import kit.edu.pse.goapp.server.authentication.Authentication; import kit.edu.pse.goapp.server.converter.daos.ParticipantDaoConverter; import kit.edu.pse.goapp.server.converter.objects.ObjectConverter; import kit.edu.pse.goapp.server.creating_obj_with_dao.MeetingWithDao; import kit.edu.pse.goapp.server.creating_obj_with_dao.ParticipantWithDao; import kit.edu.pse.goapp.server.creating_obj_with_dao.UserWithDao; import kit.edu.pse.goapp.server.daos.MeetingDAO; import kit.edu.pse.goapp.server.daos.MeetingDaoImpl; import kit.edu.pse.goapp.server.daos.ParticipantDAO; import kit.edu.pse.goapp.server.daos.ParticipantDaoImpl; import kit.edu.pse.goapp.server.datamodels.Meeting; import kit.edu.pse.goapp.server.datamodels.MeetingConfirmation; import kit.edu.pse.goapp.server.datamodels.Participant; import kit.edu.pse.goapp.server.datamodels.User; import kit.edu.pse.goapp.server.exceptions.CustomServerException; import kit.edu.pse.goapp.server.validation.MeetingValidation; import kit.edu.pse.goapp.server.validation.UserValidation; /** * Servlet implementation class MeetingParticipantManagement */ @WebServlet("/MeetingParticipantManagement") public class MeetingParticipantManagementServlet extends HttpServlet { private static final long serialVersionUID = 1L; private UserWithDao userWithDao = new UserWithDao(); private ParticipantWithDao participantWithDao = new ParticipantWithDao(); private MeetingWithDao meetingWithDao = new MeetingWithDao(); private MeetingValidation validation = new MeetingValidation(); private UserValidation userValidation = new UserValidation(); private Authentication authentication = new Authentication(); /** * Constructor * * @see HttpServlet#HttpServlet() */ public MeetingParticipantManagementServlet() { super(); } /** * Gets meeting participants * * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response, authentication); } protected void doGet(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { try { int userId = authentication.authenticateUser(request); String participantId = request.getParameter("participantId"); ParticipantDAO dao = new ParticipantDaoImpl(); try { dao.setParticipantId(Integer.parseInt(participantId)); } catch (Exception e) { throw new CustomServerException("The ParticipantID from the JSON string isn't correct!", HttpServletResponse.SC_BAD_REQUEST); } Participant participantForMeetingId = participantWithDao.createParticipantWithDao(dao.getParticipantId()); User user = userWithDao.createUserWithDao(userId); Meeting meetingCheckParticipant = meetingWithDao.createMeetingWithDao( participantForMeetingId.getMeetingId(), participantForMeetingId.getUser().getId()); meetingCheckParticipant.isParticipant(user); Participant participant = dao.getParticipantByID(); response.getWriter().write(new ObjectConverter<Participant>().serialize(participant, Participant.class)); } catch (CustomServerException e) { response.setStatus(e.getStatusCode()); response.getWriter().write(e.toString()); } catch (IOException io) { response.getWriter().write(io.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } /** * Adds meeting participants * * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response, authentication); } protected void doPost(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { try { int userId = authentication.authenticateUser(request); String jsonString = request.getReader().readLine(); ParticipantDAO dao = new ParticipantDaoConverter().parse(jsonString); dao.setConfirmation(MeetingConfirmation.PENDING); validation.checkIfUserIsParticipantAndCreator(userId, dao.getMeetingId()); userValidation.userExists(dao.getUserId()); List<Participant> participants = participantWithDao.createParticipantsWithDao(dao.getMeetingId()); validation.checkIfAlreadyParticipant(participants, dao.getUserId()); dao.addParticipant(); MeetingDAO meetingDao = new MeetingDaoImpl(); meetingDao.setMeetingId(dao.getMeetingId()); Meeting meeting = meetingDao.getMeetingByID(); response.getWriter().write(new ObjectConverter<Meeting>().serialize(meeting, Meeting.class)); } catch (CustomServerException e) { response.setStatus(e.getStatusCode()); response.getWriter().write(e.toString()); } catch (IOException io) { response.getWriter().write(io.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } /** * Confirm Meeting * * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse) */ @Override public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPut(request, response, authentication); } protected void doPut(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { try { int userId = authentication.authenticateUser(request); String jsonString = request.getReader().readLine(); ParticipantDAO dao = new ParticipantDaoConverter().parse(jsonString); MeetingConfirmation x = dao.getConfirmation(); Participant participant = dao.getParticipantByID(); validation.checkIfUserIsParticipant(userId, participant.getParticipantId()); dao.setConfirmation(x); dao.updateParticipant(); MeetingDAO meetingDao = new MeetingDaoImpl(); meetingDao.setMeetingId(dao.getMeetingId()); Meeting meeting = meetingDao.getMeetingByID(); response.getWriter().write(new ObjectConverter<Meeting>().serialize(meeting, Meeting.class)); } catch (CustomServerException e) { response.setStatus(e.getStatusCode()); response.getWriter().write(e.toString()); } catch (IOException io) { response.getWriter().write(io.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } /** * Deletes a meeting participant * * @see HttpServlet#doDelete(HttpServletRequest, HttpServletResponse) */ @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { int userId = authentication.authenticateUser(request); String participantId = request.getParameter("participantId"); ParticipantDAO dao = new ParticipantDaoImpl(); try { dao.setParticipantId(Integer.parseInt(participantId)); } catch (Exception e) { throw new CustomServerException("The ParticipantID from the JSON string isn't correct!", HttpServletResponse.SC_BAD_REQUEST); } // also checks, if participant exists Participant participant = dao.getParticipantByID(); validation.checkIfUserIsParticipantAndCreator(userId, participant.getMeetingId()); if (dao != null) { dao.deleteParticipant(); } response.setStatus(HttpServletResponse.SC_OK); } catch (CustomServerException e) { response.setStatus(e.getStatusCode()); response.getWriter().write(e.toString()); } catch (IOException io) { response.getWriter().write(io.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
package com.xjf.wemall.service.crazyjavachapter16.part4; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class DaemonThread1 extends Thread { // 定义后台线程的线程执行体与普通线程没有任何区别 public void run() { for (int i = 0; i < 100 ; i++ ) { System.out.println(getName() + " " + i); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { for (int i = 0 ; i < 10 ; i++ ) { System.out.println(Thread.currentThread().getName() + " " + i); if (i == 0) { DaemonThread1 t = new DaemonThread1(); // 启动后台线程 t.start(); } Thread.currentThread().sleep(1000); } } }
package com.example.android.pokefinder; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.android.pokefinder.data.Pokemon; import com.example.android.pokefinder.data.Status; import com.example.android.pokefinder.utils.PokeUtils; import java.util.List; public class PokemonDetailActivity extends AppCompatActivity{ private static final String TAG = PokemonDetailActivity.class.getSimpleName(); public static final String EXTRA_POKEMON = "Pikachu"; private TextView mHeightTV; private TextView mWeightTV; private TextView mNameTV; private TextView mEvolvesFromTV; private TextView mEvolvesToTV; private ImageView mPokemonIconIV; private ImageView mPokemonEvolvesFromIconIV; private ImageView mPokemonEvolvesToIconIV; private TextView mErrorMessageTV; private ProgressBar mLoadingIndicatorPB; private SavedPokemonViewModel mViewModel; private PokemonViewModel mViewModelForSearch; private Toast mToast; private Pokemon mPokemon; private boolean mIsSaved = false; Menu mOptionsMenu = null; private RecyclerView mPokemonTypesRV; private PokemonTypeAdapter mPokemonTypeAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pokemon_item_detail); mPokemonTypesRV = findViewById(R.id.rv_pokemon_types); mLoadingIndicatorPB = findViewById(R.id.pb_loading_indicator); mErrorMessageTV = findViewById(R.id.tv_error_message); mPokemonTypeAdapter = new PokemonTypeAdapter(); mPokemonTypesRV.setAdapter(mPokemonTypeAdapter); GridLayoutManager horizontalLayout = new GridLayoutManager(this, 1, GridLayoutManager.HORIZONTAL, false); mPokemonTypesRV.setLayoutManager(horizontalLayout); mPokemonTypesRV.setHasFixedSize(true); // mPokemonTypesRV.setLayoutManager(new GridLayoutManager(this, 1)); // mPokemonTypesRV.setHasFixedSize(true); mViewModel = new ViewModelProvider(this).get(SavedPokemonViewModel.class); mToast = null; Intent intent = getIntent(); if (intent != null && intent.hasExtra(EXTRA_POKEMON)) { mViewModelForSearch = new ViewModelProvider(this).get(PokemonViewModel.class); mViewModelForSearch.getLoadingStatus().observe(this, new Observer<Status>() { @Override public void onChanged(Status status) { if (status == Status.SUCCESS) { Pokemon pokemon = mViewModelForSearch.getSearchResults().getValue(); mLoadingIndicatorPB.setVisibility(View.GONE); onPokemonSearched(pokemon); } else if (status == Status.LOADING) { mLoadingIndicatorPB.setVisibility(View.VISIBLE); } else if (status == Status.ERROR) { mLoadingIndicatorPB.setVisibility(View.GONE); mErrorMessageTV.setVisibility(View.VISIBLE); mViewModelForSearch.resetStatus(); } else if (status == Status.ERROR) { mLoadingIndicatorPB.setVisibility(View.GONE); } } }); mViewModelForSearch.resetStatus(); mPokemon = (Pokemon) intent.getSerializableExtra(EXTRA_POKEMON); mEvolvesFromTV = findViewById(R.id.tv_evolves_from); mPokemonEvolvesFromIconIV = findViewById(R.id.pokemon_evolve_from_image); mEvolvesToTV = findViewById(R.id.tv_evolves_to); mPokemonEvolvesToIconIV = findViewById(R.id.pokemon_evolve_to_image); /* * This pokemon evolves from another pokemon */ if(mPokemon.evolves_from != null) { mEvolvesFromTV.setText(PokeUtils.capitalizeFirstLetter(mPokemon.evolves_from)); mPokemonEvolvesFromIconIV = findViewById(R.id.pokemon_evolve_from_image); String iconEvolveFromURL = PokeUtils.buildPokemonIconURL(Integer.toString(mPokemon.evolves_from_id)); Glide.with(this).load(iconEvolveFromURL).into(mPokemonEvolvesFromIconIV); mPokemonEvolvesFromIconIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doPokemonSearch(mPokemon.evolves_from); } }); mEvolvesFromTV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doPokemonSearch(mPokemon.evolves_from); } }); } else{ /* * This pokemon is at the base of the evolution tree. */ mEvolvesFromTV.setText(R.string.no_evolution_form); mPokemonEvolvesFromIconIV.setVisibility(View.GONE); } if(mPokemon.evolves_to != null) { mEvolvesToTV.setText(PokeUtils.capitalizeFirstLetter(mPokemon.evolves_to)); mPokemonEvolvesToIconIV = findViewById(R.id.pokemon_evolve_to_image); String iconEvolveToURL = PokeUtils.buildPokemonIconURL(Integer.toString(mPokemon.evolves_to_id)); Glide.with(this).load(iconEvolveToURL).into(mPokemonEvolvesToIconIV); mPokemonEvolvesToIconIV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doPokemonSearch(mPokemon.evolves_to); } }); mEvolvesToTV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doPokemonSearch(mPokemon.evolves_to); } }); } else{ /* * This pokemon is at the top of the evolution tree. */ mEvolvesToTV.setText(R.string.no_evolution_form); mPokemonEvolvesToIconIV.setVisibility(View.GONE); } mNameTV = findViewById(R.id.name); mNameTV.setText(PokeUtils.capitalizeFirstLetter(mPokemon.name)); mWeightTV = findViewById(R.id.weight); mWeightTV.setText(String.format("Weight: %s kg", Float.toString((float) mPokemon.weight / 10))); mHeightTV = findViewById(R.id.height); mHeightTV.setText(String.format("Height: %s m", Float.toString((float) mPokemon.height / 10))); String iconURL = PokeUtils.buildPokemonIconURL(Integer.toString(mPokemon.id)); mPokemonTypeAdapter.updatePokemonTypes(mPokemon.types); mPokemonIconIV = findViewById(R.id.pokemon_image); Glide.with(this).load(iconURL).into(mPokemonIconIV); } mViewModel.loadPokemonResults(); } public void onPokemonSearched(Pokemon pokemon) { if(pokemon != null) { Intent intent = new Intent(this, PokemonDetailActivity.class); intent.putExtra(PokemonDetailActivity.EXTRA_POKEMON, pokemon); startActivity(intent); } } @Override public void onResume() { super.onResume(); mViewModelForSearch.resetStatus(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.pokemon_item_detail, menu); ActionBar actionBar = getSupportActionBar(); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_action_home); mOptionsMenu = menu; mViewModel.getAllPokemon().observe(this, new Observer<List<Pokemon>>() { @Override public void onChanged(@Nullable List<Pokemon> pokemonList) { mIsSaved = pokemonList != null && pokemonList.contains(mPokemon); MenuItem item = mOptionsMenu.findItem(R.id.action_favorite); if (mIsSaved) { item.setIcon(R.drawable.ic_bookmark_black); } else { item.setIcon(R.drawable.ic_bookmark_border); } } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_favorite: if (mPokemon != null) { mIsSaved = !mIsSaved; String output = PokeUtils.capitalizeFirstLetter(mPokemon.name); if (mIsSaved) { mViewModel.insert(mPokemon); makeToast(output + " is saved"); item.setIcon(R.drawable.ic_bookmark_black); } else { mViewModel.delete(mPokemon); makeToast(output + " is no longer saved"); item.setIcon(R.drawable.ic_bookmark_border); } } return true; case android.R.id.home: Intent i=new Intent(this, MainActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); //i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); //i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(i); finish(); return true; case R.id.action_bulbapedia: viewPokeOnWeb(); return true; default: return super.onOptionsItemSelected(item); } } private void makeToast(String message){ if (mToast != null ){ mToast.cancel(); } mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT); mToast.show(); } private void doPokemonSearch(String searchQuery) { if(Status.INITIAL == mViewModelForSearch.getLoadingStatus().getValue()) { mViewModelForSearch.loadSearchResults(searchQuery); } } public void viewPokeOnWeb() { if (mPokemon != null) { Uri bulbapediaEntry = Uri.parse("https://bulbapedia.bulbagarden.net/wiki/" + mPokemon.name + "_(Pok%C3%A9mon)"); Intent webIntent = new Intent(Intent.ACTION_VIEW, bulbapediaEntry); PackageManager packageManager = getPackageManager(); List<ResolveInfo> activities = packageManager.queryIntentActivities(webIntent, PackageManager.MATCH_DEFAULT_ONLY); if (activities.size() > 0) { startActivity(webIntent); } } } }
package com.osce.vo.user.menu; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; @Setter @Getter @ToString public class PfMenuZtreeVo implements Serializable { private static final long serialVersionUID = -4901737093643963963L; /** * 菜单id */ private Long menuId; private String id; @JsonProperty(value = "pId") private String pId; private String name; private boolean checked; private boolean open; private int level; private String position; }
/* * Copyright 2017 University of Michigan * * 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 edu.umich.verdict.query; import edu.umich.verdict.VerdictContext; import edu.umich.verdict.exceptions.VerdictException; import edu.umich.verdict.parser.VerdictSQLBaseVisitor; import edu.umich.verdict.parser.VerdictSQLParser; import edu.umich.verdict.util.StringManipulations; import edu.umich.verdict.util.VerdictLogger; public class RefreshQuery extends Query { public RefreshQuery(VerdictContext vc, String q) { super(vc, q); } @Override public void compute() throws VerdictException { VerdictSQLParser p = StringManipulations.parserOf(queryString); VerdictSQLBaseVisitor<String> visitor = new VerdictSQLBaseVisitor<String>() { @Override public String visitRefresh_statement(VerdictSQLParser.Refresh_statementContext ctx) { String schema = null; if (ctx.schema != null) { schema = ctx.schema.getText(); } return schema; } }; String schema = visitor.visit(p.refresh_statement()); schema = (schema != null)? schema : ( (vc.getCurrentSchema().isPresent())? vc.getCurrentSchema().get() : null ); vc.getMeta().clearSampleInfo(); if (schema != null) { vc.getMeta().refreshSampleInfo(schema, false); // vc.getMeta().refreshTables(schema); } else { String msg = "No schema selected. No refresh done."; VerdictLogger.error(msg); throw new VerdictException(msg); } } }
package ftry.backand.first_comp.cofferorderer.Common; /** * Created by User on 4/30/2016. */ public interface IHiddable { public void Hide(); }
package String; import java.util.Scanner; public class Insert_valuetoinsert_replace { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); StringBuffer a=new StringBuffer("Hello World"); a.insert(6,"Ann ");//insert at particular index System.out.println(a); a.append("Dona");//append to the string System.out.println(a); a.delete(6,10); System.out.println(a); a.replace(0,6,"Welcome"); System.out.println(a); a.deleteCharAt(0); System.out.println(a); a.reverse(); System.out.println(a); } }
package org.sodeja.event; public interface Event { }
package com.tencent.mm.t; import android.graphics.PointF; import java.util.List; class c$a { public float[] dnV = new float[this.dnX]; public float[] dnW = new float[this.dnX]; public int dnX; final /* synthetic */ c dnY; public c$a(c cVar, List<PointF> list) { this.dnY = cVar; this.dnX = list.size(); int i = 0; while (true) { int i2 = i; if (i2 < this.dnX) { this.dnV[i2] = ((PointF) list.get(i2)).x; this.dnW[i2] = ((PointF) list.get(i2)).y; i = i2 + 1; } else { new StringBuilder("lasso size:").append(this.dnX); return; } } } }
package com.mszalek.cleaningservice.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.time.LocalDateTime; @Entity @Data @NoArgsConstructor @AllArgsConstructor public class CleaningRequest { @Id @GeneratedValue private Long id; private int roomNumber; private LocalDateTime createTime; private LocalDateTime deadline; private CleaningComplexity cleaningComplexity; private String note; private boolean handled; }
package org.librairy.modeler.services; import org.junit.Ignore; import org.junit.Test; import org.librairy.modeler.lda.tasks.LDATrainingTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; /** * @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es> */ public class ThredPoolTest { private static final Logger LOG = LoggerFactory.getLogger(ThredPoolTest.class); private ConcurrentHashMap<String,ScheduledFuture<?>> buildingTasks = new ConcurrentHashMap<>(); private ThreadPoolTaskScheduler threadpool = new ThreadPoolTaskScheduler(); SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm:ssZ"); String domainUri ="domain"; int poolSize = 5; int events = 100; Long delay = 2000l; Long taskSleep = 10000l; @Test @Ignore public void exceedsSize() throws InterruptedException { threadpool.setPoolSize(poolSize); threadpool.initialize(); for (int i=0; i<events; i++){ new Thread(new UnexpectedEvent()).run(); Thread.sleep(100); } LOG.info("waiting for partial interruption.."); Thread.sleep(taskSleep/2); for (int i=0; i<events; i++){ new Thread(new UnexpectedEvent()).run(); Thread.sleep(100); } LOG.info("waiting for finish test.."); Thread.sleep(30000); } private class UnexpectedEvent implements Runnable{ @Override public void run() { LOG.info("Scheduled creation of a new topic model (LDA) for the domain: " + domainUri + " at " + timeFormatter.format(new Date(System.currentTimeMillis() + delay))); ScheduledFuture<?> task = buildingTasks.get(domainUri); if (task != null) { task.cancel(true); // this.threadpool.getScheduledThreadPoolExecutor().purge(); } task = threadpool.schedule(new SampleTask(), new Date(System.currentTimeMillis() + delay)); buildingTasks.put(domainUri,task); } } private class SampleTask implements Runnable{ @Override public void run() { LOG.info("Task executing!!!!!!"); try { Thread.sleep(taskSleep); } catch (InterruptedException e) { LOG.warn("Task cancelled"); } } } }
package com.example.healthmanage.ui.activity.workplan.ui; import androidx.lifecycle.MutableLiveData; import com.example.healthmanage.base.BaseApplication; import com.example.healthmanage.base.BaseViewModel; import com.example.healthmanage.bean.UsersInterface; import com.example.healthmanage.bean.UsersRemoteSource; import com.example.healthmanage.data.network.exception.ExceptionHandle; import com.example.healthmanage.ui.activity.qualification.response.UploadResponse; import com.example.healthmanage.ui.activity.workplan.response.InsertPlanResponse; import com.example.healthmanage.ui.activity.workplan.response.UpdateWorkResponse; import com.example.healthmanage.ui.activity.workplan.response.WorkPlanListResponse; import java.io.File; import java.util.List; public class WorkPlanViewModel extends BaseViewModel { public UsersRemoteSource usersRemoteSource; public MutableLiveData<List<WorkPlanListResponse.DataBean>> workPlanLiveData = new MutableLiveData<>(); public MutableLiveData<String> picUrl = new MutableLiveData<>(); public MutableLiveData<Boolean> updateSuccess = new MutableLiveData<>(); public MutableLiveData<Boolean> insertSuccess = new MutableLiveData<>(); public WorkPlanViewModel() { usersRemoteSource = new UsersRemoteSource(); } public void getWorkPlanByTime(String targetTime,int doctorId){ usersRemoteSource.getWorkPlanByTime(targetTime, doctorId, BaseApplication.getToken(), new UsersInterface.GetWorkPlanByTimeCallback() { @Override public void sendSucceed(WorkPlanListResponse workPlanListResponse) { if (workPlanListResponse.getData()!=null && workPlanListResponse.getData().size()>0){ workPlanLiveData.postValue(workPlanListResponse.getData()); }else { workPlanLiveData.postValue(null); } } @Override public void sendFailed(String msg) { } @Override public void error(ExceptionHandle.ResponseException e) { } }); } public void updateWorkPlanById(int id,String updateTime){ usersRemoteSource.updateWorkPlanById(id, updateTime, BaseApplication.getToken(), new UsersInterface.UpdateWorkPlanByIdCallback() { @Override public void updateSucceed(UpdateWorkResponse updateWorkResponse) { updateSuccess.postValue(true); } @Override public void updateFailed(String msg) { updateSuccess.postValue(false); } @Override public void error(ExceptionHandle.ResponseException e) { updateSuccess.postValue(false); } }); } public void getPicUrl(File file){ usersRemoteSource.getUploadIdCard(file, new UsersInterface.UpLoadIdCardCallback() { @Override public void sendSucceed(UploadResponse uploadResponse) { if (uploadResponse.getData()!=null){ picUrl.postValue(uploadResponse.getData()); }else { picUrl.postValue(null); } } @Override public void sendFailed(String msg) { } @Override public void error(ExceptionHandle.ResponseException e) { } }); } public void insertWorkPlan(String workText,int userId,String createTime,String targetTime){ usersRemoteSource.insertWorkPlan(workText, userId, createTime,targetTime, BaseApplication.getToken(), new UsersInterface.InsertWorkPlanCallback() { @Override public void insertSucceed(InsertPlanResponse insertPlanResponse) { insertSuccess.postValue(true); } @Override public void insertFailed(String msg) { insertSuccess.postValue(false); } @Override public void error(ExceptionHandle.ResponseException e) { insertSuccess.postValue(false); } }); } }
import org.sql2o.*; import org.junit.*; import org.fluentlenium.adapter.FluentTest; import org.junit.ClassRule; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import static org.assertj.core.api.Assertions.assertThat; import static org.fluentlenium.core.filter.FilterConstructor.*; import static org.junit.Assert.*; public class AppTest extends FluentTest { public WebDriver webDriver = new HtmlUnitDriver(); @Override public WebDriver getDefaultDriver() { return webDriver; } @ClassRule public static ServerRule server = new ServerRule(); @Rule public DatabaseRule database = new DatabaseRule(); @Test public void rootTest() { goTo("http://localhost:4567/"); assertThat(pageSource()).contains("Registrar Course Scheduling"); } @Test public void studentIsCreatedTest() { goTo("http://localhost:4567/"); click("a", withText("Students")); fill("#name").with("billy"); submit(".btn"); assertThat(pageSource()).contains("billy"); } @Test public void courseIsCreatedTest() { goTo("http://localhost:4567/"); click("a", withText("Courses")); fill("#courseName").with("History"); fill("#courseNumber").with("HIST101"); submit(".btn"); assertThat(pageSource()).contains("HIST101"); } @Test public void studentShowPageDisplaysName() { Student testStudent = new Student("Billy"); testStudent.save(); String url = String.format("http://localhost:4567/students/%d", testStudent.getId()); goTo(url); assertThat(pageSource()).contains("Billy"); } @Test public void courseShowPageDisplaysDescription() { Course testCourse = new Course("History"); testCourse.save(); String url = String.format("http://localhost:4567/courses/%d", testCourse.getId()); goTo(url); assertThat(pageSource()).contains("History"); } // // @Test // public void taskIsAddedToCategory() { // Category testCategory = new Category("Household chores"); // testCategory.save(); // Task testTask = new Task("Mow the lawn"); // testTask.save(); // String url = String.format("http://localhost:4567/categories/%d", testCategory.getId()); // goTo(url); // fillSelect("#task_id").withText("Mow the lawn"); // submit(".btn"); // assertThat(pageSource()).contains("<li>"); // assertThat(pageSource()).contains("Mow the lawn"); // } // // @Test // public void categoryIsAddedToTask() { // Category testCategory = new Category("Household chores"); // testCategory.save(); // Task testTask = new Task("Mow the lawn"); // testTask.save(); // String url = String.format("http://localhost:4567/tasks/%d", testTask.getId()); // goTo(url); // fillSelect("#category_id").withText("Household chores"); // submit(".btn"); // assertThat(pageSource()).contains("<li>"); // assertThat(pageSource()).contains("Household chores"); // } }
package com.tencent.mm.plugin.qqmail.ui; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.R; import com.tencent.mm.ui.base.h; class ComposeUI$11 implements OnClickListener { final /* synthetic */ ComposeUI mfs; ComposeUI$11(ComposeUI composeUI) { this.mfs = composeUI; } public final void onClick(View view) { this.mfs.YC(); ComposeUI.j(this.mfs).getText().toString(); ComposeUI.D(this.mfs); if (this.mfs.boL()) { ComposeUI composeUI = this.mfs; ComposeUI composeUI2 = this.mfs; this.mfs.getString(R.l.app_tip); ComposeUI.a(composeUI, h.a(composeUI2, this.mfs.getString(R.l.plugin_qqmail_compose_send_ing), true, new 1(this))); if (ComposeUI.E(this.mfs).boU()) { ComposeUI.a(this.mfs, ComposeUI.H(this.mfs)); return; } ComposeUI.G(this.mfs).setMessage(this.mfs.getString(R.l.plugin_qqmail_attach_uploading)); ComposeUI.E(this.mfs).mgq = new 2(this); } } }
package com.yida.design.composite.demo2.impl; import java.util.ArrayList; import java.util.List; import com.yida.design.composite.demo2.Corp; /** ********************* * 枝节点 * * @author yangke * @version 1.0 * @created 2018年7月12日 下午2:40:38 *********************** */ public class Branch extends Corp { // 领导下边有哪些下级领导和小兵 List<Corp> subordinateList = new ArrayList<Corp>(); public Branch(String name, String position, int salary) { super(name, position, salary); }; // 增加一个下属,可能是小头目,也可能是个小兵 public void addSubordinate(Corp corp) { this.subordinateList.add(corp); } // 我有哪些下属 public List<Corp> getSubordinate() { return this.subordinateList; } }
package com.example.beautyOfProgram; //在无序数组中寻找最大的k个数 public class Test25 { private int[] theArray; private int currentSize; // 快速排序 public void quickSort(int left, int right) { if (right - left <= 0) { return; } int middle = partition(left, right); quickSort(left, middle - 1); quickSort(middle + 1, right); } private int partition(int left, int right) { int pivot = theArray[left]; while (left < right) { while (left < right && theArray[right] >= pivot) { right--; } theArray[left] = theArray[right]; while (left < right && theArray[left] < pivot) { left++; } theArray[right] = theArray[left]; } theArray[left] = pivot; return left; } // 输出最大的k个值 public void displayK(int k) { for (int i = currentSize - 1; i > currentSize - 1 - k; i--) { System.out.print(theArray[i] + " "); } } //选择排序最大的k个值 public void selectSortMaxK(int k){ if(k>currentSize){ return; } for(int i=0;i<k;i++){ } } }
package com.intenthq.horseracing.controllers; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.springframework.ui.ModelMap; import java.io.FilterInputStream; import java.io.FilterReader; import java.io.LineNumberReader; import com.intenthq.horseracing.model.Racer; import com.intenthq.horseracing.factory.RacerFactory; import com.intenthq.horseracing.NonExistingTrackException; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class RaceTest { private Race race; private static final String SAMPLE_OUTPUT = "Position, Lane, Horse name\n"+ "1, 1, racer1\n"+ "2, 2, racer2\n"; private static final String SAMPLE_OUTPUT2 = "Position, Lane, Horse name\n"+ "1, 2, racer2\n"+ "2, 1, racer1\n"; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @Test(expected=NonExistingTrackException.class) public void addNewRacerShouldThrowExceptionIfRaceIsNotInitialized() throws Exception { race = new Race(); race.addNewRacer(null,0); } @Test public void addNewRacerShouldResultANonEmptyList() throws Exception { race = new Race(); race.initRace(2,100); race.addNewRacer(new Racer(),0); assertThat(race.hasRacers(), is(true)); } @Test(expected=NonExistingTrackException.class) public void addNewRacerShouldThrowExceptionIfThereIsNoSpace() throws Exception { race = new Race(); race.initRace(2,100); race.addNewRacer(new Racer(),0); race.addNewRacer(new Racer(),1); race.addNewRacer(new Racer(),2); } @Test(expected=NonExistingTrackException.class) public void getRaceStateShouldThrowExceptionIfRaceIsNotInitialized() throws Exception { race = new Race(); race.getRaceState(); } @Test public void getRaceStateShouldReturnState() throws Exception { race = new Race(); race.initRace(2,100); race.addNewRacer(RacerFactory.createNewHorseRacer("racer1"),0); race.addNewRacer(RacerFactory.createNewHorseRacer("racer2"),1); assertThat(race.getRaceState(), is(SAMPLE_OUTPUT)); } @Test public void getRaceStateShouldReturnChangedState() throws Exception { race = new Race(); race.initRace(2,100); race.addNewRacer(RacerFactory.createNewHorseRacer("racer1"),0); race.addNewRacer(RacerFactory.createNewHorseRacer("racer2"),1); String[] updates = new String[1]; updates[0]="2 10"; race.updateRace(updates); assertThat(race.getRaceState(), is(SAMPLE_OUTPUT2)); } }
package com.example.administrator.halachavtech.Motzar; /** * Created by Admin on 2/26/2017. */ public class Status { private String idorder; private Double order_price; private Double price_motzar; private int order_quantity; private String name_motzar; private String contact_name; private String contact_phone; private String timestamp; private String status; private int stock_after_payment; private int stock; /* public Status(String idorder, Double order_price, Double price_motzar, int order_quantity, String name_motzar, String contact_name, String contact_phone, String timestamp, String status, int stock) { this.idorder = idorder; this.order_price = order_price; this.price_motzar = price_motzar; this.order_quantity = order_quantity; this.name_motzar = name_motzar; this.contact_name = contact_name; this.contact_phone = contact_phone; this.timestamp = timestamp; this.status = status; this.stock = stock; }*/ @Override public String toString() { return "Status{" + "idorder='" + idorder + '\'' + ", order_price=" + order_price + ", price_motzar=" + price_motzar + ", order_quantity=" + order_quantity + ", name_motzar='" + name_motzar + '\'' + ", contact_name='" + contact_name + '\'' + ", contact_phone='" + contact_phone + '\'' + ", timestamp='" + timestamp + '\'' + ", status='" + status + '\'' + ", stock_after_payment='" + stock_after_payment + '\'' + ", stock=" + stock + '}'; } public Status(String idorder, Double order_price, Double price_motzar, int order_quantity, String name_motzar, String contact_name, String contact_phone, String timestamp, String status, int stock_after_payment, int stock) { this.idorder = idorder; this.order_price = order_price; this.price_motzar = price_motzar; this.order_quantity = order_quantity; this.name_motzar = name_motzar; this.contact_name = contact_name; this.contact_phone = contact_phone; this.timestamp = timestamp; this.status = status; this.stock_after_payment = stock_after_payment; this.stock = stock; } public int getStock_after_payment() { return stock_after_payment; } public void setStock_after_payment(int stock_after_payment) { this.stock_after_payment = stock_after_payment; } public int getStock() { return stock; } public String getIdorder() { return idorder; } public Double getOrder_price() { return order_price; } public Double getPrice_motzar() { return price_motzar; } public int getOrder_quantity() { return order_quantity; } public String getName_motzar() { return name_motzar; } public String getContact_name() { return contact_name; } public String getContact_phone() { return contact_phone; } public String getTimestamp() { return timestamp; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
package com.cts.projectManagement.model; public class AddProjectrequest { private Long projectId; private String project; private String startDate; private String endDate; private int priority; private Long userId; public Long getProjectId() { return projectId; } public void setProjectId(Long projectId) { this.projectId = projectId; } public String getProject() { return project; } public void setProject(String project) { this.project = project; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public AddProjectrequest(Long projectId, String project, String startDate, String endDate, int priority, Long userId) { super(); this.projectId = projectId; this.project = project; this.startDate = startDate; this.endDate = endDate; this.priority = priority; this.userId = userId; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ArbeitsvorgangTypType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.VERSIEGIstdatenType; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; public class VERSIEGIstdatenTypeBuilder { public static String marshal(VERSIEGIstdatenType vERSIEGIstdatenType) throws JAXBException { JAXBElement<VERSIEGIstdatenType> jaxbElement = new JAXBElement<>(new QName("TESTING"), VERSIEGIstdatenType.class , vERSIEGIstdatenType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private Double versiegelungOberseite; private Double versiegelungUnterseite; private ArbeitsvorgangTypType arbeitsvorgang; private String aggregat; private XMLGregorianCalendar zeitpunktDurchsatz; public VERSIEGIstdatenTypeBuilder setVersiegelungOberseite(Double value) { this.versiegelungOberseite = value; return this; } public VERSIEGIstdatenTypeBuilder setVersiegelungUnterseite(Double value) { this.versiegelungUnterseite = value; return this; } public VERSIEGIstdatenTypeBuilder setArbeitsvorgang(ArbeitsvorgangTypType value) { this.arbeitsvorgang = value; return this; } public VERSIEGIstdatenTypeBuilder setAggregat(String value) { this.aggregat = value; return this; } public VERSIEGIstdatenTypeBuilder setZeitpunktDurchsatz(XMLGregorianCalendar value) { this.zeitpunktDurchsatz = value; return this; } public VERSIEGIstdatenType build() { VERSIEGIstdatenType result = new VERSIEGIstdatenType(); result.setVersiegelungOberseite(versiegelungOberseite); result.setVersiegelungUnterseite(versiegelungUnterseite); result.setArbeitsvorgang(arbeitsvorgang); result.setAggregat(aggregat); result.setZeitpunktDurchsatz(zeitpunktDurchsatz); return result; } }
package StepDefinitions; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import io.cucumber.java.en.*; import io.github.bonigarcia.wdm.WebDriverManager; public class addNewUser { private static WebDriver driver = null; @Given("go to website and login with username and password") public void go_to_website_and_login_with_username_and_password() { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); String url = "http://laravelcms-qa.devdigdev.com/admin"; driver.get(url); driver.manage().window().maximize(); driver.findElement(By.id("email")).sendKeys("monali.rana@devdigital.com"); driver.findElement(By.id("password")).sendKeys("Mvc@082019"); driver.findElement(By.xpath("//button[contains(text(),'Login')]")).click(); } @When("verify that email is already exist") public void verify_that_email_is_already_exist() { } @When("if email not exist add new user") public void if_email_not_exist_add_new_user() { } @Then("verify the user on list page") public void verify_the_user_on_list_page() { } }
package radiator; import java.util.ArrayList; public class V2Radiator { V2Radiator(ArrayList list) { for(int x=0; x < 5; x++) { list.add(new Simunit("V2radiator")); System.out.println("V2 Radiator "+ x); } } }
package com.spintech.testtask.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import info.movito.themoviedbapi.TmdbApi; @Configuration public class TmdbServiceConfig { @Value("${tmdb.apikey}") private String tmdbApiKey; @Bean public TmdbApi tmdbApi() { return new TmdbApi(tmdbApiKey); } }
// Sun Certified Java Programmer // Chapter 7, P601 // Generics and Collections import java.util.*; class Adder { int addAll(List list) { // method with a non-generic List argument, // but assumes (with no guarantee) that it will be Integers Iterator it = list.iterator(); int total = 0; while (it.hasNext()) { int i = ((Integer) it.next()).intValue(); total += i; } return total; } }
import java.util.Random; import java.util.Scanner; import java.util.ArrayList; public class BingoCard { private int [][][] card= new int[5][5][2]; BingoCard(){ boolean duplicate=true; int currentNum=0; int currentMax=15; int currentMin=1; int offset = 15; Random ran = new Random(); for(int i=0;i<card.length;i++){ for(int j=0;j<card[1].length;j++){ card[i][j][1]=0; while(duplicate==true){ duplicate=false; currentNum = ran.nextInt((currentMax-currentMin)+1)+currentMin; for(int a=0;a<card.length;a++){ for(int b=0;b<card[1].length;b++){ if(currentNum==card[a][b][0]){ duplicate=true; } } } // System.out.println(i); // System.out.println(j); } duplicate=true; card [i][j][0]= currentNum; currentMax += offset; currentMin += offset; } currentMax=15; currentMin=1; } card[2][2][1]=1; // free position card[2][2][0]=0; } void CheckCard(int call){ for(int j=0;j<card.length;j++){ for(int k=0;k<card[1].length;k++){ if(call==card[j][k][0]){ card[j][k][1]=1; } } } } boolean winner(){ boolean winner=true; for(int i=0;i<card.length;i++){ winner=true; for(int j=0;j<card[1].length-1;j++){ if(card[i][j][1]!=card[i][j+1][1]||card[i][j][1]==0){ winner=false; } } if(winner==true){ return winner; } } for(int i=0;i<card.length;i++){ winner=true; for(int j=0;j<card[1].length-1;j++){ if(card[j][i][1]!=card[j+1][i][1]||card[j][i][1]==0){ winner=false; } } if(winner==true){ return winner; } } //diagonals winner=true; for(int i=0;i<card.length-1;i++){ if(card[i][card.length-1-i][1]!=card[i+1][card.length-1-i-1][1]||card[i][card.length-1-i][1]==0){ winner=false; } } if(winner==true){ return winner; } winner=true; for(int i=0;i<card.length-1;i++){ if(card[i][i][1]!=card[i+1][i+1][1]|card[i][i][1]==0){ winner=false; } } if(winner==true){ return winner; } return winner; } void string(){ for(int i=0;i<card.length;i++){ System.out.println(" "); for(int j=0;j<card[1].length;j++){ System.out.print(card[i][j][0]); System.out.print(" "); } } for(int i=0;i<card.length;i++){ System.out.println(" "); for(int j=0;j<card[1].length;j++){ System.out.print(card[i][j][1]); System.out.print(" "); } } } public static void main(String[] args) { BingoCard test = new BingoCard(); } }
package com.tt.miniapp.route; public interface IRouteEvent { void onAppHide(); void onAppLaunch(); void onAppRoute(RouteEventBean paramRouteEventBean); void onAppShow(); void onJsCoreReady(); public static class RouteEventBean { private String openType; private String path; private String queryStr; private int webViewId; public RouteEventBean(int param1Int, String param1String1, String param1String2, String param1String3) { this.webViewId = param1Int; this.path = param1String1; this.queryStr = param1String2; this.openType = param1String3; } public String getOpenType() { return this.openType; } public String getPath() { return this.path; } public String getQueryStr() { return this.queryStr; } public int getWebViewId() { return this.webViewId; } } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\route\IRouteEvent.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.EiligkeitType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.FehlerRefType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.PlanArbeitsgangRefType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.PlanArbeitsgangTerminType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.PlanArbeitsgangType; import java.io.StringWriter; import java.math.BigInteger; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; public class PlanArbeitsgangTypeBuilder { public static String marshal(PlanArbeitsgangType planArbeitsgangType) throws JAXBException { JAXBElement<PlanArbeitsgangType> jaxbElement = new JAXBElement<>(new QName("TESTING"), PlanArbeitsgangType.class , planArbeitsgangType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private PlanArbeitsgangRefType identifikation; private Boolean nacharbeit; private Boolean solldatenaenderung; private Boolean aggregatetausch; private Boolean programmiert; private FehlerRefType hauptfehler; private Boolean endaggregat; private String aggregat; private PlanArbeitsgangTerminType termine; private EiligkeitType eiligkeit; private Boolean belegungsrelevant; private BigInteger index; public PlanArbeitsgangTypeBuilder setIdentifikation(PlanArbeitsgangRefType value) { this.identifikation = value; return this; } public PlanArbeitsgangTypeBuilder setNacharbeit(Boolean value) { this.nacharbeit = value; return this; } public PlanArbeitsgangTypeBuilder setSolldatenaenderung(Boolean value) { this.solldatenaenderung = value; return this; } public PlanArbeitsgangTypeBuilder setAggregatetausch(Boolean value) { this.aggregatetausch = value; return this; } public PlanArbeitsgangTypeBuilder setProgrammiert(Boolean value) { this.programmiert = value; return this; } public PlanArbeitsgangTypeBuilder setHauptfehler(FehlerRefType value) { this.hauptfehler = value; return this; } public PlanArbeitsgangTypeBuilder setEndaggregat(Boolean value) { this.endaggregat = value; return this; } public PlanArbeitsgangTypeBuilder setAggregat(String value) { this.aggregat = value; return this; } public PlanArbeitsgangTypeBuilder setTermine(PlanArbeitsgangTerminType value) { this.termine = value; return this; } public PlanArbeitsgangTypeBuilder setEiligkeit(EiligkeitType value) { this.eiligkeit = value; return this; } public PlanArbeitsgangTypeBuilder setBelegungsrelevant(Boolean value) { this.belegungsrelevant = value; return this; } public PlanArbeitsgangTypeBuilder setIndex(BigInteger value) { this.index = value; return this; } public PlanArbeitsgangType build() { PlanArbeitsgangType result = new PlanArbeitsgangType(); result.setIdentifikation(identifikation); result.setNacharbeit(nacharbeit); result.setSolldatenaenderung(solldatenaenderung); result.setAggregatetausch(aggregatetausch); result.setProgrammiert(programmiert); result.setHauptfehler(hauptfehler); result.setEndaggregat(endaggregat); result.setAggregat(aggregat); result.setTermine(termine); result.setEiligkeit(eiligkeit); result.setBelegungsrelevant(belegungsrelevant); result.setIndex(index); return result; } }
package com.cache.CacheDemoApp.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.cache.CacheDemoApp.beans.Student; import com.cache.CacheDemoApp.service.studentService; @RestController @RequestMapping(value = "/student") public class StudentController { @Autowired private studentService studentService; @GetMapping("/id") public ResponseEntity<Student> getStudent(@RequestParam Integer studentId){ return new ResponseEntity<Student>(studentService.getStudentById(studentId).get(), HttpStatus.OK); } }
package com.Bridgelabz; import java.util.*; public class SearchAccordingly { static Scanner sc = new Scanner(System.in); public static void viewCityStateWise(ArrayList<Person>personInfo) { boolean flag =false; Map<String,Person> citywithPerson=new HashMap<String,Person>(); Map<String,Person> statewithPerson=new HashMap<String,Person>(); for (Person p:personInfo) { citywithPerson.put(p.getCity(),p); statewithPerson.put(p.getCity(),p); } System.out.println("Enter the city name to view"); String viewByCity=sc.nextLine(); System.out.println("Enter the state name to view"); String viewByState=sc.nextLine(); for (Map.Entry<String,Person> state:statewithPerson.entrySet()){ if(viewByState.equals(state.getKey())){ for (Map.Entry<String,Person>city:citywithPerson.entrySet()){ if(viewByCity.equals(city.getKey())){ System.out.println(city.getValue()); flag=true; } } } } if(!flag){ System.out.println("Enter matching city with state"); } } // List<String> matchedCity=cityMapping.entrySet().stream(). // filter(i ->citySearch.equals(i.getValue())).map(Map.Entry::getKey).collect(Collectors.toList()); // System.out.println(matchedCity); // // List<String> matchedState=stateMapping.entrySet().stream(). // filter(j ->stateSearch.equals(j.getValue())).map(Map.Entry::getKey).collect(Collectors.toList()); // System.out.println(matchedCity); // } public static void searchPersonByCity(ArrayList<Person> personInfo) { boolean flag =false; Map<String,Person> citywithPerson=new HashMap<String,Person>(); for (Person p:personInfo) { citywithPerson.put(p.getCity(),p); } System.out.println("Enter city name to get person from"); String citysearch=sc.nextLine(); System.out.println("Enter person name to search in = "+citysearch); String personname=sc.nextLine(); for (Map.Entry<String,Person>city:citywithPerson.entrySet()){ if(citysearch.equalsIgnoreCase(city.getKey())){ if((city.getValue().getFirstName().equalsIgnoreCase(personname))){ System.out.println(city.getValue()); flag=true; } } } if(!flag){ System.out.println("No matching city and person"); } } }
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenuItem; public class MyMenuActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent arg0) { JMenuItem source = (JMenuItem)arg0.getSource(); String button = source.getText(); switch(button) { case "Random Walls": randomWalls(); break; } } private void randomWalls() { MazeSolver.setRandomWalls(); } }
package com.minephone.network; import java.util.Map; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.android.volley.VolleyError; import com.minephone.network.NetAccess.NetAccessListener; /** * json适配器,免去写adapter * @author ping * 2014-4-11 下午9:54:47 how to use ? HashMap<String, Integer> field = new HashMap<String, Integer>(); field.put("googpic", R.id.image); field.put("goodname", R.id.name); field.put("goodspec", R.id.spec); field.put("goodprice", R.id.price); HashMap<String, Object> params = new HashMap<String, Object>(); params.put("page", 1); JsonAdapter adapter = new JsonAdapter(mactivity,R.layout.item_lbsstore, Urls.LBSSTORE, "data", params,field,null); listview.setAdapter(adapter); //第一页 adapter.refresh(true); //加载下一页 HashMap<String, Object> param2 = new HashMap<String, Object>(); param2.put("page", 2); adapter.setparams(param2); adapter.refresh(false); */ public class JsonAdapter extends BaseAdapter implements NetAccessListener { private Context mcontext; private JSONArray data; private Map<String, Integer> field; private String datakey; private NetAccessListener callback; private int layoutid; private Map<String, String> params; private String url; public JSONArray getJsonArray (){ return data; } public JsonAdapter(Context context,int layoutid,String url,String datakey,Map<String, String> params,Map<String,Integer> field,NetAccessListener callback) { mcontext = context; this.layoutid = layoutid; this.datakey =datakey; this.field = field; this.url =url; this.callback = callback; } /** * 重新设置参数,可用于追加下一页数据 * @author ping * 2014-4-15 下午3:31:09 * @param params */ public void setparams (Map<String, String> params) { this.params = params; } /** * 刷新数据 * @author ping * 2014-4-15 下午3:46:54 * @param removeoldata是否移除之前数据 */ public void refresh (boolean removeoldata) { if (removeoldata) { NetAccess.request(mcontext).setFlag("JsonAdapter_get").byGet(url + NetAccess.getParamStr(params), this); } else { NetAccess.request(mcontext).setFlag("JsonAdapter_add").byGet(url + NetAccess.getParamStr(params), this); } } @Override public int getCount() { return data==null?0:data.size(); } @Override public Object getItem(int index) { return data==null?null:data.get(index); } @Override public long getItemId(int id) { return id; } @Override public View getView(int index, View view, ViewGroup viewgroup) { ViewHolder holder = null; if(view == null){ view = LayoutInflater.from(mcontext).inflate(layoutid, null); holder = new ViewHolder(); holder.childviews = new View[field.size()]; int count=0; for (String key : field.keySet()) { int id = field.get(key); holder.childviews[count] = view.findViewById(id) ; holder.childviews[count].setTag(key); count++; } view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } for (View childview:holder.childviews) { String key = (String) childview.getTag(); String jsonvalue = data.getJSONObject(index).getString(key); if (childview instanceof TextView) { ((TextView) childview).setText(jsonvalue); } else if (childview instanceof ImageView) { NetAccess.image((ImageView)childview, jsonvalue); } else { //key的id不属于TextView,也不属于ImageView } } return view; } @Override public void onAccessComplete(boolean success, String object,VolleyError error, String flag) { if (success) { JSONObject jo = JSONObject.parseObject(object); if (jo != null) { if (flag.equals("JsonAdapter_get")) { if (datakey==null) { data = JSONArray.parseArray(jo.toJSONString()); } else { data = jo.getJSONArray(datakey); } } else if (flag.equals("JsonAdapter_add")) { if (datakey==null) { data.addAll(JSONArray.parseArray(jo.toJSONString())); } else { data.addAll(data = jo.getJSONArray(datakey)); } } else { //unkonw flag } super.notifyDataSetChanged(); } } if (callback!=null) { callback.onAccessComplete(success, object, error, flag); } } private static class ViewHolder { View[] childviews; } }
package com.valunskii.university.controller.rest; import java.time.DayOfWeek; import java.util.List; import java.util.Map; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.WebRequest; import com.valunskii.university.domain.Group; import com.valunskii.university.domain.Parity; import com.valunskii.university.domain.Schedule; import com.valunskii.university.domain.Teacher; import com.valunskii.university.repository.GroupRepository; import com.valunskii.university.repository.ScheduleRepository; import com.valunskii.university.repository.TeacherRepository; @RestController @CrossOrigin @Api(tags = {"ScheduleController"}, description = "Расписание", produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping("/schedule") public class ScheduleController { private final String ANY = "any"; private TeacherRepository teacherRepo; @Autowired public void setTeacherRepo(TeacherRepository teacherRepo) { this.teacherRepo = teacherRepo; } private GroupRepository groupRepo; @Autowired public void setGroupRepo(GroupRepository groupRepo) { this.groupRepo = groupRepo; } private ScheduleRepository scheduleRepo; @Autowired public void setScheduleRepo(ScheduleRepository scheduleRepo) { this.scheduleRepo = scheduleRepo; } @ApiOperation(value = "Получить полное расписание", notes = "Возвращает расписание полностью", produces = MediaType.APPLICATION_JSON_VALUE, hidden = false) @GetMapping public List<Schedule> retriveAll(WebRequest webRequest) { Map<String, String[]> params = webRequest.getParameterMap(); String parity = null; String dayOfWeek = null; if (params.containsKey("parity")) { parity = params.get("parity")[0]; } if (params.containsKey("dayOfWeek")) { dayOfWeek = params.get("dayOfWeek")[0]; } if ((parity == null && dayOfWeek == null) || (parity.equals(ANY) && dayOfWeek.equals(ANY))) { return scheduleRepo.findAllByOrderByIdAsc(); } else { if (parity.equals(ANY)) { return scheduleRepo.findAllByDayOfWeekOrderByIdAsc(DayOfWeek.valueOf(dayOfWeek)); } else if (dayOfWeek.equals(ANY)) { return scheduleRepo.findAllByParityOrderByIdAsc(Parity.valueOf(parity)); } else { return scheduleRepo.findAllByDayOfWeekAndParityOrderByIdAsc(DayOfWeek.valueOf(dayOfWeek), Parity.valueOf(parity)); } } } @ApiOperation(value = "Получить расписание группы", notes = "Возвращает расписание для данной группы", produces = MediaType.APPLICATION_JSON_VALUE, hidden = false) @GetMapping("/group/{group}") public List<Schedule> retriveScheduleForGroup(@PathVariable Group group, WebRequest webRequest) { Map<String, String[]> params = webRequest.getParameterMap(); String parity = null; String dayOfWeek = null; if (params.containsKey("parity")) { parity = params.get("parity")[0]; } if (params.containsKey("dayOfWeek")) { dayOfWeek = params.get("dayOfWeek")[0]; } if ((parity == null && dayOfWeek == null) || (parity.equals(ANY) && dayOfWeek.equals(ANY))) { return scheduleRepo.findByGroupOrderById(group); } else { if (parity.equals(ANY)) { return scheduleRepo.findByGroupAndDayOfWeekOrderById(group, DayOfWeek.valueOf(dayOfWeek)); } else if (dayOfWeek.equals(ANY)) { return scheduleRepo.findByGroupAndParityOrderById(group, Parity.valueOf(parity)); } else { return scheduleRepo.findByGroupAndDayOfWeekAndParityOrderById(group, DayOfWeek.valueOf(dayOfWeek), Parity.valueOf(parity)); } } } @ApiOperation(value = "Получить расписание преподавателя", notes = "Возвращает расписание для данного преподавателя", produces = MediaType.APPLICATION_JSON_VALUE, hidden = false) @GetMapping("/teacher/{teacher}") public List<Schedule> retriveScheduleForTeacher(@PathVariable Teacher teacher, WebRequest webRequest) { Map<String, String[]> params = webRequest.getParameterMap(); String parity = null; String dayOfWeek = null; if (params.containsKey("parity")) { parity = params.get("parity")[0]; } if (params.containsKey("dayOfWeek")) { dayOfWeek = params.get("dayOfWeek")[0]; } if ((parity == null && dayOfWeek == null) || (parity.equals(ANY) && dayOfWeek.equals(ANY))) { return scheduleRepo.findByTeacherOrderById(teacher); } else { if (parity.equals(ANY)) { return scheduleRepo.findByTeacherAndDayOfWeekOrderById(teacher, DayOfWeek.valueOf(dayOfWeek)); } else if (dayOfWeek.equals(ANY)) { return scheduleRepo.findByTeacherAndParityOrderById(teacher, Parity.valueOf(parity)); } else { return scheduleRepo.findByTeacherAndDayOfWeekAndParityOrderById(teacher, DayOfWeek.valueOf(dayOfWeek), Parity.valueOf(parity)); } } } @ApiOperation(value = "Создать элемент Расписание (Schedule)", notes = "Создает элемент", produces = MediaType.APPLICATION_JSON_VALUE, hidden = false) @PostMapping public Schedule create(@RequestBody Schedule schedule) { return scheduleRepo.save(schedule); } @ApiOperation(value = "Обновить элемент Расписание (Schedule)", notes = "Обновляет элемент по ID", produces = MediaType.APPLICATION_JSON_VALUE, hidden = false) @PutMapping("{id}") public Schedule update( @PathVariable("id") Schedule scheduleFromDb, @RequestBody Schedule schedule ) { BeanUtils.copyProperties(schedule, scheduleFromDb, "id"); return scheduleRepo.save(scheduleFromDb); } @ApiOperation(value = "Удалить элемент Расписание (Schedule)", notes = "Удаляет элемент по ID", produces = MediaType.APPLICATION_JSON_VALUE, hidden = false) @DeleteMapping("{id}") public void delete(@PathVariable("id") Schedule schedule) { scheduleRepo.delete(schedule); } }
package com.example.lenovo.liweixin1603b20180917.utils; import java.io.IOException; import java.util.HashMap; import java.util.Map; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Created by lenovo on 2018/9/17. */ public class OkHttpUtils { private static OkHttpUtils okHttpUtils; private OkHttpClient okHttpClient; private OkHttpUtils(){ okHttpClient=new OkHttpClient.Builder() .build(); } public static OkHttpUtils getInstance(){ if (okHttpUtils==null){ synchronized (OkHttpUtils.class){ if(okHttpUtils==null){ okHttpUtils=new OkHttpUtils(); } } } return okHttpUtils; } public void postData(HashMap<String, String> prams, String url, final RequestCallback requestCallback){ FormBody.Builder formbodyBuilder=new FormBody.Builder( ); if (prams!=null){ for (Map.Entry<String, String> stringStringEntry : prams.entrySet()) { formbodyBuilder.add( stringStringEntry.getKey(),stringStringEntry.getValue() ); } } Request request = new Request.Builder() .url( url ) .post( formbodyBuilder.build() ) .build(); Call call = okHttpClient.newCall( request ); okHttpClient.newCall( request ).enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { if (requestCallback!=null){ requestCallback.error( call, e ); } } @Override public void onResponse(Call call, Response response) throws IOException { if (requestCallback!=null){ requestCallback.success( call, response ); } } } ); } public interface RequestCallback { void success(Call call, Response response); void error(Call call,IOException e); } }
package com.zznode.opentnms.isearch.otnRouteService.service; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.zznode.opentnms.isearch.model.bo.DSR; import com.zznode.opentnms.isearch.model.bo.ODU; import com.zznode.opentnms.isearch.model.bo.ODU0; import com.zznode.opentnms.isearch.model.bo.ODU1; import com.zznode.opentnms.isearch.model.bo.ODU2; import com.zznode.opentnms.isearch.model.bo.ODU3; import com.zznode.opentnms.isearch.model.bo.ODU4; import com.zznode.opentnms.isearch.model.bo.TsnGraph; import com.zznode.opentnms.isearch.model.bo.ZdResult; import com.zznode.opentnms.isearch.otnRouteService.cache.CachedClient; import com.zznode.opentnms.isearch.otnRouteService.db.po.DbEms; import com.zznode.opentnms.isearch.otnRouteService.db.po.DbTsn; import com.zznode.opentnms.isearch.otnRouteService.db.po.TsnMe; import com.zznode.opentnms.isearch.otnRouteService.manage.ObjectPool; import com.zznode.opentnms.isearch.otnRouteService.manage.ResourceManager; import com.zznode.opentnms.isearch.otnRouteService.manage.SubnetManager; import com.zznode.opentnms.isearch.otnRouteService.util.PropertiesHander; import com.zznode.opentnms.isearch.routeAlgorithm.api.ISearch; import com.zznode.opentnms.isearch.routeAlgorithm.api.enumrate.Direction; import com.zznode.opentnms.isearch.routeAlgorithm.api.model.BusinessAvator; import com.zznode.opentnms.isearch.routeAlgorithm.api.model.Link; import com.zznode.opentnms.isearch.routeAlgorithm.api.model.Section; import com.zznode.opentnms.isearch.routeAlgorithm.api.model.otn.OtnLink; import com.zznode.opentnms.isearch.routeAlgorithm.api.model.otn.OtnNode; import com.zznode.opentnms.isearch.routeAlgorithm.core.matrix.Matrix; import com.zznode.opentnms.isearch.routeAlgorithm.plugin.data.importor_base.BaseImporter; @Component public class RouteAnalyser { private static final Logger logger = LoggerFactory.getLogger(RouteAnalyser.class); @Autowired public ResourceManager resourceManager; @Autowired public SubnetManager subnetManager; public ObjectPool pool = new ObjectPool(); @Autowired public CachedClient cachedClient; private final String memcacTag = PropertiesHander.getProperty("memcacTag"); public void analyseAllRoute() throws Exception{ logger.info("网络结构抽象开始"); cachedClient.set( memcacTag , 0, new String("test") ); /** * //1、查询所有ems List<DbEms> allems = resourceManager.getAllEms(); logger.info("全网ems数量:" + allems.size()); //2.循环每个ems,处理站点链接关系 List<TsnGraph> tsnGlist = new ArrayList<TsnGraph>(); for (int i = 0; i < allems.size(); i++) { DbEms ems = allems.get(i); logger.info("处理ems:" + ems.getObjectId()); List<TsnGraph> tsnGraphlist = analyseEms(ems); if( tsnGraphlist.size() > 0 ){ tsnGlist.addAll(tsnGraphlist); } } //3.组装数据 saveAnalyseEmsData(tsnGlist); */ //4.组装完成后对于小段snc上承载长snc的情况,再进一步进行分析 analyserSeprateData(); } private void analyserSeprateData() throws Exception { //取出邻接矩阵 BusinessAvator businessAvator = new BusinessAvator(); businessAvator.setKey( PropertiesHander.getProperty("BusinessAvator") ); Matrix matrix = (Matrix)cachedClient.get(businessAvator.getKey()); Section[][] sections = matrix.getMatrix(); int size = sections.length; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { Section sec = sections[i][j]; if( sec!=null ){ dealSec(sections,sec,i,j); } } } } private void dealSec(Section[][] sections, Section sec, int i, int j) throws Exception { List<ZdResult> sourceZdResultOdu4 = new ArrayList<ZdResult>(); List<ZdResult> sourceZdResultOdu3 = new ArrayList<ZdResult>(); List<ZdResult> sourceZdResultOdu2 = new ArrayList<ZdResult>(); List<ZdResult> sourceZdResultOdu1 = new ArrayList<ZdResult>(); List<Link> sourcelinks = sec.getLinklist(); for (Iterator<Link> iter = sourcelinks.iterator(); iter.hasNext();) { Link link = iter.next(); String key = "OTN_RESOURECE_OTNLink" + "|" +sec.getAendNode()+"|"+sec.getZendNode()+"|"+ link.getLinkindex(); ZdResult zdResult = (ZdResult)cachedClient.get(key); logger.info("getkey:"+ key +",value:" + zdResult); zdResult.setStoreKey(key); ODU odu = zdResult.getOdu(); if (odu instanceof ODU4) { sourceZdResultOdu4.add(zdResult); } else if (odu instanceof ODU3) { sourceZdResultOdu3.add(zdResult); } else if (odu instanceof ODU2) { sourceZdResultOdu2.add(zdResult); } else if (odu instanceof ODU1) { sourceZdResultOdu1.add(zdResult); } } List<ZdResult> lineZdResultOdu3 = new ArrayList<ZdResult>(); List<ZdResult> lineZdResultOdu2 = new ArrayList<ZdResult>(); List<ZdResult> lineZdResultOdu1 = new ArrayList<ZdResult>(); List<ZdResult> lineZdResultOdu0 = new ArrayList<ZdResult>(); List<ZdResult> lineZdResultDsr = new ArrayList<ZdResult>(); List<ZdResult> colonumZdResultOdu3 = new ArrayList<ZdResult>(); List<ZdResult> colonumZdResultOdu2 = new ArrayList<ZdResult>(); List<ZdResult> colonumZdResultOdu1 = new ArrayList<ZdResult>(); List<ZdResult> colonumZdResultOdu0 = new ArrayList<ZdResult>(); List<ZdResult> colonumZdResultDsr = new ArrayList<ZdResult>(); int size = sections.length; for (int k = 0; k < size; k++) { Section lineSec = sections[i][k]; if( lineSec!=null && k != j ){ List<Link> linklist = lineSec.getLinklist(); for (Iterator<Link> iter = linklist.iterator(); iter.hasNext();) { Link link = iter.next(); String key = "OTN_RESOURECE_OTNLink" + "|" +lineSec.getAendNode()+"|"+lineSec.getZendNode()+"|"+ link.getLinkindex(); ZdResult zdResult = (ZdResult)cachedClient.get(key); ODU odu = zdResult.getOdu(); if (odu instanceof ODU3) { lineZdResultOdu3.add(zdResult); } else if (odu instanceof ODU2) { lineZdResultOdu2.add(zdResult); } else if (odu instanceof ODU1) { lineZdResultOdu1.add(zdResult); } else if (odu instanceof ODU0) { lineZdResultOdu0.add(zdResult); } else if (odu instanceof DSR) { lineZdResultDsr.add(zdResult); } } } Section colSec = sections[k][j]; if( colSec!=null && k != i ){ List<Link> linklist = colSec.getLinklist(); for (Iterator<Link> iter = linklist.iterator(); iter.hasNext();) { Link link = iter.next(); String key = "OTN_RESOURECE_OTNLink" + "|" +colSec.getAendNode()+"|"+colSec.getZendNode()+"|"+ link.getLinkindex(); ZdResult zdResult = (ZdResult)cachedClient.get(key); ODU odu = zdResult.getOdu(); if (odu instanceof ODU3) { colonumZdResultOdu3.add(zdResult); } else if (odu instanceof ODU2) { colonumZdResultOdu2.add(zdResult); } else if (odu instanceof ODU1) { colonumZdResultOdu1.add(zdResult); } else if (odu instanceof ODU0) { colonumZdResultOdu0.add(zdResult); } else if (odu instanceof DSR) { colonumZdResultDsr.add(zdResult); } } } } //判断占用,之判断下一层的。 for (int l = 0; l < sourceZdResultOdu4.size(); l++) { ZdResult source = sourceZdResultOdu4.get(l); boolean needfresh = false ; for (int m = 0; m < lineZdResultOdu3.size(); m++) { ZdResult line = lineZdResultOdu3.get(m); if( line.getPassedPtplist().contains(source.getHeadptpStr()) ){ ODU4 odu4 = (ODU4)source.getOdu(); ODU3 odu3 = (ODU3)line.getOdu(); odu4.getOdu3list().add(odu3); needfresh =true ; } } for (int m = 0; m < colonumZdResultOdu3.size(); m++) { ZdResult line = colonumZdResultOdu3.get(m); if( line.getPassedPtplist().contains(source.getHeadptpStr()) ){ ODU4 odu4 = (ODU4)source.getOdu(); ODU3 odu3 = (ODU3)line.getOdu(); odu4.getOdu3list().add(odu3); needfresh =true ; } } for (int m = 0; m < lineZdResultOdu2.size(); m++) { ZdResult line = lineZdResultOdu2.get(m); if( line.getPassedPtplist().contains(source.getHeadptpStr()) ){ ODU4 odu4 = (ODU4)source.getOdu(); ODU2 odu2 = (ODU2)line.getOdu(); odu4.getOdu2list().add(odu2); needfresh =true ; } } for (int m = 0; m < colonumZdResultOdu2.size(); m++) { ZdResult line = colonumZdResultOdu2.get(m); if( line.getPassedPtplist().contains(source.getHeadptpStr()) ){ ODU4 odu4 = (ODU4)source.getOdu(); ODU2 odu2 = (ODU2)line.getOdu(); odu4.getOdu2list().add(odu2); needfresh =true ; } } if(needfresh){ cachedClient.set( source.getStoreKey(), 0, source ); logger.error("刷新存贮两点间链路的路由数据:"+ source.getStoreKey()+":" + source ); } } //判断占用,之判断下一层的。 for (int l = 0; l < sourceZdResultOdu3.size(); l++) { ZdResult source = sourceZdResultOdu3.get(l); boolean needfresh = false ; for (int m = 0; m < lineZdResultOdu2.size(); m++) { ZdResult line = lineZdResultOdu2.get(m); if( line.getPassedPtplist().contains(source.getHeadptpStr()) ){ ODU3 odu3 = (ODU3)source.getOdu(); ODU2 odu2 = (ODU2)line.getOdu(); odu3.getOdu2list().add(odu2); needfresh =true ; } } for (int m = 0; m < colonumZdResultOdu2.size(); m++) { ZdResult line = colonumZdResultOdu2.get(m); if( line.getPassedPtplist().contains(source.getHeadptpStr()) ){ ODU3 odu3 = (ODU3)source.getOdu(); ODU2 odu2 = (ODU2)line.getOdu(); odu3.getOdu2list().add(odu2); needfresh =true ; } } if(needfresh){ cachedClient.set( source.getStoreKey(), 0, source ); logger.error("刷新存贮两点间链路的路由数据:"+ source.getStoreKey()+":" + source ); } } } /** * 循环所有ems,组装数据结构。 * TsnGraph:每个tsn的包含的站点信息。 * emsGraph:全网所有的站点信息,每个站点所属的tsn,和包含的网元。 * @param allems */ private List<TsnGraph> analyseEms(DbEms ems){ List<TsnGraph> tsnGlist = new ArrayList<TsnGraph>(); logger.info("处理ems:" + ems.getObjectId()); //1.查询ems的tsn信息。 List<DbTsn> tsnlist = subnetManager.getTsnByEms(ems.getObjectId()); logger.info("处理ems,tsn数量:" + tsnlist.size()); //2.查询tsn关联的tsnlink信息。 for (int j = 0; j < tsnlist.size(); j++) { DbTsn tsn = tsnlist.get(j); String tsnid = tsn.getObjectId(); List<TsnMe> tsnmes = subnetManager.getTsnMeByEms(tsnid); TsnGraph tsnGraph = new TsnGraph(); tsnGraph.setTsnid(tsnid); tsnGraph.setEmsid(ems.getObjectId()); for (int k = 0; k < tsnmes.size(); k++) { TsnMe me = tsnmes.get(k); if( me.getZhandianid()==null || me.getZhandianid().equals("")){ continue ; } tsnGraph.getZdids().add(me.getZhandianid()); } tsnGlist.add(tsnGraph); } return tsnGlist; } /** * 根据tsn分析站点间的链接关系。 * 组装图的链路信息。 * 边:OtnLink * 点:OtnNode * @throws Exception */ private void saveAnalyseEmsData( List<TsnGraph> tsnGlist ) throws Exception{ Set<Integer> allinputtype = new HashSet<Integer>(); allinputtype.add(87); allinputtype.add(76); allinputtype.add(77); allinputtype.add(78); allinputtype.add(8043); allinputtype.add(8031); allinputtype.add(104); allinputtype.add(105); allinputtype.add(106); allinputtype.add(8041); //BusiAnalyser busiAnalyser = new BusiAnalyser("Huawei/NanJingJWZ2"); List<OtnLink> linklist = new ArrayList<OtnLink>(); int linkindex = 1 ; logger.info("全网tsn数量:" + tsnGlist.size()); Set<String> dealedSet = new HashSet<String>(); Set<String> dealedFreeSet = new HashSet<String>(); //Map<String,Integer> dealedIndex = new HashMap<String,Integer>(); Map<String,ArrayList<String>> zjMap = new HashMap<String,ArrayList<String>>(); for (Iterator<TsnGraph> alliter = tsnGlist.iterator(); alliter.hasNext();) { TsnGraph tsnGraph = alliter.next(); logger.info("处理tsn,emsid:"+ tsnGraph.getEmsid() +" tsnid :" + tsnGraph.getTsnid()); logger.info("处理tsn,站点数量 :" + tsnGraph.getZdids().size()); if(tsnGraph.getZdids().size()==0){ continue ; } BusiAnalyser busiAnalyser = (BusiAnalyser)pool.getPool().borrowObject(tsnGraph.getEmsid()); String[] zdlist = tsnGraph.getZdids().toArray(new String[]{}); int zdcount = zdlist.length; for (int i = 0; i < zdcount; i++) { //a端站点 String aend = zdlist[i]; OtnNode anode = new OtnNode(); anode.setId(aend); if(zjMap.containsKey(aend)){ if( !zjMap.get(aend).contains(tsnGraph.getEmsid()) ){ zjMap.get(aend).add(tsnGraph.getEmsid()); } } else{ ArrayList<String> emslist = new ArrayList<String>(); emslist.add(tsnGraph.getEmsid()); zjMap.put(aend, emslist); } //循环其余站点,作为z端站点 for (int j = i+1; j < zdlist.length; j++) { String zend = zdlist[j]; OtnNode znode = new OtnNode(); znode.setId(zend); /** if( anode.getId().equals("16080002") && znode.getId().equals("16090001") ){ }else if ( anode.getId().equals("16090001") && znode.getId().equals("16080002") ){ System.out.println(123); }else{ continue ; } */ String dealedkey = tsnGraph.getEmsid() + "|" + anode.getId() + "|" + znode.getId() ; if( dealedSet.contains( dealedkey )){ logger.info("处理tsn,站点已经处理过 :" + dealedkey); continue ; } dealedSet.add( dealedkey ); List<ZdResult> resultlist = doAnalyserZdRoute(busiAnalyser, anode.getId(), znode.getId()); for (Iterator<ZdResult> iters = resultlist.iterator(); iters.hasNext();) { ZdResult zdResult = iters.next(); OtnLink otnLink = new OtnLink(); otnLink.setAendnode(anode); otnLink.setZendnode(znode); otnLink.setDirection(Direction.SINGLE); otnLink.setJump( (long)zdResult.getZdmap().size() ); otnLink.setLinkindex(linkindex++); linklist.add(otnLink); //客户侧路径,根据占用进行判断 if( zdResult.getOdu() instanceof DSR ){ String sncid = zdResult.getSncid(); if( resourceManager.hasCucirtBySncid(sncid) ){ logger.error("移除客户侧路径:"+ sncid ); iters.remove(); continue; } } String key = "OTNLink" + "|" + anode.getId() + "|" + znode.getId() + "|" + otnLink.getLinkindex(); cachedClient.set( memcacTag +key, 0, zdResult ); logger.error("存贮两点间链路的路由数据:"+ memcacTag +key ); } if( resultlist!=null && resultlist.size() > 0 ){ String key = anode.getId() + "|" + znode.getId() ; logger.error("存贮两点间波道数据:"+ memcacTag +key + ",size():" + resultlist.size() ); cachedClient.set( memcacTag +key, 0, resultlist ); } for (Iterator<Integer> iterin = allinputtype.iterator(); iterin.hasNext();) { Integer rate = iterin.next(); String keyfree = "OTNLink_isFress" + "|" + rate + "|" + anode.getId() + "|" + znode.getId() ; if(dealedFreeSet.contains(keyfree)){ continue; } for (int k = 0; k < resultlist.size(); k++) { ZdResult zdResult = resultlist.get(k); if( !zdResult.getODUinfo(rate).equals("")){ cachedClient.set( memcacTag +keyfree, 0, "true" ); dealedFreeSet.add(keyfree); logger.error("存贮两点间链路的路由数据空闲标记:"+ memcacTag +keyfree + ":true" ); break; } } } String dealedkeyReverse = tsnGraph.getEmsid() + "|" +znode.getId() + "|" + anode.getId() ; if( dealedSet.contains( dealedkeyReverse )){ logger.info("处理tsn,站点已经处理过2 :" + dealedkeyReverse); continue ; } dealedSet.add( dealedkeyReverse ); List<ZdResult> resultlistReverse = doAnalyserZdRoute(busiAnalyser, znode.getId(), anode.getId()); for (Iterator<ZdResult> iters = resultlistReverse.iterator(); iters.hasNext();) { ZdResult zdResult = iters.next(); OtnLink otnLink = new OtnLink(); otnLink.setAendnode(znode); otnLink.setZendnode(anode); otnLink.setDirection(Direction.SINGLE); otnLink.setJump( (long)zdResult.getZdmap().size() ); otnLink.setLinkindex(linkindex++); linklist.add(otnLink); //客户侧路径,根据占用进行判断 if( zdResult.getOdu() instanceof DSR ){ String sncid = zdResult.getSncid(); if( resourceManager.hasCucirtBySncid(sncid) ){ logger.error("移除客户侧路径2:"+ sncid ); iters.remove(); continue; } } String key = "OTNLink" + "|" + znode.getId() + "|" + anode.getId() +"|"+ otnLink.getLinkindex(); cachedClient.set( memcacTag +key, 0, zdResult ); logger.error("存贮两点间链路的反向路由数据:"+ memcacTag +key ); } if( resultlistReverse!=null && resultlistReverse.size() > 0 ){ String keyReverse = znode.getId() + "|" + anode.getId() ; logger.error("存贮两点间波道数据:"+ memcacTag +keyReverse + ",size():" + resultlistReverse.size() ); cachedClient.set( memcacTag +keyReverse, 0, resultlistReverse ); } for (Iterator<Integer> iterin = allinputtype.iterator(); iterin.hasNext();) { Integer rate = iterin.next(); String keyfree = "OTNLink_isFress" + "|" + rate + "|" + znode.getId() + "|" + anode.getId() ; if(dealedFreeSet.contains(keyfree)){ continue; } for (int k = 0; k < resultlistReverse.size(); k++) { ZdResult zdResult = resultlistReverse.get(k); if( !zdResult.getODUinfo(rate).equals("")){ cachedClient.set( memcacTag +keyfree, 0, "true" ); dealedFreeSet.add(keyfree); logger.error("存贮两点间链路的路由数据空闲标记2:"+ memcacTag +keyfree + ":true" ); break; } } } } } pool.getPool().returnObject(tsnGraph.getEmsid(), busiAnalyser); } //busiAnalyser = null ; for(Map.Entry<String,ArrayList<String>> zds : zjMap.entrySet()){ if( zds.getValue().size()> 1){ logger.info("转接站点 :" + zds.getKey() +", ems列表:" + Arrays.deepToString(zds.getValue().toArray())); } } ISearch isearch = new ISearch(); BusinessAvator businessAvator = new BusinessAvator(); businessAvator.setKey(PropertiesHander.getProperty("BusinessAvator")); isearch.regist(businessAvator); BaseImporter<OtnLink> baseImporter = new BaseImporter<OtnLink>(linklist); isearch.refreshdata(businessAvator.getKey(), baseImporter); } private List<ZdResult> doAnalyserZdRoute( BusiAnalyser busiAnalyser ,String aendzd , String zendzd){ List<ZdResult> rtnlist = new ArrayList<ZdResult>(); try{ rtnlist = busiAnalyser.analyseOtnResourceV3( aendzd , zendzd ); } catch(Exception e){ logger.error(aendzd+"|"+zendzd+", err accoured",e); } return rtnlist; } }
/* * Copyright (C), 2013-2014, 上海汽车集团股份有限公司 * FileName: OrderDateTimeComparator.java * Author: baowenzhou * Date: 2015年09月15日 下午2:35:18 * Description: //模块目的、功能描述 * History: //修改记录 * <author> <time> <version> <desc> * 修改人姓名 修改时间 版本号 描述 */ package com.xjf.wemall.comparator; import java.util.Comparator; import com.xjf.wemall.api.entity.SampleVo; /** * 美容卡时间排序<br> * 〈功能详细描述〉 * * @author xiejiefeng * @see [相关类/方法](可选) * @since [产品/模块版本] (可选) */ public class treeSetComparator implements Comparator<String>{ // 倒序 @Override public int compare(String card1, String card2) { // card1 当前一个 card2非当前 if (card1.compareTo(card2) >= 0) { return -1; } else { return 1; } } }
package at.ebinterface.validation.rtr.generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. <p/> <p>The following schema fragment specifies the * expected content contained within this class. <p/> * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Version" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="VerificationReport" type="{http://reference.e-government.gv.at/namespace/verificationservice/20120922#}VerificationReportType"/> * &lt;element name="PDFDocument" type="{http://www.w3.org/2001/XMLSchema}base64Binary" * minOccurs="0"/> * &lt;element ref="{http://www.w3.org/2000/09/xmldsig#}Signature"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "version", "verificationReport", "pdfDocument", "signature" }) @XmlRootElement(name = "VerifyDocumentResponse", namespace = "http://reference.e-government.gv.at/namespace/verificationservice/20120922#") public class VerifyDocumentResponse { @XmlElement(name = "Version", namespace = "http://reference.e-government.gv.at/namespace/verificationservice/20120922#") protected Integer version; @XmlElement(name = "VerificationReport", namespace = "http://reference.e-government.gv.at/namespace/verificationservice/20120922#", required = true) protected VerificationReportType verificationReport; @XmlElement(name = "PDFDocument", namespace = "http://reference.e-government.gv.at/namespace/verificationservice/20120922#") protected byte[] pdfDocument; @XmlElement(name = "Signature", required = true) protected SignatureType signature; /** * Gets the value of the version property. * * @return possible object is {@link Integer } */ public Integer getVersion() { return version; } /** * Sets the value of the version property. * * @param value allowed object is {@link Integer } */ public void setVersion(Integer value) { this.version = value; } /** * Gets the value of the verificationReport property. * * @return possible object is {@link VerificationReportType } */ public VerificationReportType getVerificationReport() { return verificationReport; } /** * Sets the value of the verificationReport property. * * @param value allowed object is {@link VerificationReportType } */ public void setVerificationReport(VerificationReportType value) { this.verificationReport = value; } /** * Gets the value of the pdfDocument property. * * @return possible object is byte[] */ public byte[] getPDFDocument() { return pdfDocument; } /** * Sets the value of the pdfDocument property. * * @param value allowed object is byte[] */ public void setPDFDocument(byte[] value) { this.pdfDocument = value; } /** * Gets the value of the signature property. * * @return possible object is {@link SignatureType } */ public SignatureType getSignature() { return signature; } /** * Sets the value of the signature property. * * @param value allowed object is {@link SignatureType } */ public void setSignature(SignatureType value) { this.signature = value; } }
package com.ttps.gestortareas.domain; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="team") public class Team { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String name; @ManyToMany(fetch=FetchType.EAGER) private List<User> members; @ManyToOne(optional=false, cascade=CascadeType.DETACH) @JoinColumn(name = "user_id") private User owner; public Team() { } public Team(String name, List<User> members, User owner) { super(); this.name = name; if (members == null) { this.members = new ArrayList<>(); }else { this.members = members; } this.owner = owner; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<User> getMembers() { return members; } public void setMembers(List<User> members) { this.members = members; } public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } public void addMember(User newMember) { this.members.add(newMember); } }
package fr.polytech.al.tfc.account.business; import fr.polytech.al.tfc.account.model.Account; import fr.polytech.al.tfc.account.model.Transaction; import fr.polytech.al.tfc.account.repository.AccountRepository; import fr.polytech.al.tfc.account.repository.TransactionRepository; import org.springframework.stereotype.Component; @Component public class TransactionBusiness { private final TransactionRepository transactionRepository; private final AccountRepository accountRepository; public TransactionBusiness(TransactionRepository transactionRepository, AccountRepository accountRepository) { this.transactionRepository = transactionRepository; this.accountRepository = accountRepository; } public void processTransaction(Transaction transaction, Account source, Account destination) { transactionRepository.save(transaction); source.processTransaction(transaction, true); accountRepository.save(source); destination.processTransaction(transaction, false); accountRepository.save(destination); } }
public class RomanNumerals { private static final int[] VALUES = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; private static final String[] SYMBOLS = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; public String arabicToRoman(int i) { StringBuilder result = new StringBuilder(); int remaining = i; for (int x = 0; x < VALUES.length; x++) { int value = VALUES[x]; String symbol = SYMBOLS[x]; remaining = appendRomanNumerals(remaining, value, symbol, result); } return result.toString(); } private int appendRomanNumerals(int remaining, int value, String romanDigits, StringBuilder result) { while (remaining >= value) { result.append(romanDigits); remaining -= value; } return remaining; } }