working on it ...

Filters

Explore Public Snippets

Sort by

Found 712 snippets matching: hooks

    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 cghersi  2039  0  6  0

    IntelliJ plugins development: how to implement an action

    Desperately simple!! Just extend AnAction class and implement the actionPerformed method! Moreover, you want to add the existence of this action in your plugin.xml, in the "actions" section:
    public class AboutAction extends AnAction {
    
        private static Logger log = Logger.getLogger(AboutAction.class);
    
        // If you register the action from Java code, this constructor is used to set the menu item name
        // (optionally, you can specify the menu description and an icon to display next to the menu item).
        // You can omit this constructor when registering the action in the plugin.xml file.
        public AboutAction() {
            // Set the menu item name.
            super("About");
            log.debug("about action");
            // Set the menu item name, description and icon.
            // super("Text _Boxes","Item description",IconLoader.getIcon("/Mypackage/icon.png"));
        }
    
        public void actionPerformed(AnActionEvent event) {
            //Create and set up the window.
            AboutView dialog = new AboutView();
            dialog.setVisible(true);
        }
    }

    external by Alexey Kulakov  217  0  3  0

    Supercharge your git hooks with gulp — Introducing git-guppy

    Supercharge your git hooks with gulp — Introducing git-guppy: using-git-guppy.md
    # Supercharge your git hooks with gulp
    
    
    ### Introducing [git-guppy](https://github.com/therealklanni/git-guppy)
    
    Automate your developer workflow with git-guppy. git-guppy allows you to add git-hooks to your project repository that are automatically installed when users clone and install your repository, so you won't have to worry about developers skipping essential workflow steps and bypassing your project guidelines.
    
    ## Getting Started
    
    So let's use a unit test scenario to illustrate an example. We're going to run unit tests before every commit (pre-commit hook) and reject the commit if the tests fail (giving the developer a chance to fix their tests before committing broken code).
    
    Let's assume we already have a gulp task called "unit" that does what we need.
    
    So to turn this into a pre-commit hook we first need to add the guppy dependencies to package.json:
    
    ```
    npm install --save-dev guppy-pre-commit
    ```
    
    This `guppy-pre-commit` is just a special package that installs the pre-commit hook itself into `.git/hooks` for us.
    
    Now, in gulpfile.js we add the following line:
    
    ```js
    gulp.task('pre-commit', ['unit']);
    ```
    
    **Yep, that's it. You're done.**
    
    The best part is, any time your project is cloned guppy's special pre-commit hook is automatically installed. Then any time a commit is initiated, your "unit" gulp task will run. If "unit" fails, git's pre-commit condition will fail, thus aborting the commit to allow the developer to fix the broken test.
    
    ### Oh, it gets better
    
    Let's have a look at a more complex scenario. This time we'll lint any files that were staged for commit. 
    
    This scenario is more complex, because you could of course just lint *everything* as a pre-commit condition. But that just seems like overkill to me—maybe there are some files that will certainly fail a lint because the code is incomplete but it's not what's being committed, so it's not a concern. We can do better.
    
    This is where using git hooks for things like this begins to get interesting. Because we know we're about to make a commit, we know that there must be specific files being committed. Because there are specific files being committed, we can lint *just these* as our pre-commit condition.
    
    So let's take a look. We're going to need another dependency. This time, git-guppy itself:
    
    ```sh
    npm install --save-dev git-guppy
    ```
    
    Then we need to add a new line to our gulpfile.js:
    
    ```js
    var guppy = require('git-guppy')(gulp);
    ```
    
    Now we can write our new lint git hook in gulpfile.js:
    
    ```js
    gulp.task('pre-commit', guppy.src('pre-commit', function (files) {
      return gulp.src(files)
        .pipe(gulpFilter(['*.js']))
        .pipe(jshint())
        .pipe(jshint.reporter(stylish))
        .pipe(jshint.reporter('fail'));
    });    
    ```
    
    By calling guppy's `.src()` method here and passing in the name of the git hook along with the usual gulp callback function, guppy will pass an array of the file names you staged for this commit to the gulp callback's first argument. You can then use the file name array for gulp's `.src()` method to construct your lint orchestration, as you normally would with gulp.
    
    You could also express this hook like the following, if you want to skip having to call `gulp.src()` directly:
    
    ```js
    gulp.task('pre-commit', function () {
      return guppy.src('pre-commit')
        .pipe(gulpFilter(['*.js']))
        .pipe(jshint())
        .pipe(jshint.reporter(stylish))
        .pipe(jshint.reporter('fail'));
    });    
    ```
    
    Both approaches will produce the same result, but in some cases the former may be more useful, such as in a scenario when you want to use the file list more than once.
    
    > Refer to the git-guppy docs for information on which method should be used for certain git hooks.
    
    Hang on, though. If we just use the file names to determine what to lint, what happens if a file was staged for commit *before* another change was made to it?
    
    If you've ever staged a file and then made additional changes to it between then and the time you actually commit it *without* adding the additional changes to the commit, you'll know that this can be problematic.
    
    The problem here is that when you stage a file, git lets you make additional changes to the "working copy" without affecting what you staged for commit. In other words, you could stage a file while it's in a state that would **fail lint**, then update the file so it would **pass lint** and end up committing the **failing** version of the file.
    
    Well, we can't just lint the "working copy" then. We could be inadvertently allowing code smells to be committed. Now what?
    
    For that, guppy has a `.stream()` method. Pre-commit is one of the hooks supported by this method, which will let us stream the *staged* version of the file(s) to our linter.
    
    Here's how:
    
    ```js
    gulp.task('pre-commit', function () {
      return gulp.stream('pre-commit')
        .pipe(gulpFilter(['*.js']))
        .pipe(jshint())
        .pipe(jshint.reporter(stylish))
        .pipe(jshint.reporter('fail'));
    });    
    ```
    
    Now the lint pre-commit hook will only lint **exactly what is getting committed**.
    
    Let's see `gulp.watch()` do that!
    
    ### In conclusion
    
    
    One of the biggest problems with git hooks is that it's a chore to maintain them in a collaborative scenario. It requires manual install steps and let's face it, developers are lazy (that's why we automate anything we can). You don't want to have to maintain a separate set of tools for your workflow, either. So, use the ones you have!
    
    With guppy we can create dead simple git hooks that follow your project—without adding any unnecessary baggage—and we also saw how guppy can handle more complex workflows like linting *only what's relevant* in a pre-commit condition. 
    
    These were just a couple of examples of what you can do with git hooks powered by guppy and gulp. I'd love to see what you come up with for your workflows.
    
    Check out [git-guppy](https://github.com/therealklanni/git-guppy) on GitHub and tweet me at [@therealklanni](https://twitter.com/therealklanni) with how you're using guppy!
    
    
    

    external by spotzero  206  0  2  0

    Connector module, gives hooks a chance patch

    Connector module, gives hooks a chance patch: connector-gives_hooks_a_change.patch
    diff --git a/connector.module b/connector.module
    index 4e20102..da7d430 100644
    --- a/connector.module
    +++ b/connector.module
    @@ -427,6 +427,7 @@ function _connector_log_in($connector_name, $cid = NULL, $consumer = NULL, $acce
             else {
              //Log in user
               $form_state['uid'] = $account->uid;
    +          $form_state['connector access token'] = $access_token;
               user_login_submit(array(), $form_state);
               return TRUE;
             }
    
    
    

    external by Github  528  0  3  0

    Creating throw away actors to perform computations, on completion, they commit suicide using PoisonPil. Shutdown hooks are triggered, and verify that they are GC'd by adding extra code to the finalization hooks. I used scala.concurrent's blocking meth...

    Creating throw away actors to perform computations, on completion, they commit suicide using PoisonPil. Shutdown hooks are triggered, and verify that they are GC'd by adding extra code to the finalization hooks. I used scala.concurrent's blocking method for good measure. The thread pool (used by these blocking op's) is constrained to 2 threads.:
    package com.picsolve
    
    import akka.actor.{PoisonPill, Props, Actor, ActorSystem}
    import java.util.concurrent.atomic.AtomicInteger
    import java.util.concurrent.{ThreadFactory, Executors}
    import akka.dispatch.ExecutionContexts
    import scala.concurrent.Future
    import scala.util.{Failure, Success}
    
    object RetryingActorsMain extends App {
      val yourExecutorServiceGoesHere = Executors.newFixedThreadPool(2, new ThreadFactory {
        override def newThread(r: Runnable): Thread = {
          val thread: Thread = new Thread(r)
          thread.setDaemon(true)
          thread
        }
      })
    
      val blockingOpsExecutionContext = ExecutionContexts.fromExecutorService(yourExecutorServiceGoesHere)
    
    
      object MultiTry {
    
    
        private[MultiTry] val countdown = new AtomicInteger(0)
    
        def attempt(s: String) = {
    
          Future {
            concurrent.blocking{
            Thread.sleep(1000)
            if (countdown.getAndIncrement % 3 == 0) {
              //Every third works..
              println("success")
            } else
              throw new UnsupportedOperationException("couldn't connect to server")
            }
          }(blockingOpsExecutionContext)
    
        }
      }
    
      implicit val as = ActorSystem("foo")
    
    
      case class TryingMessage(name: String)
    
      case class Trying(msg: TryingMessage, count: Int = 0)
    
      class TryingActor extends Actor {
    
        println(s"creating new ${this.getClass}")
    
        val TRIES = 4
        var attempts = 0
    
    
        override def finalize(): Unit = {
          println("time to finalize!")
          super.finalize()
        }
    
        override def preStart(): Unit = {
          println(self)
          super.preStart()
        }
    
    
    
        override def postStop(): Unit = {
        println(s"stopped : $self ")
    
          super.postStop()
        }
    
        override def receive = {
    
          case msg@TryingMessage(name) =>
            MultiTry.attempt(name).onComplete {
              case Success(_) =>
                println("sucesss")
                self ! PoisonPill
              case Failure(t) =>
                println(s"failed attempt $attempts")
                attempts += 1
                self ! Trying(msg, TRIES)
            }(blockingOpsExecutionContext)
    
          case Trying(msg, count) if count > 0 =>
            MultiTry.attempt(msg.name).onComplete {
              case Success(_) =>
                println("sucesss")
                self ! PoisonPill
              case Failure(t) =>
                println(s"failed attempt $attempts")
                attempts += 1
                self ! Trying(msg, count - 1)
            }(blockingOpsExecutionContext)
    
    
          case Trying(msg, count) if count <= 0 =>
            println("final failure, not retrying again!")
            self ! PoisonPill
        }
      }
    
      for {i <- 1 to 10} {
        as.actorOf(Props[TryingActor]()) ! TryingMessage(s"actor $i")
      }
    
    
      Thread.sleep(20000)
      println("RUNNING GARBAGE COLLECTION")
    
      Runtime.getRuntime.gc
      Thread.sleep(20000)
    
      println("TRIGGERING FINALIZATION")
      Runtime.getRuntime.runFinalization()
    
    }
    
    

    external by Github  317  0  3  0

    Creating throw away actors to perform computations, on completion, they commit suicide using PoisonPil. Shutdown hooks are triggered, and verify that they are GC'd by adding extra code to the finalization hooks. I used scala.concurrent's blocking meth...

    Creating throw away actors to perform computations, on completion, they commit suicide using PoisonPil. Shutdown hooks are triggered, and verify that they are GC'd by adding extra code to the finalization hooks. I used scala.concurrent's blocking method for good measure. The thread pool (used by these blocking op's) is constrained to 2 threads.:
    package com.picsolve
    
    import akka.actor.{PoisonPill, Props, Actor, ActorSystem}
    import java.util.concurrent.atomic.AtomicInteger
    import java.util.concurrent.{ThreadFactory, Executors}
    import akka.dispatch.ExecutionContexts
    import scala.concurrent.Future
    import scala.util.{Failure, Success}
    
    object RetryingActorsMain extends App {
      val yourExecutorServiceGoesHere = Executors.newFixedThreadPool(2, new ThreadFactory {
        override def newThread(r: Runnable): Thread = {
          val thread: Thread = new Thread(r)
          thread.setDaemon(true)
          thread
        }
      })
    
      val blockingOpsExecutionContext = ExecutionContexts.fromExecutorService(yourExecutorServiceGoesHere)
    
    
      object MultiTry {
    
    
        private[MultiTry] val countdown = new AtomicInteger(0)
    
        def attempt(s: String) = {
    
          Future {
            concurrent.blocking{
            Thread.sleep(1000)
            if (countdown.getAndIncrement % 3 == 0) {
              //Every third works..
              println("success")
            } else
              throw new UnsupportedOperationException("couldn't connect to server")
            }
          }(blockingOpsExecutionContext)
    
        }
      }
    
      implicit val as = ActorSystem("foo")
    
    
      case class TryingMessage(name: String)
    
      case class Trying(msg: TryingMessage, count: Int = 0)
    
      class TryingActor extends Actor {
    
        println(s"creating new ${this.getClass}")
    
        val TRIES = 4
        var attempts = 0
    
    
        override def finalize(): Unit = {
          println("time to finalize!")
          super.finalize()
        }
    
        override def preStart(): Unit = {
          println(self)
          super.preStart()
        }
    
    
    
        override def postStop(): Unit = {
        println(s"stopped : $self ")
    
          super.postStop()
        }
    
        override def receive = {
    
          case msg@TryingMessage(name) =>
            MultiTry.attempt(name).onComplete {
              case Success(_) =>
                println("sucesss")
                self ! PoisonPill
              case Failure(t) =>
                println(s"failed attempt $attempts")
                attempts += 1
                self ! Trying(msg, TRIES)
            }(blockingOpsExecutionContext)
    
          case Trying(msg, count) if count > 0 =>
            MultiTry.attempt(msg.name).onComplete {
              case Success(_) =>
                println("sucesss")
                self ! PoisonPill
              case Failure(t) =>
                println(s"failed attempt $attempts")
                attempts += 1
                self ! Trying(msg, count - 1)
            }(blockingOpsExecutionContext)
    
    
          case Trying(msg, count) if count <= 0 =>
            println("final failure, not retrying again!")
            self ! PoisonPill
        }
      }
    
      for {i <- 1 to 10} {
        as.actorOf(Props[TryingActor]()) ! TryingMessage(s"actor $i")
      }
    
    
      Thread.sleep(20000)
      println("RUNNING GARBAGE COLLECTION")
    
      Runtime.getRuntime.gc
      Thread.sleep(20000)
    
      println("TRIGGERING FINALIZATION")
      Runtime.getRuntime.runFinalization()
    
    }
    
    

    external by Barrett Langton  93  0  1  0

    Clears out current git hooks and runs 'git init' to apply hooks that are in .git-templates/hooks

    Clears out current git hooks and runs 'git init' to apply hooks that are in .git-templates/hooks: update-hooks
    #!/usr/bin/env bash
    
    # Check that the git directory exists.
    GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
    if [ -z "$GIT_DIR" ]; then
      echo >&2 "Fatal: GIT_DIR not set"
      exit 1
    fi
    
    # Remove existing hooks and re-init to copy new hooks.
    rm $GIT_DIR/hooks/*
    git init
    
    

    external by MarketPress Support Team  24  0  1  0

    Mini-Plugin-Boilerplate für eigene Anpassungen. Informationen zu den verwendeten WordPress-Hooks: http://www.rarst.net/wordpress/wordpress-core-load/ Schnell-Tutorial zu Hooks und Filtern: https://gist.github.com/marketpress-support-team/12fc81fcfb2b...

    Mini-Plugin-Boilerplate für eigene Anpassungen. Informationen zu den verwendeten WordPress-Hooks: http://www.rarst.net/wordpress/wordpress-core-load/ Schnell-Tutorial zu Hooks und Filtern: https://gist.github.com/marketpress-support-team/12fc81fcfb2ba797735b: _anpassungen.php
    <?php
    /**
     * Plugin Name:       _Anpassungen
     * Description:       Deine eigenen Anpassungen
     * Version:           2015.11
     * Author:            Du :)
     * License:           GNU General Public License v3 or later
     * License URI:       http://www.gnu.org/licenses/gpl-3.0.html
     */
    
    
    if ( ! defined( 'ABSPATH' ) ) {
    	exit;
    }
    
    /**
     * Anpassungen via Hook plugins_loaded.
     *
     * @return void
     */
    function _anpassungen__plugins_loaded() {
    
    	/**
    	 * Test. Zeigt einen Admin-Hinweis, wenn das Plugin aktiv ist.
    	 * Sollte im produktiven Einsatz entfernt werden.
    	 */
    	add_action( 'admin_notices', function() {
    		$msg = sprintf(
    			'<p>%s</p>',
    			'<strong>Anpassungen</strong> sind aktiv!'
    		);
    		$classes  = 'notice-info is-dismissible';
    		printf(
    			'<div class="notice %1$s">%2$s</div>',
    			$classes,
    			$msg
    		);
    	} );
    
    	/* Dein Code hier. */
    	
    	/* Nur für WooCommerce German Market. */
    	if ( class_exists( 'WGM_Template' ) ) {
    	  
    	  /* Dein WGM-Code hier. */
    	  
    	}
    	
    	/* Nur für WooCommerce. */
    	if ( class_exists( 'WooCommerce' ) ) {
    	  
    	  /* Dein WooCommerce-Code hier. */
    	  
    	}
    
    }
    add_action( 'plugins_loaded', '_anpassungen__plugins_loaded' );
    
    /**
     * Anpassungen via Hook after_setup_theme.
     *
     * @return void
     */
    function _anpassungen__after_setup_theme() {
    
    	/* Dein Code hier. */
    
    }
    add_action( 'after_setup_theme', '_anpassungen__after_setup_theme' );
    
    /**
     * Anpassungen via Hook init.
     *
     * @return void
     */
    function _anpassungen__init() {
    
    	/* Dein Code hier. */
    
    }
    add_action( 'init', '_anpassungen__init' );
    
    /**
     * Anpassungen via Hook template_redirect.
     *
     * @return void
     */
    function _anpassungen__template_redirect() {
    
    	/* Dein Code hier. */
    
    }
    add_action( 'template_redirect', '_anpassungen__template_redirect' );
    
    

    external by nickmccurdy  1  0  1  0

    add-hooks macro for Emacs: Set many hooks at once, without duplicating hook or function names.

    add-hooks macro for Emacs: Set many hooks at once, without duplicating hook or function names.: add-hooks.el
    (defun listify (object)
      "If OBJECT is a list, return it, else wrap it in a list."
      (if (listp object) object (list object)))
    
    (defun mapflat (function sequence)
      "Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
    Unlike `mapcar', the list is flattened nondestructively before it is returned."
      (apply #'append (mapcar function sequence)))
    
    (defmacro add-hooks (&rest args)
      "Call `add-hook' on each cons pair in ARGS.
    Each pair has a `car' for setting hooks and a `cdr' for setting
    functions to add to those hooks.  Either side of the pair can be
    a single symbol or a list of symbols, in which case a function
    can be added to multiple hooks and/or multiple functions can be
    added to a hook."
      (macroexp-progn
       (mapflat (lambda (arg)
                  (let ((hooks (listify (car arg)))
                        (functions (listify (cdr arg))))
                    (mapflat (lambda (hook)
                               (mapcar (lambda (function)
                                         `(add-hook ',hook ',function))
                                       functions))
                             hooks)))
                args)))
    
    

    external by tyler-sommer  172  3  2  0

    Fix broken gitlab hooks in your project repositories

    Fix broken gitlab hooks in your project repositories: fix.rb
    Dir.glob('/home/git/repositories/**/*.git') do |item|
      hook = "#{item}/hooks"
    
      if not File.symlink?(hook)
        puts "Updating #{hook}"
        File.rename(hook, "#{hook}.old")
        File.symlink("/home/git/gitlab-shell/hooks", hook)
      end
    end
    
    
    • Public Snippets
    • Channels Snippets