working on it ...

Filters

Explore Public Snippets

Sort by

Found 90 snippets matching: extensible

    public by cghersi modified Jul 2, 2014  7471  1  7  2

    Java SWT: Combobox with AutoSuggestion feature

    This component can be safely used when you want to have a combobox with the capability to display automatic filtered suggestions based on the text already entered. It uses a couple of callback actions so that the caller can specify what to do when ENTER key is hit and how to load suggestions. The call back actions are specified by a simple interf
    package com.snip2code.ui.swt;
    
    import java.util.List;
    import java.util.Random;
    
    import org.apache.log4j.Logger;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.custom.StackLayout;
    import org.eclipse.swt.events.FocusAdapter;
    import org.eclipse.swt.events.FocusEvent;
    import org.eclipse.swt.events.KeyAdapter;
    import org.eclipse.swt.events.KeyEvent;
    import org.eclipse.swt.events.MouseAdapter;
    import org.eclipse.swt.events.MouseEvent;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
    import org.eclipse.swt.graphics.Rectangle;
    import org.eclipse.swt.layout.FillLayout;
    import org.eclipse.swt.layout.GridData;
    import org.eclipse.swt.layout.GridLayout;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.swt.widgets.Control;
    import org.eclipse.swt.widgets.Event;
    import org.eclipse.swt.widgets.Label;
    import org.eclipse.swt.widgets.Listener;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.widgets.Table;
    import org.eclipse.swt.widgets.TableItem;
    import org.eclipse.swt.widgets.Text;
    
    import com.snip2code.utils.Utils;
    
    
    /**
     * (c) 2011 snip2code inc.
     * This software is property of snip2code inc. Use or reproduction without permission is prohibited 
     *
     * This widget creates a textfield with an autosuggestion feature.
     * The list of suggestion is shown when the user clicks on the text field or starts typing in the text field
     */
    public class AutoSuggestionComposite extends Composite {
    
    	protected static Logger log = Logger.getLogger(AutoSuggestionComposite.class);
    	
    	private Composite textBoxStackPanel;
    	private StackLayout textboxLayout;
    	private Text textBox;
    	private Label tooltip;
    	private Shell popupShell;
    	private Table table;
    	private String tooltipMsg;
    
    	private ICallback<String, List<String>> loadSuggestionAction;
    	private ICallback<String, String> onEnterAction;
    	
    	private String text;
    	private int numOfDisplayedSuggestions;
    	
    	private static final String POPUPVISIB = "$$$POPUP_VISIB";
    	
    	private String uniqueID; //used to differentiate AutoSuggestion composites in the same dialog
    	private static Random rdn = new Random();
    	
    	/**
    	 * Create the dialog.
    	 * @param parent
    	 * @param style
    	 * @param tooltipMsg message to display when no input is entered
    	 * @param numOfDisplayedSuggestions masimum number of items suggested in the popup of suggestions
    	 * @param loadSuggestionAction callback to routine that loads the suggestions for autocomplete
    	 * @param onEnterAction callback when enter is pressed on the textbox
    	 */
    	public AutoSuggestionComposite(Composite parent, int style, String tooltipMsg, int numOfDisplayedSuggestions, 
    			ICallback<String, List<String>> loadSuggestionAction, ICallback<String, String> onEnterAction) {
    		super(parent, style);
    
    		textboxLayout = new StackLayout();
    		this.loadSuggestionAction = loadSuggestionAction;
    		this.onEnterAction = onEnterAction;
    		this.numOfDisplayedSuggestions = numOfDisplayedSuggestions;
    		this.tooltipMsg = tooltipMsg;
    		
    		uniqueID = rdn.nextInt() + tooltipMsg;
    		
    		createDialogArea();
    	}
    	
    	private void createDialogArea() {
    		this.setBackground(SWTUIUtilities.WHITE);
    		GridLayout gridLayout = new GridLayout();
    		gridLayout.marginHeight = 0;
    		gridLayout.marginWidth = 0;
    		this.setLayout(gridLayout);
    
    		//Panel with textbox and tooltip:
    		textBoxStackPanel = new Composite(this, SWT.NONE);
    		textBoxStackPanel.setLayout(textboxLayout);
    		GridData gdPanel = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
    		gdPanel.verticalIndent = 2;
    		textBoxStackPanel.setLayoutData(gdPanel);
    		
    		tooltip = new Label(textBoxStackPanel, SWT.NONE);
    		tooltip.setBackground(SWTUIUtilities.WHITE);
    		tooltip.setForeground(SWTUIUtilities.LIGHT_GREY);
    		tooltip.setFont(SWTUIUtilities.LBL_TEXT);
    		tooltip.setText(" " + tooltipMsg); //manual horizontal indent, cause StackLayout doesn't allow this feature
    		tooltip.addMouseListener(new MouseAdapter() {
    			@Override
    			public void mouseDown(MouseEvent e) {
    				setControlVisib(textBox, true);
    				textBoxStackPanel.layout();
    				textBox.setFocus();
    				loadSuggestions(null);
    			}
    		});
    		
    		textBox = new Text(textBoxStackPanel, SWT.NONE);
    		textBox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
    		textBox.setFont(SWTUIUtilities.LBL_TEXT);
    		textBox.setBackground(SWTUIUtilities.WHITE);
    		textBox.setData(POPUPVISIB, uniqueID);
    		
    		//popup for suggestions:
    		popupShell = new Shell(getShell().getDisplay(), SWT.ON_TOP);
    		popupShell.setLayout(new FillLayout());
    		popupShell.setData(POPUPVISIB, uniqueID);
    		popupShell.setBackground(SWTUIUtilities.WHITE);
    		table = new Table(popupShell, SWT.SINGLE);
        	table.getVerticalBar().setVisible(false);
    		table.setFont(SWTUIUtilities.LBL_TEXT);
    		table.setData(POPUPVISIB, uniqueID);
    		for (int i = 0; i < numOfDisplayedSuggestions; i++) {
    			new TableItem(table, SWT.NONE);
    		}
    		
    		//Key Listener for Keyboards events:
    		textBox.addKeyListener(new KeyAdapter() {
    			@Override
    			public void keyReleased(KeyEvent e) {
    				boolean loadSuggestions = true;
    				saveInput();
    				switch (e.keyCode) {
    					case SWT.ARROW_DOWN:
    						int index = (table.getSelectionIndex() + 1) % table.getItemCount();
    						table.setSelection(index);
    						e.doit = false;
    						break;
    					case SWT.ARROW_UP:
    						index = table.getSelectionIndex() - 1;
    						if (index < 0) 
    							index = table.getItemCount() - 1;
    						table.setSelection(index);
    						e.doit = false;
    						break;
    					case SWT.CR:
    					case SWT.LF:
    					case 16777296: //enter in numeric keypad
    						if (popupShell.isVisible() && table.getSelectionIndex() != -1) {
    							textBox.setText(table.getSelection()[0].getText());
    						}
    						
    						loadSuggestions = false;
    						execEnterAction();
    
    						break;
    					case SWT.ESC:
    						popupShell.setVisible(false);
    						break;
    				}
    
    				//only for printable characters, load search history:
    				if (loadSuggestions && (e.keyCode < 256))
    					loadSuggestions(textBox.getText());
    				
    				log.debug("End of key listener");
    			}
    		});
    		
    		//make sure the input entered in the text box is saved and ready to use:
    		textBox.addFocusListener(new FocusAdapter() {
    			@Override
    			public void focusLost(FocusEvent e) {
    				log.debug("Focus lost by textbox of autosugg from " + tooltipMsg);
    				saveInput();
    				checkTooltipVisib();
    				handleFocusLost();
    			}
    			
    			@Override
    			public void focusGained(FocusEvent e) {
    				if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    					return;
    				log.debug("Focus gained by textbox of autosugg from " + tooltipMsg);
    				loadSuggestions(textBox.getText());
    			}
    		});
    		textBox.addSelectionListener(new SelectionAdapter() {
    			@Override
    			public void widgetSelected(SelectionEvent e) {
    				checkTooltipVisib();
    			}
    		});
    		
    		table.addListener(SWT.DefaultSelection, new Listener() {
    			public void handleEvent(Event event) {
    				textBox.setText(table.getSelection()[0].getText());
    				execEnterAction();
    			}
    		});
    		
    		//hide the popup of suggestions if the focus is out:
    		Listener focusOutListener = new Listener() {
    			public void handleEvent(Event event) {
    				handleFocusLost();
    			}
    		};
    		table.addListener(SWT.FocusOut, focusOutListener);
    		textBox.addListener(SWT.FocusOut, focusOutListener);
    		textBoxStackPanel.addListener(SWT.FocusOut, focusOutListener);
    		popupShell.addListener(SWT.FocusOut, focusOutListener);
    		this.addListener(SWT.FocusOut, focusOutListener);
    
    		getShell().addListener(SWT.Move, new Listener() {
    			public void handleEvent(Event event) {
    				popupShell.setVisible(false);
    				checkTooltipVisib();
    			}
    		});
    		
    		checkTooltipVisib();
    	}
    	
    	private void handleFocusLost() {
    		/* async is needed to wait until focus reaches its new Control */
    		if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    			return;
    		getShell().getDisplay().asyncExec(new Runnable() {
    			public void run() {
    				log.debug("Running handleFocusLost for " + tooltipMsg);
    				if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    					return;
    				Control control = getShell().getDisplay().getFocusControl();
    				log.debug("handleFocusLost for " + tooltipMsg + ": control is " + control + ";uniqueID:" + uniqueID);
    				if ((control == null) || (control.getData(POPUPVISIB) == null) || 
    					!control.getData(POPUPVISIB).toString().equals(uniqueID)) {
    					popupShell.setVisible(false);
    				}					
    			}
    		});
    	}
    	
    	/**
    	 * Determines the visibility of textbox content vs tooltip when the textbox is empty
    	 */
    	public void checkTooltipVisib() {
    		if (Utils.isNullOrEmpty(textBox.getText())) 
    			setControlVisib(tooltip, true);
    		else
    			setControlVisib(textBox, true);
    		textBoxStackPanel.layout();
    	}
    	
    	private void execEnterAction() {
    		saveInput();
    		popupShell.setVisible(false);
    		onEnterAction.exec(text);
    	}
    	
        private void loadSuggestions(String prefix) {
        	log.debug("loading suggestions for " + prefix);
    
    //		if (Utils.isNullOrEmpty(prefix))
    //			return;
        	
        	Rectangle textBounds = getShell().getDisplay().map(textBoxStackPanel, null, textBox.getBounds());
        	
    		//load suggestions:
        	List<String> suggestions = loadSuggestionAction.exec(prefix);
        	log.debug("loaded " + suggestions.size() + " suggestions");
        	
        	table.setItemCount(suggestions.size());
    		TableItem[] items = table.getItems();
    		int maxWidthOfItem = 0;
    		log.debug("Changing " + items.length + " items in TablePopup");
    		for (int i = 0; i < items.length; i++) {
    			if (i < suggestions.size()) {
    				String sugg = suggestions.get(i);
    				if (!Utils.isNullOrEmpty(sugg)) {
    					items[i].setText(sugg);
    					int w = items[i].getBounds().width;
    					if (w > maxWidthOfItem)
    						maxWidthOfItem = w;
    				}
    			}
    		}
    //		//avoid the display of horizontal scrollbar when not needed (10 is the width of the scrollbar)
    //		if ((maxWidthOfItem + 10) < textBounds.width)
    //			table.pack();
    		
    		//23 pixels is the height of 1 item in the drop down list; 
    		//always add a blank line at the end of the list to improve readability
    		int popupHeight = (suggestions.size() + 1) * 23; 
    		log.debug("popupHeight for [" + this.tooltipMsg + "]:" + popupHeight);
    		if (popupHeight <= 46)
    			popupHeight = 46; 
    	
    		//set a cap to the maximum height of the popup (17 lines):
    		if (popupHeight > 391) {
    			popupHeight = 391;
    			table.getVerticalBar().setVisible(true);
    		} else {
    			//avoid the display of horizontal scrollbar when not needed (10 is the width of the scrollbar)
    			if ((maxWidthOfItem + 10) < textBounds.width)
    				table.pack();
    			table.getVerticalBar().setVisible(false);
    		}
    		
    		log.debug("setBounds popup:" + textBounds.x + ";" + (textBounds.y + textBounds.height + 4) + ";" + 
    					textBounds.width + ";" + popupHeight);
    		popupShell.setBounds(textBounds.x, textBounds.y + textBounds.height + 4, textBounds.width, popupHeight);
    		popupShell.setVisible(true);		
        }
        
    	private void setControlVisib(Control c, boolean visible) {
    		if (c == null)
    			return;
    		
    		if (visible) 
    			textboxLayout.topControl = c;
    	}
    	
    	private void saveInput() {
    		text = textBox.getText();
    		if (text == null)
    			text = "";
    		text = text.trim();
    	}
    	
    	/**
    	 * Returns the content of the textbox
    	 */
    	public String getText() {
    		return text;
    	}
    	
    	/**
    	 * Sets the content of the textbox
    	 */
    	public void setText(String text) {
    		this.text = text;
    		textBox.setText(text);
    		setControlVisib(textBox, true);
    	}
    	
    	/**
    	 * Hides the popup of suggestions
    	 */
    	public void hideSuggestions() {
    		popupShell.setVisible(false);
    	}
    	
    	@Override
    	public void dispose() {
    		if (popupShell != null) {
    			hideSuggestions();
    			popupShell.dispose();
    		}
    
    		super.dispose();
    	}
    }

    public by sherazam modified Feb 24, 2016  2396  0  6  0

    How to Read and Write XMP Data to Images inside .NET Apps

    // Enter here the actual content of the snippet.//Create XMP Metadata, Write It And Read From File
    
    //[C# Code Sample]
    
    // Specify the size of image by defining a Rectangle 
    Aspose.Imaging.Rectangle rect = new Aspose.Imaging.Rectangle(0, 0, 100, 200);
    
    TiffOptions tiffOptions = new TiffOptions(TiffExpectedFormat.TiffJpegRGB);
    tiffOptions.Photometric = TiffPhotometrics.MinIsBlack;
    tiffOptions.BitsPerSample = new ushort[] { 8 };
    
    // create the brand new image just for sample purposes
    using (var image = new TiffImage(new TiffFrame(tiffOptions, rect.Width, rect.Height)))
    {
          // create an instance of XMP-Header
          Aspose.Imaging.Xmp.XmpHeaderPi xmpHeader = new Aspose.Imaging.Xmp.XmpHeaderPi(System.Guid.NewGuid().ToString());
    
          // create an instance of Xmp-TrailerPi 
          Aspose.Imaging.Xmp.XmpTrailerPi xmpTrailer = new Aspose.Imaging.Xmp.XmpTrailerPi(true);
    
          // create an instance of XMPmeta class to set different attributes
          Aspose.Imaging.Xmp.XmpMeta xmpMeta = new Aspose.Imaging.Xmp.XmpMeta();
          xmpMeta.AddAttribute("Author", "Mr Smith");
          xmpMeta.AddAttribute("Description", "The fake metadata value");
    
          // create an instance of XmpPacketWrapper that contains all metadata
          Aspose.Imaging.Xmp.XmpPacketWrapper xmpData = new Aspose.Imaging.Xmp.XmpPacketWrapper(xmpHeader, xmpTrailer, xmpMeta);
    
          // create an instacne of Photoshop package and set photoshop attributes
          Aspose.Imaging.Xmp.Schemas.Photoshop.PhotoshopPackage photoshopPackage = new Aspose.Imaging.Xmp.Schemas.Photoshop.PhotoshopPackage();
          photoshopPackage.SetCity("London");
          photoshopPackage.SetCountry("England");
          photoshopPackage.SetColorMode(Aspose.Imaging.Xmp.Schemas.Photoshop.ColorMode.Rgb);
          photoshopPackage.SetCreatedDate(DateTime.UtcNow);
    
          // add photoshop package into XMP metadata
          xmpData.AddPackage(photoshopPackage);
    
          // create an instacne of DublinCore package and set dublinCore attributes
          Aspose.Imaging.Xmp.Schemas.DublinCore.DublinCorePackage dublinCorePackage = new Aspose.Imaging.Xmp.Schemas.DublinCore.DublinCorePackage();
          dublinCorePackage.SetAuthor("Charles Bukowski");
          dublinCorePackage.SetTitle("Confessions of a Man Insane Enough to Live With the Beasts");
          dublinCorePackage.AddValue("dc:movie", "Barfly");
    
          // add dublinCore Package into XMP metadata
          xmpData.AddPackage(dublinCorePackage);
    
          using (var ms = new MemoryStream())
          {
                        // update XMP metadata into image
                        image.XmpData = xmpData;
    
                        // Save image on the disk or in memory stream
                        image.Save(ms);
    
                        ms.Seek(0, System.IO.SeekOrigin.Begin);
    
                        // Load the image from moemory stream or from disk to read/get the metadata
                        using (var img = (TiffImage)Aspose.Imaging.Image.Load(ms))
                        {
                            // getting the XMP metadata
                            Aspose.Imaging.Xmp.XmpPacketWrapper imgXmpData = img.XmpData;
                            foreach (Aspose.Imaging.Xmp.XmpPackage package in imgXmpData.Packages)
                            {
                                // use package data ...
                            }
                        }
         }
    }
     
    //[VB.NET Code Sample]
    
    ' Specify the size of image by defining a Rectangle 
    Dim rect As New Aspose.Imaging.Rectangle(0, 0, 100, 200)
    
    Dim tiffOptions As New TiffOptions(TiffExpectedFormat.TiffJpegRGB)
    tiffOptions.Photometric = TiffPhotometrics.MinIsBlack
    tiffOptions.BitsPerSample = New UShort() {8}
    
    ' create the brand new image just for sample purposes
    Using image = New TiffImage(New TiffFrame(tiffOptions, rect.Width, rect.Height))
    	' create an instance of XMP-Header
    	Dim xmpHeader As New Aspose.Imaging.Xmp.XmpHeaderPi(System.Guid.NewGuid().ToString())
    
    	' create an instance of Xmp-TrailerPi 
    	Dim xmpTrailer As New Aspose.Imaging.Xmp.XmpTrailerPi(True)
    
    	' create an instance of XMPmeta class to set different attributes
    	Dim xmpMeta As New Aspose.Imaging.Xmp.XmpMeta()
    	xmpMeta.AddAttribute("Author", "Mr Smith")
    	xmpMeta.AddAttribute("Description", "The fake metadata value")
    
    	' create an instance of XmpPacketWrapper that contains all metadata
    	Dim xmpData As New Aspose.Imaging.Xmp.XmpPacketWrapper(xmpHeader, xmpTrailer, xmpMeta)
    
    	' create an instacne of Photoshop package and set photoshop attributes
    	Dim photoshopPackage As New Aspose.Imaging.Xmp.Schemas.Photoshop.PhotoshopPackage()
    	photoshopPackage.SetCity("London")
    	photoshopPackage.SetCountry("England")
    	photoshopPackage.SetColorMode(Aspose.Imaging.Xmp.Schemas.Photoshop.ColorMode.Rgb)
    	photoshopPackage.SetCreatedDate(DateTime.UtcNow)
    
    	' add photoshop package into XMP metadata
    	xmpData.AddPackage(photoshopPackage)
    
    	' create an instacne of DublinCore package and set dublinCore attributes
    	Dim dublinCorePackage As New Aspose.Imaging.Xmp.Schemas.DublinCore.DublinCorePackage()
    	dublinCorePackage.SetAuthor("Charles Bukowski")
    	dublinCorePackage.SetTitle("Confessions of a Man Insane Enough to Live With the Beasts")
    	dublinCorePackage.AddValue("dc:movie", "Barfly")
    
    	' add dublinCore Package into XMP metadata
    	xmpData.AddPackage(dublinCorePackage)
    
    	Using ms = New MemoryStream()
    		' update XMP metadata into image
    		image.XmpData = xmpData
    
    		' Save image on the disk or in memory stream
    		image.Save(ms)
    
    		ms.Seek(0, System.IO.SeekOrigin.Begin)
    
    		' Load the image from moemory stream or from disk to read/get the metadata
    		Using img = DirectCast(Aspose.Imaging.Image.Load(ms), TiffImage)
    			' getting the XMP metadata
    			Dim imgXmpData As Aspose.Imaging.Xmp.XmpPacketWrapper = img.XmpData
    					' use package data ...
    			For Each package As Aspose.Imaging.Xmp.XmpPackage In imgXmpData.Packages
    			Next
    		End Using
    	End Using
    End Using
    
    

    public by sherazam modified Mar 24, 2016  2259  0  5  0

    How to Convert GIFF Image Frame to WebP Image inside .NET Applications

    // Enter here the actual content of the snippet.            
    // Converting GIFF Image Frame to WebP Image
    //[C# Code Sample]
    
    // Load GIFF image into the instance of image class.
    using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"D:\animation.gif"))
    {
          // Create an instance of GIFF image class.
          Aspose.Imaging.FileFormats.Gif.GifImage gif = image as Aspose.Imaging.FileFormats.Gif.GifImage;
    
          if (gif == null) return;
    
          // Load an existing WebP image into the instance of WebPImage class.
          using (Aspose.Imaging.FileFormats.Webp.WebPImage webp = new Aspose.Imaging.FileFormats.Webp.WebPImage(image.Width, image.Height, null))
          {
                 // Loop through the GIFF frames
                 for (int i = 0; i < gif.Blocks.Length; i++)
                 {
                        // Convert GIFF block to GIFF Frame
                        Aspose.Imaging.FileFormats.Gif.Blocks.GifFrameBlock gifBlock = gif.Blocks[i] as Aspose.Imaging.FileFormats.Gif.Blocks.GifFrameBlock;
                        if (gifBlock == null)
                        {
                                continue;
                        }
    
                        // Create an instance of WebP Frame instance by passing GIFF frame to class constructor.
                        Aspose.Imaging.FileFormats.Webp.WebPFrameBlock block = new Aspose.Imaging.FileFormats.Webp.WebPFrameBlock(gifBlock)
                        {
                                Top = (short)gifBlock.Top,
                                Left = (short)gifBlock.Left,
                               Duration = (short)gifBlock.ControlBlock.DelayTime
                        };
    
                        // Add WebP frame to WebP image block list
                        webp.AddBlock(block);
                }
    
                // Set Properties of WebP image.
                webp.Options.AnimBackgroundColor = 0xff; //black
                webp.Options.AnimLoopCount = 0; //infinity
                webp.Options.Quality = 50;
                webp.Options.Lossless = false;
    
                // Save WebP image.
                webp.Save(@"D:\saveAnimation.webp");
          }
    }
     
    //[VB.NET Code Sample]
    
    ' Load GIFF image into the instance of image class.
    Using image As Aspose.Imaging.Image = Aspose.Imaging.Image.Load("D:\animation.gif")
    
    	' Create an instance of GIFF image class.
    	Dim gif As Aspose.Imaging.FileFormats.Gif.GifImage = TryCast(image, Aspose.Imaging.FileFormats.Gif.GifImage)
    
    	If gif Is Nothing Then
    		Return
    	End If
    
    	' Load an existing WebP image into the instance of WebPImage class.
    	Using webp As New Aspose.Imaging.FileFormats.Webp.WebPImage(image.Width, image.Height, Nothing)
    		' Loop through the GIFF frames
    		For i As Integer = 0 To gif.Blocks.Length - 1
    			' Convert GIFF block to GIFF Frame
    			Dim gifBlock As Aspose.Imaging.FileFormats.Gif.Blocks.GifFrameBlock = TryCast(gif.Blocks(i), Aspose.Imaging.FileFormats.Gif.Blocks.GifFrameBlock)
    			If gifBlock Is Nothing Then
    				Continue For
    			End If
    
    			' Create an instance of WebP Frame instance by passing GIFF frame to class constructor.
    			Dim block As New Aspose.Imaging.FileFormats.Webp.WebPFrameBlock(gifBlock) With { _
    				Key .Top = CShort(gifBlock.Top), _
    				Key .Left = CShort(gifBlock.Left), _
    				Key .Duration = CShort(gifBlock.ControlBlock.DelayTime) _
    			}
       
                            ' Add WebP frame to WebP image block list
    			webp.AddBlock(block)
    		Next
    
    		' Set Properties of WebP image.
    		webp.Options.AnimBackgroundColor = &Hff
    		'black
    		webp.Options.AnimLoopCount = 0
    		'infinity
    		webp.Options.Quality = 50
    		webp.Options.Lossless = False
    
    		' Save WebP image.
    		webp.Save("D:\saveAnimation.webp")
    	End Using
    End Using
    
    

    public by msdn modified Jan 12, 2015  729  0  6  0

    GetRegisteredTasks: Returns all available messaging runtime extension tasks.

    Returns all available messaging runtime extension tasks. The extensible owner object that aggregates this extension. The messaging runtime extension tasks discovered by this factory component.
    /// <summary>
    /// Returns all available messaging runtime extension tasks.
    /// </summary>
    /// <param name="owner">The extensible owner object that aggregates this extension.</param>
    /// <returns>The messaging runtime extension tasks discovered by this factory component.</returns>
    public static IList<IMessagingRuntimeExtenderTask> GetRegisteredTasks(IMessagingRuntimeExtension owner)
    {
        IList<IMessagingRuntimeExtenderTask> runtimeTasks = new List<IMessagingRuntimeExtenderTask>(16);
    
        runtimeTasks.Add(new ExecuteRulesEnginePolicyTask(owner));
        runtimeTasks.Add(new ExternalComponentInvokeTask(owner));
        runtimeTasks.Add(new CreateResponseTask(owner));
        runtimeTasks.Add(new BeginTrackingActivityTask(owner));
        runtimeTasks.Add(new UpdateTrackingActivityTask(owner));
        runtimeTasks.Add(new CompleteTrackingActivityTask(owner));
        runtimeTasks.Add(new PromoteContextPropertyTask(owner));
        runtimeTasks.Add(new BlockMessageTask(owner));
    
        return runtimeTasks;
    }

    external by Krzysztof Bak modified Jun 22, 2015  162724  9  3  0

    Jenkins groovy script to get a list of latest git branches (with release/ prefix) and latest tags for a GitLab managed repository, usable with Jenkins Extensible Choice plugin and gitflow.

    Jenkins groovy script to get a list of latest git branches (with release/ prefix) and latest tags for a GitLab managed repository, usable with Jenkins Extensible Choice plugin and gitflow.: gitlab-list.groovy
    #!/usr/bin/env groovy
    
    /**
    * CONFIGURATION
    */
    def private_token = "secret_token_from_gitlab"
    def repository = "group/repository-name"
    /* CONFIGURATION END */
    
    def repository_name = repository.replace("/", "%2F");
    
    def api_tags = new URL("http://gitlab/api/v3/projects/" + repository_name + "/repository/tags?private_token=" + private_token).text
    def api_branches = new URL("http://gitlab/api/v3/projects/" + repository_name + "/repository/branches?private_token=" + private_token).text
    
    tags_list = new groovy.json.JsonSlurper().parseText(api_tags)
    branches_list = new groovy.json.JsonSlurper().parseText(api_branches)
    
    /* Get only branches with "release/" prefix */
    def branchesMatch = "^release/.*"
    def matched_branches = branches_list.findAll { it.name =~ /$branchesMatch/ }
    
    def b = matched_branches.sort{ it.commit.committed_date }.reverse().take(5)
    def t = tags_list.sort{ it.commit.committed_date }.reverse().take(10).each{ it.name = "tags/" + it.name}
    
    def results = (t << b).sort{ it.commit.committed_date }.reverse().flatten()
    
    return results.name
    
    

    external by pepijnkokke modified Sep 8, 2015  264  0  3  0

    AB grammars and extensible effects can do some fun things—depends on Eff1.hs found on <http://okmij.org/ftp/Haskell/extensible/>

    AB grammars and extensible effects can do some fun things—depends on Eff1.hs found on : AB_grammar.hs
    {-# LANGUAGE TemplateHaskell, QuasiQuotes, FlexibleInstances, FlexibleContexts,
                 TypeFamilies, GADTs, TypeOperators, DataKinds, PolyKinds, RankNTypes,
                 KindSignatures, UndecidableInstances, StandaloneDeriving,
                 RecordWildCards, DeriveFunctor, DeriveFoldable, DeriveTraversable  #-}
    module AB where
    
    
    import           Prelude hiding (lookup, lex)
    import           Control.Applicative ((<|>),empty)
    import           Data.Maybe (maybeToList)
    import           Data.Singletons.Decide (Decision(..),(:~:)(..),(%~))
    import           Data.Singletons.Prelude
    import           Data.Singletons.TH (singletons)
    import           Eff1 (Eff,Reader,Writer,ask,tell,run,runReader,runWriter)
    import           Text.Parsec (char,letter,spaces,many1,chainr1)
    import qualified Text.Parsec (parse)
    
    
    -- * Syntactic & Semantic Types
    
    singletons [d|
    
      data SynT = S | N | NP | SynT :-> SynT | SynT :<- SynT deriving (Show,Eq)
      data SemT = E | T | SemT :=> SemT deriving (Show,Eq)
    
      |]
    
    infixr 5 :->
    infixl 5 :<-
    infixr 5 :=>
    
    type S      = 'S
    type N      = 'N
    type NP     = 'NP
    type IV     = NP :-> S
    type TV     = IV :<- NP
    type a :-> b = a ':-> b
    type b :<- a = b ':<- a
    
    sS  :: SSynT S
    sS  = SS
    sN  :: SSynT N
    sN  = SN
    sNP :: SSynT NP
    sNP = SNP
    mNP :: SSynT (NP :<- NP)
    mNP = SNP :%<- SNP
    sIV :: SSynT IV
    sIV = SNP :%-> SS
    sTV :: SSynT TV
    sTV = sIV :%<- SNP
    
    type E      = 'E
    type T      = 'T
    type a :=> b = a ':=> b
    
    
    -- * Translation from Syntactic to Semantic Types
    
    type family Tr (t :: SynT) :: SemT where
      Tr 'S        = 'T
      Tr 'N        = 'E ':=> 'T
      Tr 'NP       = 'E
      Tr (a ':-> b) = Tr a ':=> Tr b
      Tr (b ':<- a) = Tr a ':=> Tr b
    
    data Typed (expr :: SemT -> *) where
      Typed :: (SSynT a, expr (Tr a)) -> Typed expr
    
    
    -- * Parse Trees
    
    data Tree a where
      Leaf :: a -> Tree a
      Node :: Tree a -> Tree a -> Tree a
    
    deriving instance (Show a) => (Show (Tree a))
    deriving instance (Functor Tree)
    deriving instance (Foldable Tree)
    deriving instance (Traversable Tree)
    
    
    -- * Lexicon & Parsing
    
    data Lexicon expr = Lexicon
      { lookup :: String -> [Typed expr]
      , apply  :: forall a b. expr (a :=> b) -> expr a -> expr b
      }
    
    
    maybeApply :: Lexicon expr -> Typed expr -> Typed expr -> Maybe (Typed expr)
    maybeApply lex (Typed (a1,x)) (Typed (a2 :%-> b,f)) =
      case a1 %~ a2 of
        Proved Refl -> pure (Typed (b, apply lex f x))
        _           -> empty
    maybeApply lex (Typed (b :%<- a1,f)) (Typed (a2,x)) =
      case a1 %~ a2 of
        Proved Refl -> pure (Typed (b, apply lex f x))
        _           -> empty
    maybeApply _ _ _ = empty
    
    
    parse :: Lexicon expr -> String -> SSynT a -> [expr (Tr a)]
    parse lex str a1 =
      case Text.Parsec.parse sent "" str of
        Left  _ -> empty
        Right t -> exec =<< (comp =<< traverse (lookup lex) t)
      where
        exec (Typed (a2,x)) =
          case a1 %~ a2 of
            Proved Refl -> pure x
            _           -> empty
    
        comp (Leaf e)     = pure e
        comp (Node t1 t2) =
          do e1 <- comp t1; e2 <- comp t2; maybeToList (maybeApply lex e1 e2)
    
        sent = chainr1 atom node
          where
            word = Leaf <$> many1 letter
            atom = word <|> (char '(' *> (sent <* char ')'))
            node = pure Node <* spaces
    
    
    
    -- * Example using Eff in Haskell
    
    data Entity = Tim | Bob
    
    data Pred where
      Like   :: Entity -> Entity -> Pred
      Stupid :: Entity -> Pred
    
    deriving instance Show Entity
    deriving instance Show Pred
    
    
    type family ToEff r t :: * where
      ToEff r E        = Eff r Entity
      ToEff r T        = Eff r Pred
      ToEff r (a :=> b) = ToEff r a -> ToEff r b
    
    newtype Ext r a = Ext (ToEff r a)
    
    type RW = (Reader Entity ': Writer Pred ': '[])
    
    
    -- * Example using freer monad, more extensible effects
    
    lex :: String -> [Typed (Ext RW)]
    lex "tim"    = pure (Typed (sNP , Ext (pure Tim)))
    lex "bob"    = pure (Typed (sNP , Ext (pure Bob)))
    lex "likes"  = pure (Typed (sTV , Ext (\y x -> Like <$> x <*> y)))
    lex "stupid" = pure (Typed (mNP , Ext (\x -> x >>= \x -> tell (Stupid x) *> pure x)))
    lex "him"    = pure (Typed (sNP , Ext ask))
    
    app :: (ToEff r t ~ (ToEff r a -> ToEff r b)) => Ext r t -> Ext r a -> Ext r b
    app (Ext f) (Ext x) = Ext (f x)
    
    ext :: Lexicon (Ext RW)
    ext = Lexicon { lookup = lex, apply = app }
    
    runExt :: Ext RW T -> Entity -> (Pred, [Pred])
    runExt (Ext e) x = run (runWriter (runReader e x))
    
    s1 :: [(Pred, [Pred])]
    s1 = runExt <$> parse ext "(stupid bob) likes him" SS <*> pure Tim
    -- [(Like Bob Tim,[Stupid Bob])]
    
    
    -- -}
    -- -}
    -- -}
    -- -}
    -- -}
    
    
    

    external by Barney Carroll modified Feb 1, 2016  184  0  2  0

    Ember plugin: Extensible className additions http://discuss.emberjs.com/t/extensible-classname-additions/9601

    Ember plugin: Extensible className additions http://discuss.emberjs.com/t/extensible-classname-additions/9601: ember.classy.js
    import Ember from 'ember'
    
    const pushTo = key => ( ...items ) =>
      Ember.Mixin.create( {
        init(){
          this._super( ...arguments )
    
          this[ key ].push( ...items )
        }
      } )
    
    const names    = pushTo( 'classNames' )
    const bindings = pushTo( 'classNameBindings' )
    
    export default Object.assign( names, { names, bindings } )
    
    

    external by funnelback modified Sep 30, 2014  45  0  1  0

    Uses Bootstrap markup patterns to create a 'Sort' dropdown. All existing CGI parameters are preserved, except for 'sort' and 'start_rank'. Examples provided for common sort modes. Extensible to sort by arbitrary metadata fields.

    Uses Bootstrap markup patterns to create a 'Sort' dropdown. All existing CGI parameters are preserved, except for 'sort' and 'start_rank'. Examples provided for common sort modes. Extensible to sort by arbitrary metadata fields.: freemarker-sort-snippet
    <#-- SORT MODES -->
    <div class="dropdown pull-right">
      <a class="dropdown-toggle text-muted" data-toggle="dropdown" href="#" id="dropdown-sortmode" title="Sort">
      <small><span class="glyphicon glyphicon-sort"></span>&nbsp;Sort</small>
      </a>
      <ul class="dropdown-menu" role="menu" aria-labelledby="dropdown-sortmode">
        <li role="menuitem"><a href="${question.collection.configuration.value("ui.modern.search_link")}?${removeParam(QueryString,["start_rank","sort"])?html}"><span class="glyphicon glyphicon-sort-by-attributes-alt"></span> Relevance</a></li>
        <li role="menuitem"><a href="${question.collection.configuration.value("ui.modern.search_link")}?${removeParam(QueryString,["start_rank","sort"])?html}&amp;sort=date"><span class="glyphicon glyphicon-sort-by-order-alt"></span> Recency</a></li>
        <li role="menuitem"><a href="${question.collection.configuration.value("ui.modern.search_link")}?${removeParam(QueryString,["start_rank","sort"])?html}&amp;sort=title"><span class="glyphicon glyphicon-sort-by-alphabet"></span> Title (A-Z)</a></li>
        <li role="menuitem"><a href="${question.collection.configuration.value("ui.modern.search_link")}?${removeParam(QueryString,["start_rank","sort"])?html}&amp;sort=dtitle"><span class="glyphicon glyphicon-sort-by-alphabet-alt"></span> Title (Z-A)</a></li>
        <li role="menuitem"><a href="${question.collection.configuration.value("ui.modern.search_link")}?${removeParam(QueryString,["start_rank","sort"])?html}&amp;sort=shuffle"><span class="glyphicon glyphicon-random"></span> Shuffle</a></li>
      </ul>
    </div>
    
    

    external by doubleshow modified May 21, 2015  45  0  1  0

    Hinge, extensible

    Hinge, extensible: index.xml
    <craft>
        <parameter name="n" default="5" type="int"/>
        <craft name="female" src="female.xml"/>
        <craft name="male" src="male.xml"/>
        
        <row transform="scale(0.75,0.75,0.75)">
            <repeat n="{{n}}">
                <column spacing="5">
                    <female color="yellow"></female>
                    <male color="red" transform="rotateX(180)"></male>
                </column>
            </repeat>
        </row>
     
    </craft>
    
    

    external by albert modified Oct 5, 2016  34  0  1  0

    Python microformats parser that supports hCard, hCalendar, hResume and rel-tag and provides an extensible model for other microformats.

    Python microformats parser that supports hCard, hCalendar, hResume and rel-tag and provides an extensible model for other microformats.: microformats.py
    # -*- coding: utf-8 -*-
    #!/usr/bin/env python
    
    """
    Model for microformat properties and parsers. A microformat parser can
    parse an HTML element into a dictionary of properties, whose keys are
    strings and whose values are strings or other dictionary of properties.
    
    As an example, the main program of this script parses an hResume from
    given URL.
    """
    
    import pprint
    import re
    import sys
    import urllib
    import urllib2
    import urlparse
    from cStringIO import StringIO
    
    import html5lib
    import lxml.html
    
    
    class BaseMicroformatProperty(object):
        """ Base class for a microformat property """
    
        def __init__(self, root, index=0):
            self.root = root
            self.index = index # None for multiple values, else selects one
    
        def parse(self, node):
            children = self.get_children(node)
            if children is None:
                return {}
            if self.index is None:
                value = filter(lambda value: value is not None, \
                        [self.get_value(child) for child in children]) or None
            else:
                try:
                    child = children[self.index]
                except IndexError:
                    value = None
                else:
                    value = self.get_value(child)
            return {self.get_key(): value} if value is not None else {}
    
        def get_children(self, node):
            return node.find_class(self.root)
    
        def get_key(self):
            return self.root
    
        def get_value(self, node):
            mapper = {'abbr': ('title',), 'a': ('href', 'alt'), \
                    'img': ('src',), 'object': ('data',)}
            value = None
            for attr in mapper.get(node.tag, []):
                if attr in node.attrib:
                    value = node.attrib[attr]
                    break
            if value is None:
                value = node.text_content()
            return self.transform_value(value)
    
        def transform_value(self, value):
            return force_unicode(whitespace_cleanup(value))
    
    class NestingMicroformatProperty(BaseMicroformatProperty):
        """ Base class for a microformat property that can have other nested """
    
        def __init__(self, root, index=0, subproperties=None):
            super(NestingMicroformatProperty, self).__init__(root, index)
            self.subproperties = subproperties or []
    
        def get_value(self, node):
            value = {}
            for property in self.subproperties:
                data = property.parse(node)
                if data is not None:
                    value.update(data)
            return value if value else None
    
    class BaseMicroformatParser(NestingMicroformatProperty):
        """ Base class for a microformat parser """
    
        DEFINITION = ()
    
        def __init__(self, root, index=None):
            super(BaseMicroformatParser, self).__init__(root, index=index, \
                    subproperties=self.get_subproperties(self.get_definition()))
    
        def get_subproperties(self, definition):
            retval = []
            for i in definition:
                if isinstance(i, basestring):
                    retval.append(BaseMicroformatProperty(i))
                else:
                    for k, v in i.iteritems():
                        retval.append(NestingMicroformatProperty(k, \
                                subproperties=self.get_subproperties(v)))
            return retval
    
        def get_definition(self):
            return self.DEFINITION
    
    class MultipleMicroformatParser(NestingMicroformatProperty):
        """ Base class for a parser of multiple microformat properties """
    
        def __init__(self, root, index=0, subindex=0, parsers=None):
            super(MultipleMicroformatParser, self).__init__( \
                    root, index=index)
            for parser_class in parsers:
                parser = parser_class(root, index=subindex)
                self.subproperties.extend(parser.subproperties)
    
    class HCardParser(BaseMicroformatParser):
        """ Implementation of an hCard microformat parser """
    
        DEFINITION = (
                'fn',
                {'n': ('family-name', 'given-name', 'additional-name', \
                        'honorific-prefix', 'honorific-suffix')},
                {'adr': ('post-office-box', 'extended-address', \
                        'street-address', 'locality', 'region', \
                        'postal-code', 'country-name', 'type', 'value')},
                'agent',
                'bday',
                'category',
                'class',
                {'email': ('type', 'value')},
                {'geo': ('latitude', 'longitude')},
                'key',
                'label',
                'logo',
                'mailer',
                'nickname',
                'note',
                {'org': ('organization-name', 'organization-unit')},
                'photo',
                'rev',
                'role',
                'sort-string',
                'sound',
                {'tel': ('type', 'value')},
                'title',
                'tz',
                'uid',
                'url'
            )
    
        def __init__(self, root='vcard', index=None):
            super(HCardParser, self).__init__(root, index=index)
    
    class HCalendarParser(BaseMicroformatParser):
        """ Implementation of an hCalendar microformat parser """
    
        DEFINITION = ('category', 'class', 'description', \
                    'dtend', 'dtstart', 'duration', 'location', 'status', \
                    'summary', 'uid', 'url', 'last-modified', 'rdate', \
                    'rrule', 'attendee', 'contact', 'organiser',
                    {'geo': ('latitude', 'longitude')}
            )
    
        def __init__(self, root='vevent', index=None):
            super(HCalendarParser, self).__init__(root, index=index)
    
    class HResumeParser(BaseMicroformatParser):
        """ Implementation of an hResume microformat parser """
    
        DEFINITION = ('summary', 'publications')
    
        def __init__(self, root='hresume', index=None):
            super(HResumeParser, self).__init__(root, index=index)
            self.subproperties.append(HCardParser('contact', index=0))
            self.subproperties.append(HCalendarParser('education'))
            self.subproperties.append(MultipleMicroformatParser('experience', \
                    index=None, subindex=0, parsers= \
                    [HCardParser, HCalendarParser]))
            self.subproperties.append(RelTagParser('skill'))
            self.subproperties.append(HCardParser('affiliation'))
    
    class RelTagProperty(BaseMicroformatProperty):
        """ Base class for a rel="tag" microformat property """
    
        def __init__(self, root='tag', index=0):
            super(RelTagProperty, self).__init__(root, index=index)
    
        def get_children(self, node):
            return node.find_rel_links(self.root)
    
        def get_value(self, node):
            href = node.attrib.get('href')
            value = urlparse.urlsplit(href)[2].split('/')[-1] if href else None
            return force_unicode(urllib.unquote_plus(value))
    
    class RelTagHrefUrlProperty(RelTagProperty):
    
        def get_key(self):
            return 'url'
    
        def get_value(self, node):
            return force_unicode(node.attrib.get('href'))
    
    class RelTagTextContentProperty(RelTagProperty):
    
        def get_key(self):
            return 'text'
    
        def get_value(self, node):
            return self.transform_value(node.text_content())
    
    class RelTagParser(BaseMicroformatParser):
        """ Implementation of a rel="tag" microformat parser """
    
        def __init__(self, root='tag', index=None, rel='tag'):
            super(RelTagParser, self).__init__(root, index=index)
            self.rel = rel
            self.subproperties = [RelTagProperty(rel), \
                    RelTagHrefUrlProperty(rel), \
                    RelTagTextContentProperty(rel)]
    
        def get_children(self, node):
            return node.find_rel_links(self.rel)
    
    
    ### Tools
    
    def cleanup_html(html):
        """Cleanups malformed and wrongly-encoded HTML. Returns UTF-8 encoded well-formed HTML"""
        h = html5lib.parse(html, treebuilder='lxml', namespaceHTMLElements=False)
        stream = StringIO()
        h.write(stream, encoding='utf-8')
        return stream.getvalue()
    
    def force_unicode(text, encoding='utf8'):
        """Force ``text`` to be decoded using ``encoding``, if not already decoded."""
        if not isinstance(text, unicode):
            return text.encode(encoding)
        return text
    
    def whitespace_cleanup(text):
        """Replace continuous whitespace by a single space"""
        return _re_whitespace.sub(u' ', text).strip()
    _re_whitespace = re.compile(r'\s+', re.UNICODE)
    
    
    
    
    # More microformats:
    # hReview: http://microformats.org/wiki/hreview
    # hAtom: http://microformats.org/wiki/hatom
    # rel="license": http://microformats.org/wiki/rel-license
    # rel="bookmark": http://microformats.org/wiki/rel-bookmark
    # XFN: http://www.gmpg.org/xfn/intro
    
    
    def main(program, url=None):
        """ Main program: Parses an hResume from given URL """
        if not url:
            print 'Usage: python %s <URL>' % program
        else:
            parser = HResumeParser()
            html = urllib2.urlopen(url).read()
            root = lxml.html.fromstring(cleanup_html(html))
            data = parser.parse(root)
            pprint.pprint(data)
    
    if __name__ == '__main__':
        main(*sys.argv)
    
    
    
    • Public Snippets
    • Channels Snippets