working on it ...

Filters

Explore Public Snippets

Sort by

Found 815 snippets matching: formatting

    public by lbottaro  303328  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 sherazam  228331  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 lbottaro  7639  12  6  0

    How to set a conditional formatting in a cell of Excel document in C#

    This c# code allows to set a conditional formatting for cells in a sheet for a Microsoft Excel document (xls). Conditional formatting allows to set some property to a cell based on the cell value.
    /// <summary>
    /// This method creates a Excel Conditional Formatting for cell
    /// </summary>
    /// <param name="ws">Worksheet to use</param>
    /// <param name="excelList_firstCell">First cell</param>
    /// <param name="excelList_lastCell">Last cell</param>
    /// <param name="condOperator">Operator to use for validation</param>
    /// <param name="condValidation">String to use for validation</param>
    /// <param name="c">Color to use when validating</param>
    private void Excel_createCellFormatValidation(Worksheet ws, string excelList_firstCell, string excelList_lastCell, XlFormatConditionOperator condOperator, string condValidation, Color c)
    {
    	FormatCondition cf = (FormatCondition)ws.get_Range(excelList_firstCell, excelList_lastCell).FormatConditions.Add(XlFormatConditionType.xlCellValue, condOperator, condValidation, Type.Missing);
    	cf.Interior.PatternColorIndex = Constants.xlAutomatic;
    	cf.Interior.Color = ColorTranslator.ToWin32(c);
    	cf.Font.Bold = true;
    }
    
    
    //Example of usage
    
    //cond_passed is a string which value must be present in the cell range to trigger the conditional formatting.
    string cond_passed = "SUCCESS";
    this.Excel_createCellFormatValidation(ws, "C1", "C19", XlFormatConditionOperator.xlEqual, cond_passed, Color.Green);
    

    public by marksimon232  9069  4  9  5

    String reference guide for Swift

    Below are the different examples on Swift strings
    //1.Create empty string
    var str = "" //emtpy string literal
    var str1 = String() //empty string
     
     
    //2.Check if string is empty
    if str.isEmpty
    {
             
    }
     
    //3.Check length of string 
    countElements(str)
     
     
    //4.String Concatenation
     
    var str2 = "Snip2"
    var str3 = "Code"
    var str4 = str2+" "+str3
     
     
    //Iterate through String
    var str2 = "Snip2"
     for char in str2
     {
            println(char) //each character
     }
     
    //5.Iterate through UTF-8
     
    var name = "Mark"; //UTF8-Code 224 164 176 224 164 181 224 164
    for code in name.utf8
    {
        println(code); // each UTF8 code
    }
     
     
     
    //6.Formatting String
    var int1 = 33
    var str5 = "Mark age \(int1)"  //Mark age 33
     
    //7.Comparing Strings
    if str2 == str4
    {
       println("Equal")                
    }

    public by cghersi  2680  2  7  2

    Print in a nice format the given date in C#

    This is how to print the given date in a pretty way. Make sure the input date is in UTC.
    static public string SmartDate(this DateTime dateToPrint, bool longDate = false)
    {
        DateTime now = DateTime.Now.ToUniversalTime();
        TimeSpan deltaTime = now - dateToPrint;
        if (deltaTime.TotalDays >= 7.0)
          return string.Format("on {0}", (longDate) ? dateToPrint.ToString("MMM d, yyyy") : dateToPrint.ToShortDateString());
        if (deltaTime.TotalDays >= 2.0)
          return string.Format("on {0} at {1}", dateToPrint.DayOfWeek.ToString(), dateToPrint.ToLongTimeString());
        if (deltaTime.TotalDays >= 1.0)
            return string.Format("yesterday at {0}", (longDate) ? dateToPrint.ToLongTimeString() : dateToPrint.ToShortTimeString());
        if (deltaTime.TotalHours >= 2.0)
          return string.Format("{0} hours ago", (int)(deltaTime.TotalHours));
        if (deltaTime.TotalHours >= 1.0)
          return string.Format("{0} hour ago", (int)(deltaTime.TotalHours));
        if (deltaTime.TotalMinutes > 1.0)
          return string.Format("{0} minutes ago", (int)(deltaTime.TotalMinutes));
    
        return "just now";
    }
    

    public by Geometry  1416  0  4  0

    handleOtherFormats: Handles formatting for objects other than matrices.

    Handles formatting for objects other than matrices.
    /// <summary>
    ///   Handles formatting for objects other than matrices.
    /// </summary>
    private static string handleOtherFormats(string format, object arg, IFormatProvider culture)
    {
        try
        {
            IFormattable obj = arg as IFormattable;
            if (obj != null)
            {
                return obj.ToString(format, culture);
            }
            else if (arg != null)
            {
                return arg.ToString();
            }
        }
        catch (FormatException e)
        {
            throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
        }
    
        return String.Empty;
    }

    public by jamesmoey  2995  1  4  0

    Ext grid date column with date formatting for human.

    Ext grid date column with date formatting for human.: EasyDateColumn.js
    /**
     * Ext grid column for formatting date that is human friendly.
     */
    Ext.define('Ms.EasyDateColumn', {
        extend: 'Ext.grid.column.Column',
        alias: ['widget.easydatecolumn'],
        requires: ['Ext.Date'],
    
        /**
         * @cfg {String} recentFormat
         * A formatting string as used by {@link Ext.Date#format} to format a Date for this Column, where the date is between
         * yesterday and tomorrow.
         *
         * Default to "H:i:s" e.g 11:14:34  or  Tomorrow, 05:23:12  or  Yesterday, 14:21:43
         */
    
        /**
         * @cfg {String} weekFormat
         * A formatting string as used by {@link Ext.Date#format} to format a Date for this Column that is within 1 week
         * timeframe.
         *
         * Default to "l, H:i" e.g Sunday, 11:14
         */
    
        /**
         * @cfg {String} monthFormat
         * A formatting string as used by {@link Ext.Date#format} to format a Date for this Column that is within this year.
         *
         * Default to "F j, H:i" e.g May 1, 11:14
         */
    
        /**
         * @cfg {String} yearFormat
         * A formatting string as used by {@link Ext.Date#format} to format a Date for this Column that is outside of this year.
         *
         * Default to "F j, y" e.g May 1, 2010
         */
    
        initComponent: function(){
            if (!this.recentFormat) {
                this.recentFormat = 'H:i:s';
            }
    
            if (!this.weekFormat) {
                this.weekFormat = 'l, H:i';
            }
    
            if (!this.monthFormat) {
                this.monthFormat = 'F j, H:i';
            }
    
            if (!this.yearFormat) {
                this.yearFormat = 'F j, y';
            }
    
            this.callParent(arguments);
        },
    
        renderer: function(value, metaData){
            var column = metaData.column;
            var now = new Date();
            var today = new Date(now.getFullYear(), now.getMonth(), now.getDay());
            var startOfThisWeek = new Date(today.getTime() - (60*60*24*6));
            var startOfThisYear = new Date(now.getFullYear(), 0, 1);
            var endOfThisYear = new Date(now.getFullYear(), 11, 31, 23, 59, 59);
            var endOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
            var yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate()-1);
            var tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1, 23, 59, 59);
            if (Ext.Date.between(value, yesterday, tomorrow)) {
                var day;
                if (Ext.Date.between(value, today, endOfToday)) day = '';
                else if (value > endOfToday) day = 'Tomorrow, ';
                else day = 'Yesterday, ';
                return day + Ext.Date.format(value, column.recentFormat);
            } else if (value < now) {
                if (value >= startOfThisWeek) {
                    return Ext.Date.format(value, column.weekFormat);
                } else if (value >= startOfThisYear) {
                    return Ext.Date.format(value, column.monthFormat);
                }
            } else if (value > now) {
                if (value < today.getTime() + (60*60*24*6)) {
                    return 'Coming ' + Ext.Date.format(value, column.weekFormat);
                } else if (value < endOfThisYear) {
                    return Ext.Date.format(value, column.monthFormat);
                }
            }
            return Ext.Date.format(value, column.yearFormat);
        }
    });
    
    

    public by giovanni.gambaro  1743  1  4  1

    Date formatting using ThreadLocal variable

    How to avoid synchronization for a not thread safe classes
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class Foo
    {
        // SimpleDateFormat is not thread-safe, so give one to each thread
        private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
            @Override
            protected SimpleDateFormat initialValue()
            {
                return new SimpleDateFormat("yyyyMMdd HHmm");
            }
        };
    
        public String formatIt(Date date)
        {
            return formatter.get().format(date);
        }
    }

    public by Geometry  1298  0  7  0

    AllowNestedProperties: Enables the display of recursively nested properties in the Windows.Forms' DataGridView control.

    Enables the display of recursively nested properties in the Windows.Forms' DataGridView control. The to enable nested properties. True to use nested properties, false otherwise. This method will register a custom cell formatting event in the DataGridView and retrieve any nested property specified in the column's DataPropertyName propert
    /// <summary>
    ///   Enables the display of recursively nested properties 
    ///   in the Windows.Forms' DataGridView control.
    /// </summary>
    /// 
    /// <param name="dataGridView">The <see cref="DataGridView"/> to enable nested properties.</param>
    /// <param name="value">True to use nested properties, false otherwise.</param>
    /// 
    /// <remarks>
    ///   This method will register a custom cell formatting event in the DataGridView and
    ///   retrieve any nested property specified in the column's DataPropertyName property
    ///   using reflection. This method is based on th idea by Antonio Bello, originally 
    ///   shared in:
    ///   
    ///    http://www.developer-corner.com/2007/07/datagridview-how-to-bind-nested-objects_18.html
    ///    
    /// </remarks>
    /// 
    public static void AllowNestedProperties(this DataGridView dataGridView, bool value)
    {
        if (value)
            dataGridView.CellFormatting += dataGridView1_CellFormatting;
        else
            dataGridView.CellFormatting -= dataGridView1_CellFormatting;
    }

    public by sherazam  2338  0  5  0

    How to Create/Format Forward & Reply Email Messages inside .NET Apps

    This technical tip explains how .NET developers can Create the Forward & Reply Email Messages inside .NET Applications using Aspose.Email for .NET. Aspose.Email API provides the capability of creating and formatting the forward and reply messages. The ReplyMessageBuilder and ForwardMessageBuilder classes of the API are used to create the Reply and
    // Enter here the actual content of the snippet.            
    // Creating Reply Message
    
    //[C# Code Sample]
    
    MapiMessage originalMsg = MapiMessage.FromFile("original.msg");
    
    ReplyMessageBuilder builder = new ReplyMessageBuilder();
    builder.ReplyAll = true;
    builder.AdditionMode = OriginalMessageAdditionMode.Textpart;
    builder.ResponseText = "<p><b>Dear Friend,</b></p> I want to do is introduce my co-author and co-teacher. <p><a href=\"www.google.com\">This is a first link</a></p><p><a href=\"www.google.com\">This is a second link</a></p>";
    MapiMessage replyMsg = builder.BuildResponse(originalMsg);
    
    replyMsg.Save("reply.msg");
    
    //[VB.NET Code Sample]
    
    Dim originalMsg As MapiMessage = MapiMessage.FromFile("original.msg")
    
    Dim builder As New ReplyMessageBuilder()
    builder.ReplyAll = True
    builder.AdditionMode = OriginalMessageAdditionMode.Textpart
    builder.ResponseText = "<p><b>Dear Friend,</b></p> I want to do is introduce my co-author and co-teacher. <p><a href=""www.google.com"">This is a first link</a></p><p><a href=""www.google.com"">This is a second link</a></p>"
    Dim replyMsg As MapiMessage = builder.BuildResponse(originalMsg)
    
    replyMsg.Save("reply.msg")
    
    //Creating Forward Message
    
    //[C# Code Sample]
    
    ForwardMessageBuilder builder = new ForwardMessageBuilder();
    builder.AdditionMode = OriginalMessageAdditionMode.Textpart;
    MapiMessage forwardMsg = builder.BuildResponse(originalMsg);
    forwardMsg.Save("forward.msg");
    
    //[VB.NET Code Sample]
    
    Dim builder As New ForwardMessageBuilder()
    builder.AdditionMode = OriginalMessageAdditionMode.Textpart
    Dim forwardMsg As MapiMessage = builder.BuildResponse(originalMsg)
    forwardMsg.Save("forward.msg")
    
    
    • Public Snippets
    • Channels Snippets