working on it ...

Filters

Explore Public Snippets

Sort by

Found 13k snippets matching: functions

    public by micurs  6866149  356  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  748072  19  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 JMichaelTX  263326  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 sTiLL-iLL  235415  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  188263  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 by lbottaro  3625  1  8  3

    Dalekjs - Define a simple functions file

    This file contains a sample of utility functions you can import in your web automation test file, using dalekjs testing tool. You can specify the argument to pass to the method: here the 'domain' argument is used into the method. More info about dalekjs tool here Site: dalekjs.com
    module.exports = {
    S2CLogout: function (domain, test) {
      console.log('Domain is:', domain);
      test
        .open(domain+'/Access/Logout')
        .done();
    }
    };

    public by marksimon232  4873  7  6  2

    Swift Collections: Function with multiple return values

    I want my function to get the current time and the date formatted as Strings.
    => Objective-C:
    Objective-C doesn’t support a function returning multiple values. The closest you can get would be to create your values add them to a NSDictionary and return the dictionary. 
    
    
    => Swift:
    In Swift, we include the return arrow “->” which specifies that the function will return and a tuple with the types we wish to be returned. A tuple type is simply a comma-separated list of zero or more types, enclosed in parentheses.
        func getCurrentDateAndTime() -> (date: String, time: String) {
            
            let date = NSDate() //Get current date
            
            //Formatter for time
            let formatterTime = NSDateFormatter()
            formatterTime.timeStyle = .ShortStyle //Set style of time
            var timeString = formatterTime.stringFromDate(date) //Convert to String
    
    
            //Formatter for date
            let formatterDate = NSDateFormatter()
            formatterDate.dateStyle = .ShortStyle //Set style of date
            var dateString = formatterDate.stringFromDate(date) //Convert to String
    
            return (dateString, timeString) //Returns a Tuple type
            
        }
        
    To call this method within the same class:
            let time = getCurrentDateAndTime()
            println(time.date)
            println(time.time)
            
    //Results in the getCurrentDateAndTime function being called and the current date & time printed to the console. Notice how simply the values can be accessed from the returned Tuple;

    public by lbottaro  4547  2  8  5

    Functions as first class objects in Python

    Python allows the coder to treat functions as objects, also known as first class objects. Usually a first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. In this case the functional programming paradigm al
    #!/usr/local/bin/python2.7
        
    def add(a, b):
      return a + b
    
    def subtract(a, b):
      return a - b
    
    def multiply(a, b):
      return a * b
    
    def divide(a, b):
      if b:
        return a /b
      else:
        return "Error, divide by zero!"
        
    def power(a, b):
      return a ** b
      
    def modulus(a, b):
      return a % b
    
    functions = [add, subtract, multiply, divide, power, modulus]
    
    for function in functions:
    
      name = function.__name__
      result = function(4.0,5.0)
      print(name + ": " + str(result))

    public by sTiLL-iLL  3707  4  8  18

    map, reduce, flter..... MY WAY

    funky functions that operate iteratively against an array or something similar
    // Map Reduce & Filter fo ya!
    
    function map(func, array) {
    
        var len = array.length;
    
        var result = new Array(len);
    
        for (var i = 0; i < len; i++)
    
            result[i] = func(array[i]);
    
        return result;
    
    }
    
    
    
    function reduce(func, start, array) {
    
        var len = array.length;
    
        for (var i = 0; i < len; i++)
    
            start = func(start, array[i]);
    
        return start;
    
    }
    
    
    
    function filter(test, array) {
    
        var result = [],
    
            len = array.length;
    
        for (var i = 0; i < len; i++) {
    
            var current = array[i];
    
            if (test(current))
    
                result.push(current);
    
        }
    
        return result;
    
    }

    public by marksimon232  9200  1  6  2

    How To Limit WordPress the_content By Words

    With the help of snippet below, you will be able to limit WordPress the_content by words.
    //Add this function to your functions.php file
    
    function get_news($cat_slug, $limit){
     $my_query = new WP_Query('category_name='.$cat_slug.'&posts_per_page='.$limit);
    	$result = "<ul class='news-feed'>";
      	while ($my_query->have_posts()) : $my_query->the_post();
    		$result .= '<li class="news-item"><a href="' . get_permalink() . '" target="_blank">' . get_the_title() . '</a><p>';
    		$result .= apply_filters( 'the_content', wp_trim_words( get_the_content(), 15, '&hellip;' ) ) . ' <a href="' . get_permalink() . '" target="_blank" class="read_more"><strong>read more</strong> &raquo;</a>';
    		$result .= '</li>';
    	endwhile;
      		$result .= '</ul>';
      	return $result;
    }
    
    //Usage:
    // get company news from the 'news' category with limit of 2 posts
    print get_news('news', 2);
    • Public Snippets
    • Channels Snippets