Java: Get quoted string regex java     
 
                  
                Get quoted string regex java ... Reveal Code
Keep, track and share your code snippets with your friends
 
            | Location: | |
| Website: | |
| Has joined us: | 30th May 2013, 15:10 | 
| Last visit: | 25th June 2013, 01:42 | 
| Profile views: | 476 | 
 
 
Get quoted string regex java ... Reveal Code
              String REGEX = "\"([^\"]*)\"";
                String sentence = "World \"Hello\" World!";
                
                Pattern pattern = Pattern.compile(REGEX);
            Matcher matcher = pattern.matcher(sentence);
                
            if(matcher.find()){
                String result = matcher.group(1);
                System.out.println(result);
            } else {
                        System.out.println("Nothing");
            }
                 
 
Serialization and Deserialization objects on Android ... Reveal Code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import com.AllErrorsJSON;
import com.ErrorJSON;
public class CacheControllerImpl implements CacheController{
        private Context context;
        private final String CACHED_ERRORS_FILE_NAME = "cachedErrors.dat";
        
        public CacheControllerImpl(Context context) {
                this.context = context;
        }
        @Override
        public boolean putErrorsToCache(AllErrorsJSON allErrorsJSON) {
                
                File cacheDir = context.getCacheDir();
                File cachedDataFile = new File(cacheDir.getPath() + "/" + CACHED_ERRORS_FILE_NAME) ;
                FileOutputStream   fos  = null;
        ObjectOutputStream oos  = null;
        boolean            keep = true;
        try {
            fos = new FileOutputStream(cachedDataFile);
            fos.write((new String()).getBytes());
            oos = new ObjectOutputStream(fos);
            oos.writeObject(allErrorsJSON);
        } catch (Exception e) {
            keep = false;
        } finally {
            try {
                if (oos != null)   oos.close();
                if (fos != null)   fos.close();
                if (keep == false) cachedDataFile.delete();
        } catch (Exception e) 
        { /* do nothing */ }
        }
        return keep;
        }
        @Override
        public AllErrorsJSON getErrorsFromCache() {
                AllErrorsJSON allErrorsJSON= null;
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        File cacheDir = context.getCacheDir();
                File cachedDataFile = new File(cacheDir.getPath() + "/" + CACHED_ERRORS_FILE_NAME) ;
        try {
            fis = new FileInputStream(cachedDataFile);
            ois = new ObjectInputStream(fis);
            allErrorsJSON = (AllErrorsJSON) ois.readObject();
        } catch(Exception e) {
            
        } finally {
            try {
                if (fis != null)   fis.close();
                if (ois != null)   ois.close();
            } catch (Exception e) { }
        }
        return allErrorsJSON;  
        }
                 
 
Merge sort ... Reveal Code
***************************************************************** * File: Mergesort.hh * Author: Keith Schwarz () * * An implementation of the Mergesort algorithm. This algorithm * is implemented with a focus on readability and clarity rather * than speed. Ideally, this should give you a better sense * for how Mergesort works, which you can then use as a starting * point for implementing a more optimized version of the algorithm. * * In case you are not familiar with Mergesort, the idea behind the * algorithm is as follows. Given an input list, we wish to sort * the list from lowest to highest. To do so, we split the list * in half, recursively sort each half, and then use a merge algorithm * to combine the two lists back together. As a base case for * the recursion, a list with zero or one elements in it is trivially * sorted. * * The only tricky part of this algorithm is the merge step, which * takes the two sorted halves of the list and combines them together * into a single sorted list. The idea behind this algorithm is * as follows. Given the two lists, we look at the first element of * each, remove the smaller of the two, and place it as the first * element of the overall sorted sequence. We then repeat this * process to find the second element, then the third, etc. For * example, given the lists 1 2 5 8 and 3 4 7 9, the merge * step would work as follows: * * FIRST LIST SECOND LIST OUTPUT * 1 2 5 8 3 4 7 9 * * FIRST LIST SECOND LIST OUTPUT * 2 5 8 3 4 7 9 1 * * FIRST LIST SECOND LIST OUTPUT * 5 8 3 4 7 9 1 2 * * FIRST LIST SECOND LIST OUTPUT * 5 8 4 7 9 1 2 3 * * FIRST LIST SECOND LIST OUTPUT * 5 8 7 9 1 2 3 4 * * FIRST LIST SECOND LIST OUTPUT * 8 7 9 1 2 3 4 5 * * FIRST LIST SECOND LIST OUTPUT * 8 9 1 2 3 4 5 7 * * FIRST LIST SECOND LIST OUTPUT * 9 1 2 3 4 5 7 8 * * FIRST LIST SECOND LIST OUTPUT * 1 2 3 4 5 7 8 9 * * The merge step runs in time O(N), and so using the Master Theorem * Mergesort can be shown to run in O(N lg N), which is asymptotically * optimal for a comparison sort. * * Our implementation sorts elements stored in std::vectors, since * it abstracts away from the complexity of the memory management for * allocating the scratch arrays. */ #ifndef Mergesort_Included #define Mergesort_Included #include #include /** * Function: Mergesort(vector & elems); * Usage: Mergesort(myVector); * --------------------------------------------------- * Applies the Mergesort algorithm to sort an array in * ascending order. */ template void Mergesort(std::vector & elems); /** * Function: Mergesort(vector & elems, Comparator comp); * Usage: Mergesort(myVector, std::greater ()); * --------------------------------------------------- * Applies the Mergesort algorithm to sort an array in * ascending order according to the specified * comparison object. The comparator comp should take * in two objects of type T and return true if the first * argument is strictly less than the second. */ template void Mergesort(std::vector & elems, Comparator comp); /* * * * * Implementation Below This Point * * * * */ /* We store all of the helper functions in this detail namespace to avoid cluttering * the default namespace with implementation details. */ namespace detail { /* Given vectors 'one' and 'two' sorted in ascending order according to comparator * comp, returns the sorted sequence formed by merging the two sequences. */ template std::vector Merge(const std::vector & one, const std::vector & two, Comparator comp) { /* We will maintain two indices into the sorted vectors corresponding to * where the next unchosen element of each list is. Whenever we pick * one of the elements from the list, we'll bump its corresponding index * up by one. */ size_t onePos = 0, twoPos = 0; /* The resulting vector. */ std::vector result; /* For efficiency's sake, reserve space in the result vector to hold all of * the elements in the two vectors. To be truly efficient, we should probably * take in as another parameter an existing vector to write to, but doing so * would complicate this implementation unnecessarily. */ result.reserve(one.size() + two.size()); /* The main loop of this algorithm continuously polls the first and second * list for the next value, putting the smaller of the two into the output * list. This loop stops once one of the lists is completely exhausted * so that we don't try reading off the end of one of the lists. */ while (onePos < one.size() && twoPos < two.size()) { /* If the first element of list one is less than the first element of * list two, put it into the output sequence. */ if (comp(one[onePos], two[twoPos])) { result.push_back(one[onePos]); /* Also bump onePos since we just consumed the element at that * position. */ ++onePos; } /* Otherwise, either the two are equal or the second element is smaller * than the first. In either case, put the first element of the second * sequence into the result. */ else { result.push_back(two[twoPos]); ++twoPos; } } /* At this point, one of the sequences has been exhausted. We should * therefore put whatever is left of the other sequence into the * output sequence. We do this by having two loops which consume the * rest of both sequences, putting the elements into the result. Of these * two loops, only one will execute, although it isn't immediately * obvious from the code itself. */ for (; onePos < one.size(); ++onePos) result.push_back(one[onePos]); for (; twoPos < two.size(); ++twoPos) result.push_back(two[twoPos]); /* We now have merged all of the elements together, so we can safely * return the resulting sequence. */ return result; } } /* Implementation of Mergesort itself. */ template void Mergesort(std::vector & elems, Comparator comp) { /* If the sequence has fewer than two elements, it is trivially in sorted * order and we can return without any more processing. */ if (elems.size() < 2) return; /* Break the list into a left and right sublist. */ std::vector left, right; /* The left half are elements [0, elems.size() / 2). */ for (size_t i = 0; i < elems.size() / 2; ++i) left.push_back(elems[i]); /* The right half are the elements [elems.size() / 2, elems.size()). */ for (size_t i = elems.size() / 2; i < elems.size(); ++i) right.push_back(elems[i]); /* Mergesort each half. */ Mergesort(left, comp); Mergesort(right, comp); /* Merge the two halves together. */ elems = detail::Merge(left, right, comp); } /* The Mergesort implementation that does not require a comparator is implemented * in terms of the Mergesort that does use a comparator by passing in std::less . */ template void Mergesort(std::vector & elems) { Mergesort(elems, std::less ()); } #endif 
 
 
Dijkstra algorithm ... Reveal Code
/**************************************************************************
 * File: Dijkstra.java
 * Author: Keith Schwarz ()
 *
 * An implementation of Dijkstra's single-source shortest path algorithm.
 * The algorithm takes as input a directed graph with non-negative edge
 * costs and a source node, then computes the shortest path from that node
 * to each other node in the graph.
 *
 * The algorithm works by maintaining a priority queue of nodes whose
 * priorities are the lengths of some path from the source node to the
 * node in question.  At each step, the algortihm dequeues a node from
 * this priority queue, records that node as being at the indicated
 * distance from the source, and then updates the priorities of all nodes
 * in the graph by considering all outgoing edges from the recently-
 * dequeued node to those nodes.
 *
 * In the course of this algorithm, the code makes up to |E| calls to
 * decrease-key on the heap (since in the worst case every edge from every
 * node will yield a shorter path to some node than before) and |V| calls
 * to dequeue-min (since each node is removed from the prioritiy queue
 * at most once).  Using a Fibonacci heap, this gives a very good runtime
 * guarantee of O(|E| + |V| lg |V|).
 *
 * This implementation relies on the existence of a FibonacciHeap class, also
 * from the Archive of Interesting Code.  You can find it online at
 *
 *         http://keithschwarz.com/interesting/code/?dir=fibonacci-heap
 */
import java.util.*; // For HashMap
public final class Dijkstra {
    /**
     * Given a directed, weighted graph G and a source node s, produces the
     * distances from s to each other node in the graph.  If any nodes in
     * the graph are unreachable from s, they will be reported at distance
     * +infinity.
     *
     * @param graph The graph upon which to run Dijkstra's algorithm.
     * @param source The source node in the graph.
     * @return A map from nodes in the graph to their distances from the source.
     */
    public static  Map shortestPaths(DirectedGraph graph, T source) {
        /* Create a Fibonacci heap storing the distances of unvisited nodes
         * from the source node.
         */
        FibonacciHeap pq = new FibonacciHeap();
        /* The Fibonacci heap uses an internal representation that hands back
         * Entry objects for every stored element.  This map associates each
         * node in the graph with its corresponding Entry.
         */
        Map> entries = new HashMap>();
        /* Maintain a map from nodes to their distances.  Whenever we expand a
         * node for the first time, we'll put it in here.
         */
        Map result = new HashMap();
        /* Add each node to the Fibonacci heap at distance +infinity since
         * initially all nodes are unreachable.
         */
        for (T node: graph)
            entries.put(node, pq.enqueue(node, Double.POSITIVE_INFINITY));
        /* Update the source so that it's at distance 0.0 from itself; after
         * all, we can get there with a path of length zero!
         */
        pq.decreaseKey(entries.get(source), 0.0);
        /* Keep processing the queue until no nodes remain. */
        while (!pq.isEmpty()) {
            /* Grab the current node.  The algorithm guarantees that we now
             * have the shortest distance to it.
             */
            FibonacciHeap.Entry curr = pq.dequeueMin();
            /* Store this in the result table. */
            result.put(curr.getValue(), curr.getPriority());
            /* Update the priorities of all of its edges. */
            for (Map.Entry arc : graph.edgesFrom(curr.getValue()).entrySet()) {
                /* If we already know the shortest path from the source to
                 * this node, don't add the edge.
                 */
                if (result.containsKey(arc.getKey())) continue;
                /* Compute the cost of the path from the source to this node,
                 * which is the cost of this node plus the cost of this edge.
                 */
                double pathCost = curr.getPriority() + arc.getValue();
                /* If the length of the best-known path from the source to
                 * this node is longer than this potential path cost, update
                 * the cost of the shortest path.
                 */
                FibonacciHeap.Entry dest = entries.get(arc.getKey());
                if (pathCost < dest.getPriority())
                    pq.decreaseKey(dest, pathCost);
            }
        }
        /* Finally, report the distances we've found. */
        return result;
    }
}            
                 
 
This main method shows how get scripts created by Hibernate ... Reveal Code
import org.hibernate.cfg.Configuration; import org.hibernate.dialect.MySQLDialect; import com.globallogic.volokh.beans.Authority; import com.globallogic.volokh.beans.Contact; /** * @author danylo.volokh * * This class is made to get Creation schema script generated by * Hibernate. Need this dependency * ** * */ public class HibernateScriptCreator { public static void main(String[] args) { Configuration cfg = new Configuration(); // add classes that are models and add Dialect depends witch DB are used cfg.addAnnotatedClass(Authority.class); cfg.addAnnotatedClass(Contact.class); String[] lines = cfg.generateSchemaCreationScript(new MySQLDialect()); System.out.println(lines); System.out.println(lines.length); for (int i = 0; i < lines.length; i++) { System.out.println(lines[i] + ";"); } } }org.hibernate.common *hibernate-commons-annotations *4.0.1.Final *
