working on it ...

Filters

Explore Public Snippets

Sort by

Found 38k snippets matching: @function

    public by micurs  6866048  355  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 micurs  748011  18  7  0

    JQuery typescript interface for $.ajax() callbacks

    To use JQuery $.ajax() you must define your callback functions with the following interfaces
    interface OnSuccessAjaxCallback {
      (data: any, textStatus?: string, jqXHR?: JQueryXHR): any;
    }
    interface OnErrorAjaxCallback {
      (jqXHR?: JQueryXHR, textStatus?: string, errorThrow?: string) : any;
    }
    

    public by lbottaro  463514  0  7  0

    Excel function to calculate the average of positive data in range

    This excel function calculate the average of a specific range of cells, regarding only positive values. Zero or less than zero value won't be used in average calculation. The italian version of this snippet can be used as well on OpenOffice 3.
    =SUMIF(B2:B6;">0")/MAX(COUNTIF(B2:B6;">0");1)
    
    # Italian version
    =SOMMA.SE(B2:B6;">0")/MAX(CONTA.SE(B2:B6;">0");1)

    public by Zenitram.PRO  404444  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 JMichaelTX  351573  2  3  0

    AppleScript Trim Function / Handler Using ASObjC (Shane Stanley)

    AppleScript Trim Function / Handler Using ASObjC (Shane Stanley): trimThis Function AS.applescript
    ###BEGIN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    #    trimThis()      Trim (remove) Characters from Left and/or Right of String
    #
    #    Ver 1.1          2016-02-25
    #    AUTHOR:          Shane Stanley
    #                     (minor revisions by JMichaelTX)
    #    REF:             MacScripter / Trim [Remove Spaces]
    #                     http://macscripter.net/viewtopic.php?pid=182209#p182209
    #  PARAMETERS:
    #    • pstrCharToTrim    : A list of characters to trim, or true to use default
    #    • pstrSourceText    : The text to be trimmed
    #    • pstrTrimDirection : Direction of Trim left, right or any value for full
    ###——————————————————————————————————————————————————————————————————————————————————
    
    on trimThis(pstrSourceText, pstrCharToTrim, pstrTrimDirection)
      
      --- SET CHARACTERS TO TRIM ---
      
      if pstrCharToTrim = missing value or pstrCharToTrim = true then
        -- SPACE, TAB, RETURN, newline characters (U+000A–U+000D, U+0085)
        -- Equiv to: ASCII character 10, return, ASCII character 0
        
        set setToTrim to current application's NSCharacterSet's whitespaceAndNewlineCharacterSet()
      else
        set setToTrim to current application's NSCharacterSet's characterSetWithCharactersInString:pstrCharToTrim
      end if
      
      set anNSString to current application's NSString's stringWithString:pstrSourceText
      
      --- TRIM STRING BASED ON REQUESTED DIRECTION ---
      
      if pstrTrimDirection = left then -- FROM LEFT SIDE OF STRING
        
        set theRange to anNSString's rangeOfCharacterFromSet:(setToTrim's invertedSet())
        if |length| of theRange = 0 then return ""
        set anNSString to anNSString's substringFromIndex:(theRange's location)
        
      else if pstrTrimDirection = right then -- FROM RIGHT SIDE OF STRING
        set theRange to anNSString's rangeOfCharacterFromSet:(setToTrim's invertedSet()) options:(current application's NSBackwardsSearch)
        if |length| of theRange = 0 then return ""
        set anNSString to anNSString's substringToIndex:(theRange's location)
        
      else -- FROM BOTH SIDES OF STRING
        set anNSString to anNSString's stringByTrimmingCharactersInSet:setToTrim
      end if
      
      return anNSString as text
    end trimThis
    ###END~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    

    public by clsw  350050  0  6  1

    Image upload to API, return direct link. (IMGUR)

    Imgur, one of the best image hosts in the world, has a fantastic API, this is a VERY simple and usable implementation of it, just pass an image to the function and it will return the direct link to yout image, heavily commented and easy to use.
    public string UploadImage(Image img)
            {
                //get a dev key from api.imgur.com, anonymous usage (no user auth) only.
                string devkey = "YOUR_CLIENT_ID (e.g. abcde1f234567g8)";
    
                //define the WebClient we'll use to communicate with Imgur.
                WebClient w = new WebClient();
                
                //adds the Header to authorize this application with Imgur, must include a valid CLIENT_ID from 'devkey' above.
                w.Headers.Add("Authorization", "Client-ID " + devkey);
    
                System.Collections.Specialized.NameValueCollection Keys = new System.Collections.Specialized.NameValueCollection();
                try
                {
                    //Converts the image to a byte array so it can be turned into a string for upload.
                    using (MemoryStream stream = new MemoryStream())
                    {
                        img.Save(stream, ImageFormat.Png);
                        Keys.Add("image", Convert.ToBase64String(stream.ToArray()));
                    }
                    
                    //uploads the string-formatted-image and waits for the response.
                    byte[] responseArray = w.UploadValues("https://api.imgur.com/3/image", Keys);
                    dynamic result = Encoding.ASCII.GetString(responseArray);
    
                    //formats the (long and technical) result into just the direct image link.
                    Regex reg = new Regex("link\":\"(.*?)\""); Match match = reg.Match(result);
                    string url = match.ToString().Replace("link\":\"", "").Replace("\"", "").Replace("\\/", "/");
    
                    //returns the online address of the image.
                    return url;
                }
                catch (Exception s) { MessageBox.Show(s.Message); return "err"; }
            }

    public by JMichaelTX  263311  0  3  0

    JXA Functions to Get and Set Keyboard Maestro (KM) Variables using JavaScript for Automation (JXA)

    JXA Functions to Get and Set Keyboard Maestro (KM) Variables using JavaScript for Automation (JXA): Get & Set Functions for KM Variables JXA.js
    //=====================================================================	
    function setKMVar(pstrName, pstrValue) {
    //=====================================================================	
    
    	var app = Application.currentApplication()
    	app.includeStandardAdditions = true
    
    	var appKM = Application("Keyboard Maestro Engine")
    		
    	var oVars = appKM.variables
    		
    	try {
    		oVars[pstrName].name();
    		
    	} catch (e) {
    		appKM.variables.push(appKM.Variable({'name': pstrName	}));
    		
    		app.displayNotification(
    			pstrName, 
    			{
    				withTitle: "Set KM Variable",
    				subtitle:  "Variable was Created",
    				soundName: "Basso"
    		  });
    
    		}	// END try/catch
    		
    		oVars[pstrName].value = pstrValue
    		
    		return
    		
    }	// END function setKMVar
    //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
    
    //=====================================================================	
    function getKMVar(pstrName) {
    //=====================================================================	
    
    	var app = Application.currentApplication()
    	app.includeStandardAdditions = true
    
    	var appKM = Application("Keyboard Maestro Engine")
    		
    	var oVars = appKM.variables
    		
    	try {
    		var strValue = oVars[pstrName].value();
    		
    	} catch (e) {
    		
    		strValue = undefined
    		
    		app.beep()
    		var oAns = app.displayAlert('KM Variable does NOT exist', {
    				message: 'Var Name: ' + pstrName,
    				as: 'critical'
    			})
    
    		}	// END try/catch
    				
    		return strValue
    		
    }	// END function getKMVar
    //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
    
    
    

    public by micurs  267835  11  7  2

    Check if Event was Triggered or Native

    You can easily add extra argument when triggering an event function programmatically in jquery. This way you can recognize if the event was triggered by a real mouse click rather than a direct call to the .click() function. As seen on http://css-tricks.com/snippets/jquery/check-if-event-was-triggered-or-native/
    $('button').click(function(event, wasTriggered) {
        if (wasTriggered) {
            alert('triggered in code');
        } else {
            alert('triggered by mouse');
        }
    });
    
    $('button').trigger('click', true);

    public by sTiLL-iLL  235389  1  7  15

    ES5 Array funKtion polly-fillerz...

    just in case your browser sucks
    
    // filler for Array.prototype.bind()
    
    if (!Function.prototype.bind) {
      Function.prototype.bind = function(that) {
        if (typeof this !== 'function') {
          throw new TypeError('obj is not callable');
        }
        var a_Argz = Array.prototype.slice.call(arguments, 1), noop = function() {},
            bFnky = this, bnd  = function() {
              return bFnky.apply(this instanceof noop && that? this: that,
                     a_Argz.concat(Array.prototype.slice.call(arguments)));
            };
    
        noop.prototype = this.prototype;
        bnd.prototype = new noop();
        return bnd;
      };
    }
    
    // different approach for isArray()...
    
    function isArray (list) {
      
    }
    
    if (!Array.isArray) {
      Array.isArray = function(argz) {
        return Object.prototype.toString.call(argz) === '[object Array]';
      };
    }
    
    function isArray (list) {
      if (Array.isArray) {
        return Array.isArray(list);
      }
    }
    
    function isArray (list) {
      if (Array.isArray) {
        return Array.isArray(list);
      }
      return Object.prototype.toString.call(list) === '[object Array]';
    }
    
    
    var isArray;
    var isArray = (function () {
      
    })();
    
    var isArray = (function () {
      if (Array.isArray) {
        return Array.isArray;
      }
    })();
    
    var isArray = (function () {
      if (Array.isArray) {
        return Array.isArray;
      }
      return function (list) {
        return Object.prototype.toString.call(list) === '[object Array]';
      };
    })();
    
    function (list) {
      return Object.prototype.toString.call(list) === '[object Array]';
    }                        

    public by strykerraven  188253  7  5  1

    WordPress safely defining and executing functions

    Handy safe way to include functions in your WordPress Themes functions.php file. This is even more useful if you are using a child theme and don't want to conflict with functions already defined by the parent theme. Even better; These functions can be executed within the same if(function_exists()) block that defines them creating a neater to manage
    <?php
    
    // Lets get rid of the versioning on static .js and .css files.
    // It looks tacky anyway for static files.
    
    	/**
    	 * Strips Version query strings
    	 * @param type $src
    	 * @return type
    	 */
    	if(!function_exists('remove_css_js_versions')){ // if the function doesnt exist then...
    		function remove_css_js_versions($src){ // define the function
    			return remove_query_arg('ver', $src); // call built-in wordpress function to remove query named "ver" from whatever is passed as $src
    		}
    		add_filter('script_loader_src', 'remove_css_js_versions'); // Pass a hook as $src for js to function listed above named "remove_css_js_versions"
    		add_filter('style_loader_src', 'remove_css_js_versions'); // Pass a hook as $src for css to function listed above named "remove_css_js_versions"
    	} // All scripts and styles will be filtered to have ?ver=1.2.3 stripped from urls. Function defined and executed in same if() statement.
    
      /**
      * Need to debug? Instead of just using print_r($array) you just do preprint_r($array)
      * the array will be output neatly instead of wrapped and messy.
      */
    	if(!function_exists('preprint_r')){
    		function preprint_r($val){
    			echo '<pre>' . PHP_EOL;
    			print_r($val) . PHP_EOL;
    			echo '</pre>' . PHP_EOL;
    		}
    	}
    	
    	/** Remove the WP Icon (Menu) from profile and admin pages. */
    		if(!function_exists('remove_wp_logo')){
      		function remove_wp_logo($wp_admin_bar){
      			$wp_admin_bar->remove_node('wp-logo');
      		}
      		add_action('admin_bar_menu', 'remove_wp_logo', 33);
      	}
      	
    /**
    	 * Wordpress Login Page fixes. By default WordPress shows its logo on your login pages and links to its own site.
    	 * A visitor logging into your site don't need this potential roadblock so lets show WordPress that we mean business!
    	 */
    	# Fix Login Page WordPress URL
    	if(!function_exists('fix_wp_login_img_url')){
    		function fix_wp_login_img_url($url){
    			return get_bloginfo('url');
    		}
    		add_filter('login_headerurl', 'fix_wp_login_img_url');
    	}
    
    	# Fix Login Page WordPress Title (Text displayed on hover defaults to Powered By WordPress)
    	if(!function_exists('fix_wp_login_img_title')){
    		function fix_wp_login_img_title($title){
    			return get_bloginfo('description');
    		}
    		add_filter('login_headertitle', 'fix_wp_login_img_title');
    	}
    
    	/**
    		Change Login Page WordPress Logo, You will need to update path and point to a valid image.
    		WordPress adds this with a CSS background image for your anchor link. It first applys a PNG and then a SVG override if your browser is modern and supports svg
    		In your themes custom stylesheet you can change default Wordpress image by supplying a new background image:
    
    		.login h1 a {
    			background-image: none,url(images/your_image.png);
    		}
    
    		Hint: WordPress uses an 64x64 image but you can adapt size to your need. You might want to use SVG like WordPress did because it will scale best at any resolution.
    
    	 */
    
    	/**
    	 * Simple Actions that use wp_head hook to cleanup WP header Junk/Bloat
    	 * that is included with WordPress by default.
    	 */
    	remove_action('wp_head', 'wp_generator');
    	remove_action('wp_head', 'rsd_link');
    	remove_action('wp_head', 'wlwmanifest_link');
    	remove_action('wp_head', 'wp_shortlink_wp_head');            
    	
    	
    	?>
    • Public Snippets
    • Channels Snippets