working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,235 snippets matching: efficient

    public by sTiLL-iLL @ SniPitz-KND modified Dec 15, 2014  443969  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 cghersi modified Jan 10, 2017  2070  10  5  3

    How to write bytes into file in Java

    Efficient way to write strings or bytes onto a file.
      import java.nio.file.Files;
      import java.nio.file.Paths;
    
      public static void writeFile(String path, String content) throws Exception {
    		if (isNullOrEmpty(path) || isNullOrEmpty(content)) {
    			return;
    		}
    		Files.write(Paths.get(path), content.getBytes());
    	}                     

    public by cghersi modified Jan 10, 2017  2286  2  5  0

    Read file in Java

    Efficient way to read file in Java using Files class
      import java.nio.file.Files; 
      import java.nio.file.Paths;
    
      public static String readFile(String path) throws Exception {
    		if (isNullOrEmpty(path)) {
    			return "";
    		}
    		return new String(Files.readAllBytes(Paths.get(path)));
    	}      

    public by marksimon232 modified Jul 2, 2014  4276  7  7  8

    Efficient ModExp for Cryptographic purpose in C

    How to implement an efficient routine to calculate the Modular exponentiation as stated in http://en.wikipedia.org/wiki/Modular_exponentiation.
    Using modular multiplication rules:
    i.e. A^2 mod C = (A * A) mod C = ((A mod C) * (A mod C)) mod C
    We can use this to calculate 7^256 mod 13 quickly
    7^1 mod 13 = 7
    7^2 mod 13 = (7^1 *7^1) mod 13 = (7^1 mod 13 * 7^1 mod 13) mod 13
    We can substitute our previous result for 7^1 mod 13 into this equation.
    7^2 mod 13 = (7 *7) mod 13 = 49 mod 13 = 10
    7^2 mod 13 = 10
    7^4 mod 13 = (7^2 *7^2) mod 13 = (7^2 mod 13 * 7^2 mod 13) mod 13
    We can substitute our previous result for 7^2 mod 13 into this equation.
    7^4 mod 13 = (10 * 10) mod 13 = 100 mod 13 = 9
    7^4 mod 13 = 9
    7^8 mod 13 = (7^4 * 7^4) mod 13 = (7^4 mod 13 * 7^4 mod 13) mod 13
    We can substitute our previous result for 7^4 mod 13 into this equation.
    7^8 mod 13 = (9 * 9) mod 13 = 81 mod 13 = 3
    7^8 mod 13 = 3
    We continue in this manner, substituting previous results into our equations.
    ...after 5 iterations we hit:
    7^256 mod 13 = (7^128 * 7^128) mod 13 = (7^128 mod 13 * 7^128 mod 13) mod 13
    7^256 mod 13 = (3 * 3) mod 13 = 9 mod 13 = 9
    7^256 mod 13 = 9
    This has given us a method to calculate A^B mod C quickly provided that B is a power of 2.
    However, we also need a method for fast modular exponentiation when B is not a power of 
    
    Let say.. How can we calculate A^B mod C quickly for any B ?
    => Step 1: Divide B into powers of 2 by writing it in binary
    Start at the rightmost digit, let k=0 and for each digit:
    
    If the digit is 1, we need a part for 2^k, otherwise we do not
    Add 1 to k, and move left to the next digit
    
    => Step 2: Calculate mod C of the powers of two ≤ B
    5^1 mod 19 = 5
    5^2 mod 19 = (5^1 * 5^1) mod 19 = (5^1 mod 19 * 5^1 mod 19) mod 19
    5^2 mod 19 = (5 * 5) mod 19 = 25 mod 19
    5^2 mod 19 = 6
    5^4 mod 19 = (5^2 * 5^2) mod 19 = (5^2 mod 19 * 5^2 mod 19) mod 19
    5^4 mod 19 = (6 * 6) mod 19 = 36 mod 19
    5^4 mod 19 = 17
    5^8 mod 19 = (5^4 * 5^4) mod 19 = (5^4 mod 19 * 5^4 mod 19) mod 19
    5^8 mod 19 = (17 * 17) mod 19 = 289 mod 19
    5^8 mod 19 = 4
    5^16 mod 19 = (5^8 * 5^8) mod 19 = (5^8 mod 19 * 5^8 mod 19) mod 19
    5^16 mod 19 = (4 * 4) mod 19 = 16 mod 19
    5^16 mod 19 = 16
    5^32 mod 19 = (5^16 * 5^16) mod 19 = (5^16 mod 19 * 5^16 mod 19) mod 19
    5^32 mod 19 = (16 * 16) mod 19 = 256 mod 19
    5^32 mod 19 = 9
    5^64 mod 19 = (5^32 * 5^32) mod 19 = (5^32 mod 19 * 5^32 mod 19) mod 19
    5^64 mod 19 = (9 * 9) mod 19 = 81 mod 19
    5^64 mod 19 = 5
    
    => Step 3: Use modular multiplication properties to combine the calculated mod C values
    5^117 mod 19 = ( 5^1 * 5^4 * 5^16 * 5^32 * 5^64) mod 19
    5^117 mod 19 = ( 5^1 mod 19 * 5^4 mod 19 * 5^16 mod 19 * 5^32 mod 19 * 5^64 mod 19) mod 19
    5^117 mod 19 = ( 5 * 17 * 16 * 9 * 5 ) mod 19
    5^117 mod 19 = 61200 mod 19 = 1
    5^117 mod 19 = 1
    
    Notes:
    More optimization techniques exist, but are outside the scope of this snippet. It should be noted that when we perform modular exponentiation in cryptography, it is not unusual to use exponents for B > 1000 bits.
    

    public by marksimon232 modified Aug 12, 2014  2547  1  6  4

    Most efficient way to perform a FullText Search on SQL MS Azure

    On Azure SQL Database the FullText Search is not enabled, so what is the best way to do a similar search with acceptable performances? Using LIKE operator is not an option for large databases...
    SQL Azure Database does not currently (August 2014) support Full Text Search. Many requiring this functionality have opted to use Lucene.NET instead. There's a useful overview of Lucene.NET plus code samples below:
    
    Lucene.NET Overview and Code Samples: 
    http://leoncullens.nl/post/2012/11/18/Full-Text-Search-on-Azure-with-LuceneNET.aspx
    
    I was able to create a working demo against one of my own SQL Azure tables in about 10 minutes.
    var indexWriter = new IndexWriter(azureDir, new StandardAnalyzer(Version.LUCENE_30), true, IndexWriter.MaxFieldLength.UNLIMITED);

    public by HeathDernovich modified Nov 24, 2014  3520  0  4  1

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

    Signals.js... A fast and efficient event system in javascript.: Signals.js
     // SignalsBest2.js   8;]
        
        var Signals = (function() {
            'use strict';
            var sigCache = {}, singleRtnVal = false, 
            received = function(eventName, func) {
                return wen(eventName, function(evnt) {
                    return func(evnt);
                });
            }, 
            dropReceivers = function(eventName, func) {
                if (eventName && func && typeof func === "function") {
    		    dropReceiver(eventName, func);
    		    return this;
    	        }
                if (!eventName) {
                    sigCache = {};
                    return this;
                }
                if (sigCache && sigCache[eventName]) {
                    sigCache[eventName] = null;
                }
                return this;
            }, 
            setSingleRV = function(val) {
                singleRtnVal = val;
                return this;
            }, 
            getSingleRV = function() {
                if (receivers.hasOwnProperty('singleRtnVal')) {
                    return singleRtnVal;
                } 
                else {
                    return true;
                }
            }, 
            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;
            }, 
            signalOnce = function(eventName, func) {
                var slf = this;
                setSingleRV(true);
                wen.receiver = function onit() {
                    dropReceiver(eventName, this);
                    func.apply(slf, arguments);
                };
                wen(eventName, onit);
                return this;
            }, 
            castSignal = function(eventName, args) {
                var recvrLst = receiverObjects(eventName), 
                k = {}, recvr = [], i = 0, 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 (isAry(sigCache[eventName])) {
                    sigCache[eventName].push(func);
                } 
                else {
                    sigCache[eventName] = [sigCache[eventName], func];
                }
                return this;
            };
            return {
                signal: castSignal,
                signaled: received,
                receive: received,
                receiveOnce: signalOnce,
                receivers: receivers,
                dropReceivers: dropReceivers
            };
        }());
    
    // exports.Signals = Signals;   //<-- for nodejs
    
    
    // use it...
    
    var signals = Signals;
    
    signals.receive("myEvent", function(dta) {
    	console.log(dta);	
    });
    
    signals.signal("myEvent", "data to send in event...");
    
    // note: this will drop just this receiver.
    // If there are no arguments included it drops all the receivers
    
    signals.dropReceivers("myEvent");
    
    // you can also use inheritance to bake the signals functionality into your own objects
    
    function usrID(uId) {
    	var id = uId.toString(),
    	slf = this;
    	this.setId = function(val) {
    		if(id !== val){
    			id = val.toString();
    			slf.signal("change", this);
    		}
    		else {
    			return;	
    		}
    	};
    	
    	this.getId = function() {
    		var x = id;
    		return x;
    	}
    }
    
    usrID.prototype = Signals;
    usrID.constructor = usrID;
    
    // now use it and abuse it!
    
    var oID = new usrID("sytw94pt8");
    
    oID.receive("change", function(dta) {
    	alert("'change' signal data: " + dta);
    });
    
    oID.getId();   //  sytw94pt8
    
    // executing this will trigger the alert box defined in the "receive" callback
    
    oID.setId("000XXX");   //   "000XXX" 
    
    // you can also observe the signals of any/all signalCasters using the static Signals object you inherited from
    // It knows all and receives all signals....  So backing up a bit, we could do something like this...
    
    userID.prototype = Signals;
    userID.constructor = userID;
    
    // now use it and abuse it!
    
    var uID = new userID("sytw94pt8");
    
    uID.receive("change", function(dta) {
    	alert("'change' signal data from uID Object: " + dta);
    });
    
    // AND SOMEWHERE ELSE IN THE CODE AN OBSERVER....   *LoL
    
    Signals.receive("change", function(dta) {
    	alert("I also heard " + dta.target + "'s 'change' signal data: " + dta);
    });
    
    uID.getId();   //  sytw94pt8
    
    // executing this will trigger the BOTH alert boxs defined above
    
    uID.setId("000XXX");   //   "000XXX"
    
    // ENJOY!!!    --sTiLL-iLL--
    
    
    
    
    

    public by sherazam modified May 25, 2016  2326  5  5  0

    How to Convert Large Text Files to PDF inside .NET Applications

    This technical tip shows how to convert a text file to PDF inside .NET applications. We are often asked if we can quickly provide some code which can accomplish this task and save them the effort of going through the documentation. So for the benefit of everyone, we present here a simple example which can be used as it is to easily and efficiently
    // Enter here the actual content of the snippet.            
    //Please take a look over the following code snippet for converting a text file to PDF
    
    //[C# Code Sample]
     
    
    //read the source text file
    System.IO.TextReader tr = new StreamReader("test.txt");
    
    //Instantiate Pdf pbject by calling its empty constructor
    Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();
    
    //Create a new section in the Pdf object
    Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();
    
    //Create a new text paragraph and pass the text to its constructor as argument
    Aspose.Pdf.Generator.Text t2 = new Aspose.Pdf.Generator.Text(tr.ReadToEnd());
    sec1.Paragraphs.Add(t2);
    
    pdf1.Save("test.Pdf");
    
    //[VB.NET Code Sample]
     
    
    Dim tr As System.IO.TextReader = New StreamReader("test.txt")
    
    'Instantiate Pdf pbject by calling its empty constructor
    Dim pdf1 As Aspose.Pdf.Generator.Pdf = New Aspose.Pdf.Generator.Pdf()
    
    'Create a new section in the Pdf object
    Dim sec1 As Aspose.Pdf.Generator.Section = pdf1.Sections.Add()
    
    'Create a new text paragraph and pass the text to its constructor as argument
    Dim t2 As Aspose.Pdf.Generator.Text = New Aspose.Pdf.Generator.Text(tr.ReadToEnd())
    
    sec1.Paragraphs.Add(t2)
    
    pdf1.Save("test.Pdf")
    
    //Converting Large Text files to PDF
    
    //[C# Code Sample]
     
    
    //Instantiate Pdf pbject by calling its empty constructor
    Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();
    //Create a new section in the Pdf object
    Aspose.Pdf.Generator.Section sec1 = pdf1.Sections.Add();
    
    //Specify the location of input text file
    String FILE_NAME = "d:/pdftest/LargeText.txt";
    
    if (File.Exists(FILE_NAME))
       {
           
        System.IO.TextReader objReader =  new System.IO.StreamReader(FILE_NAME);
        // Read the file till the end of the file has come
        do 
        {
         //Create a new text paragraph & pass text to its constructor as argument
         Aspose.Pdf.Generator.Text t2 = new Aspose.Pdf.Generator.Text(objReader.ReadLine());
         // add the text object to paragraphs collection of section
         sec1.Paragraphs.Add(t2);
    
         // Read till the end of file
         }while(objReader.Peek() != -1);
    
       // Close the StreamReader object
       objReader.Close();
       }
       else
       MessageBox.Show("File Does Not Exist");
        
    // Save the PDF file
    pdf1.Save("d:/pdftest/large_textfile.pdf");
    
    //[VB.NET Code Sample]
     
    
    'Instantiate Pdf pbject by calling its empty constructor
    Dim pdf1 As Aspose.Pdf.Generator.Pdf = New Aspose.Pdf.Generator.Pdf()
    
    'Create a new section in the Pdf object
    Dim sec1 As Aspose.Pdf.Generator.Section = pdf1.Sections.Add()
    
    ' Specify the location of input text file
    Dim FILE_NAME As String = "d:/pdftest/LargeText.txt"
    
    If System.IO.File.Exists(FILE_NAME) = True Then
    
        Dim objReader As New System.IO.StreamReader(FILE_NAME)
        ' Read the file till the end of the file has come
        Do While objReader.Peek() <> -1
            'Create a new text paragraph and pass text to its constructor as argument
            Dim t2 As Aspose.Pdf.Generator.Text = New Aspose.Pdf.Generator.Text(objReader.ReadLine())
            ' add the text object to paragraphs collection of section
            sec1.Paragraphs.Add(t2)
        Loop
        ' Close the StreamReader object
        objReader.Close()
    Else
        MsgBox("File Does Not Exist")
    End If
    
    ' Save the PDF file
    pdf1.Save("d:/pdftest/large_textfile.pdf")
    
    

    public by AkivaMeir modified Aug 15, 2013  2226  1  4  0

    AS3 | Compare Dates

    Efficient way to compare two dates. It converts to millisecons and then compares.
    if(ObjectUtils.dateCompare(date1,date2 ) == 1){ }

    public by UdeF modified Mar 8, 2015  823  2  4  -1

    for loop

    a. A more efficient way to code to increment up by 1 is to write i++. b. We decrement down by 1 by writing i--. c. We can increment up by any value by writing i += x, where x is how much we want to increment up by. e.g., i += 3 counts up by 3s. d. We can decrement down by any value by writing i -= x.
    // Example of a for loop:
    
    for (var counter = 1; counter < 11; counter++) {
    	console.log(counter);
    }          

    external by Ben Felder modified Oct 1, 2017  2  0  1  0

    Ordered those from "most Pythonic" to "least Pythonic" and "least efficient" to "most efficient". - the len(set()) solution is idiomatic, - but constructing a set is less efficient memory and speed-wise.

    Ordered those from "most Pythonic" to "least Pythonic" and "least efficient" to "most efficient". - the len(set()) solution is idiomatic, - but constructing a set is less efficient memory and speed-wise.: all_equal.py
    >>> lst = ['a', 'a', 'a']
    
    >>> len(set(lst)) == 1
    True
    
    >>> all(x == lst[0] for x in lst)
    True
    
    >>> lst.count(lst[0]) == len(lst)
    True
    
    
    
    
    • Public Snippets
    • Channels Snippets