working on it ...

Filters

Explore Public Snippets

Sort by

Found 2,130 snippets matching: token

    public by lbottaro  476348  9  6  2

    JavaScript equivalent to C# String.format

    The code below is the Javascript equivalent to C# String.Format() for replacing elements like {0}, {1}, {2} with parameters. In this case the String prototype is modified, adding the new format() method to all string instances. How to use var mystring = "Hello {0}, how are you? My name is {1}. Bye {0}!" mystring.format("Alice", "Bob") //
    // First, checks if it isn't implemented yet.
    if (!String.prototype.format) {
      String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
            ? args[number]
            : match
          ;
        });
      };
    }            

    public by cghersi  15020  33  10  3

    C#: String Tokenizer

    This class provides a fast way to tokenize the given string and can be fully customizable in terms of splitting symbols, strange characters managed as letters, etc.
    using System;
    using System.IO;
    using System.Text;
    using System.Collections;
    using System.Collections.Generic;
    
    public class StringTokenizer
    {
        const char EOF = (char)0;
    
        int line;
        int column;
        int pos;	// position within data
    
        string data;
    
        List<Token> tokens;
    
        bool ignoreWhiteSpace;
        bool ignoreEqualChar;
        bool ignoreDigits;
        bool tokenSeparatedBySpace;
        char[] symbolChars;
        char[] symbolAsLetter;  //array of symbols treated as common letters inside words
    
        int saveLine;
        int saveCol;
        int savePos;
    
        bool tokenListCreated = false;
    
        public StringTokenizer(TextReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");
    
            data = reader.ReadToEnd();
    
            Reset();
        }
    
        public StringTokenizer(string data)
        {
            if (data == null)
                throw new ArgumentNullException("data");
    
            this.data = data;
    
            Reset();
        }
    
    
        /// <summary>
        /// gets the list of tokens representing the input
        /// </summary>
        public List<Token> Tokens
        {
            get
            {
                if (!tokenListCreated)
                    this.CreateArrayList();
                return this.tokens;
            }
        }
    
    
        /// <summary>
        /// gets or sets which characters are part of TokenKind.Symbol
        /// </summary>
        public char[] SymbolChars
        {
            get { return this.symbolChars; }
            set { this.symbolChars = value; }
        }
    
    
        /// <summary>
        /// gets or sets which special characters (symbols) are treated as common letters inside words.
        /// Default is empty list.
        /// </summary>
        public char[] SymbolAsLetter
        {
            get { return this.symbolAsLetter; }
            set { this.symbolAsLetter = value; }
        }
    
    
        /// <summary>
        /// if set to true, white space characters will be ignored,
        /// but EOL and whitespace inside of string will still be tokenized.
        /// Default is false.
        /// </summary>
        public bool IgnoreWhiteSpace
        {
            get { return this.ignoreWhiteSpace; }
            set { this.ignoreWhiteSpace = value; }
        }
    
        /// <summary>
        /// if set to true, '=' character will be ignored,
        /// but EOL and whitespace inside of string will still be tokenized.
        /// Default is false.
        /// </summary>
        public bool IgnoreEqualChar
        {
            get { return this.ignoreEqualChar; }
            set { this.ignoreEqualChar = value; }
        }
    
        /// <summary>
        /// if set to true, digits are treated as normal characters, like literals.
        /// Default is false.
        /// </summary>
        public bool IgnoreDigits
        {
            get { return this.ignoreDigits; }
            set { this.ignoreDigits = value; }
        }
    
        /// <summary>
        /// if set to true, tokens must be separated by separators (spaces, tabs, etc).
        /// Default is false.
        /// </summary>
        public bool TokenSeparatedBySpace
        {
            get { return this.tokenSeparatedBySpace; }
            set { this.tokenSeparatedBySpace = value; }
        }
    
        private void Reset()
        {
            this.ignoreWhiteSpace = false;
            this.ignoreEqualChar = false;
            this.ignoreDigits = false;
            this.tokenSeparatedBySpace = false;
            this.symbolChars = new char[]{  '+', '-', '/', '*', '~', '@', '#', '%', '^',
                                            '=', '<', '>', '!',
                                            ',', '.', ':', ';', '_',
                                            '$', '€', '£', '&', '?', '|', '\\', '\'', '§', '°', 
                                            'ç', 'ì', 'è', 'é', 'ò', 'à', 'ù',    
                                            '(', ')', '{', '}', '[', ']'};
            this.symbolAsLetter = new char[] { };
    
            this.tokens = new List<Token>();
    
            line = 1;
            column = 1;
            pos = 0;
            tokenListCreated = false;
        }
    
        protected char LA(int count)
        {
            if (pos + count >= data.Length)
                return EOF;
            else
                return data[pos + count];
        }
    
        protected char Consume()
        {
            char ret = data[pos];
            pos++;
            column++;
    
            return ret;
        }
    
        protected Token CreateToken(TokenKind kind, string value)
        {
            Token tmp = new Token(kind, value, line, column);
            tokens.Add(tmp);
            return tmp;
        }
    
        protected Token CreateToken(TokenKind kind)
        {
            string tokenData = data.Substring(savePos, pos - savePos);
            Token tmp = new Token(kind, tokenData, saveLine, saveCol);
            tokens.Add(tmp);
            return tmp;
        }
    
        /* populate the arraylist. */
        protected void CreateArrayList()
        {
            //initialization of the positions for the scrolling of the input string:
            line = 1;
            column = 1;
            pos = 0;
            tokens.Clear();
    
            //sliding input in order to fill the arraylist:
            Token tmp = Next();
            while ((tmp.Kind != TokenKind.EOF) && (tmp.Kind != TokenKind.EOL))
                tmp = Next();
    
            tokenListCreated = true;
        }
    
        public Token Next()
        {
        ReadToken:
    
            char ch = LA(0);
            switch (ch)
            {
                case EOF:
                    return CreateToken(TokenKind.EOF, string.Empty);
    
                case ' ':
                case '\t':
                    {
                        if (this.ignoreWhiteSpace)
                        {
                            Consume();
                            goto ReadToken;
                        }
                        else
                            return ReadWhitespace();
                    }
    
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    if (ignoreDigits)
                        return ReadWord();
                    else
                        return ReadNumber();
    
                case '\r':
                    {
                        StartRead();
                        Consume();
                        if (LA(0) == '\n')
                            Consume();	// on DOS/Windows we have \r\n for new line
    
                        line++;
                        column = 1;
    
                        return CreateToken(TokenKind.EOL);
                    }
                case '\n':
                    {
                        StartRead();
                        Consume();
                        line++;
                        column = 1;
    
                        return CreateToken(TokenKind.EOL);
                    }
    
                case '"':
                    {
                        return ReadString();
                    }
    
                default:
                    {
                        if (Char.IsLetter(ch) || (ignoreDigits && Char.IsDigit(ch)) ||
                            (ch == '_') || IsSymbolAsLetter(ch))
                            return ReadWord();
                        else if (IsSymbol(ch))
                        {
                            string symbol = new string(ch, 1);
                            char firstChar = ch;
    
                            StartRead();
                            Consume();
                            ch = LA(0);
    
                            //case of symbols composed by more than 1 char:
                            //symbols: "<>" or "!=" or ">=" or "<=":
                            switch (firstChar)
                            {
                                case '<':
                                    if ((ch == '>') || (ch == '='))
                                    {
                                        StartRead();
                                        Consume();
                                        symbol = string.Format("{0}{1}", symbol, ch);
                                    }
                                    break;
    
                                case '>':
                                    if ((ch == '<') || (ch == '='))
                                    {
                                        StartRead();
                                        Consume();
                                        symbol = string.Format("{0}{1}", symbol, ch);
                                    }
                                    break;
    
                                case '!':
                                    if (ch == '=')
                                    {
                                        StartRead();
                                        Consume();
                                        symbol = string.Format("{0}{1}", symbol, ch);
                                    }
                                    break;
    
                                default: break;
                            }
    
                            //if user wants tokens separated only by separators (spaces, tabs, etc.), check if 
                            //symbol is alone or within a word:
                            if (tokenSeparatedBySpace && (ch != EOF) && (ch != ' ') && (ch != '\t') &&
                                (ch != '\n') && (ch != '\r'))
                            {
                                return ReadWord(string.Format("{0}{1}", firstChar, ch));
                            }
    
                            return CreateToken(TokenKind.Symbol, symbol);
                        }
                        else
                        {
                            StartRead();
                            Consume();
                            return CreateToken(TokenKind.Unknown);
                        }
                    }
    
            }
        }
    
        /// <summary>
        /// save read point positions so that CreateToken can use those
        /// </summary>
        private void StartRead()
        {
            saveLine = line;
            saveCol = column;
            savePos = pos;
        }
    
        /// <summary>
        /// reads all whitespace characters (does not include newline)
        /// </summary>
        /// <returns></returns>
        protected Token ReadWhitespace()
        {
            StartRead();
    
            Consume(); // consume the looked-ahead whitespace char
    
            while (true)
            {
                char ch = LA(0);
                if (ch == '\t' || ch == ' ')
                    Consume();
                else
                    break;
            }
    
            return CreateToken(TokenKind.WhiteSpace);
    
        }
    
        /// <summary>
        /// reads number. Number is: DIGIT+ ("." DIGIT*)?
        /// </summary>
        /// <returns></returns>
        protected Token ReadNumber()
        {
            StartRead();
    
            bool hadDot = false;
    
            Consume(); // read first digit
    
            while (true)
            {
                char ch = LA(0);
                if (Char.IsDigit(ch))
                    Consume();
                else if (ch == '.' && !hadDot)
                {
                    hadDot = true;
                    Consume();
                }
                else
                    break;
            }
    
            return CreateToken(TokenKind.Number);
        }
    
        /// <summary>
        /// reads word. Word contains any alpha character or _
        /// </summary>
        protected Token ReadWord()
        {
            StartRead();
    
            Consume(); // consume first character of the word
    
            while (true)
            {
                char ch = LA(0);
                if (Char.IsLetter(ch) || (ignoreDigits && Char.IsDigit(ch)) || ch == '_' ||
                    (ignoreEqualChar && (ch == '=')) || IsSymbolAsLetter(ch) ||
                    (tokenSeparatedBySpace && IsSymbol(ch)))
                    Consume();
                else
                    break;
            }
    
            return CreateToken(TokenKind.Word);
        }
    
        /// <summary>
        /// reads word. Word contains any alpha character or _ and is appended to input string
        /// </summary>
        /// <param name="prefix">string which word is appended to</param>
        protected Token ReadWord(string prefix)
        {
            StartRead();
    
            //bring forward the position cursor of the nmber of chars in prefix:
            savePos = savePos - prefix.Length + 1;
    
            while (true)
            {
                char ch = LA(0);
                if (Char.IsLetter(ch) || (ignoreDigits && Char.IsDigit(ch)) || ch == '_' ||
                    (ignoreEqualChar && (ch == '=')) || IsSymbolAsLetter(ch) ||
                    (tokenSeparatedBySpace && IsSymbol(ch)))
                    Consume();
                else
                    break;
            }
    
            return CreateToken(TokenKind.Word);
        }
    
        /// <summary>
        /// reads all characters until next " is found.
        /// If "" (2 quotes) are found, then they are consumed as
        /// part of the string
        /// </summary>
        /// <returns></returns>
        protected Token ReadString()
        {
            StartRead();
    
            Consume(); // read "
    
            while (true)
            {
                char ch = LA(0);
                if (ch == EOF)
                    break;
                else if (ch == '\r')	// handle CR in strings
                {
                    Consume();
                    if (LA(0) == '\n')	// for DOS & windows
                        Consume();
    
                    line++;
                    column = 1;
                }
                else if (ch == '\n')	// new line in quoted string
                {
                    Consume();
    
                    line++;
                    column = 1;
                }
                else if (ch == '"')
                {
                    Consume();
                    if (LA(0) != '"')
                        break;	// done reading, and this quotes does not have escape character
                    else
                        Consume(); // consume second ", because first was just an escape
                }
                else
                    Consume();
            }
    
            return CreateToken(TokenKind.QuotedString);
        }
    
        /// <summary>
        /// checks whether c is a symbol character.
        /// </summary>
        protected bool IsSymbol(char c)
        {
            for (int i = 0; i < symbolChars.Length; i++)
                if (symbolChars[i] == c)
                    return true;
    
            return false;
        }
    
        /// <summary>
        /// checks whether c is a symbol character treated as common letter inside words.
        /// </summary>
        protected bool IsSymbolAsLetter(char c)
        {
            for (int i = 0; i < symbolAsLetter.Length; i++)
                if (symbolAsLetter[i] == c)
                    return true;
    
            return false;
        }
    }
    
    public enum TokenKind
    {
        Unknown,
        Word,
        Number,
        QuotedString,
        WhiteSpace,
        Symbol,
        EOL,
        EOF,
        BinaryOp,
        UnaryOp,
        MetaValueOp,
        OpenBrace,
        ClosedBrace
    }
    
    
    /// <summary>
    /// Token is the single element in which is broken a string
    /// </summary>
    public class Token
    {
        int line;
        int column;
        string value;
        TokenKind kind;
    
        public Token(TokenKind kind, string value, int line, int column)
        {
            this.kind = kind;
    
            //if the token is a QuotedString, remove quotes from the value:
            if (kind == TokenKind.QuotedString)
            {
                if (value[0] == '"' && (value.Length >= 2))
                {
                    int len = value.Length - 2;
                    //particular case when the quoted string doesn't end with '"' (e.g. "san francisco)
                    if (value[value.Length - 1] != '"')
                        len++;
                    this.value = value.Substring(1, len);
                }
                else
                    this.value = value;
            }
            else
                this.value = value;
    
            this.line = line;
            this.column = column;
        }
    
        public Token(TokenKind kind, string value) : this (kind, value, 0, 0)
        {
        }
    
        public int Column
        {
            get { return this.column; }
        }
    
        public TokenKind Kind
        {
            get { return this.kind; }
            set { kind = value; }
        }
    
        public int Line
        {
            get { return this.line; }
        }
    
        public string Value
        {
            get { return this.value; }
            set { this.value = value; }
        }
    
        public override string ToString()
        {
            string val = value;
            if (kind == TokenKind.QuotedString)
                val = string.Format("\"{0}\"", val);
    
            return string.Format("value:{0} ;kind:{1}", val, kind);
        }
    }

    public by cghersi  5858  1  8  3

    How to retrieve GMail contacts via API, using OAuth2 token and not username/password credentials

    This class takes charge of the interaction with Google Contacts API, authenticating with an AccessToken authorization flow. In this way the final user should type the credentials in the Google form and not in your form. The "token" parameter of GetContacts() method is the one sent by Google to the callback url specified in the static constant "s_
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Google.Contacts;
    using Google.GData.Contacts;
    using Google.GData.Client;
    using Google.GData.Extensions;
    
    namespace Contact.Utils
    {
      /// <summary>
      /// Summary description for GmailHelper
      /// </summary>
      public class GmailHelper
      {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
        private static fastJSON.JSON jsonUtils = EntityUtils.InitJSONUtils();
    
        private static readonly string APP_NAME = "my app name";
        private static readonly string s_ClientId = "client id given by Google";
        private static readonly string s_ClientSecret = "secret given by Google;
        private static readonly string s_accessTokenUrl = "https://accounts.google.com/o/oauth2/token";
        private static readonly string s_redirUri = WebConfig.Current.PublicPath + "User/GmailCallback";
    
        #region PUBLIC API
        //////////////////////////////////////////////////////////////////////////////////////////////////////
    
        public static string GetRedirUriForContacts()
        {
          return string.Format("https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&redirect_uri={0}&response_type=code&client_id={1}",
            s_redirUri, s_ClientId);
        }
    
        public static List<SimpleContact> GetContacts(string token)
        {
          List<SimpleContact> results = new List<SimpleContact>();
    
          //exchange the code for a token:
          string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
            token, s_ClientId, s_ClientSecret, s_redirUri);
          string accessTokenResp = Utilities.SendHttpRequest(s_accessTokenUrl, postData, true);
          if (string.IsNullOrEmpty(accessTokenResp))
            return results;
    
          AccessTokenStruct parsedJson = null;
          try
          {
            parsedJson = jsonUtils.ToObject<AccessTokenStruct>(accessTokenResp); 
          }
          catch (Exception e)
          {
            log.ErrorFormat("Cannot deserialize access token response: '{0}' due to {1}", accessTokenResp, e.Message);
            return results;
          }
          if (parsedJson == null)
            return results;
    
          //ask for contacts:
          RequestSettings settings = new RequestSettings(APP_NAME, parsedJson.access_token); 
          settings.AutoPaging = true;
          ContactsRequest cr = new ContactsRequest(settings);
          Feed<Contact> contactsFeed = cr.GetContacts();
          IEnumerable<Contact> contacts = null;
          if (contactsFeed != null)
            contacts = contactsFeed.Entries;
          if (contacts == null)
            return results;
    
          try
          {
            foreach (SimpleContact c in contacts)
            {
              if (c.PrimaryEmail == null)
                continue;
              string preferredEmail = c.PrimaryEmail.Address;
              if (string.IsNullOrEmpty(preferredEmail))
                continue;
              string[] otherEmails = null;
              if (c.Emails != null)
                otherEmails = c.Emails.Select(e => e.Address).ToArray();
              S2CContact contact = new S2CContact((c.Name == null ? "" : c.Name.FullName), 
                                                  preferredEmail, otherEmails);
              results.Add(contact);
            }
          }
          catch (Exception e)
          {
            log.ErrorFormat("Cannot retrieve contacts due to {0}", e.Message);
            return results;
          }
    
          return results;
        }
    
        #endregion
        //////////////////////////////////////////////////////////////////////////////////////////////////////
      }
    
      public class AccessTokenStruct
      {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string token_type { get; set; }
    
        public AccessTokenStruct() { }
      }
    
      public class SimpleContact
      {
        public string PreferredEmail { get; set; }
        public string Name { get; set; }
        public string[] Emails { get; set; }
    
        public SimpleContact(string name, string preferredEmail, string[] emails = null)
        {
          Name = name;
          PreferredEmail = preferredEmail;
          if (emails == null)
            Emails = new string[] { preferredEmail };
          else
          {
            List<string> allEmails = new List<string>(emails);
            allEmails.Add(preferredEmail);
            Emails = allEmails.Distinct().ToArray();
          }
        }
    
        public override string ToString()
        {
          if (string.IsNullOrEmpty(Name))
            return PreferredEmail;
          else
            return string.Format("{0} [{1}]", Name, PreferredEmail);
        }
      }
    
    }            

    public by cghersi @ MailUp API DEV  2016  20  5  0

    MailUp REST API - How to authenticate with 3 leg process flow

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 3 leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailUpC
    @using MailUp.Sdk.Base
    @using MailUp.Framework.Contracts.API.Base
    @using MailUp.Framework.Contracts.API.DataContracts.Console
    
    @{  
        Layout = "~/_SiteLayout.cshtml";
        Page.Title = "Welcome to the sample client to interact with MailUp REST API";
        
        MailUpClient mailUp = Session["MailUpClient"] as MailUpClient;
        string receivedCode = Request["code"];
        string redirUri = string.Empty;
        string accessTokenRetrieval = "Your application has been granted. You are now able to consume MailUp API!";
        if (string.IsNullOrEmpty(receivedCode))
        {
            // Phase 1: the authorization flow should be started with the redirection towards MailUp login form
            redirUri = mailUp.GetLogOnUri(Request.Url.AbsoluteUri);
        }
        else
        {
            // Phase 2: the MailUp login form redirected the user back to this page, with the code to be exchanged
            // with access token to securely consume REST API:
            try
            {
                mailUp.RetrieveAccessToken(receivedCode);
                
                //invoke a sample API:
                CollectionOf<ConsoleListItem> lists = mailUp.GetLists("", "idList ASC", 1);
                if ((lists != null) && (lists.Count > 0))
                {
                    accessTokenRetrieval += " E.g. your first list is named '" + lists[0].Name + "'";
                }
            }
            catch (MailUpException ex)
            {
                accessTokenRetrieval = "Unable to access the service due to " + ex.Message;
            }
        }
    }
    <p>
        Click here to start the authorization process. <br />
        The MailUp login page will be displayed and you will be able to enter your username and password. <br />
        Then, you will be redirected back here, with a valid access token that can be used to perform all the REST calls. <br />
        <br />
        @if (string.IsNullOrEmpty(receivedCode))
        {
            <input id="authFlowBtn" type="button" value="Login" onclick="javascript:document.location='@redirUri';" />
        }
        else
        {
            <text>@accessTokenRetrieval</text>
        }
    </p>            

    public by frozeman  740  0  3  0

    Token proposal

    Token proposal: token.md
    ## Token
    
    ### Methods
    
    #### transfer
    
    ```js
    transfer(address _to, uint256 _value) returns (bool success)
    ```
    Send `_value` amount of coins to address `_to`
    
    #### transferFrom
    
    ```js
    transferFrom(address _from, address _to, uint256 _value) returns (bool success)
    ```
    Send `_value` amount of coins from address `_from` to address `_to`
    
    #### balanceOf
    
    ```js
    balanceOf(address _address) constant returns (uint256 balance)
    ```
    Get the account balance of another account with address `_address`
    
    ---
    The `transferFrom` method is used for a "direct debit" workflow, allowing contracts to send coins on your behalf, for example to "deposit" to a contract address and/or to charge fees in sub-currencies; the command should fail unless the `_from` account has deliberately authorized the sender of the message via some mechanism; we propose these standardized APIs for approval:
    
    #### approve
    
    ```js
    approve(address _address) returns (bool _success)
    ```
    Allow `_address ` to direct debit from your account with full custody. Only implement if absolutely required and use carefully. See `approveOnce` below for a more limited method.
    
    #### unapprove
    
    ```js
    unapprove(address _address) returns (bool _success)
    ```
    Unapprove address `_address ` to direct debit from your account if it was previously approved. Must reset both one-time and full custody approvals.
    
    #### isApprovedFor
    
    ```js
    isApprovedFor(address _target, address _proxy) constant returns (bool _r)
    ```
    Returns 1 if `_proxy` is allowed to direct debit from `_target`
    
    #### approveOnce
    
    ```js
    approveOnce(address _address, uint256 _maxValue) returns (bool _success)
    ```
    Makes a one-time approval for `_address ` to send a maximum amount of currency equal to `_maxValue`
    
    #### isApprovedOnceFor
    
    ```js
    isApprovedOnceFor(address _target, address _proxy) returns (uint256 _maxValue)
    ```
    Returns `_maxValue` if `_proxy` is allowed to direct debit the returned `_maxValue` from address `_target` only once. The approval must be reset on any transfer by `_proxy` of `_maxValue` or less.
    
    ### Events
    #### Transfer
    
    ```js
    Transfer(address indexed from, address indexed to, uint256 value)
    ```
    Triggered when tokens are transferred.
    
    #### AddressApproval
    
    ```js
    AddressApproval(address indexed address, address indexed proxy, bool result)
    ```
    Triggered when an `address` approves `proxy` to direct debit from their account.
    
    #### AddressApprovalOnce
    
    ```js
    AddressApprovalOnce(address indexed address, address indexed proxy, uint256 value)
    ```
    Triggered when an `address` approves `proxy` to direct debit from their account only once for a maximum of `value`
    
    
    

    public by cghersi  3138  2  7  0

    Parse number from string in MS SQL Server

    This SQL function lets the user parse a number in a string composed by several known tokens like a URL
    CREATE FUNCTION dbo.parseNumFromTokenizedString
    (
    	@page nvarchar(50)
    )
    RETURNS bigint
    AS
    BEGIN
    	-- Declare the return variable here
    	DECLARE @res bigint = 0
    	DECLARE @pos int = LEN('www.acme.com/Embed/')
    	
    	-- the @page is expected to be a url, 
    	-- something like www.acme.com/Embed/123/blabla
    	-- we want to retrieve the 123 number
    	DECLARE @lastIndexOfSlash bigint = CHARINDEX('/', @page, @pos);
    	IF (@lastIndexOfSlash <= 0)
    		SET @lastIndexOfSlash = LEN(@page)
    	SET @res = TRY_CONVERT(bigint, SUBSTRING(@page, @pos, @lastIndexOfSlash - @pos))
    	IF (@res IS NULL)
    		SET @res = 0;
    	return @res;
    
    END
    GO

    public by jstoledano  329  0  3  0

    Cómo usar httpie para probar la autorización por medio de Tokens.

    Cómo usar httpie para probar la autorización por medio de Tokens.: gistfile1.txt
    (cmi) C:\Users\INE\proyectos\cmi\src [master ≡]> http -v http://localhost:8000/restricted/ "Authorization: Token 6d56369b27c3d36232aab52d47ffbc8779a182dd"
    GET /restricted/ HTTP/1.1
    Accept: */*
    Accept-Encoding: gzip, deflate
    Authorization:  Token 6d56369b27c3d36232aab52d47ffbc8779a182dd
    Connection: keep-alive
    Host: localhost:8000
    User-Agent: HTTPie/0.9.4
    
    
    
    HTTP/1.0 200 OK
    Allow: GET, HEAD, OPTIONS
    Content-Type: application/json
    Date: Wed, 03 Aug 2016 20:42:10 GMT
    Server: WSGIServer/0.2 CPython/3.4.3
    Vary: Accept
    X-Frame-Options: SAMEORIGIN
    
    {
        "id": "2f36592c-77c1-4f80-bacf-21b1ae4f056f",
        "token": "6d56369b27c3d36232aab52d47ffbc8779a182dd",
        "username": "admin"
    }
    
    

    public by mirage3d  4238  0  6  0

    Custom SpriteKit Scene in Swift - Xcode

    A bare-bones custom SpriteKit scene snippet in Swift for Xcode with placeholder tokens
    // XCode bare-bones custom SpriteKit scene snippet
    
    import SpriteKit
    
    class <#Custom#>Scene: SKScene {
    	// MARK: - Properties
    	// use optionals or initialised values to avoid having to write
    	// custom init()'s and the required required init?(coder aDecoder: NSCoder)
    	var <#property1#>: Int!
    	var <#property2#>: CGPoint!
    	let <#property3#> = 3.1415962
    	var <#button1#>: SKSpriteNode!
    	var <#sprite#1>: SKSpriteNode!
    	var <#helperNode#>: SKSNode!
    
    	// MARK: - Methods
    	override func didMoveToView(view: SKView) {
    		<#code#>	
    	}
    
    	override func willMoveFromView(view: SKView) {
    		<#code#>	
    	}
    
    	override func update(currentTime: NSTimeInterval) {
    		<#code#>	
    	}
    
    	// MARK: - <#Other Methods#>
    }
                

    public by Github  1035  1  4  0

    Created using browser-solidity: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://chriseth.github.io/browser-solidity/#version=undefined&optimize=undefined&gist=

    Created using browser-solidity: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://chriseth.github.io/browser-solidity/#version=undefined&optimize=undefined&gist=: Token Standard
    contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }
    
        contract MyToken { 
            /* Public variables of the token */
            string public name;
            string public symbol;
            uint8 public decimals;
    
            /* This creates an array with all balances */
            mapping (address => uint256) public balanceOf;
            mapping (address => mapping (address => uint)) public allowance;
            mapping (address => mapping (address => uint)) public spentAllowance;
    
            /* This generates a public event on the blockchain that will notify clients */
            event Transfer(address indexed from, address indexed to, uint256 value);
    
            /* Initializes contract with initial supply tokens to the creator of the contract */
            function MyToken(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) {
                balanceOf[msg.sender] = initialSupply;              // Give the creator all initial tokens                    
                name = tokenName;                                   // Set the name for display purposes     
                symbol = tokenSymbol;                               // Set the symbol for display purposes    
                decimals = decimalUnits;                            // Amount of decimals for display purposes        
            }
    
            /* Send coins */
            function transfer(address _to, uint256 _value) {
                if (balanceOf[msg.sender] < _value) throw;           // Check if the sender has enough   
                if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
                balanceOf[msg.sender] -= _value;                     // Subtract from the sender
                balanceOf[_to] += _value;                            // Add the same to the recipient            
                Transfer(msg.sender, _to, _value);                   // Notify anyone listening that this transfer took place
            }
    
            /* Allow another contract to spend some tokens in your behalf */
    
            function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
                allowance[msg.sender][_spender] = _value;     
                tokenRecipient spender = tokenRecipient(_spender);
                spender.receiveApproval(msg.sender, _value, this, _extraData);  
            }
    
            /* A contract attempts to get the coins */
    
            function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
                if (balanceOf[_from] < _value) throw;                 // Check if the sender has enough   
                if (balanceOf[_to] + _value < balanceOf[_to]) throw;  // Check for overflows
                if (spentAllowance[_from][msg.sender] + _value > allowance[_from][msg.sender]) throw;   // Check allowance
                balanceOf[_from] -= _value;                          // Subtract from the sender
                balanceOf[_to] += _value;                            // Add the same to the recipient            
                spentAllowance[_from][msg.sender] += _value;
                Transfer(msg.sender, _to, _value); 
            } 
    
            /* This unnamed function is called whenever someone tries to send ether to it */
            function () {
                throw;     // Prevents accidental sending of ether
            }        
        } 
    
    

    public by msdn  133171  1  6  0

    GetS2SClientContextWithWindowsIdentity: Retrieves an S2S client context with an access token signed by the application's private certificate on behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri...

    Retrieves an S2S client context with an access token signed by the application's private certificate on behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Collections.ObjectModel;
    using System.Globalization;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.IO;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Principal;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.Text;
    using System.Web.Configuration;
    using System.Web.Script.Serialization;
    using Microsoft.IdentityModel;
    using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
    using Microsoft.IdentityModel.S2S.Tokens;
    using Microsoft.SharePoint.Client;
    using Microsoft.SharePoint.Client.EventReceivers;
    
    private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
    
    /// <summary>
    /// Retrieves an S2S client context with an access token signed by the application's private certificate on 
    /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the 
    /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the 
    /// targetApplicationUri to discover it.
    /// </summary>
    /// <param name="targetApplicationUri">Url of the target SharePoint site</param>
    /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
    /// <returns>A ClientContext using an access token with an audience of the target application</returns>
    public static ClientContext GetS2SClientContextWithWindowsIdentity(
        Uri targetApplicationUri,
        WindowsIdentity identity)
    {
        string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
    
        JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
    
        string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
    
        return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
    }
    • Public Snippets
    • Channels Snippets