working on it ...


Explore Public Snippets

Sort by

Found 2,651 snippets matching: strings

    public by zenitramPRO modified May 4, 2016  404038  3  5  1

    Adding an Element in an Array using a Function.

    Arrays of Objects Remember that an object is just another type, like a string or number but more complex. This means that just as we can make arrays of numbers and strings, we can also make arrays of objects. Here we have our Person constructor which should look familiar. We can use this constructor to make an array of Person objects, similar
    // Our person constructor
    function Person (name, age) { = name;
        this.age = age;
    // Now we can make an array of people
    var family = new Array();
    family[0] = new Person("alice", 40);
    family[1] = new Person("bob", 42);
    family[2] = new Person("michelle", 8);
    // add the last family member, "timmy", who is 6 years old
    family[3] = new Person("timmy", 6);

    public by cghersi modified Jan 31, 2014  9685  57  9  0

    How to encrypt and decrypt strings in C#

    This class can be used to encrypt and decrypt the given string. In the current implementation the passwrod is directly saved inside the code; depending on the infrastructure and architecture of the code sometimes it can be passed as parameter
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Security.Cryptography;
    public static class Encryptor
        static private string _key = "myVeryStrongPsw";
        /// <summary>
        /// Encrypt the given string using the default key.
        /// </summary>
        /// <param name="strToEncrypt">The string to be encrypted.</param>
        /// <returns>The encrypted string.</returns>
        public static string Encrypt(string strToEncrypt)
                return Encrypt(strToEncrypt, _key);
            catch (Exception ex)
                return "Wrong Input. " + ex.Message;
        /// <summary>
        /// Decrypt the given string using the default key.
        /// </summary>
        /// <param name="strEncrypted">The string to be decrypted.</param>
        /// <returns>The decrypted string.</returns>
        public static string Decrypt(string strEncrypted)
                return Decrypt(strEncrypted, _key);
            catch (Exception ex)
                return "Wrong Input. " + ex.Message;
        /// <summary>
        /// Encrypt the given string using the specified key.
        /// </summary>
        /// <param name="strToEncrypt">The string to be encrypted.</param>
        /// <param name="strKey">The encryption key.</param>
        /// <returns>The encrypted string.</returns>
        public static string Encrypt(string strToEncrypt, string strKey)
                TripleDESCryptoServiceProvider objDESCrypto =
                    new TripleDESCryptoServiceProvider();
                MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
                byte[] byteHash, byteBuff;
                string strTempKey = strKey;
                byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
                objHashMD5 = null;
                objDESCrypto.Key = byteHash;
                objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
                byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
                return Convert.ToBase64String(objDESCrypto.CreateEncryptor().
                    TransformFinalBlock(byteBuff, 0, byteBuff.Length));
            catch (Exception ex)
                return "Wrong Input. " + ex.Message;
        /// <summary>
        /// Decrypt the given string using the specified key.
        /// </summary>
        /// <param name="strEncrypted">The string to be decrypted.</param>
        /// <param name="strKey">The decryption key.</param>
        /// <returns>The decrypted string.</returns>
        public static string Decrypt(string strEncrypted, string strKey)
                TripleDESCryptoServiceProvider objDESCrypto =
                    new TripleDESCryptoServiceProvider();
                MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
                byte[] byteHash, byteBuff;
                string strTempKey = strKey;
                byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
                objHashMD5 = null;
                objDESCrypto.Key = byteHash;
                objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
                byteBuff = Convert.FromBase64String(strEncrypted);
                string strDecrypted = ASCIIEncoding.ASCII.GetString
                (byteBuff, 0, byteBuff.Length));
                objDESCrypto = null;
                return strDecrypted;
            catch (Exception ex)
                return "Wrong Input. " + ex.Message;

    public by cghersi modified Jan 31, 2014  7121  11  9  0

    compare string with ignore case in C#

    This comparer can be used to check whether two strings are equal ignoring the case. It can be used e.g. in HashSets to define keys with ignorecase component
    public class IgnoreCaseComparer : IEqualityComparer<string>
        public bool Equals(string x, string y)
            if (x == null)
                return (y == null);
            return x.Equals(y, StringComparison.InvariantCultureIgnoreCase);
        public int GetHashCode(string obj)
            if (obj == null)
                return 0;
            return obj.ToLowerInvariant().GetHashCode();

    public by FMXExpress modified Nov 12, 2014  4533  2  7  1

    Process Strings Using A Parallel For Loop In Delphi XE7 Firemonkey

     procedure(I: Integer)

    public by te777 modified Sep 24, 2016  2957  3  5  0

    Hackerrank Count Strings solution python

    Hackerrank Count Strings solution python
    Created on Aug 7, 2016
    @author: Siddharthasahu @
    Automata build from from regex to DFA taken from there. Count Strings (Matrix class) added
    # You can test with input " 1 ((((ab)|a)*)|(((aa)|(bb))*)) 368046388 "
    #The result of the code executed in main should be 198110437 with the test input
    #import fileinput
    #from os import popen
    #import time
    #import sys, traceback
    class Automata:
        """class to represent an Automata"""
        def __init__(self, language = set(['a', 'b'])):
            self.states = set()
            self.startstate = None
            self.finalstates = []
            self.transitions = dict()
            self.language = language
        def epsilon():
            return ":e:"
        def setstartstate(self, state):
            self.startstate = state
        def addfinalstates(self, state):
            if isinstance(state, int):
                state = [state]
            for s in state:
                if s not in self.finalstates:
        def addtransition(self, fromstate, tostate, inp):
            if isinstance(inp, str):
                inp = set([inp])
            if fromstate in self.transitions:
                if tostate in self.transitions[fromstate]:
                    self.transitions[fromstate][tostate] = self.transitions[fromstate][tostate].union(inp)
                    self.transitions[fromstate][tostate] = inp
                self.transitions[fromstate] = {tostate : inp}
        def addtransition_dict(self, transitions):
            for fromstate, tostates in transitions.items():
                for state in tostates:
                    self.addtransition(fromstate, state, tostates[state])
        def gettransitions(self, state, key):
            if isinstance(state, int):
                state = [state]
            trstates = set()
            for st in state:
                if st in self.transitions:
                    for tns in self.transitions[st]:
                        if key in self.transitions[st][tns]:
            return trstates
        def getEClose(self, findstate):
            allstates = set()
            states = set([findstate])
            while len(states)!= 0:
                state = states.pop()
                if state in self.transitions:
                    for tns in self.transitions[state]:
                        if Automata.epsilon() in self.transitions[state][tns] and tns not in allstates:
            return allstates
        def display(self):
            print ("states:", self.states)
            print ("start state: ", self.startstate)
            print ("final states:", self.finalstates)
            print ("transitions:")
            for fromstate, tostates in self.transitions.items():
                for state in tostates:
                    for char in tostates[state]:
                        print ("  ",fromstate, "->", state, "on '"+char+"'",)
        def getPrintText(self):
            text = "language: {" + ", ".join(self.language) + "}\n"
            text += "states: {" + ", ".join(map(str,self.states)) + "}\n"
            text += "start state: " + str(self.startstate) + "\n"
            text += "final states: {" + ", ".join(map(str,self.finalstates)) + "}\n"
            text += "transitions:\n"
            linecount = 5
            for fromstate, tostates in self.transitions.items():
                for state in tostates:
                    for char in tostates[state]:
                        text += "    " + str(fromstate) + " -> " + str(state) + " on '" + char + "'\n"
                        linecount +=1
            return [text, linecount]
        def newBuildFromNumber(self, startnum):
            translations = {}
            for i in list(self.states):
                translations[i] = startnum
                startnum += 1
            rebuild = Automata(self.language)
            for fromstate, tostates in self.transitions.items():
                for state in tostates:
                    rebuild.addtransition(translations[fromstate], translations[state], tostates[state])
            return [rebuild, startnum]
        def newBuildFromEquivalentStates(self, equivalent, pos):
            # Added "sorted" next line
            rebuild = Automata(sorted(self.language))
            for fromstate, tostates in self.transitions.items():
                for state in tostates:
                    rebuild.addtransition(pos[fromstate], pos[state], tostates[state])
            for s in self.finalstates:
            return rebuild
        def getDotFile(self):
            dotFile = "digraph DFA {\nrankdir=LR\n"
            if len(self.states) != 0:
                dotFile += "root=s1\nstart [shape=point]\nstart->s%d\n" % self.startstate
                for state in self.states:
                    if state in self.finalstates:
                        dotFile += "s%d [shape=doublecircle]\n" % state
                        dotFile += "s%d [shape=circle]\n" % state
                for fromstate, tostates in self.transitions.items():
                    for state in tostates:
                        for char in tostates[state]:
                            dotFile += 's%d->s%d [label="%s"]\n' % (fromstate, state, char)
            dotFile += "}"
            return dotFile
    class BuildAutomata:
        """class for building e-nfa basic structures"""
        def basicstruct(inp):
            state1 = 1
            state2 = 2
            basic = Automata()
            basic.addtransition(1, 2, inp)
            return basic
        def plusstruct(a, b):
            [a, m1] = a.newBuildFromNumber(2)
            [b, m2] = b.newBuildFromNumber(m1)
            state1 = 1
            state2 = m2
            plus = Automata()
            plus.addtransition(plus.startstate, a.startstate, Automata.epsilon())
            plus.addtransition(plus.startstate, b.startstate, Automata.epsilon())
            plus.addtransition(a.finalstates[0], plus.finalstates[0], Automata.epsilon())
            plus.addtransition(b.finalstates[0], plus.finalstates[0], Automata.epsilon())
            return plus
        def dotstruct(a, b):
            [a, m1] = a.newBuildFromNumber(1)
            [b, m2] = b.newBuildFromNumber(m1)
            state1 = 1
            state2 = m2-1
            dot = Automata()
            dot.addtransition(a.finalstates[0], b.startstate, Automata.epsilon())
            return dot
        def starstruct(a):
            [a, m1] = a.newBuildFromNumber(2)
            state1 = 1
            state2 = m1
            star = Automata()
            star.addtransition(star.startstate, a.startstate, Automata.epsilon())
            star.addtransition(star.startstate, star.finalstates[0], Automata.epsilon())
            star.addtransition(a.finalstates[0], star.finalstates[0], Automata.epsilon())
            star.addtransition(a.finalstates[0], a.startstate, Automata.epsilon())
            return star
    class DFAfromNFA:
        """class for building dfa from e-nfa and minimise it"""
        def __init__(self, nfa):
        def getDFA(self):
            return self.dfa
        def getAllStates(self):
            return self.allstates
        def getTransitions(self):
            return self.trstates
        def getMinimisedDFA(self):
            return self.minDFA
        def displayDFA(self):
        def displayMinimisedDFA(self):
        def buildDFA(self, nfa):
            allstates = dict()
            eclose = dict()
            count = 1
            state1 = nfa.getEClose(nfa.startstate)
            eclose[nfa.startstate] = state1
            dfa = Automata(nfa.language)
            states = [[state1, count]]
            allstates[count] = state1
            count +=  1
            while len(states) != 0:
                [state, fromindex] = states.pop()
                # Next line was originally "for char in dfa.language:"
                # But returned "char" in random order, since dfa.language is a set,
                # so dfa.finalstates result was not consistent
                for char in sorted(dfa.language):
                    trstates = nfa.gettransitions(state, char)
                    for s in list(trstates)[:]:
                        if s not in eclose:
                            eclose[s] = nfa.getEClose(s)
                        trstates = trstates.union(eclose[s])
                    if len(trstates) != 0:
                        if trstates not in allstates.values():
                            states.append([trstates, count])
                            allstates[count] = trstates
                            toindex = count
                            count +=  1
                            toindex = [k for k, v in allstates.items() if v  ==  trstates][0]
                        dfa.addtransition(fromindex, toindex, char)
            for value, state in allstates.items():
                if nfa.finalstates[0] in state:
            self.dfa = dfa
            self.allstates = allstates
            self.trstates = trstates 
        def acceptsString(self, string):
            currentstate = self.dfa.startstate
            for ch in string:
                if ch==":e:":
                st = list(self.dfa.gettransitions(currentstate, ch))
                if len(st) == 0:
                    return False
                currentstate = st[0]
            if currentstate in self.dfa.finalstates:
                return True
            return False
        def minimise(self):
            states = list(self.dfa.states)
            n = len(states)
            unchecked = dict()
            count = 1
            distinguished = []
            equivalent = dict(zip(range(len(states)), [{s} for s in states]))
            pos = dict(zip(states,range(len(states))))
            for i in range(n-1):
                for j in range(i+1, n):
                    if not ([states[i], states[j]] in distinguished or [states[j], states[i]] in distinguished):
                        eq = 1
                        toappend = []
                        # Added "sorted" next line
                        for char in sorted(self.dfa.language):
                            s1 = self.dfa.gettransitions(states[i], char)
                            s2 = self.dfa.gettransitions(states[j], char)
                            if len(s1) != len(s2):
                                eq = 0
                            if len(s1) > 1:
                                raise BaseException("Multiple transitions detected in DFA")
                            elif len(s1) == 0:
                            s1 = s1.pop()
                            s2 = s2.pop()
                            if s1 != s2:
                                if [s1, s2] in distinguished or [s2, s1] in distinguished:
                                    eq = 0
                                    toappend.append([s1, s2, char])
                                    eq = -1
                        if eq == 0:
                            distinguished.append([states[i], states[j]])
                        elif eq == -1:
                            s = [states[i], states[j]]
                            unchecked[count] = s
                            count += 1
                            p1 = pos[states[i]]
                            p2 = pos[states[j]]
                            if p1 != p2:
                                st = equivalent.pop(p2)
                                for s in st:
                                    pos[s] = p1
                                equivalent[p1] = equivalent[p1].union(st)
            newFound = True
            while newFound and len(unchecked) > 0:
                newFound = False
                toremove = set()
                for p, pair in list(unchecked.items()):  #.items():
                    for tr in pair[2:]:
                        if [tr[0], tr[1]] in distinguished or [tr[1], tr[0]] in distinguished:
                            distinguished.append([pair[0], pair[1]])
                            newFound = True
            for pair in unchecked.values():
                p1 = pos[pair[0]]
                p2 = pos[pair[1]]
                if p1 != p2:
                    st = equivalent.pop(p2)
                    for s in st:
                        pos[s] = p1
                    equivalent[p1] = equivalent[p1].union(st)
            if len(equivalent) == len(states):
                self.minDFA = self.dfa
                self.minDFA = self.dfa.newBuildFromEquivalentStates(equivalent, pos)
    class NFAfromRegex:
        """class for building e-nfa from regular expressions"""
        def __init__(self, regex):
   = '*'
            # Next line was originally " = '+'
            # Changed to '|' to fit aplication of regex for program
   = '|'
   = '.'
            self.openingBracket = '('
            self.closingBracket = ')'
            self.operators = [,]
            self.regex = regex
            self.alphabet = [chr(i) for i in range(65,91)]
            self.alphabet.extend([chr(i) for i in range(97,123)])
            self.alphabet.extend([chr(i) for i in range(48,58)])
        def getNFA(self):
            return self.nfa
        def displayNFA(self):
        def buildNFA(self):
            language = set()
            self.stack = []
            self.automata = []
            previous = "::e::"
            for char in self.regex:
                if char in self.alphabet:
                    if previous != and (previous in self.alphabet or previous in [self.closingBracket,]):
                elif char  ==  self.openingBracket:
                    if previous != and (previous in self.alphabet or previous in [self.closingBracket,]):
                elif char  ==  self.closingBracket:
                    if previous in self.operators:
                        raise BaseException("Error processing '%s' after '%s'" % (char, previous))
                        if len(self.stack) == 0:
                            raise BaseException("Error processing '%s'. Empty stack" % char)
                        o = self.stack.pop()
                        if o == self.openingBracket:
                        elif o in self.operators:
                elif char ==
                    if previous in self.operators or previous  == self.openingBracket or previous ==
                        raise BaseException("Error processing '%s' after '%s'" % (char, previous))
                elif char in self.operators:
                    if previous in self.operators or previous  == self.openingBracket:
                        raise BaseException("Error processing '%s' after '%s'" % (char, previous))
                    raise BaseException("Symbol '%s' is not allowed" % char)
                previous = char
            while len(self.stack) != 0:
                op = self.stack.pop()
            if len(self.automata) > 1:
                print (self.automata)
                raise BaseException("Regex could not be parsed successfully")
            self.nfa = self.automata.pop()
            self.nfa.language = language
        def addOperatorToStack(self, char):
                if len(self.stack) == 0:
                top = self.stack[len(self.stack)-1]
                if top == self.openingBracket:
                if top == char or top ==
                    op = self.stack.pop()
        def processOperator(self, operator):
            if len(self.automata) == 0:
                raise BaseException("Error processing operator '%s'. Stack is empty" % operator)
            if operator ==
                a = self.automata.pop()
            elif operator in self.operators:
                if len(self.automata) < 2:
                    raise BaseException("Error processing operator '%s'. Inadequate operands" % operator)
                a = self.automata.pop()
                b = self.automata.pop()
                if operator ==
                elif operator ==
    """def drawGraph(automata, file = ""):
        f = popen(r"dot -Tpng -o graph%s.png" % file, 'w')
            raise BaseException("Error creating graph")
    def isInstalled(program):
        import os
        def is_exe(fpath):
            return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
        fpath, fname = os.path.split(program)
        if fpath:
            if is_exe(program) or is_exe(program+".exe"):
                return True
            for path in os.environ["PATH"].split(os.pathsep):
                exe_file = os.path.join(path, program)
                if is_exe(exe_file) or is_exe(exe_file+".exe"):
                    return True
        return False
    class Matrix:
        def __init__(self, DFA, allstates, transitions, length):
            self.length = length
            self.DFA = DFA
            self.allstates = allstates
            dim = 0
            for value, _state in allstates.items():
                if value != 0:
                    dim += 1
            dim += 1
            self.dim = dim
            self.matrix= self.createMatrix( self.DFA, self.allstates, transitions, self.dim)
        def getDim(self):
            return self.dim
        def createMatrix(self, DFA, allstates, transitions, dim):
            matrix = [[0]*(dim) for _ in range(dim)]
            for from_state, to_state in transitions.items():
                for to_state, _char in to_state.items():
                    matrix[from_state-1][to_state-1] = 1 
            return matrix   
        def count_paths(self, DFA, dim, length):
            modulo = 1000000007
            result = Matrix.pow2(self, length, self.matrix, dim, modulo)
            count = 0
            for i in range(dim):
                for j in range(dim):
                    if i == 0:
                        for k in DFA.finalstates:
                            k -= 1
                            if j == k:
                                count += result[i][j]
            return count % modulo
        def copy(self, dim):
            my_matrix = [[0]*(dim) for _ in range(dim)]
            for i in range(dim):
                for j in range(dim):
                    my_matrix[i][j] = self.matrix[i][j]
            return my_matrix
        def printMatrix(self, matrix, dim):
            for i in range(dim):
        def pow2(self, power, matrix, dim, mod=None):
            result1 = [[0]*(dim) for _ in range(dim)]
            for i in range(dim):
                result1[i][i] = 1
            while power > 0:
                if power & 1:
                    result1 = Matrix.mat_square_mult(self, result1, matrix, dim, mod);
                power >>= 1;
                if power > 0:
                    matrix = Matrix.mat_square_mult(self, matrix, matrix, dim, mod);
            matrix = result1 
            return matrix
        def mat_square_mult(self, matrix, other, dim, mod=None):
            result = [[0]*(dim) for _ in range(dim)]
            for i in range(dim):
                for j in range(dim):
                    index = 0
                    for k in range(dim):
                        index += (matrix[i][k] * other[k][j]) % mod
                        result[i][j] = index
            return result
    def count_strings(regex, length):
        nfaObj = NFAfromRegex(regex)
        nfa = nfaObj.getNFA()
        dfaObj = DFAfromNFA(nfa)
        dfa = dfaObj.getDFA()
        #minDFA = dfaObj.getMinimisedDFA()
        #print ("\nNFA: ")
        #print ("\nDFA: ")
        #print ("\nMinimised DFA: ")
        #result = None
        transitions = dfa.transitions
        allstates = dfaObj.getAllStates()
        resultObj = Matrix(dfa, allstates, transitions, length) 
        dim = resultObj.getDim()
        result = Matrix.count_paths(resultObj, dfa, dim, length)
        #The result should be 198110437 for the test input
        print (result)
    def main():
        cases = int(input().strip())
        for _i in range(cases):
            in_line = input().strip().split()
            regex = in_line[0]
            length = int(in_line[1])
            count_strings(regex, length)
    if __name__  ==  '__main__':

    public by zioj modified Feb 27, 2014  2000  1  6  2

    SQL Concatenation of strings

    How to use CAST to concat several values into a unique string
    DECLARE @num int = 1;
    DECLARE @sql nvarchar(max) = 
    		'My String has number ' + CAST(@num AS nvarchar(20)) + 
    		' and other strings concatenated'

    public by sai1857 modified Apr 30, 2014  1992  2  5  1

    Extract urls from a string and list the strings and urls in the same sequence.

    public static List<String> extractUrls(String value) throws Exception
    	    if (value == null) throw new Exception("urls to extract");
    	    List<String> result = new ArrayList<String>();
    	   String urlPattern = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
    	    Pattern p = Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);
    	    Matcher m = null;
    	    	m = p.matcher(value);
    	    		String pre = value.substring(0, m.start(0));
    	    		String url = value.substring(m.start(0),m.end(0));
    	    		value = value.substring(m.end(0));
    	    return result;

    public by ekarakas modified Aug 29, 2013  2236  0  5  0

    A print_r replacement function that can handle nested arrays and strings

    Usage: printr($array);
        A print_r replacement function that can handle nested arrays and strings
        Usage: printr($array);
        function printr($array){
        echo '<blockquote>';
        if (!is_array($array)) return;
        foreach($array as $key => $value){
        echo htmlspecialchars("$key: ");
        if (is_array($value)){ printr($value);}else{echo htmlspecialchars($value).'<br />';}
        echo '</blockquote>';

    public by oscoder modified Mar 19, 2015  1878  1  3  0

    replace the special strings in all files according to the regular expression.

    find . -type f -name "*.php"|xargs perl -pi -e 's|||g'

    public by snip2code modified Oct 29, 2013  14533  47  8  1

    Custom SWT List Box

    This widget presents a ListBox, with vertical scroll-bars, whose items can be custom (instead of simple strings as in List widget). The items should be of the same height and all homogeneous.
    import java.util.HashMap;
    import java.util.Map;
    import org.apache.log4j.Logger;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.custom.ScrolledComposite;
    import org.eclipse.swt.layout.FormData;
    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.Link;
    import org.eclipse.swt.widgets.Listener;
    import org.eclipse.wb.swt.SWTResourceManager;
    public class CustomListBox extends Composite {
    	protected static Logger log = Logger.getLogger(CustomListBox.class);
    	private ScrolledComposite scrolledResults;
    	private Composite listResults;
    	private int width;
    	private int height;
    	private int itemRowHeight;
    	private int rowWidth;
    	private int maxResultsDisplayed;
    	private Map<String, Composite> rows = new HashMap<String, Composite>();
    	 * @param parent container of the component
    	 * @param style style of the componen
    	 * @param marginLeft pixels from left border of the dialog
    	 * @param topHeight pixels from top border fo the dialog
    	 * @param width total width in pixel of the component
    	 * @param height total height in pixel of the component
    	 * @param scrolledCompoFormData FormData for the component
    	 * @param itemRowHeight height in pixel of a single item
    	public CustomListBox(Composite parent, int style, int marginLeft, int topHeight, int width, int height,
    			FormData scrolledCompoFormData, int itemRowHeight) {
    		super(parent, style);
    		this.width = width;
    		rowWidth = width - 25;
    		this.height = height;
    		this.itemRowHeight = itemRowHeight;
    		maxResultsDisplayed = height / itemRowHeight;
    		scrolledResults = new ScrolledComposite(parent, SWT.BORDER | SWT.V_SCROLL);
    		scrolledResults.setLocation(marginLeft, topHeight);
    		scrolledResults.setSize(width, height);
    		scrolledResults.setMinSize(width, height);	
    		scrolledCompoFormData.height = height;	//force height of the component
    		scrolledResults.addListener(SWT.Activate, new Listener() {
    		    public void handleEvent(Event e) {
    		listResults = new Composite(scrolledResults, SWT.NONE);
    		listResults.setSize(width, height);
    		parent.addListener(SWT.Resize, new Listener() { 
    			public void handleEvent(Event event) { 
    		parent.notifyListeners(SWT.Resize, new Event()); 
    	private void resizeScrollableResults() {
    		int actualHeight = rows.size() * itemRowHeight;
    		scrolledResults.setMinSize(width, Math.max(actualHeight, height));
    	public void layout() {
    	 * Creates a new row in the list, identified by the given key.
    	 * @param key identifier to retrieve the newly created item
    	 * @return the just created and added composite item
    	 * @throws IllegalArgumentException if key already exists or is null/empty
    	public Composite addRow(String key) throws IllegalArgumentException {
    		if (key == null || key.length() <= 0)
    			throw new IllegalArgumentException("Null or empty key");
    		if (rows.containsKey(key))
    			throw new IllegalArgumentException("Item with key " + key + " already exists");
    		int rowCompoWidth = rowWidth;
    		if (!scrollbarIsShown()) 
    			rowCompoWidth += 20;
    		final Composite rowCompo = new Composite(listResults, SWT.BORDER);
    		rowCompo.setLocation(0, (rows.size() * itemRowHeight));
    		rowCompo.setSize(rowCompoWidth, itemRowHeight - 2);
    		rows.put(key, rowCompo);
    		return rowCompo;
    	 * True if the number of items is greater than the total visible items 
    	public boolean scrollbarIsShown() {
    		return (rows.size() >= maxResultsDisplayed);
    	 * Returns the number of visible items
    	public int getMaxResultsDisplayed() {
    		return maxResultsDisplayed;
    	 * Empties the list of items in the list and shows a single item with the given text
    	 * @param textToShow text to display
    	 * @param font font of the text to display
    	 * @param backgroundColor background color of the item that shows the text to display
    	 * @param link link to follow (if not empty, a Link instead of a Label will be created)
    	public void displayMessage(String textToShow, Font font, Color backgroundColor, final String link) {
    		final Composite rowCompo = new Composite(listResults, SWT.NONE);
    		rowCompo.setLocation(0, 0);
    		rowCompo.setSize(width, itemRowHeight - 2);
    		Control lblNoResults = null;
    		if (link != null) {
    			lblNoResults = new Link(rowCompo, SWT.NONE);
    			((Link)lblNoResults).setCursor(new Cursor(getShell().getDisplay(), SWT.CURSOR_HAND));
    			((Link)lblNoResults).addSelectionListener(new SelectionAdapter() {
    				public void widgetSelected(SelectionEvent e) {
    					//something to do with the link...
    		} else {		
    			lblNoResults = new Label(rowCompo, SWT.NONE);
    		lblNoResults.setBounds(0, 0, width, itemRowHeight - 2); 
    	 * Removes all the items from the list and dispose all the children content
    	public void cleanItems() {
    		//clean previous results:
    		Control[] children = listResults.getChildren();
    		if (children != null) {
    			for (Control child : children) {
    		rows = new HashMap<String, Composite>();
    • Public Snippets
    • Channels Snippets