working on it ...

Filters

Explore Public Snippets

Sort by

Found 9,528 snippets matching: format

    public by lbottaro  476199  8  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  369740  4  6  3

    How to prettify a number with thousands or millions

    Prepares a pretty version of the given number, with the ability to match the right plural/singular form for English text
    public static string PaintNumber(int number, string followingText = "", bool numberInBold = false)
    {
      string content = String.Format("{0:N0}", number);
      if (number >= 10000)
      {
        double numberInThousands = number / 1000.0;
        if (numberInThousands < 100)
          content = String.Format("{0:N0}k", numberInThousands);
        else
          content = String.Format("{0:0.#}M", numberInThousands / 1000.0);
      }
      if (number >= 1000000)
      {
        double numberInMillions = number / 1000000.0;
        if (numberInMillions < 100)
          content = String.Format("{0:N0}M", numberInMillions);
        else
          content = String.Format("{0:0.#}B", numberInMillions / 1000.0);
      }
    
      if (numberInBold)
        content = "<b>" + content + "</b>";
    
      if (!string.IsNullOrEmpty(followingText))
        content += " " + followingText + (number != 1 ? "s" : "");
    
      return content;
    }
    

    public by lbottaro  303286  31  7  0

    How to read and parse a txt file in python

    This code shows how to read a txt file and parse the data
    import os
    import sys
    
    myfile = open('/some/path/to/file.txt', "r")
    # EXAMPLE OF FILE FORMAT:
    # abc 123 234 456 678
    # def 122223 2333334 454446 611178
    # ghi 144423 211134 44456 61114478
    
    for line in myfile.readlines():
        name= ''
        numList = list()
    
        print line
        try:
            name = line.split()[0] # it will get 'abc'/'def'/'ghi'
            numList = line.split()[1:] # it will get all other stuff inline...
        except:
            print "Invalid file format"
            myfile.close()
            sys.exit(1)
        
        if not numList:
            print("Invalid numList format! name= " + str(name))
            myfile.close()
            sys.exit(1)
    
        print 'name='+str(name)
        print 'numList='+str(numList)
    
    myfile.close()

    public by lbottaro  311374  3  6  0

    Get MAC address of current interface in Python

    This python uses uuid.getnode to get current mac address as an integer. It formats the number in a standard mac address form (i.e. bytes splitted by :)
    import uuid
    print ':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1])
    

    public by marksimon232  283242  0  7  1

    Swift 2: Custom logger that mimics NSLog

    Using this initializer, you can easily build a custom logger that mimics NSLog:
    public func SWLog(format: String, _ args: CVarArgType...) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = 
            NSDateFormatter.dateFormatFromTemplate(
                "mm:ss:SSS", options: 0, 
                locale: NSLocale.currentLocale())
        let timeString = 
            dateFormatter.stringFromDate(NSDate())
        print("\(timeString): " + 
            String(format: format, arguments: args))
    }

    public by sherazam  228300  0  5  0

    How to Insert Check Boxes or HTML into Word Docs during Mail Merge inside .NET Apps

    How to Insert Check Boxes or HTML into Word Docs during Mail Merge inside .NET Apps
    // Enter here the actual content of the snippet.            
    //[C# Code Sample]
     
    using System;
    using System.IO;
    using System.Reflection;
    using Aspose.Words;
    using Aspose.Words.Fields;
    using Aspose.Words.MailMerging;
    
    namespace MailMergeFormFields
    {
        /// <summary>
        /// This sample shows how to insert check boxes and text input form fields during mail merge into a document.
        /// </summary>
        class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            public static void Main(string[] args)
            {
                Program program = new Program();
                program.Execute();
            }
    
            private void Execute()
            {
                string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
                string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;
    
                // Load the template document.
                Document doc = new Document(dataDir + "Template.doc");
    
                // Setup mail merge event handler to do the custom work.
                doc.MailMerge.FieldMergingCallback = new HandleMergeField();
    
                // This is the data for mail merge.
                String[] fieldNames = new String[] {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber",
                    "Subject", "Body", "Urgent", "ForReview", "PleaseComment"};
                Object[] fieldValues = new Object[] {"Josh", "Jenny", "123456789", "", "Hello",
                    "<b>HTML Body Test message 1</b>", true, false, true};
    
                // Execute the mail merge.
                doc.MailMerge.Execute(fieldNames, fieldValues);
    
                // Save the finished document.
                doc.Save(dataDir + "Template Out.doc");
            }
    
            private class HandleMergeField : IFieldMergingCallback
            {
                /// <summary>
                /// This handler is called for every mail merge field found in the document,
                ///  for every record found in the data source.
                /// </summary>
                void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
                {
                    if (mBuilder == null)
                        mBuilder = new DocumentBuilder(e.Document);
    
                    // We decided that we want all boolean values to be output as check box form fields.
                    if (e.FieldValue is bool)
                    {
                        // Move the "cursor" to the current merge field.
                        mBuilder.MoveToMergeField(e.FieldName);
    
                        // It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
                        string checkBoxName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
    
                        // Insert a check box.
                        mBuilder.InsertCheckBox(checkBoxName, (bool)e.FieldValue, 0);
    
                        // Nothing else to do for this field.
                        return;
                    }
    
                    // We want to insert html during mail merge.
                    if (e.FieldName == "Body")
                    {
                        mBuilder.MoveToMergeField(e.FieldName);
                        mBuilder.InsertHtml((string)e.FieldValue);
                    }
    
                    // Another example, we want the Subject field to come out as text input form field.
                    if (e.FieldName == "Subject")
                    {
                        mBuilder.MoveToMergeField(e.FieldName);
                        string textInputName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
                        mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", (string)e.FieldValue, 0);
                    }
                }
    
                void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
                {
                    // Do nothing.
                }
    
                private DocumentBuilder mBuilder;
            }
        }
    }
     
    //[VB.NET Code Sample]
     
    
    Imports Microsoft.VisualBasic
    Imports System
    Imports System.IO
    Imports System.Reflection
    Imports Aspose.Words
    Imports Aspose.Words.Fields
    Imports Aspose.Words.MailMerging
    
    Namespace MailMergeFormFields
        ''' <summary>
        ''' This sample shows how to insert check boxes and text input form fields during mail merge into a document.
        ''' </summary>
        Friend Class Program
            ''' <summary>
            ''' The main entry point for the application.
            ''' </summary>
            Public Shared Sub Main(ByVal args() As String)
                Dim program As New Program()
                program.Execute()
            End Sub
    
            Private Sub Execute()
                Dim exeDir As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar
                Dim dataDir As String = New Uri(New Uri(exeDir), "../../Data/").LocalPath
    
                ' Load the template document.
                Dim doc As New Document(dataDir & "Template.doc")
    
                ' Setup mail merge event handler to do the custom work.
                doc.MailMerge.FieldMergingCallback = New HandleMergeField()
    
                ' This is the data for mail merge.
                Dim fieldNames() As String = {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber", "Subject", "Body", "Urgent", "ForReview", "PleaseComment"}
                Dim fieldValues() As Object = {"Josh", "Jenny", "123456789", "", "Hello", "<b>HTML Body Test message 1</b>", True, False, True}
    
                ' Execute the mail merge.
                doc.MailMerge.Execute(fieldNames, fieldValues)
    
                ' Save the finished document.
                doc.Save(dataDir & "Template Out.doc")
            End Sub
    
            Private Class HandleMergeField
                Implements IFieldMergingCallback
                ''' <summary>
                ''' This handler is called for every mail merge field found in the document,
                '''  for every record found in the data source.
                ''' </summary>
                Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
                    If mBuilder Is Nothing Then
                        mBuilder = New DocumentBuilder(e.Document)
                    End If
    
                    ' We decided that we want all boolean values to be output as check box form fields.
                    If TypeOf e.FieldValue Is Boolean Then
                        ' Move the "cursor" to the current merge field.
                        mBuilder.MoveToMergeField(e.FieldName)
    
                        ' It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
                        Dim checkBoxName As String = String.Format("{0}{1}", e.FieldName, e.RecordIndex)
    
                        ' Insert a check box.
                        mBuilder.InsertCheckBox(checkBoxName, CBool(e.FieldValue), 0)
    
                        ' Nothing else to do for this field.
                        Return
                    End If
    
                    ' We want to insert html during mail merge.
                    If e.FieldName = "Body" Then
                        mBuilder.MoveToMergeField(e.FieldName)
                        mBuilder.InsertHtml(DirectCast(e.FieldValue, String))
                    End If
    
                    ' Another example, we want the Subject field to come out as text input form field.
                    If e.FieldName = "Subject" Then
                        mBuilder.MoveToMergeField(e.FieldName)
                        Dim textInputName As String = String.Format("{0}{1}", e.FieldName, e.RecordIndex)
                        mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", CStr(e.FieldValue), 0)
                    End If
                End Sub
    
                Private Sub ImageFieldMerging(ByVal args As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
                    ' Do nothing.
                End Sub
    
                Private mBuilder As DocumentBuilder
            End Class
        End Class
    End Namespace
    
    

    public by boxshadow  96683  1  3  1

    Function to Format Phone Number with RegEx and Coldfusion

    Function to Format Phone Number with RegEx and Coldfusion: formatPhone.cfc
    <cfscript>
         component output="false" {
    
            public formatPhone function init(){
                    return this;
                    }
    
    	public string function formatPhone(required string phoneNumber)
    		description="Strips out anything that isn't a number and then takes the first 10 digits and formats them to our spec: (404) 555-1212"
    		output="false" 
    		{
    			var failedReturn = 0;
    			// Strip out everything but the numbers
    			var cleanNumber = REReplaceNoCase(arguments.phoneNumber,"[^0-9]","","All");
    			
    			// area code can't start with a 1 or 0, so remove them if they are at the beginning
    			do{
    				if(Left(cleanNumber,1) EQ 1 OR Left(cleanNumber,1) EQ 0){
    					cleanNumber = right(cleanNumber,len(cleanNumber) - 1);
    				}
    			}
    			while(left(cleanNumber,1) EQ 1 OR left(cleanNumber,1) EQ 0);
    			
    			// If there are stil 10 or more digits left, lets use the left 10 and drop the rest
    			if(len(cleanNumber) LT 10){
    				return failedReturn;
    			}
    			else{
    				cleanNumber = left(cleanNumber,10);
    			}
    			// Format the 10 digits we have
    			cleanNumber = "(#left(cleanNumber,3)#) #mid(cleanNumber,4,3)#-#right(cleanNumber,4)#";
    			return cleanNumber;		
    		}
         }
    </cfscript>
    
    

    public by Geometry  87811  2  4  0

    PubKeyToScript: For POS coins - used to format wallet address pubkey to use in generation transaction's output.

    For POS coins - used to format wallet address pubkey to use in generation transaction's output. nodejs: https://github.com/zone117x/node-stratum-pool/blob/3586ec0d7374b2acc5a72d5ef597da26f0e39d54/lib/util.js#L243 nodejs: http://runnable.com/me/VCFHE0RrZnwbsQ6y
    using System;
    using System.IO;
    using System.Linq;
    using CoiniumServ.Coin.Address;
    using CoiniumServ.Coin.Address.Exceptions;
    using CoiniumServ.Cryptology;
    using CoiniumServ.Utils.Extensions;
    using CoiniumServ.Utils.Numerics;
    using Gibbed.IO;
    using Serilog;
    
    /// <summary>
    /// For POS coins - used to format wallet address pubkey to use in generation transaction's output.
    /// </summary>
    /// <param name="key"></param>
    /// <example>
    /// nodejs: https://github.com/zone117x/node-stratum-pool/blob/3586ec0d7374b2acc5a72d5ef597da26f0e39d54/lib/util.js#L243
    /// nodejs: http://runnable.com/me/VCFHE0RrZnwbsQ6y
    /// </example>
    /// <returns></returns>
    public static byte[] PubKeyToScript(string key)
    {
        var pubKey = key.HexToByteArray();
    
        if (pubKey.Length != 33)
        {
            Log.Error("invalid pubkey length for {0:l}", key);
            return null;
        }
    
        byte[] result;
    
        using (var stream = new MemoryStream())
        {
            stream.WriteValueU8(0x21);
            stream.WriteBytes(pubKey);
            stream.WriteValueU8(0xac);
            result = stream.ToArray();
        }
    
        return result;
    }

    public by Geometry  83217  0  4  0

    Checks for supported pixel format

    Checks for supported pixel format
    // Check for supported pixel format
    private static void CheckPixelFormat(PixelFormat format)
    {
        // check pixel format
        if ((format != PixelFormat.Format8bppIndexed))
        {
            throw new UnsupportedImageFormatException("Unsupported pixel format of the source image.");
        }
    }

    public by Geometry  81824  0  5  0

    GetFormat: Gets the image format most likely associated with a given file name.

    Gets the image format most likely associated with a given file name. The filename in the form "image.jpg". The most likely associated with the given .
    /// <summary>
    ///   Gets the image format most likely associated with a given file name.
    /// </summary>
    /// 
    /// <param name="fileName">The filename in the form "image.jpg".</param>
    /// 
    /// <returns>The <see cref="ImageFormat"/> most likely associated with
    ///   the given <paramref name="fileName"/>.</returns>
    /// 
    public static ImageFormat GetFormat(string fileName)
    {
        string extension = Path.GetExtension(fileName);
    
        if (string.IsNullOrEmpty(extension))
            throw new ArgumentException("Unable to determine file extension for fileName: " + fileName);
    
        switch (extension.ToUpperInvariant())
        {
            case @".BMP":
                return ImageFormat.Bmp;
    
            case @".GIF":
                return ImageFormat.Gif;
    
            case @".ICO":
                return ImageFormat.Icon;
    
            case @".JPG":
            case @".JPEG":
                return ImageFormat.Jpeg;
    
            case @".PNG":
                return ImageFormat.Png;
    
            case @".TIF":
            case @".TIFF":
                return ImageFormat.Tiff;
    
            case @".WMF":
                return ImageFormat.Wmf;
    
            case @".EMF":
                return ImageFormat.Emf;
    
            default:
                throw new NotImplementedException();
        }
    }
    • Public Snippets
    • Channels Snippets