问:
simulate key press in JUnit tests
I am completely stuck in a java test; it's about sending by the test method the character 'a' to the JTextField of a JFrame component.

The JFrame class implements the KeyListener interface, and as such overrides KeyPressed, KeyTyped, and KeyReleased. Along with this, I transfer all the keypressed of the JTextField to the JFrame; inside the JFrame constructor I have :

```<code>JTextField txf_version = new JTextField();
txf_version.addKeyListener(this);
</code>```

I would like to test this behavior and then to simulate the action of type a character in the JTextField.

all my attempts failed; I tried with the java.awt.Robot class, like this : hava a look at this other post in stack overflow, but I get a strange behavior : calling

```<code>robot.keyPress(KeyEvent.VK_A);
</code>```

displays the character in my IDE directly, not in the virtual JFrame! try to play with requestFocus() or requestFocusInWindow() is ineffective.

I also tried with KeyEvents:

```<code>KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
        .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);
</code>```

but again the textfield's text property is not changed...

here is the method I have for now:

```<code>@Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
      InterruptedException, NoSuchFieldException, IllegalAccessException {
  initTest();

  KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
        .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
  bookWindow.txf_version.dispatchEvent(key);

  System.out.println("dans txf_version : " + bookWindow.txf_version.getText
        ());

  assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());

}
</code>```

I can have a look at the actual behavior by writing a main() method in the JFrame's child class, but I think it is useful to know how to simulate keys for swing components testing.

thank you

EDIT:
I changed the code of my test according to AJNeufeld's answer, but it still doesn't work. Here is my test code :

```<code>@Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
      InterruptedException, NoSuchFieldException, IllegalAccessException,
      InvocationTargetException {
//bookEditor2 & bookWindow
SwingUtilities.invokeAndWait(() -> {
  bookWindow = new BookWindow();
  VectorPerso two = new VectorPerso();
  two.add(le_livre_de_la_jungle);
  two.add(elogeMaths);
  bookWindow.setTableDatas(two);
  bookWindow.table.setRowSelectionInterval(1, 1);
  bookWindow.txf_version.requestFocusInWindow();
  KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System
          .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
  bookWindow.txf_version.dispatchEvent(key);
  try {
    Thread.sleep(1000);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  System.out.println("dans txf_version : " + bookWindow.txf_version.getText
          ());

  assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
});

}
</code>```

the plintln line produces a text in the console : "dans txf_version : 0", which indicates the key isn't send to the txf_version.

EDIT 2:

new try:

```<code>@Test
  void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
          InterruptedException, NoSuchFieldException, IllegalAccessException,
          InvocationTargetException {
    //bookEditor2 & bookWindow
    SwingUtilities.invokeAndWait(() -> {
      bookWindow = new BookWindow();
      VectorPerso two = new VectorPerso();
      two.add(le_livre_de_la_jungle);
      two.add(elogeMaths);
      bookWindow.setTableDatas(two);
      bookWindow.table.setRowSelectionInterval(1, 1);
      bookWindow.txf_version.requestFocusInWindow();
      KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System

              .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
      bookWindow.txf_version.dispatchEvent(key);
    });
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    SwingUtilities.invokeAndWait(() -> {
      System.out.println("dans txf_version : " + bookWindow.txf_version.getText
              ());

      assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
    });

  }
</code>```

答:
I think you're doing a couple of things wrong, but without a complete example, it is hard to tell.

First, the JTextField is not really concerned with KEY_PRESSED events.  It is concerned with the KEY_TYPED events.

Second, Swing processes events on the Event Dispatching Thread (EDT), which is not necessarily the thread that JUnit is going to be running on.  You really shouldn't be changing things when you're not on the EDT.  I'm not certain eventDispatch() does the switch to the EDT or not.  It might.  But it might also do it using invokeLater(), in which case the execution immediately passes to the assertEquals(), which fails, because the event processing hasn't happened yet.

Here is minimal, complete, verifiable example, which shows a keypress sent, which changes the button colour, and a JUnit test case which checks it and passes:

First, the code under test:

```<code>public class SwingUnitTesting extends JFrame {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(SwingUnitTesting::new);
    }

    JTextField tf = new JTextField();
    JButton btn = new JButton("Test Button");

    SwingUnitTesting() {
        add(tf, BorderLayout.PAGE_END);
        add(btn, BorderLayout.PAGE_START);

        tf.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                btn.setForeground(Color.RED);
            }
        });

        setSize(200, 80);
        setLocationByPlatform(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setVisible(true);
    }
}
</code>```

And the unit test:

```<code>public class SwingUnitTestingTest {

    SwingUnitTesting sut;

    @Before
    public void setUp() throws Exception {
        SwingUtilities.invokeAndWait(() -> {
            sut = new SwingUnitTesting();
        });
    }

    @Test
    public void btnNotRedBeforeKeypress() throws InvocationTargetException, InterruptedException {
        SwingUtilities.invokeAndWait(() -> {
            assertNotEquals(Color.RED, sut.btn.getForeground());
        });
    }

    @Test
    public void btnRedAfterKeypress() throws InvocationTargetException, InterruptedException {
        SwingUtilities.invokeAndWait(() -> {
            sut.tf.requestFocusInWindow();
            sut.tf.dispatchEvent(new KeyEvent(sut.tf,
                    KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0,
                    KeyEvent.VK_UNDEFINED, 'A'));
            assertEquals(Color.RED, sut.btn.getForeground());
        });
    }
}
</code>```

You can probably use some JUnit @Rule trickery or a custom runner to automatically change to the EDT when running swing tests.

Update:

I got curious, and tried to find an existing @Rule which puts the @Before, @Test, and @After code on to the EDT, but my Google-fu failed me;
I know I've seen it before, but I couldn't find it.
In the end, I created my own:

```<code>public class EDTRule implements TestRule {

    @Override
    public Statement apply(Statement stmt, Description dscr) {
        return new Statement() {
            private Throwable ex;

            @Override
            public void evaluate() throws Throwable {
                SwingUtilities.invokeAndWait(() -> {
                    try {
                        stmt.evaluate();
                    } catch (Throwable t) {
                        ex = t;
                    }
                });
                if (ex != null) {
                    throw ex;
                }
            }
        };
    }
}
</code>```

Using this rule, the JUnit test becomes a little simpler:

```<code>public class SwingUnitTestingTest {

    @Rule
    public TestRule edt = new EDTRule();

    SwingUnitTesting sut;

    @Before
    public void setUp() throws Exception {
        sut = new SwingUnitTesting();
    }

    @Test
    public void btnNotRedBeforeKeypress() {
        assertNotEquals(Color.RED, sut.btn.getForeground());
    }

    @Test
    public void btnRedAfterKeypress() {
        sut.tf.requestFocusInWindow();
        sut.tf.dispatchEvent(
                new KeyEvent(sut.tf, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'A'));
        assertEquals(Color.RED, sut.btn.getForeground());
    }
}
</code>```

Tested on MacOS, with jdk1.8.0_121

Title: simulate key press in JUnit tests

Body:
I am completely stuck in a java test; it's about sending by the test method the character 'a' to the JTextField of a JFrame component.

The JFrame class implements the KeyListener interface, and as such overrides KeyPressed, KeyTyped, and KeyReleased. Along with this, I transfer all the keypressed of the JTextField to the JFrame; inside the JFrame constructor I have :

JTextField txf_version = new JTextField();
txf_version.addKeyListener(this);

I would like to test this behavior and then to simulate the action of type a character in the JTextField.

all my attempts failed; I tried with the java.awt.Robot class, like this : hava a look at this other post in stack overflow, but I get a strange behavior : calling

robot.keyPress(KeyEvent.VK_A);

displays the character in my IDE directly, not in the virtual JFrame! try to play with requestFocus() or requestFocusInWindow() is ineffective.

I also tried with KeyEvents:

KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
        .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
bookWindow.txf_version.dispatchEvent(key);

but again the textfield's text property is not changed...

here is the method I have for now:

@Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
      InterruptedException, NoSuchFieldException, IllegalAccessException {
  initTest();

  KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_PRESSED, System
        .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
  bookWindow.txf_version.dispatchEvent(key);

  System.out.println("dans txf_version : " + bookWindow.txf_version.getText
        ());

  assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());

}

I can have a look at the actual behavior by writing a main() method in the JFrame's child class, but I think it is useful to know how to simulate keys for swing components testing.

thank you

EDIT:
I changed the code of my test according to AJNeufeld's answer, but it still doesn't work. Here is my test code :

@Test
void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
      InterruptedException, NoSuchFieldException, IllegalAccessException,
      InvocationTargetException {
//bookEditor2 & bookWindow
SwingUtilities.invokeAndWait(() -> {
  bookWindow = new BookWindow();
  VectorPerso two = new VectorPerso();
  two.add(le_livre_de_la_jungle);
  two.add(elogeMaths);
  bookWindow.setTableDatas(two);
  bookWindow.table.setRowSelectionInterval(1, 1);
  bookWindow.txf_version.requestFocusInWindow();
  KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System
          .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
  bookWindow.txf_version.dispatchEvent(key);
  try {
    Thread.sleep(1000);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  System.out.println("dans txf_version : " + bookWindow.txf_version.getText
          ());

  assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
});

}

the plintln line produces a text in the console : "dans txf_version : 0", which indicates the key isn't send to the txf_version.

EDIT 2:

new try:

@Test
  void testBtnSaveChangesBecomesRedWhenVersionChanged() throws AWTException,
          InterruptedException, NoSuchFieldException, IllegalAccessException,
          InvocationTargetException {
    //bookEditor2 & bookWindow
    SwingUtilities.invokeAndWait(() -> {
      bookWindow = new BookWindow();
      VectorPerso two = new VectorPerso();
      two.add(le_livre_de_la_jungle);
      two.add(elogeMaths);
      bookWindow.setTableDatas(two);
      bookWindow.table.setRowSelectionInterval(1, 1);
      bookWindow.txf_version.requestFocusInWindow();
      KeyEvent key = new KeyEvent(bookWindow.txf_version, KeyEvent.KEY_TYPED, System

              .currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'a');
      bookWindow.txf_version.dispatchEvent(key);
    });
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    SwingUtilities.invokeAndWait(() -> {
      System.out.println("dans txf_version : " + bookWindow.txf_version.getText
              ());

      assertEquals(Color.RED, bookWindow.getBtnSaveChangesForegroundColor());
    });

  }

Body:
I think you're doing a couple of things wrong, but without a complete example, it is hard to tell.

First, the JTextField is not really concerned with KEY_PRESSED events.  It is concerned with the KEY_TYPED events.

Second, Swing processes events on the Event Dispatching Thread (EDT), which is not necessarily the thread that JUnit is going to be running on.  You really shouldn't be changing things when you're not on the EDT.  I'm not certain eventDispatch() does the switch to the EDT or not.  It might.  But it might also do it using invokeLater(), in which case the execution immediately passes to the assertEquals(), which fails, because the event processing hasn't happened yet.

Here is minimal, complete, verifiable example, which shows a keypress sent, which changes the button colour, and a JUnit test case which checks it and passes:

First, the code under test:

public class SwingUnitTesting extends JFrame {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(SwingUnitTesting::new);
    }

    JTextField tf = new JTextField();
    JButton btn = new JButton("Test Button");

    SwingUnitTesting() {
        add(tf, BorderLayout.PAGE_END);
        add(btn, BorderLayout.PAGE_START);

        tf.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                btn.setForeground(Color.RED);
            }
        });

        setSize(200, 80);
        setLocationByPlatform(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setVisible(true);
    }
}

And the unit test:

public class SwingUnitTestingTest {

    SwingUnitTesting sut;

    @Before
    public void setUp() throws Exception {
        SwingUtilities.invokeAndWait(() -> {
            sut = new SwingUnitTesting();
        });
    }

    @Test
    public void btnNotRedBeforeKeypress() throws InvocationTargetException, InterruptedException {
        SwingUtilities.invokeAndWait(() -> {
            assertNotEquals(Color.RED, sut.btn.getForeground());
        });
    }

    @Test
    public void btnRedAfterKeypress() throws InvocationTargetException, InterruptedException {
        SwingUtilities.invokeAndWait(() -> {
            sut.tf.requestFocusInWindow();
            sut.tf.dispatchEvent(new KeyEvent(sut.tf,
                    KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0,
                    KeyEvent.VK_UNDEFINED, 'A'));
            assertEquals(Color.RED, sut.btn.getForeground());
        });
    }
}

You can probably use some JUnit @Rule trickery or a custom runner to automatically change to the EDT when running swing tests.

Update:

I got curious, and tried to find an existing @Rule which puts the @Before, @Test, and @After code on to the EDT, but my Google-fu failed me;
I know I've seen it before, but I couldn't find it.
In the end, I created my own:

public class EDTRule implements TestRule {

    @Override
    public Statement apply(Statement stmt, Description dscr) {
        return new Statement() {
            private Throwable ex;

            @Override
            public void evaluate() throws Throwable {
                SwingUtilities.invokeAndWait(() -> {
                    try {
                        stmt.evaluate();
                    } catch (Throwable t) {
                        ex = t;
                    }
                });
                if (ex != null) {
                    throw ex;
                }
            }
        };
    }
}

Using this rule, the JUnit test becomes a little simpler:

public class SwingUnitTestingTest {

    @Rule
    public TestRule edt = new EDTRule();

    SwingUnitTesting sut;

    @Before
    public void setUp() throws Exception {
        sut = new SwingUnitTesting();
    }

    @Test
    public void btnNotRedBeforeKeypress() {
        assertNotEquals(Color.RED, sut.btn.getForeground());
    }

    @Test
    public void btnRedAfterKeypress() {
        sut.tf.requestFocusInWindow();
        sut.tf.dispatchEvent(
                new KeyEvent(sut.tf, KeyEvent.KEY_TYPED, System.currentTimeMillis(), 0, KeyEvent.VK_UNDEFINED, 'A'));
        assertEquals(Color.RED, sut.btn.getForeground());
    }
}

Tested on MacOS, with jdk1.8.0_121


来源: stackexchange

问:
How to compare differnt node value fields using angular 2
How can I compare both node Uid == ChById.

this code for first node value access.
provides into badminton sports uid access into array.

```<code>this.db.list('/Providers/'+this.mySport+'', {preserveSnapshot:     true}).subscribe(snapshots => {
if(snapshots.values()==null) {console.log('its empty')}else {
snapshots.forEach(snapshot => {
  snapshot.forEach(snapshot1 => {
    var myTeamName = [snapshot1.val().team_name];
    var availability = [snapshot1.val().Availability];
    var userid = [snapshot1.val().Uid];
    this.getallprovidersuserids = [userid];
    //console.log(this.getallprovidersuserids);
    this.allelementsofuser.push({teams: myTeamName, userloginid: userid, availability: availability});
  });
});
}
});
</code>```

this code for second node access.
challanges node into badminton sports ChById value accessing into array value.

```<code>this.db.list('/Challenges/'+this.mySport+'', {
  preserveSnapshot: true}).subscribe(snapshots2 => {
  snapshots2.forEach(snapshot2 => {
    snapshot2.forEach(snapshot3 => {
      var getallChallenegesuserid = [snapshot3.val().ChByUid];
      console.log(getallChallenegesuserid[0]);
    });
  });
  // console.log(this.getallprovidersuserids);
 });
</code>```

if i store both value two different arrays and compare both using nested for loop.its not given output.please help to solve my code.

答:
You need to combineLatest so they resolve at the same time (they're both async + lazy):

```<code>Observable.combineLatest(
    this.db.list(`/Providers/${this.mySport}`,  {preserveSnapshot: true}),
    this.db.list(`/Challenges/${this.mySport}`, {preserveSnapshot: true})
).subscribe(([providersSnapshot, challengesSnapshot]) => {
   // do your comparison in here
})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I compare both node Uid == ChById.

this code for first node value access.
provides into badminton sports uid access into array.

this.db.list('/Providers/'+this.mySport+'', {preserveSnapshot:     true}).subscribe(snapshots => {
if(snapshots.values()==null) {console.log('its empty')}else {
snapshots.forEach(snapshot => {
  snapshot.forEach(snapshot1 => {
    var myTeamName = [snapshot1.val().team_name];
    var availability = [snapshot1.val().Availability];
    var userid = [snapshot1.val().Uid];
    this.getallprovidersuserids = [userid];
    //console.log(this.getallprovidersuserids);
    this.allelementsofuser.push({teams: myTeamName, userloginid: userid, availability: availability});
  });
});
}
});

this code for second node access.
challanges node into badminton sports ChById value accessing into array value.

this.db.list('/Challenges/'+this.mySport+'', {
  preserveSnapshot: true}).subscribe(snapshots2 => {
  snapshots2.forEach(snapshot2 => {
    snapshot2.forEach(snapshot3 => {
      var getallChallenegesuserid = [snapshot3.val().ChByUid];
      console.log(getallChallenegesuserid[0]);
    });
  });
  // console.log(this.getallprovidersuserids);
 });

if i store both value two different arrays and compare both using nested for loop.its not given output.please help to solve my code.

Body:
You need to combineLatest so they resolve at the same time (they're both async + lazy):

Observable.combineLatest(
    this.db.list(`/Providers/${this.mySport}`,  {preserveSnapshot: true}),
    this.db.list(`/Challenges/${this.mySport}`, {preserveSnapshot: true})
).subscribe(([providersSnapshot, challengesSnapshot]) => {
   // do your comparison in here
})


问:
I've Got to add a new record to my access DBMS through VS2008 and ADO.NET how?
This is my code:

```<code>Imports System.Data
Public Class frmNieuweGebruiker

Private Sub frmNieuweGebruiker_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'verbinding maken met databank
    Dim strConnection As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=I:\Geïntegreerde proef\ApplicatieOntwikkeling\GIP.mdb"
    Dim strSQL As String = "SELECT * FROM GEBRUIKER"
    Dim dataAdapter As New OleDb.OleDbDataAdapter(strSQL, strConnection)
    'databank gebruiker info ophalen.
    dataAdapter.Fill(frmAanmeldingsscherm.dtGEBRUIKER)
    dataAdapter.Dispose()
End Sub

Private Sub btnGebruikersnaamBevestigen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGebruikersnaamBevestigen.Click
    Dim strGebruikersnaam As String
    Dim strWachtwoord As String
    Dim drNieuweGebruiker As DataRow = frmAanmeldingsscherm.dtGEBRUIKER.NewRow()

    strGebruikersnaam = txtGebruikersnaam.Text

    If txtWachtwoord.Text <> txtWachtwoordBevestigen.Text Or txtWachtwoord.Text = "" Or txtWachtwoordBevestigen.Text = "" Then
        MsgBox("U hebt een fout ingegeven." + vbNewLine + "Probeer nogmaals.")
        txtWachtwoord.Text = ""
        txtWachtwoordBevestigen.Text = ""
    Else
        strWachtwoord = txtWachtwoord.Text

        drNieuweGebruiker("Gebruikersnaam") = strGebruikersnaam
        drNieuweGebruiker("Wachtwoord") = strWachtwoord

        frmAanmeldingsscherm.dtGEBRUIKER.Rows.Add(drNieuweGebruiker)

        frmMenu.Show()
        frmAanmeldingsscherm.txtGebruikersnaam.Text = strGebruikersnaam
        Me.Close()
    End If

End Sub
</code>```

End Class

He gives a fault report when i tell him to do this:

```<code>drNieuweGebruiker("Gebruikersnaam") = strGebruikersnaam
drNieuweGebruiker("Wachtwoord") = strWachtwoord
frmAanmeldingsscherm.dtGEBRUIKER.Rows.Add(drNieuweGebruiker)
</code>```

and i just need to add a user to my database...

答:
Firstly ensure Gebruikersnaam and Wachtwoord exist as DataColumns in the dtGEBRUIKER table.

When you say that you get an error on these lines:

```<code>drNieuweGebruiker("Gebruikersnaam") = strGebruikersnaam
drNieuweGebruiker("Wachtwoord") = strWachtwoord
frmAanmeldingsscherm.dtGEBRUIKER.Rows.Add(drNieuweGebruiker)
</code>```

Which line? And what error?

ContentLicense: CC BY-SA 2.5

Body:
This is my code:

Imports System.Data
Public Class frmNieuweGebruiker

Private Sub frmNieuweGebruiker_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'verbinding maken met databank
    Dim strConnection As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=I:\Geïntegreerde proef\ApplicatieOntwikkeling\GIP.mdb"
    Dim strSQL As String = "SELECT * FROM GEBRUIKER"
    Dim dataAdapter As New OleDb.OleDbDataAdapter(strSQL, strConnection)
    'databank gebruiker info ophalen.
    dataAdapter.Fill(frmAanmeldingsscherm.dtGEBRUIKER)
    dataAdapter.Dispose()
End Sub

Private Sub btnGebruikersnaamBevestigen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGebruikersnaamBevestigen.Click
    Dim strGebruikersnaam As String
    Dim strWachtwoord As String
    Dim drNieuweGebruiker As DataRow = frmAanmeldingsscherm.dtGEBRUIKER.NewRow()

    strGebruikersnaam = txtGebruikersnaam.Text

    If txtWachtwoord.Text <> txtWachtwoordBevestigen.Text Or txtWachtwoord.Text = "" Or txtWachtwoordBevestigen.Text = "" Then
        MsgBox("U hebt een fout ingegeven." + vbNewLine + "Probeer nogmaals.")
        txtWachtwoord.Text = ""
        txtWachtwoordBevestigen.Text = ""
    Else
        strWachtwoord = txtWachtwoord.Text

        drNieuweGebruiker("Gebruikersnaam") = strGebruikersnaam
        drNieuweGebruiker("Wachtwoord") = strWachtwoord

        frmAanmeldingsscherm.dtGEBRUIKER.Rows.Add(drNieuweGebruiker)

        frmMenu.Show()
        frmAanmeldingsscherm.txtGebruikersnaam.Text = strGebruikersnaam
        Me.Close()
    End If

End Sub

End Class

He gives a fault report when i tell him to do this:

drNieuweGebruiker("Gebruikersnaam") = strGebruikersnaam
drNieuweGebruiker("Wachtwoord") = strWachtwoord
frmAanmeldingsscherm.dtGEBRUIKER.Rows.Add(drNieuweGebruiker)

and i just need to add a user to my database...

Body:
Firstly ensure Gebruikersnaam and Wachtwoord exist as DataColumns in the dtGEBRUIKER table.

When you say that you get an error on these lines:

drNieuweGebruiker("Gebruikersnaam") = strGebruikersnaam
drNieuweGebruiker("Wachtwoord") = strWachtwoord
frmAanmeldingsscherm.dtGEBRUIKER.Rows.Add(drNieuweGebruiker)

Which line? And what error?


问:
How to do a relative import from the parent directory?
I have searched this and found many answers, all of which tell me to do exactly what I am doing, here is my directory structure:

app/
+-- __init__.py
+-- app_manager.py
+-- app_gui/
|   +-- __init__.py
|   +-- app_gui.py
```

<p>in app_gui.py I have:</p>

```import tkinter as tk
from tkinter import ttk
from app_manager import AppManager
```

<p>in app manager:</p>

```class AppManager():
    def __init__(self):
    """ default constructor for app manager """
```

<p>In Visual Code, it actually resolves this to an auto completion, which tells me that at least Visual Code sees it as correctly done. However, if I run this I get the following error:</p>

<pre class="lang-none prettyprint-override"><code>ModuleNotFoundError: No Module named "app_manager"
</code>```

Edit

Full stack trace when changing to from app.app_manager import AppManager:

Traceback (most recent call last):
   File ".\app_gui\app_gui.py", line 4, in <module>
     from app_manager import AppManager
ModuleNotFoundError: No module named 'app_manager'
```

答:
Running python code like this is hacky at best.

Use a setup.py

This will require some small changes but will pay immediate benefits.

You will then be able to use your app package like any other installed package.

New Directory Structure

```<code>.
├── app
│   ├── app_gui
│   │   ├── app_gui.py
│   │   └── __init__.py
│   ├── app_manager.py
│   └── __init__.py
└── setup.py
</code>```

setup.py

```<code>from setuptools import find_packages, setup

setup(name='app',
      version='0.0.1-dev',
      description='My app package',
      install_requires=['tkinter'],
      packages=find_packages(),
      zip_safe=False)
</code>```

app_gui.py

```<code>from app.app_manager import AppManager

manager = AppManager()
</code>```

Putting it all together

From the same dir as setup.py run:

  $> python setup.py develop

This will symlink the package into your site-pacakges folder where you can treat it like any other package. i.e. import it using import app from scripts located anywhere on your system.

Body:
I have searched this and found many answers, all of which tell me to do exactly what I am doing, here is my directory structure:

app/
+-- __init__.py
+-- app_manager.py
+-- app_gui/
|   +-- __init__.py
|   +-- app_gui.py

in app_gui.py I have:

import tkinter as tk
from tkinter import ttk
from app_manager import AppManager

in app manager:

class AppManager():
    def __init__(self):
    """ default constructor for app manager """

In Visual Code, it actually resolves this to an auto completion, which tells me that at least Visual Code sees it as correctly done. However, if I run this I get the following error:

ModuleNotFoundError: No Module named "app_manager"

Edit

Full stack trace when changing to from app.app_manager import AppManager:

Traceback (most recent call last):
   File ".\app_gui\app_gui.py", line 4, in <module>
     from app_manager import AppManager
ModuleNotFoundError: No module named 'app_manager'

Body:
Running python code like this is hacky at best.

Use a setup.py

This will require some small changes but will pay immediate benefits.

You will then be able to use your app package like any other installed package.

New Directory Structure

.
├── app
│   ├── app_gui
│   │   ├── app_gui.py
│   │   └── __init__.py
│   ├── app_manager.py
│   └── __init__.py
└── setup.py

setup.py

from setuptools import find_packages, setup

setup(name='app',
      version='0.0.1-dev',
      description='My app package',
      install_requires=['tkinter'],
      packages=find_packages(),
      zip_safe=False)

app_gui.py

from app.app_manager import AppManager

manager = AppManager()

Putting it all together

From the same dir as setup.py run:

  $> python setup.py develop

This will symlink the package into your site-pacakges folder where you can treat it like any other package. i.e. import it using import app from scripts located anywhere on your system.


问:
Twisted Web serving Django project
I have fresh Django project without any application just the defaults (e.g. admin)

My plan is to have video chat and instant messaging within my Django project.

wsgi.py

```<code>import os, sys
from django.core.wsgi import get_wsgi_application

sys.path.append('MY_DJANGO_PROJECT_PATH')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MY_DJANGO_PROJECT.settings")
application = get_wsgi_application()
</code>```

I run my Twisted Web server within MY_DJANGO_PROJECT_PATH and the server start on port 8080.

cd MY_DJANGO_PROJECT_PATH
twistd -n web --wsgi=MY_DJANG_PROJECT

When I open it to the browser (http://127.0.0.1:8080/), I got an error

WSGI application error

File "/Library/Python/2.7/site-packages/Twisted-15.5.0-py2.7-macosx-10.12-intel.egg/twisted/web/wsgi.py", line 315, in run
        appIterator = self.application(self.environ, self.startResponse)
    exceptions.TypeError: 'module' object is not callable

Does anyone help me with this? Thanks in advance.

答:
I have able to serve my Django project within the Twisted using twisted.web.wsgi.WSGIResource.

Following the example here.

my_django_project.tac

```<code>from twisted.web import server
from twisted.web.wsgi import WSGIResource
from twisted.python.threadpool import ThreadPool
from twisted.internet import reactor
from twisted.application import service, strports

# Create and start a thread pool
wsgiThreadPool = ThreadPool()
wsgiThreadPool.start()

# ensuring that it will be stopped when the reactor shuts down
reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop)

import sys
sys.path.append('MY_DJANGO_PROJECT_PATH')
from MY_DJANGO_PROJECT import wsgi

# Create the WSGI resource
wsgiAppAsResource = WSGIResource(reactor, wsgiThreadPool,
wsgi.application)

# Hooks for twisted
application = service.Application('My Django Project')
server = strports.service('tcp:8080', server.Site(wsgiAppAsResource))
server.setServiceParent(application)
</code>```

Title: Twisted Web serving Django project

Body:
I have fresh Django project without any application just the defaults (e.g. admin)

My plan is to have video chat and instant messaging within my Django project.

wsgi.py

import os, sys
from django.core.wsgi import get_wsgi_application

sys.path.append('MY_DJANGO_PROJECT_PATH')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MY_DJANGO_PROJECT.settings")
application = get_wsgi_application()

I run my Twisted Web server within MY_DJANGO_PROJECT_PATH and the server start on port 8080.

cd MY_DJANGO_PROJECT_PATH
twistd -n web --wsgi=MY_DJANG_PROJECT

When I open it to the browser (http://127.0.0.1:8080/), I got an error

WSGI application error

File "/Library/Python/2.7/site-packages/Twisted-15.5.0-py2.7-macosx-10.12-intel.egg/twisted/web/wsgi.py", line 315, in run
        appIterator = self.application(self.environ, self.startResponse)
    exceptions.TypeError: 'module' object is not callable

Does anyone help me with this? Thanks in advance.

Body:
I have able to serve my Django project within the Twisted using twisted.web.wsgi.WSGIResource.

Following the example here.

my_django_project.tac

from twisted.web import server
from twisted.web.wsgi import WSGIResource
from twisted.python.threadpool import ThreadPool
from twisted.internet import reactor
from twisted.application import service, strports

# Create and start a thread pool
wsgiThreadPool = ThreadPool()
wsgiThreadPool.start()

# ensuring that it will be stopped when the reactor shuts down
reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop)

import sys
sys.path.append('MY_DJANGO_PROJECT_PATH')
from MY_DJANGO_PROJECT import wsgi

# Create the WSGI resource
wsgiAppAsResource = WSGIResource(reactor, wsgiThreadPool,
wsgi.application)

# Hooks for twisted
application = service.Application('My Django Project')
server = strports.service('tcp:8080', server.Site(wsgiAppAsResource))
server.setServiceParent(application)


问:
Python Casting Nested String of Lists to List
Does anyone know a simple way to convert the given list into the desired format?

Given:

```<code>['[[2.1, 3.7], [5.5, -1.3]]']
</code>```

Desired Format:

```<code>[[2.1, 3.7], [5.5, -1.3]]
</code>```

Thanks in advance

答:
I think json.loads is quite suitable for this particular one, ie:</p>

```<code>import json

lst = ['[[2.1, 3.7], [5.5, -1.3]]']
lst = [json.loads(lst[0])]
print(lst)
</code>```

Body:
Does anyone know a simple way to convert the given list into the desired format?

Given:

['[[2.1, 3.7], [5.5, -1.3]]']

Desired Format:

[[2.1, 3.7], [5.5, -1.3]]

Thanks in advance

Body:
I think json.loads is quite suitable for this particular one, ie:

import json

lst = ['[[2.1, 3.7], [5.5, -1.3]]']
lst = [json.loads(lst[0])]
print(lst)


Title: Python Casting Nested String of Lists to List

Body:
Try this:

import ast
lst = ['[[2.1, 3.7], [5.5, -1.3]]']
ast.literal_eval(lst[0])
=> [[2.1, 3.7], [5.5, -1.3]]


问:
Python Simulate Y^2 + Z^2 = (SinX)^2
I use matplotlib to simulate Y^2 + Z^2 = (SinX)^2

That is,the sine graph rotate 360 degrees based on x axis.

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# Make data.

t = np.arange(-5, 5, 0.25)
X,Y = np.meshgrid(t,t)
Z = np.sin(t)**2

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
</code>```

Following is the image

However,that seems not fit my expectation.

Is my way reasonable?

Or is there any way can implement in vpython?

答:
Here is a VPython program that plots a function in 3D, which may be related to what you want to do.

http://www.glowscript.org/#/user/GlowScriptDemos/folder/Examples/program/Plot3D

Title: Python Simulate Y^2 + Z^2 = (SinX)^2

Body:
I use matplotlib to simulate Y^2 + Z^2 = (SinX)^2

That is,the sine graph rotate 360 degrees based on x axis.

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# Make data.

t = np.arange(-5, 5, 0.25)
X,Y = np.meshgrid(t,t)
Z = np.sin(t)**2

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

Following is the image

However,that seems not fit my expectation.

Is my way reasonable?

Or is there any way can implement in vpython?


答:
It looks like you have a list with a single element, which is a string, and you want to evaluate the string and return it, discarding the outer list.  If so, then you can use literal_eval from ast to safely evaluate the expression:

```<code>import ast
s = ['[[2.1, 3.7], [5.5, -1.3]]']
t = s[0]
ast.literal_eval(t)
</code>```

This evaluates to:

```<code>[[2.1, 3.7], [5.5, -1.3]]
</code>```

Body:
It looks like you have a list with a single element, which is a string, and you want to evaluate the string and return it, discarding the outer list.  If so, then you can use literal_eval from ast to safely evaluate the expression:

import ast
s = ['[[2.1, 3.7], [5.5, -1.3]]']
t = s[0]
ast.literal_eval(t)

This evaluates to:

[[2.1, 3.7], [5.5, -1.3]]


答:
This should do it easily:</p>

```<code>eval(x[0])
</code>```

Body:
This should do it easily:

eval(x[0])


问:
how to use cookies in javascript and html?
my question is I took one form like register form and fill al fields like first name, last name,address, check boxes  also used then when submit at final i want it to display those data in new page. Here I want code only in javascript and html. Is their possible please help me........... and send code and guide lines </p>

答:
Yes it's possible through plain javascript also. Try it like this:

```<code>document.cookie = "name=value; expires=date; path=path; domain=domain; secure";
</code>```

Example:

```<code>var cookie_date_str = new Date ( 2011, 01, 19 );
document.cookie = "username=chand;
                  expires=" + cookie_date_str.toGMTString();
</code>```

Body:
Yes it's possible through plain javascript also. Try it like this:

document.cookie = "name=value; expires=date; path=path; domain=domain; secure";

Example:

var cookie_date_str = new Date ( 2011, 01, 19 );
document.cookie = "username=chand;
                  expires=" + cookie_date_str.toGMTString();


问:
Different font size of strings in the same TextView
I have a textView inside with a number (variable) and a string, how can I give the number one size larger than the string?
the code:

```<code>TextView size = (TextView)convertView.findViewById(R.id.privarea_list_size);
if (ls.numProducts != null) {
    size.setText(ls.numProducts + " " + mContext.getString(R.string.products));
}
</code>```

I want ls.numproducts has a size different from the rest of the text. How to do?

答:
Method 1

```<code>public static void increaseFontSizeForPath(Spannable spannable, String path, float increaseTime) {
    int startIndexOfPath = spannable.toString().indexOf(path);
    spannable.setSpan(new RelativeSizeSpan(increaseTime), startIndexOfPath,
            startIndexOfPath + path.length(), 0);
}
</code>```

using

```<code>Utils.increaseFontSizeForPath(spannable, "big", 3); // make "big" text bigger 3 time than normal text
</code>```

Method 2

```<code>public static void setFontSizeForPath(Spannable spannable, String path, int fontSizeInPixel) {
    int startIndexOfPath = spannable.toString().indexOf(path);
    spannable.setSpan(new AbsoluteSizeSpan(fontSizeInPixel), startIndexOfPath,
            startIndexOfPath + path.length(), 0);
}
</code>```

using

```<code>Utils.setFontSizeForPath(spannable, "big", (int) textView.getTextSize() + 20); // make "big" text bigger 20px than normal text
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a textView inside with a number (variable) and a string, how can I give the number one size larger than the string?
the code:

TextView size = (TextView)convertView.findViewById(R.id.privarea_list_size);
if (ls.numProducts != null) {
    size.setText(ls.numProducts + " " + mContext.getString(R.string.products));
}

I want ls.numproducts has a size different from the rest of the text. How to do?

Body:
Method 1

public static void increaseFontSizeForPath(Spannable spannable, String path, float increaseTime) {
    int startIndexOfPath = spannable.toString().indexOf(path);
    spannable.setSpan(new RelativeSizeSpan(increaseTime), startIndexOfPath,
            startIndexOfPath + path.length(), 0);
}

using

Utils.increaseFontSizeForPath(spannable, "big", 3); // make "big" text bigger 3 time than normal text

Method 2

public static void setFontSizeForPath(Spannable spannable, String path, int fontSizeInPixel) {
    int startIndexOfPath = spannable.toString().indexOf(path);
    spannable.setSpan(new AbsoluteSizeSpan(fontSizeInPixel), startIndexOfPath,
            startIndexOfPath + path.length(), 0);
}

using

Utils.setFontSizeForPath(spannable, "big", (int) textView.getTextSize() + 20); // make "big" text bigger 20px than normal text


问:
Can two FORTRAN modules use parts of one another?
I know that circular dependence of modules in FORTRAN is forbidden.  But I am wondering how strong that proscription is.  Let's say I have:

```<code>module mod1
   integer, public :: i,j,k
   use mod2, only: m
end module mod1
</code>```

and

```<code>module mod2
   integer, public :: l,m,n
   use mod1, only: j
end module mod2
</code>```

It seems to me that this evades circularity in a logical sense, but that doesn't mean the standard allows it.  Should it work?

If so, I am having trouble compiling because, of course, mod1 wants to see mod2 and vice versa.  Is there a way around this?

答: No, it shouldn't work. The standard says that a module must be "available" when a USE is seen. If mod2 hasn't been compiled by the time the "use mod2" is seen, the build will fail. (Some compilers might allow you to use a module defined later in the same source, some do not.) You might be able to use submodules (see https://software.intel.com/en-us/blogs/2015/07/07/doctor-fortran-in-we-all-live-in-a-yellow-submodule) to accomplish what you want - I don't know because clearly what you posted is not representative of your real application, but Mark's suggestion of a separate module is easier to understand.</p>

Body:
I know that circular dependence of modules in FORTRAN is forbidden.  But I am wondering how strong that proscription is.  Let's say I have:

module mod1
   integer, public :: i,j,k
   use mod2, only: m
end module mod1

and

module mod2
   integer, public :: l,m,n
   use mod1, only: j
end module mod2

It seems to me that this evades circularity in a logical sense, but that doesn't mean the standard allows it.  Should it work?

If so, I am having trouble compiling because, of course, mod1 wants to see mod2 and vice versa.  Is there a way around this?


问:
Tensorflow-Python - InvalidArgumentError - logits and labels must be of the same size, logits_size=[512, 8] labels_size=[128, 8]
I tried to port the Levi-Hassner non-BN model from the rude-carnie Github project into tf.layers syntax which now looks like this:

```<code>pkeep=0.5

weight_decay = 0.0005
weights_regularizer = tf.contrib.layers.l2_regularizer(weight_decay)
weights_initializer = tf.random_normal_initializer(stddev=0.01)

input_image = features["x"]

input_layer = tf.reshape(input_image, [-1, 227, 227, 3])

conv1 = tf.layers.conv2d(
        inputs=input_layer,
        filters=96,
        kernel_size=[7,7],
        strides=[4,4],
        padding="valid",
        kernel_initializer=weights_initializer,
        bias_initializer=tf.constant_initializer(0.),
        kernel_regularizer=weights_regularizer,
        activation=tf.nn.relu)
pool1 = tf.layers.max_pooling2d(inputs=conv1,
                                pool_size=[3, 3],
                                strides=2,
                                padding="valid")
lr_n1 = tf.nn.local_response_normalization(input=pool1, depth_radius=5, alpha=0.0001, beta=0.75, name='norm1')

conv2 = tf.layers.conv2d(
        inputs=lr_n1,
        filters=256,
        kernel_size=[5,5],
        strides=[1,1],
        kernel_initializer=weights_initializer,
        bias_initializer=tf.constant_initializer(1.),
        kernel_regularizer=weights_regularizer,
        padding="same",
        activation=tf.nn.relu)
pool2 = tf.layers.max_pooling2d(inputs=conv2,
                                pool_size=[3, 3],
                                strides=2,
                                padding="valid")
lr_n2 = tf.nn.local_response_normalization(input=pool2,
                                           depth_radius=5,
                                           alpha=0.0001,
                                           beta=0.75,
                                           name='norm2')

conv3 = tf.layers.conv2d(
        inputs=lr_n2,
        filters=384,
        kernel_size=[3,3],
        strides=[1,1],
        kernel_initializer=weights_initializer,
        bias_initializer=tf.constant_initializer(0.),
        kernel_regularizer=weights_regularizer,
        padding="same",
        activation=tf.nn.relu)
pool3 = tf.layers.max_pooling2d(inputs=conv3,
                                pool_size=[3, 3],
                                strides=2,
                                padding="valid")

flat = tf.reshape(pool3, [-1, 384*6*6 ], name="reshape")

full1 = tf.layers.dense(inputs=flat, units=512)
drop1 = tf.layers.dropout(inputs=full1, rate=1-pkeep, training=(mode == tf.estimator.ModeKeys.TRAIN), name='drop1')
full2 = tf.layers.dense(inputs=drop1, units=512)
drop2 = tf.layers.dropout(inputs=full2, rate=1-pkeep, training=(mode == tf.estimator.ModeKeys.TRAIN), name='drop2')

l_weights = tf.Variable(tf.random_normal([512, 8], mean=0.0, stddev=0.01), name='weights')
l_biases = tf.Variable(tf.constant(0.0, shape=[8], dtype=tf.float32), name='biases')
#logits = tf.layers.dense(inputs=drop2, units=8,kernel_initializer=tf.constant_initializer(l_weights))
logits = tf.add(tf.matmul(drop2, l_weights), l_biases)

tf.logging.info("{} {} {} {}, {}, {}".format(pool1.get_shape(), pool2.get_shape(), pool3.get_shape(), flat.get_shape(), drop2.get_shape(), logits.get_shape()))

predictions = {
    # Generate predictions (for PREDICT and EVAL mode)
    "classes": tf.argmax(input=logits, axis=1),
    # Add `softmax_tensor` to the graph. It is used for PREDICT and by the
    # `logging_hook`.
    "probabilities": tf.nn.softmax(logits, name="matmul_tensor")
}

if mode == tf.estimator.ModeKeys.PREDICT:
    export_outputs = {
            'predict_output': tf.estimator.export.PredictOutput(predictions)
    }
    return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions, export_outputs=export_outputs)

# Calculate Loss (for both TRAIN and EVAL modes)
onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=8)
#logger.info("onehots {} logits {}".format(tf.shape(onehot_labels), tf.shape(logits)))
loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels, logits=logits)

# Configure the Training Op (for TRAIN mode)
if mode == tf.estimator.ModeKeys.TRAIN:
    """
    optimizer = tf.train.MomentumOptimizer(learning_rate=0.01,
                                           momentum=0.9,
                                           use_nesterov=True)
    """
    #optimizer = tf.train.AdamOptimizer(learning_rate=1e-4)
    optimizer= tf.train.AdadeltaOptimizer(rho=0.95, epsilon=1e-6)
    train_op = optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

  # Add evaluation metrics (for EVAL mode)
eval_metric_ops = {
    "accuracy": tf.metrics.accuracy(
        labels=labels, predictions=predictions["classes"])}
return tf.estimator.EstimatorSpec(
    mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)
</code>```

Running it with my tf.Estimator gives the error in the title.

I've checked the tensors' sizes. conv1's is (?, 56, 56, 96), pool1's is (?, 27, 27, 96), pool2's is (?, 13, 13, 256), pool3's is (?, 6, 6, 384), flat's is (?, 13824), drop2's is (?, 512), and logits's is (?, 8).

All the shapes seem to check out to me, or am I missing something? And since the '?' refers to the batch size which I set up as 128, is it possible that I'm setting up the TFRecords input function wrong?

EDIT:

With batch size being 1, I get the same error except with a twist: the logits_size is [4, 8] and the layers_size is [1, 8]

答: Turns out it really is my TFRecords reading function. I encoded my images from float32 and read it with uint8.

Body:
I tried to port the Levi-Hassner non-BN model from the rude-carnie Github project into tf.layers syntax which now looks like this:

pkeep=0.5

weight_decay = 0.0005
weights_regularizer = tf.contrib.layers.l2_regularizer(weight_decay)
weights_initializer = tf.random_normal_initializer(stddev=0.01)

input_image = features["x"]

input_layer = tf.reshape(input_image, [-1, 227, 227, 3])

conv1 = tf.layers.conv2d(
        inputs=input_layer,
        filters=96,
        kernel_size=[7,7],
        strides=[4,4],
        padding="valid",
        kernel_initializer=weights_initializer,
        bias_initializer=tf.constant_initializer(0.),
        kernel_regularizer=weights_regularizer,
        activation=tf.nn.relu)
pool1 = tf.layers.max_pooling2d(inputs=conv1,
                                pool_size=[3, 3],
                                strides=2,
                                padding="valid")
lr_n1 = tf.nn.local_response_normalization(input=pool1, depth_radius=5, alpha=0.0001, beta=0.75, name='norm1')

conv2 = tf.layers.conv2d(
        inputs=lr_n1,
        filters=256,
        kernel_size=[5,5],
        strides=[1,1],
        kernel_initializer=weights_initializer,
        bias_initializer=tf.constant_initializer(1.),
        kernel_regularizer=weights_regularizer,
        padding="same",
        activation=tf.nn.relu)
pool2 = tf.layers.max_pooling2d(inputs=conv2,
                                pool_size=[3, 3],
                                strides=2,
                                padding="valid")
lr_n2 = tf.nn.local_response_normalization(input=pool2,
                                           depth_radius=5,
                                           alpha=0.0001,
                                           beta=0.75,
                                           name='norm2')

conv3 = tf.layers.conv2d(
        inputs=lr_n2,
        filters=384,
        kernel_size=[3,3],
        strides=[1,1],
        kernel_initializer=weights_initializer,
        bias_initializer=tf.constant_initializer(0.),
        kernel_regularizer=weights_regularizer,
        padding="same",
        activation=tf.nn.relu)
pool3 = tf.layers.max_pooling2d(inputs=conv3,
                                pool_size=[3, 3],
                                strides=2,
                                padding="valid")

flat = tf.reshape(pool3, [-1, 384*6*6 ], name="reshape")

full1 = tf.layers.dense(inputs=flat, units=512)
drop1 = tf.layers.dropout(inputs=full1, rate=1-pkeep, training=(mode == tf.estimator.ModeKeys.TRAIN), name='drop1')
full2 = tf.layers.dense(inputs=drop1, units=512)
drop2 = tf.layers.dropout(inputs=full2, rate=1-pkeep, training=(mode == tf.estimator.ModeKeys.TRAIN), name='drop2')

l_weights = tf.Variable(tf.random_normal([512, 8], mean=0.0, stddev=0.01), name='weights')
l_biases = tf.Variable(tf.constant(0.0, shape=[8], dtype=tf.float32), name='biases')
#logits = tf.layers.dense(inputs=drop2, units=8,kernel_initializer=tf.constant_initializer(l_weights))
logits = tf.add(tf.matmul(drop2, l_weights), l_biases)

tf.logging.info("{} {} {} {}, {}, {}".format(pool1.get_shape(), pool2.get_shape(), pool3.get_shape(), flat.get_shape(), drop2.get_shape(), logits.get_shape()))

predictions = {
    # Generate predictions (for PREDICT and EVAL mode)
    "classes": tf.argmax(input=logits, axis=1),
    # Add `softmax_tensor` to the graph. It is used for PREDICT and by the
    # `logging_hook`.
    "probabilities": tf.nn.softmax(logits, name="matmul_tensor")
}

if mode == tf.estimator.ModeKeys.PREDICT:
    export_outputs = {
            'predict_output': tf.estimator.export.PredictOutput(predictions)
    }
    return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions, export_outputs=export_outputs)

# Calculate Loss (for both TRAIN and EVAL modes)
onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=8)
#logger.info("onehots {} logits {}".format(tf.shape(onehot_labels), tf.shape(logits)))
loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels, logits=logits)

# Configure the Training Op (for TRAIN mode)
if mode == tf.estimator.ModeKeys.TRAIN:
    """
    optimizer = tf.train.MomentumOptimizer(learning_rate=0.01,
                                           momentum=0.9,
                                           use_nesterov=True)
    """
    #optimizer = tf.train.AdamOptimizer(learning_rate=1e-4)
    optimizer= tf.train.AdadeltaOptimizer(rho=0.95, epsilon=1e-6)
    train_op = optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

  # Add evaluation metrics (for EVAL mode)
eval_metric_ops = {
    "accuracy": tf.metrics.accuracy(
        labels=labels, predictions=predictions["classes"])}
return tf.estimator.EstimatorSpec(
    mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)

Running it with my tf.Estimator gives the error in the title.

I've checked the tensors' sizes. conv1's is (?, 56, 56, 96), pool1's is (?, 27, 27, 96), pool2's is (?, 13, 13, 256), pool3's is (?, 6, 6, 384), flat's is (?, 13824), drop2's is (?, 512), and logits's is (?, 8).

All the shapes seem to check out to me, or am I missing something? And since the '?' refers to the batch size which I set up as 128, is it possible that I'm setting up the TFRecords input function wrong?

EDIT:

With batch size being 1, I get the same error except with a twist: the logits_size is [4, 8] and the layers_size is [1, 8]


问:
Calling setValuesForKeys fails in my Swift 4 code
I'm having this problem, im trying to retrieve data from the firebase database, but it's saying the profilepic isn't a key, but it is. This is the object class.

```<code>class User: NSObject {
    var firstname: String?
    var lastname: String?
    var username: String?
    var profilepic: String?
}
</code>```

and this is me trying to retrieve

```<code>func getusers(){
        ref.child("Friends").child(currentuser!).observe(.childAdded, with: { (snapshot) in
            print(snapshot)
            if let dic = snapshot.value as? [String: AnyObject]{
                let user = User()
                user.setValuesForKeys(dic)
                print(user.firstname, user.lastname)

                DispatchQueue.main.async {
                    self.tableview.reloadData()
                }}
        }) { (error) in
            print(error.localizedDescription)
        }

    }
</code>```

and the crash is here user.setValuesForKeys(dic).

Anyone has any idea why isn't working?

答:
Change your User declaration to this:

```<code>class User: NSObject {
    @objc var firstname: String?
    @objc var lastname: String?
    @objc var username: String?
    @objc var profilepic: String?
}
</code>```

In Swift 4, Objective-C cannot see your instance properties unless you expose them explicitly.

Body:
I'm having this problem, im trying to retrieve data from the firebase database, but it's saying the profilepic isn't a key, but it is. This is the object class.

class User: NSObject {
    var firstname: String?
    var lastname: String?
    var username: String?
    var profilepic: String?
}

and this is me trying to retrieve

func getusers(){
        ref.child("Friends").child(currentuser!).observe(.childAdded, with: { (snapshot) in
            print(snapshot)
            if let dic = snapshot.value as? [String: AnyObject]{
                let user = User()
                user.setValuesForKeys(dic)
                print(user.firstname, user.lastname)

                DispatchQueue.main.async {
                    self.tableview.reloadData()
                }}
        }) { (error) in
            print(error.localizedDescription)
        }

    }

and the crash is here user.setValuesForKeys(dic).

Anyone has any idea why isn't working?

Body:
Change your User declaration to this:

class User: NSObject {
    @objc var firstname: String?
    @objc var lastname: String?
    @objc var username: String?
    @objc var profilepic: String?
}

In Swift 4, Objective-C cannot see your instance properties unless you expose them explicitly.


问:
sizeof void pointer
why is sizeof void pointer 2 ?

答:
Size of a Pointer is equal to the size of an Integer . It can be 2 bytes in a 16bit compiler and 4 bytes in 32 bit compiler and 8 in 64 bit compiler.

void *ptr, int *ptr and char *ptr will give you same size but if you do ptr++ , the corresponding pointer will jump according to there data types. ie 1 position in void and char case. Similarly 4 positions in int case.

Title: sizeof void pointer

Body: why is sizeof void pointer 2 ?


问:
ng-show only working once
Basically, i am importing a file and upon success/ fail show a bootstrap panel. I am using ng-show. The panel works only one time. If i try to import a file a second time the panel wont show at all. I think its the way its being closed its not tied to the angular. How can i get the panel to show/hide more than one time?

Here is part of my controller.

```<code>$scope.importValidatedFile = function(){
    var file = $scope.importFile;
    var fd = new FormData();
    fd.append('file', file);
    $scope.loading = true;

    $http.post('rest/importfeed/import/' + $scope.selectedSource.sourceId, fd,{
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).
    success(function (data) {
        $scope.loading = false;

       $scope.fileSuccess = true;   //here is the panel

        document.getElementById('fileInput').value = "";
        angular.element(document.getElementById('validate'))[0].disabled = true;
        angular.element(document.getElementById('import'))[0].disabled = true;

    }).
    error(function (error) {
        $scope.danger = true;
        document.getElementById('fileInput').value = "";
        angular.element(document.getElementById('validate'))[0].disabled = true;
        angular.element(document.getElementById('import'))[0].disabled = true;
    }).finally(function () {
        $scope.loading = false;
    });

};
</code>```

Here is the panel on the html page.

```<code> <div ng-show="fileSuccess">
       <div class="row">
       <div class="col-sm-9 col-lg-12">
       <div class="panel-body">
      <div class="col-xs-12 alert alert-success" id="success">

    <button type="button" class="close" data-target="#success" data-dismiss="alert"> <span aria-hidden="true">×</span>
       <span class="sr-only">Close</span>
       </button>
      <div class="glyphicon glyphicon glyphicon-ok success-gliph"></div>
      <div class="success-text"><b>Success!</b></div>
      <p class="record-text">The Record was saved.</p>
      </div>
      </div>
     </div>
    </div>
    </div>
</code>```

I have a sneaky suspicion its how its being closed and how angular doesn't know about it.

What can i do to get the panel in ng-show to work more than once?

EDIT** I tried adding this to the button.

```<code><button ng-click="check();" type="button" class="close" data-target="#success" data-dismiss="alert"> <span ng-click="check();" aria-hidden="true">×</span>
                                        <span class="sr-only">Close</span>
</code>```

and in angular controller

```<code> $scope.check = function (){
    alert("in check");
    $scope.fileSuccess = false;
};
</code>```

and it still doesnt work

答:
can you try this? reset fileSucess every time you call importValidateFile(), and change ng-show to ng-if in your html</p>

```<code>$scope.importValidatedFile = function(){
    var file = $scope.importFile;
    var fd = new FormData();
    fd.append('file', file);
    $scope.loading = true;
    $scope.fileSuccess = false;

$http.post('rest/importfeed/import/' + $scope.selectedSource.sourceId, fd,{
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
}).
</code>```

Title: ng-show only working once

Body:
Basically, i am importing a file and upon success/ fail show a bootstrap panel. I am using ng-show. The panel works only one time. If i try to import a file a second time the panel wont show at all. I think its the way its being closed its not tied to the angular. How can i get the panel to show/hide more than one time?

Here is part of my controller.

$scope.importValidatedFile = function(){
    var file = $scope.importFile;
    var fd = new FormData();
    fd.append('file', file);
    $scope.loading = true;

    $http.post('rest/importfeed/import/' + $scope.selectedSource.sourceId, fd,{
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).
    success(function (data) {
        $scope.loading = false;

       $scope.fileSuccess = true;   //here is the panel

        document.getElementById('fileInput').value = "";
        angular.element(document.getElementById('validate'))[0].disabled = true;
        angular.element(document.getElementById('import'))[0].disabled = true;

    }).
    error(function (error) {
        $scope.danger = true;
        document.getElementById('fileInput').value = "";
        angular.element(document.getElementById('validate'))[0].disabled = true;
        angular.element(document.getElementById('import'))[0].disabled = true;
    }).finally(function () {
        $scope.loading = false;
    });

};

Here is the panel on the html page.

    <button type="button" class="close" data-target="#success" data-dismiss="alert"> ×
       Close
       </button>

Success!

The Record was saved.

I have a sneaky suspicion its how its being closed and how angular doesn't know about it.

What can i do to get the panel in ng-show to work more than once?

EDIT** I tried adding this to the button.

<button ng-click="check();" type="button" class="close" data-target="#success" data-dismiss="alert"> ×
                                        Close

and in angular controller

 $scope.check = function (){
    alert("in check");
    $scope.fileSuccess = false;
};

and it still doesnt work

Body:
can you try this? reset fileSucess every time you call importValidateFile(), and change ng-show to ng-if in your html

$scope.importValidatedFile = function(){
    var file = $scope.importFile;
    var fd = new FormData();
    fd.append('file', file);
    $scope.loading = true;
    $scope.fileSuccess = false;

$http.post('rest/importfeed/import/' + $scope.selectedSource.sourceId, fd,{
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
}).


问:
Azure B2C - Migrating users from SQL Database to B2C tenant
We are looking for any template or process available to migrate users that exist within an existing SQL Database into B2C users for their tenant. We also would need to validate the user's passwords prior to creation of these migrated users.

Is there any type of script/process you can suggest for completing such a B2C Tenant migration task.

答:
Is there any type of script/process you can suggest for completing
  such a B2C Tenant migration task.

Yes, you can use the Azure AD Graph API to achieve that. Also,we can migrate user accounts with hashed passwords to Azure AD B2C now.

See more details about a new guide to User migration to Azure AD B2C in this document.

We also would need to validate the user's passwords prior to creation
  of these migrated users.

There is two flows in this migration. Whether you can access the users' passwords or not, you can both migrate them easily.

Pre-migration: This flow applies when you either have clear access to a user's credentials (user name and password) or the credentials are encrypted, but you can decrypt them. The pre-migration process involves reading the users from the old identity provider and creating new accounts in the Azure AD B2C directory.

Pre-migration and password reset: This flow applies when a user's password is not accessible. For example:
The password is stored in HASH format.
The password is stored in an identity provider that you can't access. Your old identity provider validates the user credential by calling a web service.

In both flows, you first run the pre-migration process, read the users from your old identity provider, and create new accounts in the Azure AD B2C directory. If you do not have the password, you create the account by using a password that's generated randomly. You then ask the user to change the password or, when the user signs in for the first time, Azure AD B2C asks the user to reset it.

Also, if you are unfamiliar with using Azure AD Graph API to Azure AD B2C, you can refer to this document.


问:
making non-static http links
i am currently trying to add a file directory into a http so that the http link will not be static to a single computer.

I tried to input getcwd() into the http link but it does work.

is there any way to make a non-static http link ?

for example this is my old link :

```<code>$link="http://qna.nyp.edu.sg/qa4u/qa4u_working/presenter/eventfile/EventID".$eid."/".$eid."_".$email.".pdf";
</code>```

I am trying to do this instead :

```<code>$link="http:\\".getcwd()."\\eventfile\\EventID".$eid."\\".$eid."_".$email.".pdf";
</code>```

is it possible to make it work?

答:
use $_SERVER['HTTP_HOST']</p>

```<code>$link="http:\\".$_SERVER['HTTP_HOST']."\\eventfile\\EventID".$eid."\\".$eid."_".$email.".pdf";
</code>```

Title: making non-static http links

Body:
i am currently trying to add a file directory into a http so that the http link will not be static to a single computer.

I tried to input getcwd() into the http link but it does work.

is there any way to make a non-static http link ?

for example this is my old link :

$link="http://qna.nyp.edu.sg/qa4u/qa4u_working/presenter/eventfile/EventID".$eid."/".$eid."_".$email.".pdf";

I am trying to do this instead :

$link="http:\\".getcwd()."\\eventfile\\EventID".$eid."\\".$eid."_".$email.".pdf";

is it possible to make it work?

Body:
use $_SERVER['HTTP_HOST']

$link="http:\\".$_SERVER['HTTP_HOST']."\\eventfile\\EventID".$eid."\\".$eid."_".$email.".pdf";


问:
Set AlertBox Title Bar Background Color
How can I change the background color for an alertbox's title bar?</p>

```<code>AlertDialog.Builder alert=new AlertDialog.Builder(getParent());
alert.setTitle("sample");
alert.show();
</code>```

答:
From the answer @CornflakesDK and @ice spirit, I thought you can use the current AlertDialog.Builder implementation to do the custom dialog and make it easy to maintain.

CustomDialogBuilder.java

```<code>public class CustomDialogBuilder extends AlertDialog.Builder {

  private View view;

  public CustomDialogBuilder(Context context) {
    super(context);
    view = LayoutInflater.from(getContext()).inflate(R.layout.custom_dialog_title, null);
    setCustomTitle(view);
  }

  @Override
  public Builder setTitle(int titleId) {
    TextView titleTextView = view.findViewById(R.id.exemptionSubHeading4);
    titleTextView.setText(getContext().getString(titleId));
    return this;
  }

  @Override
  public Builder setTitle(CharSequence title) {
    TextView titleTextView = view.findViewById(R.id.exemptionSubHeading4);
    titleTextView.setText(title);
    return this;
  }
}
</code>```

custom_dialog.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">
  <LinearLayout
    android:id="@+id/llsubhead"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:background="@color/black"
    android:orientation="vertical">
    <TextView
      android:id="@+id/exemptionSubHeading4"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:layout_margin="15dp"
      android:layout_gravity="center"
      android:text="Exemption Sub Head"
      android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
      android:textColor="@color/white" />
  </LinearLayout>
</LinearLayout>
</code>```

Inside your activity code,

```<code> new CustomDialogBuilder(MyActivity.this)
                  .setTitle(R.string.actions)
                  .setItems(R.array.items_actions, (dialog, which) -> {
                    // handle items
                  }).create().show();
</code>```

Then, you can have styling inside the DialogBuilder and also utilize the functions of the AlertDialog.Builder.

Title: Set AlertBox Title Bar Background Color

Body:
How can I change the background color for an alertbox's title bar?

AlertDialog.Builder alert=new AlertDialog.Builder(getParent());
alert.setTitle("sample");
alert.show();

Body:
From the answer @CornflakesDK and @ice spirit, I thought you can use the current AlertDialog.Builder implementation to do the custom dialog and make it easy to maintain.

CustomDialogBuilder.java

public class CustomDialogBuilder extends AlertDialog.Builder {

  private View view;

  public CustomDialogBuilder(Context context) {
    super(context);
    view = LayoutInflater.from(getContext()).inflate(R.layout.custom_dialog_title, null);
    setCustomTitle(view);
  }

  @Override
  public Builder setTitle(int titleId) {
    TextView titleTextView = view.findViewById(R.id.exemptionSubHeading4);
    titleTextView.setText(getContext().getString(titleId));
    return this;
  }

  @Override
  public Builder setTitle(CharSequence title) {
    TextView titleTextView = view.findViewById(R.id.exemptionSubHeading4);
    titleTextView.setText(title);
    return this;
  }
}

custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">
  <LinearLayout
    android:id="@+id/llsubhead"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:background="@color/black"
    android:orientation="vertical">
    <TextView
      android:id="@+id/exemptionSubHeading4"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:layout_margin="15dp"
      android:layout_gravity="center"
      android:text="Exemption Sub Head"
      android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
      android:textColor="@color/white" />
  </LinearLayout>
</LinearLayout>

Inside your activity code,

 new CustomDialogBuilder(MyActivity.this)
                  .setTitle(R.string.actions)
                  .setItems(R.array.items_actions, (dialog, which) -> {
                    // handle items
                  }).create().show();

Then, you can have styling inside the DialogBuilder and also utilize the functions of the AlertDialog.Builder.


问:
No matching overloaded function found C++ TEMPLATE
Recurvise call C++ template function with Variable template

```<code>void int void foo()
{

}

template <typename T, typename ...U> void foo()
{
    foo<U...>();
}

int main()
{
    foo<int, char, int>();
    return 0;
}
</code>```

The compile meesage such as:

error C2672: 'foo': no matching overloaded function found
note: see reference to function template instantiation 'void foo(void)' being compiled
note: see reference to function template instantiation 'void foo(void)' being compiled
note: see reference to function template instantiation 'void foo(void)' being compiled
error C2783: 'void foo(void)': could not deduce template argument for 'T'
note: see declaration of 'foo'

I declare the void foo(void), Why the error occured?
complier can match template  void foo(), but can't match void foo(void)

答:
Assuming your base case is void foo() {}, in your recursive case you're performing the following function invocations:

```<code>foo<int, char, int>();
foo<char, int>();
foo<int>();
foo<>();
</code>```

Notice that the last invocation is foo<>(); rather than foo();.
The compiler error is due to the fact that your base case of
void foo() {} cannot be called with the foo<>(); syntax.

Body:
Recurvise call C++ template function with Variable template

void int void foo()
{

}

template <typename T, typename ...U> void foo()
{
    foo();
}

int main()
{
    foo<int, char, int>();
    return 0;
}

The compile meesage such as:

error C2672: 'foo': no matching overloaded function found
note: see reference to function template instantiation 'void foo(void)' being compiled
note: see reference to function template instantiation 'void foo(void)' being compiled
note: see reference to function template instantiation 'void foo(void)' being compiled
error C2783: 'void foo(void)': could not deduce template argument for 'T'
note: see declaration of 'foo'

I declare the void foo(void), Why the error occured?
complier can match template  void foo(), but can't match void foo(void)

Body:
Assuming your base case is void foo() {}, in your recursive case you're performing the following function invocations:

foo<int, char, int>();
foo<char, int>();
foo<int>();
foo<>();

Notice that the last invocation is foo<>(); rather than foo();.
The compiler error is due to the fact that your base case of
void foo() {} cannot be called with the foo<>(); syntax.


问:
How to avoid warning of Unreachable code
I have the below

```<code>string currency = string.Empty;
Regex r = new Regex(@"~(\w*[a-zA-Z0-9$£~%]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (Match m = r.Match(expression); m.Success; m = m.NextMatch())
{
      currency = (m.Groups[1].Value);
      break;
}
return currency;
</code>```

The intension is that, after the first match in the loop it should break.

The warning messge(Unreachable code) is happening  m = m.NextMatch() of the loop.

How to overcome this?

Thanks

答:
Perhaps I'm missing something, but why are you even using a loop here? Why not just use r.Match(expression) straight off?

There's little point of having a loop if you'll always break out of it on the first iteration.

Body:
I have the below

string currency = string.Empty;
Regex r = new Regex(@"~(\w*[a-zA-Z0-9$£~%]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (Match m = r.Match(expression); m.Success; m = m.NextMatch())
{
      currency = (m.Groups[1].Value);
      break;
}
return currency;

The intension is that, after the first match in the loop it should break.

The warning messge(Unreachable code) is happening  m = m.NextMatch() of the loop.

How to overcome this?

Thanks


问:
Open an image using URI in Android's default gallery image viewer
I have extracted image uri, now I would like to open image with Android's default image viewer. Or even better, user could choose what program to use to open the image. Something like File Explorers offer you if you try to open a file.</p>

答:
The problem with showing a file using Intent.ACTION_VIEW, is that if you pass the Uri parsing the path. Doesn't work in all cases. To fix that problem, you need to use:

```<code>Uri.fromFile(new File(filePath));
</code>```

Instead of:

```<code>Uri.parse(filePath);
</code>```

Edit

Here is my complete code:

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(mediaFile.filePath)), mediaFile.getExtension());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
</code>```

Info

MediaFile is my domain class to wrap files from database in objects.
MediaFile.getExtension() returns a String with Mimetype for the file extension. Example: "image/png"

Aditional code: needed for showing any file (extension)

```<code>import android.webkit.MimeTypeMap;

public String getExtension () {
    MimeTypeMap myMime = MimeTypeMap.getSingleton();
    return myMime.getMimeTypeFromExtension(MediaFile.fileExtension(filePath));
}

public static String fileExtension(String path) {
    if (path.indexOf("?") > -1) {
        path = path.substring(0, path.indexOf("?"));
    }
    if (path.lastIndexOf(".") == -1) {
        return null;
    } else {
        String ext = path.substring(path.lastIndexOf(".") + 1);
        if (ext.indexOf("%") > -1) {
            ext = ext.substring(0, ext.indexOf("%"));
        }
        if (ext.indexOf("/") > -1) {
            ext = ext.substring(0, ext.indexOf("/"));
        }
        return ext.toLowerCase();
    }
}
</code>```

Let me know if you need more code.

Body:
The problem with showing a file using Intent.ACTION_VIEW, is that if you pass the Uri parsing the path. Doesn't work in all cases. To fix that problem, you need to use:

Uri.fromFile(new File(filePath));

Instead of:

Uri.parse(filePath);

Edit

Here is my complete code:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(mediaFile.filePath)), mediaFile.getExtension());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Info

MediaFile is my domain class to wrap files from database in objects.
MediaFile.getExtension() returns a String with Mimetype for the file extension. Example: "image/png"

Aditional code: needed for showing any file (extension)

import android.webkit.MimeTypeMap;

public String getExtension () {
    MimeTypeMap myMime = MimeTypeMap.getSingleton();
    return myMime.getMimeTypeFromExtension(MediaFile.fileExtension(filePath));
}

public static String fileExtension(String path) {
    if (path.indexOf("?") > -1) {
        path = path.substring(0, path.indexOf("?"));
    }
    if (path.lastIndexOf(".") == -1) {
        return null;
    } else {
        String ext = path.substring(path.lastIndexOf(".") + 1);
        if (ext.indexOf("%") > -1) {
            ext = ext.substring(0, ext.indexOf("%"));
        }
        if (ext.indexOf("/") > -1) {
            ext = ext.substring(0, ext.indexOf("/"));
        }
        return ext.toLowerCase();
    }
}

Let me know if you need more code.


问:
Repeat Customers with multiple purchases on the same day counts a 1
I am trying to wrap my head around this problem.  I was asked to create a report that show repeat customers in our database.

One of the requirements is if a customer has more than 1 order on a specific date, it would only count as 1.
Then if they have more than 1 purchase date, they would then count as a repeat customer.

Searching on here, I found this which works for finding the Customers with more then 1 purchase on a specific purchase date.

```<code>SELECT DISTINCT s.[CustomerName], s.PurchaseDate

FROM Reports.vw_Repeat s WHERE s.PurchaseDate <> ''

GROUP BY s.[CustomerName] , cast(s.PurchaseDate as date)

HAVING COUNT(*) > 1;
</code>```

This MSSQL code works like it should, by showing customers who had more than 1 purchase on the same date.
My problem is what would the best approach be to Join this into another query (this is where i need help) that then shows a complete repeat customer list where customers with more than 1 purchase would be returned.

I am using MSSQL.  Any help would be greatly appreciated.

答:
You're close, you need to move distinct into your having clause because you want to include only customers that have more than 1 distinct purchase date.

Also, only group by the customer id because the different dates have to be part of the same group for count distinct to work.

```<code>SELECT s.[CustomerName], COUNT(distinct cast(s.PurchaseDate as date))
FROM Reports.vw_Repeat s WHERE s.PurchaseDate <> ''
GROUP BY s.[CustomerName]
HAVING COUNT(distinct cast(s.PurchaseDate as date)) > 1;
</code>```

Body:
I am trying to wrap my head around this problem.  I was asked to create a report that show repeat customers in our database.

One of the requirements is if a customer has more than 1 order on a specific date, it would only count as 1.
Then if they have more than 1 purchase date, they would then count as a repeat customer.

Searching on here, I found this which works for finding the Customers with more then 1 purchase on a specific purchase date.

SELECT DISTINCT s.[CustomerName], s.PurchaseDate

FROM Reports.vw_Repeat s WHERE s.PurchaseDate <> ''

GROUP BY s.[CustomerName] , cast(s.PurchaseDate as date)

HAVING COUNT(*) > 1;

This MSSQL code works like it should, by showing customers who had more than 1 purchase on the same date.
My problem is what would the best approach be to Join this into another query (this is where i need help) that then shows a complete repeat customer list where customers with more than 1 purchase would be returned.

I am using MSSQL.  Any help would be greatly appreciated.

Body:
You're close, you need to move distinct into your having clause because you want to include only customers that have more than 1 distinct purchase date.

Also, only group by the customer id because the different dates have to be part of the same group for count distinct to work.

SELECT s.[CustomerName], COUNT(distinct cast(s.PurchaseDate as date))
FROM Reports.vw_Repeat s WHERE s.PurchaseDate <> ''
GROUP BY s.[CustomerName]
HAVING COUNT(distinct cast(s.PurchaseDate as date)) > 1;


问:
ReformAlign executable not stable.
I have compiled and executable (ReformAlign) from a makefile, however, on launching it, it opens and closes immediately.

Is there something I failed to do or should do to enable work properly.
Any suggestions and help is greatly appreciated.

答:
on launching it, it opens and closes immediately

You don't offer much context.  I suspect by launching it, you mean clicking on an icon in Windows.  The program runs and, because it's very small, finishes immediately.  The window it runs in barely shows on your screen, if at all.

If that's the case, start cmd.exe, and run your program from the command line.  That will give you a chance to see its output.

Title: ReformAlign executable not stable.


问:
How to reverse geocoding using gms?
I noticed that there exists the GMSGeocoder for reverse geocoding for iOS, but not found the similarity in Google play service.

Of course, I can use the Geocoder in the Android Location api, or, there also a way for reverse geocoding using http request for this. but with the applied API key, I did find the corresponding XXGeocoder in GMS for Android in Google play service.

Did I miss it?

答:
This might fulfill your question Android: Reverse geocoding - getFromLocation

I've used it, and you have to specify how many matching address you want. The first address be accurate most of the times, but at times it can be a bit off the current address, just so you know

Title: How to reverse geocoding using gms?


问:
PHP - Echo Groups of 4 Index(s)
I am pulling information from a text document that has the following information

Example1, Test, Example1, Test, Example2, Test, Example2, Test,

I am trying to pull information from that document and present it as the following:

Example1, Test, Example1, Test

Example2, Test, Example2, Test

and so on.......

This is what I have right now of the PHP code as it deplays the message in an array and the index. My goal is to try and print only the first 4 index then break and print the next 4 index and so on. I'm not sure where I should start, so if anyone could help I would greatly appreciate it.

    <!DOCTYPE html>

<?php
$print_data=file_get_contents("http://xxxxxxxxx.log");
$array = explode(',', $print_data);
$length = count($array);
$new_formatted_array = array();
for($i = 0; $i < $length; $i++){
    if( ($i + 1) % 4 == 1){
        $new_formatted_array[] = array();
    }
    $new_array_index = count($new_formatted_array) - 1;
    $new_formatted_array[$new_array_index][] = $array[$i];
}

//Just for demo
echo "```";
print_r($new_formatted_array);
?>
</div>
</body>
</html></code>```

Output:

Array
(
    [0] => Array
        (
            [0] => Example1
            [1] =>  Test
            [2] =>  Example1
            [3] =>  Test
        )

    [1] => Array
        (
            [0] =>
Example2
            [1] =>  Test
            [2] =>  Example2
            [3] =>  Test
        )

    [2] => Array
        (
            [0] =>
Example3
            [1] =>  Test
            [2] =>  Example3
            [3] =>  Test
        )

    [3] => Array
        (
            [0] =>
        )

)```
</div>
</div>
</p>

<p>I have used array_chuck which shows the chunk of indexes I want, but it shows array(), [1]array, ect. My end goal is to get the four indexes as a group, but then to be able to format it into a table. </p>

<p>Table:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Example1  Test  Example1  Test

Example2  Test  Example2  Test

Example3  Test  Example3  Test</code>```

Can someone help fix the formatting of the table? Not sure why the rows are not even.

Figured it out, just not echo print_r

答:
You can use this as your basis. I just put a value in array so you can see the output.

```<code>$array  = array(
     'Example1',
     'Test',
     'Example1',
     'Test',
     'Example2',
     'Test',
     'Example2',
     'Test',
     'Example3',
     'Test',
     'Example3',
     'Test'
);
$length = count($array);
$new_formatted_array = array();
for($i = 0; $i < $length; $i++){
    if( ($i + 1) % 4 == 1){
        $new_formatted_array[] = array();
    }
    $new_array_index = count($new_formatted_array) - 1;
    $new_formatted_array[$new_array_index][] = $array[$i];
}

//Just for demo
echo "```";
print_r($new_formatted_array);

$output = '
';
//Display it in table
foreach($new_formatted_array as $i){
    $output .= '
';
    foreach($i as $value){
        $output .= '' . $value . '	';
    }
    $output .= '
';
}

$output .= '
';
//Just for demo
echo htmlentities($output);
```

<p><strong>New Array output:</strong></p>

```Array
(
    [0] => Array
        (
            [0] => Example1
            [1] => Test
            [2] => Example1
            [3] => Test
        )

    [1] => Array
        (
            [0] => Example2
            [1] => Test
            [2] => Example2
            [3] => Test
        )

    [2] => Array
        (
            [0] => Example3
            [1] => Test
            [2] => Example3
            [3] => Test
        )

)
```

<p><strong>Creating Table output:</strong></p>

```

        Example1
        Test
        Example1
        Test

        Example2
        Test
        Example2
        Test

        Example3
        Test
        Example3
        Test

```

Title: PHP - Echo Groups of 4 Index(s)

Body:
I am pulling information from a text document that has the following information

Example1, Test, Example1, Test, Example2, Test, Example2, Test,

I am trying to pull information from that document and present it as the following:

Example1, Test, Example1, Test

Example2, Test, Example2, Test

and so on.......

This is what I have right now of the PHP code as it deplays the message in an array and the index. My goal is to try and print only the first 4 index then break and print the next 4 index and so on. I'm not sure where I should start, so if anyone could help I would greatly appreciate it.

    <!DOCTYPE html>

<?php
$print_data=file_get_contents("http://xxxxxxxxx.log");
$array = explode(',', $print_data);
$length = count($array);
$new_formatted_array = array();
for($i = 0; $i < $length; $i++){
    if( ($i + 1) % 4 == 1){
        $new_formatted_array[] = array();
    }
    $new_array_index = count($new_formatted_array) - 1;
    $new_formatted_array[$new_array_index][] = $array[$i];
}

//Just for demo
echo "
";
print_r($new_formatted_array);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => Example1
            [1] =>  Test
            [2] =>  Example1
            [3] =>  Test
        )

    [1] => Array
        (
            [0] =>
Example2
            [1] =>  Test
            [2] =>  Example2
            [3] =>  Test
        )

    [2] => Array
        (
            [0] =>
Example3
            [1] =>  Test
            [2] =>  Example3
            [3] =>  Test
        )

    [3] => Array
        (
            [0] =>
        )

)

I have used array_chuck which shows the chunk of indexes I want, but it shows array(), [1]array, ect. My end goal is to get the four indexes as a group, but then to be able to format it into a table.

Table:

Example1  Test  Example1  Test

Example2  Test  Example2  Test

Example3  Test  Example3  Test

Can someone help fix the formatting of the table? Not sure why the rows are not even.

Figured it out, just not echo print_r

Body:
You can use this as your basis. I just put a value in array so you can see the output.

$array  = array(
     'Example1',
     'Test',
     'Example1',
     'Test',
     'Example2',
     'Test',
     'Example2',
     'Test',
     'Example3',
     'Test',
     'Example3',
     'Test'
);
$length = count($array);
$new_formatted_array = array();
for($i = 0; $i < $length; $i++){
    if( ($i + 1) % 4 == 1){
        $new_formatted_array[] = array();
    }
    $new_array_index = count($new_formatted_array) - 1;
    $new_formatted_array[$new_array_index][] = $array[$i];
}

//Just for demo
echo "<pre>";
print_r($new_formatted_array);

$output = '<table>';
//Display it in table
foreach($new_formatted_array as $i){
    $output .= '<tr>';
    foreach($i as $value){
        $output .= '<td>' . $value . '</td>';
    }
    $output .= '</tr>';
}

$output .= '</table>';
//Just for demo
echo htmlentities($output);

New Array output:

Array
(
    [0] => Array
        (
            [0] => Example1
            [1] => Test
            [2] => Example1
            [3] => Test
        )

    [1] => Array
        (
            [0] => Example2
            [1] => Test
            [2] => Example2
            [3] => Test
        )

    [2] => Array
        (
            [0] => Example3
            [1] => Test
            [2] => Example3
            [3] => Test
        )

)

Creating Table output:

<table>
    <tr>
        <td>Example1</td>
        <td>Test</td>
        <td>Example1</td>
        <td>Test</td>
    </tr>
    <tr>
        <td>Example2</td>
        <td>Test</td>
        <td>Example2</td>
        <td>Test</td>
    </tr>
    <tr>
        <td>Example3</td>
        <td>Test</td>
        <td>Example3</td>
        <td>Test</td>
    </tr>
</table>


问:
Why doesn't a lazy_static slog::Logger print until a non-static logger is used?
If I uncomment create_log, both log and LOG are printed on the console. Without it, nothing is printed. What is going on?

```<code>#[macro_use]
extern crate slog;
extern crate slog_term;
extern crate slog_async;
#[macro_use]
extern crate lazy_static;

use slog::Drain;

lazy_static! {
    static ref LOG: slog::Logger = create_log();
}

fn create_log() -> slog::Logger {
    let decorator = slog_term::TermDecorator::new().force_plain().build();
    let drain = slog_term::CompactFormat::new(decorator).build().fuse();
    let drain = slog_async::Async::new(drain).build().fuse();
    slog::Logger::root(drain, o!())
}

fn main() {
    info!(LOG, "LOG");  // NOT printed unless next line is uncommented

    // let log = create_log();     // enables printing both log and LOG
    // info!(log, "log");
}
</code>```

答:
By using slog-async, you have opted into:

slog-async allows building Drains that offload processing to another thread. Typically serialization and IO operations can be slow enough that they could make logging hinder performance of the main code. Sending logging records to another thread is much faster (ballpark of 100ns).

Your code registers a log event which will be sent to another thread and then immediately exits. There wasn't any time for the background thread to actually log.

However, by putting a sleep at the end of your program, it "works":

```<code>std::thread::sleep_ms(1000);
</code>```

Why does the other case work? Again, we turn to the docs, emphasis mine:

When using std::process::exit to terminate a process with an exit code it is imporant to notice that destructors will not be called. This matters for slog_async as it will prevents flushing of the async drain and discarding messages that are not yet written.

Items in lazy-static do not have their destructors run (when would they, if the point of it is to live forever).

When you construct another logger from the main function, it is allocated on the stack and will be dropped. This causes the previous log message to also be flushed.

Body:
If I uncomment create_log, both log and LOG are printed on the console. Without it, nothing is printed. What is going on?

#[macro_use]
extern crate slog;
extern crate slog_term;
extern crate slog_async;
#[macro_use]
extern crate lazy_static;

use slog::Drain;

lazy_static! {
    static ref LOG: slog::Logger = create_log();
}

fn create_log() -> slog::Logger {
    let decorator = slog_term::TermDecorator::new().force_plain().build();
    let drain = slog_term::CompactFormat::new(decorator).build().fuse();
    let drain = slog_async::Async::new(drain).build().fuse();
    slog::Logger::root(drain, o!())
}

fn main() {
    info!(LOG, "LOG");  // NOT printed unless next line is uncommented

    // let log = create_log();     // enables printing both log and LOG
    // info!(log, "log");
}

Body:
By using slog-async, you have opted into:

slog-async allows building Drains that offload processing to another thread. Typically serialization and IO operations can be slow enough that they could make logging hinder performance of the main code. Sending logging records to another thread is much faster (ballpark of 100ns).

Your code registers a log event which will be sent to another thread and then immediately exits. There wasn't any time for the background thread to actually log.

However, by putting a sleep at the end of your program, it "works":

std::thread::sleep_ms(1000);

Why does the other case work? Again, we turn to the docs, emphasis mine:

When using std::process::exit to terminate a process with an exit code it is imporant to notice that destructors will not be called. This matters for slog_async as it will prevents flushing of the async drain and discarding messages that are not yet written.

Items in lazy-static do not have their destructors run (when would they, if the point of it is to live forever).

When you construct another logger from the main function, it is allocated on the stack and will be dropped. This causes the previous log message to also be flushed.