问:
How to count each element from a pdb file
I am having trouble trying to count the amount of each element provided in a pdb file. So far, the code has achieved to take the lines from the file that starts with ATOM. I have also gotten to the point where I can print each element. But  now I want to count each element such as C,O,N, and so on and list them in alphabetical order.
The data looks like this:

```<code> ATOM   4851  O   PRO A 715      89.164  76.083  75.292  1.00 99.41           O
 ATOM   4852  CB  PRO A 715      88.324  78.267  73.865  1.00 95.88           C
 ATOM   4853  CG  PRO A 715      88.836  78.838  72.540  1.00 95.93           C
 ATOM   4854  CD  PRO A 715      90.288  78.546  72.593  1.00 94.99           C
 ATOM   4855  N   PHE A 716      90.009  77.320  76.994  1.00100.00           N
 ATOM   4856  CA  PHE A 716      90.100  76.203  77.966  1.00 99.66           C
 ATOM   4857  C   PHE A 716      89.942  76.667  79.419  1.00 99.17           C
 ATOM   4858  O   PHE A 716      88.895  76.334  80.027  1.00100.00           O
 ATOM   4859  CB  PHE A 716      91.409  75.402  77.819  1.00 97.04           C
 ATOM   4860  CG  PHE A 716      91.290  74.219  76.899  1.00 96.00           C
 ATOM   4861  CD1 PHE A 716      90.323  73.236  77.133  1.00 94.17           C
 ATOM   4862  CD2 PHE A 716      92.112  74.107  75.774  1.00 94.87           C
 ATOM   4863  CE1 PHE A 716      90.170  72.157  76.260  1.00 93.04           C
 ATOM   4864  CE2 PHE A 716      91.971  73.037  74.894  1.00 93.41           C
 ATOM   4865  CZ  PHE A 716      90.996  72.057  75.137  1.00 95.29           C
</code>```

My code is :

```<code>open (FILE, $ARGV[0])
    or die "Could not open file\n";

my @newlines;
while ( my $line = <FILE> ) {
    if ($line =~ m/^ATOM.*/) {
    push @newlines, $line;
    }
}

##############################################################
#This function will take out the element from each line
#The element is from column 77 and contains one or two letters
#The function will also sort each element alphabetically and count them
sub atomfreq {
    foreach my $record1(@newlines) {
      my @element = substr($record1, 76, 2);
      my @sortelement = sort(@element);
      print "@sortelement\n";
    }
}
</code>```

Thanks.

答:
For counting the occurences of the elements C, O and N (and others) a hash is the proper data structure.
Use the elements as keys and increment the corresponding value. After the loop you can then print the hash sorted by its keys:

```<code>sub atomfreq {
    my %count;
    foreach my $record1(@newlines) {
        my $element = substr($record1, 76, 2);
        $count{$element} += 1;
    }
    foreach my $element ( sort keys %count ) {
        print "element=$element, count=$count{$element}\n";
    }
}
</code>```

Body:
I am having trouble trying to count the amount of each element provided in a pdb file. So far, the code has achieved to take the lines from the file that starts with ATOM. I have also gotten to the point where I can print each element. But  now I want to count each element such as C,O,N, and so on and list them in alphabetical order.
The data looks like this:

 ATOM   4851  O   PRO A 715      89.164  76.083  75.292  1.00 99.41           O
 ATOM   4852  CB  PRO A 715      88.324  78.267  73.865  1.00 95.88           C
 ATOM   4853  CG  PRO A 715      88.836  78.838  72.540  1.00 95.93           C
 ATOM   4854  CD  PRO A 715      90.288  78.546  72.593  1.00 94.99           C
 ATOM   4855  N   PHE A 716      90.009  77.320  76.994  1.00100.00           N
 ATOM   4856  CA  PHE A 716      90.100  76.203  77.966  1.00 99.66           C
 ATOM   4857  C   PHE A 716      89.942  76.667  79.419  1.00 99.17           C
 ATOM   4858  O   PHE A 716      88.895  76.334  80.027  1.00100.00           O
 ATOM   4859  CB  PHE A 716      91.409  75.402  77.819  1.00 97.04           C
 ATOM   4860  CG  PHE A 716      91.290  74.219  76.899  1.00 96.00           C
 ATOM   4861  CD1 PHE A 716      90.323  73.236  77.133  1.00 94.17           C
 ATOM   4862  CD2 PHE A 716      92.112  74.107  75.774  1.00 94.87           C
 ATOM   4863  CE1 PHE A 716      90.170  72.157  76.260  1.00 93.04           C
 ATOM   4864  CE2 PHE A 716      91.971  73.037  74.894  1.00 93.41           C
 ATOM   4865  CZ  PHE A 716      90.996  72.057  75.137  1.00 95.29           C

My code is :

open (FILE, $ARGV[0])
    or die "Could not open file\n";

my @newlines;
while ( my $line = <FILE> ) {
    if ($line =~ m/^ATOM.*/) {
    push @newlines, $line;
    }
}

##############################################################
#This function will take out the element from each line
#The element is from column 77 and contains one or two letters
#The function will also sort each element alphabetically and count them
sub atomfreq {
    foreach my $record1(@newlines) {
      my @element = substr($record1, 76, 2);
      my @sortelement = sort(@element);
      print "@sortelement\n";
    }
}

Thanks.

Body:
For counting the occurences of the elements C, O and N (and others) a hash is the proper data structure.
Use the elements as keys and increment the corresponding value. After the loop you can then print the hash sorted by its keys:

sub atomfreq {
    my %count;
    foreach my $record1(@newlines) {
        my $element = substr($record1, 76, 2);
        $count{$element} += 1;
    }
    foreach my $element ( sort keys %count ) {
        print "element=$element, count=$count{$element}\n";
    }
}


来源: stackexchange

问:
JLabels only appear after resize of window
```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class Gui extends JFrame {

    JPanel panel1;
    JMenuBar daysMenu;
    JMenu[] days;
    JMenu chestMenu, backMenu, legsMenu, armsMenu, shouldersMenu;
    JMenuItem[] chest, back, legs, arms, shoulders;
    JLabel[] abs1, abs2;

    public Gui() {
        setResizable(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // setSize(1000,1000);
        setTitle("Gym Workout Program");
        setLocationRelativeTo(null);

        days = new JMenu[7];
        for (int i = 0; i < days.length; i++) {
            days[i] = new JMenu();
        }
        days[0].setText("MONDAY");
        days[1].setText("TUESDAY");
        days[2].setText("WEDNESDAY");
        days[3].setText("THURSDAY");
        days[4].setText("FRIDAY");
        days[5].setText("SATURDAY");
        days[6].setText("SUNDAY");
        daysMenu = new JMenuBar();
        for (JMenu day : days) {
            daysMenu.add(day);
        }
        setJMenuBar(daysMenu);

        // bodyPartsMenu
        chestMenu = new JMenu("Chest(1X12,2X10,2X8)");
        chest = new JMenuItem[5];
        for (int i = 0; i < chest.length; i++) {
            chest[i] = new JMenuItem();
        }
        chest[0].setText("Bench Press");
        chest[1].setText("Incline Press w/ Dumbbells");
        chest[2].setText("Chest Flyes w/ Dumbbells 180˚");
        chest[3].setText("Pullover w/ Dumbbells");
        chest[4].setText("Dips(Reps till failure/3X10)");
        for (JMenuItem item : chest) {
            chestMenu.add(item);
        }
        days[0].add(chestMenu);

        backMenu = new JMenu("Back(1X12,2X10,2X8)");
        back = new JMenuItem[4];
        for (int i = 0; i < back.length; i++) {
            back[i] = new JMenuItem();
        }
        back[0].setText("Pullups 3X10 TRYHARD/ Κ.Λ. Front Pulldowns");
        back[1].setText("Bend Over Row with Bar");
        back[2].setText("Lat Pulldowns");
        back[3].setText("Rowing Machine");
        for (JMenuItem item : back) {
            backMenu.add(item);
        }
        days[1].add(backMenu);

        days[2].add("KENO");

        legsMenu = new JMenu("Legs (1X12,2X10,2X8)");
        legs = new JMenuItem[5];
        for (int i = 0; i < legs.length; i++) {
            legs[i] = new JMenuItem();
        }
        legs[0].setText("Body Squat/Smith Machine/ w/Dumbbells");
        legs[1].setText("Leg Extensions Machine");
        legs[2].setText("Leg Curls Machine");
        legs[3].setText("Leg Press/ Walking Lunges w/ Dumbbells");
        legs[4].setText("Calves Machine 4X15");
        for (JMenuItem item : legs) {
            legsMenu.add(item);
        }
        days[3].add(legsMenu);

        armsMenu = new JMenu("Arms (1X12,2X10,2X8)");
        arms = new JMenuItem[6];
        for (int i = 0; i < arms.length; i++) {
            arms[i] = new JMenuItem();
        }
        arms[0].setText("Dumbbell Curls w/ twist");
        arms[1].setText("Larry Scot");
        arms[2].setText("Dumbbell Hammer Curls");
        arms[3].setText("SkullCrushers w/ Bar/Dumbbells");
        arms[4].setText("Triceps Press Downs");
        arms[5].setText("Reverse Triceps Press Downs");
        int countSeperator = 0;
        for (JMenuItem item : arms) {
            countSeperator++;
            armsMenu.add(item);
            if (countSeperator == 3) {
                armsMenu.addSeparator();
            }
        }
        days[4].add(armsMenu);

        shouldersMenu = new JMenu("Shoulders(1X12,2X10,2X8)");
        shoulders = new JMenuItem[4];
        for (int i = 0; i < shoulders.length; i++) {
            shoulders[i] = new JMenuItem();
        }
        shoulders[0].setText("Military Press Smith Machine");
        shoulders[1].setText("Lateral Raises");
        shoulders[2].setText("Shoulder Press Machine");
        shoulders[3].setText("Traps");
        for (JMenuItem item : shoulders) {
            shouldersMenu.add(item);
        }
        days[5].add(shouldersMenu);

        days[6].add("KENO");

        abs1 = new JLabel[5];
        for (int i = 0; i < abs1.length; i++) {
            abs1[i] = new JLabel();
        }
        abs1[0].setText("Full and Elbow Plank(1min each)");
        abs1[1].setText("Both Sides Plank(35-50 sec)");
        abs1[2].setText("Knee Up-LsitHold High Bar(1min each)");
        abs1[3].setText("HollowBodyHold(2X1min) LowerBackDown");
        abs1[4].setText("Wheel(2X8reps)");

        abs2 = new JLabel[3];
        for (int i = 0; i < abs2.length; i++) {
            abs2[i] = new JLabel();
        }
        abs2[0].setText("Leg Raises(3X12)");
        abs2[1].setText("Knee Raises(3X12)");
        abs2[2].setText("Side and Obliques(3X12)");

        JLabel abs3 = new JLabel("Free Choice");

        JLabel abs = new JLabel("Abs(3/3+ Times/week)");
        add(abs, BorderLayout.NORTH);

        JRadioButton b1 = new JRadioButton("Style 1");
        JRadioButton b2 = new JRadioButton("Style 2");
        JRadioButton b3 = new JRadioButton("Style 3");
        ButtonGroup group = new ButtonGroup();
        group.add(b1);
        group.add(b2);
        group.add(b3);
        JPanel panel2 = new JPanel(new GridLayout(0, 1));

        b1.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    for (JLabel label : abs1) {
                        panel2.add(label);
                    }
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    for (JLabel label : abs1) {
                        panel2.remove(label);
                    }
                }
            }
        });
        b2.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    for (JLabel label : abs2) {
                        panel2.add(label);
                    }
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    for (JLabel label : abs2) {
                        panel2.remove(label);
                    }
                }
            }
        });
        b3.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    panel2.add(abs3);
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    panel2.remove(abs3);
                }
            }
        });

        add(panel2, BorderLayout.LINE_END);
        panel1 = new JPanel(new GridLayout(0, 1, 50, 50));
        panel1.add(b1);
        panel1.add(b2);
        panel1.add(b3);

        add(panel1, BorderLayout.LINE_START);
        pack();
        setVisible(true);
    }
}
</code>```

I am trying to display my "abs workout" programme using JLabels and JRadioButtons.

I have used pack before setVisible and setVisible(true) after adding all the components but still my items(abs1 or abs2 or abs3) won't be displayed unless I resize my window.

When I click on Style 1 for example nothing happens and then if I resize my window everything seems to work fine.
Any help?

答:
You need to call revalidate() method after adding and removing the labels from the panel. Your code should look something like this.

```<code>if(e.getStateChange()==ItemEvent.SELECTED){
    for(JLabel label: abs1){
        panel2.add(label);
        revalidate();
    }
}
if(e.getStateChange()==ItemEvent.DESELECTED){
    for(JLabel label: abs1){
        panel2.remove(label);
        revalidate();
    }
}
</code>```

EDIT: The answer is similar to what has been mentioned in the comments, and a previous answer :/

ContentLicense: CC BY-SA 3.0

Body:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class Gui extends JFrame {

    JPanel panel1;
    JMenuBar daysMenu;
    JMenu[] days;
    JMenu chestMenu, backMenu, legsMenu, armsMenu, shouldersMenu;
    JMenuItem[] chest, back, legs, arms, shoulders;
    JLabel[] abs1, abs2;

    public Gui() {
        setResizable(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // setSize(1000,1000);
        setTitle("Gym Workout Program");
        setLocationRelativeTo(null);

        days = new JMenu[7];
        for (int i = 0; i < days.length; i++) {
            days[i] = new JMenu();
        }
        days[0].setText("MONDAY");
        days[1].setText("TUESDAY");
        days[2].setText("WEDNESDAY");
        days[3].setText("THURSDAY");
        days[4].setText("FRIDAY");
        days[5].setText("SATURDAY");
        days[6].setText("SUNDAY");
        daysMenu = new JMenuBar();
        for (JMenu day : days) {
            daysMenu.add(day);
        }
        setJMenuBar(daysMenu);

        // bodyPartsMenu
        chestMenu = new JMenu("Chest(1X12,2X10,2X8)");
        chest = new JMenuItem[5];
        for (int i = 0; i < chest.length; i++) {
            chest[i] = new JMenuItem();
        }
        chest[0].setText("Bench Press");
        chest[1].setText("Incline Press w/ Dumbbells");
        chest[2].setText("Chest Flyes w/ Dumbbells 180˚");
        chest[3].setText("Pullover w/ Dumbbells");
        chest[4].setText("Dips(Reps till failure/3X10)");
        for (JMenuItem item : chest) {
            chestMenu.add(item);
        }
        days[0].add(chestMenu);

        backMenu = new JMenu("Back(1X12,2X10,2X8)");
        back = new JMenuItem[4];
        for (int i = 0; i < back.length; i++) {
            back[i] = new JMenuItem();
        }
        back[0].setText("Pullups 3X10 TRYHARD/ Κ.Λ. Front Pulldowns");
        back[1].setText("Bend Over Row with Bar");
        back[2].setText("Lat Pulldowns");
        back[3].setText("Rowing Machine");
        for (JMenuItem item : back) {
            backMenu.add(item);
        }
        days[1].add(backMenu);

        days[2].add("KENO");

        legsMenu = new JMenu("Legs (1X12,2X10,2X8)");
        legs = new JMenuItem[5];
        for (int i = 0; i < legs.length; i++) {
            legs[i] = new JMenuItem();
        }
        legs[0].setText("Body Squat/Smith Machine/ w/Dumbbells");
        legs[1].setText("Leg Extensions Machine");
        legs[2].setText("Leg Curls Machine");
        legs[3].setText("Leg Press/ Walking Lunges w/ Dumbbells");
        legs[4].setText("Calves Machine 4X15");
        for (JMenuItem item : legs) {
            legsMenu.add(item);
        }
        days[3].add(legsMenu);

        armsMenu = new JMenu("Arms (1X12,2X10,2X8)");
        arms = new JMenuItem[6];
        for (int i = 0; i < arms.length; i++) {
            arms[i] = new JMenuItem();
        }
        arms[0].setText("Dumbbell Curls w/ twist");
        arms[1].setText("Larry Scot");
        arms[2].setText("Dumbbell Hammer Curls");
        arms[3].setText("SkullCrushers w/ Bar/Dumbbells");
        arms[4].setText("Triceps Press Downs");
        arms[5].setText("Reverse Triceps Press Downs");
        int countSeperator = 0;
        for (JMenuItem item : arms) {
            countSeperator++;
            armsMenu.add(item);
            if (countSeperator == 3) {
                armsMenu.addSeparator();
            }
        }
        days[4].add(armsMenu);

        shouldersMenu = new JMenu("Shoulders(1X12,2X10,2X8)");
        shoulders = new JMenuItem[4];
        for (int i = 0; i < shoulders.length; i++) {
            shoulders[i] = new JMenuItem();
        }
        shoulders[0].setText("Military Press Smith Machine");
        shoulders[1].setText("Lateral Raises");
        shoulders[2].setText("Shoulder Press Machine");
        shoulders[3].setText("Traps");
        for (JMenuItem item : shoulders) {
            shouldersMenu.add(item);
        }
        days[5].add(shouldersMenu);

        days[6].add("KENO");

        abs1 = new JLabel[5];
        for (int i = 0; i < abs1.length; i++) {
            abs1[i] = new JLabel();
        }
        abs1[0].setText("Full and Elbow Plank(1min each)");
        abs1[1].setText("Both Sides Plank(35-50 sec)");
        abs1[2].setText("Knee Up-LsitHold High Bar(1min each)");
        abs1[3].setText("HollowBodyHold(2X1min) LowerBackDown");
        abs1[4].setText("Wheel(2X8reps)");

        abs2 = new JLabel[3];
        for (int i = 0; i < abs2.length; i++) {
            abs2[i] = new JLabel();
        }
        abs2[0].setText("Leg Raises(3X12)");
        abs2[1].setText("Knee Raises(3X12)");
        abs2[2].setText("Side and Obliques(3X12)");

        JLabel abs3 = new JLabel("Free Choice");

        JLabel abs = new JLabel("Abs(3/3+ Times/week)");
        add(abs, BorderLayout.NORTH);

        JRadioButton b1 = new JRadioButton("Style 1");
        JRadioButton b2 = new JRadioButton("Style 2");
        JRadioButton b3 = new JRadioButton("Style 3");
        ButtonGroup group = new ButtonGroup();
        group.add(b1);
        group.add(b2);
        group.add(b3);
        JPanel panel2 = new JPanel(new GridLayout(0, 1));

        b1.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    for (JLabel label : abs1) {
                        panel2.add(label);
                    }
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    for (JLabel label : abs1) {
                        panel2.remove(label);
                    }
                }
            }
        });
        b2.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    for (JLabel label : abs2) {
                        panel2.add(label);
                    }
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    for (JLabel label : abs2) {
                        panel2.remove(label);
                    }
                }
            }
        });
        b3.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    panel2.add(abs3);
                }
                if (e.getStateChange() == ItemEvent.DESELECTED) {
                    panel2.remove(abs3);
                }
            }
        });

        add(panel2, BorderLayout.LINE_END);
        panel1 = new JPanel(new GridLayout(0, 1, 50, 50));
        panel1.add(b1);
        panel1.add(b2);
        panel1.add(b3);

        add(panel1, BorderLayout.LINE_START);
        pack();
        setVisible(true);
    }
}

I am trying to display my "abs workout" programme using JLabels and JRadioButtons.

I have used pack before setVisible and setVisible(true) after adding all the components but still my items(abs1 or abs2 or abs3) won't be displayed unless I resize my window.

When I click on Style 1 for example nothing happens and then if I resize my window everything seems to work fine.
Any help?

Body:
You need to call revalidate() method after adding and removing the labels from the panel. Your code should look something like this.

if(e.getStateChange()==ItemEvent.SELECTED){
    for(JLabel label: abs1){
        panel2.add(label);
        revalidate();
    }
}
if(e.getStateChange()==ItemEvent.DESELECTED){
    for(JLabel label: abs1){
        panel2.remove(label);
        revalidate();
    }
}

EDIT: The answer is similar to what has been mentioned in the comments, and a previous answer :/


问:
multithreading synchronized for loop
I am trying to write a multithreaded program that runs two threads. The two threads execute a for loop together and print out numbers 0 to 99. The problem I am having is each thread runs the for loop 0 to 99, so I get 0 to 99 twice instead of them working together to get to 99.

My results look like this

```<code>1
1
2
2
3
3
</code>```

I want something like this, where each thread prints a number all the way to 100.

```<code>1
2
3
4
all the way to 100 then stop
</code>```

What am I doing wrong?

This is my code

```<code>public class JavaApplication220 implements Runnable {

    public int i;

    public void run() {
        synchronized (this) {
            for (i = 0; i < 100; i++) {
                System.out.println(i);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(JavaApplication220.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}
</code>```

This is the main() class

```<code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NewClass {
    public static void main(String[] args) {
        JavaApplication220 thread1 = new JavaApplication220();
        JavaApplication220 thread2 = new JavaApplication220();

        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute(thread1);
        executor.execute(thread2);

        executor.shutdown();
    }
}
</code>```

答:
```<code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Test {
    public static void main(String args[]){

        AtomicInteger i = new AtomicInteger(0);
        i.set(0);
        TestingT thread1 = new TestingT(i);
        TestingT thread2 = new TestingT(i);

        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute( thread1 );
        executor.execute( thread2 );

        executor.shutdown();
    }
}
class TestingT implements Runnable {
    AtomicInteger i;
    TestingT(AtomicInteger i ){
        this.i = i;
    }
    @Override
    public void run(){
        while(this.i.get() < 100) {
            int i = this.i.incrementAndGet();
            System.out.println(Thread.currentThread().getName()+" "+i);
        }
    }
}
</code>```

<p>this should works fine with your requirements </p>

Title: multithreading synchronized for loop

Body:
I am trying to write a multithreaded program that runs two threads. The two threads execute a for loop together and print out numbers 0 to 99. The problem I am having is each thread runs the for loop 0 to 99, so I get 0 to 99 twice instead of them working together to get to 99.

My results look like this

1
1
2
2
3
3

I want something like this, where each thread prints a number all the way to 100.

1
2
3
4
all the way to 100 then stop

What am I doing wrong?

This is my code

public class JavaApplication220 implements Runnable {

    public int i;

    public void run() {
        synchronized (this) {
            for (i = 0; i < 100; i++) {
                System.out.println(i);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(JavaApplication220.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

This is the main() class

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NewClass {
    public static void main(String[] args) {
        JavaApplication220 thread1 = new JavaApplication220();
        JavaApplication220 thread2 = new JavaApplication220();

        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute(thread1);
        executor.execute(thread2);

        executor.shutdown();
    }
}

Body:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Test {
    public static void main(String args[]){

        AtomicInteger i = new AtomicInteger(0);
        i.set(0);
        TestingT thread1 = new TestingT(i);
        TestingT thread2 = new TestingT(i);

        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute( thread1 );
        executor.execute( thread2 );

        executor.shutdown();
    }
}
class TestingT implements Runnable {
    AtomicInteger i;
    TestingT(AtomicInteger i ){
        this.i = i;
    }
    @Override
    public void run(){
        while(this.i.get() < 100) {
            int i = this.i.incrementAndGet();
            System.out.println(Thread.currentThread().getName()+" "+i);
        }
    }
}

this should works fine with your requirements


问:
Ruby On rails form validation
So I've created a contact mailer, within my ruby on rails app, and wish to validate that the email being entered, is indeed an e-mail, and that the other fields have been filled.

I've downloaded and installed gem jquery-validation-rails

Here is my contact.html.erb file, I cannot see what is missing!?

```<code><!DOCTYPE html>
  <html>
  <head>
      <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
      <script src="js/jquery.validate.js"></script>
  </head>
  <body>

      <h1>Contact Us</h1>
      <p>Complete the following form</p>
      <%= form_tag request_contact_path, method: 'post' do %>
      <br>
      <%= label_tag :name, "Name" %>
      <%= text_field :name, :class => "required"%>
      <br>
      <%= label_tag :email, "Email" %>
      <%= text_field :email, :class => "required email"%>
      <br>
      <%= label_tag :telephone, "Telephone" %>
      <%= text_field :telephone, :class => "required"%>
      <br>
      <%= label_tag :message, "Message" %>
      <%= text_field :telephone, :class => "required"%>
      <br>
      <%= submit_tag "Submit", name: nil %>
      <% end %>
      <script>
          $(document).ready(function () {
              $("request_contact_path").validate();
          });
      </script>
  </body>
  </html>
</code>```

I appreciate any feedback on this as I am new to both ruby on rails and jquery.

答:
First of all $("request_contact_path").validate(); shouldnt have a # or . appended to it like $("#request_contact_path").validate(); ?.

Second, the JqueryValidate requires the field to be of type=email to validate the input against a valid email and the required attribute to make a field required, I am not a ROR guy so pardon me if I am wrong here, but looking at the code it looks like you are assigning the email to class attribute of the input

```<code><%= text_field :email, :class => "required email"%>
</code>```

change it to render the input in this format

```<code><input id="email" type="email" name="email" required="" aria-required="true">
</code>```

Title: Ruby On rails form validation

Body:
So I've created a contact mailer, within my ruby on rails app, and wish to validate that the email being entered, is indeed an e-mail, and that the other fields have been filled.

I've downloaded and installed gem jquery-validation-rails

Here is my contact.html.erb file, I cannot see what is missing!?

<!DOCTYPE html>

Contact Us

Complete the following form

      <%= form_tag request_contact_path, method: 'post' do %>

      <%= label_tag :name, "Name" %>
      <%= text_field :name, :class => "required"%>

      <%= label_tag :email, "Email" %>
      <%= text_field :email, :class => "required email"%>

      <%= label_tag :telephone, "Telephone" %>
      <%= text_field :telephone, :class => "required"%>

      <%= label_tag :message, "Message" %>
      <%= text_field :telephone, :class => "required"%>

      <%= submit_tag "Submit", name: nil %>
      <% end %>

I appreciate any feedback on this as I am new to both ruby on rails and jquery.

Body:
First of all $("request_contact_path").validate(); shouldnt have a # or . appended to it like $("#request_contact_path").validate(); ?.

Second, the JqueryValidate requires the field to be of type=email to validate the input against a valid email and the required attribute to make a field required, I am not a ROR guy so pardon me if I am wrong here, but looking at the code it looks like you are assigning the email to class attribute of the input

<%= text_field :email, :class => "required email"%>

change it to render the input in this format

<input id="email" type="email" name="email" required="" aria-required="true">


问:
Recursively requiring modules in Node
So, let's say I have two classes, each of which requires the other:

Department.js:

```<code>const Person = require("./Person");
class Department{
  constructor(id){
    this.personel = getPersonel(id).map(person => new Person(person));
  }
}
</code>```

Person.js

```<code>const Department = require("./Department");
class Person {
  constructor(id){
    this.department = new Department(getDeptOfPerson(id));
  }
}
const person = new Person(1);
const coworkers = person.department.personel;
</code>```

Now, this doesn't work, and I can kinda understand why. It says "Person" is not a constructor at Department.js. However, if I put both classes in the same file, it works just fine.

So; my question is, how do I work around this? I'd really rather not keep both of these classes in the same file -- is there a better way?

I'm running the latest version of Node.

答:
You can separate initializing objects from fetching data:

```<code>// types/Department.js
class Department {
  constructor(id, personnel) {
    this.id = id;
    this.personnel = personnel;
  }
}

// types/Person.js
class Person {
  constructor(id, department) {
    this.id = id;
    this.department = department;
  }
}

// findDepartment.js
const Department = require('./types/Department');
const Person = require('./types/Person');

function findDepartment(id) {
  const personnel = getPersonnel(id).map(person => new Person(person));
  return new Department(id, personnel);
}

// findPerson.js
const Department = require('./types/Department');
const Person = require('./types/Person');

function findPerson(id) {
  const department = getDeptOfPerson(id);
  return new Person(id, department);
}
</code>```

These can even go back on the types (findDepartment.js → Department.js, Department.findDepartment = function (id) { …) if you really want.

Title: Recursively requiring modules in Node

Body:
So, let's say I have two classes, each of which requires the other:

Department.js:

const Person = require("./Person");
class Department{
  constructor(id){
    this.personel = getPersonel(id).map(person => new Person(person));
  }
}

Person.js

const Department = require("./Department");
class Person {
  constructor(id){
    this.department = new Department(getDeptOfPerson(id));
  }
}
const person = new Person(1);
const coworkers = person.department.personel;

Now, this doesn't work, and I can kinda understand why. It says "Person" is not a constructor at Department.js. However, if I put both classes in the same file, it works just fine.

So; my question is, how do I work around this? I'd really rather not keep both of these classes in the same file -- is there a better way?

I'm running the latest version of Node.

Body:
You can separate initializing objects from fetching data:

// types/Department.js
class Department {
  constructor(id, personnel) {
    this.id = id;
    this.personnel = personnel;
  }
}

// types/Person.js
class Person {
  constructor(id, department) {
    this.id = id;
    this.department = department;
  }
}

// findDepartment.js
const Department = require('./types/Department');
const Person = require('./types/Person');

function findDepartment(id) {
  const personnel = getPersonnel(id).map(person => new Person(person));
  return new Department(id, personnel);
}

// findPerson.js
const Department = require('./types/Department');
const Person = require('./types/Person');

function findPerson(id) {
  const department = getDeptOfPerson(id);
  return new Person(id, department);
}

These can even go back on the types (findDepartment.js → Department.js, Department.findDepartment = function (id) { …) if you really want.


问:
PyMongo NoneType error when I try to use None as null for query
Hi guys and sorry for my bad english. I am using pymongo for querying to mongodb. so when i try to use None as null in my query, I get error: NoneType object is not subscriptable.

Here is an example:

```<code>db.collection.find_one({'name': "Nick", 'age': None})
# 'NoneType' object is not subscriptable error
</code>```

Can you help me to solve this problem, please?

答:
Although, not tried but try passing null instead of None:

```<code>db.collection.find_one({'name': "Nick", 'age': null})
</code>```

Body:
Hi guys and sorry for my bad english. I am using pymongo for querying to mongodb. so when i try to use None as null in my query, I get error: NoneType object is not subscriptable.

Here is an example:

db.collection.find_one({'name': "Nick", 'age': None})
# 'NoneType' object is not subscriptable error

Can you help me to solve this problem, please?

Body:
Although, not tried but try passing null instead of None:

db.collection.find_one({'name': "Nick", 'age': null})


问:
Convert an object to datetime in python
I have a dataframe like the one below.  How can I transform the reviewTime column to date format?  Currently, the reviewTime is an object.

```<code> overall    reviewTime
 6          10 19,2013
 5          06 18, 2014
 4          05 5, 2013
</code>```

overall           1682 non-null object
reviewTime        1682 non-null object

答:
Let us try something new ..

```<code>import re

df['reviewTime']=list(map(lambda x : re.sub('[^0-9]','', x),df['reviewTime'].values))

df['reviewTime'] = pd.to_datetime(df['reviewTime'].astype(str),format='%m%d%Y')
df
Out[352]:
  reviewTime
0 2013-10-19
1 2014-06-18
2 2013-05-05
</code>```

More info

```<code>list(map(lambda x : re.sub('[^0-9]','', x),df['reviewTime'].values))

Out[344]: ['10192013', '06182014', '0552013']
</code>```

Title: Convert an object to datetime in python

Body:
I have a dataframe like the one below.  How can I transform the reviewTime column to date format?  Currently, the reviewTime is an object.

 overall    reviewTime
 6          10 19,2013
 5          06 18, 2014
 4          05 5, 2013

overall           1682 non-null object
reviewTime        1682 non-null object

Body:
Let us try something new ..

import re

df['reviewTime']=list(map(lambda x : re.sub('[^0-9]','', x),df['reviewTime'].values))

df['reviewTime'] = pd.to_datetime(df['reviewTime'].astype(str),format='%m%d%Y')
df
Out[352]:
  reviewTime
0 2013-10-19
1 2014-06-18
2 2013-05-05

More info

list(map(lambda x : re.sub('[^0-9]','', x),df['reviewTime'].values))

Out[344]: ['10192013', '06182014', '0552013']


问:
how to get only positive results when applying hashCode()?
I am working on a Scala code that convert set of unique strings to unique IDs. I applied HashCode() but I got negative numbers and I need to work only with positive numbers.
I know that I have to use math.abs to get rid of the negative values but I am not sure if this is the correct solution or not.
If I read before that something like this could solve my problem

```<code>math.abs(hashCode()) * constant % size
</code>```

how can I determine the right constant? and does the size means the total number of strings?

previous questions related to that topic solved the question by using math.abs only but if the total number of string is large an overflow could happen and there is a chance to get a negative number as well. by multiplying the result with constant and take the mod of size could help. This is why I need to understand how to determine the constant and the size?

Also is there another way to get unique numbers for unique strings?

答:
To strip a sign from an Int, you can just use .abs. It does break on Int.MinValue, but you can just special case it:

```<code>def stripSign(n: Int) = math.abs(n) max 0
</code>```

or simply drop the sign bit:

```<code>def stripSign2(n: Int) = n & Int.MaxValue
</code>```

Or just use negative numbers (what's wrong with them anyway?).

To your other question, you cannot convert a bunch of unique strings to ints, and guarantee that there won't be duplications (for the simple reason that there are more strings than distinct Ints, so, if you wanted to assign an unique int to each of them, you'd run out of ints before you run out of strings), so you have to be able to handle collisions, however infrequent.

You can only shoot for lowering the probability of a collision by making your hash longer (with a 32-bit hash code, you have about 50% probability of at least one collision in a population of approximately 75000 strings, with 31 bits (if you do not want negative numbers), it is 55000, but with a 64-bit hash, the "magic number" is about 5 billion, provided that your hash function is good enough, and produces the numbers that are very evenly distributed).

Body:
I am working on a Scala code that convert set of unique strings to unique IDs. I applied HashCode() but I got negative numbers and I need to work only with positive numbers.
I know that I have to use math.abs to get rid of the negative values but I am not sure if this is the correct solution or not.
If I read before that something like this could solve my problem

math.abs(hashCode()) * constant % size

how can I determine the right constant? and does the size means the total number of strings?

previous questions related to that topic solved the question by using math.abs only but if the total number of string is large an overflow could happen and there is a chance to get a negative number as well. by multiplying the result with constant and take the mod of size could help. This is why I need to understand how to determine the constant and the size?

Also is there another way to get unique numbers for unique strings?

Body:
To strip a sign from an Int, you can just use .abs. It does break on Int.MinValue, but you can just special case it:

def stripSign(n: Int) = math.abs(n) max 0

or simply drop the sign bit:

def stripSign2(n: Int) = n & Int.MaxValue

Or just use negative numbers (what's wrong with them anyway?).

To your other question, you cannot convert a bunch of unique strings to ints, and guarantee that there won't be duplications (for the simple reason that there are more strings than distinct Ints, so, if you wanted to assign an unique int to each of them, you'd run out of ints before you run out of strings), so you have to be able to handle collisions, however infrequent.

You can only shoot for lowering the probability of a collision by making your hash longer (with a 32-bit hash code, you have about 50% probability of at least one collision in a population of approximately 75000 strings, with 31 bits (if you do not want negative numbers), it is 55000, but with a 64-bit hash, the "magic number" is about 5 billion, provided that your hash function is good enough, and produces the numbers that are very evenly distributed).


问:
What is strictness?
In Haskell, I try to understand the notion of strictness. I understand that

```<code>const x y = x
</code>```

is strict on the first argument but not on the second.
But is

```<code> ifFun pred cons alt = if pred then cons else alt
</code>```

strict? It is strict on the first argument. I understand that the fact that cons and alt are evaluated depending on the value of pred. Does that mean the function is not strict on those arguments?

答:
"Strict" is one of those words that has a precise technical meaning that has been coopted by the community to mean something a bit less formal. Here's the technical definition.

Function f is strict if f ⊥ = ⊥.

Here ⊥ is the standard symbol for an undefined computation; generally in denotational semantics there is just one and all undefined computations are indistinguishable from each other, but in Haskell as a concession to practicality we have many different kinds that can be distinguished: exceptions, infinite loops, pattern match failures, and so on. For the purposes of this answer, we'll consider them all equal.

Let's ask if const is strict. We have

```<code>const = \x -> \y -> x
</code>```

hence

```<code>const ⊥ = \y -> ⊥ ≠ ⊥
</code>```

and therefore const is not strict. But, oh, we've lost some very important communication power here! There is a good sense in which, when applied to undefined behavior, const doesn't behave well. So many people will say "strict in the nth argument" and we'll pretty much understand what they mean. It isn't obvious how to define what they mean formally, but a half-decent first stab at it goes something like this:

If function f has m arguments, then it is strict in the nth argument for some n ≤ m when ∀ a1, ..., am. f a1 a2 ... a(n-1) ⊥ a(n+1) ... am = ⊥.

(Aside: why isn't this quite right? For many functions -- including const -- we can't statically know how many arguments it has. Although const looks like it might be a two-argument function, const id () () is perfectly well typed and applies const to three arguments.)

Now we can say something like "const is strict on its first argument" and have it mean what we want it to mean (provided, as above, that const actually is a two-argument function), because ∀y. const ⊥ y = ⊥ does indeed hold.

We now also have the tools to address your question about ifFun, namely: is ifFun strict on its second argument? That is, can we cook up pred and alt such that

```<code>ifFun pred ⊥ alt ≠ ⊥ -- ?
</code>```

I think it's clear we can do so, since:

```<code>ifFun False ⊥ () = if False then ⊥ else () = () ≠ ⊥
</code>```

A similar argument shows that ifFun is "not strict on its third argument" in the popular understanding of this phrase (again modulo the provisos discussed above), but is "strict on its first argument".

Title: What is strictness?

Body:
In Haskell, I try to understand the notion of strictness. I understand that

const x y = x

is strict on the first argument but not on the second.
But is

 ifFun pred cons alt = if pred then cons else alt

strict? It is strict on the first argument. I understand that the fact that cons and alt are evaluated depending on the value of pred. Does that mean the function is not strict on those arguments?

Body:
"Strict" is one of those words that has a precise technical meaning that has been coopted by the community to mean something a bit less formal. Here's the technical definition.

Function f is strict if f ⊥ = ⊥.

Here ⊥ is the standard symbol for an undefined computation; generally in denotational semantics there is just one and all undefined computations are indistinguishable from each other, but in Haskell as a concession to practicality we have many different kinds that can be distinguished: exceptions, infinite loops, pattern match failures, and so on. For the purposes of this answer, we'll consider them all equal.

Let's ask if const is strict. We have

const = \x -> \y -> x

hence

const ⊥ = \y -> ⊥ ≠ ⊥

and therefore const is not strict. But, oh, we've lost some very important communication power here! There is a good sense in which, when applied to undefined behavior, const doesn't behave well. So many people will say "strict in the nth argument" and we'll pretty much understand what they mean. It isn't obvious how to define what they mean formally, but a half-decent first stab at it goes something like this:

If function f has m arguments, then it is strict in the nth argument for some n ≤ m when ∀ a1, ..., am. f a1 a2 ... a(n-1) ⊥ a(n+1) ... am = ⊥.

(Aside: why isn't this quite right? For many functions -- including const -- we can't statically know how many arguments it has. Although const looks like it might be a two-argument function, const id () () is perfectly well typed and applies const to three arguments.)

Now we can say something like "const is strict on its first argument" and have it mean what we want it to mean (provided, as above, that const actually is a two-argument function), because ∀y. const ⊥ y = ⊥ does indeed hold.

We now also have the tools to address your question about ifFun, namely: is ifFun strict on its second argument? That is, can we cook up pred and alt such that

ifFun pred ⊥ alt ≠ ⊥ -- ?

I think it's clear we can do so, since:

ifFun False ⊥ () = if False then ⊥ else () = () ≠ ⊥

A similar argument shows that ifFun is "not strict on its third argument" in the popular understanding of this phrase (again modulo the provisos discussed above), but is "strict on its first argument".


问:
Where to start debugging, when you get the "Activity is not responding, Force Close, Wait"?
I have worked on a simple application. It application includes diffrent levels that can be solved by placing some components inside a canvas, dragging them to the right place and so on.

The application is working fine, but when trying it on my HTC Desire 2.2, I sometimes get the warning message:

Sorry:
Activity xxxxx is not respoding.
Force Close - Wait

If I press the wait-button and let it be for some seconds (up to ~30 sec sometimes), then it runs without any problems. I don´t know where I should start debugging the code, since it happenes only once in a while.

I have read the stuff in google developer site and it was just mostly very general stuff that did not really help.

any ideas?

since, I was not able to debug the problem myself, I am going to post the most important parts of the application. Please check and let me know If I need to post more classes.

```<code>//Evrything else
Bitmap bitmap;
GraphicObject.Coordinates coords;
for (GraphicObject graphic : _graphics) {
    bitmap = graphic.getGraphic();
    coords = graphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
// draw current graphic at last...
if (_currentGraphic != null) {
    bitmap = _currentGraphic.getGraphic();
    coords = _currentGraphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
</code>```

答:
Android has a relatively good profiler support built in.
When you know the place where this ADNR will show up (e.g. with in one method of your activity, you can put that block in a tracing block:

```<code>Debug.startMethodTracing("xyz");
<your code goes here>
Debug.stopMethodTracing()
</code>```

This will upon activation write a trace file to /sdcard/xyz.trace

You can later (after such a ADNR occurred) obtain it via

```<code>adb pull /sdcard/xyz.trace
</code>```

and analyze it via

```<code>traceview xyz.trace
</code>```

Within the traceview screen, you see the method with its called methods and you can then see the timings.
See http://developer.android.com/guide/developing/tools/adb.html and http://developer.android.com/guide/developing/tools/traceview.html

Body:
I have worked on a simple application. It application includes diffrent levels that can be solved by placing some components inside a canvas, dragging them to the right place and so on.

The application is working fine, but when trying it on my HTC Desire 2.2, I sometimes get the warning message:

Sorry:
Activity xxxxx is not respoding.
Force Close - Wait

If I press the wait-button and let it be for some seconds (up to ~30 sec sometimes), then it runs without any problems. I don´t know where I should start debugging the code, since it happenes only once in a while.

I have read the stuff in google developer site and it was just mostly very general stuff that did not really help.

any ideas?

since, I was not able to debug the problem myself, I am going to post the most important parts of the application. Please check and let me know If I need to post more classes.

//Evrything else
Bitmap bitmap;
GraphicObject.Coordinates coords;
for (GraphicObject graphic : _graphics) {
    bitmap = graphic.getGraphic();
    coords = graphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
// draw current graphic at last...
if (_currentGraphic != null) {
    bitmap = _currentGraphic.getGraphic();
    coords = _currentGraphic.getCoordinates();
    canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}

Body:
Android has a relatively good profiler support built in.
When you know the place where this ADNR will show up (e.g. with in one method of your activity, you can put that block in a tracing block:

Debug.startMethodTracing("xyz");
<your code goes here>
Debug.stopMethodTracing()

This will upon activation write a trace file to /sdcard/xyz.trace

You can later (after such a ADNR occurred) obtain it via

adb pull /sdcard/xyz.trace

and analyze it via

traceview xyz.trace

Within the traceview screen, you see the method with its called methods and you can then see the timings.
See http://developer.android.com/guide/developing/tools/adb.html and http://developer.android.com/guide/developing/tools/traceview.html

ContentLicense: CC BY-SA 2.5


问:
SKLearn MLPClassifier import error
I'm unable to import MLPClassifier from SKLearn.
The version is 0.17
This is the error I get:

```<code>ImportError: cannot import name MLPClassifier
</code>```

This is my code:

```<code>from sklearn.neural_network import MLPClassifier
</code>```

I have the latest version of SKLearn I installed. I also updated it using:

pip install -U scikit-learn

答:
Run the below command. This will uninstall the older version and re install the updated version.

pip install -U scikit-learn

The message below will appear after installation.

DEPRECATION: Uninstalling a distutils installed project (scikit-learn) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.

```<code>Uninstalling scikit-learn-0.14.1:
  Successfully uninstalled scikit-learn-0.14.1
</code>```

Successfully installed scikit-learn-0.19.1

Title: SKLearn MLPClassifier import error

Body:
I'm unable to import MLPClassifier from SKLearn.
The version is 0.17
This is the error I get:

ImportError: cannot import name MLPClassifier

This is my code:

from sklearn.neural_network import MLPClassifier

I have the latest version of SKLearn I installed. I also updated it using:

pip install -U scikit-learn

Body:
Run the below command. This will uninstall the older version and re install the updated version.

pip install -U scikit-learn

The message below will appear after installation.

DEPRECATION: Uninstalling a distutils installed project (scikit-learn) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.

Uninstalling scikit-learn-0.14.1:
  Successfully uninstalled scikit-learn-0.14.1

Successfully installed scikit-learn-0.19.1


问:
starting an app after User_Present Action - not working
I would like to make an app that starts up every time the device is unlocked.

I'm new to Android and although I've read dozens of answers and the documentation there are just too many moving parts that I'm having a hard time troubleshooting.

Here is what I have ...

Structure

```<code>app
 - manifests
  -- AndroidManifest.xml
 - java
  -- DisplayMessageActivity.java
  -- MainActivity.java
 - res
 - UnlockReceiver.java
</code>```

This is in  in my AndroidManifest.xml

```<code><receiver android:name="UnlockReceiver">
    <intent-filter>
        <action android:name="android.intent.action.USER_PRESENT" />
    </intent-filter>
</receiver>
</code>```

This is my UnlockReceiver.java class

```<code>import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.xywebsolutions.myapplication.MainActivity;

public class UnlockReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent myIntent = new Intent(context, MainActivity.class);
        myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(myIntent);
    }
}
</code>```

What am I doing wrong? Is it my Structure? Do I need to add permissions before adding the receiver?

答:
You don't need any broadcast to start/stop video.
You can use onResume() of activity lifecycle to start video. onResume will be called when activity becomes visible to user.
onPause() of activity to pause the video. You can also save current play position and start from that position when activity started again using onSaveInstanceState() function   </p>

<p>For your case you can try this </p>

```<code>@Override
    public void onReceive(Context context, Intent intent) {
        //start activity
        Intent i = new Intent();
        i.setClassName("com.test", "com.test.MainActivity");
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
</code>```

Body:
I would like to make an app that starts up every time the device is unlocked.

I'm new to Android and although I've read dozens of answers and the documentation there are just too many moving parts that I'm having a hard time troubleshooting.

Here is what I have ...

Structure

app
 - manifests
  -- AndroidManifest.xml
 - java
  -- DisplayMessageActivity.java
  -- MainActivity.java
 - res
 - UnlockReceiver.java

This is in  in my AndroidManifest.xml

<receiver android:name="UnlockReceiver">
    <intent-filter>
        <action android:name="android.intent.action.USER_PRESENT" />
    </intent-filter>
</receiver>

This is my UnlockReceiver.java class

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.xywebsolutions.myapplication.MainActivity;

public class UnlockReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent myIntent = new Intent(context, MainActivity.class);
        myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(myIntent);
    }
}

What am I doing wrong? Is it my Structure? Do I need to add permissions before adding the receiver?

Body:
You don't need any broadcast to start/stop video.
You can use onResume() of activity lifecycle to start video. onResume will be called when activity becomes visible to user.
onPause() of activity to pause the video. You can also save current play position and start from that position when activity started again using onSaveInstanceState() function

For your case you can try this

@Override
    public void onReceive(Context context, Intent intent) {
        //start activity
        Intent i = new Intent();
        i.setClassName("com.test", "com.test.MainActivity");
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }


问:
mouseenter() event doesn't fully work first time
I'm creating a system that increases the margin of a container based on the height of the option-container class, but the problem is that when the event is called, It doesn't extend the option-container class.

Only after the second time does it fully extend, i.e when the mouse hovers over the header, the text appears but the margin doesn't extend, but if I do it again it does extend. It would be appreciated if the problem could be fixed only with javaScript/Jquery. Thanks in advance!

Here's the javaScript:

    $(".option1").mouseenter(function() {
        $("#info2, #info3, #info4").fadeOut(20);
        $("#info1").delay(50).fadeIn(200);
        $("#height1").height();
        var infoHeight1 = $("#height1").height();
        $(".option-container").delay(100).animate({
            marginBottom: "22px"
        }, 300);
        $("#option-container1").animate({
            marginBottom: infoHeight1 + 20
        }, 300);
        $(".option2, .option3, .option4").css({
            "text-decoration": "none"
        });
        $(this).css({
            "text-decoration": "underline"
        });
    });

    $(".option2").mouseenter(function() {
        $("#info1, #info3, #info4").fadeOut(20);
        $("#info2").delay(50).fadeIn(200);
        $("#height2").height();
        var infoHeight2 = $("#height2").height();
        $(".option-container").delay(100).animate({
            marginBottom: "22px"
        }, 300);
        $("#option-container2").animate({
            marginBottom: infoHeight2 + 20
        }, 300);
        $(".option1, .option3, .option4").css({
            "text-decoration": "none"
        });
        $(this).css({
            "text-decoration": "underline"
        });
    });

    $(".option3").mouseenter(function() {
        $("#info1, #info2, #info4").fadeOut(20);
        $("#info3").delay(50).fadeIn(200);
        $("#height3").height();
        var infoHeight3 = $("#height3").height();
        $(".option-container").delay(100).animate({
            marginBottom: "22px"
        }, 300);
        $("#option-container3").animate({
            marginBottom: infoHeight3 + 20
        }, 300);
        $(".option1, .option2, .option4").css({
            "text-decoration": "none"
        });
        $(this).css({
            "text-decoration": "underline"
        });
    });

    $(".option4").mouseenter(function() {
        $("#info1, #info2, #info3").fadeOut(200);
        $("#info4").delay(50).fadeIn(200);
        $("#height4").height();
        var infoHeight4 = $("#height4").height();
        $(".option-container").delay(100).animate({
            marginBottom: "22px"
        }, 300);
        $("#option-container4").animate({
            marginBottom: infoHeight4 + 20
        }, 300);
        $(".option1, .option2, .option3").css({
            "text-decoration": "none"
        });
        $(this).css({
            "text-decoration": "underline"
        });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   .header {
    display: inline-block;
    position: relative;
    background-color: rgb(81, 154, 226);
    font-size: 2.3em;
    height: 100px;
    color: white;
    font-family: 'saira', arial;
    text-shadow: 2px 2px #2280dd;
    width: 250px;
    text-align: center;
    text-transform: uppercase;
    margin: auto;
    top: 70px;
    -webkit-box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
    -moz-box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
    box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
    z-index: 1;
    line-height: 100px;
    }

    #container {
    text-align: center;
    width: 100%;
    }

    .option-container {
    display: inline-block;
    width: 250px;
    margin: 22px 22px 100px 22px;
    }

    .info-container {
    position: absolute;
    width: 100%;
    right: 0;
    left: 0;
    height: 100%;
    }

    .option-info {
    display: inline-block;
    position: relative;
    width: 100%;
    font-family: 'roboto', arial;
    font-size: 1.3em;
    text-align:  center;
    color: black;
    color: rgba(0, 0, 0, 0.9);
    margin: auto;
    top: 100px;
    }</code>```

hardware

                        By choosing hardware we will tailor your content by sending you tutorials and information about hardware, based on your preference. Such as how to pick out the components of a computer and understanding the specifications of PC components as to make a more informed decision when looking to buy them.

                        We will also tailor the promotions sent by us to accommodate your wants and needs. We will give you things like overclocking guides and of course how to build a computer. If you choose hardware you will also have the chance to join our premium membership and getting a full course on hardware, based on your past knowledge.

You have picked hardware as an interest

Tap the option to select it

design

                        Graphic design can be a great tool when you know what you are doing; without proper knowledge about the things that look good or how to make your ideas come to life, it is very hard to make something look nice.

 We will teach you everything from how to design a website using CSS to making digital posters, and how to make it beautiful.

                        We will send you tutorials on website design, font contrast, recommendations on graphic design tools and much, much more.

You have picked design as an interest

Tap the option to select it

software

                        The software is the backbone of any program on the internet. So it is necessary to have the knowledge of what programs are best suited for you or perhaps even how to start making your own digital creations. We will teach you how to properly manage your files and the important rules of online security; because the best anti-virus is your knowledge of what is secure and what is not.

                        We will send you recommendations on software that we find helpful and improve your digital experience and will give you the opportunity to join our premium membership where we will teach you the intricacies of software development and what to start with when developing an application.

You have picked software as an interest

Tap the option to select it

gaming

                        PC gaming is the pinnacle of digital entertainment and can be a great way to have fun and make friends, so it is important that you money gets you the best value games and performance; spending 60$ on a single game only to find it is not for you is a bad bargain.

                        By choosing gaming you will get the complete guide to gaming. We will help you pick out the right peripherals, how to optimize the game settings, get the most out of your gaming experience and how to pick out graphics cards.

You have picked gaming as an interest

Tap the option to select it

```

答:
I've seen this sort of problem before, for myself, the issue was caused because I didn't have display:block on the element that the event was being triggered for.

After the entering the element, the browser then added the display:block styling automatically, allowing for the event to work on the second attempt.

Body:
I'm creating a system that increases the margin of a container based on the height of the option-container class, but the problem is that when the event is called, It doesn't extend the option-container class.

Only after the second time does it fully extend, i.e when the mouse hovers over the header, the text appears but the margin doesn't extend, but if I do it again it does extend. It would be appreciated if the problem could be fixed only with javaScript/Jquery. Thanks in advance!

Here's the javaScript:

    $(".option1").mouseenter(function() {
        $("#info2, #info3, #info4").fadeOut(20);
        $("#info1").delay(50).fadeIn(200);
        $("#height1").height();
        var infoHeight1 = $("#height1").height();
        $(".option-container").delay(100).animate({
            marginBottom: "22px"
        }, 300);
        $("#option-container1").animate({
            marginBottom: infoHeight1 + 20
        }, 300);
        $(".option2, .option3, .option4").css({
            "text-decoration": "none"
        });
        $(this).css({
            "text-decoration": "underline"
        });
    });

    $(".option2").mouseenter(function() {
        $("#info1, #info3, #info4").fadeOut(20);
        $("#info2").delay(50).fadeIn(200);
        $("#height2").height();
        var infoHeight2 = $("#height2").height();
        $(".option-container").delay(100).animate({
            marginBottom: "22px"
        }, 300);
        $("#option-container2").animate({
            marginBottom: infoHeight2 + 20
        }, 300);
        $(".option1, .option3, .option4").css({
            "text-decoration": "none"
        });
        $(this).css({
            "text-decoration": "underline"
        });
    });

    $(".option3").mouseenter(function() {
        $("#info1, #info2, #info4").fadeOut(20);
        $("#info3").delay(50).fadeIn(200);
        $("#height3").height();
        var infoHeight3 = $("#height3").height();
        $(".option-container").delay(100).animate({
            marginBottom: "22px"
        }, 300);
        $("#option-container3").animate({
            marginBottom: infoHeight3 + 20
        }, 300);
        $(".option1, .option2, .option4").css({
            "text-decoration": "none"
        });
        $(this).css({
            "text-decoration": "underline"
        });
    });

    $(".option4").mouseenter(function() {
        $("#info1, #info2, #info3").fadeOut(200);
        $("#info4").delay(50).fadeIn(200);
        $("#height4").height();
        var infoHeight4 = $("#height4").height();
        $(".option-container").delay(100).animate({
            marginBottom: "22px"
        }, 300);
        $("#option-container4").animate({
            marginBottom: infoHeight4 + 20
        }, 300);
        $(".option1, .option2, .option3").css({
            "text-decoration": "none"
        });
        $(this).css({
            "text-decoration": "underline"
        });
    });

   .header {
    display: inline-block;
    position: relative;
    background-color: rgb(81, 154, 226);
    font-size: 2.3em;
    height: 100px;
    color: white;
    font-family: 'saira', arial;
    text-shadow: 2px 2px #2280dd;
    width: 250px;
    text-align: center;
    text-transform: uppercase;
    margin: auto;
    top: 70px;
    -webkit-box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
    -moz-box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
    box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
    z-index: 1;
    line-height: 100px;
    }

    #container {
    text-align: center;
    width: 100%;
    }

    .option-container {
    display: inline-block;
    width: 250px;
    margin: 22px 22px 100px 22px;
    }

    .info-container {
    position: absolute;
    width: 100%;
    right: 0;
    left: 0;
    height: 100%;
    }

    .option-info {
    display: inline-block;
    position: relative;
    width: 100%;
    font-family: 'roboto', arial;
    font-size: 1.3em;
    text-align:  center;
    color: black;
    color: rgba(0, 0, 0, 0.9);
    margin: auto;
    top: 100px;
    }

hardware

                        By choosing hardware we will tailor your content by sending you tutorials and information about hardware, based on your preference. Such as how to pick out the components of a computer and understanding the specifications of PC components as to make a more informed decision when looking to buy them.

                        We will also tailor the promotions sent by us to accommodate your wants and needs. We will give you things like overclocking guides and of course how to build a computer. If you choose hardware you will also have the chance to join our premium membership and getting a full course on hardware, based on your past knowledge.

You have picked hardware as an interest

Tap the option to select it

design

                        Graphic design can be a great tool when you know what you are doing; without proper knowledge about the things that look good or how to make your ideas come to life, it is very hard to make something look nice.

 We will teach you everything from how to design a website using CSS to making digital posters, and how to make it beautiful.

                        We will send you tutorials on website design, font contrast, recommendations on graphic design tools and much, much more.

You have picked design as an interest

Tap the option to select it

software

                        The software is the backbone of any program on the internet. So it is necessary to have the knowledge of what programs are best suited for you or perhaps even how to start making your own digital creations. We will teach you how to properly manage your files and the important rules of online security; because the best anti-virus is your knowledge of what is secure and what is not.

                        We will send you recommendations on software that we find helpful and improve your digital experience and will give you the opportunity to join our premium membership where we will teach you the intricacies of software development and what to start with when developing an application.

You have picked software as an interest

Tap the option to select it

gaming

                        PC gaming is the pinnacle of digital entertainment and can be a great way to have fun and make friends, so it is important that you money gets you the best value games and performance; spending 60$ on a single game only to find it is not for you is a bad bargain.

                        By choosing gaming you will get the complete guide to gaming. We will help you pick out the right peripherals, how to optimize the game settings, get the most out of your gaming experience and how to pick out graphics cards.

You have picked gaming as an interest

Tap the option to select it


问:
failed using cuda-gdb to launch program with CUPTI calls
I'm having this weird issue: I have a program that uses CUPTI callbackAPI to monitor the kernels in the program. It runs well when it's directly launched; but when I put it under cuda-gdb and run, it failed with the following error:

error: function cuptiSubscribe(&subscriber, CUpti_CallbackFunc)my_callback, NULL) failed with error CUPTI_ERROR_NOT_INITIALIZED

I've tried all examples in CUPTI/samples and concluded that programs that use callbackAPI and activityAPI will fail under cuda-gdb. (They are all well-behaved without cuda-gdb) But the fail reason differs:
If I have calls from activityAPI, then once run it under cuda-gdb, it'll hang for a minute then exit with error:

The CUDA driver has hit an internal error. Error code: 0x100ff00000001c Further execution or debugging is unreliable. Please ensure that your temporary directory is mounted with write and exec permissions.

If I have calls from callbackAPI like my own program, then it'll fail out much sooner with the same error:

CUPTI_ERROR_NOT_INITIALIZED

Any experience on this kinda issue? I really appreciate that!

答:
According to NVIDIA forum posting here and also referred to here, the CUDA "tools" must be used uniquely.  These tools include:

CUPTI

any profiler

cuda-memcheck

a debugger

Only one of these can be "in use" on a code at a time.  It should be fairly easy for developers to use a profiler, or cuda-memcheck, or a debugger independently, but a possible takeaway for those using CUPTI, who also wish to be able to use another CUDA "tool" on the same code, would be to provide a coding method to be able to disable CUPTI use in their application, when they wish to use another tool.


问:
F# generic type with static members. Is that ever possible?
I have the following situation:

1.
There are many (20 - 40) very similarly structured slowly changing data types.

2.
Each data type at the low level is represented by a unique (for a type) string label and a unique (again, for a type) key (usually string or long). The key does not change, but the label (on average) may be updated less than once a year.

3.
I "promoted" each such data type to F# DU, so that for each label/key there is a DU case. This is needed because some of the higher-level code needs to do a pattern matching. So, in a rare case when the types get updated, I want a compile error in case the things change. So, for each such type I generate/write the code like:

```<code>type CollegeSize =
    | VerySmall
    | Small
    | Medium
    | Large
    | VeryLarge
with
    static member all =
        [|
            (CollegeSize.VerySmall, "Very small (less than 2,000 students)", 1L)
            (CollegeSize.Small, "Small (from 2,001 to 5,000 students)", 2L)
            (CollegeSize.Medium, "Medium (from 5,001 to 10,000 students)", 3L)
            (CollegeSize.Large, "Large (from 10,000 to 20,000 students)", 4L)
            (CollegeSize.VeryLarge, "Very large (over 20,000 students)", 5L)
        |]
</code>```

4.
All such types are consumed in two places: F# engine, which does some calculations, and a web site. The F# engine just works with DU cases. The web sites these days, unfortunately, are mostly based on strings. So, the web team wanted a string based methods for almost any actions with the types and they are using C#.

5.
So, I created two generic factories:

```<code>type CaseFactory<'C, 'L, 'K when 'C : comparison and 'L : comparison and 'K : comparison> =
    {
        caseValue : 'C
        label : 'L
        key : 'K
    }

// DU factory: 'C - case, 'L - label, 'K - key
type UnionFactory< 'C, 'L, 'K when 'C : comparison and 'L : comparison and 'K : comparison> (all : array< 'C * 'L * 'K> ) =
    let map = all |> Array.map (fun (c, l, _) -> (c, l)) |> Map.ofArray
    let mapRev = all |> Array.map (fun (c, l, _) -> (l, c)) |> Map.ofArray
    let mapVal = all |> Array.map (fun (c, _, k) -> (c, k)) |> Map.ofArray
    let mapValRev = all |> Array.map (fun (c, _, k) -> (k, c)) |> Map.ofArray

    let allListValue : System.Collections.Generic.List<CaseFactory< 'C, 'L, 'K>> =
        let x =
            all
            |> List.ofArray
            |> List.sortBy (fun (_, s, _) -> s)
            |> List.map (fun (c, s, v) -> { caseValue = c; label = s; key = v } : CaseFactory< 'C, 'L, 'K>)
        new System.Collections.Generic.List<CaseFactory< 'C, 'L, 'K>> (x)

    //Use key, NOT label to create.
    [<CompiledName("FromKey")>]
    member this.fromKey (k : 'K) : 'C = mapValRev.Item (k)

    // For integer keys you can pass "1" instead of 1
    [<CompiledName("FromKeyString")>]
    member this.fromKeyString (s : string) : 'C = this.fromKey (convert s)

     //Use key, NOT label to create.
    [<CompiledName("TryFromKey")>]
    member this.tryFromKey (k : 'K) : 'C option = mapValRev.TryFind k

    [<CompiledName("TryFromKeyString")>]
    member this.tryFromKeyString (s : string) : 'C option = mapValRev.TryFind (convert s)

     //Use key, NOT label to create.
    [<CompiledName("TryFromKey")>]
    member this.tryFromKey (k : 'K option) : 'C option =
        match k with
        | Some x -> this.tryFromKey x
        | None -> None

    [<CompiledName("AllList")>]
    member this.allList : System.Collections.Generic.List< CaseFactory< 'C, 'L, 'K>> = allListValue

    [<CompiledName("FromLabel")>]
    member this.fromLabel (l : 'L) : 'C = mapRev.[l]

    [<CompiledName("TryFromLabel")>]
    member this.tryFromLabel (l : 'L) : 'C option = mapRev.TryFind l

    [<CompiledName("TryFromLabel")>]
    member this.tryFromLabel (l : 'L option) : 'C option =
        match l with
        | Some x -> this.tryFromLabel x
        | None -> None

    [<CompiledName("GetLabel")>]
    member this.getLabel (c : 'C) : 'L = map.[c]

    [<CompiledName("GetKey")>]
    member this.getKey (c : 'C) : 'K = mapVal.[c]
</code>```

6.
At this point everything works as a clock if I create a generic factory with the singleton for each type like:

```<code>type CollegeSizeFactory private () =
    inherit UnionFactory<CollegeSize, string, int64> (CollegeSize.all)
    static let instance = CollegeSizeFactory ()
</code>```

7.
… except that web team does not want to use Instance each and every time when they call methods of a generic factory. So, I ended up writing:

```<code>type CollegeSizeFactory private () =
    inherit UnionFactory<CollegeSize, string, int64> (CollegeSize.all)
    static let instance = CollegeSizeFactory ()
    static member Instance = instance

    static member FromLabel s = CollegeSizeFactory.Instance.fromLabel s
    static member FromKey k = CollegeSizeFactory.Instance.fromKey k
    static member FromKeyString s = CollegeSizeFactory.Instance.fromKeyString s
</code>```

The problem with that is that if tomorrow they need a few more shortcuts (like static member FromLabel s) then all implementations of generic factory must be updated by hands.

Ideally, I want a one-liner so that for each factory that I need I could just inherit from a generic type, like:

```<code>type CollegeSizeFactory private () =
    inherit UnionFactory<CollegeSize, string, int64> (CollegeSize.all)
</code>```

and then automatically get everything that could be possibly needed, including all static members. I wonder if this is ever possible, and if yes, then how exactly.

Thanks a lot.

答:
I would suggest you drop the singleton idea, and instead use instance members, avoiding the problem altogether. Singletons are a bad idea to start with.

One approach would be to have a module with the factories, perhaps lazily evaluated (though I don't believe that's a concern in your scenario, they're not expensive to create). Then you could use that module directly, or maybe re-expose it through a static member on the type you want to create, e.g.

```<code>type CollegeSizeFactory () =
    inherit UnionFactory<CollegeSize, string, int64> (CollegeSize.all)

module Factories =
    let collegeSize = lazy CollegeSizeFactory()

type CollegeSize with
    static member Factory = Factories.collegeSize.Value

CollegeSize.Factory.tryFromKey 1
</code>```

The design space of your problem is rather large, and no doubt that's not the best solution to be found, but I feel it's a good first step that can be put in place with a simple refactoring.

But to be honest, you could probably get away with coding against your all members directly instead of precomputing those lookups. They are likely small enough that the performance difference doesn't justify maintaining this more complicated setup.

Body:
I have the following situation:

1.
There are many (20 - 40) very similarly structured slowly changing data types.

2.
Each data type at the low level is represented by a unique (for a type) string label and a unique (again, for a type) key (usually string or long). The key does not change, but the label (on average) may be updated less than once a year.

3.
I "promoted" each such data type to F# DU, so that for each label/key there is a DU case. This is needed because some of the higher-level code needs to do a pattern matching. So, in a rare case when the types get updated, I want a compile error in case the things change. So, for each such type I generate/write the code like:

type CollegeSize =
    | VerySmall
    | Small
    | Medium
    | Large
    | VeryLarge
with
    static member all =
        [|
            (CollegeSize.VerySmall, "Very small (less than 2,000 students)", 1L)
            (CollegeSize.Small, "Small (from 2,001 to 5,000 students)", 2L)
            (CollegeSize.Medium, "Medium (from 5,001 to 10,000 students)", 3L)
            (CollegeSize.Large, "Large (from 10,000 to 20,000 students)", 4L)
            (CollegeSize.VeryLarge, "Very large (over 20,000 students)", 5L)
        |]

4.
All such types are consumed in two places: F# engine, which does some calculations, and a web site. The F# engine just works with DU cases. The web sites these days, unfortunately, are mostly based on strings. So, the web team wanted a string based methods for almost any actions with the types and they are using C#.

5.
So, I created two generic factories:

type CaseFactory<'C, 'L, 'K when 'C : comparison and 'L : comparison and 'K : comparison> =
    {
        caseValue : 'C
        label : 'L
        key : 'K
    }

// DU factory: 'C - case, 'L - label, 'K - key
type UnionFactory< 'C, 'L, 'K when 'C : comparison and 'L : comparison and 'K : comparison> (all : array< 'C * 'L * 'K> ) =
    let map = all |> Array.map (fun (c, l, _) -> (c, l)) |> Map.ofArray
    let mapRev = all |> Array.map (fun (c, l, _) -> (l, c)) |> Map.ofArray
    let mapVal = all |> Array.map (fun (c, _, k) -> (c, k)) |> Map.ofArray
    let mapValRev = all |> Array.map (fun (c, _, k) -> (k, c)) |> Map.ofArray

    let allListValue : System.Collections.Generic.List<CaseFactory< 'C, 'L, 'K>> =
        let x =
            all
            |> List.ofArray
            |> List.sortBy (fun (_, s, _) -> s)
            |> List.map (fun (c, s, v) -> { caseValue = c; label = s; key = v } : CaseFactory< 'C, 'L, 'K>)
        new System.Collections.Generic.List<CaseFactory< 'C, 'L, 'K>> (x)

    //Use key, NOT label to create.
    [<CompiledName("FromKey")>]
    member this.fromKey (k : 'K) : 'C = mapValRev.Item (k)

    // For integer keys you can pass "1" instead of 1
    [<CompiledName("FromKeyString")>]
    member this.fromKeyString (s : string) : 'C = this.fromKey (convert s)

     //Use key, NOT label to create.
    [<CompiledName("TryFromKey")>]
    member this.tryFromKey (k : 'K) : 'C option = mapValRev.TryFind k

    [<CompiledName("TryFromKeyString")>]
    member this.tryFromKeyString (s : string) : 'C option = mapValRev.TryFind (convert s)

     //Use key, NOT label to create.
    [<CompiledName("TryFromKey")>]
    member this.tryFromKey (k : 'K option) : 'C option =
        match k with
        | Some x -> this.tryFromKey x
        | None -> None

    [<CompiledName("AllList")>]
    member this.allList : System.Collections.Generic.List< CaseFactory< 'C, 'L, 'K>> = allListValue

    [<CompiledName("FromLabel")>]
    member this.fromLabel (l : 'L) : 'C = mapRev.[l]

    [<CompiledName("TryFromLabel")>]
    member this.tryFromLabel (l : 'L) : 'C option = mapRev.TryFind l

    [<CompiledName("TryFromLabel")>]
    member this.tryFromLabel (l : 'L option) : 'C option =
        match l with
        | Some x -> this.tryFromLabel x
        | None -> None

    [<CompiledName("GetLabel")>]
    member this.getLabel (c : 'C) : 'L = map.[c]

    [<CompiledName("GetKey")>]
    member this.getKey (c : 'C) : 'K = mapVal.[c]

6.
At this point everything works as a clock if I create a generic factory with the singleton for each type like:

type CollegeSizeFactory private () =
    inherit UnionFactory<CollegeSize, string, int64> (CollegeSize.all)
    static let instance = CollegeSizeFactory ()

7.
… except that web team does not want to use Instance each and every time when they call methods of a generic factory. So, I ended up writing:

type CollegeSizeFactory private () =
    inherit UnionFactory<CollegeSize, string, int64> (CollegeSize.all)
    static let instance = CollegeSizeFactory ()
    static member Instance = instance

    static member FromLabel s = CollegeSizeFactory.Instance.fromLabel s
    static member FromKey k = CollegeSizeFactory.Instance.fromKey k
    static member FromKeyString s = CollegeSizeFactory.Instance.fromKeyString s

The problem with that is that if tomorrow they need a few more shortcuts (like static member FromLabel s) then all implementations of generic factory must be updated by hands.

Ideally, I want a one-liner so that for each factory that I need I could just inherit from a generic type, like:

type CollegeSizeFactory private () =
    inherit UnionFactory<CollegeSize, string, int64> (CollegeSize.all)

and then automatically get everything that could be possibly needed, including all static members. I wonder if this is ever possible, and if yes, then how exactly.

Thanks a lot.

Body:
I would suggest you drop the singleton idea, and instead use instance members, avoiding the problem altogether. Singletons are a bad idea to start with.

One approach would be to have a module with the factories, perhaps lazily evaluated (though I don't believe that's a concern in your scenario, they're not expensive to create). Then you could use that module directly, or maybe re-expose it through a static member on the type you want to create, e.g.

type CollegeSizeFactory () =
    inherit UnionFactory<CollegeSize, string, int64> (CollegeSize.all)

module Factories =
    let collegeSize = lazy CollegeSizeFactory()

type CollegeSize with
    static member Factory = Factories.collegeSize.Value

CollegeSize.Factory.tryFromKey 1

The design space of your problem is rather large, and no doubt that's not the best solution to be found, but I feel it's a good first step that can be put in place with a simple refactoring.

But to be honest, you could probably get away with coding against your all members directly instead of precomputing those lookups. They are likely small enough that the performance difference doesn't justify maintaining this more complicated setup.


问:
Dynamically updating a specific view in a RecyclerView
I'm currently working on android using RecyclerView, let's say I have 2 TextView in my custom row, I wanted to dynamically change the text of one in the TextView, how can I do that?

I do have the following code in my MainActivity

```<code>public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private AdaptersOnline adaptersOnline;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<ModelClientInformation> modelOnlineLists = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = getApplicationContext();

        mLayoutManager = new LinearLayoutManager(this);
        adaptersOnline = new AdaptersOnline(this, modelOnlineLists);
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adaptersOnline);
    }

    //call this to new row
    public void initializeClient(String id, String data1, String data2){
        this.modelOnlineLists.add(new ModelClientInformation(id, data1, data2));
        adaptersOnline.notifyDataSetChanged();
    }

    //Call this method to update textview
    public void updateSpecificViewItem(String theID){
         //get position base on the ID
         adaptersOnline.updateTextView(
         adaptersOnline.getPositionBaseOnItemID(theID));
    }

}
</code>```

in my Adapter Class

```<code>public class AdaptersOnline extends RecyclerView.Adapter<AdaptersOnline.TheViewHolder> {
    Context mContext;
    public List<ModelClientInformation> onlineList;

    public AdaptersOnline(Context mContext, List<ModelClientInformation> modelOnlineList){
        this.mContext = mContext;
        this.onlineList = modelOnlineList;
    }

    public class TheViewHolder extends RecyclerView.ViewHolder {

        TextView text1, text2;

        public TheViewHolder(View view) {
            super(view);

            text1 = (TextView)view.findViewById(R.id.text1);
            text2 = (TextView)view.findViewById(R.id.text2);
        }
    }

    @Override
    public TheViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recyclerview_row, parent, false);
        return new TheViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(TheViewHolder holder, int position) {
        final ModelClientInformation info = onlineList.get(position);

        holder.text1.setText(holder.getText1());
        holder.text1.setText(holder.getText2());
    }

    /**Function to Return the size of List**/
    @Override
    public int getItemCount() {
        return onlineList.size();
    }

    /**Function to Clear the List**/
    public void clear(){
        onlineList.clear();
    }

    /**Possibly way to update one of the TextView here**/
    public void updateTextView(int position){
        //what should I do to update the TextView
    }

    /*Get the position of item inside data list base on the given ID*/
    public int getPositionBaseOnItemID(String theID) {

    int length = onlineList.size();
    for (int i = 0; i < length; i ++) {
        if(onlineList.get(i).getItemID().equals(theID)) {
            return i;
        }
    }
    return -1; //Item not found
}
}
</code>```

and the Pojo

```<code>public ModelClientInformation class{

    private String theID, text1, text2;

    public ModelClientInformation(String theID, String text1, String text2){
        this.theID = theID;
        this.text1 = text1;
        this.text2 = text2;
    }

    public String getItemID(){
        return theID;
    }

    public String getText1(){
        return text1;
    }

    public String getText2(){
        return text2;
    }

}
</code>```

I'm don't have any idea to do it. . .
Anyone can help me?

UPDATE:

Please look at my changes,

1: I want to update one of the TextView inside MainActivity class by calling updateSpecificViewItem("theID").

2: Get the position of the item base on the given id by calling getPositionBaseOnItemID("theID").

3: To finally update the specific item, I want to call updateTextView(int position) method.

the only problem I'm facing right now is the number 3, how can I update only the text2 and not the entire item?

答:
You need to override onBindViewHolder (TheViewHolder holder, int position, List payload)

```<code>@Override
    public void onBindViewHolder(HelloViewHolder holder, int position, List<Object> payload) {

        if (payloads.isEmpty()) {
             super.onBindViewHolder(holder, position , payloads);
        }else{

            for (Object payload : payloads) {
               if (payload instanceof String) {
                  holder.textView.setText(payload.toString)
                 }
              }
          }

    }
</code>```

And to update your textView you just need to call

adapter.notifyItemChanged(position , "an string for example")

This gives you a partial update of your view.

Hope this helps.

Body:
I'm currently working on android using RecyclerView, let's say I have 2 TextView in my custom row, I wanted to dynamically change the text of one in the TextView, how can I do that?

I do have the following code in my MainActivity

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private AdaptersOnline adaptersOnline;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<ModelClientInformation> modelOnlineLists = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = getApplicationContext();

        mLayoutManager = new LinearLayoutManager(this);
        adaptersOnline = new AdaptersOnline(this, modelOnlineLists);
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adaptersOnline);
    }

    //call this to new row
    public void initializeClient(String id, String data1, String data2){
        this.modelOnlineLists.add(new ModelClientInformation(id, data1, data2));
        adaptersOnline.notifyDataSetChanged();
    }

    //Call this method to update textview
    public void updateSpecificViewItem(String theID){
         //get position base on the ID
         adaptersOnline.updateTextView(
         adaptersOnline.getPositionBaseOnItemID(theID));
    }

}

in my Adapter Class

public class AdaptersOnline extends RecyclerView.Adapter<AdaptersOnline.TheViewHolder> {
    Context mContext;
    public List<ModelClientInformation> onlineList;

    public AdaptersOnline(Context mContext, List<ModelClientInformation> modelOnlineList){
        this.mContext = mContext;
        this.onlineList = modelOnlineList;
    }

    public class TheViewHolder extends RecyclerView.ViewHolder {

        TextView text1, text2;

        public TheViewHolder(View view) {
            super(view);

            text1 = (TextView)view.findViewById(R.id.text1);
            text2 = (TextView)view.findViewById(R.id.text2);
        }
    }

    @Override
    public TheViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recyclerview_row, parent, false);
        return new TheViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(TheViewHolder holder, int position) {
        final ModelClientInformation info = onlineList.get(position);

        holder.text1.setText(holder.getText1());
        holder.text1.setText(holder.getText2());
    }

    /**Function to Return the size of List**/
    @Override
    public int getItemCount() {
        return onlineList.size();
    }

    /**Function to Clear the List**/
    public void clear(){
        onlineList.clear();
    }

    /**Possibly way to update one of the TextView here**/
    public void updateTextView(int position){
        //what should I do to update the TextView
    }

    /*Get the position of item inside data list base on the given ID*/
    public int getPositionBaseOnItemID(String theID) {

    int length = onlineList.size();
    for (int i = 0; i < length; i ++) {
        if(onlineList.get(i).getItemID().equals(theID)) {
            return i;
        }
    }
    return -1; //Item not found
}
}

and the Pojo

public ModelClientInformation class{

    private String theID, text1, text2;

    public ModelClientInformation(String theID, String text1, String text2){
        this.theID = theID;
        this.text1 = text1;
        this.text2 = text2;
    }

    public String getItemID(){
        return theID;
    }

    public String getText1(){
        return text1;
    }

    public String getText2(){
        return text2;
    }

}

I'm don't have any idea to do it. . .
Anyone can help me?

UPDATE:

Please look at my changes,

1: I want to update one of the TextView inside MainActivity class by calling updateSpecificViewItem("theID").

2: Get the position of the item base on the given id by calling getPositionBaseOnItemID("theID").

3: To finally update the specific item, I want to call updateTextView(int position) method.

the only problem I'm facing right now is the number 3, how can I update only the text2 and not the entire item?

Body:
You need to override onBindViewHolder (TheViewHolder holder, int position, List payload)

@Override
    public void onBindViewHolder(HelloViewHolder holder, int position, List<Object> payload) {

        if (payloads.isEmpty()) {
             super.onBindViewHolder(holder, position , payloads);
        }else{

            for (Object payload : payloads) {
               if (payload instanceof String) {
                  holder.textView.setText(payload.toString)
                 }
              }
          }

    }

And to update your textView you just need to call

adapter.notifyItemChanged(position , "an string for example")

This gives you a partial update of your view.

Hope this helps.