working on it ...


Explore Public Snippets

Sort by

Found 13k snippets matching: method

    public by @ Amazon_AWS_Python_API  588309  5  8  -1

    Amazon S3 Aws - S3Connection object from python boto API

    This snippet is about the S3Connection object provided by python boto package for Amazon AWS API. Here the __init__ method is listed with all its variables. The AWSAuthConnection object is initialized and it handles all the data for managing requests and response from Amazon AWS service. Path: [boto/s3/] Learn more about S3Con
    import boto.utils
    from boto.connection import AWSAuthConnection
    class S3Connection(AWSAuthConnection):
        DefaultHost = boto.config.get('s3', 'host', '')
        DefaultCallingFormat = boto.config.get('s3', 'calling_format', 'boto.s3.connection.SubdomainCallingFormat')
        QueryString = 'Signature=%s&Expires=%d&AWSAccessKeyId=%s'
        def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
                     is_secure=True, port=None, proxy=None, proxy_port=None,
                     proxy_user=None, proxy_pass=None,
                     host=DefaultHost, debug=0, https_connection_factory=None,
                     calling_format=DefaultCallingFormat, path='/',
                     provider='aws', bucket_class=Bucket, security_token=None,
                     suppress_consec_slashes=True, anon=False,
            if isinstance(calling_format, str):
            self.calling_format = calling_format
            self.bucket_class = bucket_class
            self.anon = anon
            AWSAuthConnection.__init__(self, host,
                    aws_access_key_id, aws_secret_access_key,
                    is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,
                    debug=debug, https_connection_factory=https_connection_factory,
                    path=path, provider=provider, security_token=security_token,

    public by lbottaro  476354  9  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 cghersi  475324  5  7  0

    C#: Parse a comma separated string into a collection of numeric items

    This method can be used with any separator you need, just setting the 'separator' input
    public static List<long> ParseIntoListOfLongs(string content, char separator = ',')
        List<long> ids = new List<long>();
        if (string.IsNullOrEmpty(content))
            return ids;
        string[] strIds = content.Split(separator);
        foreach (string str in strIds)
            long id = -1;
            if (long.TryParse(str, out id))
                if (id > 0)
        return ids;

    public by cghersi  468738  7  8  2

    Load a SOAP endpoint with Apache CXF using JMS transport provided by Apache ActiveMQ

    This is an example on how to load a SOAP web service in order to be able to invoke its methods via JMS transport
    private JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    public MyInterface loadEndPoint() {
    	//try to load from local, if available:
    	boolean loadOK = false;
    	MyInterface result = null;
    	try {
    		Class<?> c = Class.forName("MyImplClass");
    		Method fact = c.getMethod("get");
    		result = (MyInterface) fact.invoke(null);
    		loadOK = true;
    	} catch (ClassNotFoundException e) {"Cannot find MyImplClass, redirecting to  remote access...", e);		
    	} catch (Exception e) {
    		log.warn("Error searching MyImplClass, , redirecting to remote access. Exception is " + e, e);
    	//load remote endpoint:
    	if (!loadOK) {
    		//detect transport protocol for web services:
    		String brokerAddr = ""; //the right broker address
    		String queueName = "MyQueueName";
    		String address = "jms:jndi:dynamicQueues/" + queueName + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory&jndiConnectionFactoryName=ConnectionFactory&jndiURL=" + brokerAddr;
 "Connecting to " + address);
    		String connString = "tcp://" + brokerAddr + ":61616";
    		ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory("Myusername", "Mypassword", connString);
    		SoapBindingConfiguration conf = new SoapBindingConfiguration();
    		//MTOM not supported! .net does not interoperate with cxf mtom impl.
    //		conf.setMtomEnabled(true);
    		factory.getFeatures().add(new WSAddressingFeature());
    		factory.getFeatures().add(getJMSConfigFeature(queueName, connFactory, 10000)));
    		Object resObj = factory.create();
    		if ((resObj != null) && (resObj instanceof MyInterface))
    			result = (MyInterface) resObj;
    		return result;
    public static JMSConfigFeature getJMSConfigFeature(String queueName, ActiveMQConnectionFactory connectionFactory, Long receiveTimeout) {
    	JMSConfigFeature jmsConfigFeature = new JMSConfigFeature();
    	JMSConfiguration jmsConfig = new JMSConfiguration();
    	if (receiveTimeout != null)
    	return jmsConfigFeature;

    public by lbottaro  406590  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[])
           // Create and initialize the ORB
          ORB orb = ORB.init(args, null);
          // Create the servant and register it with the ORB
          HelloServant helloRef = new HelloServant();
          // Get the root naming context
        org.omg.CORBA.Object objRef = 
          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();
              } catch(Exception e) {
            System.err.println("ERROR: " + e);
    class HelloServant extends _HelloImplBase
      public String sayHello()
        return "\nHello world!!\n";

    public by cghersi  290459  1  6  0

    How to simply compute the MD5 hash of a given string, being sure to have the same results retrieved by HASH method of MS SQL Server

    Returns the MD5 hash of the given string
    public static String computeMD5Hash(String input) {
    	if (isNullOrEmpty(input))
    		return "";
    	byte[] bytesOfMessage = null;
    	try {
    		bytesOfMessage = input.getBytes("UTF-16LE");
    	} catch (UnsupportedEncodingException e) {
    		log.error("Cannot support UTF-8 encoding due to " + e, e);
    		return "";
    	MessageDigest md = null;
    	try {
    		md = MessageDigest.getInstance("MD5");
    	} catch (NoSuchAlgorithmException e) {
    		log.error("Cannot support MD5 algorithm due to " + e, e);
    		return "";
    	byte[] thedigest = md.digest(bytesOfMessage);
    	return printHexByteArray(thedigest);

    public by lbottaro  294427  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());

    public by lbottaro  281568  2  6  3

    Simple RMI Java server

    This code shows a basic RMI server example. A "server" is the class which has a main method that creates an instance of the remote object implementation, exports the remote object and then binds that instance to a name in a RMI registry. Here the server implements the remote interface Hello. The class that contains this main method could be the
    package example.hello;
    import java.rmi.registry.Registry;
    import java.rmi.registry.LocateRegistry;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    public class Server implements Hello {
        public Server() {}
        public String sayHello() {
    	return "Hello, world!";
        public static void main(String args[]) {
    	try {
    	    Server obj = new Server();
    	    Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
    	    // Bind the remote object's stub in the registry
    	    Registry registry = LocateRegistry.getRegistry();
    	    registry.bind("Hello", stub);
    	    System.err.println("Server ready");
    	} catch (Exception e) {
    	    System.err.println("Server exception: " + e.toString());

    public by micheleaiello  263171  0  6  1

    Mark methods as deprecated

    Mark a method (or a whole class) as deprecated. Works in Xcode v4.2 and higher.
    __attribute((deprecated("Use xxx: instead")))
    @interface MyClass : NSObject
      - (void)myOldMethod:(id)param __attribute__((deprecated));
    @interface MyOldClass : NSObject
    void myOldFunction(...) {

    public by zonaro  205458  1  7  0

    Image toBase64 String

    Extension method to convert a System.Drawing.Image to Base64 String
    public static string toBase64(this System.Drawing.Image OriginalImage)
              using (MemoryStream ms = new MemoryStream())
                  OriginalImage.Save(ms, OriginalImage.RawFormat);
                  byte[] imageBytes = ms.ToArray();
                  return Convert.ToBase64String(imageBytes);
    • Public Snippets
    • Channels Snippets