working on it ...

Filters

Explore Public Snippets

Sort by

Found 15k snippets matching: safe

    public by cghersi modified Nov 4, 2014  283148  2  6  1

    Remove HTML tags from text

    Removes the given tag (and all its content) from the specified text.
    static public string RemoveHtmlTag(string pageString, string tagName)
    {
      string output = pageString;
      int exprIni = 0;
      int firstChar = 0;
      int lastChar = 0;
    
      // find html element
      exprIni = output.IndexOf("<" + tagName, 0, output.Length,
                                      StringComparison.InvariantCultureIgnoreCase);
      while (exprIni >= 0)
      {
        // extract the html
        firstChar = exprIni;
    
        // find <tag ... />
        lastChar = output.IndexOf("/>", (firstChar + 1)) + 1;
        int nextCloseTag = output.IndexOf('>', (firstChar + 1));
    
        // closed with </tag> marker..
        if ((lastChar <= 0) || (nextCloseTag < lastChar))
        {
          // find </tag>
          lastChar = output.IndexOf("</" + tagName, (firstChar + 1), (output.Length - firstChar - 1),
                                                          StringComparison.InvariantCultureIgnoreCase);
          lastChar = output.IndexOf('>', (lastChar + 1));
        }
    
        if ((firstChar < 0) || (lastChar <= 0) || (firstChar == lastChar))
          return output.Substring(0, firstChar);
        else
        {
          output = String.Format("{0} {1}",
                      output.Substring(0, firstChar).Trim(),
                      output.Substring((lastChar + 1), (output.Length - lastChar - 1)).Trim());
        }
        exprIni = output.IndexOf("<" + tagName, 0, output.Length,
                                    StringComparison.InvariantCultureIgnoreCase);
      }
    
      return output;
    }
    

    public by strykerraven modified Sep 22, 2016  187940  3  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 DavidEGrayson modified Aug 2, 2015  134135  0  3  0

    Safe signed multiplication test suite

    Safe signed multiplication test suite: int64_test.c
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdint.h>
    #include <limits.h>
    
    // Multiplies two 64-bit signed ints if possible.
    // Returns 0 on success, and puts the product of x and y into the result.
    // Returns 1 if there was an overflow.
    int int64_mult(int64_t x, int64_t y, int64_t * result)
    {
        *result = 0;
        if (x > 0 && y > 0 && x > INT64_MAX / y) return 1;
        if (x < 0 && y > 0 && x < INT64_MIN / y) return 1;
        if (x > 0 && y < 0 && y < INT64_MIN / x) return 1;
        if (x < 0 && y < 0 && (x <= INT64_MIN || y <= INT64_MIN || -x > INT64_MAX / -y))
            return 1;
        *result = x * y;
        return 0;
    }
    
    void test_int64_mult_success(int64_t x, int64_t y, int64_t expected)
    {
        int64_t result;
    
        // x * y
        if (int64_mult(x, y, &result))
        {
            fprintf(stderr, "unexpected overflow: %lld %lld\n", x, y);
        }
        if (result != expected)
        {
            fprintf(stderr, "wrong result: %lld %lld %lld %lld\n", x, y, expected, result);
        }
    
        // y * x should be the same
        if (int64_mult(y, x, &result))
        {
            fprintf(stderr, "unexpected overflow: %lld %lld\n", y, x);
        }
        if (result != expected)
        {
            fprintf(stderr, "wrong result: %lld %lld %lld %lld\n", y, x, expected, result);
        }
    }
    
    void test_int64_mult_error(int64_t x, int64_t y)
    {
        int64_t result;
    
        // x * y
        if (int64_mult(x, y, &result) == 0)
        {
            fprintf(stderr, "unexpected success: %lld %lld\n", x, y);
        }
    
        // y * x shoul be the same
        if (int64_mult(y, x, &result) == 0)
        {
            fprintf(stderr, "unexpected success: %lld %lld\n", y, x);
        }
    }
    
    int main()
    {
        // min, min
        test_int64_mult_error(INT64_MIN, INT64_MIN);
    
        // min, min/100
        test_int64_mult_error(INT64_MIN, INT64_MIN / 100);
    
        // min, 0
        test_int64_mult_error(INT64_MIN, -2);
        test_int64_mult_error(INT64_MIN, -1);
        test_int64_mult_success(INT64_MIN, 0, 0);
        test_int64_mult_success(INT64_MIN, 1, INT64_MIN);
        test_int64_mult_error(INT64_MIN, 2);
    
        // min, max/100
        test_int64_mult_error(INT64_MIN, INT64_MAX / 100);
    
        // min, max
        test_int64_mult_error(INT64_MIN, INT64_MAX);
    
        // min/100, min/100
        test_int64_mult_error(INT64_MIN / 100, INT64_MIN / 100);
    
        // min/100, 0
        test_int64_mult_error(INT64_MIN / 100, -101);
        test_int64_mult_success(INT64_MIN / 100, -100, 0x7ffffffffffffff8);
        test_int64_mult_success(INT64_MIN / 100, -99, 0x7eb851eb851eb84a);
        test_int64_mult_success(INT64_MIN / 100, 0, 0);
        test_int64_mult_success(INT64_MIN / 100, 100, -0x7ffffffffffffff8);
        test_int64_mult_error(INT64_MIN / 100, 101);
    
        // min/100, max/100
        test_int64_mult_error(INT64_MIN / 100, INT64_MAX / 100);
    
        // min/100, max
        test_int64_mult_error(INT64_MIN / 100, INT64_MAX);
    
        // 0, 0
        test_int64_mult_success(0, 0, 0);
        test_int64_mult_success(0, 1, 0);
        test_int64_mult_success(1, 1, 1);
        test_int64_mult_success(1, 3, 3);
        test_int64_mult_success(3, 3, 9);
    
        // 0, max/100
        test_int64_mult_error(INT64_MAX / 100, -101);
        test_int64_mult_success(INT64_MAX / 100, -100, -0x7ffffffffffffff8);
        test_int64_mult_success(INT64_MAX / 100, -99, -0x7eb851eb851eb84a);
        test_int64_mult_success(INT64_MAX / 100, 0, 0);
        test_int64_mult_success(INT64_MAX / 100, 100, 0x7ffffffffffffff8);
        test_int64_mult_error(INT64_MAX / 100, 101);
    
        // 0, max
        test_int64_mult_error(-2, INT64_MAX);
        test_int64_mult_success(-1, INT64_MAX, -INT64_MAX);
        test_int64_mult_success(0, INT64_MAX, 0);
        test_int64_mult_success(1, INT64_MAX, INT64_MAX);
        test_int64_mult_error(2, INT64_MAX);
    
        // max/100, max
        test_int64_mult_error(INT64_MAX / 100, INT64_MAX);
    }
    
    
    

    public by MatteoP modified Aug 5, 2014  2409  3  6  0

    Thread safe update of textbox

    //thread safe component update
    private void log(string text)
    {
        /*
         * Thread-safe method to write things in the textbox
         */
        if (InvokeRequired)
        {
            Invoke(new Action<string>(log), text);
        }
        else
        {
            tbLogging.Text += text + "\n";
        }
    }

    public by sTiLL-iLL @ SniPitz-KND modified Oct 13, 2014  3417  3  7  19

    Equality in javascript...

    An "equals" method for any type... try it, you might like it
    
    // a true Equalty comparor in JS
    
    Object.prototype.equals = function(x) {
        var p;
        for(p in this) {
          if (typeof(x[p]) == "undefined") {
            return false;
          }
        }
        for(p in this) {
          if (this[p]) {
            switch(typeof(this[p])) {
              case "object":
                if (!this[p].equals(x[p])) {
                  return false;
                }
                break;
              case "function":
                if (typeof(x[p]) == "undefined"||(p != "equals" &&
                  this[p].toString() != x[p].toString())) {
                    return false;
                }
                break;
              default:
                if (this[p] != x[p]) {
                  return false;
                }
            }
          }
          else {
            if (x[p]) {
              return false;
            }
        }
        for(p in x) {
          if(typeof(this[p])=="undefined") {
            return false;
          }
        }
        return true;
      }
    }
    

    public by sTiLL-iLL @ SniPitz-KND modified Jun 27, 2015  2747  5  8  12

    EKOING C# WebSokETS server Thangy

    it might work
    using System;
    using System.Web;
    using System.Net.WebSockets;
    using System.Web.WebSockets;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    public class EKOSocket : IHttpHandler {
        private const int MaxBuffer = 64 * 1024;
    
        public void OnRequest (HttpContext cntxt)
        {
            try
            {
                cntxt.AcceptWebSocketRequest(async wsContext => {
                    try
                    {
                        WebSocket skt = wsContext.WebSocket;
                        byte[] received = new byte[MaxBuffer];
                        ArraySegment<byte> buff = new ArraySegment<byte>(receive);
                        
                        string clientMsg;
    
                        if (skt.State == WebSocketState.Open)
                        {
                            var announce = "Connection @ : " + DateTime.Now.ToString();
                            ArraySegment<byte> output2 = new ArraySegment<byte>(Encoding.UTF8.GetBytes(announce));
                            await skt.SendAsync(output2, WebSocketMessageType.Text, true, CancellationToken.None);
                        }
    
                        while (skt.State == WebSocketState.Open)
                        {
                            WebSocketReceiveResult receive = await skt.ReceiveAsync(buff, CancellationToken.None);
    
                            if (receive.MessageType == WebSocketMessageType.Close)
                            {
                                // EKO back
                                await skt.CloseAsync(
                                    receive.CloseStatus.GetValueOrDefault(), 
                                    receive.CloseStatusDescription, CancellationToken.None);
                                return;
                            }
    
                            int offset = receive.Count;
                            while (receive.EndOfMessage == false)
                            {
                                receive = await skt.ReceiveAsync(new ArraySegment<byte>(received, offset,
                                MaxBuffer - offset),CancellationToken.None);
                                offset += received.Count;
                            }
    
                            if (receive.MessageType == WebSocketMessageType.Text)
                            {
                                string cmd = Encoding.UTF8.GetString(received, 0, offset);
                                clientMsg = cmd;
                                clientMsg = "EKO: \"" + clientMsg + "\"";
    
                                ArraySegment<byte> output = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userString));
                                await skt.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
                            }
                            else if (receive.MessageType == WebSocketMessageType.Binary)
                            {
                                clientMsg = String.Format("binary message received, size={0} bytes", receiveResult.Count);
                                ArraySegment<byte> output = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userString));
                                await skt.SendAsync(output, WebSocketMessageType.Text, true, CancellationToken.None);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // do something with the exception
                    }
                });
            }
            catch (Exception ex)
            {
                cntxt.Response.StatusCode = 500;
                cntxt.Response.StatusDescription = ex.Message;
                cntxt.Response.End();
            }
        }
    
        public bool canRecycle
        {
            get
            {
                return false;
            }
        }
    }
               

    public by cghersi modified Jan 7, 2014  3401  1  9  0

    Safe conversion of string to float in SQL Server 2012

    This function allows a safe conversion of strings to float values.
    CREATE FUNCTION [dbo].[isFloatTryConvertible] (@str nvarchar(70))
    RETURNS bit WITH SCHEMABINDING
    AS
    BEGIN
    	DECLARE @res bit = 0;
    
    	IF (TRY_CONVERT(float, @str) IS NOT NULL)
    		SET @res = 1;
    	
    	RETURN @res;
    END

    public by cghersi modified Mar 18, 2014  2553  1  6  2

    Safe Realization of a Thread in Java

    Manage threads in Java can be tricky, most of all the stop of them. With this class no littering thread will be left behind.
    import java.lang.Thread;
    import java.util.List;
    
    public class MySafeThread implements Runnable {
    
    	private static MySafeThread singleton = null;
    	/**
    	 * Synchronization variable for the safe instantiation of the singleton
    	 */
    	private static Object synchSingleton = new Object();
    	/**
    	 * The actual thread object
    	 */
    	private Thread thread;
    	/**
    	 * The flag signalling whether the thread is running or not
    	 */
    	private boolean threadRunning = false;
    
    	
    	private MySafeThread(){
    	}
    
    	public void restart() {
    		closeThread();
    		startThread();
    	}
    
    
    	/**
    	 * Closes the thread, releasing all the resources
    	 */
    	public void closeThread(){
    		threadRunning = false;
    
    		//break the execution of the thread and wait until the last loop is finished:
    		Thread moribond = this.thread;
    		this.thread=null;
    		moribond.interrupt();
    
    		singleton = null;
    	}
    
    	
    	/**
    	 * Retrieves the singleton instance of the class; if
    	 * the singleton has not yet been instantiated, it builds 
    	 * a new instance using the protected constructor.
    	 * @return The singleton instance of the class
    	 */
    	public static MySafeThread get(){
    		if (singleton == null) {
    			synchronized (synchSingleton) {
    				if (singleton == null) {
    					singleton = new MySafeThread();
    				}
    			}
    		}
    	
    		return singleton;
    	}
    
    	/**
    	 * The main method of the thread which listens for new responses available, and
    	 * sends them via IPC
    	 */
    	public void run(){
    		Thread t = Thread.currentThread();
    		
    		threadRunning = true;
    		while(threadRunning) {
    			//do something...
    		}
    	}
    
    	/**
    	 * Starts the thread
    	 */
    	public void startThread(){
    		//only a single instance of the thread can run:
    		if (threadRunning)
    			return;
    	
    		this.thread = new Thread(this, "GiveANameToTheThread");
    		this.thread.start();	
    	}
    }

    public by cghersi modified Jul 31, 2013  2806  1  6  0

    Safe creation of Stored Procedure for MS SQL Server 2012

    The following example of Stored Procedure can be use as a template for the creation of every procedure that needs a transaction
    CREATE PROCEDURE [dbo].[TblName_ProcName]
    	@Param1 nvarchar(50)
    AS
    BEGIN
    	SET NOCOUNT ON;
    	SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
    	SET XACT_ABORT ON;
    
    	DECLARE @error int = 0;
    
    	BEGIN TRAN
    
    		-- do stuff; for each SQL instruction add the following statement to 
    		-- check the occurrence of an error: 
    		SET @error = @error + @@ERROR
    	
    	IF @error = 0
    		BEGIN
    			COMMIT;
    			RETURN 0;
    		END
    	ROLLBACK
    	RETURN -1;
    	
    END
    GO

    public by cghersi modified May 12, 2014  2350  0  7  2

    safe use of locks in Java

    This class shows how to safely implement a lock to manage a crucial variable, accessed by several threads in concurrency. Just a notes on the use of ReentrantLock: its use may be replaced by a simple synchronized block where no huge concurrency issues are forecasted (say, less than 700 concurrent threads)
    import java.util.concurrent.locks.ReentrantLock;
    
    public abstract class LockedClass {
    
    	/**
    	 * Determines whether or not a call (i.e. a particular method of the class)
    	 * should be always sent, without depending from the implementation 
    	 * of isChildSendable() in the children classes
    	 */
    	private boolean isAlwaysSendable = true;
    	/**
    	 * Lock for the guard of sending mechanism.
    	 */
    	private ReentrantLock lock = new ReentrantLock();
    	
    	public LockedClass(boolean isAlwaysendable) {
    	  this.isAlwaysendable = isAlwaysendable;
    	}
    
    	protected boolean isChildSendable(){
    	  //override this behavior in children classes if you need...
    		return true;
    	}
    
    	public final boolean isSendable(){
    		if (isAlwaysSendable)
    			return true;
    		
    		boolean b;
    		lock.lock();
    		b = isChildSendable();
    		if (b)
    			setChildSendable(false);
    		lock.unlock();
    		return b;
    	}
    
    	protected void setChildSendable(boolean sendable){
    	  //put something here or override in children classes if you want to 
    	  //customize
    	}
    
    	public final void setSendable(boolean sendable){
    		if (isAlwaysSendable)
    			return;
    		
    		lock.lock();
    		setChildSendable(sendable);
    		lock.unlock();
    	}
    }
    • Public Snippets
    • Channels Snippets