Programming challenges

This thread serves as a collection of small (solvable in less than 1 hour), but yet not trivial programming challenges. Please feel free to post your solution below, but try to avoid lengthy discussions.
1. Challenge:
Create a program to print the solution for any given (solvable, i.e. no guessing is needed) sudoku puzzle. Puzzles are represented as follows:
5 3 0 0 7 0 0 0 0
6 0 0 1 9 5 0 0 0
0 9 8 0 0 0 0 6 0
8 0 0 0 6 0 0 0 3
4 0 0 8 0 3 0 0 1
7 0 0 0 2 0 0 0 6
0 6 0 0 0 0 2 8 0
0 0 0 4 1 9 0 0 5
0 0 0 0 8 0 0 7 9
2. Challenge:
Create a program which takes a conjugated (regular) verb from in the present tense in various languages and tells you the language and the infinitive of the verb.
For simplicity's sake, I'll narrow it down a bit further: The program should be able to recognize German regular verbs (see "spielen"), Portuguese verbs on -ar (see "falar") and French verbs on -ir (see "choisir")
Example session:
$ ./lang kennst
German: kennen
./lang cantam
Portuguese: cantar
./lang finit
French: finir
If you want to suggest another challenge, please write me a mail. Remarkable solutions (very fast, small or elegant) for each challenge will be highlighted.
Last edited by wuischke (2008-03-02 13:12:33)

wuischke wrote:
OK, I'll post my solution as well. Written in ansi-C. It's sometimes very ugly (particularly the code to clear the square), well, but it works. You can add a call to the "PrintField" function before adding each value to see how this solver works.
I've seen incredibly small solvers written in Haskell - anyone here who knows functional programming languages well enough to post a nice solution?
This is a late solution to the first one.
This haskell solver isn't too small, but it is fast, and does guess when it gets stuck.
I used a similar strategy to yours: fill a list of lists with lists of candidates, and repeatedly check rows, columns, 3x3 squares (with wheel), and eliminate taken numbers (which also including 1 if we already have [1,2] in two spots).
It's a bit long, but it does guess once the above strategy stops changing the square, which solves all the newspaper problems I've tried (some of which end up taking the algorithm to maybe 15 dead ends: without guessing, those could probably be solved more intelligently using linear algebra (the problem is still np) (since each row,col,3x3 totals 45, giving at least as many equations as knowns), which would be elegant, but probably less efficient and more confusing)
My parser takes files without spaces, since I like it that way.
Ex:
53__7____
6__195___
_98____6_
8___6___3
4__8_3__1
7___2___6
_6____28_
___419__5
____8__79
Here it is:
module Main where
import Control.Monad
import Data.Maybe
import Data.Char (digitToInt,intToDigit)
import Data.List (nub,transpose,group,sort)
import Debug.Trace
import System.Environment
type MagicSq = [[[Int]]]
main = do f <- getArgs
if null f then error "specify one or more sudoku problem files to solve"
else mapM (\x -> unparseSq . solPret . rowsPar =<< readFile x) f
sol :: (Monad m) => [MagicSq] -> m [MagicSq]
sol = liftM (concat) . mapM sol'
sol' :: (Monad m) => MagicSq -> m [MagicSq]
sol' = let y x = mapMaybe wheel $ x
ty x = let yx = y x in trace ("branch of: " ++ show (length yx)) yx
in return . y . branch
solPret x = let f x = untillSame $ scanl (>>=) (sol x) $ repeat sol
-- somewhere magicSq is reversed... corrected here
goodSol x = if length x == 1 then return $ reverse $ head x
else fail "multiple, possibly incomplete solution found"
in join $ goodSol =<< f (wheel' x)
branch :: MagicSq -> [MagicSq]
branch x = if isSolved x then [x]
else map (unConcat x) $ branchRow $ concat x
where
unConcat o = segment $ length o
branchRow = bR []
bR a [] = []
bR a (l:ls)
| length l == min = map (\split -> (reverse a) ++ [split]:ls) l
| otherwise = bR (l:a) ls
where min = minimum $ filter (1/=) $ map length (l:ls)
wheel x = untillSame $ scanl (>>=) (wheel' x) $ repeat wheel'
wheel' x = rowCk x >>= zoneApp rowCk >>= colCk
untillSame (l:m:ms) = if l == m then l else untillSame (m:ms)
rowCk,colCk :: (Ord a, Show a, Monad m) => [[[a]]] -> m [[[a]]]
rowCk x = let exclCks x = foldr (=<<) (return x) $ map (exclusionCk) [1..2]
y = map (exclCks) x
--y = map (totalOneCk) x
in if Nothing `elem` y then fail "A row failed"
else return (map fromJust $ y)
colCk = liftM transpose . rowCk . transpose
zoneApp f = liftM (zC 3) . f . zC 3
zC _ [] = []
zC _ [[[]]] = [[[]]]
zC z l = let (i,ls) = splitAt z l
nrs = map (segment z) i
headGr x | null $ concat $ concat x = []
| otherwise = concatMap (head) x : headGr (map tail x)
in if length l `mod` z == 0
then headGr nrs ++ (zC z ls)
else error $ "square edge length:" ++ show (length l)
++ "does not divide by: " ++ show z
segment n l = let (a,as) = splitAt n l
in if null as then [a] else a:segment n as
rowsPar = parseSq . par' [] []
where
par' a b [] = (a)
par' a b ('\n':xs) = par' (reverse b :a) [] xs
par' a b (x:xs) = par' a (x:b) xs
parseSq :: [String] -> MagicSq
parseSq p@(m:ms) = if length m /= length p
then error "Must use a square grid"
else map (\x -> map (options) x) p
where
options x | x `elem` ['1'..intToDigit (length m)] = [digitToInt x]
| otherwise = [1..length m ]
unparseSq x = if isSolved x
then putStrLn $ unlines $ map show $ map (concatMap (map intToDigit)) x
else putStrLn $ unlines $ map show $ map (map (map intToDigit)) x
isSolved x = (length x)^2 == (length $ concat $ concat x)
totalOneCk l = let decided = concat $ filter (\x -> 1 == length x) l
uniqueL x = length x == length (nub x)
f x = if length x == 1 then x
else filter (\x -> x `notElem` decided) x
in if uniqueL decided then return $ map (f) l
else fail $ "Invalid row: " ++ show decided
-- this is a generalization of the totalOneCk; candidates are eliminated
-- based on the values in n same candidate lists of n length
exclusionCk :: (Monad m, Ord a, Show a) => Int -> [[a]] -> m [[a]]
exclusionCk n l =
let areLen = filter (\x -> n == length x)
ggs = group $ sort $ areLen l
ugPairs = areLen ggs
removals = map (head) ugPairs
maxGG = maximum $ map length $ ggs
errPP = fail $ "Length " ++ show n
++ " overbooked: " ++ show ggs
++ "\nIn: " ++ show l
-- The actual filter
f l [] = l
f l (r:rs)
| length l == 1 = l
| l == r = l
| otherwise = f (filter (\x -> x `notElem` r) l) rs
manage | null ugPairs = return l
| maxGG > n = errPP
| otherwise = return $ map (\l -> f l removals) l
in manage
edit: changed branch (guessing) to take the first smallest branch.
Last edited by vogt (2008-08-08 00:56:00)

Similar Messages

  • Programming Challenge -- Your chance to win an Ultra 20 Workstation.

    In order to celebrate our first ever release of early Alpha bits of Sun Studio
    Compilers for Linux OS we've decided to give all of you a chance to experience
    first hand how indispensable our tools can be in the most challenging situations
    when you have to tune the last possible drop of performance out of your app and
    also to have an opportunity to win a blazing fast x64 Sun Ultra 20 Workstation.
    Here's how: you participate in the programming challenge by developing
    an application that reads alphanumeric strings from standard input
    and prints out the top 1000 string occurrences to standard output. The output
    of your application should be identical to the output produced by the following
    command:
    $ cat input_file | sort | tail -1000
    Turn in your source code, build instructions and binary to the Sun Studio
    booth at LinuxWorld 2005 Conference and Expo in Moscone, San Francisco
    by Thursday, August 11 at 3pm. If your application executes faster than
    all other solutions, including our own, you win Sun Ultra 20 Workstation!
    Of course, we'll be also glad to explain to you how by using our tools
    you can tune your app into a wild performer.
    Please check the special forum dedicated to Sun Studio for Linux for
    the latest scoop on the challenge and what's up with compilers on
    Linux in general:
    http://developers.sun.com/prodtech/cc/linux_index.html
    If you want to chat with us in person -- go the the Linux World 2005:
    http://www.linuxworldexpo.com
    and register using this promotion code: N0388.
    Thanks and have fun,
    Compiler team @ Sun microsystems.
    P.S. A copy of the Official Rules will be available at the Sun
    Microsystems Booth.

    It's saying my password is wrong, but it's not. When I try to reset the password the form won't submit. So I guess i'm out

  • Programming Challenge -- Your chance to win an Ulra 20 Workstation

    In order to celebrate our first ever release of early Aplpha bits of Sun Studio
    Compilers for Linux OS we've decided to give all of you a chance to experience
    first hand how indispensable our tools can be in the most challenging situations
    when you have to tune the last possible drop of performance out of your app and
    also to have an opportunity to win a blazing fast x64 Sun Ultra 20 Workstation.
    Here's how: you participate in the programming challenge by developing
    and application that reads alphanumeric strings from standard input
    and prints out the top 1000 string occurrences to standard output. The output
    of your application should be identical to the output produced by the following
    command:
    $ cat input_file | sort | tail -1000
    Turn in your source code, build instructions and binary to the Sun Studio
    booth at LinuxWorld 2005 Conference and Expo in Moscone, San Francisco
    by Thursday, August 11 at 3pm. If your application executes faster than
    all other solutions, including our ow, you win a Sun Ultra 20 Workstation!
    Of course, we'll be also glad to explain to you how by using our tools
    you can tune your app into a wild performer.
    We will be also using this forum for discussing some of the entries and hear
    what you have to say -- so check back early, check back often!
    Oh yeah, and one more thing:
    if you want to get the latest scoop on Sun Stduio Compilers for the Linux OS go right here:
    http://developers.sun.com/prodtech/cc/linux_index.html
    or if you want to chat with us in person -- go the the Linux World 2005:
    http://www.linuxworldexpo.com
    and register using this promotion code: N0388.
    Thanks and have fun,
    Compiler team @ Sun microsystems.
    P.S. A copy of the Official Rules will be available at the Sun
    Microsystems Booth.

    In order to celebrate our first ever release of early Aplpha bits of Sun Studio
    Compilers for Linux OS we've decided to give all of you a chance to experience
    first hand how indispensable our tools can be in the most challenging situations
    when you have to tune the last possible drop of performance out of your app and
    also to have an opportunity to win a blazing fast x64 Sun Ultra 20 Workstation.
    Here's how: you participate in the programming challenge by developing
    and application that reads alphanumeric strings from standard input
    and prints out the top 1000 string occurrences to standard output. The output
    of your application should be identical to the output produced by the following
    command:
    $ cat input_file | sort | tail -1000
    Turn in your source code, build instructions and binary to the Sun Studio
    booth at LinuxWorld 2005 Conference and Expo in Moscone, San Francisco
    by Thursday, August 11 at 3pm. If your application executes faster than
    all other solutions, including our ow, you win a Sun Ultra 20 Workstation!
    Of course, we'll be also glad to explain to you how by using our tools
    you can tune your app into a wild performer.
    We will be also using this forum for discussing some of the entries and hear
    what you have to say -- so check back early, check back often!
    Oh yeah, and one more thing:
    if you want to get the latest scoop on Sun Stduio Compilers for the Linux OS go right here:
    http://developers.sun.com/prodtech/cc/linux_index.html
    or if you want to chat with us in person -- go the the Linux World 2005:
    http://www.linuxworldexpo.com
    and register using this promotion code: N0388.
    Thanks and have fun,
    Compiler team @ Sun microsystems.
    P.S. A copy of the Official Rules will be available at the Sun
    Microsystems Booth.

  • Programming challenge!

    This question isn�t a specific Javaprogramming question, instead it�s a more general programming problem/challenge.
    I�m trying to create a football league generator in java. It should be possible to generate leagues with 4 to 24 teams (only even leagues, 4, 6, 8, 10� teams). Every team should meet each other twice (homeTeam vs. awayTeam and awayTeam vs. homeTaem).
    An example:
    A league with 4 teams, A, B, C and D.
    Round 1.1
    A vs. B
    C vs. D
    Round 1.2
    B vs. C
    D vs. A
    Round 1.3
    A vs. C
    D vs. B
    Round 2.1
    B vs. A
    D vs. C
    Round 2.2
    C vs. B
    A vs. D
    Round 2.3
    C vs. A
    B vs. D
    Because there are 4 teams it is easy to calculate the following:
    1: It is necessary to have 2 matches per round.
    2: Total of 12 matches for the whole league
    3: It is necessary to have 6 rounds (12/2) in the league.
    It is also easy to generate all the matches that are going to be played in the league:
    A vs. B B vs. C C vs. D D vs. A
    A vs. C B vs. D C vs. A D vs. B
    A vs. D B vs. A C vs. B D vs. C
    The difficult part is to put the matches in rounds so that every team plays once and only once per round. This is the part that is challenging! Any suggestions how this could be solved?

    Unfortunately, the maths magazine I used to have which has a solution is at my parents' house. I think it's something like this:
    You have n teams.
    1. Arrange the teams in a circle. (So addition is done mod n).
    2. i = 1
    3. Go round the circle, pairing each unmatched team j with the team (i+j). If there's a team left over, they don't play that round.
    4. if (! some sensible termination condition) {i++; goto 2}

  • Programming Challenge - creating a "Stopwatch" in ABAP

    Howdy,
    I was going to get a colleague to create this in VB but I'm sure you could do something like this in SAP.
    Basically I just want to write a program that acts as a "stopwatch". It just needs three buttons -START, STOP RESET.And it jus6t needs to show the time that has transpired.
    Any ideas on how I could do this - does SAP already ahve something like this?

    in pseudocode: (you will need a dynrpo aand some PAI Logig and  fields in which you disply l_start l_stop and l_diff.
    data: l_start type i,
          l_stop type i,
          l_diff type i.
    case oK_code
    when 'START' "user presses start
    if l_start is initial.
       get run time l_start.
    endif.
    when 'STOP'.
    get run time l_stop.
    l_diff = l_stop - l_start.
    when 'RESET'.
    clear l_start.
    endcase.
    Christian

  • Programming Challenge - NI-Spy Equivalent?

    Hello :}
    I'm writing C-based console applications under Windows NT and am trying
    to find a more useful way of debugging them.
    Specifically, I would like to find out the exact string being sent from
    the console application to the VISA dll. This would probably be similar
    to something that NI-SPY does. However, since the console application
    is assembling the string on the fly (and therefore a lot of times %s is
    sent), NI-SPY isn't very useful.
    What I would like to be able to do is something like this:
    // Partial C example
    void main()
    ViSession vis;
    char buffer[256] = "\0";
    char String1[256]="\0", String2[256]="\0", SendString[256]="\0";
    ViUInt32 Count = 0;
    sprintf(SendS
    tring, "%s%s", String1, String2); // combine the
    strings to send
    StartSpy(/*whatever parameters are needed here*/);
    /* StartSpy would alert whatever (dll? includes?) to start
    recording what's being
    sent to VISA. */
    viWrite(vis, SendString, 256, &Count);
    EndSpy(buffer, /*whatever other parameters are needed.*/);
    /* buffer would then contain whatever was sent to VISA via viWrite.
    It should have the exact same contents as SendString... but this
    is
    needed for more complex debugging purposes elsewhere. */
    Any idea, leads, points-in-the-right-direction?
    Thanks!
    Scott

    In article <[email protected]>,
    [email protected] wrote:
    > Hello :}
    >
    > I'm writing C-based console applications under Windows NT and am
    > trying to find a more useful way of debugging them.
    >
    >
    > Any idea, leads, points-in-the-right-direction?
    >
    > Thanks!
    > Scott
    Scott:
    I am glad to hear that you are trying to use NI Spy for debugging your
    app. I am sorry to hear that it's not helping you. It should work
    just as well for a console app as from LabVIEW or CVI. It should also
    certainly work completely correctly for viWrite. You mention your
    program sends "%s" - do you really mean that the function call you are
    using is viPrintf? Because with viPrintf we do have some shortcomings
    in NI Spy currently. We will be working on that in the f
    uture. One
    possible workaround for now is to use viSPrintf (print to user buffer)
    followed by viWrite of that data. That should allow you to spy on the
    formatted data returned by viSPrintf and sent to viWrite.
    If you have further problems, feel free to contact me directly with a
    larger code snippet and perhaps even a .spy file with what NI Spy is
    actually seeing.
    Dan Mondrik
    Senior Software Engineer, VISA/VXI
    National Instruments
    Sent via Deja.com http://www.deja.com/
    Before you buy.

  • A Programming challenge thread

    Could we have a thread like this one http://ubuntuforums.org/showthread.php?t=1714324 here on arch forums for beginners/intermidiates?
    That would be great. I'm asking someone with enough experience with programming languages for this so he could manage things.
    Programs could be peer reviewed as well, but we need someone to look over things.
    Hopefully, if people show interest, the thread would be stickied too.

    Not a suitable subforum, this one is for questions relating to programming & scripting.
    Moving to 'forum & wiki discussion'.

  • Announcing the Java Spring Programming IDE Challenge

    Help promote your favorite Java Spring Programming IDE by taking part in the Java Spring Programming IDE Challenge which is taking place on JavaPocket.net.
    The resulting contest entries will be used to help teach Java Spring Programming. See JavaPocket.net for more details.

    In case you don't have time to partake in the programming challenge right now, at least come take a really short - single page - survey on JavaPocket.net to help us figure out which Java Programming IDE best lends itself to learning Java Spring. Thanks!

  • Problem challenge

    Hi all!
    I have an algorithm and programming challenge :)
    I have the following dimensions:
    -Time (lev0 is day)
    -Scenario (Actual and Budget)
    - Unit (where ROOM is the lowest level)
    - Year
    Let's leave it here to make it easier. Now, what I need to do is the following:
    If the actual value for a room in a day and year is bigger than the same value in budget, I need to assign
    the difference to a room which budget is bigger than it's actual. This is:
    For JAN1 2011
    ROOM1 ACTUAL=10 BUDGET=8
    ROOM2 ACTUAL=3     BUDGET=11
    Add 2 (10-8 from room1) to ROOM2. The final result would be:
    ROOM1     ACTUAL=8     BUDGET=8
    ROOM2     ACTUAL=5     BUDGET=11
    Of course this will be updated no in "Actual" but in a Version dimension.
    There's a $100.000 compensation price :P

    Solving the riddel is no probelm but knowingthe dimensionality will determine your approach.
    At its simplest, how much you are over budget for all room. Once you know how much you must reallocate, process each room bringing the actual up until it equals budget. Using a variance dimension for the decrements & increments.
    Dave

  • Simple LabVIEW Puzzle Challenge

    I am a big fan of Games Magazine and have always enjoyed puzzles, so I decided to start a simple fun thread about puzzles.  This is a perfect way to learn some tips and tricks using LabVIEW.
    Since this is a programming challenge credit should be giving to speed...but I think presentation should also factor in.
    The first puzzle, is a puzzle about crossing a rickety bridge in the dark.  It was originally published in Games Magazine but I do not have the original reference.  Four people named 1, 2, 5, and 10 have to quickly cross the bridge.  They have a single flashlight and everyone needs to get safely across.  1 takes one minute, 2 takes two minutes, 5 takes five minutes, and 10 takes ten minutes.  Only two people are allowed across at any one time, and you must walk the speed of the slower person. 
    Example:
    We will have 1 and 2 go across first = 2 mins.
    1 goes back = 1 min.
    1 and 5 goes across = 5 mins.
     for a total of 8 mins. so far.
    The trick is to do this in  the minimum time possible (and no you don't get to throw the flashlight). 
    There are solutions on the web but I would suggest if you've never seen this puzzle to avoid looking up the answer since solving it is more fun.
    The trick is to be creative and have fun and I look forward to seeing your solutions. 
    Regards,
    -SS

    smercurio_fc wrote:
    "In your description you stated that only two people are allowed to cross, but in your example you indicate that 1 goes back alone. This would seem to contradict the rules of crossing."
    Ravens Fan wrote:
    "1&8 across (8) 1 back (1) 1&4 across (4) 1 back (1)  1 and 2 across (2),  total 16 minutes."
    Sorry for the late reply, Enthusiast's are a tough crowd
    OK some clarification is needed.  The idea is that the bridge can only handle at most two people.  One person can certainly cross alone and needs to in order to bring the flashlight safely back to the others.  You need the flashlight for safety as it is a dark rickety bridge
    The actual description of this puzzle was something like two sentences so you have to make assumptions about not cheating, etc.
    Raven's Fan is on the right track but were he came up with 4 and 8 I'll never know.  It's interesting to note with software it could be any four positive integers.  It would be interesting to see which give the best result for example.  For now lets stick with 1, 2, 5, and 10.
    Also if you get a solution I was hoping people would post in LabVIEW.
    I can tell you the answer which was also in the original problem and it is "17".  There is no doubt most people can solve this on paper in a few minutes but I think you will enjoy the solution.  In a way it is not common sense.  For example 1 is not the person who is used the most, as most people would think.
    Enjoy, I will post a solution once I feel people have had an adequate go at it
    -SS 
    Message Edited by ShotSimon on 09-09-2008 09:51 AM

  • GUI building difficulties, nested Frames and other stuff

    I am currently working on a GUI and I am running into some difficulties. I have created a class which extends JFrame
    public class DelFace extends JFrame implements ActionListener, ItemListenerI am instantiating an object of this class from within another object of a different class as follows:
    DelFace DelGUI = new DelFace(this,MastFile);The creation of the object takes place within the listener methods of another object:
    public void actionPerformed(ActionEvent e)
      if(e.getActionCommand().equals("Delete"))
          DelFace DelGUI = new DelFace(this,MastFile);
      }The class that creates the object that makes this call does not contain the main method. Instead the afore mentioned object is created from a class that extends JFrame
    class GUI extends JFrame implements ActionListenerSo the code in it's order of activity is as follows:
    It breaks down hardcore at the beginning
    public class StartProgram {
      private static GUI LauncherGUI;
      private static FileOps MastFile;
      public static void main(String[] args)
      MastFile = new FileOps();
      MastFile.fileStatus();            //Create File object &/or file.
      MastFile.readFile();              //Read file contents if any.
      LauncherGUI = new GUI(StartProgram.MastFile);
    }A GUI object is created, - LauncherGUI = new GUI(StartProgram.MastFile);
    From here the code differentiates somewhat - FileOperations stem from here as do all code related to the complete construction of the General User Interface.
    Specifically my difficulties lie with the GUI, therefore I will present the next peice of code related to the GUI. The following code creates a JFrame and places a whole stack of buttons on it. Included with these buttons are menus. So basically the code creates a menu bar and adds menu items to that bar and so on until a menu similar to that found in any regular program is produced. Also contained on this part of the GUI are the five buttons that are fundemental to the programs operation.
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.EventObject; //Try removing this!!
    class GUI extends JFrame implements ActionListener
      private JButton button1;
      private JButton button2;
      private JButton button3;
      private JButton button4;
      private JButton button5;
      private String Path1;
      private String Path2;
      private String Path3;
      private String Path4;
      private String Path5;
      private FileOps MastFile;
      private DataEntryBox EntryBox;
      private HelpGUI Instruct;
      FrameListener GUIListener = new FrameListener();  //Listener object created.
      GUI(FileOps MastFile)
        this.MastFile = MastFile;          //Make MastFile objects methods available
                                           //to all of LauncherGUI object.
        Toolkit tk = Toolkit.getDefaultToolkit();       //intialize the toolkit.
        Dimension sSize = tk.getScreenSize();           //determine screen size.
        Container c = getContentPane();
        GridBagLayout gridbag2 = new GridBagLayout();    //GridBagLayout object
                                                        //instantiated.
        GridBagConstraints d = new GridBagConstraints();//GridBagConstraints object
                                                        //instantiated.
        c.setLayout(gridbag2);                          //Content pane's layout set
                                                        //to gridbag object.
        d.fill = GridBagConstraints.BOTH;               //Make all components fill
                                                        //their dispaly areas
                                                        //entirely.
        d.insets = new Insets(5,1,5,1);
        JMenuBar menuBar = new JMenuBar();  //Creates Menubar object called menuBar.
        setJMenuBar(menuBar);
        JMenu FMenu = new JMenu("File");    //File Menu object instantiated.
        FMenu.setMnemonic(KeyEvent.VK_F);   //Key that activates File menu...F.
        menuBar.add(FMenu);                 //File Menu added to menuBar object.
        JMenuItem NewItem = new JMenuItem("New");   //Creates New sub-menu object.
        NewItem.setMnemonic(KeyEvent.VK_N);         //Key that activates New sub-
                                                    //menu....N.
        FMenu.add(NewItem);
        NewItem.addActionListener(this);   //ActionListner for NewItem added.
        //Tutorial Note: Steps involved in creating a menu UI are as follows,
        //1). Create an instance of a JMenuBar.
        //2). Create an instance of a JMenu.
        //3). Add items to the JMenu (not to the JMenuBar).
        //Note: It is possible to include the Mnemonic activation key as part of
        //the JMenu or JMenuItem constructor. e.g.: JMenuItem NewItem = new JMenu
        //Item("New",KeyEvent.VK_N);
        JMenuItem DeleteItem = new JMenuItem("Delete");
        DeleteItem.setMnemonic(KeyEvent.VK_D);
        FMenu.add(DeleteItem);
        DeleteItem.addActionListener(this);
        JMenuItem ExitItem = new JMenuItem("Exit",KeyEvent.VK_E); //Mnemonic key
        //included with constructor method here and from now on.
        FMenu.add(ExitItem);
        ExitItem.addActionListener(this);
        JMenu HMenu = new JMenu("Help");
        HMenu.setMnemonic(KeyEvent.VK_H);
        menuBar.add(HMenu);
        JMenuItem InstructItem = new JMenuItem("Instructions",KeyEvent.VK_I);
        HMenu.add(InstructItem);
        InstructItem.addActionListener(this);
        JMenuItem AboutItem = new JMenuItem("About",KeyEvent.VK_A);
        HMenu.add(AboutItem);
        AboutItem.addActionListener(this);
        button1 = new JButton();
    /* The following if statments block first checks to see if the value held in the
    String array is equals to null (note: this only occurs when the program is first
    started and no data has been written to file). If the array is null then the
    buttons text is set to "". If the array value is not null (meaning that the file
    already holds data) then the value of the array is checked. If the value equals
    the String "null" then button text is set to "", otherwise button text is set to
    the relevant array value (a user defined shortcut name). Also the value of each
    buttons actionCommand is set to this string value. */
        if(MastFile.getFDArray(0) == null)
          button1.setText("");
          button1.setActionCommand("Link1");
        else
        if(MastFile.getFDArray(0) != null)
          if(MastFile.getFDArray(0).equals("null"))
            button1.setText("");
            button1.setActionCommand("Link1");
          else
            button1.setText(MastFile.getFDArray(0));
            button1.setActionCommand(MastFile.getFDArray(0));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 0;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button1, d);
        c.add(button1);
        button1.addActionListener(this);
        button2 = new JButton();
        if(MastFile.getFDArray(2) == null) //If the file contains no contents then..
          button2.setText("");
          button2.setActionCommand("Link2");
        else
        if(MastFile.getFDArray(2) != null)
          if(MastFile.getFDArray(2).equals("null"))//If the file contains the string
          {                                        //"null" then do as above.
            button2.setText("");
            button2.setActionCommand("Link2");
          else  //Set both button text and actionCommand to relevant shortcut name.
            button2.setText(MastFile.getFDArray(2));
            button2.setActionCommand(MastFile.getFDArray(2));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 1;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button2, d);
        c.add(button2);
        button2.addActionListener(this);
        button3 = new JButton();
        if(MastFile.getFDArray(4) == null)
          button3.setText("");
          button3.setActionCommand("Link3");
        else
        if(MastFile.getFDArray(4) != null)
          if(MastFile.getFDArray(4).equals("null"))
            button3.setText("");
            button3.setActionCommand("Link3");
          else
            button3.setText(MastFile.getFDArray(4));
            button3.setActionCommand(MastFile.getFDArray(4));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 2;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button3, d);
        c.add(button3);
        button3.addActionListener(this);
        button4 = new JButton();
        if(MastFile.getFDArray(6) == null)
          button4.setText("");
          button4.setActionCommand("Link4");
        else
        if(MastFile.getFDArray(6) != null)
          if(MastFile.getFDArray(6).equals("null"))
            button4.setText("");
            button4.setActionCommand("Link4");
          else
            button4.setText(MastFile.getFDArray(6));
            button4.setActionCommand(MastFile.getFDArray(6));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 3;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button4, d);
        c.add(button4);
        button4.addActionListener(this);
        button5 = new JButton();
        if(MastFile.getFDArray(8) == null)
          button5.setText("");
          button5.setActionCommand("Link5");
        else
        if(MastFile.getFDArray(8) != null)
          if(MastFile.getFDArray(8).equals("null"))
            button5.setText("");
            button5.setActionCommand("Link5");
          else
            button5.setText(MastFile.getFDArray(8));
            button5.setActionCommand(MastFile.getFDArray(8));
        d.weightx = 0.2;  //Specifies horizontal sizing behaviour.
        d.weighty = 0.3;  //Specifies vertical resizing behaviour.
        d.gridx = 4;      //c.gridx and c.gridy specify the x,y starting position
        d.gridy = 0;      //of this label, in regard to column and row respectively.
        gridbag2.setConstraints(button5, d);
        c.add(button5);
        button5.addActionListener(this);
        Path1 = MastFile.getFDArray(1);       //Load Path variables with path
        Path2 = MastFile.getFDArray(3);       //details from String Array in
        Path3 = MastFile.getFDArray(5);       //MastFile object of FileOps class.
        Path4 = MastFile.getFDArray(7);       //Effectively loading these variables
        Path5 = MastFile.getFDArray(9);       //with file data.
        this.addWindowListener(GUIListener);  //Listener registered with Frame.
        setLocation(sSize.width*1/2,sSize.height*1/20);
        setSize(sSize.width*1/2,sSize.height*1/7);
        setTitle("Java QuickLaunch Toolbar");
        setVisible(true);
      /* The following methods return the ActionCommand and Text Label
         String values of the buttons */
      public String getButton1Command()
        return button1.getActionCommand();
      public String getButton2Command()
        return button2.getActionCommand();
      public String getButton3Command()
        return button3.getActionCommand();
      public String getButton4Command()
        return button4.getActionCommand();
      public String getButton5Command()
        return button5.getActionCommand();
      public String getBt1Text()
        return button1.getText();
      public String getBt2Text()
        return button2.getText();
      public String getBt3Text()
        return button3.getText();
      public String getBt4Text()
        return button4.getText();
      public String getBt5Text()
        return button5.getText();
      /* The following methods set the Path, Button and ActionCommand String values. */
      public void setPath1(String setPath)
        Path1 = setPath;
      public void setPath2(String setPath)
        Path2 = setPath;
      public void setPath3(String setPath)
        Path3 = setPath;
      public void setPath4(String setPath)
        Path4 = setPath;
      public void setPath5(String setPath)
        Path5 = setPath;
      public void setButton1(String setButton)
        button1.setText(setButton);
      public void setButton2(String setButton)
        button2.setText(setButton);
      public void setButton3(String setButton)
        button3.setText(setButton);
      public void setButton4(String setButton)
        button4.setText(setButton);
      public void setButton5(String setButton)
        button5.setText(setButton);
      public void setBt1Action(String setAct)
        button1.setActionCommand(setAct);
      public void setBt2Action(String setAct)
        button2.setActionCommand(setAct);
      public void setBt3Action(String setAct)
        button3.setActionCommand(setAct);
      public void setBt4Action(String setAct)
        button4.setActionCommand(setAct);
      public void setBt5Action(String setAct)
        button5.setActionCommand(setAct);
      /* actionPerformed methods */
      public void actionPerformed(ActionEvent e)
        if(e.getActionCommand().equals("New"))
          //Create a data entry box.
          EntryBox = new DataEntryBox(this,MastFile);
        else
        if(e.getActionCommand().equals("Delete"))//Example part of interest
          DelFace DelGUI = new DelFace(this,MastFile);   /// -------- ////
        else
        if(e.getActionCommand().equals("Exit"))
          System.exit(0);
        else
        if(e.getActionCommand().equals("Instructions"))
          Instruct = new HelpGUI();
        else
        if(e.getActionCommand().equals("About"))
          JOptionPane.showMessageDialog(this,"Java QuickLaunch Toolbar created by David "+
                                        "Dartnell.","Programming Credits",1);
        else
          if(e.getActionCommand().equals(button1.getActionCommand())) //Determine source of event.
          if(Path1 == null)                        //If Path var is a null reference
            EntryBox = new DataEntryBox(this,MastFile);//create a data entry box.
          else
          if(Path1 != null)                        //If not a null reference then...
            if(Path1.equals("null"))               //Determine if string is "null".
              EntryBox = new DataEntryBox(this,MastFile);
            else        //If both the reference and the String are not null then run
            {           //the relevant command/program.
              try
                Runtime.getRuntime().exec(new String[]{Path1});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button2.getActionCommand()))
          if(Path2 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path2 != null)
            if(Path2.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path2});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button3.getActionCommand()))
          if(Path3 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path3 != null)
            if(Path3.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path3});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button4.getActionCommand()))
          if(Path4 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path4 != null)
            if(Path4.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path4});
              catch(IOException run){}
        else
        if(e.getActionCommand().equals(button5.getActionCommand()))
          if(Path5 == null)
            EntryBox = new DataEntryBox(this,MastFile);
          else
          if(Path5 != null)
            if(Path5.equals("null"))
              EntryBox = new DataEntryBox(this,MastFile);
            else
              try
                Runtime.getRuntime().exec(new String[]{Path5});
              catch(IOException run){}
    Something to consider concerning actionListeners:
    It must be remembered that String values are in fact objects and as such
    they require the equals() method unlike their cousins the primitive data
    types (int, float, boolean, byte, short, long and double) which require
    the == operator.
    */A comment is placed next to the line of code that is of interest to my problem (///-------////).
    When a button is pressed in the menu section that reads "Delete" then an actionCommand event is fired and the program responds by creating a second general user interface.
    When DelFace is instantiated in the form of the object called DelGUI I am once again creating an object which extends JFrame. I now have two objects of type JFrame on the screen at once, and I conveniently position one over the top of the other, so to the general user the programs appearance has changed in only very specified ways (i.e.: I have decided to increase the GUI's dimensions in the area of height only and not width). The code that constitutes class DelFace is as follows:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class DelFace extends JFrame implements ActionListener, ItemListener
      private GUI TkBar;        //GUI object.
      private FileOps Fops;     //File Operations object.
      private JCheckBox ckbox1; //Delete shortcut 1.
      private JCheckBox ckbox2; //Delete shortcut 2.
      private JCheckBox ckbox3; //Delete shortcut 3.
      private JCheckBox ckbox4; //Delete shortcut 4.
      private JCheckBox ckbox5; //Delete shortcut 5.
      private JButton OkBtn;    //OK button.
      private JButton CnBtn;    //Cancel button.
      private JOptionPane confirm;
      private boolean short1 = false;  //Boolean variables indicate whether to
      private boolean short2 = false;  //delete a shortcut entry. True = delete.
      private boolean short3 = false;
      private boolean short4 = false;
      private boolean short5 = false;
      DelFace(GUI TkBar, FileOps Fops)
        this.TkBar = TkBar;
        this.Fops = Fops;
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension sSize = tk.getScreenSize();
        Container dcon = getContentPane();
        GridBagLayout gb = new GridBagLayout();
        GridBagConstraints bagcon = new GridBagConstraints();
        dcon.setLayout(gb);
        bagcon.fill = GridBagConstraints.BOTH;
        bagcon.gridwidth = GridBagConstraints.REMAINDER;
        JLabel TLabel = new JLabel("Delete Wizard",JLabel.CENTER);
        TLabel.setFont(new Font("Tahoma",Font.BOLD+Font.ITALIC,32));
        bagcon.gridx = 0;
        bagcon.gridy = 0;
        bagcon.weightx = 1.0;      //Take up all the 'x room' in this row.
        bagcon.weighty = 0.5;      //Take up all the 'y room' in this column.
        /* The weightx and weighty values are required otherwise all components will
           gravitate toward the center of screen. */
        gb.setConstraints(TLabel,bagcon);
        dcon.add(TLabel);
        JTextArea TxArea = new JTextArea("Tick the box(s) of the shortcut(s)"+
                               " that you would like to delete and"+
                               " press the Delete button. Alternatively"+
                               " press the Cancel button to exit.");
        TxArea.setLineWrap(true);
        TxArea.setWrapStyleWord(true);
        TxArea.setEditable(false);
        TxArea.setFont(new Font("Times New Roman",Font.PLAIN,15));
        TxArea.setBackground(this.getBackground());
        bagcon.gridx = 0;
        bagcon.gridy = 1;
        gb.setConstraints(TxArea,bagcon);
        dcon.add(TxArea);
        bagcon.gridwidth = 1;
        JPanel Nopan1 = new JPanel();
        bagcon.gridx = 0;
        bagcon.gridy = 2;
        gb.setConstraints(Nopan1,bagcon);
        dcon.add(Nopan1);
        ckbox1 = new JCheckBox(TkBar.getBt1Text());
        bagcon.gridx = 1;
        bagcon.gridy = 2;
        gb.setConstraints(ckbox1,bagcon);
        dcon.add(ckbox1);
        ckbox1.addItemListener(this);
        ckbox2 = new JCheckBox(TkBar.getBt2Text());
        bagcon.gridy = 3;
        gb.setConstraints(ckbox2,bagcon);
        dcon.add(ckbox2);
        ckbox2.addItemListener(this);
        ckbox3 = new JCheckBox(TkBar.getBt3Text());
        bagcon.gridy = 4;
        gb.setConstraints(ckbox3,bagcon);
        dcon.add(ckbox3);
        ckbox3.addItemListener(this);
        ckbox4 = new JCheckBox(TkBar.getBt4Text());
        bagcon.gridy = 5;
        gb.setConstraints(ckbox4,bagcon);
        dcon.add(ckbox4);
        ckbox4.addItemListener(this);
        ckbox5 = new JCheckBox(TkBar.getBt5Text());
        bagcon.gridy = 6;
        gb.setConstraints(ckbox5,bagcon);
        dcon.add(ckbox5);
        ckbox5.addItemListener(this);
        JPanel Nopan2 = new JPanel();
        bagcon.gridx = 1;
        bagcon.gridy = 7;
        gb.setConstraints(Nopan2,bagcon);
        dcon.add(Nopan2);
        OkBtn = new JButton("OK");
        OkBtn.addActionListener(this);
        bagcon.gridx = 1;
        bagcon.gridy = 8;
        gb.setConstraints(OkBtn,bagcon);
        dcon.add(OkBtn);
        OkBtn.addActionListener(this);
        CnBtn = new JButton("Cancel");
        CnBtn.addActionListener(this);
        bagcon.gridx = 2;
        bagcon.gridy = 8;
        gb.setConstraints(CnBtn,bagcon);
        dcon.add(CnBtn);
        CnBtn.addActionListener(this);
        JPanel Nopan3 = new JPanel();
        bagcon.gridx = 3;
        bagcon.gridy = 8;
        gb.setConstraints(Nopan3,bagcon);
        dcon.add(Nopan3);
        JPanel Nopan4 = new JPanel();
        bagcon.gridx = 0;
        bagcon.gridy = 9;
        gb.setConstraints(Nopan4,bagcon);
        dcon.add(Nopan4);
        setLocation(sSize.width*1/2,sSize.height*1/20);
        setSize(sSize.width*1/2,sSize.height*4/5);
        setTitle("Java QuickLaunch Toolbar");
        setResizable(false);
        setVisible(true);
      public void actionPerformed(ActionEvent e)
      { /*--- Code of INTEREST begins here!!!!!! -------
        if(e.getActionCommand().equals("OK"))   
          if(short1 || short2 || short3 || short4 || short5)
            //confirm = new JOptionPane();
            int n = confirm.showConfirmDialog(this,
                 "Do you really want to delete?","Delete Confirmation",
                 JOptionPane.YES_NO_OPTION);
            if(n == confirm.YES_OPTION)  //Works Fine!
              while(short1 || short2 || short3 || short4 || short5)
                if(short1)
                  TkBar.setBt1Action("Link1");
                  TkBar.setButton1("");
                  TkBar.setPath1("null");
                  Fops.setFDArray(0,"null");
                  Fops.setFDArray(1,"null");
                  short1 = false;
                else
                if(short2)
                  TkBar.setBt2Action("Link2");
                  TkBar.setButton2("");
                  TkBar.setPath2("null");
                  Fops.setFDArray(2,"null");
                  Fops.setFDArray(3,"null");
                  short2 = false;
                else
                if(short3)
                  TkBar.setBt3Action("Link3");
                  TkBar.setButton3("");
                  TkBar.setPath3("null");
                  Fops.setFDArray(4,"null");
                  Fops.setFDArray(5,"null");
                  short3 = false;
                else
                if(short4)
                  TkBar.setBt4Action("Link4");
                  TkBar.setButton4("");
                  TkBar.setPath4("null");
                  Fops.setFDArray(6,"null");
                  Fops.setFDArray(7,"null");
                  short4 = false;
                else
                if(short5)
                  TkBar.setBt5Action("Link5");
                  TkBar.setButton5("");
                  TkBar.setPath5("null");
                  Fops.setFDArray(8,"null");
                  Fops.setFDArray(9,"null");
                  short5 = false;
              Fops.destroyFile();   //Destroy the old (outdated) file.
              Fops.fileStatus();    //Create a new file.
              Fops.writeFile();     //Write updated data to new file.
              setVisible(false);
            if(n == confirm.NO_OPTION)  //** Does not work ***
              System.out.println("No Option is being heard");
              //Listeners are working.
              //confirm.setVisible(false);
            if(n == confirm.CLOSED_OPTION) //** Does not work ***
              System.out.println("Closed Option is being heard");
              //Listeners are working.
              //confirm.setVisible(false);
        --- Code of interest ENDS here --- */
        else
        if(e.getActionCommand().equals("Cancel"))
          setVisible(false); 
      public void itemStateChanged(ItemEvent f)
        int state = f.getStateChange();
        if(state == ItemEvent.SELECTED)   //If a checkbox has been selected.
          if(f.getItem() == ckbox1)
            short1 = true;
          else
          if(f.getItem() == ckbox2)
            short2 = true;
          else
          if(f.getItem() == ckbox3)
            short3 = true;
          else
          if(f.getItem() == ckbox4)
            short4 = true;
          else
          if(f.getItem() == ckbox5)
            short5 = true;
        if(state == ItemEvent.DESELECTED)  //If a checkbox has been deselected.
          if(f.getItem() == ckbox1)
            short1 = false;
          else
          if(f.getItem() == ckbox2)
            short2 = false;
          else
          if(f.getItem() == ckbox3)
            short3 = false;
          else
          if(f.getItem() == ckbox4)
            short4 = false;
          else
          if(f.getItem() == ckbox5)
            short5 = false;
    }The code that is of interest to my current programming challenge is marked in the above code block like this:
    //*** Code of INTEREST begins here!!!!!! ********** //
    This is where my programming twilight behaviour begins to kick in. From the DelGUI object I now listen to a button event, this event when triggered causes a JOptionPane.showConfirmDialog(), as can be seen in the specified code block above. I make the JOptionPane centered over the DelGUI object ("JFrame No.: 2") which is also centered over the LauncherGUI object ("JFrame No.: 1").
    The program begins to behave quite strangely after the creation of the JOptionPane object called confirm. The JOptionPane is presented on screen without any visiual difficulty but it behaves quite strangely when it's buttons are pressed. The JOptionPane contains three event sources, the YES, NO and Close buttons.
    In my program the YES button causes a set of file operations to take place and then sets the "JFrame No.: 2"(DelGUI) invisible. It does this via the method setVisible(false). "JFrame No.: 2" is effectively the JOptionPane's parent component and as soon as it is setVisible(false) the JOptionPane is also cleared from the screen. I believe from my research that this is the JOptionPane's default behaviour, meaning that as soon as a button or event source is activated the JOptionPane will destroy itself.
    The end of the trail is near, thankyou for reading this if you have got this far, and please carry on....
    The Challenge:
    The program does not behave as desired at the two points in the code commented as such: ** Does not work ***
    if(n == confirm.NO_OPTION)
              System.out.println("No Option is being heard");
              //confirm.setVisible(false);
            if(n == confirm.CLOSED_OPTION)
              System.out.println("Closed Option is being heard");
              //confirm.setVisible(false);
            }If the NO_OPTION or the CLOSED_OPTION are pressed then the JOptionPane remains visible. After pressing the JoptionPane's button a second time it will disappear completely. I have tried a number of things in an attempt to work this out. Firstly I have inserted println messages to ensure that the events are being detected. These messages are always displayed whenever either the NO or Close buttons are pressed.
    As these messages are being passed to the Standard Output, twice by the time the JOptionPane has disappeared, I can only assume that the events are being detected.
    In addition to checking the event situation I have attempted to explicity set the JOptionPane invisible, in the form:
    confirm.setVisible(false); The above line of code did not change the situation. Still I need two button clicks for the JOptionPane to display it's default behaviour which is to set itself invisible (or possibly the object is alloted to garbage collection), either way it is no longer on screen. I have also tried this code with no if statements related to NO_OPTION and CLOSE_OPTION. This was done in an attempt to allow the default behaviour to take place. Unfortunately two presses were still required in this situation.
    A forum member mentioned the possibility that two JOptionPanes are being created. I have checked my code and am confident that I have not explicitly created the JOptionPane twice (the code throughout this question should support this).
    Is it possible that two JOptionPanes are being created because of the nature of my code, the fact that there are two JFrames on the screen at once when the JOptionPane is instantiated? I am using the this keyword to specify the parent of the JOptionPan

    Well, I've checked your code and I've seen where is the error.
    In Delface constructor (Delface.java, line 127), you've got this block of code :
    1. OkBtn = new JButton("OK");
    2. OkBtn.addActionListener(this);
    3. bagcon.gridx = 1;
    4. bagcon.gridy = 8;
    5. gb.setConstraints(OkBtn,bagcon);
    6. dcon.add(OkBtn);
    7. OkBtn.addActionListener(this);
    Have a deep look at lines 2 and 7 : you're registering twice an actionListener on this button. Then you're receiving twice the event and it shows two JOptionPanes. In fact, you've also the problem with the 'ok' option, but you don't see it, because the 'n' variable in your event handler is global to your class, then it's shared between the two calls to the event handlers.

  • Faces is missing so many faces... any way to get it to rescan?

    Is there a way to get Faces to re-scan my library (without losing what I already have tagged)?
    It took about 2 hours for it to scan my library initially but as I go through and tag, I am seeing hundreds upon hundreds of photos where perfect faces aren't even recognized as a face. Maybe a button to re-scan the current photo? Something. I am not looking forward to manually highlighting and tagging all these photos.
    I hate to say it, but so far Google's face recognition in Picasa has been more accurate than this, and I'm using both with the same 17GB photo library.

    Ah, this is my thread!
    I just spent half an hour reading posts here, looking for people reporting the same lame experience I've had. And here you are. I am also experiencing the problems described in this thread. I'd like to add a concern to the ones already mentioned:
    Faces has completely stopped making suggestions.
    For instance, my wife is fond of self-portraits. Every now and then she'll take a few hundred pictures of herself for kicks (and mine). These sets of photos tend to be extremely similar — dozens of nearly identical pictures of her pretty face that haven't been even been identified as faces, let alone as her. Yet the "Kim may also be in the photos below" section is empty. Not one suggestion!
    I can completely expected the facial recognition feature to fail with many lower-quality pictures, and I would certainly have forgiven that. Low contrast lighting, countless possible angles, foreground obstructions and many other variables make facial recognition an incredible programming challenge.
    But I did not expect this feature to fail to recognize many good quality pictures! And I find it hard to forgive the iPhoto development team for this. There's a (really) big difference between failing with poor input and failing with good input. It's sloppy and embarrassing and yet another reason why I'm not exactly tripping over myself to recommend Macs to my PC-using friends.
    Sigh.

  • List fonts used in a document, search by font.

    Help! I cannot find a way to list, by name, of the fonts used (past tense) in a document. Like in the document properties: where the word and character count is.
    Example: The author used Arial, Arial Condensed and OCR A in her document. I would like to see a list of three font names. If I have (or don't have) those fonts is outside the scope of this request.
    Simply smashing the styles of a document and then restylng by hand is not working so well for me. Most of the documents used manual formatting instead of styles too!
    Second: I can search and replace text if it had a font applied to it, but I cannot specify the font to search on. ANY font will be match and changed to the 'replace' style. Any solution?
    Thanks!
    John Fields

    Interesting request and a bit of a programing challenge but here is what I have come up with. Try it on some of the documents that you need to deal with and let me know how it does.
    Sub FontsUsed 'Version 1 John Vigor 4/25/06
    'List fonts used in Writer document. Appears to work in normal text,
    'Sections, normal Tables, and Frames. Will currently crash on a Table
    'within a Table.
    oDoc = ThisComponent
    Dim fonts as Integer: Dim aFonts(1)
    oTC = oDoc.Text.createTextCursor
    oTC.goRight(1,true) : CurrentFont = oTC.charFontName
    fonts = fonts + 1 : aFonts(fonts) = CurrentFont
    REM Do "normal" text.
    partEnum = oDoc.Text.createEnumeration
    PartEnumerator(partEnum,CurrentFont,fonts,aFonts())
    REM Do Frames.
    oFrames = oDoc.getTextFrames
    If oFrames.Count > 0 then
    fonts = fonts + 1 : ReDim Preserve aFonts(fonts)
    aFonts(fonts) = "NEW FONTS, IF ANY, FOUND IN FRAMES:"
    For I = 0 to oFrames.Count - 1
      thisFrame = oFrames.getByIndex(I)
      partEnum = thisFrame.createEnumeration
      PartEnumerator(partEnum,CurrentFont,fonts,aFonts())
    Next
    EndIf
    REM Prepare list.
    For I = 1 to fonts
    s = s & aFonts(I) & Chr(10)
    Next
    iAns = MsgBox(s,4,"FONTS FOUND. Create font list document?")
    If iAns = 7 then
      End
    Else
      NewDoc = StarDesktop.loadComponentFromURL("private:factory/swriter"," blank",O,Array())
      oVC = NewDoc.CurrentController.getViewCursor
      oVC.String = s : oVC.collapseToEnd
    EndIf  
    End Sub
    Sub PartEnumerator(partEnum,CurrentFont,fonts,aFonts())
    While partEnum.hasMoreElements
    thisElement = partEnum.nextElement
    If thisElement.supportsService("com.sun.star.text.Paragraph") then
       portionEnum = thisElement.createEnumeration
       PortionEnumerator(portionEnum,CurrentFont,fonts,aFonts())
      ElseIf thisElement. supportsService ("com.sun.star.text.TextTab le") then
       Cols = thisElement.getColumns.Count - 1
       Rows = thisElement.getRows.Count - 1
       For C = 0 to Cols
        For R = 0 to Rows
         thisCell = thisElement.getCellByPosition(C,R)
         cellEnum = thisCell.createEnumeration
         While cellEnum.hasMoreElements
          thisPara = cellEnum.nextElement
          portionEnum = thisPara.createEnumeration
          PortionEnumerator(portionEnum,CurrentFont,fonts,aFonts())
         Wend
        Next
       Next
    EndIf
    Wend
    End Sub
    Sub PortionEnumerator(portionEnum,CurrentFont,fonts,aFonts())
    Dim found as Boolean
    While portionEnum.hasMoreElements
    thisPortion = portionEnum.nextElement
    thisFont = thisPortion.charFontName
    If thisFont <> CurrentFont then
      For I = 1 to fonts
       If aFonts(I) = thisFont then found = true: Exit For
      Next
      If found then
       CurrentFont = thisFont : found = false Else
       fonts = fonts + 1 : ReDim Preserve aFonts(fonts)
       aFonts(fonts) = thisFont : CurrentFont = thisFont
      EndIF
    EndIf
    Wend
    End Sub

  • How to keep socket alive

    Dear All Java Devotees....
    I was stucked upon the following socket programming challenge in my projects
    first of all I have one Server and one Client
    what I wanted initially was client registered to server
    when the client abruptly terminated, it wont have any effect at all to the server
    But in line with the Java Socket Programming Tutorial
    it seems that it cant be done so easily
    whenever I close down my client
    Server will catch java.net.SocketException: Connection reset
    so my question basically :
    Is it possible for the Server to keeps iterating in a loop
    while listening for a client to register
    but here is the catch, I dun want anything severe happen to the Server
    when somebody close down the Client abruptly
    If possible I would like the server to keep its normal program flow
    I mean sort of roll-back to the state before the exception occured
    My punchline is to "keep the server program flow"
    Any Idea/snippet will be greatly appreciated....
    best regards,
    Honggo

    Hi Joey
    sorry I've misled you
    I've managed to solve the problem though
    but now facing a new problem
    I will be grateful if u come across the same problem
    here is the scenario:
    1. client starts
    2. server stars
    3. client & server bound to socket
    4. client sending some information to server
    5. server stops
    I've followed your suggestion to use for loops and spawn a new thread for each accepted socket
    it's a very simple & helpful idea, but as I observer i hit some shortcomings. I wish you could enlighten me with snippet of code, perhaps :D
    after steps 5 which is when the server stops, client is unaware that server has already dead.
    i've tried every methods described in the API (e.g. isClosed, isConnected, etc) but client didnt catch exception when client is sending some infomation to the "deceased" server.
    So my question: How to detect whether or not the server is dead (in client).
    regards,
    Honggo

  • Screen shot of the t420 with 1600x900

    Could someone with a t420 with 1600x900 resolution provide a screen shot of their screen?
    Thank You!

    Hi,
    I'd approach this task as follows:
    - type in the SCN search field (top right corner) the following search criteria: attach screenshot mail
    - just to be sure, restrict the results list to 'Collaborative Document'
    - study the first document titled: "Taking SAP GUI screenshot automatically and send as attachment through mail programmatically"
    - go on program my logic and thank the author of document
    In case it was the whole report output I was trying to send and not one screenshot, I'd probably be searching for: retrieve abap list memory.
    I mean no disrespect; it's just my "elaborate" way of saying: if you have an ABAP programming challenge, more likely than not the help and guidance is already on SCN - it's about searching and finding it
    cheers
    Jānis

Maybe you are looking for