Тэг "Java" (7)
«jQuery Trickshots» by tutorialzine.com ... Показать код
// Loop all .fetchSize links
$('a.fetchSize').each(function(){
// Issue an AJAX HEAD request for each one
var link = this;
$.ajax({
type: 'HEAD',
url: link.href,
complete: function(xhr){
var size = humanize(xhr.getResponseHeader('Content-Length'));
// Append the filesize to each
$(link).append(' (' + type + ')');
}
});
});
function humanize(size){
var units = ['bytes','KB','MB','GB','TB','PB'];
var ord = Math.floor( Math.log(size) / Math.log(1024) );
ord = Math.min( Math.max(0,ord), units.length-1);
var s = Math.round((size / Math.pow(1024,ord))*100)/100;
return s + ' ' + units[ord];
}
// html
// First Trickshot
// This Trickshot
// Ball.png
Java: Get quoted string regex java
Get quoted string regex java ... Показать код
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 ... Показать код
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;
}
jQuery: Get data via Ajax
06.05.2013 03:14 TestUser jQuery
Get some data via Ajax, calling to a php-script and receiving a data. ... Показать код
$.ajax({
url: "ajax.php",
type: "POST",
data: "id=" + id_value + "&mode=" + mode_value,
cache: false,
success: function(data) {
$('#ajax_result').html($.trim(data))
}
});
JavaScript: Texarea remaining characters counter
Texarea remaining characters counter ... Показать код
//event_description_counter - counter text
//event_description - textarea
$(document).ready(function() {
var text_max = 100;
$('#event_description_counter').html(text_max + ' characters remaining');
$('#event_description').keyup(function() {
var text_length = $('#event_description').val().length;
var text_remaining = text_max - text_length;
$('#event_description_counter').html(text_remaining + ' characters remaining');
});
});
JavaScript: Get UNIX timestamp
Get UNIX timestamp via JavaScript. Analogue for PHP's time() function: http://php.net/manual/en/function.time.php ... Показать код
var unix_timestamp = Math.round((new Date()).getTime() / 1000);
jQuery: close popup
скрываем всплывающее окно по клику снаружи. ... Показать код
$("body").click(function(e) {
if($(e.target).closest(".popup").length==0) $(".popup").css("display","none");
});
Добавить текст при копировании контента ... Показать код
function addLink() {
var body_element = document.getElementsByTagName('body')[0];
var selection = window.getSelection();
// Вы можете изменить текст в этой строчке
var pagelink = " Источник: "+document.location.href+"
© snippets.pro
";
var copytext = selection + pagelink;
var newdiv = document.createElement('div');
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
body_element.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout( function() {
body_element.removeChild(newdiv);
}, 0);
}
document.oncopy = addLink;
Dijkstra algorithm ... Показать код
/**************************************************************************
* 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 ... Показать код
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
*
*
* org.hibernate.common
* hibernate-commons-annotations
* 4.0.1.Final
*
*
*/
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] + ";");
}
}
}
Java: md5 hash
Method to get an md5 hash in Java ... Показать код
/**************************************************
* MD5 encoding
**************************************************/
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Method for returning an md5 hash of a string.
*
* @param val
* the string to hash.
*
* @return A hex string representing the md5 hash of the input.
*/
private static String md5(String val) {
String result = null;
if ((val != null) && (val.length() > 0)) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(val.getBytes(), 0, val.length());
result = String.format("%032X", new BigInteger(1, md5.digest()));
} catch (NoSuchAlgorithmException nsae) {
result = val.substring(0, 32);
}
}
return result;
}
jQuery: Keyboard shortcut
Using the keyboard shortcut to increase the value in the input field ... Показать код
var isShift = false;
$('input[type="text"]').keyup( function(e){
if (e.which == 16 ) isShift = false;
}).keydown( function(e) {
$(this).attr('autocomplete',"off");
// Shift key
if(e.which == 16) isShift = true;
var v = (isShift == true) ? 10 : 1;
// Arrow up code
if (e.keyCode == 38)
$(this).val( parseInt( $(this).val() ) + v );
// Arrow down code
if (e.keyCode == 40)
$(this).val( parseInt( $(this).val() ) - v );
});
JavaScript: Send a POST request
Send a POST request in the same way as it does form's submit. Was found here: http://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit ... Показать код
jQuery: Scroll to top
Scroll the page to its top ... Показать код
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "fast");
return false;
});
Tracking the Facebook comments: creating and removing. You can use it to count the FB comments in the local database. ... Показать код
JavaScript: Email validation
Validation of the entered email using regex ... Показать код
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
jQuery: Fade in then fade out
Fade in the hidden element, wait a little bit, then fade out id. Simple but useful. ... Показать код
$("#error_box").fadeIn(500).delay(3000).fadeOut(500);