text
stringlengths
10
2.72M
import java.util.*; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Rahat */ public class print_odd_number { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int i,j,start; Scanner input = new Scanner(System.in); System.out.println("Enter the Starting point"); i=input.nextInt(); System.out.println("Enter the ending point"); j=input.nextInt(); for(start=i;start<=j;start++){ if(start%2 != 0){ System.out.println("This is a odd number"+start); } else{ continue; } } } }
/* * 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 evolutionaryagent.evolution.agent.teseo; import evolutionaryagent.evolution.agent.Memory; import evolutionaryagent.types.SparseMatrix; import unalcol.agents.Percept; import unalcol.agents.simulate.util.SimpleLanguage; /** * * @author Camilo Alaguna */ public class TeseoMemory implements Memory { protected SparseMatrix<AgentSquareData> mark; protected SimpleLanguage language; protected int actX, actY; protected int dir; protected int [] dx; protected int [] dy; public static final int NORTH = 0; public static final int EAST = 1; public static final int SOUTH = 2; public static final int WEST = 3; @Override public void init() { mark = new SparseMatrix<AgentSquareData>(); dir = NORTH; dx = new int[4]; dy = new int[4]; dx[NORTH] = -1; dx[EAST] = 0; dx[SOUTH] = 1; dx[WEST] = 0; dy[NORTH] = 0; dy[EAST] = 1; dy[SOUTH] = 0; dy[WEST] = -1; setActualPosition(0, 0); } public void setLanguage(SimpleLanguage language) { this.language = language; } public void setActualPosition(int actX, int actY) { this.actX = actX; this.actY = actY; } public void rotate() { dir = (dir + 1) % 4; } public boolean advance() { setActualPosition(actX + dx[dir], actY + dy[dir]); return !hasBeenExplored(actX, actY); } public void saveActualSquareData(Percept prcpt) { if(mark.get(actX, actY) == null) mark.set(actX, actY, new AgentSquareData()); linkNeighbours(mark.get(actX, actY), prcpt); } private void linkNeighbours(AgentSquareData agentSquareData, Percept prcpt) { for(int i = 0, d = dir; i < 4; ++i, d = (d + 1) % 4) { int x = moveX(d), y = moveY(d); if((Boolean)prcpt.getAttribute(language.getPercept(d))) link(agentSquareData, mark.get(x, y), d); } } private void link(AgentSquareData actual, AgentSquareData neighbour, int dir) { if(neighbour != null) { actual.neighbours[dir] = neighbour; neighbour.neighbours[(dir + 2) % 4] = actual; } } public boolean hasBeenExplored(int x, int y) { return mark.get(x, y) != null; } public int moveX(int dir) { return actX + dx[(this.dir + dir) % 4]; } public int moveY(int dir) { return actY + dy[(this.dir + dir) % 4]; } public AgentSquareData getActualAgentSquareData() { return mark.get(actX, actY); } }
package test; import model.Comment; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import java.lang.reflect.Field; import static org.junit.Assert.assertTrue; public class CommentTest { public static void main(String[] args) { Result result = JUnitCore.runClasses(TestCase.class); if (result.wasSuccessful()) { System.out.println("Excellent - Test ran successfully"); } else { for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } } } public static class TestCase { @Test public void testFields() { Class<?> clazz = Comment.class; Field[] fields = clazz.getDeclaredFields(); assertTrue("Make sure the fields are correct!", fields.length == 6); } @Test public void testExistsAndInheritsFromObject() { Class<?> clazz = Comment.class; assertTrue("Ensure that your file Comment.java extends Objects!", Object.class.isInstance(clazz)); } } }
package animatronics.utils.misc; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraft.util.StatCollector; import net.minecraftforge.oredict.OreDictionary; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import animatronics.utils.helper.NBTHelper; public class ItemUtils{ /** * List of all items in the game. */ public static final String INFO_TAG_WIP = "wip", INFO_TAG_CRASH = "crashcause", INFO_TAG_DEV = "developer_only", INFO_TAG_CREATIVE = "creative_only"; public static List<Item> itemList = Lists.newArrayList(Item.itemRegistry.iterator()); /*public static void numberOfUses(ItemStack iStack, List list){ if(iStack.getMaxDamage() + 1 - iStack.getItemDamage() < iStack.getMaxDamage() / 3){ chatFormatting = EnumChatFormatting.RED; }else if(iStack.getMaxDamage() + 1 - iStack.getItemDamage() < iStack.getMaxDamage() / 1.4){ chatFormatting = EnumChatFormatting.YELLOW; }else{ chatFormatting = EnumChatFormatting.GREEN; } list.add(I18n.getString("numberOfUses") + " " + chatFormatting + (iStack.getMaxDamage() + 1 - iStack.getItemDamage())); }*/ public static ItemStack getItemStack(Object inputObject){ if(inputObject instanceof ArrayList){ if(((ArrayList)inputObject).size() > 0){ Object obj = ((ArrayList)inputObject).get(0); if(obj instanceof ItemStack){ return (ItemStack)inputObject; }else if(obj instanceof Item){ return new ItemStack((Item)obj); }else if(obj instanceof Block){ return new ItemStack((Block)obj); } } } if(inputObject instanceof Item){ return new ItemStack((Item)inputObject); }else if(inputObject instanceof Block){ return new ItemStack((Block)inputObject); }else if(inputObject instanceof ItemStack){ return (ItemStack)inputObject; } return null; } /** * @author King Lemming */ public static boolean areItemStacksEqualNoNBT(ItemStack stackA, ItemStack stackB){ if(stackB == null || stackA == null){ return false; } return stackA.getItem() == stackB.getItem() && (stackA.getItemDamage() == OreDictionary.WILDCARD_VALUE ? true : stackB.getItemDamage() == OreDictionary.WILDCARD_VALUE ? true : !stackA.getHasSubtypes() ? true : stackB.getItemDamage() == stackA.getItemDamage()); } /** * @author King Lemming */ public static boolean itemsEqualWithMetadata(ItemStack stackA, ItemStack stackB, boolean checkNBT){ return stackA == null ? stackB == null ? true : false : stackB != null && stackA.getItem() == stackB.getItem() && stackA.getItemDamage() == stackB.getItemDamage() && (!checkNBT || doNBTsMatch(stackA.stackTagCompound, stackB.stackTagCompound)); } public static void consumeCurrentItem(EntityPlayer player, int count){ if(player.capabilities.isCreativeMode){ return; } if(player.getCurrentEquippedItem().stackSize <= 0){ player.setCurrentItemOrArmor(0, null); }else{ player.getCurrentEquippedItem().splitStack(count); } } /** * @author King Lemming */ public static boolean doNBTsMatch(NBTTagCompound nbtA, NBTTagCompound nbtB){ return nbtA == null ? nbtB == null ? true : false : nbtB == null ? false : nbtA.equals(nbtB); } public static ItemStack createNewWrittenBook(String author, String title, String[] pageText){ ItemStack book = new ItemStack(Items.written_book); NBTTagCompound nbt = NBTHelper.checkNBT(book); nbt.setString("author", author); nbt.setString("title", title); NBTTagList pages = new NBTTagList(); for(int i = 0; i < pageText.length; i++){ pages.appendTag(new NBTTagString(String.valueOf((i + 1)))); } book.setTagInfo("pages", pages); return book; } public static ItemStack cloneStack(ItemStack stack, int stackSize){ if(stack == null) { return null; } ItemStack retStack = stack.copy(); retStack.stackSize = stackSize; return retStack; } public static String getInfoProviderTag(String tagName){ return StatCollector.translateToLocal("info." + tagName); } }
package com.zzx.socket.demo_3_字符流; import java.io.*; import java.net.ServerSocket; import java.net.Socket; @SuppressWarnings("all") public class DemoSocketServer_03 { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(9999); System.out.println("Socket服务端已经开启..."); Socket socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String data = bufferedReader.readLine(); System.out.println("服务端接受到的消息是:" + data); OutputStream outputStream = socket.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); bufferedWriter.write("hello client,你的消息我已收到."); bufferedWriter.newLine(); bufferedWriter.flush(); bufferedWriter.close(); bufferedReader.close(); outputStream.close(); inputStream.close(); socket.close(); serverSocket.close(); System.out.println("Socket服务端已经关闭..."); } }
/* package ru.yandex.ajwar.transparent; import com.sun.javafx.application.PlatformImpl; import javafx.application.Platform; import javafx.scene.Node; import javafx.stage.Stage; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; */ /** * Created by Ajwar on 21.03.2017. *//* public class TempTransparentHelper { private static TransparentHelper transparentHelper; private static ExecutorService executorServiceLoad; private static Stage primaryStage; public static void addTransparent(Stage appStage, Node appNode) throws Exception { // appStage= //TransparentWindowController transparentWindowController = new TransparentWindowController(appStage,appNode); */ /*Platform.runLater(() -> { try { transparentWindowController.getTransparentHelper().start(appStage); } catch (Exception e) { e.printStackTrace(); } });*//* } public static void main(String[] args) throws Exception { TempTransparentHelper.createAndConfigureExecutorsLoadService(); transparentHelper =new TransparentHelper(); */ /**Два способа запуска JavaFx приложения,если они не запущены*//* PlatformImpl.startup(()->{}); //new JFXPanel(); //Application.launch(TransparentHelper.class); */ /* Platform.runLater(() -> { try { transparentHelper.start(); } catch (Exception e) { e.printStackTrace(); } });*//* //System.out.println(TransparentHelper.getPrimaryStage()); while (transparentHelper ==null){ Thread.currentThread().sleep(100); } System.out.println(Platform.isImplicitExit()); Platform.setImplicitExit(false); System.out.println(transparentHelper); Platform.runLater(()->{ primaryStage= transparentHelper.getPrimaryStage(); //transparentHelper.getPrimaryStage().show(); }); while (primaryStage==null){ Thread.currentThread().sleep(100); } primaryStage.show(); System.out.println(primaryStage); */ /*TransparentHelper app=new TransparentHelper(); Stage stage=StageBuilder.create().build();*//* */ /*final Stage[] stage = new Stage[1]; Platform.runLater(() -> { try { stage[0] = app.getInstanceStage(); } catch (Exception e) { e.printStackTrace(); } }); stage[0].show();*//* */ /*app.init(); System.out.println(app.getPrimaryStage()); app.show();*//* } */ /**Инициализация кэшированного пула потоков*//* private static void createAndConfigureExecutorsLoadService() { executorServiceLoad = Executors.newCachedThreadPool(r -> { Thread thread = new Thread(r); thread.setDaemon(true); return thread; }); } public static TransparentHelper getTransparentHelper() { return transparentHelper; } public static void setTransparentHelper(TransparentHelper transparentHelper) { TempTransparentHelper.transparentHelper = transparentHelper; } } */
import java.util.*; /* Final Test * Write code that goes through something and tells me how often things occur * * TreeMap will print out in order * HashMap will be in random order */ public class Mains { public static void main(String[] args){ // LinkedLists System.out.println("LINKEDLISTS" + "\n"); // How to create an empty LinkedList in Java LinkedList<Integer> linkList = new LinkedList<>(); // add() - Appends the specified element to the end of this list. linkList.add(5); linkList.add(42); linkList.add(2); linkList.add(21); linkList.add(1); linkList.add(18); // size() - Returns the number of elements in this list. System.out.println(linkList.size()); // 6 // get() - Returns the element at the specified position in this list. System.out.println(linkList.get(1)); // 42 System.out.println(); // set() - Replaces the element at the specified position in this list with the specified element. linkList.set(3, 15); // 5, 42, 2, 15, 1, 18 // iterator() - Returns an iterator over the elements in this list Iterator<Integer> itr = linkList.iterator(); // listIterator() - Returns a list iterator over the elements in this list Iterator<Integer> iter = linkList.listIterator(); // remove() - Retrieves and removes the head (first element) of this list. linkList.remove(); // 42, 2, 15, 1, 18 // contains() - Returns true if this list contains the specified element. System.out.println(linkList.contains(1)); // true // addFirst() - Inserts the specified element at the beginning of this list. linkList.addFirst(63); // 63, 42, 2, 15, 1, 18 // getFirst() - Returns the first element in this list. System.out.println(linkList.getFirst()); // 63 // removeFirst() - Removes and returns the first element from this list. linkList.removeFirst(); // 42, 2, 15, 1, 18 // addLast() - Appends the specified element to the end of this list. //This method is equivalent to add. linkList.addLast(32); // 42, 2, 15, 1, 18, 32 // getLast() - Returns the last element in this list. System.out.println(linkList.getLast()); // 32 System.out.println(); // removeLast() - Removes and returns the last element from this list. linkList.removeLast(); // 42, 2, 15, 1, 18 // iterating through a LinkedList in 3 different ways // for loop // for each loop // iterator System.out.print("for loop: "); for(int i=0; i<linkList.size();i++){ System.out.print(linkList.get(i) + " "); } System.out.println(); System.out.print("for each loop: "); for(int x : linkList) System.out.print(x + " "); System.out.println(); Iterator<Integer> it = linkList.iterator(); System.out.print("iterator: "); while(it.hasNext()) System.out.print(it.next() + " "); System.out.println("\n"); // Stacks System.out.println("STACK" + "\n"); // create a stack ArrayStack<Character> stk = new ArrayStack<>(); for(char ch = 'A'; ch<='Z'; ch++) stk.push(ch); // push() - adds to the end of the stack System.out.println(stk); // top Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A,bottom for(int i=0; i<10; i++) stk.pop(); // pop() - lets you look at the top of the stack System.out.println("peek(): " + stk.peek()); // peek(): P System.out.println(stk); // top P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A,bottom while(!stk.isEmpty()) stk.pop(); System.out.println(stk); System.out.println(); // Deque System.out.println("DEQUE" + "\n"); Deque<Integer> dQue = new LinkedList<>(); // Queue mode - addLast(), offerLast(), removeFirst(), pollFirst(), getFirst(), peekFirst() dQue.addLast(5); dQue.addLast(10); // Stack mode - addFirst(), removeFirst(), peekFirst() // Queue System.out.println("QUEUES" + "\n"); Queue<Integer> QUQ = new LinkedList<>(); // add() - Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. // adds to the end of the list QUQ.add(10); QUQ.add(25); QUQ.add(63); QUQ.add(5); QUQ.add(43); QUQ.add(1); QUQ.add(32); for(int x : QUQ) System.out.print(x + " "); // 10 25 63 5 43 1 32 System.out.println(); // poll() - Retrieves and removes the head of this queue, or returns null if this queue is empty. System.out.println("poll()- " + QUQ.poll()); // poll()- 10 System.out.println("poll()- " + QUQ.poll()); // poll()- 25 // peek() - Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. System.out.println("peek()- " + QUQ.peek()); // peek()- 63 // size() - Returns the number of elements in this collection. System.out.println("size()- " + QUQ.size()); // size()- 5 for(int x : QUQ) System.out.print(x + " "); // 63 5 43 1 32 System.out.println("\n"); //PriorityQueue System.out.println("PriorityQueues" + "\n"); // Know how to create an empty PriorityQueue. PriorityQueue<Integer> que = new PriorityQueue<>(); // How to create a PriorityQueue using a custom comparator PriorityQueue<Integer> pQ = new PriorityQueue<>(10, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); } }); // How to implement a class that implements the Comparator<E> interface. PriorityQueue<Integer> p = new PriorityQueue<>(10, new PQ()); // add() - Inserts the specified element into this priority queue. O(log(n)) p.add(39); p.add(7); p.add(41); p.add(30); p.add(17); p.add(29); p.add(17); p.add(20); for(int x : p) System.out.print(x + " "); // 41 30 39 20 17 29 17 7 System.out.println(); // poll() - Retrieves and removes the head of this queue, or returns null if this queue is empty O(log(n)) System.out.println("poll() - " + p.poll()); // 39 30 29 20 17 7 17 // peek() - Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty O(1) System.out.println("peek() - " + p.peek()); // 39 // size() - Returns the number of elements in this collection. O(1) System.out.println("size() - " + p.size()); // 7 // isEmpty() - Returns true if this collection contains no elements. O(1) System.out.println("isEmpty() - " + p.isEmpty()); // false for(int x : p) System.out.print(x + " "); System.out.println(); // HEAPS - insertElement() and removeMin() /* add(x): 1.put x as a child of the node as far to the bottom left as you can go, where each level must be filled in. 2.Let p = the parent of x. 3.while p > x and x isn't the root swap p and x set x = p set p = the parent of p poll(): 1.swap the root with the last element in the tree. 2.delete the last element in the tree 3.find the minimum if the root, the root's left, and the root's right (assuming they exist) 4.if the root is the smallest (or it's the only element), stop. 5.else, repeat 3 and 4 with the smaller child. */ System.out.println("\n"); // SETS System.out.println("SETS" + "\n"); // How to create a TreeSet and HashSet HashSet<Integer> set1 = new HashSet<>(); TreeSet<Integer> set2 = new TreeSet<>(); // add() - Adds the specified element to this set if it is not already present. set1.add(5); set1.add(10); set1.add(3); set1.add(7); set1.add(12); set1.add(1); set2.add(5); set2.add(10); set2.add(3); set2.add(7); set2.add(12); set2.add(1); set2.add(15); // contains() - Returns true if this set contains the specified element. System.out.println("Set1 contains 1: " +set1.contains(1)); // true System.out.println("Set1 contains 50: " +set1.contains(50) + "\n"); // false // remove() - Removes the specified element from this set if it is present. set1.remove(12); // 1, 3, 5, 7, 10 set1.remove(1); // 3, 5, 7, 10 set1.remove(9); // Iterating using an Iterator System.out.print("Hashset using Iterator: "); Iterator<Integer> itr1 = set1.iterator(); while(itr1.hasNext()) System.out.print(itr1.next() + " "); System.out.println(); // Iterating using a for loop System.out.print("Hashset using for loop: "); for(int x : set1) System.out.print(x + " "); System.out.println(); System.out.print("Treeset: "); Iterator<Integer> itr2 = set2.iterator(); while(itr2.hasNext()) System.out.print(itr2.next() + " "); System.out.println("\n"); /* * removeAll() - is a new set that contains the elements that are in A but not in B. (A=A-B) A.removeAll(B); * */ //removeAll() set2 - {1, 3, 5, 7, 10, 12, 15} set1 - {3, 5, 7, 10} set2.removeAll(set1); // 1, 12, 15 System.out.print("Hashset using removeAll(): "); for(int x : set2) System.out.print(x + " "); System.out.println(); //addAll() - For 2 sets A and B, A union B is a new set that contains elements from A and B combined. set2.addAll(set1); // 1, 3, 5, 7, 10, 12, 15 System.out.print("Hashset using addAll(): "); for(int x : set2) System.out.print(x + " "); System.out.println(); //retainAll() - For 2 sets A and B, A intersect B is a new set that contains only elements that are both in A and B. set2.retainAll(set1); // 3, 5, 7, 10 System.out.print("Hashset using retainAll(): "); for(int x : set2) System.out.print(x + " "); System.out.println(); // MAPS System.out.println("MAPS" + "\n"); // How to create an empty map using HashMap or TreeMap Map<Character, Integer> map1 = new HashMap<>(); Map<Integer, Integer> map2 = new TreeMap<>(); // put() - associates the specified value with the specified key in this map // A map cannot contain duplicate keys; each key can map to at most one value. map1.put('c', 1); map1.put('a',5); map1.put('b',2); map1.put('g',8); map1.put('z',10); map1.put('a',9); // will associate 9 with 'a' instead of 5 // How to iterate through a map, 2 different ways using sets - keySet() and entrySet() // either iterate through the keys and find the values or // iterate through the set of pairs and pull out the keys and values from set of pairs System.out.println("Using entrySet()"); // Works well for both Maps for(Map.Entry<Character, Integer> entry: map1.entrySet()){ char key = entry.getKey(); int value = entry.getValue(); System.out.println("key: " + key + " value: " + value); } System.out.println(); System.out.println("Using keySet()"); // Ony works well for HashMap for(char key: map1.keySet()){ int value = map1.get(key); System.out.println("key: " + key + " value: " + value); } System.out.println(); // containsKey() - returns true if the map contains the given key System.out.println(map1.containsKey('d')); // false System.out.println(map1.containsKey('z')); // true System.out.println(); // get() - returns the value to which the specified key is mapped, or null if // this map contains no mapping for the key. System.out.println(map1.get('d')); // null System.out.println(map1.get('z')); // 10 System.out.println(); // containsValue() - returns true if this map maps one or more keys to the // specified value. System.out.println(map1.containsValue(0)); // false System.out.println(map1.containsValue(10)); // true System.out.println(); // entrySet() - Returns a Set view of the mappings contained in this map. System.out.println(map1.entrySet()); // [g=8, b=2, c=1, a=9, z=10] System.out.println(); // keySet() - Returns a Set view of the keys contained in this map. System.out.println(map1.keySet()); // [g, b, c, a, z] System.out.println(); System.out.println("BINARY SEARCH TREES"); System.out.println(); /* * A Binary Search Tree is a binary tree where every node obeys the BST property. * The BST property is that for every node x * x.left.key <= x.key and x.right.key >= x.key */ BinarySearchTree tree = new BinarySearchTree(); tree.add(50); tree.add(30); tree.add(20); tree.add(40); tree.add(70); tree.add(60); tree.add(80); // LNR - 20, 30, 40, 50, 60, 70, 80 System.out.println("BST inorder:"); tree.inOrder(); System.out.println(); // NLR - 50, 30, 20, 40, 70, 60, 80 System.out.println("BST pre-order:"); tree.preOrder(); System.out.println(); // LRN - 20, 40, 30, 60, 80, 70, 50 System.out.println("BST post order:"); tree.postOrder(); System.out.println(); } }
package com.example.mlkitshow; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.huawei.hmf.tasks.OnFailureListener; import com.huawei.hmf.tasks.OnSuccessListener; import com.huawei.hmf.tasks.Task; import com.huawei.hms.mlsdk.MLAnalyzerFactory; import com.huawei.hms.mlsdk.common.MLCoordinate; import com.huawei.hms.mlsdk.common.MLException; import com.huawei.hms.mlsdk.common.MLFrame; import com.huawei.hms.mlsdk.landmark.MLRemoteLandmark; import com.huawei.hms.mlsdk.landmark.MLRemoteLandmarkAnalyzer; import java.io.IOException; import java.util.ArrayList; import java.util.List; //1.define textview and imageview to show the result.define button to browse photo //2.create an action to browse ur phone photo gallery //3.return result after select the photo //4.create analyzer and pass the result in bitmap format to process the result public class LandmarkActivity extends AppCompatActivity implements View.OnClickListener { private TextView mTextView; private ImageView imageView; static final int REQUEST_CODE_PHOTO = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_landmark); mTextView = this.findViewById(R.id.text_result); imageView = this.findViewById(R.id.image_view); findViewById(R.id.btn_browse).setOnClickListener(this); } @Override public void onClick(View v) { if (v.getId() == R.id.btn_browse) { Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); LandmarkActivity.this.startActivityForResult(pickIntent, REQUEST_CODE_PHOTO); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_PHOTO) { final Uri uri = data.getData(); Bitmap bitmap = null; try { bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri); RemoteLandAnalyzer(bitmap); } catch (IOException e) { e.printStackTrace(); } } } private void RemoteLandAnalyzer(final Bitmap bitmap) { MLRemoteLandmarkAnalyzer analyzer = MLAnalyzerFactory.getInstance().getRemoteLandmarkAnalyzer(); MLFrame mlFrame = new MLFrame.Creator().setBitmap(bitmap).create(); Task<List<MLRemoteLandmark>> task = analyzer.asyncAnalyseFrame(mlFrame); task.addOnSuccessListener(new OnSuccessListener<List<MLRemoteLandmark>>() { public void onSuccess(List<MLRemoteLandmark> landmarkResults) { List<MLCoordinate> mlCoordinates = new ArrayList<MLCoordinate>(); mlCoordinates.add(landmarkResults.get(0).getPositionInfos().get(0)); mTextView.setText(landmarkResults.get(0).getLandmark() + "\n" + mlCoordinates.get(0).getLat() + " " + mlCoordinates.get(0).getLng() + "\n"); imageView.setImageBitmap(bitmap); } }) .addOnFailureListener(new OnFailureListener() { public void onFailure(Exception e) { try { MLException mlException = (MLException) e; } catch (Exception error) { } } }); } }
/* * 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 View.Home; import Controller.UsuarioDAO; import Model.Usuario; import java.awt.Event; import javax.swing.JOptionPane; /** * * @author Tadeu */ public class Frm_alteraSenha extends javax.swing.JFrame { int tentativas; String usuarioLogado; UsuarioDAO usuarioDAO; Usuario usuario; public Frm_alteraSenha(String usuario) { initComponents(); setVisible(true); usuarioLogado=usuario; } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { pnl_alteraSenha = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); txt_antigaSenha = new javax.swing.JPasswordField(); txt_novaSenha = new javax.swing.JPasswordField(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txt_confirmaSenha = new javax.swing.JPasswordField(); btn_salvar = new javax.swing.JButton(); btn_fechar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Alteração de senha"); pnl_alteraSenha.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel2.setText("Antiga Senha*:"); txt_antigaSenha.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_antigaSenhaKeyPressed(evt); } }); txt_novaSenha.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_novaSenhaKeyPressed(evt); } }); jLabel3.setText("Nova Senha*:"); jLabel5.setText("Confirma Senha*:"); txt_confirmaSenha.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txt_confirmaSenhaKeyPressed(evt); } }); btn_salvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Util/Img/salvar.png"))); // NOI18N btn_salvar.setText("Salvar"); btn_salvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_salvarActionPerformed(evt); } }); btn_fechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Util/Img/fechar.png"))); // NOI18N btn_fechar.setText("Fechar"); btn_fechar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_fecharActionPerformed(evt); } }); javax.swing.GroupLayout pnl_alteraSenhaLayout = new javax.swing.GroupLayout(pnl_alteraSenha); pnl_alteraSenha.setLayout(pnl_alteraSenhaLayout); pnl_alteraSenhaLayout.setHorizontalGroup( pnl_alteraSenhaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnl_alteraSenhaLayout.createSequentialGroup() .addContainerGap() .addGroup(pnl_alteraSenhaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnl_alteraSenhaLayout.createSequentialGroup() .addGroup(pnl_alteraSenhaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnl_alteraSenhaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txt_novaSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE) .addComponent(txt_confirmaSenha) .addComponent(txt_antigaSenha)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl_alteraSenhaLayout.createSequentialGroup() .addComponent(btn_fechar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btn_salvar))) .addContainerGap()) ); pnl_alteraSenhaLayout.setVerticalGroup( pnl_alteraSenhaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnl_alteraSenhaLayout.createSequentialGroup() .addContainerGap() .addGroup(pnl_alteraSenhaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txt_antigaSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnl_alteraSenhaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txt_novaSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnl_alteraSenhaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(txt_confirmaSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnl_alteraSenhaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btn_salvar) .addComponent(btn_fechar)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(pnl_alteraSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(pnl_alteraSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void txt_antigaSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_antigaSenhaKeyPressed if (evt.getKeyCode() == Event.ENTER) { txt_novaSenha.requestFocus(); } }//GEN-LAST:event_txt_antigaSenhaKeyPressed private void txt_novaSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_novaSenhaKeyPressed if (evt.getKeyCode() == Event.ENTER) { txt_confirmaSenha.requestFocus(); } }//GEN-LAST:event_txt_novaSenhaKeyPressed private void txt_confirmaSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_confirmaSenhaKeyPressed if (evt.getKeyCode() == Event.ENTER) { btn_salvar.requestFocus(); } }//GEN-LAST:event_txt_confirmaSenhaKeyPressed private void btn_salvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_salvarActionPerformed validaCampos(txt_antigaSenha.getText(), txt_novaSenha.getText(), txt_confirmaSenha.getText()); }//GEN-LAST:event_btn_salvarActionPerformed private void btn_fecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_fecharActionPerformed dispose(); }//GEN-LAST:event_btn_fecharActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Frm_alteraSenha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Frm_alteraSenha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Frm_alteraSenha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Frm_alteraSenha.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { // new Frm_alteraSenha().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_fechar; private javax.swing.JButton btn_salvar; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JPanel pnl_alteraSenha; private javax.swing.JPasswordField txt_antigaSenha; private javax.swing.JPasswordField txt_confirmaSenha; private javax.swing.JPasswordField txt_novaSenha; // End of variables declaration//GEN-END:variables private void validaCampos(String antigaSenha, String novaSenha, String confirmaSenha) { if (antigaSenha.isEmpty()) { JOptionPane.showMessageDialog(null, "Antiga Senha inválida!"); txt_antigaSenha.requestFocus(); } else { if (novaSenha.isEmpty()) { JOptionPane.showMessageDialog(null, "Nova Senha inválida!"); txt_novaSenha.requestFocus(); } else { if (confirmaSenha.isEmpty()) { JOptionPane.showMessageDialog(null, "Confirmação da Nova Senha inválida!"); txt_confirmaSenha.requestFocus(); } else { if (novaSenha.equals(confirmaSenha) == false) { JOptionPane.showMessageDialog(null, "Senhas Diferentes"); txt_novaSenha.setText(null); txt_confirmaSenha.setText(null); txt_novaSenha.requestFocus(); } else { validaAntigaSenha(antigaSenha, novaSenha); } } } } } private void validaAntigaSenha(String antigaSenha, String novaSenha) { try { usuarioDAO=new UsuarioDAO(); usuario=new Usuario(); usuario=usuarioDAO.buscar(usuarioLogado); if(usuario.getSenha().equals(antigaSenha)==true){ usuario.setSenha(novaSenha); usuarioDAO.salvar(usuario); }else{ JOptionPane.showMessageDialog(null, "Senha inválida para o usuário "+usuarioLogado+"!"); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao alterar a senha!\n"+e.getMessage()); } } }
package com.suntiago.network.network; import android.content.Context; import android.text.TextUtils; import com.suntiago.network.network.utils.SPUtils; import com.suntiago.network.network.utils.Slog; import java.util.HashMap; import retrofit2.Retrofit; public class Api { private static final String TAG = Api.class.getSimpleName(); private static String BASE_URL = ""; private HashMap<String, HashMap<Class, Object>> mApiObjects = new HashMap(); private static Api sApi; //通过netty连接后台服务器 网络地址配置 public static String NETTY_HOST = ""; public static int NETTY_HOST_PORT = 0; private Api() { mApiObjects = new HashMap<>(); } static Context sContext; private HashMap<String, HashMap<String, String>> headersKeyValue = new HashMap(); public static void init(Context context) { sContext = context; SPUtils sp = SPUtils.getInstance(context); BASE_URL = sp.get("ip", Api.get().BASE_URL); NETTY_HOST = sp.get("NETTY_HOST", NETTY_HOST); NETTY_HOST_PORT = sp.get("UPDATE_HOST_PORT", NETTY_HOST_PORT); } public static Api get() { if (sApi == null) { sApi = new Api(); } return sApi; } public Api addHeader(String host, String key, String value) { if (TextUtils.isEmpty(host) || TextUtils.isEmpty(key)) { return this; } if (headersKeyValue.containsKey(host)) { HashMap h = headersKeyValue.get(host); if (h.containsKey(key)) { h.remove(key); } if (TextUtils.isEmpty(value)) { h.put(key, value); } return this; } else { headersKeyValue.put(host, new HashMap<String, String>()); return addHeader(host, key, value); } } private HashMap getHeaders(String host) { if (TextUtils.isEmpty(host)) { return null; } if (headersKeyValue.containsKey(host)) { return headersKeyValue.get(host); } else { return null; } } private <T> T getApiObjects(String host, Class<T> tClass) { if (TextUtils.isEmpty(host)) { return null; } if (mApiObjects.containsKey(host)) { HashMap hashMap = mApiObjects.get(host); if (hashMap.containsKey(tClass)) { return (T) hashMap.get(tClass); } } else { return null; } return null; } private <T> void addApiObjects(String host, Class<T> tClass, Object o) { if (TextUtils.isEmpty(host)) { return; } if (mApiObjects.containsKey(host)) { HashMap hashMap = mApiObjects.get(host); if (hashMap.containsKey(tClass)) { hashMap.remove(tClass); } hashMap.put(tClass, o); } else { mApiObjects.put(host, new HashMap<Class, Object>()); addApiObjects(host, tClass, o); } } public synchronized <T> T getApi(Class<T> tClass) { Slog.d(TAG, "getApi [tClass]:"); if (getApiObjects(BASE_URL, tClass) != null) { return getApiObjects(BASE_URL, tClass); } Retrofit retrofit = new Retrofit.Builder() .client(HttpManager.getHttpClient(getHeaders(BASE_URL), HttpLogInterceptor.Level.BODY)) .baseUrl(BASE_URL) .addConverterFactory(HttpManager.sGsonConverterFactory) .addCallAdapterFactory(HttpManager.sRxJavaCallAdapterFactory) .build(); addApiObjects(BASE_URL, tClass, retrofit.create(tClass)); return (T) getApiObjects(BASE_URL, tClass); } public synchronized <T> T getApi(Class<T> tClass, String baseUrl) { Slog.d(TAG, "getApi [tClass]:"); if (getApiObjects(baseUrl, tClass) != null) { return getApiObjects(baseUrl, tClass); } Retrofit retrofit = new Retrofit.Builder() .client(HttpManager.getHttpClient(getHeaders(baseUrl), HttpLogInterceptor.Level.BODY)) .baseUrl(baseUrl) .addConverterFactory(HttpManager.sGsonConverterFactory) .addCallAdapterFactory(HttpManager.sRxJavaCallAdapterFactory) .build(); addApiObjects(baseUrl, tClass, retrofit.create(tClass)); return (T) getApiObjects(baseUrl, tClass); } public void setApiConfig(String api, String netty_host, int netty_port) { SPUtils.getInstance(sContext).put("ip", api); SPUtils.getInstance(sContext).put("NETTY_HOST", netty_host); SPUtils.getInstance(sContext).put("UPDATE_HOST_PORT", netty_port); BASE_URL = api; NETTY_HOST = netty_host; NETTY_HOST_PORT = netty_port; mApiObjects.clear(); } public String getApi() { return BASE_URL; } }
#include<stdio.h> int main() { int n,s,sum=0; scanf("%d %d",&n,&s); int arr[n]; for(int i=0;i<n;i++) { scanf("%d",&arr[i]); } int f=(n-1); for(int i=0;i<f;i++) sum=sum+arr[i]; if(sum>s) printf("NO"); else printf("YES"); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.apache.clerezza.utils; import org.apache.clerezza.*; import org.apache.clerezza.implementation.TripleImpl; import org.apache.clerezza.implementation.in_memory.SimpleGraph; import org.apache.clerezza.implementation.literal.PlainLiteralImpl; import org.apache.clerezza.test.utils.RandomGraph; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * @author reto, mir */ @RunWith(JUnitPlatform.class) public class TestGraphNode { @Test public void nodeContext() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); IRI property2 = new IRI("http://example.org/property2"); g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); g.add(new TripleImpl(bNode1, property2, property1)); g.add(new TripleImpl(bNode2, property2, bNode1)); g.add(new TripleImpl(property1, property1, bNode2)); g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); GraphNode n = new GraphNode(bNode1, g); Assertions.assertEquals(4, n.getNodeContext().size()); n.deleteNodeContext(); Assertions.assertEquals(1, g.size()); Assertions.assertFalse(n.getObjects(property2).hasNext()); } @Test public void addNode() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); GraphNode n = new GraphNode(bNode1, g); n.addProperty(property1, bNode2); Assertions.assertEquals(1, g.size()); } @Test public void testGetSubjectAndObjectNodes() { RandomGraph graph = new RandomGraph(500, 20, new SimpleGraph()); for (int j = 0; j < 200; j++) { Triple randomTriple = graph.getRandomTriple(); GraphNode node = new GraphNode(randomTriple.getSubject(), graph); Iterator<IRI> properties = node.getProperties(); while (properties.hasNext()) { IRI property = properties.next(); Set<RDFTerm> objects = createSet(node.getObjects(property)); Iterator<GraphNode> objectNodes = node.getObjectNodes(property); while (objectNodes.hasNext()) { GraphNode graphNode = objectNodes.next(); Assertions.assertTrue(objects.contains(graphNode.getNode())); } } } for (int j = 0; j < 200; j++) { Triple randomTriple = graph.getRandomTriple(); GraphNode node = new GraphNode(randomTriple.getObject(), graph); Iterator<IRI> properties = node.getProperties(); while (properties.hasNext()) { IRI property = properties.next(); Set<RDFTerm> subjects = createSet(node.getSubjects(property)); Iterator<GraphNode> subjectNodes = node.getSubjectNodes(property); while (subjectNodes.hasNext()) { GraphNode graphNode = subjectNodes.next(); Assertions.assertTrue(subjects.contains(graphNode.getNode())); } } } } @Test public void getAvailableProperties() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); IRI property2 = new IRI("http://example.org/property2"); IRI property3 = new IRI("http://example.org/property3"); IRI property4 = new IRI("http://example.org/property4"); ArrayList<IRI> props = new ArrayList<IRI>(); props.add(property1); props.add(property2); props.add(property3); props.add(property4); GraphNode n = new GraphNode(bNode1, g); n.addProperty(property1, bNode2); n.addProperty(property2, bNode2); n.addProperty(property3, bNode2); n.addProperty(property4, bNode2); Iterator<IRI> properties = n.getProperties(); int i = 0; while (properties.hasNext()) { i++; IRI prop = properties.next(); Assertions.assertTrue(props.contains(prop)); props.remove(prop); } Assertions.assertEquals(i, 4); Assertions.assertEquals(props.size(), 0); } @Test public void deleteAll() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); IRI property2 = new IRI("http://example.org/property2"); //the two properties two be deleted g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("bla bla"))); //this 3 properties should stay g.add(new TripleImpl(bNode1, property2, property1)); g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); g.add(new TripleImpl(bNode2, property1, new PlainLiteralImpl("bla bla"))); GraphNode n = new GraphNode(bNode1, g); n.deleteProperties(property1); Assertions.assertEquals(3, g.size()); } @Test public void deleteSingleProperty() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); IRI property2 = new IRI("http://example.org/property2"); //the properties two be deleted g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); //this 4 properties should stay g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("bla bla"))); g.add(new TripleImpl(bNode1, property2, property1)); g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); g.add(new TripleImpl(bNode2, property1, new PlainLiteralImpl("bla bla"))); GraphNode n = new GraphNode(bNode1, g); n.deleteProperty(property1, new PlainLiteralImpl("literal")); Assertions.assertEquals(4, g.size()); } @Test public void replaceWith() { Graph initialGraph = new SimpleGraph(); BlankNode bNode1 = new BlankNode(); BlankNode bNode2 = new BlankNode(); BlankNode newBnode = new BlankNode(); IRI property1 = new IRI("http://example.org/property1"); IRI property2 = new IRI("http://example.org/property2"); IRI newIRI = new IRI("http://example.org/newName"); Literal literal1 = new PlainLiteralImpl("literal"); Literal literal2 = new PlainLiteralImpl("bla bla"); Triple triple1 = new TripleImpl(bNode1, property1, literal1); Triple triple2 = new TripleImpl(bNode1, property2, property1); Triple triple3 = new TripleImpl(bNode2, property2, bNode1); Triple triple4 = new TripleImpl(property1, property1, bNode2); Triple triple5 = new TripleImpl(property1, property1, literal2); initialGraph.add(triple1); initialGraph.add(triple2); initialGraph.add(triple3); initialGraph.add(triple4); initialGraph.add(triple5); GraphNode node = new GraphNode(property1, new SimpleGraph(initialGraph.iterator())); node.replaceWith(newIRI, true); Assertions.assertEquals(5, node.getGraph().size()); Triple expectedTriple1 = new TripleImpl(bNode1, newIRI, literal1); Triple expectedTriple2 = new TripleImpl(bNode1, property2, newIRI); Triple expectedTriple3 = new TripleImpl(newIRI, newIRI, bNode2); Triple expectedTriple4 = new TripleImpl(newIRI, newIRI, literal2); Assertions.assertTrue(node.getGraph().contains(expectedTriple1)); Assertions.assertTrue(node.getGraph().contains(expectedTriple2)); Assertions.assertTrue(node.getGraph().contains(expectedTriple3)); Assertions.assertTrue(node.getGraph().contains(expectedTriple4)); Assertions.assertFalse(node.getGraph().contains(triple1)); Assertions.assertFalse(node.getGraph().contains(triple2)); Assertions.assertFalse(node.getGraph().contains(triple4)); Assertions.assertFalse(node.getGraph().contains(triple5)); node = new GraphNode(property1, new SimpleGraph(initialGraph.iterator())); node.replaceWith(newBnode); Triple expectedTriple5 = new TripleImpl(bNode1, property2, newBnode); Triple expectedTriple6 = new TripleImpl(newBnode, property1, bNode2); Triple expectedTriple7 = new TripleImpl(newBnode, property1, literal2); Assertions.assertTrue(node.getGraph().contains(triple1)); Assertions.assertTrue(node.getGraph().contains(expectedTriple5)); Assertions.assertTrue(node.getGraph().contains(expectedTriple6)); Assertions.assertTrue(node.getGraph().contains(expectedTriple7)); node = new GraphNode(literal1, new SimpleGraph(initialGraph.iterator())); node.replaceWith(newBnode); Triple expectedTriple8 = new TripleImpl(bNode1, property1, newBnode); Assertions.assertTrue(node.getGraph().contains(expectedTriple8)); node = new GraphNode(property1, new SimpleGraph(initialGraph.iterator())); node.replaceWith(newIRI); Triple expectedTriple9 = new TripleImpl(bNode1, property2, newIRI); Triple expectedTriple10 = new TripleImpl(newIRI, property1, bNode2); Triple expectedTriple11 = new TripleImpl(newIRI, property1, literal2); Assertions.assertTrue(node.getGraph().contains(triple1)); Assertions.assertTrue(node.getGraph().contains(expectedTriple9)); Assertions.assertTrue(node.getGraph().contains(expectedTriple10)); Assertions.assertTrue(node.getGraph().contains(expectedTriple11)); } @Test public void equality() { Graph g = new SimpleGraph(); BlankNode bNode1 = new BlankNode() { }; BlankNode bNode2 = new BlankNode() { }; IRI property1 = new IRI("http://example.org/property1"); GraphNode n = new GraphNode(bNode1, g); n.addProperty(property1, bNode2); Assertions.assertTrue(n.equals(new GraphNode(bNode1, g))); Assertions.assertFalse(n.equals(new GraphNode(bNode2, g))); GraphNode n2 = null; Assertions.assertFalse(n.equals(n2)); } private Set<RDFTerm> createSet(Iterator<? extends RDFTerm> resources) { Set<RDFTerm> set = new HashSet<RDFTerm>(); while (resources.hasNext()) { RDFTerm resource = resources.next(); set.add(resource); } return set; } }
package practice10; public class Klass { int number; Student leader; public Klass(int Mynumber) { number = Mynumber; } public int getNumber() { return number; } public String getDisplayName() { return "Class " + number; } public boolean assignLeader(Student student) { if (student.klass == this) { this.leader = student; return true; } else { System.out.print("It is not one of us.\n"); this.leader=null; return false; } } public Student getLeader() { return leader; } public void appendMember(Student student) { student.klass = this; } }
package com.tencent.mm.sdk.platformtools; import android.os.SystemClock; import java.util.ArrayList; public final class bg { private boolean gnY = false; private String mTag; private String sJj; ArrayList<Long> sJk; ArrayList<String> sJl; public bg(String str, String str2) { this.mTag = str; this.sJj = str2; if (!this.gnY) { if (this.sJk == null) { this.sJk = new ArrayList(); this.sJl = new ArrayList(); } else { this.sJk.clear(); this.sJl.clear(); } addSplit(null); } } public final void addSplit(String str) { if (!this.gnY) { this.sJk.add(Long.valueOf(SystemClock.elapsedRealtime())); this.sJl.add(str); } } public final void dumpToLog() { if (!this.gnY) { x.d(this.mTag, this.sJj + ": begin"); long longValue = ((Long) this.sJk.get(0)).longValue(); long j = longValue; for (int i = 1; i < this.sJk.size(); i++) { j = ((Long) this.sJk.get(i)).longValue(); x.d(this.mTag, this.sJj + ": " + (j - ((Long) this.sJk.get(i - 1)).longValue()) + " ms, " + ((String) this.sJl.get(i))); } x.d(this.mTag, this.sJj + ": end, " + (j - longValue) + " ms"); } } }
package com.info.proyectoFinal.controllers; import com.info.proyectoFinal.holder.PutUsuarioHolder; import com.info.proyectoFinal.models.Usuario; import com.info.proyectoFinal.repositories.UsuarioRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; import java.util.LinkedList; import java.util.Optional; @Controller @RequestMapping(path="/usuario") public class UsuarioController { @Autowired UsuarioRepository usuarioRepository; @GetMapping(path = "/") public @ResponseBody Iterable<Usuario> getUsuario(){ return usuarioRepository.findAll(); } @PostMapping(path = "/crear") public @ResponseBody ResponseEntity<String> postUsuario(@RequestBody Usuario usuario){ try { usuario.setCreacion(LocalDate.now()); usuarioRepository.save(usuario); return new ResponseEntity<>( "CREATED: Se ha creado un nuevo usuario.", HttpStatus.CREATED); } catch (Exception e){ return new ResponseEntity<>( "CONFLICT: Verifique que el email sea unico y que todos los campos esten cargados.", HttpStatus.CONFLICT); } } @PutMapping(path = "/actualizar") public ResponseEntity<String> putUsuario(@RequestBody PutUsuarioHolder usuarioHolder){ Optional<Usuario> resultado = usuarioRepository.findById(usuarioHolder.getId()); if(!(resultado.isPresent())){ return new ResponseEntity<>( "NOT FOUND: No se ha encontrado ningun usuario que coincida con la ID especificada.", HttpStatus.NOT_FOUND); } else{ LocalDate fechaOriginal = resultado.get().getCreacion(); usuarioHolder.getUsuario().setId(usuarioHolder.getId()); usuarioHolder.getUsuario().setCreacion(fechaOriginal); usuarioRepository.save(usuarioHolder.getUsuario()); return new ResponseEntity<>( "OK: Se ha actualizado la informacion del usuario.", HttpStatus.OK); } } @DeleteMapping(path = "/borrar") public ResponseEntity<String> deleteUsuario(@RequestBody PutUsuarioHolder usuarioHolder){ Optional<Usuario> resultado = usuarioRepository.findById(usuarioHolder.getId()); if(!(resultado.isPresent())){ return new ResponseEntity<>( "NOT FOUND: No se ha encontrado ningun usuario que coincida con la ID especificada.", HttpStatus.NOT_FOUND); } else{ usuarioRepository.delete(resultado.get()); return new ResponseEntity<>( "OK: Se ha eliminado al usuario del sistema.", HttpStatus.OK); } } @GetMapping(path = "/filtrar") public @ResponseBody Iterable<Usuario> filtrarUsuario(@RequestParam String tipo, @RequestParam String valor){ return filtrar(tipo, valor); } private LinkedList<Usuario> filtrar(String tipo, String valor){ LinkedList<Usuario> resultadoFiltrado = new LinkedList<Usuario>(); Iterable<Usuario> resultado = usuarioRepository.findAll(); valor = valor.toLowerCase(); switch (tipo.toLowerCase()) { case "nombre": for (Usuario actual : resultado){ if (actual.getNombre().toLowerCase().equals(valor)){ resultadoFiltrado.add(actual); } } break; case "apellido": for (Usuario actual : resultado){ if (actual.getApellido().toLowerCase().equals(valor)){ resultadoFiltrado.add(actual); } } break; case "ciudad": for (Usuario actual : resultado){ if (actual.getCiudad().toLowerCase().equals(valor)){ resultadoFiltrado.add(actual); } } break; case "provincia": for (Usuario actual : resultado){ if (actual.getProvincia().toLowerCase().equals(valor)){ resultadoFiltrado.add(actual); } } break; case "pais": for (Usuario actual : resultado){ if (actual.getPais().toLowerCase().equals(valor)){ resultadoFiltrado.add(actual); } } break; case "creacion": for (Usuario actual : resultado){ LocalDate referencia = LocalDate.parse(valor); if (actual.getCreacion().isAfter(referencia)){ resultadoFiltrado.add(actual); } } break; default: LinkedList<Usuario> lista = new LinkedList<>(); for (Usuario actual : resultado){ lista.add(actual); } return lista; } return resultadoFiltrado; } }
package com.harrymt.productivitymapping.database; import android.app.Notification; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.location.Location; import android.os.Bundle; import android.service.notification.StatusBarNotification; import android.util.Log; import com.harrymt.productivitymapping.coredata.NotificationParts; import com.harrymt.productivitymapping.PROJECT_GLOBALS; import com.harrymt.productivitymapping.coredata.Session; import com.harrymt.productivitymapping.coredata.Zone; import com.harrymt.productivitymapping.utility.MapUtil; import com.harrymt.productivitymapping.utility.NotificationUtil; import com.harrymt.productivitymapping.utility.Util; import java.util.ArrayList; import java.util.Map; import static com.harrymt.productivitymapping.database.DatabaseSchema.*; /** * The adapter that interacts with the database. */ public class DatabaseAdapter { private static final String TAG = PROJECT_GLOBALS.LOG_NAME + "DatabaseAdapter"; // Helper methods. private DatabaseHelper dbHelper; // Reference to the actual database. public SQLiteDatabase db; // Context of the app. private Context context; /** * Constructor. * Opens and prepares the database. * * @param context Context of app. */ public DatabaseAdapter(Context context) { this.context = context; // Open and prepare the database this.open(); } /** * Opens the database for writing/reading. * * @return a reference to the database adapter. * @throws SQLException If we cannot open the database. */ private DatabaseAdapter open() throws SQLException { dbHelper = new DatabaseHelper(context); db = dbHelper.getWritableDatabase(); return this; } /** * Closes the database for cleanup. */ public void close() { if (dbHelper != null) { dbHelper.close(); } } // // // SELECT // // /** * Gets the first zone found that is in given location. * * Uses Haversine formula * http://stackoverflow.com/a/123305/2235593 * * @param loc Location to match with. * @return Zone object that radius is in the location. */ public Zone getZoneInLocation(Location loc) { ArrayList<Zone> zones = getAllZones(); for (Zone z: zones) { double distance = MapUtil.distFrom(z.lat, z.lng, loc.getLatitude(), loc.getLongitude()); if(distance < 1) { // select the first zone return z; } } return null; } /** * Get all zones that have their synced flag as 0. * * @return Array list of zones to be synced. */ public ArrayList<Zone> getAllZonesThatNeedToBeSynced() { Cursor c = db.query(ZONE.TABLE, new String[]{ ZONE.KEY.ID, ZONE.KEY.NAME, ZONE.KEY.RADIUS, ZONE.KEY.LAT, ZONE.KEY.LNG, ZONE.KEY.HAS_SYNCED, ZONE.KEY.BLOCKING_APPS, ZONE.KEY.KEYWORDS }, ZONE.KEY.HAS_SYNCED + "=0", null, null, null, null); ArrayList<Zone> zones = new ArrayList<>(); if(c.moveToFirst()) { do { int id = c.getInt(c.getColumnIndex(ZONE.KEY.ID)); String name = c.getString(c.getColumnIndex(ZONE.KEY.NAME)); float radius = c.getFloat(c.getColumnIndex(ZONE.KEY.RADIUS)); double lat = c.getDouble(c.getColumnIndex(ZONE.KEY.LAT)); double lng = c.getDouble(c.getColumnIndex(ZONE.KEY.LNG)); int hasSynced = c.getInt(c.getColumnIndex(ZONE.KEY.HAS_SYNCED)); String[] blockingApps = Util.stringToArray(c.getString(c.getColumnIndex(ZONE.KEY.BLOCKING_APPS))); String[] keywords = Util.stringToArray(c.getString(c.getColumnIndex(ZONE.KEY.KEYWORDS))); Zone z = new Zone(id, lat, lng, radius, name, hasSynced, blockingApps, keywords); zones.add(z); } while (c.moveToNext()); } c.close(); return zones; } /** * Read all the Zones from the Zone Table database. * * @return ArrayList of zones. */ public ArrayList<Zone> getAllZones() { Cursor c = db.query(ZONE.TABLE, new String[]{ ZONE.KEY.ID, ZONE.KEY.NAME, ZONE.KEY.RADIUS, ZONE.KEY.LAT, ZONE.KEY.LNG, ZONE.KEY.HAS_SYNCED, ZONE.KEY.BLOCKING_APPS, ZONE.KEY.KEYWORDS }, null, null, null, null, null); ArrayList<Zone> zones = new ArrayList<>(); if(c.moveToFirst()) { do { int id = c.getInt(c.getColumnIndex(ZONE.KEY.ID)); String name = c.getString(c.getColumnIndex(ZONE.KEY.NAME)); float radius = c.getFloat(c.getColumnIndex(ZONE.KEY.RADIUS)); double lat = c.getDouble(c.getColumnIndex(ZONE.KEY.LAT)); double lng = c.getDouble(c.getColumnIndex(ZONE.KEY.LNG)); int hasSynced = c.getInt(c.getColumnIndex(ZONE.KEY.HAS_SYNCED)); String[] blockingApps = Util.stringToArray(c.getString(c.getColumnIndex(ZONE.KEY.BLOCKING_APPS))); String[] keywords = Util.stringToArray(c.getString(c.getColumnIndex(ZONE.KEY.KEYWORDS))); Zone z = new Zone(id, lat, lng, radius, name, hasSynced, blockingApps, keywords); zones.add(z); } while (c.moveToNext()); } c.close(); return zones; } /** * Get all the keywords from every zone. * * @return Array list of string array of keywords. */ public ArrayList<String[]> getAllKeywords() { Cursor c = db.query(ZONE.TABLE, new String[]{ ZONE.KEY.KEYWORDS }, null, null, null, null, null); ArrayList<String[]> array_of_keywords = new ArrayList<>(); if(c.moveToFirst()) { do { String[] keywords = Util.stringToArray(c.getString(c.getColumnIndex(ZONE.KEY.KEYWORDS))); array_of_keywords.add(keywords); } while (c.moveToNext()); } c.close(); return array_of_keywords; } /** * Get all the apps from every zone. * * @return Array list of string array of apps. */ public ArrayList<String[]> getAllBlockingApps() { Cursor c = db.query(ZONE.TABLE, new String[]{ ZONE.KEY.BLOCKING_APPS }, null, null, null, null, null); ArrayList<String[]> array_of_apps = new ArrayList<>(); if(c.moveToFirst()) { do { String[] apps = Util.stringToArray(c.getString(c.getColumnIndex(ZONE.KEY.BLOCKING_APPS))); array_of_apps.add(apps); } while (c.moveToNext()); } c.close(); return array_of_apps; } /** * Get the id of the last session created. * * @return ID of last session. */ private Integer getLastSessionId() { Integer sessionId = null; Cursor c = db.query(SESSION.TABLE, new String[]{SESSION.KEY.ID}, null, null, null, null, null); if(c.moveToLast()) { sessionId = c.getInt(0); } c.close(); return sessionId; } /** * Check to see if a session has ever existed yet. * * @return True if it has, false if it hasn't. */ public boolean hasASessionEverStartedYet() { boolean session_does_exist = false; Cursor c = db.query(SESSION.TABLE, new String[]{SESSION.KEY.ID}, null, null, null, null, null); if(c.moveToLast()) { session_does_exist = true; } c.close(); return session_does_exist; } /** * Get information on the last session. * * @return Session object containing information about the last * session. */ public Session getLastSessionDetails() { int session_id = getLastSessionId(); Session session = new Session(); Cursor c_session_details = db.query(SESSION.TABLE, new String[]{ SESSION.KEY.ZONE_ID, SESSION.KEY.START_TIME, SESSION.KEY.STOP_TIME }, SESSION.KEY.ID + "=" + session_id, null, null, null, null); if(c_session_details.moveToFirst()) { int zone_id = c_session_details.getInt(c_session_details.getColumnIndex(SESSION.KEY.ZONE_ID)); int start_time = c_session_details.getInt(c_session_details.getColumnIndex(SESSION.KEY.START_TIME)); int stop_time = c_session_details.getInt(c_session_details.getColumnIndex(SESSION.KEY.STOP_TIME)); session = new Session(zone_id, start_time, stop_time); } c_session_details.close(); return session; } /** * Get a list of notifications that were blocked during the last session. * * @return A list of notification parts. */ public ArrayList<NotificationParts> getLastSessionNotificationDetails() { int session_id = getLastSessionId(); ArrayList<NotificationParts> notifications = new ArrayList<>(); Cursor c_session_notifications = db.query(NOTIFICATION.TABLE, new String[]{ NOTIFICATION.KEY.ID, NOTIFICATION.KEY.TITLE, NOTIFICATION.KEY.TEXT, NOTIFICATION.KEY.SUB_TEXT, NOTIFICATION.KEY.CONTENT_INFO, NOTIFICATION.KEY.ICON, NOTIFICATION.KEY.LARGE_ICON, NOTIFICATION.KEY.PACKAGE }, NOTIFICATION.KEY.SESSION_ID + "=" + session_id + " AND " + NOTIFICATION.KEY.SENT_TO_USER + "=0", null, null, null, null); if(c_session_notifications.moveToFirst()) { do { int notificationID = c_session_notifications.getInt(c_session_notifications.getColumnIndex(NOTIFICATION.KEY.ID)); String title = c_session_notifications.getString(c_session_notifications.getColumnIndex(NOTIFICATION.KEY.TITLE)); String text = c_session_notifications.getString(c_session_notifications.getColumnIndex(NOTIFICATION.KEY.TEXT)); String subText = c_session_notifications.getString(c_session_notifications.getColumnIndex(NOTIFICATION.KEY.SUB_TEXT)); String contentInfo = c_session_notifications.getString(c_session_notifications.getColumnIndex(NOTIFICATION.KEY.CONTENT_INFO)); int iconResourceInt = c_session_notifications.getInt(c_session_notifications.getColumnIndex(NOTIFICATION.KEY.LARGE_ICON)); byte[] iconImage = c_session_notifications.getBlob(c_session_notifications.getColumnIndex(NOTIFICATION.KEY.ICON)); Bitmap bm = Util.convertBinaryToBitmap(iconImage); String package_name = c_session_notifications.getString(c_session_notifications.getColumnIndex(NOTIFICATION.KEY.PACKAGE)); notifications.add(new NotificationParts(notificationID, package_name, title, text, subText, contentInfo, bm, iconResourceInt)); } while (c_session_notifications.moveToNext()); } c_session_notifications.close(); return notifications; } /** * Get a zone from the given ID. * * @param zoneId id of zone to get. * @return Zone object. */ public Zone getZoneFromID(int zoneId) { Zone z = null; Cursor c = db.query(ZONE.TABLE, new String[] { ZONE.KEY.ID, ZONE.KEY.NAME, ZONE.KEY.RADIUS, ZONE.KEY.LAT, ZONE.KEY.LNG, ZONE.KEY.HAS_SYNCED, ZONE.KEY.BLOCKING_APPS, ZONE.KEY.KEYWORDS }, ZONE.KEY.ID + "=" + zoneId, null, null, null, null); if(c.moveToFirst()) { int id = c.getInt(c.getColumnIndex(ZONE.KEY.ID)); String name = c.getString(c.getColumnIndex(ZONE.KEY.NAME)); float radius = c.getFloat(c.getColumnIndex(ZONE.KEY.RADIUS)); double lat = c.getDouble(c.getColumnIndex(ZONE.KEY.LAT)); double lng = c.getDouble(c.getColumnIndex(ZONE.KEY.LNG)); int hasSynced = c.getInt(c.getColumnIndex(ZONE.KEY.HAS_SYNCED)); String[] blockingApps = Util.stringToArray(c.getString(c.getColumnIndex(ZONE.KEY.BLOCKING_APPS))); String[] keywords = Util.stringToArray(c.getString(c.getColumnIndex(ZONE.KEY.KEYWORDS))); z = new Zone(id, lat, lng, radius, name, hasSynced, blockingApps, keywords); } c.close(); return z; } /** * Get the total number of zones. * * @return long, number of zones currently alive. */ public long getNumberOfZones() { return DatabaseUtils.queryNumEntries(db, ZONE.TABLE); } /** * Gets the number of unique apps being blocked across all zones. * * @return The number of apps that are being blocked. */ public int getUniqueNumberOfBlockingApps() { Map<String, Integer> apps = Util.getOccurrencesFromListOfArrays(getAllBlockingApps()); return apps.size(); } /** * Gets the number of unique keywords across all zones. * * @return The number of keywords that are used. */ public int getUniqueNumberOfKeywords() { Map<String, Integer> words = Util.getOccurrencesFromListOfArrays(getAllKeywords()); return words.size(); } // // // UPDATE // // /** * Update a current zone in the Zone Table database, based on the ID of the zone object. * * @param zone to edit. */ public void editZone(Zone zone) { db.execSQL("UPDATE " + ZONE.TABLE + " SET " + ZONE.KEY.NAME + "= '" + zone.name + "', " + ZONE.KEY.RADIUS + "=" + zone.radiusInMeters + ", " + ZONE.KEY.LAT + "=" + zone.lat + ", " + ZONE.KEY.LNG + "=" + zone.lng + ", " + ZONE.KEY.HAS_SYNCED + "=" + zone.hasSynced + ", " + ZONE.KEY.BLOCKING_APPS + "='" + zone.blockingAppsAsStr() + "', " + ZONE.KEY.KEYWORDS + "='" + zone.keywordsAsStr() + "'" + " WHERE " + ZONE.KEY.ID + " = " + zone.zoneID + ";"); } /** * Mark a zone as synced to the server. * * @param zone_id to mark as synced. */ public void setZoneAsSynced(int zone_id) { db.execSQL("UPDATE " + ZONE.TABLE + " SET " + ZONE.KEY.HAS_SYNCED + "=" + 1 + " WHERE " + ZONE.KEY.ID + " = " + zone_id + ";"); } /** * Mark a session end time. * * @param session_id ID of the session to mark as ended. */ public void finishSession(Integer session_id) { long stop_time = System.currentTimeMillis() / 1000; db.execSQL("UPDATE " + SESSION.TABLE + " SET " + SESSION.KEY.STOP_TIME + "=" + stop_time + " WHERE " + SESSION.KEY.ID + " = " + session_id + ";"); } /** * Set a notification as synced based on the given notification id. * * @param notificationID Id of notification to be synced. */ public void setNotificationHasBeenSentToUser(int notificationID) { db.execSQL("UPDATE " + NOTIFICATION.TABLE + " SET " + NOTIFICATION.KEY.SENT_TO_USER + "=" + 1 + " WHERE " + NOTIFICATION.KEY.ID + " = " + notificationID + ";"); } // // // DELETE // // /** * Delete a zone with the given ID. * * @param id ID of zone to delete. */ public void deleteZone(int id) { db.execSQL("DELETE FROM " + ZONE.TABLE + " WHERE " + ZONE.KEY.ID + "=" + id + ";"); } // // // INSERT // // /** * Write a new zone (give) to the Zone Table database. * * @param zone to write. */ public void writeZone(Zone zone) { db.execSQL("INSERT INTO " + ZONE.TABLE + " (" + ZONE.KEY.NAME + "," + ZONE.KEY.RADIUS + "," + ZONE.KEY.LAT + "," + ZONE.KEY.LNG + "," + ZONE.KEY.HAS_SYNCED + "," + ZONE.KEY.BLOCKING_APPS + "," + ZONE.KEY.KEYWORDS + ") " + "VALUES " + "('" + zone.name + "', " + zone.radiusInMeters + ", " + zone.lat + ", " + zone.lng + ", " + zone.hasSynced + ", " + "'" + zone.blockingAppsAsStr() + "', " + "'" + zone.keywordsAsStr() + "');"); } /** * Track the notification in a new Notification Table row, * based on the current session id. * * @param n The notification to save. */ public void writeNotification(StatusBarNotification n) { Bundle ne = n.getNotification().extras; String nTitle = (ne.getCharSequence(Notification.EXTRA_TITLE) == null) ? "" : ne.getCharSequence(Notification.EXTRA_TITLE) + ""; String nText = (ne.getCharSequence(Notification.EXTRA_TEXT) == null) ? "" : ne.getCharSequence(Notification.EXTRA_TEXT) + ""; String nSubText = (ne.getCharSequence(Notification.EXTRA_SUB_TEXT) == null) ? "" : ne.getCharSequence(Notification.EXTRA_SUB_TEXT) + ""; String nInfoText = (ne.getCharSequence(Notification.EXTRA_INFO_TEXT) == null) ? "" : ne.getCharSequence(Notification.EXTRA_INFO_TEXT) + ""; // Get the image from the icon Bitmap b = NotificationUtil.getBitmapFromAnotherPackage(context, n.getNotification().icon, n.getPackageName()); String iconAsStr = new String(Util.convertBitmapToBinary(b)); ContentValues values = new ContentValues(); values.put(NOTIFICATION.KEY.PACKAGE, n.getPackageName()); values.put(NOTIFICATION.KEY.TITLE, nTitle); values.put(NOTIFICATION.KEY.TEXT, nText); values.put(NOTIFICATION.KEY.SUB_TEXT, nSubText); values.put(NOTIFICATION.KEY.CONTENT_INFO, nInfoText); values.put(NOTIFICATION.KEY.ICON, iconAsStr); values.put(NOTIFICATION.KEY.LARGE_ICON, n.getNotification().icon); values.put(NOTIFICATION.KEY.SENT_TO_USER, 0); values.put(NOTIFICATION.KEY.SESSION_ID, PROJECT_GLOBALS.SESSION_ID); db.insert(NOTIFICATION.TABLE, null, values); } /** * Starts a new session by creating a new row in the Session Table, * and getting that new Session ID. * * @param zoneID Zone that relates to the session. * @param startTime Start time of the session. */ public void startNewSession(Integer zoneID, long startTime) { // Create a new Row in the Session Table db.execSQL("INSERT INTO " + SESSION.TABLE + " (" + SESSION.KEY.ZONE_ID + "," + SESSION.KEY.START_TIME + "" + ") " + "VALUES " + "(" + zoneID + ", " + startTime + ");"); // Set the project state session ID PROJECT_GLOBALS.SESSION_ID = getLastSessionId(); } /** * Check to see if we are still studying or not. * * @return True if still studying, false if not. */ public Boolean areWeStillStudying() { int session_id = getLastSessionId(); Cursor c_session_details = db.query(SESSION.TABLE, new String[]{ SESSION.KEY.STOP_TIME }, SESSION.KEY.ID + "=" + session_id, null, null, null, null); int stop_time = 0; if(c_session_details.moveToFirst()) { stop_time = c_session_details.getInt(c_session_details.getColumnIndex(SESSION.KEY.STOP_TIME)); } c_session_details.close(); return(stop_time == 0); } }
package lnyswz.oa.dao.impl; import java.util.List; import java.util.Set; import lnyswz.oa.bean.Message; import lnyswz.oa.bean.Paper; import lnyswz.oa.dao.MessageDAO; import lnyswz.oa.utils.AbstractPagerManager; import lnyswz.oa.utils.PagerModel; public class MessageDAOImpl extends AbstractPagerManager implements MessageDAO{ public void addMsg(Message message) { Set<Paper> papers = (Set<Paper>)message.getAttachments(); for(Paper paper : papers){ this.getHibernateTemplate().save(paper); } this.getHibernateTemplate().save(message); } public void deleteMsg(int msgId) { this.getHibernateTemplate().delete(this.getHibernateTemplate().load(Message.class, msgId)); } public void modifyMsg(Message message) { this.getHibernateTemplate().update(message); } public Message findMsg(int msgId) { return (Message)this.getHibernateTemplate().load(Message.class, msgId); } public PagerModel findAllMsgs() { return this.searchPaginated("from Message"); } public PagerModel findMsgsBySender(int senderId) { return this.searchPaginated("from Message m where m.sender.id = ? order by m.sendedTime desc", senderId); } public PagerModel findMsgsByReceiver(int receiverId) { return this.searchPaginated("from Message m where ? in elements(m.receivers) order by m.sendedTime desc", receiverId); } public PagerModel findMsgsByStatus(int receiverId, String isReaded) { return this.searchPaginated("from Message m where ? in m.receivers and m.isRead = ?", new Object[]{receiverId, isReaded}); } }
package lista4; import java.util.Scanner; public class Exe10 { public static void main(String[] args) { Scanner entrada = new Scanner(System.in); char codigo = '\u0000'; double totalV = 0, totalP = 0, valor = 0, total = 0; for(int i=0;i<10;i++){ System.out.println("Valor: "); entrada.nextDouble(); System.out.println("Informe código de transação: \n V - Transação à vista \n P - Transação a prazo"); codigo = entrada.next().charAt(0); codigo = Character.toUpperCase(codigo); while(codigo!='V' && codigo!='P'){ System.out.println("Código errado!!! \n Informe código de transação: \n V - Transação à vista \n P - Transação a prazo"); codigo = entrada.next().charAt(0); codigo = Character.toUpperCase(codigo); } if(codigo=='V'){ totalV=totalV+valor; }else{ totalP=totalP+valor; } total=total+valor; } System.out.println("Total de compras à vista: " + totalV); System.out.println("Total de compras à prazo: " + totalP); System.out.println("Total de compras efetuadas: " + total); entrada.close(); } }
package cn.springboot.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; @Entity @Table(name = "user") public class User implements Serializable { private static final long serialVersionUID = 1L; // 主键 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // 用户名 private String username; // 生日 private String birthday; public User() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday='" + birthday + '\'' + '}'; } }
package kodlamaio.hrms.entities.concretes; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Entity @Table(name="cv_languages") @JsonIgnoreProperties ({"hibernateLazyInitializer","handler","cvLanguage"}) public class CvLanguage { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="cv_language_id") private int cvLanguageId; @Min(value = 1) @Max(value = 5) @Column(name="language_level") private int languageLevel; @Column(name="language_name") private String languageName; @ManyToOne() @JoinColumn(name="cv_id") private Cv cv; //@Column(name="languages_id") //private int languageId; // @Column(name="language_level_id") // private int languageLevelId; // // @Column(name="cv_id") // private int cvId; // @OneToOne(cascade = CascadeType.ALL) // @JoinColumn(name="languages_id") // private Language language; // // @OneToOne(cascade = CascadeType.ALL) // @JoinColumn(name="languages_level_id") // private LanguageLevel languageLevel; // 2 @ManyToOne(cascade = CascadeType.ALL) // @JsonIgnore() // @JoinColumn(name="user_id") // private Candidate candidate; // }
package de.adesso.gitstalker.core.resources.memberID_Resources; import de.adesso.gitstalker.core.resources.memberPR_Resources.NodesMember; import de.adesso.gitstalker.core.resources.rateLimit_Resources.RateLimit; import lombok.NoArgsConstructor; import java.util.ArrayList; @lombok.Data @NoArgsConstructor public class Data { private Organization organization; private ArrayList<NodesMember> nodes; private RateLimit rateLimit; }
package dao; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; public class UsersDAOImpl implements UsersDAO { private JdbcTemplate jdbcTemplate; public UsersDAOImpl(DataSource dataSource) { jdbcTemplate = new JdbcTemplate(dataSource); } @Override public String getPassword(String username) { return jdbcTemplate.queryForObject("SELECT password FROM users WHERE username = ?", new Object[] { username }, String.class); } @Override public Long allUsersCount() { return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM users", Long.class); } }
package com.icourt.architecture; import android.support.annotation.NonNull; import com.icourt.api.RequestUtils; import java.lang.ref.WeakReference; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import retrofit2.Call; import retrofit2.Callback; /** * @author youxuan E-mail:xuanyouwu@163.com * @version 2.2.2 * @Description * @Company Beijing icourt * @date createTime:2017/12/3 */ public class CallQueuePresenter implements IContextCallQueue { Queue<WeakReference<Call>> contextCallQueue = new ConcurrentLinkedQueue<>(); @Override public <T> Call<T> callEnqueue(@NonNull Call<T> call, Callback<T> callback) { if (call != null) { contextCallQueue.offer(new WeakReference<Call>(call)); return RequestUtils.callEnqueue(call, callback); } return call; } @Override public void cancelAllCall() { while (contextCallQueue.peek() != null) { WeakReference<Call> poll = contextCallQueue.poll(); if (poll != null) { RequestUtils.cancelCall(poll.get()); } } } @Override public <T> void cancelCall(@NonNull Call<T> call) { for (WeakReference<Call> poll : contextCallQueue) { if (poll != null && call == poll.get()) { contextCallQueue.remove(poll); break; } } RequestUtils.cancelCall(call); } }
package com.example.namsy.test2; /** * Created by NAMSY on 2016-07-27. */ public interface Dial_TabInterfaceListener { void receiveTab(String string); }
package chat; import java.util.Date; import java.lang.String; import org.omg.CosNaming.*; public class ChatServiceImpl extends ChatServicePOA { public String getTheDate() { Date day = new Date(); String date = day.toString(); System.out.println(date); return date; } public void newChatRoom(String _chatroom) { NameComponent[] ns = new NameComponent [2]; ns[0] = new NameComponent("ChatRooms",""); ns[1] = new NameComponent(_chatroom,""); org.omg.CORBA.Object objRef = null; try { objRef = this._orb().resolve_initial_references("NameService"); } catch(org.omg.CORBA.ORBPackage.InvalidName e) { e.printStackTrace(); } NamingContext ncRef = NamingContextHelper.narrow(objRef); try { ncRef.bind_new_context(ns); System.out.println("ChatRoom " + _chatroom + " created."); } catch(org.omg.CosNaming.NamingContextPackage.NotFound e) { e.printStackTrace(); } catch(org.omg.CosNaming.NamingContextPackage.CannotProceed e) { e.printStackTrace(); } catch(org.omg.CosNaming.NamingContextPackage.InvalidName e) { e.printStackTrace(); } catch(org.omg.CosNaming.NamingContextPackage.AlreadyBound e) { System.out.println("ChatRoom " + _chatroom + " already exists."); } } public void send(String _chatroom, String _msg) { System.out.println("[" + _chatroom + "] " + _msg); try { NameComponent[] ns = new NameComponent [2]; ns[0] = new NameComponent("ChatRooms",""); ns[1] = new NameComponent(_chatroom,""); org.omg.CORBA.Object objRef = this._orb().resolve_initial_references("NameService"); NamingContext ncRef = NamingContextHelper.narrow(objRef); NamingContext nc = NamingContextHelper.narrow(ncRef.resolve(ns)); Binding[] bl = null; BindingListHolder blh = new BindingListHolder(); BindingIteratorHolder bih = new BindingIteratorHolder(); nc.list (0, blh, bih); BindingIterator bi = bih.value; if (bi != null) { boolean continuer = true; while (continuer) { continuer = bi.next_n(10,blh); bl = blh.value; for (int i=0; i < bl.length; i++) { for(int j=0; j < bl[i].binding_name.length; ++j) { NameComponent[] nsIt = new NameComponent [3]; nsIt[0] = new NameComponent("ChatRooms",""); nsIt[1] = new NameComponent(_chatroom,""); nsIt[2] = bl[i].binding_name[j]; Chatter chatter = ChatterHelper.narrow(ncRef.resolve(nsIt)); System.out.println("Send message to " + nsIt[2].id); chatter.receive(_msg); } } } bi.destroy(); } } catch(org.omg.CosNaming.NamingContextPackage.NotFound e) { e.printStackTrace(); } catch(org.omg.CosNaming.NamingContextPackage.CannotProceed e) { e.printStackTrace(); } catch(org.omg.CosNaming.NamingContextPackage.InvalidName e) { e.printStackTrace(); } catch(org.omg.CORBA.ORBPackage.InvalidName e) { e.printStackTrace(); } } }
package com.vladan.mymovies.data.local.db; import com.vladan.mymovies.data.model.Genre; import com.vladan.mymovies.data.model.Movie; import java.util.List; import java.util.concurrent.Callable; import io.reactivex.Observable; /** * Created by Vladan on 10/14/2017. */ public class AppDatabaseHelper implements DatabaseHelper { private final AppDatabase appDatabase; public AppDatabaseHelper(AppDatabase appDatabase) { this.appDatabase = appDatabase; } @Override public Observable<List<Movie>> getAllMovies() { return Observable.fromCallable(() -> appDatabase.movieDao().getAllMovies()); } @Override public Observable<List<Movie>> getMoviesByGenre(final int genre) { // return Observable.fromCallable(() -> appDatabase.movieDao().getMoviesByGenre(genre)); return null; } @Override public Observable<Boolean> updateMovie(final Movie movie) { return Observable.fromCallable(() -> { appDatabase.movieDao().updateMovie(movie); return true; }); } @Override public Observable<List<Genre>> getAllGenres() { return Observable.fromCallable(() -> appDatabase.genreDao().getAllGenres()); } @Override public Observable<Boolean> clearAll(List<Movie> list) { return Observable.fromCallable(() -> { appDatabase.movieDao().clearAll(list); return true; }); } @Override public Observable<Boolean> insertAll(List<Movie> list) { return Observable.fromCallable(() -> { appDatabase.movieDao().insertAll(list); return true; }); } }
package com.takshine.wxcrm.base.util; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.UUID; public class MD5Util { private static final char DIGITS_LOWER[] = { '0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private static final char DIGITS_UPPER[] = { '0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static final String DEFAULT_ENCODING = "UTF8"; private static final String ALGORITH = "MD5"; private static final MessageDigest md = getMessageDigest(ALGORITH); /** * MD5(32位的十六进制表示) * * @param srcStr * 源字符串 * @param encode * 编码方式 * @return */ public static String digest(String srcStr, String encode) { byte[] rstBytes; try { rstBytes = md.digest(srcStr.getBytes(encode)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } return toHex(rstBytes, true); } /** * 默认使用UTF8编码进行解析 * * @param srcStr * 源字符串 * @return */ public static String digest(String srcStr) { return digest(srcStr, DEFAULT_ENCODING); } /** * 获取摘要处理实例 * * @param algorithm * 摘要的算法 * @return */ private static MessageDigest getMessageDigest(String algorithm) { try { return MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /** * 字节码转十六进制的字符串 * * @param bytes * 字节数组 * @param flag * 大小写标志,true为小写,false为大写 * @return */ public static String toHex(byte[] bytes, boolean flag) { return new String(processBytes2Hex(bytes, flag ? DIGITS_LOWER : DIGITS_UPPER)); } /** * 将字节数组转化为十六进制字符串 * * @param bytes * 字节数组 * @param digits * 数字加字母字符数组 * @return */ private static char[] processBytes2Hex(byte[] bytes, char[] digits) { // bytes.length << 1肯定是32,左移1位是因为一个字节是8位二进制,一个十六进制用4位二进制表示 // 当然可以写成l = 32,因为MD5生成的字节数组必定是长度为16的字节数组 int l = bytes.length << 1; char[] rstChars = new char[l]; int j = 0; for (int i = 0; i < bytes.length; i++) { // 得到一个字节中的高四位的值 rstChars[j++] = digits[(0xf0 & bytes[i]) >>> 4]; // 得到一个字节中低四位的值 rstChars[j++] = digits[0x0f & bytes[i]]; } return rstChars; } /* * 方法名称:getMD5 * 功 能:字符串MD5加密 * 参 数:待转换字符串 * 返 回 值:加密之后字符串 */ public static String getMD5(String sourceStr) throws UnsupportedEncodingException { String resultStr = ""; try { byte[] temp = sourceStr.getBytes(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(temp); // resultStr = new String(md5.digest()); byte[] b = md5.digest(); for (int i = 0; i < b.length; i++) { char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] ob = new char[2]; ob[0] = digit[(b[i] >>> 4) & 0X0F]; ob[1] = digit[b[i] & 0X0F]; resultStr += new String(ob); } return resultStr; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } public static void main(String[] args) { System.out.println(MD5Util.digest("中国")); } }
package com.example.demo.model; import lombok.Data; import javax.xml.bind.annotation.XmlRootElement; /** * @author: Cavan.Liu * @date: 2019-07-17 10:06:23 * @description: */ @Data @XmlRootElement public class User { private long id; // 用户的唯一标识 private String name; private int age; }
/* */ package datechooser.beans.editor.descriptor; /* */ /* */ import datechooser.model.multiple.Period; /* */ import java.util.Calendar; /* */ import java.util.GregorianCalendar; /* */ import java.util.Locale; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class PeriodDescriptor /* */ extends ClassDescriptor /* */ { /* */ public PeriodDescriptor() {} /* */ /* */ public Class getDescriptedClass() /* */ { /* 22 */ return Period.class; /* */ } /* */ /* */ public String getJavaDescription(Object value) { /* 26 */ StringBuffer buf = new StringBuffer(); /* 27 */ Period period = (Period)value; /* 28 */ Calendar start = period.getStartDate(); /* 29 */ Calendar end = period.getEndDate(); /* 30 */ buf.append("new " + getClassName() + "("); /* 31 */ buf.append(DescriptionManager.describeJava(start, GregorianCalendar.class)); /* 32 */ buf.append(getSeparator()); /* 33 */ buf.append(DescriptionManager.describeJava(end, GregorianCalendar.class)); /* 34 */ buf.append(")"); /* 35 */ return buf.toString(); /* */ } /* */ /* */ public String getDescription(Object value) { /* 39 */ return getDescription(value, Locale.getDefault()); /* */ } /* */ /* */ public String getDescription(Object value, Locale locale) { /* 43 */ Period period = (Period)value; /* 44 */ return DescriptionManager.describe(period.getStartDate(), locale) + (period.isOneDate() ? "" : new StringBuilder().append(" - ").append(DescriptionManager.describe(period.getEndDate(), locale)).toString()); /* */ } /* */ } /* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/beans/editor/descriptor/PeriodDescriptor.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
package com.cmu.edu.enterprisewebdevelopment.service; import com.cmu.edu.enterprisewebdevelopment.domain.Role; import com.cmu.edu.enterprisewebdevelopment.domain.User; import com.cmu.edu.enterprisewebdevelopment.repository.RoleRepository; import com.cmu.edu.enterprisewebdevelopment.repository.UserRepository; import org.omg.SendingContext.RunTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collections; import java.util.List; @Service public class UserService implements UserDetailsService { @Autowired private UserRepository userRepository; @Autowired private RoleRepository roleRepository; @Autowired private BCryptPasswordEncoder encoder; public void createUser(User newUser) { //validate if userName exists User user = userRepository.findUserByUsername(newUser.getUsername()); if (user != null) { throw new RuntimeException("error.username.exist"); } //add Role String user_role = "customer"; Role role = roleRepository.findRoleByName(user_role); if (role == null) { role = new Role(user_role); } List<Role> roles = new ArrayList<>(); roles.add(role); //add Password newUser.setPassword(encoder.encode(newUser.getPassword())); newUser.setRoles(roles); //save user userRepository.save(newUser); } public User findUserByUserName(String userName) { return userRepository.findUserByUsername(userName); } //security @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { if (s == null || s.isEmpty()) { throw new UsernameNotFoundException("username cannot be empty"); } User user = userRepository.findUserByUsername(s); if (user == null) { throw new UsernameNotFoundException("User doestn't exist"); } List<Role> roles = user.getRoles(); List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>(); for (Role role : roles) { grantedAuthorities.add(new SimpleGrantedAuthority(role.getName())); } return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), grantedAuthorities ); } }
/* * 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 entities.dto; import entities.SchoolClass; import entities.SchoolTeacher; import java.util.ArrayList; import java.util.List; /** * * @author emilt */ public class SchoolTeacherDTO { //Fields Long id; private String name; private List<SchoolClassDTO> classes; //Con public SchoolTeacherDTO(SchoolTeacher st) { this.name = st.getName(); this.id = st.getId(); List<SchoolClass> sc = st.getClasses(); for (int i = 0; i < sc.size(); ++i) { classes.add(new SchoolClassDTO(sc.get(i))); } } //Methods public String getName() { return name; } public void setName(String name) { this.name = name; } public List<SchoolClassDTO> getClasses() { return classes; } public void setClasses(List<SchoolClassDTO> classes) { this.classes = classes; } }
package com.lsht.ml; import java.io.Serializable; import java.util.*; /** * Created by Junson on 2017/8/22. */ public class RecurrentLayer implements Serializable { public double learning_rate=0.1; public int times =-1; public List<double[]> stateList=new ArrayList<>(); public double[] lastState; public double[] currentState; public List<double[]> netList=new ArrayList<>(); public double[][] U;//[state_width][input_width] public double[][] W;//[state_width][state_width] public double biasU; public double biasW; public List<double[]> deltaUList=new ArrayList<>(); public List<double[]> deltaWList=new ArrayList<>(); public List<double[]> inputList=new ArrayList<>(); public double[][] gradientW; public double[][] gradientU; public int inputWidth; public int stateWidth; public double[] getLastState() { return lastState; } public RecurrentLayer(int inputWidth,int stateWidth) { this.inputWidth=inputWidth; this.stateWidth=stateWidth; this.learning_rate=0; U = new double[stateWidth][inputWidth]; // # 初始化U gradientU = new double[stateWidth][inputWidth]; W = new double[stateWidth][stateWidth];// # 初始化W CalcOperator.randomUniform(1.0/(stateWidth*stateWidth),1.0/(stateWidth*stateWidth),U); CalcOperator.randomUniform(1.0/(stateWidth*inputWidth),1.0/(stateWidth*inputWidth),W); gradientW=new double[stateWidth][stateWidth]; } public RecurrentLayer(int inputWidth,int stateWidth,double learning_rate) { this.inputWidth=inputWidth; this.stateWidth=stateWidth; this.learning_rate=learning_rate; U = new double[stateWidth][inputWidth]; // # 初始化U gradientU = new double[stateWidth][inputWidth]; W = new double[stateWidth][stateWidth];// # 初始化W CalcOperator.randomUniform(-0.0003d,0.0007d,U); CalcOperator.randomUniform(-0.0003d, 0.0007d, W); gradientW=new double[stateWidth][stateWidth]; } /** * 要求输入数据已进行one-hot编码 * @param inputData * @return */ public double[] forward(double[] inputData) { times ++; lastState = currentState; inputList.add(inputData); double[] netU=CalcOperator.matrixMultiply(U, inputData); double[] netW=null; if(times!=0) { netW=CalcOperator.matrixMultiply(W, CalcOperator.relu(currentState)); currentState = CalcOperator .add(netU, netW); } else { currentState = netU; } netList.add( CalcOperator.relu(currentState)); currentState = CalcOperator.softMax(currentState); stateList.add(currentState); return currentState; } /** * 实现BPTT算法 * * @param label */ public void backward(double[] label) { double[] sensitivity_array =CalcOperator.softMax(CalcOperator.calcCECDelta(currentState,label)); calcDelta(sensitivity_array); calcGradient(sensitivity_array); //计算梯度 } /** * 对one-hot编码的误差数据其误差为: -*logY * @param sensitivity_array */ public void calcDelta(double[] sensitivity_array) { //公式:delta(K)=delta(T)*(W*diag(f'(net(t-1))))*(W*diag(f'(net(t-2))))*......*(W*diag(f'(net(K)))) deltaWList.clear(); deltaUList.clear(); deltaWList.add(sensitivity_array);//t t-1 t-2,... 1 deltaUList.add(sensitivity_array); //计算 double[] deltaW = sensitivity_array; double[] deltaU = sensitivity_array; for(int i=times-1;i>0;i--) { double[][] t1= calcDelta_K(W, i); double[][] t2=CalcOperator.T(deltaW); double[][] t3=null;//CalcOperator.dot(t2, t1); double[] t4=CalcOperator._T(t3); deltaW =t4; deltaU =null;//CalcOperator._T(CalcOperator.dot(CalcOperator.T(deltaU),calcDelta_K(U,i))); deltaWList.add(deltaW); deltaUList.add(deltaU); } } /** * 根据k + 1 时刻的delta计算k时刻的delta * 公式:delta(K)=delta(T)*(W*diag(f'(net(t))))*(W*diag(f'(net(t-1))))*(W*diag(f'(net(t-2))))*......*(W*diag(f'(net(K)))) * @param k */ public double[][] calcDelta_K (double[][] W,int k) { double[] netK=netList.get(k); double[] f_netK=CalcOperator.relu_back(netK); double[][] diag_fNetK = CalcOperator.diag(f_netK); return CalcOperator.matrixMultiply(diag_fNetK,W); } /** * 计算公式: TiDu =Delta * Input * */ public void calcGradient(double[] sensitivity_array) { for(int cnt=times;cnt>1;cnt--) { CalcOperator.fill(gradientU,0); CalcOperator.fill(gradientW, 0); for (int i = 1; i < cnt; i++) { for (int m = 0; m < gradientU.length; m++) { for (int n = 0; n < gradientU[0].length; n++) { gradientU[m][n] += deltaUList.get(times-i)[m] * inputList.get(i)[n]; } } } updateU(); for (int i = 1; i < cnt; i++) { for (int m = 0; m < gradientW.length; m++) { for (int n = 0; n < gradientW[0].length; n++) { gradientW[m][n] += deltaWList.get(times-i)[m] * stateList.get(i - 1)[n]; } } } updateW(); calcDelta(sensitivity_array); } } public void updateU() { // 按照梯度下降,更新权重 for(int i=0;i<stateWidth;i++) { for(int j=0;j<inputWidth;j++) { if(learning_rate==0) { U[i][j] -= (Math.pow(1/Math.E,i)) * gradientU[i][j]; } else { U[i][j] -= learning_rate * gradientU[i][j]; } } } } public void updateW() { // 按照梯度下降,更新权重 for(int i=0;i<W.length;i++) { for(int j=0;j<W[0].length;j++) { if(learning_rate==0) { W[i][j] -= (Math.pow(1/Math.E,i)) * gradientW[i][j]; } else { W[i][j] -= learning_rate * gradientW[i][j]; } } } } public void clear() { //当前时刻初始化为t0 times=-1; stateList.clear(); netList.clear(); deltaUList.clear(); deltaWList.clear(); inputList.clear(); stateList.add(lastState); } public void reset_state() { //当前时刻初始化为t0 times=-1; stateList.clear(); netList.clear(); deltaUList.clear(); deltaWList.clear(); inputList.clear(); } /** 每次计算error之前,都要调用reset_state方法重置循环层的内部状态 */ private static double error_function(double[] l) { return CalcOperator.sum(l); } /** * 梯度检查 */ public static void gradient_check() { //0000 001 //0001 010 //0010 100 //0100 001 //1000 010 RecurrentLayer recurrentLayer = new RecurrentLayer(2,2,0.2); double[] x2 = { 0, 1 }; double[] x3 = { 1, 0 }; double[] t2 = { 1, 0 }; double[] t3 = { 0, 1 }; for (int i = 0; i < 1; i++) { recurrentLayer.reset_state(); recurrentLayer.forward(x2); recurrentLayer.forward(x3); //计算梯度 recurrentLayer.backward(t3); } System.out.println("********************************************"); //检查梯度 double epsilon = 10e-4; for(int i=0;i<recurrentLayer.stateWidth;i++) { for(int j=0;j<recurrentLayer.stateWidth;j++) { recurrentLayer.W[i][j]+=epsilon; recurrentLayer.reset_state(); recurrentLayer.forward(x2); recurrentLayer.forward(x3); double[] y3=recurrentLayer.getLastState(); CalcOperator.print(y3); CalcOperator.print(t3); double err1 = error_function(CalcOperator.calcCECDelta(y3,t3)); recurrentLayer.W[i][j]-=2*epsilon; recurrentLayer.reset_state(); recurrentLayer.forward(x2); recurrentLayer.forward(x3); y3=recurrentLayer.getLastState(); System.out.println("------------------------------------------------------------"); CalcOperator.print(y3); CalcOperator.print(t3); double err2 = error_function(CalcOperator.calcCECDelta(y3,t3)); System.out.println("err1="+err1); System.out.println("err2="+err2); System.out.println("------------------------------------------------------------"); double expect_grad = (err1 - err2) / (2.0 * epsilon); recurrentLayer.W[i][j] += epsilon; System.out.printf("weights(%d,%d): expected - actural %f - %f \n", i, j, expect_grad, recurrentLayer.gradientW[i][j]); System.out.println( "==================================================================="); } } } public static void main(String[] args) { gradient_check(); } }
package algorithms.randomized; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; /** * Write a client program Subset.java that takes a command-line integer k; reads in a sequence of N strings * from standard input using StdIn.readString(); and prints out exactly k of them, uniformly at random. * Each item from the sequence can be printed out at most once. You may assume that 0 ≤ k ≤ n, * where N is the number of string on standard input. * <p> * The running time of Subset must be linear in the size of the input. * You may use only a constant amount of memory plus either one Deque or RandomizedQueue object * of maximum size at most n, where n is the number of strings on standard input. * (For an extra challenge, use only one Deque or RandomizedQueue object of maximum size at most k.) * </p> * Reservoir sampling is used for minimization of memory usage: * - use RandomizedQueue * - add all items below k to queue * - for every i item greater or equal to k such as Random(0..i) is lesser than k make dequeue and enqueue(item) * <p> * To run: * 1) compile sources * javac -classpath E:\works\java\study\libs\algs4.jar | * algorithms/randomized/Subset.java algorithms/randomized/RandomizedQueue.java * 2) run * echo aa bb cc dd | java -cp .;../../../../libs/algs4.jar algorithms.randomized.Subset 3 * type test.txt | java -cp .;../../../../libs/algs4.jar algorithms.randomized.Subset 3 */ public class Subset { private static void readAndWriteStrings(int k) { RandomizedQueue<String> queue = new RandomizedQueue<>(); String input; int i = 0; int chance; while (!StdIn.isEmpty()) { input = StdIn.readString(); if (i++ < k) { queue.enqueue(input); } else { chance = StdRandom.uniform(i); if (chance < k) { queue.dequeue(); queue.enqueue(input); } } } while (k-- > 0) { StdOut.println(queue.dequeue()); } } public static void main(String[] args) { if (args.length != 1) { StdOut.println("Expected exactly 1 integer argument"); throw new IllegalArgumentException(); } int k = Integer.parseInt(args[0]); if (k < 0) { throw new IllegalArgumentException(); } readAndWriteStrings(k); } }
public class cup { public int type; public String name; public int serialNum; public String color; public boolean handle; double maxFluid; public double currFluid; public boolean broken; public cup(int type, String name, int serialNum, String color, double maxFluid, boolean handle) { this.type = type; this.name = name; this.serialNum = serialNum; this.color = color; this.maxFluid = maxFluid; this.currFluid = 0; this.handle = handle; broken = false; } public void fillCup(double oz) { if(!broken) { if(oz == -1) { currFluid = maxFluid; System.out.println("You filled the cup completely."); }else { currFluid+=oz; if(currFluid>maxFluid)currFluid = maxFluid; System.out.println("You filled the cup."); } if(type == 3)currFluid *= 0.8; } } public void emptyCup(double oz) { if(!broken) { if(oz == -1) { currFluid = 0; System.out.println("You emptied the cup completely."); } else { currFluid-=oz; if(currFluid<0)currFluid = 0; System.out.println("You emptied the cup."); } if(type == 3)currFluid *=0.8; } } public void dropCup() { if(type == 1) { double breaks = Math.random(); if(breaks<0.2) { broken = true; currFluid = 0; System.out.println("You broke it."); }else System.out.println("It did not break."); }else if(type == 2) { double breaks = Math.random(); if(breaks<0.8) { broken = true; currFluid = 0; System.out.println("You broke it."); }else System.out.println("It did not break."); }else { System.out.println("It did not break."); } } public void breakCup() { if(type!=3) { broken = true; currFluid = 0; System.out.println("You broke it."); }else System.out.println("It could not be broken."); } }
package main; import centre.*; import dechet.*; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import planete.*; import vaisseau.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.*; import java.math.BigInteger; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.*; public class Main { public static List<Planete> listeDePlanete=new ArrayList<>(); public static Queue<Vaisseau> listeVaisseau=new LinkedList<>(); public static List<Centre> listeCentre=new ArrayList<>(); public static int nbCentre=3; public static int nbVaisseau=30; public static java.lang.String rouge = (char)27 + "[31m"; public static java.lang.String rose = (char)27 + "[35m"; public static java.lang.String vert = (char)27 + "[32m"; public static java.lang.String bleu = (char)27 + "[34m"; public static java.lang.String teal = (char)27 + "[36m"; public static java.lang.String brillant = (char)27 + "[1m"; public static java.lang.String noir = (char)27 + "[30m"; public static void main(String[] args) { listeDePlanete.add(new Alpha()); listeDePlanete.add(new Quebec()); listeDePlanete.add(new Delta()); listeDePlanete.add(new Charlie()); listeDePlanete.add(new Bravo()); for (int i =0; i<10;i++){ listeVaisseau.add(new VaisseauLeger()); listeVaisseau.add(new VaisseauNormal()); listeVaisseau.add(new VaisseauLourd()); } for(int i=0;i<nbCentre;i++) { listeCentre.add(new Centre()); } getData(); for(int i=0;i<nbVaisseau;i++){ envoieVaisseau(listeVaisseau.poll()); } System.out.println("Simulation terminé: Tous les vaisseaux on été envoyés"); affichageFin(); } public static void envoieVaisseau(Vaisseau vaisseau){ int random=(int)(Math.random()*5); listeDePlanete.get(random).charge(vaisseau); vaisseau.setCentreActuel(vaisseau.getCentreActuel()+1); try { listeCentre.get(vaisseau.getCentreActuel()).decharger(vaisseau); } catch (Exception e){ System.out.println("Simulation terminé: La dernière file d'attente est pleine"); affichageFin(); } } public static void affichageFin(){ for(int i=0;i<nbCentre;i++){ System.out.println("Centre #"+(i+1)); System.out.println("Nombre de vaisseaux en attente: "+listeCentre.get(i).getFileVaisseau().size()); System.out.println("Pile de Gadolinium: "+listeCentre.get(i).getListePile().get("Gadolinium").getPile().size()); System.out.println("Pile de Neptunium: "+listeCentre.get(i).getListePile().get("Neptunium").getPile().size()); System.out.println("Pile de Plutonium: "+listeCentre.get(i).getListePile().get("Plutonium").getPile().size()); System.out.println("Pile de Terbium: "+listeCentre.get(i).getListePile().get("Terbium").getPile().size()); System.out.println("Pile de Thulium: "+listeCentre.get(i).getListePile().get("Thulium").getPile().size()); } System.exit(0); } public static void getData(){ try { File fXmlFile = new File("C:\\Users\\Utilisateur\\IdeaProjects\\projetV2\\src\\Data.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); System.out.println("" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("Dechet"); System.out.println("----------------------------"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println(brillant+"\nElement actuel :" + nNode.getNodeName()+noir); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println(bleu+"First Name : " + eElement.getElementsByTagName("Nom").item(0).getTextContent()); System.out.println("Masse volumique : " + eElement.getElementsByTagName("masseVolumique").item(0).getTextContent()); System.out.println("Pourcentage : " + eElement.getElementsByTagName("pourcentage").item(0).getTextContent()+noir); System.out.println(); } } nList = doc.getElementsByTagName("Vaisseaux"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println(brillant+"\nElement actuel : " + nNode.getNodeName()); System.out.println(); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println(teal+"Vaisseau léger: " + eElement.getElementsByTagName("nbLeger").item(0).getTextContent()); System.out.println("Vaisseau normal: " + eElement.getElementsByTagName("nbNormal").item(0).getTextContent()); System.out.println("Vaisseau lourd: " + eElement.getElementsByTagName("nbLourd").item(0).getTextContent()+noir); System.out.println(); } } nList = doc.getElementsByTagName("Planete"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); System.out.println(brillant+"\nElement actuel : " + nNode.getNodeName()); System.out.println(); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println(vert+"Planete: " + eElement.getElementsByTagName("Nom").item(0).getTextContent()); System.out.println("Gadolinium en %: " + eElement.getElementsByTagName("nbGadolinium").item(0).getTextContent()); System.out.println("Neptunium en %: " + eElement.getElementsByTagName("nbNeptunium").item(0).getTextContent()); System.out.println("Plutonium en %: " + eElement.getElementsByTagName("nbPlutonium").item(0).getTextContent()); System.out.println("Terbium en %: " + eElement.getElementsByTagName("nbTerbium").item(0).getTextContent()); System.out.println("Thulium en %: " + eElement.getElementsByTagName("nbThulium").item(0).getTextContent()+noir); System.out.println(); } } } catch (Exception e) { e.printStackTrace(); } } public static void sendData(){ try { Socket socket = new Socket("localhost", 60010); OutputStream fluxSortant = socket.getOutputStream(); OutputStreamWriter sortie = new OutputStreamWriter(fluxSortant); sortie.write("sendData\n"); sortie.write(listeCentre.size()+"\n"); for(int i=0;i<listeCentre.size();i++) { sortie.write(listeCentre.get(i).getFileVaisseau().size()+"\n"); sortie.write(listeCentre.get(i).getListePile().get("Gadolinium").getPile().size()+"\n"); sortie.write(listeCentre.get(i).getListePile().get("Neptunium").getPile().size()+"\n"); sortie.write(listeCentre.get(i).getListePile().get("Plutonium").getPile().size()+"\n"); sortie.write(listeCentre.get(i).getListePile().get("Terbium").getPile().size()+"\n"); sortie.write(listeCentre.get(i).getListePile().get("Thulium").getPile().size()+"\n"); } sortie.close(); } catch(Exception e){ e.printStackTrace(); } } }
import java.util.*; import java.io.*; public class ProvincesAndGold { public static void main(String[] args) throws IOException { Scanner nya = new Scanner(System.in); int sum = nya.nextInt() * 3 + nya.nextInt() * 2 + nya.nextInt(); if(sum >= 8) System.out.print("Province or "); else if(sum >= 5) System.out.print("Duchy or "); else if(sum >= 2) System.out.print("Estate or "); if(sum >= 6) System.out.println("Gold"); else if(sum >= 3) System.out.println("Silver"); else System.out.println("Copper"); } }
package com.tencent.tencentmap.mapsdk.a; public class bl extends bm { public bl(String str) { super(str); } }
package cn.tlp.springboot.entity; /** * @author:tianlingpeng * @crateDate:2018/11/26 17:49 */ public class PlayerDTO { private String gid; private String name; private int age; private String nickname; }
package com.DoAn.HairStyle.respositiry; import com.DoAn.HairStyle.entity.UserEntity; import com.DoAn.HairStyle.entity.VoucherEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import javax.transaction.Transactional; @Repository @Transactional public interface VoucherRespository extends JpaRepository<VoucherEntity, String> { // VoucherEntity findByVoucherCode(String voucherCode); // VoucherEntity findByToken(String token); // private String voucherCode; }
package com.kodilla.spring.exception.test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class MapCreator { private final static Random RANDOM = new Random(); public Map<String,Boolean> initializeMapOfFlights() throws IOException { ClassLoader loader = getClass().getClassLoader(); File file = new File(loader.getResource("Files/DepartureAirport.txt").getFile()); Path path = Paths.get(file.getPath()); Stream<String> departureAirport = Files.lines(path); List<String> listOfDepartureAirports = departureAirport.collect(Collectors.toList()); Map<String, Boolean> mapOfFlights = new HashMap<>(); for (int i = 0; i < listOfDepartureAirports.size(); i++) { mapOfFlights.put(listOfDepartureAirports.get(i), RANDOM.nextBoolean()); } return mapOfFlights; } }
/* * Copyright 2008 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.services.remoting; import vanadis.common.io.Location; import java.io.Closeable; /** * A service for connecting to remote VM's. */ public interface Remoting extends Closeable { <T> T connect(TargetHandle<T> targetHandle); <T> T connect(TargetHandle<T> targetHandle, boolean newSession); <T> T connect(ClassLoader classLoader, TargetHandle<T> targetHandle); <T> T connect(ClassLoader classLoader, TargetHandle<T> targetHandle, boolean newSession); Remoting addLocator(Object locator); boolean isEndPoint(); Location getEndPoint(); boolean isActive(); }
package mk.petrovski.weathergurumvp.data.remote.model.location_models; import mk.petrovski.weathergurumvp.data.remote.model.error_models.DataResponseModel; /** * Created by Nikola Petrovski on 2/13/2017. */ public class SearchApiResponseModel extends DataResponseModel { private ResultModel search_api; public ResultModel getSearch_api() { return search_api; } public void setSearch_api(ResultModel search_api) { this.search_api = search_api; } }
package com.spring.service; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.spring.domain.BuyerViewForLenders; import com.spring.domain.DPDCasesTransaction; import com.spring.domain.DealerAccountTransactionFile; import com.spring.domain.DealerCreditAccountFile; import com.spring.domain.DealerDemographic; import com.spring.domain.DealerInterestRepaymentFile; import com.spring.domain.DealerOldInvoiceGenerated; import com.spring.domain.DealerPaymentCollected; import com.spring.domain.DealerPaymentFile; import com.spring.domain.DealerPurchaseData; import com.spring.domain.DealerSellerData; import com.spring.domain.DealerTransactionHistory; import com.spring.domain.LenderDealerRepaymentFile; import com.spring.domain.RepaymentFailedTransaction; import com.spring.domain.SMEDealerSalesManagerMapping; import com.spring.domain.SMEOrderInvoiceProcessDetails; import com.spring.domain.SMEOrderProcessDetails; import com.spring.domain.SMEPrincipalDealersSAPcode; import com.spring.domain.SalesForceDealerDetails; import com.spring.domain.SalesForcePrincipalDetails; import com.spring.domain.User; public interface PrincipalUpdateService { String updateDealerAccountFile(DealerCreditAccountFile dealerAccountFile); String updateDealerTransactionFile(DealerAccountTransactionFile dealerAccountTxnFile); List<DealerPaymentFile> generateRepaymentList(int lenderId, String date); List<DealerInterestRepaymentFile> generateIntrestRepaymentList(int lenderId, String date); List<LenderDealerRepaymentFile> generatePrincipalAmountRepaymentList(int lenderId, String date); public String savePrincipalAmountRepaymentList(LenderDealerRepaymentFile dealerPrincipalRepaymentFile); String updateDealerPurchaseData(DealerPurchaseData purchaseDealerData); String updateDealerSellerData(DealerSellerData dealerSellerData); String updateInvoiceGeneratedDate(DealerOldInvoiceGenerated invoiceGenerate); String updatePaymentCollectedData(DealerPaymentCollected paymentCleared); String updateDemographicData(DealerDemographic dealerDemographicData); public void saveSMEOrderProcessDetails(SMEOrderProcessDetails smeOrderProcessDetails); public void saveSMEOrderInvoiceProcessDetails(SMEOrderInvoiceProcessDetails smeOrderInvoiceProcessDetails ); public Double getAllServiceTax(); public SMEDealerSalesManagerMapping getSMEDealerSalesManagerMapping(int buyer_id); public SMEPrincipalDealersSAPcode getSMEPrincipalDealersSAPcode(String sap_code); boolean updateDealerTransactionHistoryData(ArrayList<DealerTransactionHistory> dealerTransactionHistory); public Integer getDealerIdFromSAPCode(String sapCode, int sellerId); public DealerOldInvoiceGenerated getDealerOldInvoiceGenerated(String sap_code,String seller_invoice_number); public boolean isInvoiceNumberExist(String sap_code,String seller_invoice_number); public boolean isInvoiceNumberExistInInvoiceProcessDetails(int seller_id,String seller_invoice_number); public List<DealerPurchaseData> findDealerPurchaseData(); public void saveSMEPrincipalDealersSAPcode(SMEPrincipalDealersSAPcode principalDealersSAPcode); public List<SMEPrincipalDealersSAPcode> findAllDealerBySAPCode(String sapCode); public String updateDealerBySAPCode(String dealerId, String sapCode, String oldDealerId) throws SQLException; public boolean validateDealerId(String dealerId); public String uploadRePaymentDPDFile(DPDCasesTransaction dpdCasesTrans); String updateDRPFFile(RepaymentFailedTransaction repaymentFailedFile); public DealerCreditAccountFile findDealerAccountFileObject(DealerCreditAccountFile dealerAccFil, User lender); public String updatePaidInvoicesDirect(DealerPaymentCollected paymentCollected); public SMEPrincipalDealersSAPcode getprincipalDealerSapCodeObject(String customerCode); public BuyerViewForLenders getLenderForDealer(int dealer_id); public SalesForcePrincipalDetails getSalesForcePrincipalDetails(int principal_id); public List<SalesForceDealerDetails> getPendingDPDDealer(List<String> storeList); int findNumberOfMonthForDPD(Integer dealerId); }
package com.semantyca.nb.core.service; import com.semantyca.nb.core.dataengine.jpa.IAppEntity; import com.semantyca.nb.core.dataengine.jpa.IDAO; import com.semantyca.nb.core.dataengine.jpa.IEntityWithAttachments; import com.semantyca.nb.core.dataengine.jpa.dao.exception.DAOException; import com.semantyca.nb.core.dataengine.jpa.dao.exception.DAOExceptionType; import com.semantyca.nb.core.dataengine.jpa.model.EntityAttachment; import com.semantyca.nb.core.dataengine.jpa.model.constant.ExistenceState; import com.semantyca.nb.core.rest.RestProvider; import com.semantyca.nb.core.rest.WebFormData; import com.semantyca.nb.core.rest.outgoing.ErrorOutcome; import com.semantyca.nb.core.rest.outgoing.Outcome; import com.semantyca.nb.core.rest.security.Session; import com.semantyca.nb.core.user.IUser; import com.semantyca.nb.logger.Lg; import com.semantyca.nb.ui.action.ActionBar; import com.semantyca.nb.ui.action.ConventionalActionFactory; import com.semantyca.nb.ui.view.SortParams; import com.semantyca.nb.ui.view.ViewPage; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import javax.activation.DataHandler; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.NoResultException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.ParameterizedType; import java.net.URLEncoder; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.UUID; public abstract class AbstractService<T extends IAppEntity> extends RestProvider { @Inject @Named("AuthenticatedUserSession") protected Session session; protected abstract IDAO<T, UUID> getDao(); @PostConstruct public void init() { // Class entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; // dao = DAOFactory.get(entityClass); } @GET @Produces(MediaType.APPLICATION_JSON) public Response getViewPage() { IUser user = session.getUser(); Outcome outcome = new Outcome(); WebFormData params = getWebFormData(); SortParams sortParams = params.getSortParams(SortParams.asc("login")); ViewPage vp = getDao().findViewPage(params.getPage(), session.getPageSize()); // vp.setResult(new UserToViewEntryConverter().convert(vp.getResult())); // vp.setViewPageOptions(new ViewOptions().getUserOptions()); if (user.isSuperUser()) { ConventionalActionFactory action = new ConventionalActionFactory(); ActionBar actionBar = new ActionBar(); actionBar.addAction(action.addNew); actionBar.addAction(action.deleteDocument); actionBar.addAction(action.refreshVew); outcome.addPayload(actionBar); } outcome.setTitle(vp.getMeta()); outcome.addPayload(vp); return Response.ok(outcome).build(); } @GET @Path("list") @Produces(MediaType.APPLICATION_JSON) public Response getList() { Outcome outcome = new Outcome(); List<T> list = getDao().findAll(); outcome.addPayload(list); return Response.ok(outcome).build(); } @GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public Response get(@PathParam("id") String id) { try { return Response.ok(getRequestHandler(id)).build(); } catch (DAOException e) { if (e.getType() == DAOExceptionType.ENTITY_NOT_FOUND) { return Response.status(Response.Status.NOT_FOUND).build(); } else { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorOutcome(e)).build(); } } } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response add(T dto) { return Response.ok(addRequestHandler(dto)).build(); } @PUT @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response update(T dto) { return Response.ok(updateRequestHandler(dto)).build(); } @DELETE @Path("{id}") public Response delete(@PathParam("id") String id) { T entity = getEntity(id); getDao().delete(entity); return Response.noContent().build(); } @POST @Path("uploadFile") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile(List<Attachment> attachments, @Context HttpServletRequest request) { return Response.status(Response.Status.CREATED).entity(attachmentRequestHandler(attachments)).build(); } @GET @Path("{id}/openFile/{fileName}") @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response openFile(@PathParam("id") String id, @PathParam("fileName") String fileName) { T entity = getEntity(id); try { File file = extractAttachment(entity, fileName); if (file != null) { String codedFileName = URLEncoder.encode(file.getName(), "UTF8"); return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM) .header("Content-Disposition", "attachment; filename*=\"utf-8'" + codedFileName + "\"").build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (Exception e) { Lg.exception(e); Outcome outcome = new Outcome(); return Response.status(HttpServletResponse.SC_BAD_REQUEST).entity(outcome).build(); } } public T getEntity(String id) { boolean isNew = "new".equals(id); if (isNew) { return composeNew(session.getUser()); } else { return getDao().findById(UUID.fromString(id)); } } protected T composeNew(IUser user) { try { Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; T entityInst = entityClass.getConstructor().newInstance(); entityInst.setAuthor(user.getId()); entityInst.setTitle(""); entityInst.setExistenceState(ExistenceState.NOT_SAVED); return entityInst; } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { Lg.exception(e); } return null; } protected Outcome getRequestHandler(String id) throws NoResultException, DAOException { Outcome outcome = new Outcome(); T entity; if ("new".equalsIgnoreCase(id)) { entity = composeNew(session.getUser()); outcome.setTitle("New"); } else { entity = getDao().findById(id); if (entity != null) { outcome.setTitle(entity.getTitle()); } else { throw new DAOException(DAOExceptionType.ENTITY_NOT_FOUND, id); } } outcome.addPayload(entity); return outcome; } protected Outcome addRequestHandler(T dto) { Outcome outcome = new Outcome(); outcome.setTitle(dto.getType()); if (dto.getExistenceState() == ExistenceState.NOT_SAVED) { dto.setExistenceState(ExistenceState.SAVED); return updateRequestHandler(dto); } else { outcome.addPayload(getDao().add(dto)); } return outcome; } protected Outcome updateRequestHandler(T dto) { Outcome outcome = new Outcome(); outcome.setTitle(dto.getType()); if (dto.getExistenceState() != ExistenceState.SAVED) { dto.setExistenceState(ExistenceState.SAVED); } outcome.temporaryFileName = normalizeAttachments(dto); outcome.addPayload(getDao().update(dto)); return outcome; } protected Outcome attachmentRequestHandler(List<Attachment> attachments) { Outcome outcome = new Outcome(); for (Attachment attachment : attachments) { DataHandler handler = attachment.getDataHandler(); try { InputStream stream = handler.getInputStream(); MultivaluedMap<String, String> map = attachment.getHeaders(); outcome.temporaryFileName = session.getTmpDir().getAbsolutePath() + File.separator + getFileName(map); OutputStream out = new FileOutputStream(new File(outcome.temporaryFileName)); int read = 0; byte[] bytes = new byte[1024]; while ((read = stream.read(bytes)) != -1) { out.write(bytes, 0, read); } stream.close(); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } return outcome; } protected String getFileName(MultivaluedMap<String, String> header) { String[] contentDisposition = header.getFirst("Content-Disposition").split(";"); for (String filename : contentDisposition) { if ((filename.trim().startsWith("filename"))) { String[] name = filename.split("="); String exactFileName = name[1].trim().replaceAll("\"", ""); try { exactFileName = new String(exactFileName.getBytes("ISO-8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) { } return exactFileName; } } return "unknown"; } protected File extractAttachment(IAppEntity entity, String fileName) { if (IEntityWithAttachments.class.isAssignableFrom(entity.getClass())) { IEntityWithAttachments entityWithAttachments = (IEntityWithAttachments) entity; for (EntityAttachment entityAttachment : entityWithAttachments.getFiles()) { if (entityAttachment.getFileName().equals(fileName)) { String temporaryFile = session.getTmpDir().getAbsolutePath() + File.separator + fileName; File tf = new File(temporaryFile); if (writeToFile(tf.getAbsolutePath(), entityAttachment.getFile())) { return tf; } } } } return null; } protected String normalizeAttachments(T entity) { if (IEntityWithAttachments.class.isAssignableFrom(entity.getClass())) { IEntityWithAttachments entityWithAttachments = (IEntityWithAttachments) entity; for (EntityAttachment entry : entityWithAttachments.getFiles()) { if (entry.getFile() == null) { EntityAttachment attachment = entry; File temporaryFile = new File(session.getTmpDir().getAbsolutePath() + File.separator + attachment.getFileName()); try { byte[] fileContent = Files.readAllBytes(temporaryFile.toPath()); attachment.setFile(fileContent); List<EntityAttachment> attachmentMap = new ArrayList<>(); attachmentMap.add(attachment); entityWithAttachments.setFiles(attachmentMap); return temporaryFile.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); } } } } return null; } private boolean writeToFile(String fileName, byte[] content) { FileOutputStream stream = null; try { if (content == null) { return false; } stream = new FileOutputStream(fileName); stream.write(content); return true; } catch (FileNotFoundException e) { Lg.error(e); } catch (IOException e) { Lg.error(e); } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { } } return false; } }
import java.util.Scanner; // Skriver ut YES om siffran är positiv, annars NO public class Positiv { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Input: "); int number = sc.nextInt(); if (number > 0) { System.out.println("YES"); } else { System.out.println("NO"); } } }
package br.com.unieuro.java; public class Int { }
package com.shopify.payment.popup; import java.io.OutputStream; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import com.shopify.admin.delivery.DeliveryService; import com.shopify.common.SpConstants; import com.shopify.common.ZXingHelper; import com.shopify.common.util.UtilFn; import com.shopify.order.OrderData; import com.shopify.seller.SellerData; import com.shopify.seller.SellerService; import com.shopify.shipment.popup.ShipmentPopupData; import com.shopify.shipment.ShipmentData; import com.shopify.payment.PaymentService; import com.shopify.shop.ShopData; import com.shopify.shop.ShopService; @RestController @RequestMapping("/payment/popup") public class PaymentPopupApiController{ private Logger LOGGER = LoggerFactory.getLogger(PaymentPopupApiController.class); @Autowired private PaymentService paymentService; @Autowired private PaymentPopupService paymentPopupService; @Autowired private UtilFn util; /** * 배송 > 팝업 > api용 결제페이지내 사용하는 method * @return ModelAndView(jsonView) */ @PostMapping(value="/apiPaymentPayment", produces=MediaType.APPLICATION_JSON_VALUE) public ModelAndView apiPaymentPayment(@RequestBody ShipmentData ship, Model model,HttpServletRequest req, HttpSession sess) { ModelAndView mav = new ModelAndView("jsonView"); // 1. 배송과 관련된 출고지 저장 여부 확인 // 2. 기본 출고지 저장 여부 확인 LOGGER.debug("###############popPaymentPayment=ship=>/"+ship); //LOGGER.debug("###############popPaymentPayment=ship=>/"+ship.getMasterCodeList()); if(ship != null) { String masterCode = ship.getMasterCode(); if(masterCode != null) { if(masterCode.indexOf(",") > 0) { String[] masterCodeList = masterCode.split(","); ship.setMasterCodeList(masterCodeList); ship.setMasterCode(""); //LOGGER.debug("###############popPaymentPayment=ship.getMasterCodeList()=>/"+ship.getMasterCodeList().toString()); LOGGER.debug("###############popPaymentPayment=ship.getMasterCodeList()=>/"+ship.getMasterCodeList().length); LOGGER.debug("###############popPaymentPayment=ship.getMasterCode()=>/"+ship.getMasterCode()); model = getPaymentPopupDetailMasterCode(ship, model, req, sess); }else { model = getPaymentPopupDetailMasterCode(ship, model, req, sess); } // LOGGER.debug("###############1aaaaaaaaaaaa=shop=>/"+shop); }else { model.addAttribute("status", "no"); } }else { model.addAttribute("status", "no"); } return mav; } /** * 배송 > 팝업 > 결제페이지내 사용하는 method * @return ModelAndView(jsonView) */ private Model getPaymentPopupDetailMasterCode(ShipmentData ship, Model model, HttpServletRequest req, HttpSession sess) { ShipmentPopupData shipPopData = new ShipmentPopupData(); @SuppressWarnings("unchecked") List<ShipmentPopupData> shipPopDataList = new ArrayList<ShipmentPopupData>(); List<ShipmentPopupData> shipPopDataListReturn = new ArrayList<ShipmentPopupData>(); String masterCode = ship.getMasterCode(); ShopData sessionData = (ShopData) sess.getAttribute(SpConstants.HTTP_SESSION_KEY); int cnt = paymentService.selectPaymentCount(ship, sess); if(cnt > 0) { ship.setCurrentPage(0); ship.setPageSize(10); ship.setEmail(sessionData.getEmail()); ship.setLocale(sessionData.getLocale()); shipPopData.setEmail(sessionData.getEmail()); shipPopData.setLocale(sessionData.getLocale()); if(ship.getMasterCodeList() != null && ship.getMasterCodeList().length > 0) { shipPopData.setMasterCodeList(ship.getMasterCodeList()); shipPopData.setMasterCode(""); //LOGGER.debug("#####getPaymentPopupDetailMasterCode=shipPopData.getMasterCodeList()=>/"+shipPopData.getMasterCodeList()); LOGGER.debug("#####getPaymentPopupDetailMasterCode=shipPopData.getMasterCode()=>/"+shipPopData.getMasterCode()); }else { shipPopData.setMasterCode(masterCode); } shipPopData.setEmail(sessionData.getEmail()); int cntDetail = 0; ShipmentData sData = paymentService.selectPaymentDetail(ship); LOGGER.debug("###############popPaymentPayment=sData=>/"+sData); //데이터 호출하여 가공처리(ex 복호화, 숫자 콤마처리) if(sData != null) { String sgetBuyerFirstname = sData.getBuyerFirstname(); if(sgetBuyerFirstname != null) sgetBuyerFirstname = util.getAESDecrypt(SpConstants.ENCRYPT_KEY, sgetBuyerFirstname); else sgetBuyerFirstname = ""; sData.setBuyerFirstname(sgetBuyerFirstname); String sgetBuyerLastname = sData.getBuyerLastname(); if(sgetBuyerLastname != null) sgetBuyerLastname = util.getAESDecrypt(SpConstants.ENCRYPT_KEY, sgetBuyerLastname); else sgetBuyerLastname = ""; sData.setBuyerLastname(sgetBuyerLastname); String sgetBuyerPhone = sData.getBuyerPhone(); if(sgetBuyerPhone != null) sgetBuyerPhone = util.getAESDecrypt(SpConstants.ENCRYPT_KEY, sgetBuyerPhone) ; else sgetBuyerPhone = ""; sData.setBuyerPhone(sgetBuyerPhone); int payment = sData.getPayment(); int paymentTotal = sData.getPaymentTotal(); int rankPrice = sData.getRankPrice(); DecimalFormat formatter = new DecimalFormat("###,###"); String paymentStr = formatter.format(payment); sData.setPaymentStr(paymentStr); String paymentToStringStr = formatter.format(paymentTotal); sData.setPaymentTotalStr(paymentToStringStr); String rankPriceStr = formatter.format(rankPrice); sData.setRankPriceStr(rankPriceStr); cntDetail = paymentPopupService.selectPopPaymentCount(shipPopData); if(cntDetail > 0) { shipPopDataList = paymentPopupService.selectPopPaymentList(shipPopData, sess); LOGGER.debug("###############popPaymentPayment=shipPopDataList=>/"+shipPopDataList); //데이터 호출하여 가공처리(ex 복호화, 숫자 콤마처리) for(ShipmentPopupData list : shipPopDataList) { String getBuyerFirstname = list.getBuyerFirstname(); if(getBuyerFirstname != null) getBuyerFirstname = util.getAESDecrypt(SpConstants.ENCRYPT_KEY, getBuyerFirstname); else getBuyerFirstname = ""; list.setBuyerFirstname(getBuyerFirstname); String getBuyerLastname = list.getBuyerLastname(); if(getBuyerLastname != null) getBuyerLastname = util.getAESDecrypt(SpConstants.ENCRYPT_KEY, getBuyerLastname); else getBuyerLastname = ""; list.setBuyerLastname(getBuyerLastname); String getBuyerPhone = list.getBuyerPhone(); if(getBuyerPhone != null) getBuyerPhone = util.getAESDecrypt(SpConstants.ENCRYPT_KEY, getBuyerPhone) ; else getBuyerPhone = ""; list.setBuyerLastname(getBuyerPhone); rankPrice = list.getRankPrice(); payment = list.getPayment(); paymentTotal = list.getPaymentTotal(); rankPriceStr = formatter.format(rankPrice); list.setRankPriceStr(rankPriceStr); paymentStr = formatter.format(payment); list.setPaymentStr(paymentStr); paymentToStringStr = formatter.format(paymentTotal); list.setPaymentTotalStr(paymentToStringStr); shipPopDataListReturn.add(list); } LOGGER.debug("###############popPaymentPayment=shipPopDataListReturn=>/"+shipPopDataListReturn); } } model.addAttribute("listCnt", cntDetail); //목록의 데이터개수 model.addAttribute("list", shipPopDataListReturn); //목록 model.addAttribute("detail", sData); //상세데이터 model.addAttribute("status", "ok"); }else { model.addAttribute("status", "non"); } return model; } /** * 배송 > 배송비 호출 * @return int */ @PostMapping(value="/apiPaymentDeliveryAmount", produces=MediaType.APPLICATION_JSON_VALUE) public ModelAndView apiPaymentDeliveryAmount(@RequestBody ShipmentPopupData shipPopData, Model model,HttpServletRequest req, HttpSession sess) { ModelAndView mav = new ModelAndView("jsonView"); /*shipPopData.setWeight(weightTotal); shipPopData.setCourier(sData.getCourier()); shipPopData.setCourierCompany(sData.getCourierCompany()); shipPopData.setOrigin(sData.getOrigin());*/ if(shipPopData != null) { int deliveryAmount = paymentPopupService.selectPaymentPrice(shipPopData); int deliveryAmountVat = (int)Math.floor(deliveryAmount * 0.1); model.addAttribute("deliveryAmount", deliveryAmount); model.addAttribute("deliveryAmountVat", deliveryAmountVat); }else { model.addAttribute("deliveryAmount", 0); model.addAttribute("deliveryAmountVat", 0); } return mav; } }
package com.smxknife.java2.thread.threadgroup; /** * @author smxknife * 2019/9/6 */ public class _Run2 { public static void main(String[] args) { // 这个是为了验证网络上某篇文章的正确性 ThreadGroup tg = Thread.currentThread().getThreadGroup(); System.out.println("1. tg = " + tg); int n = 1; for (ThreadGroup tgn = tg; tgn != null; tg = tgn, tgn = tg.getParent()) { System.out.println(++n + ". tg = " + tg + " | tgn = " + tgn); } } }
package flaxbeard.cyberware.common.item; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Stack; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.RenderItem; import net.minecraft.client.resources.I18n; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.MobEffects; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraft.util.DamageSource; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraftforge.client.event.EntityViewRenderEvent.FogDensity; import net.minecraftforge.client.event.RenderBlockOverlayEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.ISpecialArmor; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; import net.minecraftforge.fml.common.gameevent.TickEvent.RenderTickEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import flaxbeard.cyberware.Cyberware; import flaxbeard.cyberware.api.CyberwareAPI; import flaxbeard.cyberware.api.ICyberwareUserData; import flaxbeard.cyberware.client.ClientUtils; import flaxbeard.cyberware.client.KeyBinds; import flaxbeard.cyberware.common.CyberwareContent; public class ItemCybereyeUpgrade extends ItemCyberware { public ItemCybereyeUpgrade(String name, EnumSlot slot, String[] subnames) { super(name, slot, subnames); MinecraftForge.EVENT_BUS.register(this); FMLCommonHandler.instance().bus().register(this); } @Override public ItemStack[][] required(ItemStack stack) { if (stack.getItemDamage() > 2 && stack.getItemDamage() != 4) { return new ItemStack[][] { new ItemStack[] { new ItemStack(CyberwareContent.cybereyes) }, new ItemStack[] { new ItemStack(this, 1, 2) }}; } return new ItemStack[][] { new ItemStack[] { new ItemStack(CyberwareContent.cybereyes) }}; } private static List<EntityLivingBase> affected = new ArrayList<EntityLivingBase>(); @SubscribeEvent @SideOnly(Side.CLIENT) public void handleHighlight(RenderTickEvent event) { EntityPlayer p = Minecraft.getMinecraft().thePlayer; if (CyberwareAPI.isCyberwareInstalled(p, new ItemStack(this, 1, 3))) { if (event.phase == Phase.START) { affected.clear(); float range = 25F; List<EntityLivingBase> test = p.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, new AxisAlignedBB(p.posX - range, p.posY - range, p.posZ - range, p.posX + p.width + range, p.posY + p.height + range, p.posZ + p.width + range)); for (EntityLivingBase e : test) { if (p.getDistanceToEntity(e) <= range && e != p && !e.isGlowing()) { e.setGlowing(true); affected.add(e); } } } else if (event.phase == Phase.END) { for (EntityLivingBase e : affected) { e.setGlowing(false); } } } } @SideOnly(Side.CLIENT) @SubscribeEvent public void handleFog(FogDensity event) { EntityPlayer p = Minecraft.getMinecraft().thePlayer; if (CyberwareAPI.isCyberwareInstalled(p, new ItemStack(this, 1, 1))) { if (p.isInsideOfMaterial(Material.WATER)) { event.setDensity(0.01F); event.setCanceled(true); } else if (p.isInsideOfMaterial(Material.LAVA)) { event.setDensity(0.7F); event.setCanceled(true); } } } @SubscribeEvent public void handleNightVision(LivingUpdateEvent event) { EntityLivingBase e = event.getEntityLiving(); if (CyberwareAPI.isCyberwareInstalled(e, new ItemStack(this, 1, 0))) { e.addPotionEffect(new PotionEffect(MobEffects.NIGHT_VISION, Integer.MAX_VALUE, 53, true, false)); } else { PotionEffect effect = e.getActivePotionEffect(MobEffects.NIGHT_VISION); if (effect != null && effect.getAmplifier() == 53) { e.removePotionEffect(MobEffects.NIGHT_VISION); } } } @SubscribeEvent @SideOnly(Side.CLIENT) public void handleWaterVision(RenderBlockOverlayEvent event) { if (CyberwareAPI.isCyberwareInstalled(event.getPlayer(), new ItemStack(this, 1, 1))) { if (event.getBlockForOverlay().getMaterial() == Material.WATER || event.getBlockForOverlay().getMaterial() == Material.LAVA) { event.setCanceled(true); } } } private static boolean inUse = false; private static boolean wasInUse = false; private static boolean wasKeyDown = false; private static int zoomSettingOn = 0; private static float fov = 0F; private static float sensitivity = 0F; @SubscribeEvent @SideOnly(Side.CLIENT) public void tickStart(TickEvent.ClientTickEvent event) { Minecraft mc = Minecraft.getMinecraft(); if (event.phase == Phase.START) { wasInUse = inUse; EntityPlayer p = mc.thePlayer; if (!inUse && !wasInUse) { fov = mc.gameSettings.fovSetting; sensitivity = mc.gameSettings.mouseSensitivity; } if (CyberwareAPI.isCyberwareInstalled(p, new ItemStack(this, 1, 4))) { if (mc.gameSettings.thirdPersonView == 0) { if (KeyBinds.zoom.isPressed() && !wasKeyDown) { if (p.isSneaking()) { zoomSettingOn = (zoomSettingOn + 4 - 1) % 4; } else { zoomSettingOn = (zoomSettingOn + 1) % 4; } wasKeyDown = true; } if (!KeyBinds.zoom.isPressed()) { wasKeyDown = false; } switch (zoomSettingOn) { case 0: mc.gameSettings.fovSetting = fov; mc.gameSettings.mouseSensitivity = sensitivity; break; case 1: mc.gameSettings.fovSetting = fov; mc.gameSettings.mouseSensitivity = sensitivity; int i = 0; while (Math.abs((mc.gameSettings.fovSetting - ((fov + 5F)) / 2.0F)) > 2.5F && i < 200) { mc.gameSettings.fovSetting -= 2.5F; mc.gameSettings.mouseSensitivity -= 0.01F; i++; } break; case 2: mc.gameSettings.fovSetting = fov; mc.gameSettings.mouseSensitivity = sensitivity; i = 0; while (Math.abs((mc.gameSettings.fovSetting - ((fov + 5F)) / 5.0F)) > 2.5F && i < 200) { mc.gameSettings.fovSetting -= 2.5F; mc.gameSettings.mouseSensitivity -= 0.01F; i++; } break; case 3: mc.gameSettings.fovSetting = fov; mc.gameSettings.mouseSensitivity = sensitivity; i = 0; while (Math.abs((mc.gameSettings.fovSetting - ((fov + 5F)) / 12.0F)) > 2.5F && i < 200) { mc.gameSettings.fovSetting -= 2.5F; mc.gameSettings.mouseSensitivity -= 0.01F; i++; } break; } } } else { zoomSettingOn = 0; } inUse = zoomSettingOn != 0; if (!inUse && wasInUse) { mc.gameSettings.fovSetting = fov; mc.gameSettings.mouseSensitivity = sensitivity; } } } // http://stackoverflow.com/a/16206356/1754640 private static class NotificationStack<T> extends Stack<T> { private int maxSize; public NotificationStack(int size) { super(); this.maxSize = size; } @Override public Object push(Object object) { while (this.size() >= maxSize) { this.remove(0); } return super.push((T) object); } } public static class NotificationInstance { private float time; private INotification notification; public NotificationInstance(float time, INotification notification) { this.time = time; this.notification = notification; } public float getCreatedTime() { return time; } public INotification getNotification() { return notification; } } public static interface INotification { public void render(int x, int y); public int getDuration(); } @SideOnly(Side.CLIENT) private static class NotificationArmor implements INotification { private boolean light; private NotificationArmor(boolean light) { this.light = light; } @Override public void render(int x, int y) { Minecraft.getMinecraft().getTextureManager().bindTexture(HUD_TEXTURE); ClientUtils.drawTexturedModalRect(x, y + 1, 0, 25, 15, 14); if (light) { ClientUtils.drawTexturedModalRect(x + 9, y + 1 + 7, 15, 25, 7, 9); } else { ClientUtils.drawTexturedModalRect(x + 8, y + 1 + 7, 22, 25, 8, 9); } } @Override public int getDuration() { return 20; } } public static void addNotification(NotificationInstance not) { notifications.push(not); } public static final ResourceLocation HUD_TEXTURE = new ResourceLocation(Cyberware.MODID + ":textures/gui/hud.png"); private static Iterable<ItemStack> inv; private static boolean lightArmor = false; private static Stack<NotificationInstance> notifications = new NotificationStack(5); private static int cachedCap = 0; private static int cachedTotal = 0; private static float cachedPercent = 0; @SideOnly(Side.CLIENT) @SubscribeEvent public void onDrawScreenPost(RenderGameOverlayEvent.Post event) { EntityPlayer p = Minecraft.getMinecraft().thePlayer; if (CyberwareAPI.isCyberwareInstalled(p, new ItemStack(this, 1, 2))) { float currTime = p.ticksExisted + event.getPartialTicks(); GL11.glPushMatrix(); GlStateManager.enableBlend(); ICyberwareUserData data = CyberwareAPI.getCapability(p); Minecraft.getMinecraft().getTextureManager().bindTexture(HUD_TEXTURE); ScaledResolution res = event.getResolution(); int left = 5; int top = 5;//- right_height; Iterable<ItemStack> currInv = p.getArmorInventoryList(); if (currInv != inv) { inv = currInv; boolean temp = lightArmor; lightArmor = updateLightArmor(); if (lightArmor != temp) { addNotification(new NotificationInstance(currTime, new NotificationArmor(lightArmor))); } } FontRenderer fr = Minecraft.getMinecraft().fontRendererObj; if (p.ticksExisted % 20 == 0) { cachedPercent = data.getPercentFull(); cachedCap = data.getCapacity(); cachedTotal = data.getStoredPower(); } if (cachedPercent != -1) { int amount = Math.round((21F * cachedPercent)); boolean danger = (cachedPercent <= .2F); boolean superDanger = danger && (cachedPercent <= .05F); int xOffset = (danger ? 39 : 0); if (!superDanger || p.ticksExisted % 4 != 0) { ClientUtils.drawTexturedModalRect(left, top, xOffset, 0, 13, 2 + (21 - amount)); ClientUtils.drawTexturedModalRect(left, top + 2 + (21 - amount), 13 + xOffset, 2 + (21 - amount), 13, amount + 2); ClientUtils.drawTexturedModalRect(left, top + 2 + (21 - amount), 26 + xOffset, 2 + (21 - amount), 13, amount + 2); fr.drawStringWithShadow(cachedTotal + " / " + cachedCap, left + 15, top + 8, danger ? 0xFF0000 : 0x4CFF00); } top += 28; } List<NotificationInstance> nTR = new ArrayList<NotificationInstance>(); for (int i = 0; i < notifications.size(); i++) { NotificationInstance ni = notifications.get(i); INotification notification = ni.getNotification(); if (currTime - ni.getCreatedTime() < notification.getDuration() + 25) { double pct = Math.max(0F, ((currTime - ni.getCreatedTime() - notification.getDuration()) / 30F)); float move = (float) ((20 * Math.sin(pct * (Math.PI / 2F)))); GL11.glPushMatrix(); GL11.glTranslatef(0F, move, 0F); int index = (notifications.size() - 1) - i; notification.render(5 + index * 18, res.getScaledHeight() - 5 - 14); GL11.glPopMatrix(); } else { nTR.add(ni); } } for (NotificationInstance ni : nTR) { notifications.remove(ni); } RenderItem ir = Minecraft.getMinecraft().getRenderItem(); List<ItemStack> stacks = data.getPowerOutages(); List<Integer> stackTimes = data.getPowerOutageTimes(); List<Integer> toRemove = new ArrayList<Integer>(); left -= 1; float zL = ir.zLevel; ir.zLevel = -300; for (int i = stacks.size() - 1; i >= 0; i--) { ItemStack stack = stacks.get(i); if (stack != null) { int time = stackTimes.get(i); boolean keep = p.ticksExisted - time < 50; double pct = Math.max(0F, ((currTime - time - 20) / 30F)); float move = (float) ((20 * Math.sin(pct * (Math.PI / 2F)))); if (keep) { GL11.glPushMatrix(); GL11.glTranslatef(-move, 0F, 0F); fr.drawStringWithShadow("!", left + 14, top + 8, 0xFF0000); RenderHelper.enableStandardItemLighting(); ir.renderItemAndEffectIntoGUI(stack, left, top); RenderHelper.disableStandardItemLighting(); GL11.glPopMatrix(); top += 18; } else { toRemove.add(i); } } } ir.zLevel = zL; for (int i : toRemove) { stacks.remove(i); stackTimes.remove(i); } Minecraft.getMinecraft().getTextureManager().bindTexture(Gui.ICONS); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glPopMatrix(); } } @SideOnly(Side.CLIENT) private boolean updateLightArmor() { for (ItemStack stack : inv) { if (stack != null && stack.getItem() instanceof ItemArmor) { if (((ItemArmor) stack.getItem()).getArmorMaterial().getDamageReductionAmount(EntityEquipmentSlot.CHEST) > 4) { return false; } } else if (stack != null && stack.getItem() instanceof ISpecialArmor) { if (((ISpecialArmor) stack.getItem()).getProperties(Minecraft.getMinecraft().thePlayer, stack, DamageSource.cactus, 1, 1).AbsorbRatio * 25D > 4) { return false; } } } return true; } @Override public List<String> getStackDesc(ItemStack stack) { if (stack.getItemDamage() != 4) return super.getStackDesc(stack); String before = I18n.format("cyberware.tooltip.cybereyeUpgrades.4.before"); if (before.length() > 0) before = before + " "; String after = I18n.format("cyberware.tooltip.cybereyeUpgrades.4.after"); if (after.length() > 0) after = " " + after; return new ArrayList(Arrays.asList(new String[] { before + Keyboard.getKeyName(KeyBinds.zoom.getKeyCode()) + after })); } }
package com.example.demo; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class JasyptTest { @Test public void encrypt() { // 创建加密器 StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); // 配置 EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig(); config.setAlgorithm("PBEWithMD5AndDES");// 加密算法 config.setPassword("xxxx");// 密码 encryptor.setConfig(config); String plaintext = "root"; //明文 String ciphertext = encryptor.encrypt(plaintext); // 加密 System.out.println(plaintext + " : " + ciphertext);// 运行结果:root : root : zLdyNB+Dj3iw+J+TXZiv5g== } @Test public void decrypt() { StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig(); config.setAlgorithm("PBEWithMD5AndDES"); config.setPassword("xxxx"); encryptor.setConfig(config); String ciphertext = "zLdyNB+Dj3iw+J+TXZiv5g==";// 密文 //解密 String plaintext = encryptor.decrypt(ciphertext); // 解密 assertThat(plaintext).isEqualTo("root"); } }
package controllers; import models.Game; import models.State; import utils.LimitedIntDialog; public class StartController extends OperationController { private PutController putController; protected StartController(Game game) { super(game); } public void control() { assert this.getState() == State.INITIAL; int mode = new LimitedIntDialog("Selecciona la partida? \n 1. Partida \n 2. Demo \n Opcion?: ", 1,2).read(); if (mode == 1) { putController = new ManualPutController(this.getGame()); } else { putController = new RandomPutController(this.getGame()); } this.createKey(); this.setState(State.IN_GAME); } public PutController getPutController() { return putController; } }
// Sun Certified Java Programmer // Chapter 6, P469 // Strings, I/O, Formatting, and Parsing import java.io.*; class Dog extends Animal implements Serializable { // the rest of the Dog code }
package test; import java.lang.reflect.Array; public class ClassCastTest { public static <T> void testCast(T[] array,T element){ Class<?> type = array != null? array.getClass() : element !=null ? element.getClass() : Object.class; System.out.println("type: "+type); } public static <T> T[] add(T[] array, T element) { Class<?> type = array != null ? array.getClass() : (element != null ? element.getClass() : Object.class); // TODO - this is NOT safe to ignore - see LANG-571 System.out.println("passed here"); T[] newArray = (T[]) copyArrayGrow1(array, type);//Line that produces the exception. System.out.println("did not reach here"); newArray[newArray.length - 1] = element; return newArray; } private static Object copyArrayGrow1(Object array, Class<?> newArrayComponentType) { if (array != null) { int arrayLength = Array.getLength(array); Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1); System.arraycopy(array, 0, newArray, 0, arrayLength); return newArray; } return Array.newInstance(newArrayComponentType, 1); } public static void test(){ String[] array = {"1", "2", "3"}; String element = "4"; //array=null; //element=null; ClassCastTest.testCast(array, element); System.out.println("all passed"); } public static void testBug35(){ String[] array = {"1", "2", "3"}; String element = "4"; element=null; array=null; String[] newArray = ClassCastTest.add(array, element); for(String value: newArray){ System.out.println("value:"+ value); } System.out.println("all passed"); } public static void main(String[] args){ //ClassCastTest.test(); ClassCastTest.testBug35(); } }
package fr.umlv.escape.ship; import org.jbox2d.dynamics.Body; import android.graphics.Bitmap; import android.graphics.Canvas; import fr.umlv.escape.front.FrontApplication; import fr.umlv.escape.move.Movable; import fr.umlv.escape.weapon.Shootable; public class PlayerShip extends Ship{ public PlayerShip(String name, int health, Body body, Bitmap image, Movable moveBehaviour, Shootable shootBehaviour) { super(name, health, body, image, moveBehaviour, shootBehaviour); // TODO Auto-generated constructor stub } @Override public void onDrawSprite(Canvas canvas) { super.onDrawSprite(canvas); this.setImage(FrontApplication.frontImage.getImage(getNextImageName())); } @Override public boolean isStillDisplayable(){ return true; } }
package com.jim.multipos.ui.vendors.vendor_list; import com.jim.multipos.core.Presenter; public interface VendorListFragmentPresenter extends Presenter { void refreshList(); }
package com.vilio.plms.pojo; import java.math.BigDecimal; import java.util.Date; /** * 还款明细 */ public class PlmsRepaymentDetail { private int id; // private String code; //还款计划明细表code private String scheduleDetailCode; //科目 private int subject; //金额 private BigDecimal amount; // private String status; //应还日期 private Date timeHappened; private Date createDate; private Date modifyDate; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getScheduleDetailCode() { return scheduleDetailCode; } public void setScheduleDetailCode(String scheduleDetailCode) { this.scheduleDetailCode = scheduleDetailCode; } public int getSubject() { return subject; } public void setSubject(int subject) { this.subject = subject; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getTimeHappened() { return timeHappened; } public void setTimeHappened(Date timeHappened) { this.timeHappened = timeHappened; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } }
package unalcol.optimization.blackbox; import unalcol.search.space.ArityOne; import unalcol.search.space.Space; public class BlackBoxArityOne<T> extends ArityOne<T> { protected ArityOne<T> mutation; protected BlackBoxFunction<T> bb_function; protected int n; public BlackBoxArityOne(int n, ArityOne<T> mutation, BlackBoxFunction<T> bb_function) { this.n = n; this.bb_function = bb_function; this.mutation = mutation; } @Override public T apply(T x) { T s = mutation.apply(x); double q = bb_function.apply(s); // if( Math.random() < 0.5 ) for (int i = 1; i < n; i++) { T s2 = mutation.apply(x); double q2 = bb_function.apply(s2); if (q > q2) { s = s2; q = q2; } } return s; } @Override public T apply(Space<T> space, T x) { //System.out.println("n="+n); //return mutation.apply(space, x); T s = mutation.apply(space, x); double q = bb_function.apply(s); // if( Math.random() < 0.5 ) for (int i = 1; i < n; i++) { T s2 = mutation.apply(space, x); double q2 = bb_function.apply(s2); if (q < q2) { s = s2; q = q2; } } return s; } @Override public void adapt(double productivity) { mutation.adapt(productivity); } }
package jpamock.persitence; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Savepoint; import java.util.AbstractMap.SimpleEntry; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import jpamock.reflection.RecursiveSearch; import jpamock.reflection.Reflection; public class JDBCPersistence { private EntityManagerFactory entityManagerFactory; private PrepareIds prepareIds; private Reflection reflection = Reflection.get(); private DBHelper dbHelper; public JDBCPersistence(EntityManagerFactory entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } public Object persist(Object rootEntity, Map<String, Object> specialFields) { if (entityManagerFactory != null) { Connection connection = null; EntityManager entityManager = null; try { entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); connection = getConnection(entityManager); dbHelper = new DBHelper(connection); dbHelper.disableConstaints(); prepareIds = new PrepareIds(new DataHelper()); prepareIds.prepare(rootEntity, entityManager, specialFields); return persistReal(rootEntity, entityManager, connection); } catch (Throwable t) { if (entityManager.getTransaction().isActive()) entityManager.getTransaction().rollback(); throw new RuntimeException(t); } finally { if (entityManager.getTransaction().isActive()) { dbHelper.enableConstaints(); entityManager.getTransaction().commit(); } entityManager.close(); } } return rootEntity; } public boolean containsById(List<?> list, Object mock) { Object idMock = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(mock); for (Object object : list) { Object idElement = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(object); if (idElement.equals(idMock)) return true; } return false; } public boolean containsAllById(List<?> list1, List<?> list2) { for (Object object1 : list1) { Object id1 = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(object1); for (Object object2 : list2) { Object id2 = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(object2); if (!id1.equals(id2)) return false; } } return true; } public void clearAll() { new DBHelper().clearAll(entityManagerFactory); } private Connection getConnection(EntityManager entityManager) { // TODO enable others providers try { Connection connection; Object session = entityManager.unwrap(Class.forName("org.hibernate.Session")); connection = (Connection) session.getClass().getDeclaredMethod("connection", new Class[0]).invoke(session); return connection; } catch (Exception e) { throw new RuntimeException(e); } } /* PRIVATE */ private Object persistReal(Object rootEntity, EntityManager entityManager, Connection connection) throws Exception { final LinkedList<Entry<Object, InsertDeletStatement>> allToPersist = fillAllToPersist(rootEntity); dbHelper.prepareStatments(allToPersist, connection); while (!isEveryBodyClosed(allToPersist)) { Entry<Object, InsertDeletStatement> entryTemp = allToPersist.remove(0); Object entity = entryTemp.getKey(); PreparedStatement ps = entryTemp.getValue().getInsert(); allToPersist.add(entryTemp); // send to end of queue if (ps.isClosed()) continue; Savepoint savePoint = connection.setSavepoint(String.valueOf(System.nanoTime())); try { ps.executeUpdate(); Field fieldId = dbHelper.getId(entity); if (fieldId != null) { Object id = reflection.getProperty(entity, fieldId); if (id != null) { notifySubClasses(id, entity, allToPersist); } else { ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { if (fieldId.getType() == Long.class) { id = rs.getLong(1); reflection.setProperty(entity, fieldId, id); } else if (fieldId.getType() == Integer.class) { id = rs.getInt(1); reflection.setProperty(entity, fieldId, id); } else { throw new RuntimeException("Implement type " + fieldId.getType() + " on " + this.getClass().getName()); } notifySubClasses(id, entity, allToPersist); if (allToPersist.size() > 1) { dbHelper.prepareStatments(allToPersist, connection); dbHelper.deleteAll(allToPersist, connection); } } } } ps.close(); } catch (Throwable t) { connection.rollback(savePoint); } }// end while for (Entry<Object, InsertDeletStatement> entry : allToPersist) if (!entry.getValue().getDelete().isClosed()) entry.getValue().getDelete().close(); return rootEntity; } private LinkedList<Entry<Object, InsertDeletStatement>> fillAllToPersist(Object rootEntity) { final LinkedList<Entry<Object, InsertDeletStatement>> allToPersist = new LinkedList<Entry<Object, InsertDeletStatement>>(); new RecursiveSearch(propertyDescription -> { Object object = propertyDescription.getParent(); if (object.getClass().isAnnotationPresent(Entity.class)) { for (Entry<Object, InsertDeletStatement> entry : allToPersist) if (entry.getKey().equals(object)) return; allToPersist.add(new SimpleEntry<Object, InsertDeletStatement>(propertyDescription.getParent(), null)); } }).start(rootEntity); return allToPersist; } private void notifySubClasses(Object id, Object entity, LinkedList<Entry<Object, InsertDeletStatement>> allToPersist) { for (Entry<Object, InsertDeletStatement> entry : allToPersist) { if (entry.getKey().getClass().getSuperclass() != Object.class) { if (entry.getKey().getClass().getSuperclass() == entity.getClass()) { Field fieldId = dbHelper.getId(entry.getKey()); reflection.setProperty(entry.getKey(), fieldId, id); } } } } private boolean isEveryBodyClosed(LinkedList<Entry<Object, InsertDeletStatement>> allToPersist) { try { for (Entry<Object, InsertDeletStatement> entry : allToPersist) { PreparedStatement ps = entry.getValue().getInsert(); if (ps == null || !ps.isClosed()) return false; } return true; } catch (Exception e) { throw new RuntimeException(e); } } }
package com.pds.rn.module; import android.app.Activity; import android.content.Intent; import android.view.Window; import android.view.WindowManager; import com.facebook.react.bridge.ActivityEventListener; import com.facebook.react.bridge.BaseActivityEventListener; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; /** * @author pengdaosong */ public class CommonRTCModule extends ReactContextBaseJavaModule { public CommonRTCModule(ReactApplicationContext reactContext) { super(reactContext); // Add the listener for `onActivityResult` reactContext.addActivityEventListener(mActivityEventListener); reactContext.addLifecycleEventListener(mLifecycleEventListener); } private LifecycleEventListener mLifecycleEventListener = new LifecycleEventListener() { @Override public void onHostResume() { } @Override public void onHostPause() { } @Override public void onHostDestroy() { } }; @Override public String getName() { return "RNNativeModule"; } private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() { @Override public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) { } }; /** * 退出rn页面 */ @ReactMethod public void goBack() { } /** * 屏幕长亮切换 */ @ReactMethod public void setScreenLongLight(final boolean enable) { final Activity currentActivity = getCurrentActivity(); if (currentActivity != null) { currentActivity.runOnUiThread(new Runnable() { @Override public void run() { Window window = currentActivity.getWindow(); if (enable) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } }); } } }
package it.unical.asd.group6.computerSparePartsCompany.core.services.implemented; import it.unical.asd.group6.computerSparePartsCompany.core.exception.faq.FAQByDescriptionNotFoundException; import it.unical.asd.group6.computerSparePartsCompany.core.exception.faq.FAQByTitleNotFoundException; import it.unical.asd.group6.computerSparePartsCompany.core.services.FAQService; import it.unical.asd.group6.computerSparePartsCompany.data.dao.FAQDao; import it.unical.asd.group6.computerSparePartsCompany.data.dto.FAQDTO; import it.unical.asd.group6.computerSparePartsCompany.data.entities.FAQ; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Service public class FAQServiceImpl implements FAQService { @Autowired FAQDao faqDao; @Autowired ModelMapper modelMapper; @Override public Boolean insert(String title, String text) { FAQ faq = new FAQ(); faq.setTitle(title); faq.setDescription(text); faqDao.save(faq); return true; } @Override public List<FAQDTO>getAll() { Optional<List<FAQ>> faqs = faqDao.getAll(); if(faqs.isPresent()) { List<FAQ>fs = faqs.get(); return fs.stream().map(cat -> modelMapper.map(cat, FAQDTO.class)).collect(Collectors.toList()); } return new ArrayList<>(); } @Override public FAQ getByTitle(String title) { FAQ faq = faqDao.getByTitle(title).orElseThrow(() -> new FAQByTitleNotFoundException(title)); return faq; } @Override public FAQDTO getByDescription(String description) { FAQ faq = faqDao.getByDescription(description).orElseThrow(() -> new FAQByDescriptionNotFoundException(description)); return modelMapper.map(faq, FAQDTO.class); } @Override public Boolean remove(FAQ f) { faqDao.delete(f); return true; } @Override public Boolean delete(FAQ f) { faqDao.delete(f); return true; } @Override public Boolean deleteAll() { List<FAQDTO>faqs = getAll(); for(int i = 0; i < faqs.size(); i++) { FAQ faq = modelMapper.map(faqs.get(i),FAQ.class); delete(faq); } return true; } }
package com.tencent.mm.plugin.sight.decode.ui; class SnsAdNativeLandingPagesVideoPlayerLoadingBar$2 implements Runnable { final /* synthetic */ SnsAdNativeLandingPagesVideoPlayerLoadingBar ndT; final /* synthetic */ int ndU; SnsAdNativeLandingPagesVideoPlayerLoadingBar$2(SnsAdNativeLandingPagesVideoPlayerLoadingBar snsAdNativeLandingPagesVideoPlayerLoadingBar, int i) { this.ndT = snsAdNativeLandingPagesVideoPlayerLoadingBar; this.ndU = i; } public final void run() { this.ndT.setVideoTotalTime(this.ndU); } }
package app.davecstillo.com.schoolapp; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import app.davecstillo.com.schoolapp.avisosFragment.OnListFragmentInteractionListener; import app.davecstillo.com.schoolapp.Content.avisosContent.avisos; import java.util.List; /** * {@link RecyclerView.Adapter} that can display a {@link avisos} and makes a call to the * specified {@link OnListFragmentInteractionListener}. * TODO: Replace the implementation with code for your data type. */ public class avisosRecyclerViewAdapter extends RecyclerView.Adapter<avisosRecyclerViewAdapter.ViewHolder> { private final List<avisos> mValues; private final OnListFragmentInteractionListener mListener; public avisosRecyclerViewAdapter(List<avisos> items, OnListFragmentInteractionListener listener) { mValues = items; mListener = listener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.fragment_avisos, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { String texto; holder.mItem = mValues.get(position); holder.mIDAviso.setText(String.valueOf(position+1)+"."); holder.mTituloAviso.setText(mValues.get(position).Titulo); holder.mDescriptionAviso.setText(mValues.get(position).Descripcion); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (null != mListener) { // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. mListener.onListFragmentInteraction(holder.mItem); } } }); } @Override public int getItemCount() { return mValues.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; public final TextView mIDAviso; public final TextView mTituloAviso; public final TextView mDescriptionAviso; public avisos mItem; public ViewHolder(View view) { super(view); mView = view; mIDAviso = (TextView) view.findViewById(R.id.avisoID); mTituloAviso = (TextView) view.findViewById(R.id.tituloAviso); mDescriptionAviso = (TextView) view.findViewById(R.id.descripcionAviso); } @Override public String toString() { return super.toString() + " '" + mDescriptionAviso.getText() + "'"; } } }
package com.tencent.mm.ui; public interface m { void cpF(); void cpG(); void cpH(); void cpI(); void cpJ(); void cpK(); void cpL(); }
/* * Created on Jan 27, 2006 by pladd * */ package com.bottinifuel.pladd.CheckFree; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.NumberFormat; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.SwingConstants; import javax.swing.WindowConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import com.bottinifuel.Energy.Info.AddressInfo; import com.bottinifuel.Energy.Info.InfoFactory; import com.bottinifuel.Energy.Info.CustInfo; public class CorrectionDialog extends JDialog { private JButton NoChangesBtn; private JButton CorrectBtn; private JLabel PaymentLabel; private JTextField EnergyAcctNumber; private JLabel BalanceText; private JTextPane EnergyText; private static final long serialVersionUID = 1L; protected static InfoFactory EnergyInfo = null; private boolean Corrected = false; private boolean Drop = true; private boolean Stop = false; private int CorrectedAcctNum; private final LineItem Item; /** * Create the dialog */ public CorrectionDialog(CheckFreeImporter cf, LineItem item, boolean allowAccept) throws Exception { super(); Item = item; setName("CorrectionDialog"); setModal(true); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setTitle("Verify/Correct Account #"); getContentPane().setLayout(new BorderLayout()); setBounds(100, 100, 607, 468); if (EnergyInfo == null) EnergyInfo = new InfoFactory(); final JPanel InfoPanel = new JPanel(); InfoPanel.setLayout(new GridBagLayout()); getContentPane().add(InfoPanel); final JLabel CheckFreeAcctNum = new JLabel("CheckFree: " + item.CustAcctNumText); CheckFreeAcctNum.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; InfoPanel.add(CheckFreeAcctNum, gridBagConstraints); final JPanel LookupPanel = new JPanel(); final GridBagConstraints gridBagConstraints_2 = new GridBagConstraints(); gridBagConstraints_2.gridx = 1; gridBagConstraints_2.gridy = 0; gridBagConstraints_2.insets = new Insets(0, 0, 0, 1); InfoPanel.add(LookupPanel, gridBagConstraints_2); LookupPanel.setLayout(new BoxLayout(LookupPanel, BoxLayout.X_AXIS)); final JLabel energyLabel = new JLabel(); LookupPanel.add(energyLabel); energyLabel.setText("Energy: "); EnergyAcctNumber = new JTextField(); EnergyAcctNumber.setMinimumSize(new Dimension(100, 0)); EnergyAcctNumber.setColumns(20); String acctNum = item.CustAcctNumText; while (acctNum.charAt(0) == '0') acctNum = acctNum.substring(1); EnergyAcctNumber.setText(acctNum); EnergyAcctNumber.addActionListener(new RefreshAction()); EnergyAcctNumber.getDocument().addDocumentListener(new DisableChangeListener()); LookupPanel.add(EnergyAcctNumber); final JButton LookupBtn = new JButton(); LookupBtn.addActionListener(new RefreshAction()); LookupBtn.setText("Lookup"); LookupPanel.add(LookupBtn); final JButton BottiniLookupButton = new JButton(); BottiniLookupButton.setText("Bottini # Lookup"); BottiniLookupButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String text = EnergyAcctNumber.getText(); if (text.charAt(0) != 'B') EnergyAcctNumber.setText("B" + text); ReloadEnergyInfo(); } }); LookupPanel.add(BottiniLookupButton); final JScrollPane CheckFreePane = new JScrollPane(); final GridBagConstraints gridBagConstraints_1 = new GridBagConstraints(); gridBagConstraints_1.fill = GridBagConstraints.BOTH; gridBagConstraints_1.weighty = 1; gridBagConstraints_1.weightx = 1; gridBagConstraints_1.gridx = 0; gridBagConstraints_1.gridy = 1; InfoPanel.add(CheckFreePane, gridBagConstraints_1); final JTextPane CheckFreeText = new JTextPane(); CheckFreeText.setEditable(false); CheckFreeText.setText("\n" + item.toString()); CheckFreePane.setViewportView(CheckFreeText); final JScrollPane EnergyPane = new JScrollPane(); final GridBagConstraints gridBagConstraints_3 = new GridBagConstraints(); gridBagConstraints_3.weighty = 1; gridBagConstraints_3.weightx = 1; gridBagConstraints_3.fill = GridBagConstraints.BOTH; gridBagConstraints_3.gridx = 1; gridBagConstraints_3.gridy = 1; gridBagConstraints_3.insets = new Insets(0, 0, 0, 1); InfoPanel.add(EnergyPane, gridBagConstraints_3); EnergyText = new JTextPane(); EnergyText.setEditable(false); EnergyPane.setViewportView(EnergyText); final JPanel BalanceInfo = new JPanel(); final GridBagConstraints gridBagConstraints_4 = new GridBagConstraints(); gridBagConstraints_4.gridy = 2; gridBagConstraints_4.gridx = 1; InfoPanel.add(BalanceInfo, gridBagConstraints_4); BalanceText = new JLabel(); BalanceInfo.add(BalanceText); PaymentLabel = new JLabel(); NumberFormat form = NumberFormat.getCurrencyInstance(); PaymentLabel.setText("Payment: " + form.format(item.PaymentAmount)); final GridBagConstraints gridBagConstraints_5 = new GridBagConstraints(); gridBagConstraints_5.gridy = 2; gridBagConstraints_5.gridx = 0; InfoPanel.add(PaymentLabel, gridBagConstraints_5); final JPanel panel_2 = new JPanel(); getContentPane().add(panel_2, BorderLayout.SOUTH); final JButton StopBatchBtn = new JButton(); StopBatchBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Stop = true; dispose(); } }); panel_2.add(StopBatchBtn); StopBatchBtn.setText("Stop Batch"); final JButton DropBtn = new JButton(); DropBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Drop = true; dispose(); } }); panel_2.add(DropBtn); DropBtn.setText("Drop from batch"); CorrectBtn = new JButton(); CorrectBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Corrected = true; Drop = false; dispose(); } }); panel_2.add(CorrectBtn); CorrectBtn.setText("Correct Account Number"); NoChangesBtn = new JButton(); NoChangesBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Drop = false; dispose(); } }); NoChangesBtn.setText("No Changes"); NoChangesBtn.setEnabled(allowAccept); panel_2.add(NoChangesBtn); ReloadEnergyInfo(); } private class DisableChangeListener implements DocumentListener { public void insertUpdate(DocumentEvent arg0) { NoChangesBtn.setEnabled(false); CorrectBtn.setEnabled(false); } public void removeUpdate(DocumentEvent arg0) { NoChangesBtn.setEnabled(false); CorrectBtn.setEnabled(false); } public void changedUpdate(DocumentEvent arg0) { NoChangesBtn.setEnabled(false); CorrectBtn.setEnabled(false); } } private void ReloadEnergyInfo() { try { String a = EnergyAcctNumber.getText(); int shortAcctNum; int fullAccountNum; if (a.charAt(0) == InfoFactory.OACprefix) { shortAcctNum = EnergyInfo.OACLookup(a); fullAccountNum = EnergyInfo.InternalToFullAccount(shortAcctNum); EnergyAcctNumber.setText(Integer.toString(fullAccountNum)); } else { fullAccountNum = Integer.parseInt(a); shortAcctNum = EnergyInfo.AccountNum(fullAccountNum); } CorrectedAcctNum = fullAccountNum; CustInfo ci = EnergyInfo.GetCustomer(shortAcctNum); String addrString = ""; for (AddressInfo ai : ci.Addrs) { addrString += ai.toString() + "\n\n"; } EnergyText.setText(addrString); NumberFormat form = NumberFormat.getCurrencyInstance(); BalanceText.setText("Balance: " + form.format(ci.Balance) + " BPA: " + form.format(ci.BudgetPayment)); int eacct, iacct = 0; try { iacct = Integer.parseInt(Item.CustAcctNumText); } catch (NumberFormatException e) { iacct = 0; } eacct = Integer.parseInt(EnergyAcctNumber.getText()); if (eacct == iacct) { if (iacct != 0) NoChangesBtn.setEnabled(true); else NoChangesBtn.setEnabled(false); CorrectBtn.setEnabled(false); } else { NoChangesBtn.setEnabled(false); CorrectBtn.setEnabled(true); } } catch (NumberFormatException n) { EnergyText.setText("Account number is not numeric"); BalanceText.setText("Account number is not numeric"); NoChangesBtn.setEnabled(false); CorrectBtn.setEnabled(false); } catch (Exception e) { EnergyText.setText(e.getMessage()); BalanceText.setText(e.getMessage()); NoChangesBtn.setEnabled(false); CorrectBtn.setEnabled(false); } } private class RefreshAction implements ActionListener { public void actionPerformed(ActionEvent e) { ReloadEnergyInfo(); } } /** * @return Returns the corrected. */ public boolean isCorrected() { return Corrected; } /** * @return Returns the correctedAcctNum. */ public int getCorrectedAcctNum() { return CorrectedAcctNum; } /** * @return Returns the drop. */ public boolean isDrop() { return Drop; } /** * @return Returns the stop. */ public boolean isStop() { return Stop; } }
package pro.eddiecache.core.stats; public class StatElement<V> implements IStatElement<V> { private static final long serialVersionUID = 1L; private String name = null; private V data = null; public StatElement(String name, V data) { super(); this.name = name; this.data = data; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public V getData() { return data; } @Override public void setData(V data) { this.data = data; } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append(name).append(" = ").append(data); return buf.toString(); } }
package day48_MethodOverriting; class Credentials{ private final String UserName="Cybertek"; private final String Password="1234"; //we can not declare setter method for final variable //final variables can not be re-assigned /*public void setUserName(String Username) { this.UserName=UserName; }*/ //since getter is just for read we can decleare getter method for final variables public String getUserName() { return UserName; } } class Holly{ public final void printName() { System.out.println("Erhan"); } } public class FinalKeyword_4 extends Holly{ //override //@Override /*public void printName() { System.out.println("Medina"); final methods can nt be override }*/ final int AGE=27; public final static void main(String[] args) { final String SSN="123456"; //SSN="654321";//final variables constant and can not be reassinged final String DOB="04/08/1978"; FinalKeyword_4 obj=new FinalKeyword_4(); System.out.println(obj.AGE); } //overloading //we can overload the final methods public final static void add(int a, int b) { System.out.println(a+b); } public static double add(double a, double b) { return a+b; } //we can apply final to main method }
package mygroup; // mvn compile exec:java -D exec.mainClass="mygroup.ExceptionHandler" -D exec.cleanupDaemonThreads=false public class ExceptionHandler { public static void main(String[] args) { Thread td = new Thread(() -> System.out.println(1 / 0)); // how is this type conversion done? td.setUncaughtExceptionHandler((t, e) -> System.out.println(t.getName())); // 打印 Thread-2 td.start(); } }
package com.dbs.hack2hire.common.vo; import org.springframework.stereotype.Component; @Component public class DayReport { private String ISIN; private String stockName; private String exchange; private int quantity; private String tradeType; private boolean intraDay; private float price; private String saleID; public String getISIN() { return ISIN; } public void setISIN(String iSIN) { ISIN = iSIN; } public String getStockName() { return stockName; } public void setStockName(String stockName) { this.stockName = stockName; } public String getExchange() { return exchange; } public void setExchange(String exchange) { this.exchange = exchange; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getTradeType() { return tradeType; } public void setTradeType(String tradeType) { this.tradeType = tradeType; } public boolean isIntraDay() { return intraDay; } public void setIntraDay(boolean intraDay) { this.intraDay = intraDay; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getSaleID() { return saleID; } public void setSaleID(String saleID) { this.saleID = saleID; } }
/** * */ package com.lbsp.promotion.core.dao; import com.lbsp.promotion.entity.model.User; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author Barry * */ public interface UserDao { /** * 通过用户账户获取用户信息 * * @param account,status * @return */ User getUserByAccount(@Param("account") String account, @Param("status") Integer status); /** * 通过验证码获取用户信息 * * @param authKey * @return */ User getUserBySecurityKey(@Param("authKey") String authKey); /** * 更新用户信息 * * @param user */ void updateUserInfo(@Param("user") User user); /** * 通过权限查找电子邮件 * * @param codes * @return */ List<String> getEmailByOperate(@Param("codes") String[] codes); }
package stark.skplay.scale; /** * See {@link android.widget.ImageView.ScaleType} for a description * for each type */ public enum ScaleType { CENTER, CENTER_CROP, CENTER_INSIDE, FIT_CENTER, NONE }
package com.eecs493.power_trip; public class MediaData { String id; String url; String thumbnailUrl; String caption; float latitude; float longitude; String dateCreated; String mimeType; public MediaData() { } public MediaData(String Id, String Url, String ThumbnailUrl, String Caption, float Latitude, float Longitude, String DateCreated, String MimeType) { id = Id; url = Url; thumbnailUrl = ThumbnailUrl; caption = Caption; latitude = Latitude; longitude = Longitude; dateCreated = DateCreated; mimeType = MimeType; } }
/******************************************************************************* * Copyright 2020 Grégoire Martinetti * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package org.gmart.devtools.java.serdes.codeGen.javaGen.model.classTypes.fields; import javax.lang.model.element.Modifier; import org.gmart.devtools.java.serdes.codeGen.javaGen.model.EnumSpecification; import org.gmart.devtools.java.serdes.codeGen.javaLang.JPoetUtil; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import lombok.Getter; import lombok.Setter; public abstract class AbstractField { @Getter String name; @Setter String nameIncode; public String getNameInCode() { return escapeJavaKeyWords(nameIncode == null ? name : nameIncode); } private String escapeJavaKeyWords(String name) { if(EnumSpecification.javaKeyword.contains(name)) return name + "_"; return name; } @Getter public final boolean isOptional; public AbstractField(String name, boolean isOptional) { super(); this.name = name; this.isOptional = isOptional; } public abstract TypeName getReferenceJPoetType(boolean boxPrimitive); public TypeName getReferenceJPoetType(){ return getReferenceJPoetType(false); } public FieldSpec.Builder toJPoetField(){ return FieldSpec.builder(getReferenceJPoetType(), getNameInCode(), Modifier.PRIVATE); } public MethodSpec.Builder toJPoetGetter(){ return JPoetUtil.initGetter(getReferenceJPoetType(), getNameInCode()); } public MethodSpec.Builder toJPoetSetter(){ return JPoetUtil.initSetter(getReferenceJPoetType(), getNameInCode()); } }
package com.paytechnologies.cloudacar; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.ArrayList; import java.util.List; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.paytechnologies.cloudacar.AsynTask.UploadAddTask; import com.paytechnologies.cloudacar.AsynTask.UploadImageTask; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Shader.TileMode; import android.graphics.drawable.Drawable; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem.OnActionExpandListener; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.ShareActionProvider; import android.widget.TextView; import android.widget.Toast; @SuppressLint("NewApi") public class Submit_document_address extends SherlockFragmentActivity implements OnClickListener { private static final int PICK_FROM_CAMERA = 1; private static final int CROP_FROM_CAMERA = 2; private static final int PICK_FROM_FILE = 3; private Uri mImageCaptureUri; private AlertDialog dialog; String filePath,fileName,encodedImage; ImageView imgChooseFile; Button chooseFile,Submit,Next; private ListView mDrawerList; private DrawerLayout mDrawer; private CustomActionBarDrawerToggle mDrawerToggle; private String[] menuItems; private ShareActionProvider mShareActionProvider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_submit_document_address); captureImageInitialization(); chooseFile = (Button)findViewById(R.id.buttonChooseFileAddress); Submit = (Button)findViewById(R.id.buttonSubmitAddress); // Next = (Button)findViewById(R.id.buttonNextAddress); imgChooseFile = (ImageView)findViewById(R.id.imageProfileSubmitAddress); chooseFile.setOnClickListener(this); // Next.setOnClickListener(this); Submit.setOnClickListener(this); // enable ActionBar app icon to behave as action to toggle nav drawer getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); // set a custom shadow that overlays the main content when the drawer // opens mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); _initMenu(); mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer); mDrawer.setDrawerListener(mDrawerToggle); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } private void _initMenu() { // TODO Auto-generated method stub NsMenuAdapter mAdapter = new NsMenuAdapter(this); mAdapter.addProfile(R.string.ns_menu_main_header_Profile); mAdapter.notifyDataSetChanged(); //--------------------------------------------------- next header ----------------------------------------------------------------- mAdapter.addHeader(R.string.ns_menu_main_header_cac); menuItems = getResources().getStringArray( R.array.ns_menu_items_three); String[] menuItemsIcon2 = getResources().getStringArray( R.array.ns_menu_items_icon_three); int res3=0; for (String item : menuItems) { int id_title = getResources().getIdentifier(item, "string", this.getPackageName()); int id_icon = getResources().getIdentifier(menuItemsIcon2[res3], "drawable", this.getPackageName()); Log.d("id icomn", ""+id_icon); NsMenuItemModel mItem = new NsMenuItemModel(id_title,id_icon); mAdapter.addItem(mItem); res3++; } mDrawerList = (ListView) findViewById(R.id.drawer); // ImageView iv = (ImageView)mDrawerList.getChildAt(1).findViewById(R.id.imageViewuserName); // iv.setImageResource(R.drawable.secured); if (mDrawerList != null) mDrawerList.setAdapter(mAdapter); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); } @Override protected void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super.onSaveInstanceState(outState); if (mImageCaptureUri != null) { Log.d("cac", "Endocedimage uri in onsave"+mImageCaptureUri); outState.putString("cameraImageUri", mImageCaptureUri.toString()); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState.containsKey("cameraImageUri")) { Log.d("cac", "inresto"+mImageCaptureUri); mImageCaptureUri = Uri.parse(savedInstanceState.getString("cameraImageUri")); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { /* * The action bar home/up should open or close the drawer. * ActionBarDrawerToggle will take care of this. */ if (mDrawerToggle.onOptionsItemSelected(getMenuItem(item))) { return true; } switch(item.getItemId()){ case R.id.menu_item_share: Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); String shareBody = "Check it out"; sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Subject"); sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody); startActivity(Intent.createChooser(sharingIntent, "Share via")); break; } // Handle your other action bar items... return super.onOptionsItemSelected(item); } private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle { public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){ super( mActivity, mDrawerLayout, R.drawable.ic_drawer, R.string.ns_menu_open, R.string.ns_menu_close); } @Override public void onDrawerClosed(View view) { getActionBar().setTitle(getString(R.string.UploadAddress)); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } @Override public void onDrawerOpened(View drawerView) { getActionBar().setTitle(getString(R.string.UploadAddress)); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Highlight the selected item, update the title, and close the drawer // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); //You should reset item counter Log.d("Position is", ""+position); if(position==0){ TextView tv = (TextView)mDrawerList.getChildAt(0).findViewById(R.id.menurow_title); tv.setTextColor(getResources().getColor(R.color.Blue)); } if(position ==2){ Intent aboutUs = new Intent(Submit_document_address.this,MyTestActivity.class); aboutUs.putExtra("fromIntent", "docAddress"); startActivity(aboutUs); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); } if(position==3){ Intent callToBook = new Intent(Submit_document_address.this,CallToBook.class); callToBook.putExtra("cac", "submitDoc"); callToBook.putExtra("fromIntent", "docAddress"); startActivity(callToBook); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); } if(position==6){ String mailTo="info@cloudacar.com"; Intent email_intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",mailTo, null)); email_intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "CAC Comments"); email_intent.putExtra(android.content.Intent.EXTRA_TEXT,""); startActivity(Intent.createChooser(email_intent, "Send email...")); } if(position==4){ Intent benifits= new Intent(Submit_document_address.this,Benifits.class); benifits.putExtra("fromIntent", "docAddress"); startActivity(benifits); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); }if(position==5){ Intent features= new Intent(Submit_document_address.this,Features.class); features.putExtra("fromIntent", "docAddress"); startActivity(features); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); } if(position==7){ Intent logOut= new Intent(Submit_document_address.this,LogOut.class); startActivity(logOut); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); } mDrawer.closeDrawer(mDrawerList); } } public class CropOptionAdapter extends ArrayAdapter<CropOption> { private ArrayList<CropOption> mOptions; private LayoutInflater mInflater; public CropOptionAdapter(Context context, ArrayList<CropOption> options) { super(context, R.layout.crop_selector, options); mOptions = options; mInflater = LayoutInflater.from(context); } @Override public View getView(int position, View convertView, ViewGroup group) { if (convertView == null) convertView = mInflater.inflate(R.layout.crop_selector, null); CropOption item = mOptions.get(position); if (item != null) { ((ImageView) convertView.findViewById(R.id.iv_icon)) .setImageDrawable(item.icon); ((TextView) convertView.findViewById(R.id.tv_name)) .setText(item.title); return convertView; } return null; } } public class CropOption { public CharSequence title; public Drawable icon; public Intent appIntent; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d("cac", "ResultCode"+resultCode); if (resultCode != RESULT_OK) return; switch (requestCode) { case PICK_FROM_CAMERA: /** * After taking a picture, do the crop */ doCrop(); filePath = mImageCaptureUri.getEncodedPath(); Log.d("cac", "File Path:"+filePath); break; case PICK_FROM_FILE: /** * After selecting image from files, save the selected path */ mImageCaptureUri = data.getData(); Log.d("Selecting files form card", ""+mImageCaptureUri); if(mImageCaptureUri!=null){ try{ String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(mImageCaptureUri, filePathColumn, null, null, null); if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(filePathColumn[0]); filePath = cursor.getString(columnIndex); Log.d("cac", "File Path:"+filePath); } }catch(RuntimeException e){ e.printStackTrace(); } } doCrop(); break; case CROP_FROM_CAMERA: Bundle extras = data.getExtras(); /** * After cropping the image, get the bitmap of the cropped image and * display it on imageview. */ if (extras != null) { try{ Bitmap photo = extras.getParcelable("data"); imgChooseFile.setImageBitmap(photo); ByteArrayOutputStream baos = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object byte[] b = baos.toByteArray(); encodedImage = Base64.encodeToString(b, Base64.DEFAULT); }catch(RuntimeException e){ e.printStackTrace(); } // session.setProfilePic(encodedImage); } File f = new File(mImageCaptureUri.getPath()); /** * Delete the temporary image */ if (f.exists()) f.delete(); fileName = f.getName(); // new UploadImageTask(NewProfile.this).execute(encodedImage,filePath,fileName); break; } } private void doCrop() { final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>(); /** * Open image crop app by starting an intent * ‘com.android.camera.action.CROP‘. */ Intent intent = new Intent("com.android.camera.action.CROP"); intent.setType("image/*"); /** * Check if there is image cropper app installed. */ List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0); int size = list.size(); /** * If there is no image cropper app, display warning message */ if (size == 0) { Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show(); return; } else { /** * Specify the image path, crop dimension and scale */ intent.setData(mImageCaptureUri); intent.putExtra("outputX", 200); intent.putExtra("outputY", 200); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("scale", true); intent.putExtra("return-data", true); /** * There is posibility when more than one image cropper app exist, * so we have to check for it first. If there is only one app, open * then app. */ if (size == 1) { Intent i = new Intent(intent); ResolveInfo res = list.get(0); i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); startActivityForResult(i, CROP_FROM_CAMERA); } else { /** * If there are several app exist, create a custom chooser to * let user selects the app. */ for (ResolveInfo res : list) { final CropOption co = new CropOption(); co.title = getPackageManager().getApplicationLabel( res.activityInfo.applicationInfo); co.icon = getPackageManager().getApplicationIcon( res.activityInfo.applicationInfo); co.appIntent = new Intent(intent); co.appIntent .setComponent(new ComponentName( res.activityInfo.packageName, res.activityInfo.name)); cropOptions.add(co); } CropOptionAdapter adapter = new CropOptionAdapter( getApplicationContext(), cropOptions); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Choose Crop App"); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (mImageCaptureUri != null) { getContentResolver().delete(mImageCaptureUri, null, null); mImageCaptureUri = null; } } }); AlertDialog alert = builder.create(); alert.show(); } } } private void captureImageInitialization() { /** * a selector dialog to display two image source options, from camera * ‘Take from camera’ and from existing files ‘Select from gallery’ */ final String[] items = new String[] { "Take from camera", "Select from gallery" }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select Image"); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { // pick from // camera if (item == 0) { /** * To take a photo from camera, pass intent action * ‘MediaStore.ACTION_IMAGE_CAPTURE‘ to open the camera app. */ Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); /** * Also specify the Uri to save the image on specified path * and file name. Note that this Uri variable also used by * gallery app to hold the selected image path. */ mImageCaptureUri = Uri.fromFile(new File(Environment .getExternalStorageDirectory(), "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg")); intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri); try { intent.putExtra("return-data", true); startActivityForResult(intent, PICK_FROM_CAMERA); } catch (ActivityNotFoundException e) { e.printStackTrace(); } } else { // pick from file /** * To select an image from existing files, use * Intent.createChooser to open image chooser. Android will * automatically display a list of supported applications, * such as image gallery or file manager. */ try{ Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); Log.d("cac", "Before start activity"); startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE); Log.d("cac", "After start activity"); }catch(RuntimeException e){ e.printStackTrace(); } } } }); dialog = builder.create(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { // TODO Auto-generated method stub TextView textAlert =(TextView)menu.findItem(R.id.itemAlert).getActionView().findViewById(R.id.textViewActionCounter); textAlert.setText("0"); TextView textMessage =(TextView)menu.findItem(R.id.itemMessage).getActionView().findViewById(R.id.textViewActionCounterMessage); textMessage.setText("0"); return super.onPrepareOptionsMenu(menu); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu resource file. getSupportMenuInflater().inflate(R.menu.share_via, menu); return super.onCreateOptionsMenu(menu); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.buttonChooseFileAddress: dialog.show(); break; case R.id.buttonSubmitAddress : if(encodedImage!=null){ new UploadAddTask(Submit_document_address.this).execute(encodedImage); }else{ final Dialog dialog = new Dialog(Submit_document_address.this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // Include dialog.xml file dialog.setContentView(R.layout.custom_dialog); TextView title = (TextView)dialog.findViewById(R.id.textTitleDialog); // ImageView image = (ImageView)dialog.findViewById(R.id.imageDialog); TextView text = (TextView) dialog.findViewById(R.id.textViewDialog); text.setText("Please Select File To be Uploaded!!"); title.setText("Document Upload"); //image.setImageResource(R.drawable.warning); dialog.show(); Button declineButton = (Button) dialog.findViewById(R.id.buttondialog); // if decline button is clicked, close the custom dialog declineButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dialog.dismiss(); } }); } break; // case R.id.buttonNextAddress : // Intent i = new Intent(Submit_document_address.this, Submit_document_identity.class); // startActivity(i); // break; default: break; } } private android.view.MenuItem getMenuItem(final MenuItem item) { return new android.view.MenuItem() { @Override public int getItemId() { return item.getItemId(); } public boolean isEnabled() { return true; } @Override public boolean collapseActionView() { // TODO Auto-generated method stub return false; } @Override public boolean expandActionView() { // TODO Auto-generated method stub return false; } @Override public View getActionView() { // TODO Auto-generated method stub return null; } @Override public char getAlphabeticShortcut() { // TODO Auto-generated method stub return 0; } @Override public int getGroupId() { // TODO Auto-generated method stub return 0; } @Override public Intent getIntent() { // TODO Auto-generated method stub return null; } @Override public char getNumericShortcut() { // TODO Auto-generated method stub return 0; } @Override public int getOrder() { // TODO Auto-generated method stub return 0; } @Override public CharSequence getTitle() { // TODO Auto-generated method stub return null; } @Override public CharSequence getTitleCondensed() { // TODO Auto-generated method stub return null; } @Override public boolean hasSubMenu() { // TODO Auto-generated method stub return false; } @Override public boolean isActionViewExpanded() { // TODO Auto-generated method stub return false; } @Override public boolean isCheckable() { // TODO Auto-generated method stub return false; } @Override public boolean isChecked() { // TODO Auto-generated method stub return false; } @Override public boolean isVisible() { // TODO Auto-generated method stub return false; } @Override public android.view.MenuItem setActionView(View view) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setActionView(int resId) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setAlphabeticShortcut(char alphaChar) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setCheckable(boolean checkable) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setChecked(boolean checked) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setEnabled(boolean enabled) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setIcon(int iconRes) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setIntent(Intent intent) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setNumericShortcut(char numericChar) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setOnActionExpandListener(OnActionExpandListener listener) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setShortcut(char numericChar, char alphaChar) { // TODO Auto-generated method stub return null; } @Override public void setShowAsAction(int actionEnum) { // TODO Auto-generated method stub } @Override public android.view.MenuItem setShowAsActionFlags(int actionEnum) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setTitle(CharSequence title) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setTitle(int title) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setTitleCondensed(CharSequence title) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setVisible(boolean visible) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setActionProvider( android.view.ActionProvider actionProvider) { // TODO Auto-generated method stub return null; } @Override public android.view.ActionProvider getActionProvider() { // TODO Auto-generated method stub return null; } @Override public android.view.SubMenu getSubMenu() { // TODO Auto-generated method stub return null; } @Override public Drawable getIcon() { // TODO Auto-generated method stub return null; } @Override public ContextMenuInfo getMenuInfo() { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setIcon(Drawable arg0) { // TODO Auto-generated method stub return null; } }; } }
package com.uwetrottmann.trakt5.entities; public class Connections { public Boolean facebook; public Boolean twitter; public Boolean tumblr; }
/******************************************************* * Created by Marneus901 * * © 2013 Dynamac.org * ******************************************************** * Dynamac's field hook for reflection. * ********************************************************/ package org.dynamac.reflection; import java.lang.reflect.Field; import org.dynamac.enviroment.Data; import org.objectweb.asm.tree.FieldNode; public class FieldHook{ private String refactoredName=""; private Field reflectedField=null; private FieldNode bytecodeField; private int intMultiplier=1; private long longMultiplier=1; public FieldHook(String name, FieldNode fn){ refactoredName=name; bytecodeField=fn; } /** * Gets the field value. * Static field use only. * @return Field data */ public Object get(){ try { boolean isAccessible = reflectedField.isAccessible(); if(!isAccessible) reflectedField.setAccessible(true); Object data = reflectedField.get(Data.CLIENT_INSTANCE); if(!isAccessible) reflectedField.setAccessible(false); return data; } catch (Exception e) { //Should not happen. return null; } } /** * Gets the field value. * For non-static fields. * @param Parent instance * @return Field data */ public Object get(Object parent){ try { boolean isAccessible = reflectedField.isAccessible(); if(!isAccessible) reflectedField.setAccessible(true); Object data = reflectedField.get(parent); if(!isAccessible) reflectedField.setAccessible(false); return data; } catch(Exception e) { //Should not happen in wrappers. return null; } } public FieldNode getBytecodeField(){ return bytecodeField; } public int getIntMultiplier(){ return intMultiplier; } public long getLongMultiplier(){ return longMultiplier; } public String getName(){ return bytecodeField.name; } public Field getReflectedField(){ return reflectedField; } public String getRefactoredName(){ return refactoredName; } /** * Sets the field value. * Static field use only. * @param Data instance */ public void set(Object data){ try{ Field field = getReflectedField(); if(field!=null) field.set(Data.CLIENT_INSTANCE, data); } catch(Exception e){ } } /** * Sets the field value. * For non-static fields. * @param Parent instance * @param Data instance */ public void set(Object parent, Object data){ try{ Field field = getReflectedField(); if(field!=null) field.set(parent, data); } catch(Exception e){ } } public void setHook(Field f){ reflectedField=f; } public void setMultiplier(int i){ intMultiplier=i; } public void setMultiplier(long l){ longMultiplier=l; } public void setRefactoredName(String s){ refactoredName=s; } }
package com.steven.base; /** * @user steven * @createDate 2019/1/23 10:26 * @description 自定义 */ public class ARouterPath { /*----------微视---------------*/ /** * 主界面 */ public static final String WEE_VIDEO_MAIN_ACTIVITY = "/wee/weeVideoMainActivity"; /*----------解梦---------------*/ /** * 解梦登录 */ public static final String DREAM_LOGIN_ACTIVITY = "/dream/dreamLoginActivity"; /** * 主界面 */ public static final String DREAM_MAIN_ACTIVITY = "/dream/dreamMainActivity"; }
package com.htmlparser.jni; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; public class Scanner { static { // 调用文件名为JNI Library.dll的动态库 System.loadLibrary("libScannerCpp"); } public static String changeCharset(String str, String newCharset) throws UnsupportedEncodingException { if (str != null) { // 用默认字符编码解码字符串。 byte[] bs = str.getBytes(); // 用新的字符编码生成字符串 return new String(bs, newCharset); } return null; } public static void main(final String[] args) { StringBuilder html = readFile("C://parserTest//img.txt"); StringBuilder html2 = readFile("C://code2.txt"); // System.out.println(html); Scanner scanner = new Scanner(); for (int i = 0; i < 100000; i++) { System.out.println("Scanner.main()"+i); ArrayList<Token> tokens = scanner.parseHTMl(html.toString()); printToken(tokens); ArrayList<Token> tokens2 = scanner.parseHTMl(html2.toString()); printToken(tokens2); // ArrayList<Token> tokens3 = scanner.parseHTMl(html2.toString()); // printToken(tokens3); // // ArrayList<Token> tokens4 = scanner.parseHTMl(html2.toString()); // printToken(tokens4); } } private static void printToken(ArrayList<Token> tokens) { for (Token token : tokens) { switch (token.tag) { case Token.TEXT: System.out.println("text:" + token.text); break; case Token.STRONG: System.out.println("strong:" + token.text); break; case Token.HREF: System.out.println("href:" + token.text); break; case Token.IMG: System.out.println("img:" + token.text); break; default: break; } } } private static StringBuilder readFile(String fileName) { BufferedReader bf = null; try { bf = new BufferedReader(new InputStreamReader(new FileInputStream( fileName))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String line; StringBuilder html = new StringBuilder(); try { while ((line = bf.readLine()) != null) { html.append(line); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return html; } // native方法声明 public native ArrayList<Token> parseHTMl(String code); }
package com.plaiydmn.wifirouterdistace; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.wifi.ScanResult; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MainActivity extends AppCompatActivity { private static final String TAG = "TEST"; private WifiManager wifiManager; private TextView tview; private TextView tViewTime; private ProgressBar progressBar; private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private ListView listView; private final List<String> dataList = new ArrayList<>(); private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tview = findViewById(R.id.tview); tViewTime = findViewById(R.id.tViewTime); progressBar = findViewById(R.id.progressBar); progressBar.setVisibility(View.VISIBLE); tViewTime.setText(sdf.format(new Date())); listView = findViewById(R.id.listView); dataList.add("test"); adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); tview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { measure(); listView.invalidate(); } }); listView.invalidate(); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){ requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); measure(); }else{ tview.setText("No permission!"); } } private void measure() { wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); progressBar.setVisibility(View.VISIBLE); BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() { @Override public void onReceive(Context c, Intent intent) { boolean success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false); if (success) { scanSuccess(); } else { scanFailure(); } } }; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); getApplicationContext().registerReceiver(wifiScanReceiver, intentFilter); boolean success = wifiManager.startScan(); if (!success) { scanFailure(); } } private void scanSuccess() { List<ScanResult> results = wifiManager.getScanResults(); WifiInfo info = wifiManager.getConnectionInfo (); String ssid = info.getSSID(); progressBar.setVisibility(View.VISIBLE); dataList.clear(); for (ScanResult s : results){ DecimalFormat df = new DecimalFormat("#.##"); String data = s.SSID+ "\n" + s.BSSID + ": " + s.level + ", Distance: " + df.format(calculateDistance((double)s.level, s.frequency)) + "m"; if(ssid.substring(1,ssid.length()-1).equals(s.SSID)) tview.setText(data); dataList.add(data); Log.d(TAG, data); adapter.notifyDataSetChanged(); } tViewTime.setText(sdf.format(new Date())); listView.invalidate(); progressBar.setVisibility(View.INVISIBLE); } private void scanFailure() { tview.setText("WiFi Manager Scan Failure!"); } private double calculateDistance(double levelInDb, double freqInMHz) { double exp = (27.55 - (20 * Math.log10(freqInMHz)) + Math.abs(levelInDb)) / 20.0; return Math.pow(10.0, exp); } }
package com.dais.service; import com.common.pojo.ResultModel; import com.dais.model.Fvirtualaddress_withdraw; import java.util.List; /** * 招股金服 * CopyRight : www.zhgtrade.com * Author : liuyuanbo * Date: 2017/8/10 */ public interface Fvirtualaddress_withdrawService { int deleteByPrimaryKey(Integer fid); int insert(Fvirtualaddress_withdraw record); ResultModel insertFvirtualaddressWithdraw(Fvirtualaddress_withdraw record, Integer userId); List<Fvirtualaddress_withdraw> selectFvirtualaddressWithdraw(Integer userId, Integer symbol); Fvirtualaddress_withdraw selectByPrimaryKey(Integer fid); int updateByPrimaryKey(Fvirtualaddress_withdraw record); }
package com.led_on_off.led; import android.app.Fragment; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import java.io.IOException; import java.util.UUID; import static java.lang.Boolean.FALSE; /** * Created by Rut Vora */ public class LEDControl extends Fragment implements View.OnClickListener, TextWatcher, SeekBar.OnSeekBarChangeListener { //SPP UUID. Look for it static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Button btnOn, btnOff, btnDis; BluetoothAdapter myBluetooth = null; BluetoothSocket btSocket = null; SeekBar redSeekBar; Spinner redSpinner; TextView redValue; SeekBar greenSeekBar; Spinner greenSpinner; TextView greenValue; SeekBar blueSeekBar; Spinner blueSpinner; TextView blueValue; boolean userMode = FALSE; private String address = null; private ProgressDialog progress; private boolean isBtConnected = false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_led_control, container, false); redSeekBar = rootView.findViewById(R.id.seekBarRed); redSpinner = rootView.findViewById(R.id.spinnerRed); redValue = rootView.findViewById(R.id.editRed); //redValue.addTextChangedListener(this); redSeekBar.setOnSeekBarChangeListener(this); blueSeekBar = rootView.findViewById(R.id.seekBarBlue); blueSpinner = rootView.findViewById(R.id.spinnerBlue); blueValue = rootView.findViewById(R.id.editBlue); //blueValue.addTextChangedListener(this); blueSeekBar.setOnSeekBarChangeListener(this); greenSeekBar = rootView.findViewById(R.id.seekBarGreen); greenSpinner = rootView.findViewById(R.id.spinnerGreen); greenValue = rootView.findViewById(R.id.editGreen); //greenValue.addTextChangedListener(this); greenSeekBar.setOnSeekBarChangeListener(this); ToggleButton userToggle = rootView.findViewById(R.id.userToggle); //userToggle.isChecked() Button disconnect = rootView.findViewById(R.id.disconnect); disconnect.setOnClickListener(this); Button update = rootView.findViewById(R.id.update); update.setOnClickListener(this); new ConnectBT().execute(); return rootView; } private void disconnect() { if (btSocket != null) //If the btSocket is busy { try { btSocket.close(); //close connection } catch (IOException e) { Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show(); } getFragmentManager().popBackStack(); } } private void update(String message) { if (btSocket != null) { try { btSocket.getOutputStream().write(message.getBytes()); } catch (IOException e) { Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show(); } } } protected void setAddress(String address) { this.address = address; } @Override public void onClick(View view) { if (view.getId() == R.id.update) { String msg = "#R" + redValue.getText().toString() + "G" + greenValue.getText().toString() + "B" + blueValue.getText().toString() + "~"; update(msg); //TODO } else if (view.getId() == R.id.disconnect) { disconnect(); } } @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { //Nothing } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { //Nothing } @Override public void afterTextChanged(Editable editable) { try { if (Integer.parseInt(editable.toString()) <= 255 && Integer.parseInt(editable.toString()) >= 0) { View changed = getActivity().getCurrentFocus(); if (changed.getTag() == null) { if (changed.getId() == R.id.editRed) { redSeekBar.setTag("Bla"); redSeekBar.setProgress(Integer.parseInt(editable.toString())); redSeekBar.setTag(null); } if (changed.getId() == R.id.editGreen) { greenSeekBar.setTag("Bla"); greenSeekBar.setProgress(Integer.parseInt(editable.toString())); greenSeekBar.setTag(null); } if (changed.getId() == R.id.editBlue) { blueSeekBar.setTag("Bla"); blueSeekBar.setProgress(Integer.parseInt(editable.toString())); blueSeekBar.setTag(null); } } } } catch (Exception e) { Toast.makeText(getActivity(), "Only numbers allowed!", Toast.LENGTH_SHORT).show(); } } @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { if (b) { if (seekBar.getTag() == null) { if (seekBar.getId() == R.id.seekBarRed) { redValue.setTag("Bla"); redValue.setText(i + ""); redValue.setTag(null); } if (seekBar.getId() == R.id.seekBarGreen) { greenValue.setTag("Bla"); greenValue.setText(i + ""); greenValue.setTag(null); } if (seekBar.getId() == R.id.seekBarBlue) { blueValue.setTag("Bla"); blueValue.setText(i + ""); blueValue.setTag(null); } } } } @Override public void onStartTrackingTouch(SeekBar seekBar) { //Do Nothing } @Override public void onStopTrackingTouch(SeekBar seekBar) { //Do Nothing } private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread { private boolean ConnectSuccess = true; //if it's here, it's almost connected @Override protected void onPreExecute() { progress = ProgressDialog.show(getActivity(), "Connecting...", "Please wait!!!"); //show a progress dialog } @Override protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background { try { if (btSocket == null || !isBtConnected) { myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device BluetoothDevice device = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available btSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); btSocket.connect();//start connection } } catch (IOException e) { ConnectSuccess = false;//if the try failed, you can check the exception here } return null; } @Override protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine { super.onPostExecute(result); if (!ConnectSuccess) { Toast.makeText(getActivity(), "Connection Failed. Is it a SPP Bluetooth? Try again.", Toast.LENGTH_SHORT).show(); getFragmentManager().popBackStack(); } else { Toast.makeText(getActivity(), "Connected", Toast.LENGTH_SHORT).show(); isBtConnected = true; } progress.dismiss(); } } }
package fr.royalpha.bungeeannounce.command; import fr.royalpha.bungeeannounce.BungeeAnnouncePlugin; import fr.royalpha.bungeeannounce.manager.ConfigManager; import fr.royalpha.bungeeannounce.manager.MsgManager; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; /** * @author Royalpha */ public class ReplyCommand extends Command { private MsgManager msgManager; public ReplyCommand(BungeeAnnouncePlugin plugin, MsgManager msgManager) { super("reply", "", "r", "bungee:reply"); this.msgManager = msgManager; } public void execute(CommandSender sender, String[] args) { if (sender instanceof ProxiedPlayer) { ProxiedPlayer player = (ProxiedPlayer) sender; if (args.length == 0) { sender.sendMessage(new TextComponent(ChatColor.RED + "Usage: /reply <msg>")); return; } if (!this.msgManager.hasReplier(player)) { player.sendMessage(new TextComponent(ChatColor.RED + "You don't have any player to reply.")); return; } if (this.msgManager.isReplierOnline(player)) { ProxiedPlayer to = this.msgManager.getReplier(player); StringBuilder msgBuilder = new StringBuilder(); for (int i = 0; i < args.length; i++) msgBuilder.append(args[i]).append(" "); if (msgBuilder.toString().trim() == "") return; this.msgManager.message(player, to, msgBuilder.toString()); } else { player.sendMessage(new TextComponent(ConfigManager.Field.PM_PLAYER_NOT_ONLINE.getString().replaceAll("%PLAYER%", this.msgManager.getReplierName(player)))); } } else { sender.sendMessage(new TextComponent(ChatColor.RED + "You need to be a proxied player !")); } } }
package com.example.secuproc.Services; import com.example.secuproc.Serializers.UserData; import java.util.List; public interface UserService { UserData saveUser (UserData userData); boolean deleteUser (final Long id); List<UserData> getAllUsers (); UserData getUserById (final Long id); }
package kyle.game.besiege.battle; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.utils.Array; import kyle.game.besiege.Assets; import kyle.game.besiege.Random; import kyle.game.besiege.StrictArray; import kyle.game.besiege.battle.Unit.Orientation; import kyle.game.besiege.party.UnitDraw; import kyle.game.besiege.voronoi.Biomes; import static kyle.game.besiege.battle.BattleMap.GroundType.*; public class BattleMap extends Group { private TextureRegion white; private static final float SIZE_FACTOR = 1f; // change this to increase the drawn area around the battlefield. Cannot exceed 2 private static final float WALL_SLOW = .5f; private static final float LADDER_SLOW = .75f; private static final double RAIN_INTENSITY = 2f; public static final Color SHADOW_COLOR = new Color(0, 0, 0, .13f); public static final Color RAINDROP_COLOR = new Color(0, 0, .8f, 1f); // ALPHA is replaced later of course. public static final Color SNOW_COLOR = new Color(.7f, .7f, .8f, 1f); private static final Color CLEAR_WHITE = new Color(1, 1, 1, .5f); private static final Color PLACEMENT_COLOR = new Color(0, 1, 0, .2f); private static final Color COVER_COLOR = new Color(1, 1, 0, .5f); private static final Color CLOSED_COLOR = new Color(1, 0, 0, .5f); private static final Color RANGE_COLOR = new Color(1, 0, 0, .15f); private static final Color LOS_COLOR = new Color(1, 1, 0, .15f); private static final Color HIDE_COLOR = new Color(0, 0, 1, .15f); private static final int TREE_X_OFFSET = 1; private static final int TREE_Y_OFFSET = 1; private static final int TREE_WIDTH = 3; private static final int TREE_HEIGHT = 3; public static final float CASTLE_WALL_HEIGHT_DEFAULT = .5f; // This is the background color public Color bgColor = new Color(); public enum MapType { FOREST, BEACH, GRASSLAND, SWAMP, DESERT, SNOW, TUNDRA, PRARIE, CRAG, JUNGLE, MOUNTAINS } private MapType maptype; public static MapType getRandomMapType() { return (MapType) Random.getRandomValue(MapType.values()); } private BattleStage stage; public static final int BLOCK_SIZE = 4; private int total_size_x; private float edge_size_percent;// percent of drawn bg that is off map public Array<Ladder> ladders; public Array<BPoint> entrances; private int currentRainIndex; private BPoint[] raindrops; private Color rainColor; private final float SECONDS_PER_DROP = 1f; private int raindropsPerFrame; // this needs to be based on raindrop_count private int raindrop_count; private boolean snowing; // used for rare cases where mountaintops aren't snowing private Color groundcolor = new Color(); private class Wall { int pos_x; int pos_y; int hp; boolean damaged; Orientation orientation; int size; // original thickness of wall } public Array<Wall> walls; // private Array<Object> walls; public float sunRotation; public float sunStretch; public int wallTop; public int wallLeft; public int wallRight; public int wallBottom; private boolean wallDamaged; // Also have a stealth bonus. public enum GroundType { GRASS(1.2), DARKGRASS(1.5), DIRT(1.2), SAND(1), LIGHTSAND(1), MUD(1.2), WATER(1), LIGHTGRASS(1), SNOW(1), LIGHTSNOW(1), ROCK(1.2), DARKROCK(1.5), FLOWERS(1), FLOWERS2(1), SWAMP(1.5), SWAMP2(1.8); public double stealthBonus; GroundType(double stealthBonus) { this.stealthBonus = stealthBonus; } } private GroundType getGroundAt(int x, int y) { return ground[x / BLOCK_SIZE][y / BLOCK_SIZE]; } public GroundType getGroundAt(Unit unit) { if (unit == null) return null; if (!unit.inMap()) return null; return getGroundAt(unit.pos_x, unit.pos_y); } public enum Object { //CASTLE_WALL(.058f) TREE(.5f), TREE_ON_FIRE(.5f), DARK_TREE(.5f), DARK_TREE_ON_FIRE(.5f), SNOW_TREE(.5f), SNOW_TREE_ON_FIRE(.5f), PALM(.5f), PALM_ON_FIRE(.5f), PALM_DARK(.5f), PALM_DARK_ON_FIRE(.5f), STUMP(.1f), SMALL_WALL_V(.099f), SMALL_WALL_H(.099f), CASTLE_WALL(.04f, 20), CASTLE_WALL_FLOOR(0f, 20), COTTAGE_LOW(.1f), COTTAGE_MID(.12f), COTTAGE_HIGH(.14f), FIRE_SMALL(0.0f); float height; Orientation orientation; // for ladders int hp; // for walls private Object(float height) { this.orientation = Orientation.UP; this.height = height; this.hp = 1; } private Object(float height, int hp) { this.orientation = Orientation.UP; this.height = height; this.hp = hp; } } public class Ladder { int pos_x, pos_y; Orientation orientation; } public Array<BPoint> cover; // points with protection private GroundType[][] ground; private StrictArray<GroundType> groundTypes = new StrictArray<>(); // try this, more memory intensive but less gpu intensive private TextureRegion[][] groundTexture; public Object[][] objects; public float obscurity_factor; // This makes it harder to see units on certain types of maps. private float rainDrawOffsetX; private float rainDrawOffsetY; private StrictArray<FireContainer> fc; // private Pixmap grass, flowers, flowers2, dirt, sand, swamp, swamp2, darkgrass, mud, water, lightgrass, rock, darkrock, snow, lightsnow, lightsand; private TextureRegion wallV, wallH, castleWall, castleWallFloor, ladder, tree, snowDarkTree, darkTree, stump, palm, palmDark, treeShadow, palmShadow; private int min_x; private int max_x; public BattleMap(BattleStage mainmap, MapType mapType) { this.stage = mainmap; // this.maptype = randomMapType(); if (mapType == null) { this.maptype = getMapTypeForBiome(mainmap.biome); } else { this.maptype = mapType; } // total height is twice as big as normal size, for a massive map this.total_size_x = (int) (mainmap.size_x * SIZE_FACTOR); // this.total_size_y = (int) (mainmap.size_y * SIZE_FACTOR); this.edge_size_percent = (SIZE_FACTOR - 1) / SIZE_FACTOR / 2; ground = new GroundType[mainmap.size_x/ BLOCK_SIZE][mainmap.size_y/ BLOCK_SIZE]; objects = new Object[mainmap.size_y][mainmap.size_x]; ladders = new Array<>(); entrances = new Array<BPoint>(); cover = new Array<BPoint>(); walls = new Array<Wall>(); tree = Assets.map.findRegion("tree2"); darkTree = Assets.map.findRegion("tree dark"); snowDarkTree = Assets.map.findRegion("tree snow dark"); palm = Assets.map.findRegion("palm"); palmShadow = Assets.map.findRegion("palmShadow"); palmDark = Assets.map.findRegion("palm red"); treeShadow = Assets.map.findRegion("treeShadow"); stump = Assets.map.findRegion("stump"); wallV = Assets.map.findRegion("stone fence v"); wallH = Assets.map.findRegion("stone fence"); castleWall = Assets.map.findRegion("castle wall wood"); castleWallFloor = Assets.map.findRegion("castle wall floor wood"); ladder = Assets.map.findRegion("ladder"); white = new TextureRegion(new Texture("whitepixel.png")); this.sunStretch = (float) Math.random() * 1 + 0.5f; this.sunRotation = (float) Math.random() * 360; fc = new StrictArray<FireContainer>(); min_x = 0; max_x = stage.size_x; if (stage.isRaining() || stage.isSnowing()) { raindrop_count = 100 + (int) (Math.random() * 400); // 100 - 500 is good raindrops = new BPoint[raindrop_count]; for (int i = 0; i < raindrop_count; i++) { raindrops[i] = new BPoint(0, 0); } float delta = 1.0f / 60; raindropsPerFrame = (int) (raindrop_count * delta / SECONDS_PER_DROP); if (raindropsPerFrame < 1) raindropsPerFrame = 1; System.out.println("raindrops per frame: " + raindropsPerFrame); if (stage.isRaining()) { this.rainColor = RAINDROP_COLOR; // this.rainColor.mul(stage.targetDarkness *1f); } else { this.rainColor = SNOW_COLOR; } // System.out.println("snowing!!!"); } // default values wallTop = Integer.MAX_VALUE; wallLeft = Integer.MIN_VALUE; wallRight = Integer.MAX_VALUE; wallBottom = Integer.MIN_VALUE; // wallTop = 60; // wallLeft = 10; // wallBottom = 10;c // wallRight = 60; if (stage.hasWall() && !stage.alliesDefending) wallBottom = stage.size_y * 2/ 3; if (stage.hasWall() && stage.alliesDefending) wallTop = stage.size_y * 1/ 3; // create castle // if (stage.siegeDefense) // wallTop = (int) (stage.size_y*.2f); // if (stage.siegeAttack) // wallBottom = (int) (stage.size_y*.8f); obscurity_factor = 1; // generate random map if (maptype == MapType.FOREST) { setGroundTypesWithProbabilities(new GroundType[]{GRASS, DARKGRASS, DIRT}, new double[]{0.33, 0.80}); addAppropriateLocationFeatures(); addFences(5); addTrees(.03*Math.random() + .01, new Object[]{Object.DARK_TREE, Object.TREE}); obscurity_factor = 1.5f; bgColor = new Color(20/256f, 70/256f, 20/256f, 1); } if (maptype == MapType.GRASSLAND) { setGroundTypesWithProbabilities(new GroundType[]{LIGHTGRASS, GRASS, DIRT}, new double[]{0.5, 0.94}); addAppropriateLocationFeatures(); addTrees(.001, Object.TREE); addFences(1); bgColor = new Color(91f/256, 164/256f, 63/256f, 1); } if (maptype == MapType.PRARIE) { setGroundTypesWithProbabilities(new GroundType[]{GRASS, LIGHTGRASS, FLOWERS2, FLOWERS}, new double[]{0.7, 0.9, 0.95}); addAppropriateLocationFeatures(); addTrees(.01, Object.TREE); addFences(15); bgColor = new Color(91f/256, 164/256f, 63/256f, 1); } if (maptype == MapType.BEACH) { // this will have to be tweaked for the new map size double slope = Math.random()*3+3; double slope2 = Math.random()*1; double thresh = Random.getRandomInRange(BLOCK_SIZE * 1f, BLOCK_SIZE * 5f); int maxWaterX = 0; boolean left = Random.coinflip(); for (int i = 0; i < ground.length; i++) { for (int j = 0; j < ground[0].length; j++) { int i1 = i; int j1 = j; if (!left) { i1 = ground.length - i - 1; } ground[i1][j1] = GroundType.SAND; if (Math.random() < .01) setGround(i1, j1, GroundType.MUD); double leftSide = slope*i + slope2*j; if (leftSide < thresh || (leftSide - thresh < 4 && Math.random() < .5)) { setGround(i1, j1, WATER); if (i > maxWaterX) maxWaterX = i; // set as closed closeGround(j1, i1); } else if (leftSide > thresh + Random.getRandomInRange(100/ BLOCK_SIZE, 150/ BLOCK_SIZE)) setGround(i1, j1, GroundType.LIGHTGRASS); } } if (left) { min_x = (maxWaterX + 1) * BLOCK_SIZE; } else { max_x = (ground.length - maxWaterX ) * BLOCK_SIZE; } addAppropriateLocationFeatures(); addTrees(.005, Object.PALM); bgColor = new Color(143f/256, 202/256f, 85/256f, 1); } if (maptype == MapType.DESERT) { setGroundTypesWithProbabilities(new GroundType[]{SAND, LIGHTSAND, DIRT, MUD}, new double[]{0.6, 0.98, 0.99}); this.addFences(20); addAppropriateLocationFeatures(); addTrees(Math.random() * 0.005, Object.PALM); bgColor = new Color(204/256f, 188/256f, 74/256f, 1); } if (maptype == MapType.MOUNTAINS) { setGroundTypesWithProbabilities(new GroundType[]{ROCK, SNOW, DARKROCK}, new double[]{0.6, 0.95}); addAppropriateLocationFeatures(); addStumps(.01); bgColor = new Color(150/256f, 150/256f, 150/256f, 1); } if (maptype == MapType.JUNGLE) { setGroundTypesWithProbabilities(new GroundType[]{SWAMP2, DARKGRASS, MUD}, new double[]{0.1, 0.8}); // this.addFences(20); addAppropriateLocationFeatures(); addTrees(0.03, new Object[]{Object.PALM_DARK, Object.PALM, Object.TREE, Object.DARK_TREE}); bgColor = new Color(30/256f, 80/256f, 20/256f, 1); } if (maptype == MapType.SNOW) { setGroundTypesWithProbabilities(new GroundType[]{LIGHTSNOW, SNOW, DIRT, MUD}, new double[]{0.7, 1, 0.99}); addAppropriateLocationFeatures(); bgColor = new Color(0.95f, 0.95f, 0.95f, 1); } if (maptype == MapType.TUNDRA) { setGroundTypesWithProbabilities(new GroundType[]{LIGHTSNOW, SNOW, SWAMP, SWAMP2}, new double[]{0.3, 0.7, 0.9}); addAppropriateLocationFeatures(); // addTrees(.03*Math.random() + .01, new Object[]{Object.DARK_TREE, Object.TREE}); addTrees(Random.getRandomInRange(0.005, 0.05), new Object[]{Object.DARK_TREE, Object.SNOW_TREE}); addStumps(.01); bgColor = new Color(0.95f, 0.95f, 0.95f, 1); } if (maptype == MapType.CRAG) { setGroundTypesWithProbabilities(new GroundType[]{DARKROCK, MUD, ROCK}, new double[]{0.7, 0.9}); stage.targetDarkness = .5f; addAppropriateLocationFeatures(); addFire(.001); addStumps(.01); bgColor = new Color(58/256f, 47/256f, 45/256f, 1); } if (maptype == MapType.SWAMP) { setGroundTypesWithProbabilities(new GroundType[]{SWAMP, SWAMP2, DIRT}, new double[]{0.5, 0.95}); addAppropriateLocationFeatures(); bgColor = new Color(65/256f, 138/256f, 92/256f, 1); } // Manipulate background color based on time of day: if (stage.options != null) bgColor = blend(bgColor, stage.options.timeOfDay.tint); // remove cover on top of objects for (BPoint p : cover) { if (objects[p.pos_y][p.pos_x] != null || stage.closed[p.pos_y][p.pos_x]) { // System.out.println("removing value from cover"); // cover.removeValue(p, true); // doesn't work for some reason } } if (stage.isSnowing()) obscurity_factor *= 1.5f; if (stage.isRaining()) obscurity_factor *= 1.2f; rainDrawOffsetX = 0; rainDrawOffsetY = 0; initializeGround(); } private Color blend(Color c1, Color c0) { c0 = new Color(c0); c1 = new Color(c1); // r0 over 1 = (1 - a0)·r1 + a0·r0 Color c3 = new Color(); c3.r = (1 - c0.a) * c1.r + c0.a * c0.r; c3.g = (1 - c0.a) * c1.g + c0.a * c0.r; c3.b = (1 - c0.a) * c1.b + c0.a * c0.r; c3.a = 1; return c3; } // Example: {GRASS, DARKGRASS, DIRT}, {0.33, 0.83} // That means theres's a 33% chance of grass, 0.5 chance for darkgrass, and a 0.17 chance of dirt. private void setGroundTypesWithProbabilities(GroundType[] types, double[] probs) { for (int i = 0; i < ground.length; i++) { for (int j = 0; j < ground[0].length; j++) { double random = Math.random(); for (int k = 0; k < types.length; k++) { // Use default if no ground set yet. if (k >= probs.length || random < probs[k]) { setGround(i, j, types[k]); break; } } } } } private void setGround(int i, int j, GroundType groundType) { ground[i][j] = groundType; if (!groundTypes.contains(groundType, true)) groundTypes.add(groundType); } // Takes into account water, etc. public int getMinX() { return min_x; } public int getMaxX() { return max_x; } public void initializeGround() { // Texture[][] baseTextures = new Texture[ground.length][ground[0].length]; groundTexture = new TextureRegion[ground.length][ground[0].length]; // // create base texture, first test this // for (int i = 0; i < groundTexture.length; i++) { // for (int j = 0; j < groundTexture[0].length; j++) { //// Pixmap base = this.getTexture(ground[i][j]); //// //// Pixmap mask = this.getTexture(ground[0][0]); //// //// Color c; //// //// for (int x = 0; x < base.getWidth(); x++) { //// for (int y = 0; y < base.getHeight(); y++) { //// int maskColor = mask.getPixel(x, y); //// System.out.println(maskColor); //// c = new Color(maskColor); //// c = new Color(c.r, c.g, c.b, 0.5f); //// base.setColor(c); //// base.drawPixel(x, y); //// } //// } //// //// groundTexture[i][j] = new TextureRegion(new Texture(base)); // groundTexture[i][j] = new TextureRegion(new Texture(this.getTexture(ground[i][j]))); // } // } // int half_width = (int) (getDrawWidth()/2); // int half_height = (int) (getDrawHeight()/2); // apply pixmap layers // TODO this blending and the need to store so many textures might be the most expensive part of battle map. can test by having a small battle on a huge map. // then add blend textures (shift down and right 1) for (int i = 0; i < ground[0].length; i++) { for (int j = 0; j < ground.length; j++) { Pixmap current = getTexture(ground[j][i]); // current. // DON'T mess with this, the algo is really good now. boolean blend = true; if (blend) { // now for each of the 8 (9) adjacent textures, blend them with appropriate corners of this guy // Option 1: draw one ground type at a time. e.g., draw the most popular ground type first, then accents on top of that. or vice versa for smoothing. // for (GroundType currentType : groundTypes) { // TODO randomize this a little bit int deltaX = 1; int deltaY = 1; int xStart = -1; int xEnd = 2; int yStart = -1; int yEnd = 2; // This doesn't work as intended because order does matter for two adjacent squares I think. // Not high priority. // if (Random.coinflip()) { // deltaX = -1; // xStart = 1; // xEnd = -2; // } // if (Random.coinflip()) { // deltaY = -1; // yStart = 1; // yEnd = -2; // } for (int x = xStart; x != xEnd; x += deltaX) { for (int y = yStart; y != yEnd; y += deltaY) { if (x + j < 0 || x + j >= ground.length || y + i < 0 || y + i >= ground[0].length) continue; // if (ground[j + x][i + y] != currentType) // continue; Pixmap mask = this.getTexture(ground[j + x][i + y]); Color c; float MAX_ALPHA = 0.6f; // Current blending algo -- // for every square // go through all 8 adjacent squares // go through every pixel in this guy // blend this pixel's color with a random // pixel from the adjacent square // blending is based on distance away from // that square. // // problems: every pixel in this light square // might be darkened by a dark square to the right, but a square to the left of this one won't be // affected by the dark one (because it's nonadjacent). so the border of this one and // the neighbor won't be blended. simple fix: only let pixels that are actually // close to the dark square be affected (so the far edge won't see any darkening). // complex fix: have multiple passes for blending (using already blended textures for blending) // How to implement simple fix: // the alpha calculation should be 0 for pixels that are width pixels away from the opposite // side, and 1 for pixels that are adjacent. alpha calculation should be based on distance // to the center of the adjacent square? or, based on distance to center of this square? for (int x_pix = 0; x_pix < current.getWidth(); x_pix++) { for (int y_pix = 0; y_pix < current.getHeight(); y_pix++) { // add some randomness for which pixel in // adjacent square we're talking about. int random_x = (int) (Math.random() * current.getWidth()); int random_y = (int) (Math.random() * current.getHeight()); int maskColor = mask.getPixel(random_x, random_y); c = new Color(maskColor); // position is relative to current boxs // bottom left corner (x_pix = 0, y_pix // = 0) float adjacentCenterX = x * current.getWidth() + current.getWidth() / 2; float adjacentCenterY = -y * current.getHeight() + current.getHeight() / 2; boolean useRandomInsteadOfCenter = false; if (useRandomInsteadOfCenter) { adjacentCenterX = x * current.getWidth() + random_x; adjacentCenterY = -y * current.getHeight() + random_y; } // First, calculate distance to center of adjacent square. float distanceToCenterOfAdjacent = (float) Math.sqrt((x_pix - adjacentCenterX) * (x_pix - adjacentCenterX) + (y_pix - adjacentCenterY) * (y_pix - adjacentCenterY)); // Distance to center of adjacent is proportional to the affect on alpha // Picture a square, and then draw a circle that's just small enough to fit // the square. That circle has radius = hypotenuse of the square. // Everything within that distance will have a high alpha impact. beyond that // will have diminishing alpha impact. float hypotenuse = (float) Math.sqrt((current.getWidth() / 2) * (current.getWidth () / 2) + (current.getHeight() / 2) * (current.getHeight() / 2)); // Now that we have the minimum impact distance (the hypotenuse), we need the // maximum impact distance. Let's go as far as possible without // affecting non-adjacent squares. The distance from the center of this // square will simply be 1.5 * square width. float maxImpactDistance = 1.5f * current.getWidth(); // Now, to calculate the distance impact. // Might be greater than one, but should never be less than 0. // if distance < hypotenuse, impact = 1; // if distance > maxImpactDistance, impact // = 0; // |0 1| // ----- -- --- ----- // o | ) o | float distanceImpactInverted = (distanceToCenterOfAdjacent - hypotenuse) / (maxImpactDistance - hypotenuse); float distanceImpact = 1 - distanceImpactInverted; if (distanceImpact > 1) distanceImpact = 1; if (distanceImpact < 0) distanceImpact = 0; c.a = distanceImpact * MAX_ALPHA; current.setColor(c); current.drawPixel(x_pix, y_pix); } } } } // } } groundTexture[j][i] = new TextureRegion(new Texture(current)); } } // // convert to textureRegions // for (int i = 0; i < groundTexture.length; i++) { // for (int j = 0; j < groundTexture[0].length; j++) { // groundTexture[i][j] = new TextureRegion(baseTextures[i][j]); // } // } } public static MapType getMapTypeForBiome(Biomes biome) { switch(biome) { case BEACH : return MapType.BEACH; case SNOW : return MapType.SNOW; case TUNDRA : return MapType.TUNDRA; case MOUNTAINS: return MapType.MOUNTAINS; case SCORCHED : return MapType.CRAG; case TAIGA : return MapType.TUNDRA; case PLATEAU : return MapType.GRASSLAND; case SWAMP : return MapType.SWAMP; case TEMPERATE_DECIDUOUS_FOREST : return MapType.FOREST; case GRASSLAND : return MapType.PRARIE; case SUBTROPICAL_DESERT : return MapType.DESERT; case SHRUBLAND: return MapType.GRASSLAND; case ICE : return MapType.SNOW; case MARSH : return MapType.SWAMP; case TROPICAL_RAIN_FOREST : return MapType.JUNGLE; case TROPICAL_SEASONAL_FOREST : return MapType.JUNGLE; case LAKESHORE: return MapType.BEACH; default : return MapType.GRASSLAND; } } private void addWall() { // figure out what kind of shape you want... // different types of sieges: ladder, catapult, or already broken double percent_broken = .1; System.out.println("adding wall"); if (wallTop != Integer.MAX_VALUE) { for (int i = Math.max(0, wallLeft); i < Math.min(total_size_x/SIZE_FACTOR, wallRight); i++) { if (Math.random() > percent_broken) { boolean bool = false; if (i % 10 == 7 || i % 10 == 5) bool = true; this.addSingleWall(i, wallTop, 3, Orientation.UP, bool); } else { BPoint entrance = new BPoint(i, wallTop); entrances.add(entrance); } } } if (wallBottom != Integer.MIN_VALUE) { for (int i = Math.max(0, wallLeft); i < Math.min(total_size_x/SIZE_FACTOR, wallRight); i++) { if (Math.random() > percent_broken) { boolean bool = false; if (i % 10 == 7 || i % 10 == 5) bool = true; this.addSingleWall(i, wallBottom, 3, Orientation.DOWN, bool); } else { BPoint entrance = new BPoint(i, wallBottom); entrances.add(entrance); } } } if (wallRight != Integer.MAX_VALUE) { for (int i = Math.max(0, wallBottom); i < Math.min(total_size_x/SIZE_FACTOR, wallTop); i++) { if (Math.random() > percent_broken) { boolean bool = false; if (i % 10 == 7 || i % 10 == 5) bool = true; this.addSingleWall(wallRight, i, 3, Orientation.RIGHT, bool); } else { BPoint entrance = new BPoint(wallRight, i); entrances.add(entrance); } } } if (wallLeft != Integer.MIN_VALUE) { for (int i = Math.max(0, wallBottom); i < Math.min(total_size_x/SIZE_FACTOR, wallTop); i++) { if (Math.random() > percent_broken) { boolean bool = false; if (i % 10 == 7 || i % 10 == 5) bool = true; this.addSingleWall(wallLeft, i, 3, Orientation.LEFT, bool); } else { BPoint entrance = new BPoint(wallLeft, i); entrances.add(entrance); } } } } private void addAppropriateLocationFeatures() { if (stage.hasWall()) { System.out.println("adding wall"); addWall(); } else if (stage.isVillage()) { // TODO have addVillage(); addRuins(); } else if (stage.isRuins()) { addRuins(); } } private void addLadder(int pos_x, int pos_y, Orientation orientation) { Ladder l = new Ladder(); l.pos_x = pos_x; l.pos_y = pos_y; l.orientation = orientation; this.ladders.add(l); stage.slow[l.pos_y][l.pos_x] = LADDER_SLOW; } public void removeLadderAt(int pos_x, int pos_y) { for (Ladder l : ladders) { if (l.pos_x == pos_x && l.pos_y == pos_y) ladders.removeValue(l, true); } stage.slow[pos_y][pos_x] = 0; } public boolean ladderAt(int pos_x, int pos_y) { return getLadderAt(pos_x, pos_y) != null; } public Ladder getLadderAt(int pos_x, int pos_y) { for (Ladder l : ladders) { if (l.pos_x == pos_x && l.pos_y == pos_y) return l; } return null; } public boolean entranceAt(int pos_x, int pos_y) { for (BPoint l : entrances) { if (l.pos_x == pos_x && l.pos_y == pos_y) return true; } return false; } private void addCottage() { int MIN_SIZE = 5; int MAX_SIZE = 10; int size_x, size_y; size_x = size_y = (int) (Math.random() * (MAX_SIZE - MIN_SIZE) + MIN_SIZE); // find clear region } // private void addTower(int y_position) { // // // add ladders // if (addObject(stage.size_x/2, y_position+1, Object.LADDER)) { // stage.slow[y_position+1][stage.size_x/2] = LADDER_SLOW; // stage.closed[y_position+1][stage.size_x/2] = false; // } // // for (int i = 0; i < stage.size_x; i++) { // if (addObject(i, y_position, Object.CASTLE_WALL_FLOOR)) { // stage.heights[y_position][i] = CASTLE_WALL_HEIGHT_DEFAULT; // close random middle row // Point coverPoint = new Point(i, y_position); // coverPoint.orientation = Orientation.UP; // if (inMap(coverPoint)) cover.add(coverPoint); // } // } // // for (int i = 0; i < stage.size_x; i++) { // if (addObject(i, y_position-1, Object.CASTLE_WALL_FLOOR)) // stage.heights[y_position-1][i] = CASTLE_WALL_HEIGHT_DEFAULT; // close random middle row // } // for (int i = 0; i < stage.size_x; i++) { // if (addObject(i, y_position+1, Object.CASTLE_WALL)) { // stage.heights[y_position+1][i] = CASTLE_WALL_HEIGHT_DEFAULT; // close random middle row // stage.closed[y_position+1][i] = true; // } // } // // // add ladders // if (addObject(stage.size_x/2-1, y_position-2, Object.LADDER)) // stage.slow[y_position-2][stage.size_x/2-1] = LADDER_SLOW; // // add ladders // if (addObject(stage.size_x/2+1, y_position-2, Object.LADDER)) // stage.slow[y_position-2][stage.size_x/2+1] = LADDER_SLOW; // // } // Returns true if any of the adjacent squares is obstructed private boolean adjacentObstructed(int x, int y) { // System.out.println("checking: " + x + " " + y); boolean obstructed = false; for (int i = x - 1; i <= x+1; i++) { for (int j = y - 1; j <= y+1; j++) { if (stage.inMap(i, j) && stage.closed[j][i]) { //!stage.inMap(i, j) || // System.out.println("checking: " + x + " " + y + ", obstructed by: " + i + " " + j); obstructed = true; } } } return obstructed; } private void addSnowTrees(double probability) { for (int i = 0; i < stage.size_x; i++) { for (int j = 0; j < stage.size_y; j++) { GroundType g = getGroundAt(i, j); double prob = probability * getTreeProb(g); if (Math.random() < prob && objects[j][i] == null && !insideWalls(i, j) && stage.canPlaceUnit(i, j) && !adjacentObstructed(i, j)) { objects[j][i] = Object.SNOW_TREE; stage.closed[j][i] = true; // mainmap.closed[i][j] = true; } } } } private void addTrees(double probability, Object[] array) { for (int i = 0; i < stage.size_x; i++) { for (int j = 0; j < stage.size_y; j++) { GroundType g = getGroundAt(i, j); double prob = probability * getTreeProb(g); if (this.maptype == MapType.BEACH) { if (Math.random() < probability && objects[j][i] == null && !insideWalls(i, j) && ground[i / BLOCK_SIZE][j / BLOCK_SIZE] == GroundType.LIGHTGRASS && !adjacentObstructed(i, j)) { objects[j][i] = (Object) Random.getRandomValue(array); stage.closed[j][i] = true; } } else if (Math.random() < prob && objects[j][i] == null && !insideWalls(i, j) && stage.canPlaceUnit(i, j) && !adjacentObstructed(i, j)) { objects[j][i] = (Object) Random.getRandomValue(array); stage.closed[j][i] = true; // mainmap.closed[i][j] = true; } } } } private void addTrees(double probability, Object treeType) { Object[] array = new Object[1]; array[0] = treeType; addTrees(probability, array); } private float getTreeProb(GroundType ground) { switch(ground) { case ROCK: return 0.1f; case DARKROCK: return 0.0f; case SAND: return 0.2f; case SNOW: return 0.5f; case DIRT: return 0.5f; case GRASS: return 1.5f; case DARKGRASS: return 3.5f; case MUD: return 0.5f; case WATER: return 0; default: return 1; } } // private void addPalms(double probability) { // for (int i = 0; i < stage.size_x; i++) { // for (int j = 0; j < stage.size_y; j++) { // // Only add palms on the grassy part of the map (not the sand) // if (this.maptype == MapType.BEACH) { // if (Math.random() < probability && objects[j][i] == null && !insideWalls(i, j) && ground[i / BLOCK_SIZE][j / BLOCK_SIZE] == GroundType.LIGHTGRASS && !adjacentObstructed(i, j)) { // objects[j][i] = Object.PALM; // stage.closed[j][i] = true; // } // } // else { // if (Math.random() < probability && objects[j][i] == null && !insideWalls(i, j) && !adjacentObstructed(i, j)) { // objects[j][i] = Object.PALM; // stage.closed[j][i] = true; // } // } // } // } // } private boolean fireAt(int posX, int posY) { Object o = objects[posY][posX]; if (o == Object.TREE_ON_FIRE || o == Object.PALM_ON_FIRE || o == Object.PALM_DARK_ON_FIRE || o == Object.FIRE_SMALL || o == Object.DARK_TREE_ON_FIRE || o == Object.SNOW_TREE_ON_FIRE) return true; return false; } public void createFireAt(int posX, int posY) { if (fireAt(posX, posY)) return; // Do this check so we can draw both tree and fire at the same time ;) // problem is it still allows multiple fires to be created on the same tree. // can solve with Object.TREE_ON_FIRE boolean shouldGrow = true; if (objects[posY][posX] == Object.TREE) objects[posY][posX] = Object.TREE_ON_FIRE; else if (objects[posY][posX] == Object.DARK_TREE) objects[posY][posX] = Object.DARK_TREE_ON_FIRE; else if (objects[posY][posX] == Object.SNOW_TREE) objects[posY][posX] = Object.SNOW_TREE_ON_FIRE; else if (objects[posY][posX] == Object.PALM) objects[posY][posX] = Object.PALM_ON_FIRE; else if (objects[posY][posX] == Object.PALM_DARK) objects[posY][posX] = Object.PALM_DARK_ON_FIRE; else { objects[posY][posX] = Object.FIRE_SMALL; shouldGrow = false; } stage.closed[posY][posX] = true; FireContainer fireContainer = new FireContainer(); Fire fire = new Fire(800, 1000, stage.getMapScreen(), null, shouldGrow, false); fireContainer.addFire(fire); float y = posY * stage.unit_height + stage.unit_height * 0.5f; if (objects[posY][posX] == Object.TREE_ON_FIRE || objects[posY][posX] == Object.DARK_TREE_ON_FIRE || objects[posY][posX] == Object.SNOW_TREE_ON_FIRE) y = posY * stage.unit_height + stage.unit_height * 0.5f; // note we move it a bit down (for aesthetics) if (objects[posY][posX] == Object.PALM_ON_FIRE || objects[posY][posX] == Object.PALM_DARK_ON_FIRE) y = posY * stage.unit_height + stage.unit_height * 0.5f; // note we move it a bit down (for aesthetics) fireContainer.setPosition(posX * stage.unit_width + stage.unit_width * 0.5f, y); // we shift it a bit to the left to account for size. fc.add(fireContainer); // fire.setPosition(0, 0); // System.out.println("adding fire: " + j + " " + i); this.addActor(fireContainer); } private void addFire(double probability) { for (int i = 0; i < stage.size_x; i++) { for (int j = 0; j < stage.size_y; j++) { if (Math.random() < probability && objects[j][i] == null) { createFireAt(i, j); } } } } private void addStumps(double probability) { for (int i = 0; i < stage.size_x; i++) { for (int j = 0; j < stage.size_y; j++) { if (Math.random() < probability && objects[j][i] == null) { objects[j][i] = Object.STUMP; stage.closed[j][i] = true; // add cover BPoint cover_right = new BPoint(i+1, j); cover_right.orientation = Orientation.LEFT; if (inMap(cover_right) && objects[cover_right.pos_y][cover_right.pos_x] == null) cover.add(cover_right); BPoint cover_left = new BPoint(i-1, j); cover_left.orientation = Orientation.RIGHT; if (inMap(cover_left) && objects[cover_left.pos_y][cover_left.pos_x] == null) cover.add(cover_left); BPoint cover_up = new BPoint(i, j+1); if (inMap(cover_up) && objects[cover_up.pos_y][cover_up.pos_x] == null) cover.add(cover_up); cover_up.orientation = Orientation.DOWN; BPoint cover_down = new BPoint(i, j-1); if (inMap(cover_down) && objects[cover_down.pos_y][cover_down.pos_x] == null) cover.add(cover_down); cover_down.orientation = Orientation.UP; } } } } // first draw wall at position, then floor, then private void addSingleWall(int pos_x, int pos_y, int width, Orientation orientation, boolean withLadder) { if (!inMap(new BPoint(pos_x, pos_y))) return; if (addWall(pos_x, pos_y, Object.CASTLE_WALL, orientation, width)) { stage.heights[pos_y][pos_x] = CASTLE_WALL_HEIGHT_DEFAULT; // close random middle row stage.closed[pos_y][pos_x] = true; } int vertFactor = 0; int horFactor = 0; if (orientation == Orientation.UP) vertFactor = -1; else if (orientation == Orientation.DOWN) vertFactor = 1; else if (orientation == Orientation.RIGHT) horFactor = -1; else if (orientation == Orientation.LEFT) horFactor = 1; // add floor behind wall for (int i = 1; i < width; i++) { if (addWall(pos_x + horFactor*i, pos_y + vertFactor*i, Object.CASTLE_WALL_FLOOR, orientation, width)) { stage.heights[pos_y + vertFactor*i][pos_x + horFactor*i] = CASTLE_WALL_HEIGHT_DEFAULT; } if (i == 1) { BPoint coverPoint = new BPoint(pos_x + horFactor, pos_y + vertFactor); coverPoint.orientation = orientation; if (inMap(coverPoint)) cover.add(coverPoint); } } if (withLadder) { this.addLadder(pos_x+horFactor*width, pos_y+vertFactor*width, orientation); } } public void damageWallAt(int pos_x, int pos_y, float damage) { for (Wall wall : walls) { if (wall.pos_x == pos_x && wall.pos_y == pos_y) { wall.hp -= damage; wall.damaged = true; this.wallDamaged = true; boolean floor = false; if (wall.hp <= 0) { if (this.objects[pos_y][pos_x] == Object.CASTLE_WALL_FLOOR) floor = true; this.objects[pos_y][pos_x] = null; // delete entire wall? stage.heights[pos_y][pos_x] = 0; stage.closed[pos_y][pos_x] = false; //delete ladder; if (wall.orientation == Orientation.DOWN || wall.orientation == Orientation.UP) { if (ladderAt(pos_x, pos_y+1)) removeLadderAt(pos_x, pos_y+1); if (ladderAt(pos_x, pos_y-1)) removeLadderAt(pos_x, pos_y-1); } else { if (ladderAt(pos_x+1, pos_y)) removeLadderAt(pos_x+1, pos_y); if (ladderAt(pos_x-1, pos_y)) removeLadderAt(pos_x-1, pos_y); } // injure unit if (stage.units[pos_y][pos_x] != null) { if (!stage.units[pos_y][pos_x].outOfBattle) { stage.units[pos_y][pos_x].isDying = true; stage.units[pos_y][pos_x].kill(); } } checkForNewEntrance(wall); } } } } private void checkForNewEntrance(Wall wall) { // find the appropriate point to add entrance at int entrance_x; int entrance_y; if (wall.orientation == Orientation.DOWN) { entrance_x = wall.pos_x; entrance_y = wallBottom; // make sure no walls left for (int i = 0; i < wall.size; i++) if (objects[entrance_y+i][entrance_x] != null) return; } else if (wall.orientation == Orientation.UP) { entrance_x = wall.pos_x; entrance_y = wallTop; // make sure no walls left for (int i = 0; i < wall.size; i++) if (objects[entrance_y-i][entrance_x] != null) return; } else if (wall.orientation == Orientation.LEFT) { entrance_x = wallLeft; entrance_y = wall.pos_y; // make sure no walls left for (int i = 0; i < wall.size; i++) if (objects[entrance_y][entrance_x+i] != null) return; } else { entrance_x = wallRight; entrance_y = wall.pos_y; // make sure no walls left for (int i = 0; i < wall.size; i++) if (objects[entrance_y][entrance_x-i] != null) return; } // add entrance BPoint entrance = new BPoint(entrance_x, entrance_y); this.entrances.add(entrance); } // We add Ruins to the side of the map where the defenders are private void addRuins() { int min_house_size = 5; int max_house_size = 10; int limit_min = 5; int limit_max = 10; int start_x = Random.getRandomInRange(limit_min, limit_max); int end_x = Random.getRandomInRange(stage.size_x - max_house_size - limit_max, stage.size_x - max_house_size - limit_min); // int start_y = stage.MIN_PLACE_Y_1 + Random.getRandomInRange(-5, 5); int gap = 10; int start_y = 0; int end_y = stage.size_y / 2 - max_house_size; if (stage.playerAttacking()) { start_y = stage.size_y / 2; end_y = stage.size_y - max_house_size - 1; } // int end_y = Random.getRandomInRange(stage.size_y - max_house_size - limit_max, stage.size_y - max_house_size - limit_min); for (int i = start_x; i < end_x; i++) { for (int j = start_y; j < end_y; j++) { if (Math.random() < 0.02) { int size = Random.getRandomInRange(min_house_size, max_house_size); addRuinSquare(i, j, size); j += size; i += Random.getRandomInRange(min_house_size, max_house_size); } } } // Also add some walls addFences(10); } private void addRuinSquare(int bottom_left_x, int bottom_left_y, int size) { addFence(bottom_left_x, bottom_left_y, size, true); addFence(bottom_left_x, bottom_left_y, size, false); addFence(bottom_left_x + size, bottom_left_y, size, true); addFence(bottom_left_x , bottom_left_y + size, size, false); // if (maptype == MapType.SNOW) return; // Don't do it for snow maps (snow covered the ground). // Make floor brown GroundType toUse = GroundType.DARKROCK; // Iterate through the center of the square and set all appropriate ground colors int gap = BLOCK_SIZE / 2; gap = 0; for (int i = bottom_left_x + gap; i < bottom_left_x + size - gap; i += BLOCK_SIZE) { for (int j = bottom_left_y + gap; j < bottom_left_y + size - gap; j += BLOCK_SIZE) { int x = (i + BLOCK_SIZE / 2) / BLOCK_SIZE; int y = (j+ BLOCK_SIZE / 2) / BLOCK_SIZE; if (ground[x][y] != GroundType.WATER) { setGround(x, y, toUse); } } } // ground[(bottom_left_x + size / 2) / BLOCK_SIZE][(bottom_left_y + size / 2)/BLOCK_SIZE] = toUse; // if (size >= BLOCK_SIZE * 2) { // ground[(bottom_left_x + size / 2) / BLOCK_SIZE + 1][(bottom_left_y + size / 2)/BLOCK_SIZE] = toUse; // ground[(bottom_left_x + size / 2) / BLOCK_SIZE][(bottom_left_y + size / 2)/BLOCK_SIZE + 1] = toUse; // ground[(bottom_left_x + size / 2) / BLOCK_SIZE + 1][(bottom_left_y + size / 2)/BLOCK_SIZE + 1] = toUse; // // ground[(bottom_left_x + size / 2) / BLOCK_SIZE - 1][(bottom_left_y + size / 2)/BLOCK_SIZE] = toUse; // ground[(bottom_left_x + size / 2) / BLOCK_SIZE][(bottom_left_y + size / 2)/BLOCK_SIZE + 1] = toUse; // ground[(bottom_left_x + size / 2) / BLOCK_SIZE - 1][(bottom_left_y + size / 2)/BLOCK_SIZE - 1] = toUse; // // ground[(bottom_left_x + size / 2) / BLOCK_SIZE + 1][(bottom_left_y + size / 2)/BLOCK_SIZE - 1] = toUse; // ground[(bottom_left_x + size / 2) / BLOCK_SIZE - 1][(bottom_left_y + size / 2)/BLOCK_SIZE + 1] = toUse; // } } private void addFence(int wall_start_x, int wall_start_y, int wall_length, boolean vertical) { for (int i = 0; i < wall_length; i++) { if (Math.random() < .9) { if (vertical) { if (objects[wall_start_y + i][wall_start_x] == null && !stage.closed[wall_start_y + i][wall_start_x]) { if (!stage.closed[wall_start_x][wall_start_y + i]) objects[wall_start_y + i][wall_start_x] = Object .SMALL_WALL_V; stage.slow[wall_start_y + i][wall_start_x] = WALL_SLOW; // add cover BPoint cover_right = new BPoint(wall_start_x + 1, wall_start_y + i); cover_right.orientation = Orientation.LEFT; if (inMap(cover_right) && objects[cover_right .pos_y][cover_right.pos_x] == null) cover.add(cover_right); BPoint cover_left = new BPoint(wall_start_x - 1, wall_start_y + i); cover_left.orientation = Orientation.RIGHT; if (inMap(cover_left) && objects[cover_left .pos_y][cover_left.pos_x] == null) cover.add(cover_left); } } else if (objects[wall_start_y][wall_start_x + i] == null && !stage.closed[wall_start_y][wall_start_x + i]) { objects[wall_start_y][wall_start_x + i] = Object .SMALL_WALL_H; stage.slow[wall_start_y][wall_start_x + i] = WALL_SLOW; // add cover BPoint cover_up = new BPoint(wall_start_x + i, wall_start_y + 1); if (inMap(cover_up) && objects[cover_up.pos_y][cover_up .pos_x] == null) cover.add(cover_up); cover_up.orientation = Orientation.DOWN; BPoint cover_down = new BPoint(wall_start_x + i, wall_start_y - 1); if (inMap(cover_down) && objects[cover_down .pos_y][cover_down.pos_x] == null) cover.add(cover_down); cover_down.orientation = Orientation.UP; } } } } // TODO use specifically seeded random generator for this and // for ruin generator, so that when you go back to the same ruin or village // It will have the same layout private void addFences(int maxWalls) { int number_walls = (int)(Math.random()*maxWalls + .5); for (int count = 0; count < number_walls; count++) { int wall_length = (int) (10*Math.random()+5); int wall_start_x = (int) ((stage.size_x-wall_length)*Math.random()); int wall_start_y = (int) ((stage.size_y-wall_length)*Math.random()); boolean vertical = true; if (Math.random() < .5) vertical = false; addFence(wall_start_x, wall_start_y, wall_length, vertical); } } // keep in mind that the input is in LAND units, not map units (each has size BLOCK_SIZE) private float getDrawX(float input) { return (input - (SIZE_FACTOR - 1)*stage.size_x/ BLOCK_SIZE /2.0f) *stage.unit_width* BLOCK_SIZE; } private float getDrawY(float input) { return (input - (SIZE_FACTOR - 1)*stage.size_y/ BLOCK_SIZE /2.0f) *stage.unit_height* BLOCK_SIZE; } private float getDrawWidth() { return stage.unit_width* BLOCK_SIZE; } private float getDrawHeight() { return stage.unit_height* BLOCK_SIZE; } // @Override public void actSpecial(float delta) { super.act(delta); } @Override public void draw(SpriteBatch batch, float parentAlpha) { super.draw(batch, parentAlpha); TextureRegion texture; this.toBack(); // System.out.println(ground.length); // System.out.println(stage.size_x); // // draw base layer textures for (int i = 0; i < ground[0].length; i++) { for (int j = 0; j < ground.length; j++) { texture = groundTexture[j][i]; boolean offMap = false; if (i < ground[0].length * this.edge_size_percent - 1 || i >= ground[0].length - ground[0].length * this.edge_size_percent) offMap = true; if (j < ground.length * this.edge_size_percent - 1 || j >= ground.length - ground.length * this.edge_size_percent) offMap = true; Color c = batch.getColor(); groundcolor.set(c); // if (offMap) { groundcolor.a = c.a * 0.6f; batch.setColor(groundcolor); } batch.draw(texture, getDrawX(j), getDrawY(i), getDrawWidth(), getDrawHeight()); if (offMap) { batch.setColor(c); } } } for (FireContainer f : fc) { f.toFront(); f.updateRotation(stage.getMapScreen().getBattleRotation()); } // TODO: make this happen first // create an array of textures of size BLOCK_SIZE. For each one, // add base layer pixmap, then add blended version of neighbor textures as pixmaps. // save and draw // draw obstacles for (int i = 0; i < stage.size_y; i++) { for (int j = 0; j < stage.size_x; j++) { texture = null; boolean flashWhite = false; // Don't draw trees here if (objects[i][j] == Object.SMALL_WALL_V) texture = wallV; else if (objects[i][j] == Object.SMALL_WALL_H) texture = wallH; else if (objects[i][j] == Object.STUMP) texture = stump; else if (objects[i][j] == Object.CASTLE_WALL) { texture = castleWall; if (wallDamaged) { for (Wall wall : walls) { if (wall.pos_x == j && wall.pos_y == i && wall.damaged) { flashWhite = true; wallDamaged = false; wall.damaged = false; } } } } else if (objects[i][j] == Object.CASTLE_WALL_FLOOR) { texture = castleWallFloor; if (wallDamaged) { for (Wall wall : walls) { if (wall.pos_x == j && wall.pos_y == i && wall.damaged) { flashWhite = true; wallDamaged = false; wall.damaged = false; } } } } float stretch = this.sunStretch; float rotation = this.sunRotation; if (texture != null) { // TODO drawShadow(batch, texture, (j * stage.unit_width), (i * stage.unit_height), texture.getRegionWidth() * stage.unit_width / 8, texture.getRegionHeight() * stage.unit_height / 8); batch.draw(texture, (j * stage.unit_width), (i * stage.unit_height), texture.getRegionWidth() * stage.unit_width / 8, texture.getRegionHeight() * stage.unit_height / 8); } if (flashWhite) { Color c = batch.getColor(); groundcolor.set(CLEAR_WHITE); batch.setColor(groundcolor); batch.draw(white, (j * stage.unit_width), (i * stage.unit_height), stage.unit_width, stage.unit_height); batch.setColor(c); } } } // draw ladders for (Ladder l : ladders) { texture = ladder; float rotation = getOrientationRotation(l.orientation); //setKingdomRotation(kingdomRotation); //atch.draw(toDraw, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), getScaleX(),getScaleY(), getKingdomRotation()); float x = l.pos_x * stage.unit_width; float y = l.pos_y * stage.unit_height; float width = texture.getRegionWidth() * stage.unit_width / 8; float height = texture.getRegionHeight() * stage.unit_height / 8; batch.draw(texture, x, y, width / 2, height / 4, width, height, 1, 1, rotation); } if (stage.selectedUnit != null && stage.placementPhase && !stage.isOver()) { stage.selectedUnit.bsp.drawPlacement(batch); } boolean drawPlacementArea = true; if (drawPlacementArea && stage.dragging && !stage.isOver() && stage.placementPhase) { Color c = batch.getColor(); groundcolor.set(PLACEMENT_COLOR); batch.setColor(groundcolor); for (int i = stage.MIN_PLACE_X; i < stage.MAX_PLACE_X; i++) { for (int j = stage.MIN_PLACE_Y_1; j < stage.MAX_PLACE_Y_1; j++) { batch.draw(white, (i * stage.unit_width), (j * stage.unit_height), stage.unit_width, stage.unit_height); } } // for now, only draw enemy's placement area if we can actually place there // TODO make enemy's area visible for certain cases. if (stage.ambush) { for (int i = stage.MIN_PLACE_X; i < stage.MAX_PLACE_X; i++) { for (int j = stage.MIN_PLACE_Y_2; j < stage.MAX_PLACE_Y_2; j++) { batch.draw(white, (i * stage.unit_width), (j * stage.unit_height), stage.unit_width, stage.unit_height); } } } batch.setColor(c); } boolean drawAll = false; // if (stage.selectedUnit != null) drawAll = true; // draw range of selected unit if (!drawAll && stage.currentPanel != null && !stage.dragging && !stage.isOver()) { Unit drawRange = stage.currentPanel; boolean drewRange = drawRange(drawRange, batch); // if (!drewRange) } // Draw Hide radius around friendly unit boolean drawHideRadius = true; if (drawHideRadius && stage.currentPanel != null && !stage.isOver()) { Unit unit = stage.currentPanel; if (unit.isHidden() && unit.bsp.stance == Unit.Stance.DEFENSIVE) { drawHideRadius(unit.bsp, batch); // Also draw LOS radius around enemies. for (BattleSubParty bsp : unit.enemyParty.subparties) { drawLOS(bsp, batch); } } } boolean debugDrawLosSelected = false; // Draw LOS radius around selected BSP if (debugDrawLosSelected && stage.currentPanel != null && !stage.isOver()) { Unit unit = stage.currentPanel; boolean allEnemiesHidden = true; for (BattleSubParty bsp : unit.enemyParty.subparties) { if (bsp.isRevealed()) allEnemiesHidden = false; } if (allEnemiesHidden) drawLOS(unit.bsp, batch); } boolean drawAllLOS = false; if (drawAllLOS) { for (BattleSubParty bsp : stage.enemies.subparties) { drawLOS(bsp, batch); } } // else if (drawAll && stage.currentPanel != null) { // if (stage.currentPanel.team == 0) { // for (Unit drawRange : stage.getAllies()) // drawRange(drawRange, batch); // } // else if (stage.currentPanel.team == 1) { // for (Unit drawRange : stage.getEnemies()) // drawRange(drawRange, batch); // } // } // draw cover boolean drawCover = false; // boolean drawCover = false; if (drawCover) { Color c = batch.getColor(); groundcolor.set(COVER_COLOR); batch.setColor(groundcolor); for (BPoint p : cover) batch.draw(white, (p.pos_x*stage.unit_width), (p.pos_y*stage.unit_height), stage.unit_width, stage.unit_height); batch.setColor(c); } // draw closed boolean drawClosed = false; // boolean drawClosed = true; if (drawClosed) { Color c = batch.getColor(); groundcolor.set(CLOSED_COLOR); batch.setColor(groundcolor); for (int i = 0; i < stage.closed.length; i++) { for (int j = 0; j < stage.closed[0].length; j++) { if (stage.closed[i][j]) batch.draw(white, (j*stage.unit_width), (i*stage.unit_height), stage.unit_width, stage.unit_height); } } batch.setColor(c); } // draw ladders boolean drawLadders = false; // boolean drawClosed = true; if (drawLadders) { Color c = batch.getColor(); Color mycolor = new Color(0, 0, 1, .5f); batch.setColor(mycolor); for (Ladder l : ladders) { batch.draw(white, (l.pos_x*stage.unit_width), (l.pos_y*stage.unit_height), stage.unit_width, stage.unit_height); } batch.setColor(c); } // draw entrances boolean drawEntrances = false; if (drawEntrances) { Color c = batch.getColor(); Color mycolor = new Color(1, 0, 0, .5f); batch.setColor(mycolor); for (BPoint l : entrances) { batch.draw(white, (l.pos_x*stage.unit_width), (l.pos_y*stage.unit_height), stage.unit_width, stage.unit_height); } batch.setColor(c); } // draw area inside walls boolean drawInsideWalls = false; // boolean drawClosed = true; if (drawInsideWalls) { Color c = batch.getColor(); Color mycolor = new Color(1, 0, 1, .2f); batch.setColor(mycolor); for (int i = 0; i < stage.size_y; i++) { for (int j = 0; j < stage.size_x; j++) { if (insideWalls(j, i)) batch.draw(white, (j*stage.unit_width), (i*stage.unit_height), stage.unit_width, stage.unit_height); } } batch.setColor(c); } // draw rain boolean drawRain = true; if (drawRain) { if (stage.isRaining() || stage.isSnowing()) { for (int i = 0; i < raindropsPerFrame; i++) { raindrops[currentRainIndex].pos_x = (int) (Math.random()*stage.size_x); raindrops[currentRainIndex].pos_y = (int) (Math.random()*stage.size_y); // increment current rain index proportionally to the number of drops, otherwise the speed of drops // will be too low. currentRainIndex++; if (currentRainIndex >= raindrops.length) currentRainIndex = 0; } Color c = batch.getColor(); Color mycolor = rainColor; // we can figure out how much to fade drop by calculating distance between its index and currentrainindex, // then divide by array size to get between 0 and 1 yay // eg if index = 20 and currentIndex = 10, diff is (20-10)/40 = 1/4 // eg if index = 20 and currentIndex = 25, diff is 40 + (20 - 25) = // This is nice because it makes the raindrops look "softer" float MAX_ALPHA = .3f; if (stage.isSnowing()) { mycolor = SNOW_COLOR; float speed = 4; rainDrawOffsetX += speed; rainDrawOffsetY += speed; MAX_ALPHA = 1f; // makes snow last longer // if (rainDrawOffsetX >= this.total_width) rainDrawOffsetX = 0; } for (int i = 0; i < raindrops.length; i++) { BPoint p = raindrops[i]; double indexDiff = i - currentRainIndex; if (indexDiff < 0) indexDiff += raindrops.length; mycolor.a = (float) (Math.max(0, (indexDiff / raindrops.length) * MAX_ALPHA)); batch.setColor(mycolor); float drawAtX = (p.pos_x*stage.unit_width + rainDrawOffsetX) % (this.stage.size_x*stage.unit_width); float drawAtY = (p.pos_y*stage.unit_height + rainDrawOffsetY) % (this.stage.size_y*stage.unit_height); batch.draw(white, (drawAtX), (drawAtY),stage.unit_width/2, stage.unit_height/2); } batch.setColor(c); } } //gray out unplayable area super.draw(batch, parentAlpha); } // public boolean isSnowing() { // return stage.isSnowing(); // } // // public boolean isRaining() { // return stage.raining; // } // used to draw trees after units have been drawn public void drawTrees(SpriteBatch batch) { TextureRegion texture; for (int i = 0; i < stage.size_y; i++) { for (int j = 0; j < stage.size_x; j++) { texture = null; if (objects[i][j] == Object.TREE || objects[i][j] == Object.TREE_ON_FIRE || objects[i][j] == Object.DARK_TREE || objects[i][j] == Object.DARK_TREE_ON_FIRE || objects[i][j] == Object.SNOW_TREE || objects[i][j] == Object.SNOW_TREE_ON_FIRE) { // System.out.println("drawing trees"); // TODO add tree shadow texture = treeShadow; } else if (objects[i][j] == Object.PALM || objects[i][j] == Object.PALM_DARK|| objects[i][j] == Object.PALM_ON_FIRE || objects[i][j] == Object.PALM_DARK_ON_FIRE ) { texture = palmShadow; } if (texture != null) drawShadow(batch, texture, ((j-TREE_X_OFFSET)*stage.unit_width), ((i-TREE_Y_OFFSET)*stage.unit_height), TREE_WIDTH*stage.unit_width, TREE_HEIGHT*stage.unit_height); } } // draw actual trees for (int i = 0; i < stage.size_y; i++) { for (int j = 0; j < stage.size_x; j++) { texture = null; if (objects[i][j] == Object.TREE || objects[i][j] == Object.TREE_ON_FIRE) { texture = tree; } else if (objects[i][j] == Object.DARK_TREE || objects[i][j] == Object.DARK_TREE_ON_FIRE) { texture = darkTree; } else if (objects[i][j] == Object.SNOW_TREE || objects[i][j] == Object.SNOW_TREE_ON_FIRE) { texture = snowDarkTree; } else if (objects[i][j] == Object.PALM || objects[i][j] == Object.PALM_ON_FIRE) { texture = palm; } else if (objects[i][j] == Object.PALM_DARK || objects[i][j] == Object.PALM_DARK_ON_FIRE) { texture = palmDark; } if (texture != null) batch.draw(texture, ((j-TREE_X_OFFSET)*stage.unit_width), ((i-TREE_Y_OFFSET)*stage.unit_height), TREE_WIDTH*stage.unit_width, TREE_HEIGHT*stage.unit_height); } } for (FireContainer f : fc) { f.draw(batch, 1); } } public void drawShadow(SpriteBatch batch, TextureRegion texture, float x, float y, float width, float height) { boolean drawShadows = true; if (!drawShadows) { batch.draw(texture, x, y, width, height); return; } float scale = 1; if (texture == palmShadow) scale = 1.2f; Color o = batch.getColor(); batch.setColor(SHADOW_COLOR); batch.draw(texture, x, y + height * 0.3f, width/2, height * 0.2f, width, height, scale, scale * sunStretch, sunRotation); batch.setColor(o); } private StrictArray<BPoint> getAllHidePoints(BattleSubParty bsp) { StrictArray<BPoint> allPoints = new StrictArray<>(); for (Unit unit : bsp.units) { if (unit.team == 1) throw new AssertionError(); if (!unit.inMap()) continue; StrictArray<BPoint> unitPoints = getRadiusPoints(unit, unit.getHideRadius()); for (int i = 0; i < unitPoints.size; i++) { BPoint p = unitPoints.get(i); if (allPoints.contains(p, false)) { // System.out.println("encountered duplicate point in battlemap. good"); continue; // Using .equals comparison here. } allPoints.add(p); } } return allPoints; } private StrictArray<BPoint> getAllLOSPoints(BattleSubParty bsp) { StrictArray<BPoint> allPoints = new StrictArray<>(); for (Unit unit : bsp.units) { if (!unit.inMap()) continue; if (unit.team == 1 && unit.isHidden()) continue; StrictArray<BPoint> unitPoints = getRadiusPoints(unit, unit.getLineOfSight()); for (int i = 0; i < unitPoints.size; i++) { BPoint p = unitPoints.get(i); if (allPoints.contains(p, false)) { // System.out.println("encountered duplicate point in battlemap. good"); continue; // Using .equals comparison here. } allPoints.add(p); } } return allPoints; } private StrictArray<BPoint> getRadiusPoints(Unit unit, int range) { StrictArray<BPoint> points = new StrictArray<>(); int center_x = unit.pos_x; int center_y = unit.pos_y; for (int i = -range + 1; i < range; i++) { for (int j = -range + 1; j < range; j++) { if (i == 0 && j == 0) continue; if (i*i + j*j <= range*range && center_x+i >= 0 && center_y+j >= 0 && center_x+i < stage.size_x && center_y+j < stage.size_y) { BPoint point = new BPoint(center_x + i, center_y + j); points.add(point); } } } return points; } private void drawRadius(Unit drawRange, SpriteBatch batch, boolean diminishing, Color color, int range, boolean quarter) { Color c = batch.getColor(); groundcolor.set(color); float max_alpha = .3f; float base_alpha = .1f; batch.setColor(groundcolor); int center_x = drawRange.pos_x; int center_y = drawRange.pos_y; for (int i = -range + 1; i < range; i++) { for (int j = -range + 1; j < range; j++) { if (i == 0 && j == 0) continue; if (i*i + j*j <= range*range && center_x+i >= 0 && center_y+j >= 0 && center_x+i < stage.size_x && center_y+j < stage.size_y) { if (diminishing) { // calculate distance as fraction of range float alpha_factor = (float) (Math.sqrt(i * i + j * j) / range); groundcolor.a = (1 - alpha_factor) * max_alpha + base_alpha; } batch.setColor(groundcolor); if (quarter) { if (drawRange.orientation == Orientation.UP) if (Math.abs(i) < Math.abs(j) && j > 0) batch.draw(white, (center_x + i) * stage.unit_width, (center_y + j) * stage.unit_height, stage.unit_width, stage.unit_height); if (drawRange.orientation == Orientation.DOWN) if (Math.abs(i) < Math.abs(j) && j < 0) batch.draw(white, (center_x + i) * stage.unit_width, (center_y + j) * stage.unit_height, stage.unit_width, stage.unit_height); if (drawRange.orientation == Orientation.LEFT) if (Math.abs(i) > Math.abs(j) && i < 0) batch.draw(white, (center_x + i) * stage.unit_width, (center_y + j) * stage.unit_height, stage.unit_width, stage.unit_height); if (drawRange.orientation == Orientation.RIGHT) if (Math.abs(i) > Math.abs(j) && i > 0) batch.draw(white, (center_x + i) * stage.unit_width, (center_y + j) * stage.unit_height, stage.unit_width, stage.unit_height); } else { batch.draw(white, (center_x + i) * stage.unit_width, (center_y + j) * stage.unit_height, stage.unit_width, stage.unit_height); } } } } batch.setColor(c); } private void drawHideRadius(BattleSubParty bsp, SpriteBatch batch) { Color c = batch.getColor(); StrictArray<BPoint> points = getAllHidePoints(bsp); batch.setColor(HIDE_COLOR); for (BPoint p : points) { batch.draw(white, p.pos_x * stage.unit_width, p.pos_y * stage.unit_height, stage.unit_width, stage.unit_height); } batch.setColor(c); } private void drawLOS(BattleSubParty bsp, SpriteBatch batch) { Color c = batch.getColor(); StrictArray<BPoint> points = getAllLOSPoints(bsp); batch.setColor(LOS_COLOR); for (BPoint p : points) { batch.draw(white, p.pos_x * stage.unit_width, p.pos_y * stage.unit_height, stage.unit_width, stage.unit_height); } batch.setColor(c); } private boolean drawRange(Unit drawRange, SpriteBatch batch) { if (drawRange.rangedWeaponOut() && !drawRange.isRetreating()) { drawRadius(drawRange, batch, true, RANGE_COLOR, (int) drawRange.getCurrentRange(), true); Color c = batch.getColor(); batch.setColor(Color.BLACK); // draw target if (drawRange.nearestTarget != null) { // System.out.println("drawing nearest target"); batch.draw(white, (drawRange.nearestTarget.getX()), (drawRange.nearestTarget.getY()), stage.unit_width, stage.unit_height); } batch.setColor(c); return true; } return false; } void drawLOS(Unit drawLos, SpriteBatch batch) { drawRadius(drawLos, batch, false, LOS_COLOR, drawLos.getLineOfSight(), false); } void drawHideRadius(Unit unit, SpriteBatch batch) { System.out.println("Drawing hide radius"); drawRadius(unit, batch, false, HIDE_COLOR, unit.getHideRadius(), false); } private boolean addWall(int pos_x, int pos_y, Object object, Orientation orientation, int width) { if (objects[pos_y][pos_x] == null && !stage.closed[pos_y][pos_x]) { objects[pos_y][pos_x] = object; if (object == Object.CASTLE_WALL || object == Object.CASTLE_WALL_FLOOR) { Wall wall = new Wall(); wall.pos_x = pos_x; wall.pos_y = pos_y; wall.hp = object.hp; wall.orientation = orientation; wall.size = width; walls.add(wall); } return true; } return false; } private boolean addObject(int pos_x, int pos_y, Object object) { return addWall(pos_x, pos_y, object, null, 0); } // private Pixmap getTexture(GroundType ground) { // Pixmap texture; // if (ground == GroundType.GRASS) texture = grass; // else if (ground == GroundType.DARKGRASS) texture = darkgrass; // else if (ground == GroundType.LIGHTGRASS) texture = lightgrass; // else if (ground == GroundType.SAND) texture = sand; // else if (ground == GroundType.WATER) texture = water; // else if (ground == GroundType.MUD) texture = mud; // else if (ground == GroundType.ROCK) texture = rock; // else if (ground == GroundType.DARKROCK) texture = darkrock; // else if (ground == GroundType.SNOW) texture = snow; // else if (ground == GroundType.LIGHTSAND) texture = lightsand; // else if (ground == GroundType.LIGHTSNOW) texture = lightsnow; // else if (ground == GroundType.FLOWERS) texture = flowers; // else if (ground == GroundType.FLOWERS2) texture = flowers2; // else if (ground == GroundType.SWAMP) texture = swamp; // else if (ground == GroundType.SWAMP2) texture = swamp2; // else texture = dirt; // // return texture; // } private Pixmap getTexture(GroundType ground) { switch (ground) { case GRASS: return new Pixmap(Gdx.files.internal("ground/grass.png")); case DIRT: return new Pixmap(Gdx.files.internal("ground/dirt.png")); case SAND: return new Pixmap(Gdx.files.internal("ground/sand.png")); case DARKGRASS: return new Pixmap(Gdx.files.internal("ground/darkgrass.png")); case MUD: return new Pixmap(Gdx.files.internal("ground/mud.png")); case WATER: return new Pixmap(Gdx.files.internal("ground/water.png")); case LIGHTGRASS: return new Pixmap(Gdx.files.internal("ground/lightgrass.png")); case FLOWERS: return new Pixmap(Gdx.files.internal("ground/flowers.png")); case FLOWERS2: return new Pixmap(Gdx.files.internal("ground/flowers2.png")); case ROCK: return new Pixmap(Gdx.files.internal("ground/rock.png")); case DARKROCK: return new Pixmap(Gdx.files.internal("ground/darkrock.png")); case SNOW: return new Pixmap(Gdx.files.internal("ground/snow.png")); case LIGHTSNOW: return new Pixmap(Gdx.files.internal("ground/lightsnow.png")); case LIGHTSAND: return new Pixmap(Gdx.files.internal("ground/sandlight.png")); case SWAMP: return new Pixmap(Gdx.files.internal("ground/swamp3.png")); case SWAMP2: return new Pixmap(Gdx.files.internal("ground/swamp2.png")); } return null; } private MapType randomMapType() { int count = MapType.values().length; int index = (int) (Math.random() * count); return MapType.values()[index]; } // close a spot of ground BLOCK_SIZE by BLOCK_SIZE private void closeGround(int y, int x) { for (int k = 0; k < BLOCK_SIZE; k++) { for (int l = 0; l < BLOCK_SIZE; l++) { if (!inMap(new BPoint(x* BLOCK_SIZE + l, y* BLOCK_SIZE + k))) continue; stage.closed[y* BLOCK_SIZE + k][x* BLOCK_SIZE + l] = true; } } } private float getOrientationRotation(Orientation orientation) { if (orientation == Orientation.UP) return 0; if (orientation == Orientation.LEFT) return 90; if (orientation == Orientation.DOWN) return 180; else return 270; } public boolean insideWalls(int pos_x, int pos_y) { if (!stage.hasWall()) return false; if (wallTop > stage.size_y && wallRight > stage.size_x && wallBottom < 0 && wallLeft < 0) return false; if (pos_y <= wallTop && pos_y >= wallBottom) if (pos_x <= wallRight && pos_x >= wallLeft) return true; return false; } // trying it out with double the size public boolean inMap(BPoint p) { if (p == null) return false; return p.pos_x < stage.size_x && p.pos_y < stage.size_y && p.pos_x >= 0 && p.pos_y >= 0; } }
package bean.item.name; public class ItemKeyValueDTO { /* * 설문 사용자의 최적합 알고리즘을 찾기위해 정보를 LIST형태로 도정하여 담아 둘 DTO * vitaA : INDEX 1 : 비타민 A * vitaB : INDEX 2 : 비타민 B * vitaC : INDEX 3 : 비타민 C * vitaD : INDEX 4 : 비타민 D * vitaE : INDEX 5 : 비타민 E * vitaK : INDEX 6 : 비타민 K * omega3 : INDEX 7 : 오메가3 * lutein : INDEX 8 : 루테인 * probiotics : INDEX 9 : 프로바이오틱스 * calcium : INDEX 10 : 칼슘 * collagen : INDEX 11 : 콜라겐 * redGinseng : INDEX 12 : 홍삼 * magnesium : INDEX 13 : 마그네슘 * mineral : INDEX 14 : 미네랄 * zinc : INDEX 15 : 아연 * biotin : INDEX 16 : 비오틴 * milkthistle : INDEX 17 : 밀크씨슬 * iron : INDEX 18 : 철 * Propolis : INDEX 19 : 프로폴리스 * amino : INDEX 20 : 아미노산 * dietryfiber : INDEX 21 : 식이섬유 * gammalinolenic : INDEX 22 : 감마 리놀레산 */ // 기본값을 넣어주기 위한 기본 생성자 public ItemKeyValueDTO() { this.vitaA = 0; this.vitaB = 0; this.vitaC = 0; this.vitaD = 0; this.vitaE = 0; this.vitaK = 0; this.omega3 = 0; this.lutein = 0; this.probiotics = 0; this.calcium = 0; this.collagen = 0; this.redGinseng = 0; this.magnesium = 0; this.mineral = 0; this.zinc = 0; this.biotin = 0; this.milkthistle = 0; this.iron = 0; this.propolis = 0; this.amino = 0; this.dietryfiber = 0; this.gammalinolenic = 0; } private String PRDLST_REPORT_NO; private double vitaA; private double vitaB; private double vitaC; private double vitaD; private double vitaE; private double vitaK; private double omega3; private double lutein; private double probiotics; private double calcium; private double collagen; private double redGinseng; private double magnesium; private double mineral; private double zinc; private double biotin; private double milkthistle; private double iron; private double propolis; private double amino; private double dietryfiber; private double gammalinolenic; public void addVitaA(double vitaA) {this.vitaA = this.vitaA + vitaA;} public void addVitaB(double vitaB) {this.vitaB = this.vitaB + vitaB;} public void addVitaC(double vitaC) {this.vitaC = this.vitaC + vitaC;} public void addVitaD(double vitaD) {this.vitaD = this.vitaD + vitaD;} public void addVitaE(double vitaE) {this.vitaE = this.vitaE + vitaE;} public void addVitaK(double vitaK) {this.vitaK = this.vitaK + vitaK;} public void addOmega3(double omega3) {this.omega3 = this.omega3 + omega3;} public void addLutein(double lutein) {this.lutein = this.lutein + lutein;} public void addProbiotics(double probiotics) {this.probiotics = this.probiotics + probiotics;} public void addCalcium(double calcium) {this.calcium = this.calcium + calcium;} public void addCollagen(double collagen) {this.collagen = this.collagen + collagen;} public void addRedGinseng(double redGinseng) {this.redGinseng = this.redGinseng + redGinseng;} public void addMagnesium(double magnesium) {this.magnesium = this.magnesium + magnesium;} public void addMineral(double mineral) {this.mineral = this.mineral + mineral;} public void addZinc(double zinc) {this.zinc = this.zinc + zinc;} public void addBiotin(double biotin) {this.biotin = this.biotin + biotin;} public void addMilkthistle(double milkthistle) {this.milkthistle = this.milkthistle + milkthistle;} public void addIron(double iron) {this.iron = this.iron + iron;} public void addPropolis(double propolis) {this.propolis = this.propolis + propolis;} public void addAmino(double amino) {this.amino = this.amino + amino;} public void addDietryfiber(double dietryfiber) {this.dietryfiber = this.dietryfiber + dietryfiber;} public void addGammalinolenic(double gammalinolenic) {this.gammalinolenic = this.gammalinolenic + gammalinolenic;} public double getVitaA() { return vitaA; } public void setVitaA(double vitaA) { this.vitaA = vitaA; } public double getVitaB() { return vitaB; } public void setVitaB(double vitaB) { this.vitaB = vitaB; } public double getVitaC() { return vitaC; } public void setVitaC(double vitaC) { this.vitaC = vitaC; } public double getVitaD() { return vitaD; } public void setVitaD(double vitaD) { this.vitaD = vitaD; } public double getVitaE() { return vitaE; } public void setVitaE(double vitaE) { this.vitaE = vitaE; } public double getVitaK() { return vitaK; } public void setVitaK(double vitaK) { this.vitaK = vitaK; } public double getOmega3() { return omega3; } public void setOmega3(double omega3) { this.omega3 = omega3; } public double getLutein() { return lutein; } public void setLutein(double lutein) { this.lutein = lutein; } public double getProbiotics() { return probiotics; } public void setProbiotics(double probiotics) { this.probiotics = probiotics; } public double getCalcium() { return calcium; } public void setCalcium(double calcium) { this.calcium = calcium; } public double getCollagen() { return collagen; } public void setCollagen(double collagen) { this.collagen = collagen; } public double getRedGinseng() { return redGinseng; } public void setRedGinseng(double redGinseng) { this.redGinseng = redGinseng; } public double getMagnesium() { return magnesium; } public void setMagnesium(double magnesium) { this.magnesium = magnesium; } public double getMineral() { return mineral; } public void setMineral(double mineral) { this.mineral = mineral; } public double getZinc() { return zinc; } public void setZinc(double zinc) { this.zinc = zinc; } public double getBiotin() { return biotin; } public void setBiotin(double biotin) { this.biotin = biotin; } public double getMilkthistle() { return milkthistle; } public void setMilkthistle(double milkthistle) { this.milkthistle = milkthistle; } public double getIron() { return iron; } public void setIron(double iron) { this.iron = iron; } public double getPropolis() { return propolis; } public void setPropolis(double propolis) { this.propolis = propolis; } public double getAmino() { return amino; } public void setAmino(double amino) { this.amino = amino; } public double getDietryfiber() { return dietryfiber; } public void setDietryfiber(double dietryfiber) { this.dietryfiber = dietryfiber; } public double getGammalinolenic() { return gammalinolenic; } public void setGammalinolenic(double gammalinolenic) { this.gammalinolenic = gammalinolenic; } public String getPRDLST_REPORT_NO() { return PRDLST_REPORT_NO; } public void setPRDLST_REPORT_NO(String pRDLST_REPORT_NO) { PRDLST_REPORT_NO = pRDLST_REPORT_NO; } }
package com.tencent.mm.plugin.webview.ui.tools.jsapi; import android.os.Bundle; import android.text.TextUtils; import com.tencent.mm.g.a.jt; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.x; class g$26 extends c<jt> { final /* synthetic */ g qiK; g$26(g gVar) { this.qiK = gVar; this.sFo = jt.class.getName().hashCode(); } private boolean a(jt jtVar) { x.i("MicroMsg.MsgHandler", "backgroundAudioListener callback in, state:%s", new Object[]{jtVar.bTE.state}); int i = (int) (jtVar.bTE.duration / 1000); if (jtVar.bTE.bTG) { try { Bundle bundle = new Bundle(); bundle.putString("background_audio_state_player_state", r2); bundle.putInt("background_audio_state_player_duration", i); if (jtVar.bTE.bTy != null) { bundle.putString("background_audio_state_player_src", jtVar.bTE.bTy.rYp); bundle.putString("background_audio_state_player_src_id", jtVar.bTE.bTy.eaZ); } bundle.putInt("background_audio_state_player_err_code", jtVar.bTE.errCode); String str = ""; if (!TextUtils.isEmpty(jtVar.bTE.Yy)) { str = jtVar.bTE.Yy; } bundle.putString("background_audio_state_player_err_msg", str); if (g.D(this.qiK) != null) { x.i("MicroMsg.MsgHandler", "onBackgroundAudioStateChange"); g.D(this.qiK).c(2100, bundle); } else { x.e("MicroMsg.MsgHandler", "backgroundAudioListener callbacker is null"); } return true; } catch (Exception e) { x.e("MicroMsg.MsgHandler", e.getMessage()); return false; } } x.e("MicroMsg.MsgHandler", "is not from QQMusicPlayer, don't callback!"); return false; } }
package com.app.aztask.ui; import org.json.JSONObject; import com.app.aztask.R; import com.app.aztask.data.DeviceInfo; import com.app.aztask.data.Task; import com.app.aztask.net.CreateTaskWorker; import com.app.aztask.util.Util; import android.app.Activity; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; public class CreateTaskActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.create_task_activity); Button submitButton = (Button) findViewById(R.id.submitId); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText taskDesc = (EditText) findViewById(R.id.taskDescId); Spinner taskCategory =(Spinner) findViewById(R.id.categoryId); EditText taskComments = (EditText) findViewById(R.id.commentsId); Task task = new Task(); task.setTaskDesc(taskDesc.getText().toString()); task.setTaskCategories(taskCategory.getSelectedItem().toString()); task.setTaskComments(taskComments.getText().toString()); DeviceInfo deviceInfo = new DeviceInfo(); deviceInfo.setDeviceId(Util.getDeviceId()); Location location=Util.getDeviceLocation(); deviceInfo.setLatitude(""+location.getLatitude()); deviceInfo.setLongitude(""+location.getLongitude()); task.setDeviceInfo(deviceInfo); Log.i("MainActivity", "Task:" + task); try { String response=new CreateTaskWorker().execute(task).get(); JSONObject responseObj = new JSONObject(response); int responseCode=(responseObj.getString("code")!=null && responseObj.getString("code").length()>0) ? Integer.parseInt(responseObj.getString("code")) : 400; if(responseCode==200){ Log.i("Create Task Activity", "Task has been created:"); Toast.makeText(getApplicationContext(),"Task has been created.", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } } catch (Exception e) { e.printStackTrace(); } } }); } }
package com.hua.beautifulimage.ui.adapter; import android.app.Fragment; import android.app.FragmentManager; import android.support.v13.app.FragmentStatePagerAdapter; import android.support.v4.widget.SwipeRefreshLayout; import android.view.View; import com.hua.beautifulimage.ui.fragment.BaseFragment; import java.util.List; import in.srain.cube.views.ptr.PtrFrameLayout; /** * 主页适配器 */ public class PagerAdapter extends FragmentStatePagerAdapter { private List<FragmentModel> mList; public PagerAdapter(FragmentManager fm, List<FragmentModel> list) { super(fm); mList = list; } @Override public Fragment getItem(int position) { return mList.get(position).getFragment(); } @Override public int getCount() { return mList != null ? mList.size() : 0; } @Override public CharSequence getPageTitle(int position) { return mList.get(position).getTitle(); } public boolean checkCanDoRefresh(int position, PtrFrameLayout frame, View content, View header) { return getCurrentFragment(position).checkCanDoRefresh(frame, content, header); } private BaseFragment getCurrentFragment(int position) { return (BaseFragment) getItem(position); } public void update(int position, SwipeRefreshLayout swipe){ getCurrentFragment(position).update(swipe); } public static class FragmentModel { private String title; private BaseFragment fragment; public FragmentModel(String title, BaseFragment fragment) { this.title = title; this.fragment = fragment; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public BaseFragment getFragment() { return fragment; } public void setFragment(BaseFragment fragment) { this.fragment = fragment; } } }
package fr.pederobien.uhc.exceptions; import fr.pederobien.uhc.interfaces.IMessageCode; public class RandomTeamException extends UHCPluginException { private static final long serialVersionUID = 1L; public RandomTeamException(IMessageCode code) { super(code); } }
package com.znamenacek.jakub.spring_boot_security_test.security.authentication; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface UserRepository extends JpaRepository<User, Integer> { public Optional<User> getUserByUsername(String username); }
package Thread; import CalculOptimisation.*; import java.io.IOException; import java.sql.SQLException; public class ThreadOptiGlobale extends Thread { static int tour = 0; /** * Méthode permettant de faire une optimisation automatique globale au bout de 5 minutes écoulées. * @throws SQLException */ static synchronized void optimisationAutomatique() throws SQLException { Optimisation optimisation = Optimisation.getInstance(); try { //sleep(120000); tour++; System.out.println(currentThread().getName() + " effectue une optimisation globale " + tour); optimisation.optimiserConsommationGlobale(); sleep(35000); } catch (SQLException | InterruptedException | IOException e){e.printStackTrace();} } /** * Méthode activée lors du lancement du thread. Elle effectue une optimisation globale toutes les 5 minutes * tant que l'application est ouverte. * @Override */ @Override public void run() { while(true){ try { optimisationAutomatique(); } catch (SQLException e) { e.printStackTrace(); } } } }
package com.mx.profuturo.bolsa.model.recruitment.vo; public class InterviewInfoVO { private String fecha; private String hora; private String candidato; private String vacante; private String lugar; private int idReclutamiento; private int idCandidato; public int getIdReclutamiento() { return idReclutamiento; } public void setIdReclutamiento(int idReclutamiento) { this.idReclutamiento = idReclutamiento; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public String getHora() { return hora; } public void setHora(String hora) { this.hora = hora; } public String getCandidato() { return candidato; } public void setCandidato(String candidato) { this.candidato = candidato; } public String getVacante() { return vacante; } public void setVacante(String vacante) { this.vacante = vacante; } public String getLugar() { return lugar; } public void setLugar(String lugar) { this.lugar = lugar; } public int getIdCandidato() { return idCandidato; } public void setIdCandidato(int idCandidato) { this.idCandidato = idCandidato; } }
package com.spring.di; public class CharacterManager1 { // 클래스 내부에서 다른 객체를 생성 // CharacterManager1클래스는 Wizard , Warrior , Hunter 클래스에 의존한다. // 결합력(의존성)이 강하다. Warrior warrior = new Warrior(); Wizard wizard = new Wizard(); Hunter hunter = new Hunter(); // 데이터 확인용 메서드 void printCharacter1Info() { System.out.println(warrior.getOccupation() +" / " + warrior.getLevel()); } void printCharacter2Info() { System.out.println(wizard.getOccupation() +" / " + wizard.getLevel()); } void printCharacter3Info() { System.out.println(hunter.getOccupation() +" / " + hunter.getLevel()); } }
package boj; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.StringTokenizer; public class BOJ_2252_줄_세우기 { private static int N,M; private static int[] idxCnt; private static List<Integer>[] graph; private static int INF = -1; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; StringBuilder sb = new StringBuilder(); st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); graph = new ArrayList[N+1]; idxCnt = new int[N+1]; for (int i = 1; i < graph.length; i++) { graph[i] = new ArrayList<>(); } for (int i = 0; i < M; i++) { st = new StringTokenizer(br.readLine()); int start = Integer.parseInt(st.nextToken()); int end = Integer.parseInt(st.nextToken()); // 유향 그래프 graph[start].add(end); idxCnt[end]++; } System.out.println(Arrays.toString(graph)); System.out.println(Arrays.toString(idxCnt)); Queue<Integer> queue = new LinkedList<>(); for (int i = 1; i < idxCnt.length; i++) { if(idxCnt[i] == 0) { queue.offer(i); } } if(queue.size() == 0) { System.out.println("사이클 발생"); return; } //Queue<Integer> ans = new LinkedList<>(); int cnt =0; while(!queue.isEmpty()) { int tmp = queue.poll(); for (int i = 0; i < graph[tmp].size(); i++) { int child = graph[tmp].get(i); idxCnt[child]--; if(idxCnt[child] == 0) { queue.offer(child); } } sb.append(tmp).append(" "); cnt++; } if(cnt==N) { System.out.println(sb); }else { return; } } }
package com.tencent.mm.plugin.normsg; import android.os.Build.VERSION; import com.tencent.mm.kernel.api.c; import com.tencent.mm.kernel.b.f; import com.tencent.mm.kernel.b.g; import com.tencent.mm.kernel.e; import com.tencent.mm.modelcdntran.i; import com.tencent.mm.plugin.comm.a.a; import com.tencent.mm.plugin.messenger.foundation.a.n; import com.tencent.mm.plugin.messenger.foundation.a.o; import com.tencent.mm.plugin.normsg.a.b; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.plugin.zero.a.d; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.io.File; import java.util.Map; import java.util.concurrent.TimeUnit; public class PluginNormsg extends f implements c, n, a { private static final String lFF = b.lFB.IO("\u001c:/-9+\n.\"0:41\r\"!"); public void installed() { alias(a.class); } public void dependency() { dependsOn(d.class); dependsOn(com.tencent.mm.plugin.report.c.class); dependsOn(a.class); dependsOn(o.class); } public void configure(g gVar) { b.a(b.lFB); } public void execute(g gVar) { } public void onAccountInitialized(e.c cVar) { com.tencent.mm.plugin.normsg.b.a bjF = com.tencent.mm.plugin.normsg.b.a.bjF(); g DM = com.tencent.mm.kernel.g.Ef().DM(); if (com.tencent.mm.plugin.normsg.b.a.c.isEnabled()) { int bjL = com.tencent.mm.plugin.normsg.b.a.c.bjL(); if (bjL <= 0) { bjL = 26; } if (VERSION.SDK_INT > bjL) { x.w("MircoMsg.AEDHLP", "[tomys] unsupported system, aedh is not enabled."); } else if (com.tencent.mm.plugin.normsg.b.a.lFM.contains(com.tencent.mm.plugin.normsg.b.a.IQ(DM.dox))) { try { com.tencent.mm.plugin.normsg.b.b bjN = com.tencent.mm.plugin.normsg.b.b.bjN(); bjN.initialize(DM.dsQ); bjN.Ff(); bjN.lGs.add(bjF); x.i("MircoMsg.AEDHLP", "[tomys] aed installed."); } catch (Throwable e) { x.printErrStackTrace("MircoMsg.AEDHLP", e, "[tomys] aed install failed.", new Object[0]); bjF.g(e); } } else { x.w("MircoMsg.AEDHLP", "[tomys] not target process, skip installing aed."); } } else { x.w("MircoMsg.AEDHLP", "[tomys] aedh is not enabled."); } ((o) com.tencent.mm.kernel.g.n(o.class)).getSysCmdMsgExtension().a(lFF, this); } public void onAccountRelease() { ((o) com.tencent.mm.kernel.g.n(o.class)).getSysCmdMsgExtension().b(lFF, this); } public void onNewXmlReceived(String str, Map<String, String> map, com.tencent.mm.ab.d.a aVar) { x.i("MicroMsg.PluginNormsg", "xml cmd received, subType: %s", new Object[]{str}); if (lFF.equals(str)) { processUpdateCCEncryptKey(map); } } private void processUpdateCCEncryptKey(Map<String, String> map) { String str = (String) map.get(b.lFB.IO("k5>3,1$b\u0018>+)=/\u000e:6$. %\u00196%s+-4")); if (bi.oW(str)) { x.e("MicroMsg.PluginNormsg", "uccek: cannot get required url."); return; } String bjy = Normsg.a.bjy(); File file = bjy != null ? new File(bjy) : null; if (file == null) { x.e("MicroMsg.PluginNormsg", "uccek: failure to get required path."); h.mEJ.e(876, 0, 1); return; } if (!file.exists()) { File parentFile = file.getParentFile(); if (!(parentFile.exists() || parentFile.mkdirs())) { x.e("MicroMsg.PluginNormsg", "uccek: failure to create required path."); h.mEJ.e(876, 1, 1); return; } } File file2 = new File(bjy + "_@tmp"); if (file2.exists()) { file2.delete(); } else { file2.getParentFile().mkdirs(); } i iVar = new i(); iVar.ceW = false; iVar.dPW = str; iVar.field_fileType = com.tencent.mm.modelcdntran.b.dOw; iVar.field_fullpath = file2.getAbsolutePath(); iVar.field_mediaId = bjy; iVar.allow_mobile_net_download = false; iVar.dQa = true; iVar.is_resume_task = false; iVar.field_autostart = true; iVar.dPX = (int) TimeUnit.MINUTES.toSeconds(1); iVar.dPY = (int) TimeUnit.MINUTES.toSeconds(10); iVar.dPV = new 1(this, file2, file); com.tencent.mm.modelcdntran.g.ND().b(iVar, -1); } }
package com.bierocratie.model.security; /** * Created with IntelliJ IDEA. * User: pir * Date: 15/04/14 * Time: 14:57 * To change this template use File | Settings | File Templates. */ public enum Role { ADMIN, GUEST; }
package com.asiainfo.dubbo.config.api; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.rpc.service.GenericService; import com.asiainfo.dubbo.config.service.GenericServiceImpl; /** * @Description: 使用generic api编程的provider,POJO对象必须实现Serializable * * @author chenzq * @date 2019年4月28日 下午6:38:39 * @version V1.0 * @Copyright: Copyright(c) 2019 jaesonchen.com Inc. All rights reserved. */ public class GenericProvider { public static void main(String[] args) throws Exception { // 遇到虚拟机使用ipv4/ipv6双地址时优先返回ipv4地址 System.setProperty("java.net.preferIPv4Stack", "true"); //System.setProperty("java.net.preferIPv6Addresses", "true"); ServiceConfig<GenericService> service = new ServiceConfig<>(); service.setApplication(new ApplicationConfig("generic-provider")); service.setRegistry(new RegistryConfig("zookeeper://192.168.0.102:2181")); // 弱类型接口名,provider 端不需要真的存在MyGenericService接口类型 service.setInterface("com.asiainfo.dubbo.config.service.MyGenericService"); service.setRef(new GenericServiceImpl()); // 暴露及注册服务 service.export(); System.out.println("generic-provider is running."); System.in.read(); } }
package br.org.funcate.glue.utilities; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; /** * \brief This Class Launch Browser. * * @author Moraes, Emerson Leite * */ public class BrowserLauncher { private static BrowserLauncher _instance; /** <Attribute instance of BrowserLauncher */ /** * This method is a Singleton Implementation of this class */ public static BrowserLauncher getInstance() { if (_instance == null) { _instance = new BrowserLauncher(); } return _instance; } /** * This method opens the default browser with the requested URL * * @param URL */ public void launchBrowser(String URL) { Desktop desktop = null; if (!Desktop.isDesktopSupported()) throw new IllegalStateException("Desktop resources not supported!"); desktop = Desktop.getDesktop(); if (!desktop.isSupported(Desktop.Action.BROWSE)) throw new IllegalStateException("No default browser set!"); URI uri = null; try { uri = new URI(URL); } catch (URISyntaxException e1) { e1.printStackTrace(); } try { desktop.browse(uri); } catch (IOException e) { e.printStackTrace(); } } }
package popcol.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import popcol.service.CustomerService; public class LoginCheck2 implements HandlerInterceptor { @Autowired CustomerService cs = null; public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { } public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { } public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception { HttpSession session; session = request.getSession(); String id = (String) session.getAttribute("id"); if (id != null) { response.sendRedirect("home.do"); return false; } return true; } }
package com.java.app.beans; import java.util.Date; public class InviteUsersDO { private Integer id; private String sFirstName; private String sLastName; private String sEmailId; private char cIsEmailStatus; private StatusDO reg_status; private StatusDO survey_status; private String sCreatedBy; private Date dCreatedDate; private String sUpdatedBy; private Date dUpdatedDate; private char cIsDeleted; private String sKey; public InviteUsersDO() {} public InviteUsersDO(Integer id) { this.id = id; } /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the sEmailId */ public String getsEmailId() { return sEmailId; } /** * @param sEmailId the sEmailId to set */ public void setsEmailId(String sEmailId) { this.sEmailId = sEmailId; } /** * @return the cIsEmailStatus */ public char getcIsEmailStatus() { return cIsEmailStatus; } /** * @param cIsEmailStatus the cIsEmailStatus to set */ public void setcIsEmailStatus(char cIsEmailStatus) { this.cIsEmailStatus = cIsEmailStatus; } /** * @return the reg_status */ public StatusDO getReg_status() { return reg_status; } /** * @param reg_status the reg_status to set */ public void setReg_status(StatusDO reg_status) { this.reg_status = reg_status; } /** * @return the survey_status */ public StatusDO getSurvey_status() { return survey_status; } /** * @param survey_status the survey_status to set */ public void setSurvey_status(StatusDO survey_status) { this.survey_status = survey_status; } /** * @return the sCreatedBy */ public String getsCreatedBy() { return sCreatedBy; } /** * @param sCreatedBy the sCreatedBy to set */ public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy; } /** * @return the dCreatedDate */ public Date getdCreatedDate() { return dCreatedDate; } /** * @param dCreatedDate the dCreatedDate to set */ public void setdCreatedDate(Date dCreatedDate) { this.dCreatedDate = dCreatedDate; } /** * @return the sUpdatedBy */ public String getsUpdatedBy() { return sUpdatedBy; } /** * @param sUpdatedBy the sUpdatedBy to set */ public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy; } /** * @return the dUpdatedDate */ public Date getdUpdatedDate() { return dUpdatedDate; } /** * @param dUpdatedDate the dUpdatedDate to set */ public void setdUpdatedDate(Date dUpdatedDate) { this.dUpdatedDate = dUpdatedDate; } /** * @return the sFirstName */ public String getsFirstName() { return sFirstName; } /** * @param sFirstName the sFirstName to set */ public void setsFirstName(String sFirstName) { this.sFirstName = sFirstName; } /** * @return the sLastName */ public String getsLastName() { return sLastName; } /** * @param sLastName the sLastName to set */ public void setsLastName(String sLastName) { this.sLastName = sLastName; } /** * @return the cIsDeleted */ public char getcIsDeleted() { return cIsDeleted; } /** * @param cIsDeleted the cIsDeleted to set */ public void setcIsDeleted(char cIsDeleted) { this.cIsDeleted = cIsDeleted; } /** * @return the sKey */ public String getsKey() { return sKey; } /** * @param sKey the sKey to set */ public void setsKey(String sKey) { this.sKey = sKey; } }
package com.smxknife.energy.services.enterprise.infras.converter; import com.smxknife.energy.services.enterprise.infras.entity.EnterpriseMeta; import com.smxknife.energy.services.enterprise.spi.domain.Enterprise; import org.mapstruct.Mapper; import org.mapstruct.Mappings; import java.util.List; /** * @author smxknife * 2021/5/19 */ @Mapper(componentModel = "spring") public interface EnterpriseConverter { @Mappings({}) EnterpriseMeta toMeta(Enterprise enterprise); @Mappings({}) List<Enterprise> fromMetas(List<EnterpriseMeta> meta); }