working on it ...

Filters

Explore Public Snippets

Sort by

Found 60k snippets matching: java

    public by micurs modified Mar 4, 2014  6861900  269  9  18

    Typescript: passing a class member function as parameter to another function

    Typescript introduces the class construct and the concept of member functions. However if you try to pass a instance member function as parameter to another function the binding with the instance is lost. To solve this problem you can use the capability of javascript (and Typescript) to support closures on anonymous function (or lambda expressio
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    class SomePeople {
      values : string[] = [ 'John', 'Mary', 'Peter'];
    
      out() {
        _.each( this.values, (v) => process.stdout.write( v + '\n') );
      }
    }
    // This function accept a function it will execute internally
    function outSomething( outFunc : () => any ) {
      outFunc();
    }
    
    var crowd = new SomePeople();
    
    // This won't work since the actual crowd instance binding will be lost
    outSomething( crowd.out );
    
    // This will work: the closure within the lambda expression retain the
    // crowd instance and its data
    outSomething( () => crowd.out() );
        

    public by sTiLL-iLL @ SniPitz-KND modified Dec 1, 2015  531764  2  8  21

    Ajax again?? Wrap it!! XHR Agent 4Ya

    XHR wrapper! object pooling and cueing!!! EveryOneZ dOing IT!
    
    var myXHR = {
           ESpec: function (wrap, evt) {
               return { xhrWrap: wrap, event: evt };
           },
           Agent: function(maxConnect) {
               var bCued = [], slf = this,
                   max = maxConnect || 3;
                   this.curCon = 0;
               function inCue() {
                   if (self.bCued < max) {
                       self.bCued++;
                       var itm = is.Readied.shift();
                       itm.evt.addEventListener(['EVENT_COMPLETE'], 
                         function (e) {
                             self.bCued--;
                             if (this.Readied.length !== 0) {
                               inCue();
                             }
                         });
                       itm.wrap.call(itm, args, itm.evt);
                    }
               }
               this.Readied = function (ESpec) {
                   bCued.push(ESpec);
                   inCue();
                   return ESpec.evt;
               };
            }
       };
    
                

    public by lbottaro modified Mar 24, 2014  405991  1  7  9

    Simple CORBA java server

    This code shows an example of simple corba server in java. A CORBA server needs a local ORB object. The server instantiates an ORB and registers its servant objects so that the ORB can find the server when it receives an invocation for it. the server is a process that instantiates one or more servant objects. Each servant implements the
    // The package containing our stubs.
    import HelloApp.*;
    
    // HelloServer will use the naming service.
    import org.omg.CosNaming.*;
    
    // The package containing special exceptions thrown by the name service.
    import org.omg.CosNaming.NamingContextPackage.*;
    
    // All CORBA applications need these classes.
    import org.omg.CORBA.*;
    
    public class HelloServer 
    {
      public static void main(String args[])
      {
        try{
           // Create and initialize the ORB
          ORB orb = ORB.init(args, null);
          
          // Create the servant and register it with the ORB
          HelloServant helloRef = new HelloServant();
          orb.connect(helloRef);
          
          // Get the root naming context
        org.omg.CORBA.Object objRef = 
    orb.resolve_initial_references("NameService");
          NamingContext ncRef = NamingContextHelper.narrow(objRef);
          
          // Bind the object reference in naming
          NameComponent nc = new NameComponent("Hello", "");
          NameComponent path[] = {nc};
          ncRef.rebind(path, helloRef);
          
          // Wait for invocations from clients
          java.lang.Object sync = new java.lang.Object();
          synchronized(sync){
            sync.wait();
          }
              } catch(Exception e) {
            System.err.println("ERROR: " + e);
            e.printStackTrace(System.out);
          }  
      }
    }
    
    class HelloServant extends _HelloImplBase
    {
      public String sayHello()
      {
        return "\nHello world!!\n";
        }
    }
        

    public by lbottaro modified Mar 31, 2014  355576  0  7  3

    Vendor class - Java example for marshalling/unmarshalling, using JAX-B XmlID annotation

    This is the Vendor class, where the XmlElement annotation sets the vendorID attribute as XmlID. Such key will match the reference set in Card class, using annotation XmlIDREF.
    package com.test.jaxb;
    
    import java.io.Serializable;
    
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlID;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Vendor implements Serializable {
    	
    	 @XmlElement(name = "vendor-ID")
    	 @XmlID
    	private String vendorID;
    	 @XmlElement(name = "vendor-Name")
    	private String vendorName;
    	/**
    	 * @param vendorID
    	 * @param vendorName
    	 */
    	public Vendor(String vendorID, String vendorName) {
    		super();
    		this.vendorID = vendorID;
    		this.vendorName = vendorName;
    	}
    	/**
    	 * 
    	 */
    	public Vendor() {
    		super();
    		// TODO Auto-generated constructor stub
    	}
    	/**
    	 * @return the vendorID
    	 */
    	public String getVendorID() {
    		return vendorID;
    	}
    	/**
    	 * @param vendorID the vendorID to set
    	 */
    	public void setVendorID(String vendorID) {
    		this.vendorID = vendorID;
    	}
    	/**
    	 * @return the vendorName
    	 */
    	public String getVendorName() {
    		return vendorName;
    	}
    	/**
    	 * @param vendorName the vendorName to set
    	 */
    	public void setVendorName(String vendorName) {
    		this.vendorName = vendorName;
    	}
    	/* (non-Javadoc)
    	 * @see java.lang.Object#toString()
    	 */
    	@Override
    	public String toString() {
    		return "Vendor [vendorID=" + vendorID + ", vendorName=" + vendorName
    				+ "]";
    	}
    }
    

    public by lbottaro modified Dec 10, 2014  475569  3  6  2

    JavaScript equivalent to C# String.format

    The code below is the Javascript equivalent to C# String.Format() for replacing elements like {0}, {1}, {2} with parameters. In this case the String prototype is modified, adding the new format() method to all string instances. How to use var mystring = "Hello {0}, how are you? My name is {1}. Bye {0}!" mystring.format("Alice", "Bob") //
    // First, checks if it isn't implemented yet.
    if (!String.prototype.format) {
      String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
            ? args[number]
            : match
          ;
        });
      };
    }            

    public by sTiLL-iLL @ SniPitz-KND modified Dec 15, 2014  443889  2  8  24

    Signals.js... A fast and efficient event system in javascript.

    Signals.js... A fast and efficient event system in javascript.: Signals.js
    // Signalz.js
    
    var Signals = (function () {
    	'use strict';
    	var sigCache = {},
    	addReceiver = function(eventName, func) {
    		return wen(eventName, function(evnt){
    			return func(evnt);
    		});
    	},
    	signalReceived = function(eventName, func) {
    		return wen(eventName, function(evnt){
    			return func(evnt);
    		});
    	},
    	dropReceivers = function (eventName) {
    		if (!eventName) {
    			sigCache = {};
    			return this;
    		}
    		if (sigCache && sigCache[eventName]) {
    			sigCache[eventName] = null;
    		}
    		return this;
    	},    
    	signalOnce = function (eventName, func) {
    		var slf = this;
    		setSingleRV(true);
    		function onit () {
    			dropReceiver(eventName, wen);
    			func.apply(this, arguments);
    		};
    		wen.receiver = onit;	
    		return this;
    	},
    	dropReceiver = function (eventName, func) {
    		if (sigCache && sigCache[eventName]) {
    			var sigLst = sigCache[eventName];	
    			if (isAry(sigLst)) {
    				var idx = -1;
    				for (var i = 0, l = sigLst.length; i < l; i++) {
    					if (sigLst[i] === func || (sigLst[i].receiver && sigLst[i].receiver === func)) {
    						idx = i;
    						break;
    					}
    				}
    				if (idx < 0) {
    					return this;
    				}
    				sigLst.splice(idx, 1);
    				if (!sigLst.length) {
    					delete sigCache[eventName];
    				}
    			} 
    			else if (sigLst === func || (sigLst.receiver && sigLst.receiver === func)) {
    				delete sigCache[eventName];
    			}
    		}
    		return this;
    	},  
    	setSingleRV = function (val) {
    		singleRtnVal = val;
    		return this;
    	},  
    	getSingleRV = function() {
    		if (receivers.hasOwnProperty('singleRtnVal')) {
    			return singleRtnVal;
    		}
    		else {
    			return true;
    		}
    	},	 
    	castSignal = function(eventName, args) {
    		var recvrLst = receiverObjects(eventName),
    		k, recvr, i, rspns;
    		for (k in recvrLst ) {
    			if (recvrLst.hasOwnProperty(k)) {
    				i = recvrLst[k].length;		
    				while (i--) {
    					recvr = recvrLst[k][i];
    					if (recvr.signalOnce === true) {
    						dropReceiver(eventName, recvr);
    					}	
    					rspns = recvr.call(this, args || []);
    					if (rspns === getSingleRV()) {
    						dropReceiver(eventName, recvr);
    					}
    				}
    			}
    		}
    	 	return this;
      	};
    	function isAry(obj) {
    		return (obj.constructor === Array);
    	};
    	function receiverObjects(eventName) {
    		var recvrLst = receivers(eventName), rspns;	
    		if (isAry(recvrLst)) {
    			rspns = {};
    			rspns[eventName] = recvrLst;
    		}	
    		return rspns || recvrLst;
    	};
    	function receivers(eventName) {
    		if (!sigCache) {
    			sigCache = {};
    		}
    		if (!sigCache[eventName]) {
    			sigCache[eventName] = [];
    		}
    		if (!isAry(sigCache[eventName])) {
    			sigCache[eventName] = [sigCache[eventName]];
    		}
    		return sigCache[eventName];
    	};
    	function wen(eventName, func) {
    		if (!sigCache) {
    			sigCache = {};
    		}
    		if (!sigCache[eventName]) {
    			sigCache[eventName] = func;
    		} 
    		else if (isArry(sigCache[eventName])) {
    			sigCache[eventName].push(func);
    		} 
    		else {
    			sigCache[eventName] = [sigCache[eventName], func];
    		}	
    		return;
    	};
    	return {
    		signal: castSignal,
    		signaled: signalReceived,
    		receive: addReceiver,
    		receiveOnce: signalOnce,
    		signaledOnce: signalOnce,
    		dropReceiver: dropReceiver,
    		assignReceiver: addReceiver,
    		receivers: receivers,
    		dropReceivers: dropReceivers
    	};
    }());
    
    exports.Signals = Signals;
    
    
                

    public by zenitramPRO modified May 4, 2016  404073  3  5  1

    Adding an Element in an Array using a Function.

    Arrays of Objects Remember that an object is just another type, like a string or number but more complex. This means that just as we can make arrays of numbers and strings, we can also make arrays of objects. Here we have our Person constructor which should look familiar. We can use this constructor to make an array of Person objects, similar
    // Our person constructor
    function Person (name, age) {
        this.name = name;
        this.age = age;
    }
    
    // Now we can make an array of people
    var family = new Array();
    family[0] = new Person("alice", 40);
    family[1] = new Person("bob", 42);
    family[2] = new Person("michelle", 8);
    // add the last family member, "timmy", who is 6 years old
    family[3] = new Person("timmy", 6);
                                                    

    public by przodownikR1 modified Jul 21, 2015  394476  0  3  0

    example create datasource in javaConfig with full desc and params

    example create datasource in javaConfig with full desc and params: db_config_full.java
    @Bean
      public DataSource dataSource() {
        final DataSource dataSource = new DataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.username"));
        dataSource.setPassword(env.getProperty("jdbc.password"));
        dataSource.setTestOnBorrow(true);
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnReturn(false);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setValidationInterval(30000);
        dataSource.setTimeBetweenEvictionRunsMillis(5000);
        dataSource.setMaxActive(100);
        dataSource.setMinIdle(10);
        dataSource.setMaxWait(10000);
        dataSource.setInitialSize(10);
        dataSource.setRemoveAbandonedTimeout(3600);
        dataSource.setRemoveAbandoned(true);
        dataSource.setLogAbandoned(true);
        dataSource.setMinEvictableIdleTimeMillis(30000);
        return dataSource;
      }
    
    

    public by lbottaro modified Mar 23, 2014  293895  1  6  3

    Simple RMI Java client

    This is a simple RMI client implementation. Here the client program obtains a stub for the registry on the server's host, then looks up the remote object's stub by name in the registry. Finally invokes the sayHello method on the remote object using the stub. Here the client invokes the method exposes by Hello remote interface. Note that if no
    package example.hello;
    
    import java.rmi.registry.LocateRegistry;
    import java.rmi.registry.Registry;
    
    public class Client {
    
        private Client() {}
    
        public static void main(String[] args) {
    
    	String host = (args.length < 1) ? null : args[0];
    	try {
    	    Registry registry = LocateRegistry.getRegistry(host);
    	    Hello stub = (Hello) registry.lookup("Hello");
    	    String response = stub.sayHello();
    	    System.out.println("response: " + response);
    	} catch (Exception e) {
    	    System.err.println("Client exception: " + e.toString());
    	    e.printStackTrace();
    	}
        }
    }    

    public by sTiLL-iLL @ SniPitz-KND modified Nov 10, 2014  377996  6  9  29

    set.js... its my "Set", it runs this code-block

    Full on structure type implimentation of a Set
    
    // Set....   hut-1, hut-2, hike!
    
    function Set() {
       this.dStr = [];
       this.size = size;
       this.unionOf = unionOf;
       this.contains = contains;
       this.subSet = subSet;
       this.getDiff = getDiff;
       this.removeItem = removeItem;
       this.intersection = intersection;
       this.addItem = addItem;
       this.show = show;
    }
    
    function show() {
       return "[" + this.dStr + "]";
    }
    
    function size() {
       return this.dStr.length;
    }
    
    
    
    function addItem(dta) {
       if (this.dStr.indexOf(dta) < 0) {
          this.dStr.push(dta);
          return true;
       } 
       else {
          return false;
       }
    }
    
    function removeItem(dta) {
       var pstn = this.dStr.indexOf(dta);
       if (pstn > -1) {
          this.dStr.splice(pstn, 1);
          return true;
       }
       else {
          return false;
       }
    }
    
    function contains(dta) {
       if (this.dStr.indexOf(dta) > -1) {
          return true;
       }
       else {
          return false;
       }
    }
    
    function unionOf(set) {
       var tmp = new Set(),
           i = 0;
       for (;i < this.dStr.length; ++i) {
          tmp.add(this.dStr[i]);
       }
       i = 0;
       for (;i < set.dStr.length; ++i) {
          if (!tmp.contains(set.dStr[i])) {
             tmp.dStr.push(set.dStr[i]);
          }
       }
       return tmp;
    }
    
    function intersection(set) {
       var tSet = new Set();
       for (var i = 0; i < this.dStr.length; ++i) {
          if (set.contains(this.dStr[i])) {
             tSet.add(this.dStr[i]);
          }
       }
       return tmp;
    }
    
    function subSet(set) {
       if (this.size() > set.size()) {
          return false;
       }
       else {
          for each (var m in this.dStr) {
             if (!set.contains(m)) {
                return false;
             }
          }
       }
       return true;
    }
    i = 0;
    function difference(set) {
       var tmp = new Set();
       for (;i < this.dStor.length; ++i) {
          if (!set.contains(this.dStor[i])) {
             tmp.add(this.dStor[i]);
          }
       }
       return tmp;
    }  
    
    
    
    • Public Snippets
    • Channels Snippets