问:
JAVA Match a Username with a Password for Login Program
I am coding a login program that allows you to set and store a password and username in two separate files (named accordingly). My problem is I can't figure out how to set a username to a password. Ex: Username is Bob, Password is cat, and the user needs to input Bob as the username and cat as the password or else it gives an error(if the user inputs the username as bill and the password as cat, it should detect that the username doesn't go with its respective password). Any help would be nice. *I have not added the username part yet as it is structured the same as the password part, I just need the username to correspond with the password so that the user cannot use a different username with the same password

Here is my code I have so far for a reference:

```<code>import java.io.File;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.FileReader;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class PassCode
{
    static String adminPassword = "Change Password";
    public static void fileMaker() throws IOException
    {
        PrintStream standard = System.out;
        File f = new File("Password.txt");
        FileOutputStream fs= new FileOutputStream(f);
        PrintStream ps = new PrintStream(fs);
        System.setOut(ps);
        String theMessage = "Set New Password";
        String userInput = JOptionPane.showInputDialog(theMessage);
        System.out.println(userInput);
        ps.close();
        System.setOut(standard);
    }
public static void Checker() throws IOException
    {
        Scanner inputStream = new Scanner(new FileReader("Password.txt")); //Scans declared file for text on the first line
        String fileChecker = inputStream.nextLine(); //Sets scanned line into a string variable
        if(fileChecker.isEmpty())
        {
            fileMaker();
        }
        else
        {
        int reply = JOptionPane.showConfirmDialog(null, "Would you like to change the current password", "Warning!", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION)
          {
              String inquire = "Type Administrator Password to Proceed";
              boolean flag = true;
              while(flag == true)
          {
              String confirm = JOptionPane.showInputDialog(inquire);
          if(confirm.equals(adminPassword))
          {
              fileMaker();
              flag = false;
          }
          else
          {
              inquire = "Incorrect!" + "\n" + "Retry";
          }
          }
        }
        }
    }
    public static void main(String[] args) throws IOException
    {
        Checker();
        Scanner inputStreamThree = new Scanner(new FileReader("Password.txt"));
        String line = inputStreamThree.nextLine();
        String question = "Password Please";
        Boolean right = true;
         while(right == true)
        {
            String ask = JOptionPane.showInputDialog(question); //Asks for user to input password
        if(ask.equals(adminPassword)) //Checks if user input the admin password
        {
            fileMaker();
            Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
            String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
            line = adminChecker;
        }
        else if(line.equals(ask)) //Checks if user password is correct
        {
            System.out.println("Welcome Fellow Programmer to the Now Functioning Password Checker!" +
                "\n" + "Date Today: 10/31/2017" +
                "\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
            right = false;
        }
        else if(ask != line) //Checks if user password is incorrect
            {
               question = "Incorrect Password!";
            }
        }
    }
}
</code>```

答:
If both username and password are located in the same line number in their respective file, then it should be possible to deduct the right password for a given user.

Example:

```<code>Username.txt                       Password.txt
bob                                cat
alice                              rabbit
victor                             salmon
</code>```

When searching the username, count the line read until you find the username. Then in the password file, read the number of lines and retrieve the password value. Then compare!

I assume this is academic work because storing password in clear in files is a major security hole and should never be allowed on professional project.

Body:
I am coding a login program that allows you to set and store a password and username in two separate files (named accordingly). My problem is I can't figure out how to set a username to a password. Ex: Username is Bob, Password is cat, and the user needs to input Bob as the username and cat as the password or else it gives an error(if the user inputs the username as bill and the password as cat, it should detect that the username doesn't go with its respective password). Any help would be nice. *I have not added the username part yet as it is structured the same as the password part, I just need the username to correspond with the password so that the user cannot use a different username with the same password

Here is my code I have so far for a reference:

import java.io.File;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.FileReader;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class PassCode
{
    static String adminPassword = "Change Password";
    public static void fileMaker() throws IOException
    {
        PrintStream standard = System.out;
        File f = new File("Password.txt");
        FileOutputStream fs= new FileOutputStream(f);
        PrintStream ps = new PrintStream(fs);
        System.setOut(ps);
        String theMessage = "Set New Password";
        String userInput = JOptionPane.showInputDialog(theMessage);
        System.out.println(userInput);
        ps.close();
        System.setOut(standard);
    }
public static void Checker() throws IOException
    {
        Scanner inputStream = new Scanner(new FileReader("Password.txt")); //Scans declared file for text on the first line
        String fileChecker = inputStream.nextLine(); //Sets scanned line into a string variable
        if(fileChecker.isEmpty())
        {
            fileMaker();
        }
        else
        {
        int reply = JOptionPane.showConfirmDialog(null, "Would you like to change the current password", "Warning!", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION)
          {
              String inquire = "Type Administrator Password to Proceed";
              boolean flag = true;
              while(flag == true)
          {
              String confirm = JOptionPane.showInputDialog(inquire);
          if(confirm.equals(adminPassword))
          {
              fileMaker();
              flag = false;
          }
          else
          {
              inquire = "Incorrect!" + "\n" + "Retry";
          }
          }
        }
        }
    }
    public static void main(String[] args) throws IOException
    {
        Checker();
        Scanner inputStreamThree = new Scanner(new FileReader("Password.txt"));
        String line = inputStreamThree.nextLine();
        String question = "Password Please";
        Boolean right = true;
         while(right == true)
        {
            String ask = JOptionPane.showInputDialog(question); //Asks for user to input password
        if(ask.equals(adminPassword)) //Checks if user input the admin password
        {
            fileMaker();
            Scanner inputStreamAdmin = new Scanner(new FileReader("Password.txt")); //Scans for admin password
            String adminChecker = inputStreamAdmin.nextLine(); //Sets scanned line as a new string variable
            line = adminChecker;
        }
        else if(line.equals(ask)) //Checks if user password is correct
        {
            System.out.println("Welcome Fellow Programmer to the Now Functioning Password Checker!" +
                "\n" + "Date Today: 10/31/2017" +
                "\n\n\n\n\n\n\n" + "Did you figure out the Admin password yet?");
            right = false;
        }
        else if(ask != line) //Checks if user password is incorrect
            {
               question = "Incorrect Password!";
            }
        }
    }
}

Body:
If both username and password are located in the same line number in their respective file, then it should be possible to deduct the right password for a given user.

Example:

Username.txt                       Password.txt
bob                                cat
alice                              rabbit
victor                             salmon

When searching the username, count the line read until you find the username. Then in the password file, read the number of lines and retrieve the password value. Then compare!

I assume this is academic work because storing password in clear in files is a major security hole and should never be allowed on professional project.


来源: stackexchange

问:
Lotus Notes: display fields values in different rows in column
I have a number field called Days and an editable names field called Names ( which allows multiple values ).

Let say that Days=1 and Names=Mike/Rock, Tom/Rock, Dean/Rock.

I want to display them in a column view like this:

```<code>    1
    Mike
    Tom
    Dean
</code>```

I tried it with @NewLine, but no luck for me.

I also created a computed (hidden) field test with the following formula as default value:

```<code>@Text(Days)+@NewLine+@Implode(@Name([CN];Names);@NewLine)
</code>```

It seems to be the wanted form for me, but when I just put test in a column default value, it shows nothing.

I appreciate your time.

答:
In a view we get only one row for one document. Multiple values are therefore shown in one row only with multi value separator.
Eclipse view may perhaps help.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a number field called Days and an editable names field called Names ( which allows multiple values ).

Let say that Days=1 and Names=Mike/Rock, Tom/Rock, Dean/Rock.

I want to display them in a column view like this:

    1
    Mike
    Tom
    Dean

I tried it with @NewLine, but no luck for me.

I also created a computed (hidden) field test with the following formula as default value:

@Text(Days)+@NewLine+@Implode(@Name([CN];Names);@NewLine)

It seems to be the wanted form for me, but when I just put test in a column default value, it shows nothing.

I appreciate your time.


问:
malloc error -[CFString release]
For some reason my app was crashing on a particular action. After investigation, I found out it is because of releasing something that has already been released. Then I read on the internet that I can track down the cause of this using NSZombie and MallocStackLogging which I implemented and got this as the result.

NSZombie: 2011-01-19 14:39:09.523
  iota[13649:207] * -[CFString
  release]: message sent to deallocated
  instance 0xeeaf510

malloc_history

ALLOC 0xeeaf510-0xeeaf52f [size=32]:
  thread_a0041500 |start | main |
  UIApplicationMain | GSEventRun |
  GSEventRunModal | CFRunLoopRunInMode |
  CFRunLoopRunSpecific | CFRunLoopRun
  | __CFRunLoopDoTimer |
  __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION
  | __NSFireDelayedPerform |
  -[UITableView _userSelectRowAtIndexPath:] | -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:]
  | -[CorpDirViewController
  tableView:didSelectRowAtIndexPath:] |
  -[CorpDirPersonViewController corpDirViewController:shouldContinueAfterSelectingContact:]
  | -[ContactItem mergeWithContact:] |
  -[ContactItem getValueForProperty:] | ABRecordCopyValue |
  CPRecordCopyProperty |
  CPRecordGetProperty |
  ABCMultiValueLoad |
  ABCDBContextFetchMultiValuePropertyIntoRecord
  | ABCDBContextFetchMultiValueEntries |
  CPSqliteStatementSendResults |
  CollectMultiValueEntries |
  _sqliteStatementApplyValuesFromRecordWithNullValue
  | CFStringCreateWithCString |
  __CFStringCreateImmutableFunnel3 | _CFRuntimeCreateInstance | malloc_zone_malloc

Now I am unable to find out particularly what is causing the crash. Can anyone help me out with it?

答:
Verify your alloc/ release on that string. Numbers of alloc+retain must be equal to numbers of release.
Do not release an autorelease object.</p>

ContentLicense: CC BY-SA 2.5

Title: malloc error -[CFString release]


问:
How to capitalise the first letter of each word after reversing a string
I want to make everything lowercase for when the string is reversed but then capitalise the first letter of each word after. I have reversed the string but after many attempts, the only outcome I can get is to then capitalise the entire reversed string.</p>

```<code>function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
        newArr[i] = firstLetter + restOfWord;
 }
 return newArr.join('');
}
</code>```

答:
Try this -

function reverseString(str) {
  return str.split("").reverse().join("").toLowerCase();
}
document.getElementById('test').append(reverseString("Hello"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#test {
  text-transform: capitalize
}</code>```

```

Body:
I want to make everything lowercase for when the string is reversed but then capitalise the first letter of each word after. I have reversed the string but after many attempts, the only outcome I can get is to then capitalise the entire reversed string.

function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
        newArr[i] = firstLetter + restOfWord;
 }
 return newArr.join('');
}

Body:
Try this -

function reverseString(str) {
  return str.split("").reverse().join("").toLowerCase();
}
document.getElementById('test').append(reverseString("Hello"));

#test {
  text-transform: capitalize
}

<span id='test'></span>


问:
How is the event tied to the button in Angular?
Visual Studio 2017 has an ASP.NET Core with Angular project template. I created it and it had a counter sample. The code was simple.

counter.component.html

```<code><p>Current count: <strong>{{ currentCount }}</strong></p>

<button (click)="incrementCounter()">Increment</button>
</code>```

counter.component.ts

```<code>export class CounterComponent {
    public currentCount = 0;

    public incrementCounter() {
        this.currentCount++;
    }
}
</code>```

In the browser, it looked like,

```<code><p>Current count: <strong>0</strong></p>

<button>Increment</button>
</counter>
        </div>
    </div>
</div>
</app></body></html></app>

<script src="/dist/vendor.js?v=RCvRrqPvM2Kc5BlkEQ045FeXR6gPMRIwfn51ludN14I"></script>

    <script src="/dist/main-client.js?v=cH2S4H872p2E0HNFomc0vsA3ykslPAJyz8CIv7STiuY"></script>

</body>
</code>```

I clicked the script with the cryptic name, but it was very long and difficult to read.

I think I could have created that kind of simple counter by hand using JavaScript, but then, I would have probably set the ID of the display element, called a function in the onClick event of the button, and then when it was clicked, I would have change the innerText of the element. But the generated code has none of that, and still worked. How does the number in  change when the Increment button is clicked?

And can I set a break point when the Increment button is clicked and follow the code step-by-step in Chrome?

答:
There are a few basic Angular/Javascript concepts that you need to understand first.

Angular data binding - https://angular.io/guide/architecture

Yes, you could write Javascript to sync values in your component object with those in your template. But a primary reason for Angular is so that you don't have to do this. The goal is to separate the view from the object model and let Angular take care of this.

Bundling - https://www.sitepoint.com/javascript-modules-bundling-transpiling/

The code in /dist/vendor.js is transpiled and bundled code. It was originally written in Typescript. It was transpiled into Javascript and then all the Javascript files were combined into one.

Debugging and Source maps - https://medium.com/@ttemplier/how-to-debug-the-typescript-source-code-of-angular2-99a593e2983f

Yes if you wanted to, you could put a breakpoint on the increment statement and step all the way through the Angular source. But first you would need to download the un-transpiled Typescript code for Angular and generate the source maps that map the original Typescript to the output Javascript.

Body:
Visual Studio 2017 has an ASP.NET Core with Angular project template. I created it and it had a counter sample. The code was simple.

counter.component.html

Current count: {{ currentCount }}

<button (click)="incrementCounter()">Increment</button>

counter.component.ts

export class CounterComponent {
    public currentCount = 0;

    public incrementCounter() {
        this.currentCount++;
    }
}

In the browser, it looked like,

Current count: 0

<button>Increment</button>
</counter>

</app></app>

I clicked the script with the cryptic name, but it was very long and difficult to read.

I think I could have created that kind of simple counter by hand using JavaScript, but then, I would have probably set the ID of the display element, called a function in the onClick event of the button, and then when it was clicked, I would have change the innerText of the element. But the generated code has none of that, and still worked. How does the number in  change when the Increment button is clicked?

And can I set a break point when the Increment button is clicked and follow the code step-by-step in Chrome?


问:
Permalinks give 404 error in WordPress on AWS EC2 instance running Ubuntu 16.04
I have created an AWS (Ubuntu 16.04) AMI. Installed WordPress and uploaded my Custom theme. Both operations went fine.

I put my site inside /var/www/html.

This is a fresh installation. I created two two pages /login and /forbidden. In Permalinks page I have selected Post Name option.

The site has .htaccess file in place (root) with the following content:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

But whenever I am trying to access http://ec2-54-174-120-1.compute-1.amazonaws.com/login I get 404 error.

Configuration in: /etc/apache2/apache2.conf

```<code><Directory /var/www/html>
   Options Indexes FollowSymLinks
   AllowOverride All
   Require all granted
</Directory>
</code>```

DocumentRoot /var/www/html is set in both /etc/apache2/sites-availabe/000-default.conf and /etc/apache2/sites-enabled/000-default.conf

I restarted Apache server several times with no luck.

sudo service apache2 restart

答:
I think you need to enable Apache mod_rewrite module. You can do it by running the following command:

sudo a2enmod rewrite

ContentLicense: CC BY-SA 4.0

Body:
I have created an AWS (Ubuntu 16.04) AMI. Installed WordPress and uploaded my Custom theme. Both operations went fine.

I put my site inside /var/www/html.

This is a fresh installation. I created two two pages /login and /forbidden. In Permalinks page I have selected Post Name option.

The site has .htaccess file in place (root) with the following content:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

But whenever I am trying to access http://ec2-54-174-120-1.compute-1.amazonaws.com/login I get 404 error.

Configuration in: /etc/apache2/apache2.conf

<Directory /var/www/html>
   Options Indexes FollowSymLinks
   AllowOverride All
   Require all granted
</Directory>

DocumentRoot /var/www/html is set in both /etc/apache2/sites-availabe/000-default.conf and /etc/apache2/sites-enabled/000-default.conf

I restarted Apache server several times with no luck.

sudo service apache2 restart


问:
Is there an open source tool based on perl or python to generate the summary of mindmap of documents
I am really looking for a toolkit or readymade tool which will parse a given document and then generate a brief summary of better still a mindmap of the document. I know Python has ntlk and perl has quite a few  modules which will help in natural language parsing etc.
It is even feasible to write a tool to do so, with using ntlk like tool kit, but for the lack of time. Would appreciate if you know of some such tool or has some pointer to such a tool, if you could post it here, with thanks in advance. </p>

答:
Google people may already be working on such a thing. ;-)

If I get you right, you want a tool that will read a book for you and then briefly summarize for you what it was all about so you can spare the time reading it yourself. Maybe you're not interested in the contents but rather want to categorize the material, as a librarian for example.

That may be technically possible for very structured text with many very similar documents in a very specialized area, say mathematical proofs of theses or experimental results or medical reports. Surely it would be possible to have a tool that can distinguish between a novel and a phone book to roughly sort through literature. Obviously it's very easy to provide page or word counts, identify the written language etc. because these parameters can be clearly defined.

Quite surely though, computers will fail trying to get a grasp of actual stories, anything more conversational or casual. So to decide who's the good guy and who's the bad one, or whether the piece at hand is a love novel featuring detectives or a criminal thriller where a detective is in love with somebody, a machine would have no chance to decide what's what with any feasible amount of memory, CPU power, and knowledge database.

Maybe it would help if you could be more specific regarding the actual purpose for which you want to use this tool.


问:
Providing types explicitly in Go var declaraction fails while implicit works
I am new to go and currently going through the go tool tour.

While on the Short variable declarations section, I modified the sample code to look like this?

```<code>package main

import "fmt"

func main() {
    var i, j int = 1, 2
    k := 3
    var c bool, python string = true, "test"

    fmt.Println(i, j, k, c, python)
}
</code>```

However, then I run the above code, I get the error:

```<code># command-line-arguments
./compile233.go:8:12: syntax error: unexpected comma at end of statement
</code>```

However, if I remove the types from the var declaration like the following:

```<code>package main

import "fmt"

func main() {
    var i, j int = 1, 2
    k := 3
    var c, python = true, "test"

    fmt.Println(i, j, k, c, python)
}
</code>```

It works.

I cannot figure out what is wrong with the first example, and the error seems a bit misleading to me. Could anyone explain what I did wrong and why I'm getting the error?

答:
The variable declaration statement is defined as

```<code>VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
</code>```

which means that if you want to declare multiple variables with type specified explicitly in a single statement they all must have the same type. And that type must come after the identifier list.

So

```<code>var foo, bar bool // is valid
var foo bool, bar bool // is not (only one type qualifier is allowed)
</code>```

Reference:

https://golang.org/ref/spec#Variable_declarations

Body:
I am new to go and currently going through the go tool tour.

While on the Short variable declarations section, I modified the sample code to look like this?

package main

import "fmt"

func main() {
    var i, j int = 1, 2
    k := 3
    var c bool, python string = true, "test"

    fmt.Println(i, j, k, c, python)
}

However, then I run the above code, I get the error:

# command-line-arguments
./compile233.go:8:12: syntax error: unexpected comma at end of statement

However, if I remove the types from the var declaration like the following:

package main

import "fmt"

func main() {
    var i, j int = 1, 2
    k := 3
    var c, python = true, "test"

    fmt.Println(i, j, k, c, python)
}

It works.

I cannot figure out what is wrong with the first example, and the error seems a bit misleading to me. Could anyone explain what I did wrong and why I'm getting the error?

Body:
The variable declaration statement is defined as

VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .

which means that if you want to declare multiple variables with type specified explicitly in a single statement they all must have the same type. And that type must come after the identifier list.

So

var foo, bar bool // is valid
var foo bool, bar bool // is not (only one type qualifier is allowed)

Reference:

https://golang.org/ref/spec#Variable_declarations


问:
Savefig outputs blank image
I am trying to save plots I make using matplotlib; however, the images are saving blank.

Here is my code:

```<code>plt.subplot(121)
plt.imshow(dataStack, cmap=mpl.cm.bone)

plt.subplot(122)
y = copy.deepcopy(tumorStack)
y = np.ma.masked_where(y == 0, y)

plt.imshow(dataStack, cmap=mpl.cm.bone)
plt.imshow(y, cmap=mpl.cm.jet_r, interpolation='nearest')

if T0 is not None:
    plt.subplot(123)
    plt.imshow(T0, cmap=mpl.cm.bone)

    #plt.subplot(124)
    #Autozoom

#else:
    #plt.subplot(124)
    #Autozoom

plt.show()
plt.draw()
plt.savefig('tessstttyyy.png', dpi=100)
</code>```

And tessstttyyy.png is blank (also tried with .jpg)

答:
plt.show() should come after plt.savefig()

Explanation: plt.show() clears the whole thing, so anything afterwards will happen on a new empty figure

Title: Savefig outputs blank image

Body:
I am trying to save plots I make using matplotlib; however, the images are saving blank.

Here is my code:

plt.subplot(121)
plt.imshow(dataStack, cmap=mpl.cm.bone)

plt.subplot(122)
y = copy.deepcopy(tumorStack)
y = np.ma.masked_where(y == 0, y)

plt.imshow(dataStack, cmap=mpl.cm.bone)
plt.imshow(y, cmap=mpl.cm.jet_r, interpolation='nearest')

if T0 is not None:
    plt.subplot(123)
    plt.imshow(T0, cmap=mpl.cm.bone)

    #plt.subplot(124)
    #Autozoom

#else:
    #plt.subplot(124)
    #Autozoom

plt.show()
plt.draw()
plt.savefig('tessstttyyy.png', dpi=100)

And tessstttyyy.png is blank (also tried with .jpg)


问:
Handling a False selection from Dialog Box
I'm trying to handle a false or no file selection from a dialog box. The rest of the code is working very well but when no file selection is made I receive the following error message from VBA:  1004 False.xlsx could not be found. Do you know how to manage the code to prevent that error message to pop up?</p>

```<code>Sub OpeningExcelFile2()
    Dim Finfo As String
    Dim FilterIndex As Integer
    Dim Title As String
    Dim Filename As Variant
    Dim wb As Workbook
    Dim objWdApp As Object
    Dim objWdDoc As Object

    'Setup the list of file filters
    Finfo = "Excel Files (*.xlsx),*xlsx," & _
            "Macro-Enable Worksheet (*.xlsm),*xlsm," & _
            "Word Files (*.docx),*.docx," & _
            "All Files (*.*),*.*"
             MultiSelect = True

    'Display *.* by default
    FilterIndex = 4

    'Set the dialog box caption
    Title = "Select a File to Open"

    'Get the Filename
    Filename = Application.GetOpenFilename(Finfo, _
        FilterIndex, Title)

    'Handle return info from dialog box

    If Filename = False Then
            MsgBox "No file was selected."
    Else
        MsgBox "You selected " & Filename
    End If

    If InStr(1, Filename, ".docx", vbTextCompare) > 0 Then
        Set objWdApp = CreateObject("Word.Application")
        objWdApp.Visible = True
        Set objWdDoc = objWdApp.Documents.Open(Filename) '\\ Open Word Document

    Else
        Set wb = Workbooks.Open(Filename) '\\ Open Excel Spreadsheet

    'how to bring application excel to the front like word in this code?

    End If

End Sub
</code>```

答:
If no file is selected, exit the subroutine:</p>

```<code>If Filename = False Then
    MsgBox "No file was selected."
    Exit Sub
Else
    MsgBox "You selected " & Filename
End If
</code>```

Body:
I'm trying to handle a false or no file selection from a dialog box. The rest of the code is working very well but when no file selection is made I receive the following error message from VBA:  1004 False.xlsx could not be found. Do you know how to manage the code to prevent that error message to pop up?

Sub OpeningExcelFile2()
    Dim Finfo As String
    Dim FilterIndex As Integer
    Dim Title As String
    Dim Filename As Variant
    Dim wb As Workbook
    Dim objWdApp As Object
    Dim objWdDoc As Object

    'Setup the list of file filters
    Finfo = "Excel Files (*.xlsx),*xlsx," & _
            "Macro-Enable Worksheet (*.xlsm),*xlsm," & _
            "Word Files (*.docx),*.docx," & _
            "All Files (*.*),*.*"
             MultiSelect = True

    'Display *.* by default
    FilterIndex = 4

    'Set the dialog box caption
    Title = "Select a File to Open"

    'Get the Filename
    Filename = Application.GetOpenFilename(Finfo, _
        FilterIndex, Title)

    'Handle return info from dialog box

    If Filename = False Then
            MsgBox "No file was selected."
    Else
        MsgBox "You selected " & Filename
    End If

    If InStr(1, Filename, ".docx", vbTextCompare) > 0 Then
        Set objWdApp = CreateObject("Word.Application")
        objWdApp.Visible = True
        Set objWdDoc = objWdApp.Documents.Open(Filename) '\\ Open Word Document

    Else
        Set wb = Workbooks.Open(Filename) '\\ Open Excel Spreadsheet

    'how to bring application excel to the front like word in this code?

    End If

End Sub

Body:
If no file is selected, exit the subroutine:

If Filename = False Then
    MsgBox "No file was selected."
    Exit Sub
Else
    MsgBox "You selected " & Filename
End If


问:
Python indentation not intuitive
I am trying to follow proper protocol for Python indentation, but still python throws an error. I am sure python has good reason and my code is just bad, but I fail to see the root cause.

When run the error is pointed to the last line

```<code>~/python $ ./hover_api_v1.0.py
  File "./hover_api_v1.0.py", line 139
    time.sleep(60.0)
    ^
IndentationError: expected an indented block
</code>```

Below is my code. There are some headers not relevant for indentation.

The error is thrown at the last line with the time command. But I fail to see my mistake in the code. The time cmd is part of the top while loop and properly indented.

```<code>while True:
    ip_now = get_asus_wan_ip()
    if (ip_now == ip_last):
        day = datetime.datetime.now().day
        if day != last_day:
            last_day = day
            with open(logfile, "a") as lf:
                lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " WAN IP still the same " + str(ip_last) +"\n")

    else:
        # We need to do something
        #print('WAN IP changed from ' + str(ip_last) + " to " + str(ip_now))
        with open(logfile, "a") as lf:
            lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " WAN IP changed from " + str(ip_last) + " to " + str(ip_now) + "\n")
        ip_last= ip_now

        # connect to API
        client = HoverAPI('XXXXXXX','YYYYYYY')
        for dnsname in ['*.zzzzz.zzz', '@.zzzzz.zzz']:
            #print('Testing: ' + dnsname)
            dns_name, domain_name = dnsname.split('.', 1)

            # get all DNS records
            result = client.call("get", "dns")
            assert result['succeeded'], result

            # discover existing dns record, if any
            dns_record = None
            domain_record = None
            for dns_domain in result['domains']:
                if dns_domain['domain_name'] == domain_name:
                    domain_record = dns_domain
                    for dns_entry in dns_domain['entries']:
                        if dns_entry['name'] == dns_name:
                            dns_record = dns_entry
                            break
                if dns_record is not None and domain_record is not None:
                    break

            if dns_record is not None and domain_record is not None:
                #print('Hover-IP for ' + dnsname + ' = ' + str(dns_entry['content'].encode('ascii','ignore')))
                #print('Current IP= ' + str(ip_now))
                if str(dns_entry['content']) == str(ip_now):
                    #print('Hover-IP for ' + dnsname + ' = ' + str(dns_entry['content'].encode('ascii','ignore')) + ' same as Current IP = ' + str(ip_now) + '. No action.')
                    with open(logfile, "a") as lf:
                        lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Hover-IP for " + dnsname + " = " + str(dns_entry['content'].encode('ascii','ignore')) + " same as Current IP = " + str(ip_now) + ". No action." + "\n")
                else:
                    #print(" Deleting entry for {0}.{1} ... ".format(dns_name, domain_name), end="")
                    with open(logfile, "a") as lf:
                        lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Deleting entry for " + dnsname + "\n")
                    result = client.call("delete", "dns/{0}".format(dns_record['id']))
                    assert result['succeeded'], result
                    #print("OK")
                    ## create a new A record:
                    #print("Creating A record {0}.{1} => {2} ... ".format(dns_name, domain_name, ip_now), end="")
                    with open(logfile, "a") as lf:
                        lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Creating A record " + dnsname + " => " + ip_now + "\n")
                    record = {"name": dns_name, "type": "A", "content": ip_now}
                    post_id = "domains/{0}/dns".format(domain_record['id'])
                    #print("post", post_id, record)
                    result = client.call("post", post_id, record)
                    assert result['succeeded'], result
                    #print("OK")
            else:
                #print("No record exists for {0}".format(dnsname))

    # Sleep at end of loop.
    time.sleep(60.0)
</code>```

Feedback is much appreciated.
Gert

答:
The problem is here;

```<code>else:
    #print("No record exists for {0}".format(dnsname))
</code>```

Comments do not count as code as far as indention is considered.
So you need to have real code in that spot.

A way around this is python's pass keyword.

```<code>else:
    #print("No record exists for {0}".format(dnsname))
    pass
</code>```

This signals to python that you have intentionally left the code required at that indentation level empty.

Alternatively, simply uncommenting the code you have there would also solve this problem, assuming of course you actually want to print there.

Title: Python indentation not intuitive

Body:
I am trying to follow proper protocol for Python indentation, but still python throws an error. I am sure python has good reason and my code is just bad, but I fail to see the root cause.

When run the error is pointed to the last line

~/python $ ./hover_api_v1.0.py
  File "./hover_api_v1.0.py", line 139
    time.sleep(60.0)
    ^
IndentationError: expected an indented block

Below is my code. There are some headers not relevant for indentation.

The error is thrown at the last line with the time command. But I fail to see my mistake in the code. The time cmd is part of the top while loop and properly indented.

while True:
    ip_now = get_asus_wan_ip()
    if (ip_now == ip_last):
        day = datetime.datetime.now().day
        if day != last_day:
            last_day = day
            with open(logfile, "a") as lf:
                lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " WAN IP still the same " + str(ip_last) +"\n")

    else:
        # We need to do something
        #print('WAN IP changed from ' + str(ip_last) + " to " + str(ip_now))
        with open(logfile, "a") as lf:
            lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " WAN IP changed from " + str(ip_last) + " to " + str(ip_now) + "\n")
        ip_last= ip_now

        # connect to API
        client = HoverAPI('XXXXXXX','YYYYYYY')
        for dnsname in ['*.zzzzz.zzz', '@.zzzzz.zzz']:
            #print('Testing: ' + dnsname)
            dns_name, domain_name = dnsname.split('.', 1)

            # get all DNS records
            result = client.call("get", "dns")
            assert result['succeeded'], result

            # discover existing dns record, if any
            dns_record = None
            domain_record = None
            for dns_domain in result['domains']:
                if dns_domain['domain_name'] == domain_name:
                    domain_record = dns_domain
                    for dns_entry in dns_domain['entries']:
                        if dns_entry['name'] == dns_name:
                            dns_record = dns_entry
                            break
                if dns_record is not None and domain_record is not None:
                    break

            if dns_record is not None and domain_record is not None:
                #print('Hover-IP for ' + dnsname + ' = ' + str(dns_entry['content'].encode('ascii','ignore')))
                #print('Current IP= ' + str(ip_now))
                if str(dns_entry['content']) == str(ip_now):
                    #print('Hover-IP for ' + dnsname + ' = ' + str(dns_entry['content'].encode('ascii','ignore')) + ' same as Current IP = ' + str(ip_now) + '. No action.')
                    with open(logfile, "a") as lf:
                        lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Hover-IP for " + dnsname + " = " + str(dns_entry['content'].encode('ascii','ignore')) + " same as Current IP = " + str(ip_now) + ". No action." + "\n")
                else:
                    #print(" Deleting entry for {0}.{1} ... ".format(dns_name, domain_name), end="")
                    with open(logfile, "a") as lf:
                        lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Deleting entry for " + dnsname + "\n")
                    result = client.call("delete", "dns/{0}".format(dns_record['id']))
                    assert result['succeeded'], result
                    #print("OK")
                    ## create a new A record:
                    #print("Creating A record {0}.{1} => {2} ... ".format(dns_name, domain_name, ip_now), end="")
                    with open(logfile, "a") as lf:
                        lf.write(time.strftime("%Y-%m-%d %H:%M:%S") + " Creating A record " + dnsname + " => " + ip_now + "\n")
                    record = {"name": dns_name, "type": "A", "content": ip_now}
                    post_id = "domains/{0}/dns".format(domain_record['id'])
                    #print("post", post_id, record)
                    result = client.call("post", post_id, record)
                    assert result['succeeded'], result
                    #print("OK")
            else:
                #print("No record exists for {0}".format(dnsname))

    # Sleep at end of loop.
    time.sleep(60.0)

Feedback is much appreciated.
Gert

Body:
The problem is here;

else:
    #print("No record exists for {0}".format(dnsname))

Comments do not count as code as far as indention is considered.
So you need to have real code in that spot.

A way around this is python's pass keyword.

else:
    #print("No record exists for {0}".format(dnsname))
    pass

This signals to python that you have intentionally left the code required at that indentation level empty.

Alternatively, simply uncommenting the code you have there would also solve this problem, assuming of course you actually want to print there.


问:
What is the sequence of calls of copy constructor in a multi-level inheritance?
I have been trying to figure this out rigorously. Given three classes inheriting from each other, how does the sequence work?
For eg: Classes Vehicle->Car->Mercedes</p>

答:
Easy enough to create MCVE ...

```<code>#include <chrono>
// 'compressed' chrono access --------------vvvvvvv
typedef std::chrono::high_resolution_clock  HRClk_t; // std-chrono-hi-res-clk
typedef HRClk_t::time_point                 Time_t;  // std-chrono-hi-res-clk-time-point
typedef std::chrono::milliseconds           MS_t;    // std-chrono-milliseconds
typedef std::chrono::microseconds           US_t;    // std-chrono-microseconds
typedef std::chrono::nanoseconds            NS_t;    // std-chrono-nanoseconds
using   namespace std::chrono_literals;          // support suffixes like 100ms, 2s, 30us

#include <iostream>
#include <iomanip>

class Vehicle_t
{
public:
   Vehicle_t () { std::cout << "\n  Vehicle_t" << std::flush;   }
   ~Vehicle_t () = default;
};

class Car_t
   : public Vehicle_t
{
public:
   Car_t () { std::cout << "\n  Car_t" << std::flush;   }
   ~Car_t () = default;
};

class Mercedes_t
   : public Car_t
{
public:
   Mercedes_t () { std::cout << "\n  Mercedes_t" << std::flush;   }
   ~Mercedes_t () = default;
};

int main(int , char** )
{
   int retVal = -1;
   {
      Time_t start_us = HRClk_t::now();

      Mercedes_t  m;

      retVal = 0;

      auto  duration_us = std::chrono::duration_cast<US_t>(HRClk_t::now() - start_us);

      std::cout << "\n\n  duration  " << duration_us.count() << " us" << std::endl;
   }

   return(retVal);
}
</code>```

With output

```<code>Vehicle_t
Car_t
Mercedes_t
</code>```

Notes for the beginner:

I'm sure you have heard it before, "execution begins at 'main'".  This code does too.

Thus the statement, "Mercedes_t  m;" is 1st (for this class hierarchy).  It shows the invocation of the "Mercedes_t" ctor (the most derived) is invoked first.

Remember, all methods (and functions) have both an entry and an exit.

The most derived ctor invokes "Car_t" ctor, which invokes "Vehicle_t" ctor.

The output shows that "Vehicle_t" ctor cout statement finishes first.  And thus you may infer that this ctor finishes first.

The output shows that the next ctor to finish is "Car_t", and then "Mercedes_t"

Summary

the most base class is invoked last, but finishes first.

the most derived class is invoked first, but finishes last.

```<code>ctor Entry/Invocation sequence:   Mercedes_t -> Car_t -> Vehicle_t
ctor Exit/ctor completion seq :   Vehicle_t  -- Car_t -- Mercedes_t
</code>```

update - 11/19/2017

I think most of my answer is about implementation details.  It occurred to me that such 'proof' as I provided above is insufficient.  (and contradicts one or more alternate answers).

The more convincing 'proof' is to inspect the assembly.  The following is from code some what different than my MCVE above, but still has recognizable names.  FYI - My system is Ubuntu 15.10, and g++ reports (Ubuntu 5.2.1-23ubuntu1~15.10) 5.2.1.

Using gdb, I set break point at main (i.e. b main), issued run, then used the command

(gdb) disassemble /m

and found

```<code>154      {
155         Mercedes_t  m; // invoke Mercedes_t ctor
   0x00000000004019e2 <+40>:  lea    -0x30(%rbp),%rax
   0x00000000004019e6 <+44>:  mov    %rax,%rdi
   0x00000000004019e9 <+47>:  callq  0x40214a <Mercedes_t::Mercedes_t()>
   0x00000000004019ee <+52>:  lea    -0x30(%rbp),%rax
</code>```

This confirms that the first call to create the object is the
< Mercedes_t::Mercedes_t() > ctor, i.e. the most derived ctor is called first.

Next, from the same type of disassembly of the Mercedes_t ctor, you can see the call to < Car_t::Car_t() >.

```<code>Dump of assembler code for function Mercedes_t::Mercedes_t():
91     Mercedes_t () : initLineNum (log(__LINE__)) // Mercedes_t ctor init
   0x000000000040214a <+0>: push   %rbp
   0x000000000040214b <+1>: mov    %rsp,%rbp
   0x000000000040214e <+4>: sub    $0x10,%rsp
   0x0000000000402152 <+8>: mov    %rdi,-0x8(%rbp)
=> 0x0000000000402156 <+12>:    mov    -0x8(%rbp),%rax
   0x000000000040215a <+16>:    mov    %rax,%rdi
   0x000000000040215d <+19>:    callq  0x4020ec <Car_t::Car_t()>
   0x0000000000402162 <+24>:    mov    $0x5b,%edi
   0x0000000000402167 <+29>:    callq  0x401616 <log(int)>
   0x000000000040216c <+34>:    mov    %eax,%edx
   0x000000000040216e <+36>:    mov    -0x8(%rbp),%rax
   0x0000000000402172 <+40>:    mov    %edx,0x8(%rax)
</code>```

Enough for me.  I strongly recommend you learn gdb.

But again, I think these might be implementation details.

update - 11/20/2017
Added code to identify copy ctor sequence.

I added the copy ctor to each class (after default ctor, before dtor):

```<code>Vehicle_t(const Vehicle_t& /*rhs*/){
   std::cout << "\n  Vehicle_t(rhs) " << std::flush; }//Vehicle_t copy ctor (3)

Car_t(const Car_t& rhs) : Vehicle_t(rhs) {
   std::cout << "\n  Car_t(rhs) " << std::flush; }  // Car_t copy ctor (3)

Mercedes_t(const Mercedes_t& rhs) : Car_t(rhs) {
   std::cout << "\n  Mercedes_t(rhs) " << std::flush; }  // Mercedes_t copy ctor (3)
</code>```

Added 2 lines to main, after default ctor, and before "retVal = 0;"

```<code>  Mercedes_t  m;    // invoke default ctor

  std::cout << "\n";

  Mercedes_t m2(m); // invoke copy ctor

  retVal = 0;
</code>```

The output now looks like:

```<code>  Vehicle_t
  Car_t
  Mercedes_t

  Vehicle_t(rhs)
  Car_t(rhs)
  Mercedes_t(rhs)
</code>```

This is the same sequence as default ctors.

I also used gdb and the "disassemble /m" command and inspected the assy.   The invocation sequence matches the default ctor.

Body:
Easy enough to create MCVE ...

#include <chrono>
// 'compressed' chrono access --------------vvvvvvv
typedef std::chrono::high_resolution_clock  HRClk_t; // std-chrono-hi-res-clk
typedef HRClk_t::time_point                 Time_t;  // std-chrono-hi-res-clk-time-point
typedef std::chrono::milliseconds           MS_t;    // std-chrono-milliseconds
typedef std::chrono::microseconds           US_t;    // std-chrono-microseconds
typedef std::chrono::nanoseconds            NS_t;    // std-chrono-nanoseconds
using   namespace std::chrono_literals;          // support suffixes like 100ms, 2s, 30us

#include <iostream>
#include <iomanip>

class Vehicle_t
{
public:
   Vehicle_t () { std::cout << "\n  Vehicle_t" << std::flush;   }
   ~Vehicle_t () = default;
};

class Car_t
   : public Vehicle_t
{
public:
   Car_t () { std::cout << "\n  Car_t" << std::flush;   }
   ~Car_t () = default;
};

class Mercedes_t
   : public Car_t
{
public:
   Mercedes_t () { std::cout << "\n  Mercedes_t" << std::flush;   }
   ~Mercedes_t () = default;
};

int main(int , char** )
{
   int retVal = -1;
   {
      Time_t start_us = HRClk_t::now();

      Mercedes_t  m;

      retVal = 0;

      auto  duration_us = std::chrono::duration_cast<US_t>(HRClk_t::now() - start_us);

      std::cout << "\n\n  duration  " << duration_us.count() << " us" << std::endl;
   }

   return(retVal);
}

With output

Vehicle_t
Car_t
Mercedes_t

Notes for the beginner:

I'm sure you have heard it before, "execution begins at 'main'".  This code does too.

Thus the statement, "Mercedes_t  m;" is 1st (for this class hierarchy).  It shows the invocation of the "Mercedes_t" ctor (the most derived) is invoked first.

Remember, all methods (and functions) have both an entry and an exit.

The most derived ctor invokes "Car_t" ctor, which invokes "Vehicle_t" ctor.

The output shows that "Vehicle_t" ctor cout statement finishes first.  And thus you may infer that this ctor finishes first.

The output shows that the next ctor to finish is "Car_t", and then "Mercedes_t"

Summary

the most base class is invoked last, but finishes first.

the most derived class is invoked first, but finishes last.

ctor Entry/Invocation sequence:   Mercedes_t -> Car_t -> Vehicle_t
ctor Exit/ctor completion seq :   Vehicle_t  -- Car_t -- Mercedes_t

update - 11/19/2017

I think most of my answer is about implementation details.  It occurred to me that such 'proof' as I provided above is insufficient.  (and contradicts one or more alternate answers).

The more convincing 'proof' is to inspect the assembly.  The following is from code some what different than my MCVE above, but still has recognizable names.  FYI - My system is Ubuntu 15.10, and g++ reports (Ubuntu 5.2.1-23ubuntu1~15.10) 5.2.1.

Using gdb, I set break point at main (i.e. b main), issued run, then used the command

(gdb) disassemble /m

and found

154      {
155         Mercedes_t  m; // invoke Mercedes_t ctor
   0x00000000004019e2 <+40>:  lea    -0x30(%rbp),%rax
   0x00000000004019e6 <+44>:  mov    %rax,%rdi
   0x00000000004019e9 <+47>:  callq  0x40214a <Mercedes_t::Mercedes_t()>
   0x00000000004019ee <+52>:  lea    -0x30(%rbp),%rax

This confirms that the first call to create the object is the
< Mercedes_t::Mercedes_t() > ctor, i.e. the most derived ctor is called first.

Next, from the same type of disassembly of the Mercedes_t ctor, you can see the call to < Car_t::Car_t() >.

Dump of assembler code for function Mercedes_t::Mercedes_t():
91     Mercedes_t () : initLineNum (log(__LINE__)) // Mercedes_t ctor init
   0x000000000040214a <+0>: push   %rbp
   0x000000000040214b <+1>: mov    %rsp,%rbp
   0x000000000040214e <+4>: sub    $0x10,%rsp
   0x0000000000402152 <+8>: mov    %rdi,-0x8(%rbp)
=> 0x0000000000402156 <+12>:    mov    -0x8(%rbp),%rax
   0x000000000040215a <+16>:    mov    %rax,%rdi
   0x000000000040215d <+19>:    callq  0x4020ec <Car_t::Car_t()>
   0x0000000000402162 <+24>:    mov    $0x5b,%edi
   0x0000000000402167 <+29>:    callq  0x401616 <log(int)>
   0x000000000040216c <+34>:    mov    %eax,%edx
   0x000000000040216e <+36>:    mov    -0x8(%rbp),%rax
   0x0000000000402172 <+40>:    mov    %edx,0x8(%rax)

Enough for me.  I strongly recommend you learn gdb.

But again, I think these might be implementation details.

update - 11/20/2017
Added code to identify copy ctor sequence.

I added the copy ctor to each class (after default ctor, before dtor):

Vehicle_t(const Vehicle_t& /*rhs*/){
   std::cout << "\n  Vehicle_t(rhs) " << std::flush; }//Vehicle_t copy ctor (3)

Car_t(const Car_t& rhs) : Vehicle_t(rhs) {
   std::cout << "\n  Car_t(rhs) " << std::flush; }  // Car_t copy ctor (3)

Mercedes_t(const Mercedes_t& rhs) : Car_t(rhs) {
   std::cout << "\n  Mercedes_t(rhs) " << std::flush; }  // Mercedes_t copy ctor (3)

Added 2 lines to main, after default ctor, and before "retVal = 0;"

  Mercedes_t  m;    // invoke default ctor

  std::cout << "\n";

  Mercedes_t m2(m); // invoke copy ctor

  retVal = 0;

The output now looks like:

  Vehicle_t
  Car_t
  Mercedes_t

  Vehicle_t(rhs)
  Car_t(rhs)
  Mercedes_t(rhs)

This is the same sequence as default ctors.

I also used gdb and the "disassemble /m" command and inspected the assy.   The invocation sequence matches the default ctor.


问:
PHP curl post to login to wordpress
I am using php curl to login to wordpress behind-the-scenes as described here:
Wordpress autologin using CURL or fsockopen in PHP

However my script is not setting the cookies necessary to retain the wordpress session.  Instead they are being sent back to my script and stored in cookies.txt.

Both the curl script and the wordpress login are on the same server in different directories.

Do I need to write another curl script to manually set the wordpress cookies?  Is that possible?

答:
I needed the cookies to be sent to the browser not back to my curl script.  The curl script was triggered by a php script running in the browser.

I solved the problem as follows:

Added these params to the curl object:

curl_setopt($ch, CURLOPT_HEADER ,1);
  curl_setopt ($ch, CURLOPT_HEADERFUNCTION, 'read_header');

Added a php functions called read_header which parsed out the cookie data

Used setcookie() to manually set the cookies

If anyone wants the details please comment.

Title: PHP curl post to login to wordpress


问:
Tensorflow: where is the documentation of 'tensorflow.python.training'?
I had seen code "from tensorflow.python.training import moving_averages" many times when i read open source code. But i don't know what 'moving_averages' really do, and i want to read docs about it. I didn't found the links about docs, i need some help.

Thanks for your help.

答:
you can find it here tensorflow moving average (v0.12)

edit:

As you can see from the official Tesnorflow (v1.4) documentation and the code

Class ExponentialMovingAverage

Defined in tensorflow/python/training/moving_averages.py


答: The final else block needs a valid statement.  Use pass.

Title: Python indentation not intuitive


答:
After reversing the string, you need to join it back and split on spaces, so that inside your for loop you are only capitalising the first letter of each word.

function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
reversed = reversed.join('').split(' ');
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
        newArr[i] = firstLetter + restOfWord;
 }
 return newArr.join(' ');
}

console.log(titleCase('hello HELLO'));```

Title: How to capitalise the first letter of each word after reversing a string


问:
d3 get quantile on array of object
I am trying to get the first quartile, the median and last quartile of an array of object base on their value.

```<code>0: Object { key: "Aeronautical, Mechanical, Chemical and Manufacturing Engineering", value: 0.6100000000000001 }
1: Object { key: "Agriculture, Veterinary and Food Science", value: 1.3400000000000003 }
2: Object { key: "Allied Health Professions, Dentistry, Nursing and Pharmacy", value: 2.2699999999999996 }
3: Object { key: "Anthropology and Development Studies", value: 1.1400000000000003 }
4: Object { key: "Architecture, Built Environment and Planning", value: 4.21 }
5: Object { key: "Area Studies", value: 0.9800000000000001 }
6: Object { key: "Art and Design: History, Practice and Theory", value: 6.659999999999997 }
7: Object { key: "Biological Sciences", value: 1.3500000000000003 }
8: Object { key: "Business and Management Studies", value: 8.409999999999993 }
9: Object { key: "Chemistry", value: 0.15000000000000002 }
</code>```

I would like to return an array of object with 3 object.
My final goal is to draw a pie chart with it.

so far i tried this method

```<code>        var rank = dmObj.getRank();
        console.log("test",rank);
        // using nest function from d3 to "classify" data into years
        // then rollup to change array of values into sum of money
        var nestedData = d3.nest()
            .key(function(d){ return d.naAsses;})
            .rollup(function (v) { return {
                first: d3.quantile(v.map(function(d){return rank.value ;}),.25),
                median: d3.median(v,function(d){return rank.value}),
                last: d3.quantile(v.map(function(d){return rank.value;}),.75)
            };

            })
            .sortKeys(d3.ascending)
            .entries(filteredData());

        console.log("quartil :data",nestedData);

        return nestedData;
    }
</code>```

rank is the dataset linked above.

答:
Instead of using d3.nest() you can simply use those methods in the array directly:

var data = [{
  key: "Aeronautical, Mechanical, Chemical and Manufacturing Engineering",
  value: 0.6100000000000001
}, {
  key: "Agriculture, Veterinary and Food Science",
  value: 1.3400000000000003
}, {
  key: "Allied Health Professions, Dentistry, Nursing and Pharmacy",
  value: 2.2699999999999996
}, {
  key: "Anthropology and Development Studies",
  value: 1.1400000000000003
}, {
  key: "Architecture, Built Environment and Planning",
  value: 4.21
}, {
  key: "Area Studies",
  value: 0.9800000000000001
}, {
  key: "Art and Design: History, Practice and Theory",
  value: 6.659999999999997
}, {
  key: "Biological Sciences",
  value: 1.3500000000000003
}, {
  key: "Business and Management Studies",
  value: 8.409999999999993
}, {
  key: "Chemistry",
  value: 0.15000000000000002
}];

data.sort(function(a, b) {
  return d3.ascending(a.value, b.value)
});

var firstQuartile = d3.quantile(data.map(function(d) {
  return d.value
}), 0.25);
var median = d3.median(data.map(function(d) {
  return d.value
}));
var lastQuartile = d3.quantile(data.map(function(d) {
  return d.value
}), 0.75);

console.log("First quartile: " + firstQuartile)
console.log("Median: " + median)
console.log("Last quartile: " + lastQuartile)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

EDIT: according to your comment, you can create a new property based on the quartiles:

var data = [{
  key: "Aeronautical, Mechanical, Chemical and Manufacturing Engineering",
  value: 0.6100000000000001
}, {
  key: "Agriculture, Veterinary and Food Science",
  value: 1.3400000000000003
}, {
  key: "Allied Health Professions, Dentistry, Nursing and Pharmacy",
  value: 2.2699999999999996
}, {
  key: "Anthropology and Development Studies",
  value: 1.1400000000000003
}, {
  key: "Architecture, Built Environment and Planning",
  value: 4.21
}, {
  key: "Area Studies",
  value: 0.9800000000000001
}, {
  key: "Art and Design: History, Practice and Theory",
  value: 6.659999999999997
}, {
  key: "Biological Sciences",
  value: 1.3500000000000003
}, {
  key: "Business and Management Studies",
  value: 8.409999999999993
}, {
  key: "Chemistry",
  value: 0.15000000000000002
}];

data.sort(function(a, b) {
  return d3.ascending(a.value, b.value)
})

data.forEach(function(d, i, arr) {
  d.quartile = d.value < d3.quantile(arr.map(function(d) {
    return d.value
  }), 0.25) ? "belowFirst" : d.value > d3.quantile(arr.map(function(d) {
    return d.value
  }), 0.75) ? "aboveThird" : "betweenFirstandThird"
});

console.log(data)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

Title: d3 get quantile on array of object

Body:
I am trying to get the first quartile, the median and last quartile of an array of object base on their value.

0: Object { key: "Aeronautical, Mechanical, Chemical and Manufacturing Engineering", value: 0.6100000000000001 }
1: Object { key: "Agriculture, Veterinary and Food Science", value: 1.3400000000000003 }
2: Object { key: "Allied Health Professions, Dentistry, Nursing and Pharmacy", value: 2.2699999999999996 }
3: Object { key: "Anthropology and Development Studies", value: 1.1400000000000003 }
4: Object { key: "Architecture, Built Environment and Planning", value: 4.21 }
5: Object { key: "Area Studies", value: 0.9800000000000001 }
6: Object { key: "Art and Design: History, Practice and Theory", value: 6.659999999999997 }
7: Object { key: "Biological Sciences", value: 1.3500000000000003 }
8: Object { key: "Business and Management Studies", value: 8.409999999999993 }
9: Object { key: "Chemistry", value: 0.15000000000000002 }

I would like to return an array of object with 3 object.
My final goal is to draw a pie chart with it.

so far i tried this method

        var rank = dmObj.getRank();
        console.log("test",rank);
        // using nest function from d3 to "classify" data into years
        // then rollup to change array of values into sum of money
        var nestedData = d3.nest()
            .key(function(d){ return d.naAsses;})
            .rollup(function (v) { return {
                first: d3.quantile(v.map(function(d){return rank.value ;}),.25),
                median: d3.median(v,function(d){return rank.value}),
                last: d3.quantile(v.map(function(d){return rank.value;}),.75)
            };

            })
            .sortKeys(d3.ascending)
            .entries(filteredData());

        console.log("quartil :data",nestedData);

        return nestedData;
    }

rank is the dataset linked above.

Body:
Instead of using d3.nest() you can simply use those methods in the array directly:

var data = [{
  key: "Aeronautical, Mechanical, Chemical and Manufacturing Engineering",
  value: 0.6100000000000001
}, {
  key: "Agriculture, Veterinary and Food Science",
  value: 1.3400000000000003
}, {
  key: "Allied Health Professions, Dentistry, Nursing and Pharmacy",
  value: 2.2699999999999996
}, {
  key: "Anthropology and Development Studies",
  value: 1.1400000000000003
}, {
  key: "Architecture, Built Environment and Planning",
  value: 4.21
}, {
  key: "Area Studies",
  value: 0.9800000000000001
}, {
  key: "Art and Design: History, Practice and Theory",
  value: 6.659999999999997
}, {
  key: "Biological Sciences",
  value: 1.3500000000000003
}, {
  key: "Business and Management Studies",
  value: 8.409999999999993
}, {
  key: "Chemistry",
  value: 0.15000000000000002
}];

data.sort(function(a, b) {
  return d3.ascending(a.value, b.value)
});

var firstQuartile = d3.quantile(data.map(function(d) {
  return d.value
}), 0.25);
var median = d3.median(data.map(function(d) {
  return d.value
}));
var lastQuartile = d3.quantile(data.map(function(d) {
  return d.value
}), 0.75);

console.log("First quartile: " + firstQuartile)
console.log("Median: " + median)
console.log("Last quartile: " + lastQuartile)

<script src="https://d3js.org/d3.v4.min.js"></script>

EDIT: according to your comment, you can create a new property based on the quartiles:

var data = [{
  key: "Aeronautical, Mechanical, Chemical and Manufacturing Engineering",
  value: 0.6100000000000001
}, {
  key: "Agriculture, Veterinary and Food Science",
  value: 1.3400000000000003
}, {
  key: "Allied Health Professions, Dentistry, Nursing and Pharmacy",
  value: 2.2699999999999996
}, {
  key: "Anthropology and Development Studies",
  value: 1.1400000000000003
}, {
  key: "Architecture, Built Environment and Planning",
  value: 4.21
}, {
  key: "Area Studies",
  value: 0.9800000000000001
}, {
  key: "Art and Design: History, Practice and Theory",
  value: 6.659999999999997
}, {
  key: "Biological Sciences",
  value: 1.3500000000000003
}, {
  key: "Business and Management Studies",
  value: 8.409999999999993
}, {
  key: "Chemistry",
  value: 0.15000000000000002
}];

data.sort(function(a, b) {
  return d3.ascending(a.value, b.value)
})

data.forEach(function(d, i, arr) {
  d.quartile = d.value < d3.quantile(arr.map(function(d) {
    return d.value
  }), 0.25) ? "belowFirst" : d.value > d3.quantile(arr.map(function(d) {
    return d.value
  }), 0.75) ? "aboveThird" : "betweenFirstandThird"
});

console.log(data)

<script src="https://d3js.org/d3.v4.min.js"></script>


答:
Python is looking for a statement after the else clause above your time.sleep(60.0) statement (above your commented "No record exists" print() call); when Python does not see a line with the proper indentation to be categorized under the else clause, it will throw an error.

What I tend to do (which may not be the best way) to bypass this issue is to refer to None or use pass and optionally add a comment to circumvent this issue. Your code near the else clause would look something similar to this:

```<code># ...
        else:
            # TODO
            # print("No record exists for {0}".format(dnsname))
            pass

    # Sleep at end of loop.
    time.sleep(60.0)
</code>```

Hope this helped!

Title: Python indentation not intuitive

Body:
Python is looking for a statement after the else clause above your time.sleep(60.0) statement (above your commented "No record exists" print() call); when Python does not see a line with the proper indentation to be categorized under the else clause, it will throw an error.

What I tend to do (which may not be the best way) to bypass this issue is to refer to None or use pass and optionally add a comment to circumvent this issue. Your code near the else clause would look something similar to this:

# ...
        else:
            # TODO
            # print("No record exists for {0}".format(dnsname))
            pass

    # Sleep at end of loop.
    time.sleep(60.0)

Hope this helped!


问:
How to publish a message to rabbitmq using Mocha framework
Hi i'm unable to figure out how to connect to rabbitmq using Mocha & chai framework.
I've installed rabbitmq & erlang on my local & trying to connect to rabbitmq by starting the server on local.

The code i'm using is as below:

```<code>    var chai = require('chai');
    var chaiHttp = require('chai-http');
    var request = chai.request;
    var should = chai.should();
    var expect = chai.expect;
    var assert = chai.assert;
    var supertest = require('supertest');
    var fs = require('fs');
    var amqp = require('amqplib/callback_api');

    //Plugin for HTTP, etc.
    chai.use(chaiHttp);
    process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';

    describe("Testing RabbitMQ : ", function () {

        it("Send a message : ", function (done) {
            amqp.connect('amqp://localhost:15672/', function (err, conn) {
                conn.createChannel(function (err, ch) {
                    var q = 'hello';
                    ch.assertQueue(q, { durable: false });
                    // Note: on Node 6 Buffer.from(msg) should be used
                    ch.sendToQueue(q, new Buffer('Hello World!'));
                    console.log(" [x] Sent 'Hello World!'");
                });
                setTimeout(function () { conn.close(); process.exit(0) }, 500);
            });
            done();
        });

        it("Receive a message", function (done) {
            amqp.connect('amqp://localhost:15672/', function (err, conn) {
                conn.createChannel(function (err, ch) {
                    var q = 'hello';

                    ch.assertQueue(q, { durable: false });
                    console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q);
                    ch.consume(q, function (msg) {
                        console.log(" [x] Received %s", msg.content.toString());
                    }, { noAck: true });
                });
            });
            done();
        });
    })
</code>```

So is there any other way to connect to rabbitmq & publish a message?
I've tried with amqp library, any sample code for connecting to rabbitmq will be helpful.

Can anyone make me understand how to connect to a specific queue to send a message, where the message can be published.

Any help would be really appreciated. Thank you.

答:
You are specifying the wrong port. The default amqp port is 5672. If you are not changing the default port then you don't need to specify the port in amqp server url. That is instead of amqp://localhost:15672/, you can simply specify the url as amqp://localhost. I would like to give a working program for How to publish a message to rabbitmq using Mocha framework?.

I run the RabbitMQ server in my system using docker

```<code>docker run -d --hostname rabbit1 --name rabbit1 -e RABBITMQ_ERLANG_COOKIE=rabbitcluster -p 30000:5672 -p 30001:15672 rabbitmq:management
</code>```

Then

```<code>// test.js

var chai = require('chai')
var amqp = require('amqplib/callback_api');
var chaiHttp = require('chai-http')
var should = chai.should()
chai.use(chaiHttp);
var config={
  protocol: 'amqp',
  hostname: 'localhost',
  port: 30000,
  username: 'guest',
  password: 'guest',
}
var q="ex.queue";
var msg =  "Hello World!";

describe('Testing RabbitMQ',function(){
  it('Sending Message to RabbitMQ Server',function(done){
    amqp.connect(config, function(err, conn) {
      if(err){
        console.log("connection error");
        return;
      }
      conn.createConfirmChannel(function(err, ch) {
        if(err){
           return;
        }
          ch.assertQueue(q, {durable: true});
    ch.sendToQueue(q, new Buffer(msg), {persistent: true},
        function(err){
          if(err){
            console.log("msg resend err==>",err);
            return;
          }
          else{
            console.log(" [x] reSent '%s'", msg);
          }
        });
        });
        done();
        setTimeout(function() { conn.close();}, 500);
      });
  });
});
</code>```

Body:
Hi i'm unable to figure out how to connect to rabbitmq using Mocha & chai framework.
I've installed rabbitmq & erlang on my local & trying to connect to rabbitmq by starting the server on local.

The code i'm using is as below:

    var chai = require('chai');
    var chaiHttp = require('chai-http');
    var request = chai.request;
    var should = chai.should();
    var expect = chai.expect;
    var assert = chai.assert;
    var supertest = require('supertest');
    var fs = require('fs');
    var amqp = require('amqplib/callback_api');

    //Plugin for HTTP, etc.
    chai.use(chaiHttp);
    process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';

    describe("Testing RabbitMQ : ", function () {

        it("Send a message : ", function (done) {
            amqp.connect('amqp://localhost:15672/', function (err, conn) {
                conn.createChannel(function (err, ch) {
                    var q = 'hello';
                    ch.assertQueue(q, { durable: false });
                    // Note: on Node 6 Buffer.from(msg) should be used
                    ch.sendToQueue(q, new Buffer('Hello World!'));
                    console.log(" [x] Sent 'Hello World!'");
                });
                setTimeout(function () { conn.close(); process.exit(0) }, 500);
            });
            done();
        });

        it("Receive a message", function (done) {
            amqp.connect('amqp://localhost:15672/', function (err, conn) {
                conn.createChannel(function (err, ch) {
                    var q = 'hello';

                    ch.assertQueue(q, { durable: false });
                    console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q);
                    ch.consume(q, function (msg) {
                        console.log(" [x] Received %s", msg.content.toString());
                    }, { noAck: true });
                });
            });
            done();
        });
    })

So is there any other way to connect to rabbitmq & publish a message?
I've tried with amqp library, any sample code for connecting to rabbitmq will be helpful.

Can anyone make me understand how to connect to a specific queue to send a message, where the message can be published.

Any help would be really appreciated. Thank you.

Body:
You are specifying the wrong port. The default amqp port is 5672. If you are not changing the default port then you don't need to specify the port in amqp server url. That is instead of amqp://localhost:15672/, you can simply specify the url as amqp://localhost. I would like to give a working program for How to publish a message to rabbitmq using Mocha framework?.

I run the RabbitMQ server in my system using docker

docker run -d --hostname rabbit1 --name rabbit1 -e RABBITMQ_ERLANG_COOKIE=rabbitcluster -p 30000:5672 -p 30001:15672 rabbitmq:management

Then

// test.js

var chai = require('chai')
var amqp = require('amqplib/callback_api');
var chaiHttp = require('chai-http')
var should = chai.should()
chai.use(chaiHttp);
var config={
  protocol: 'amqp',
  hostname: 'localhost',
  port: 30000,
  username: 'guest',
  password: 'guest',
}
var q="ex.queue";
var msg =  "Hello World!";

describe('Testing RabbitMQ',function(){
  it('Sending Message to RabbitMQ Server',function(done){
    amqp.connect(config, function(err, conn) {
      if(err){
        console.log("connection error");
        return;
      }
      conn.createConfirmChannel(function(err, ch) {
        if(err){
           return;
        }
          ch.assertQueue(q, {durable: true});
    ch.sendToQueue(q, new Buffer(msg), {persistent: true},
        function(err){
          if(err){
            console.log("msg resend err==>",err);
            return;
          }
          else{
            console.log(" [x] reSent '%s'", msg);
          }
        });
        });
        done();
        setTimeout(function() { conn.close();}, 500);
      });
  });
});


问:
Can't import Flask while using Google App Engine
I'm following this guide and trying to develop a Flask app to run on the Google App Engine. I followed the guide to the letter but when I launch the dev app server from the Launcher and go to http://localhost:8080/, I get a HTTP 500 error.

I check the logs and it says No module named flask. Then I check the interactive console in the admin console by running import flask and I get the same error message. I can import flask in any other python file without error.

Is there a way to fix this?

答:
I was also facing the same issue and after spending 1 day on it have found out my silly mistake actually while refactoring my flask app I have changed
 appengine_config.py to some other name.

Ideally appengine_config.py should look like below if you are having all your dependencies in lib folder only

```<code>from google.appengine.ext import vendor

#Add any libraries installed in the "lib" folder.
vendor.add('lib')
</code>```

And because it was not able to find and execute appengine_config.py so lib folder was not registered as a dependency folder. To check you can try printing something in appengine_config.py to check if it's being executed on server startup.

Body:
I was also facing the same issue and after spending 1 day on it have found out my silly mistake actually while refactoring my flask app I have changed
 appengine_config.py to some other name.

Ideally appengine_config.py should look like below if you are having all your dependencies in lib folder only

from google.appengine.ext import vendor

#Add any libraries installed in the "lib" folder.
vendor.add('lib')

And because it was not able to find and execute appengine_config.py so lib folder was not registered as a dependency folder. To check you can try printing something in appengine_config.py to check if it's being executed on server startup.


问:
How to check in Java color of text when I have .html and .css files?
I have html with css and I want to check what is real color (and other visual text attributes) of specified text in html document. Can I do this with JSoup or must I look for some real-like html engine/processor? Speed of processing this operation is one of main factor.</p>

答:
if you need to know accurate info about the object in web page,

like default border of standard HTML table, or color of a standard link,

use FireBug extension for FireFox.


问:
GitLab: lost gitlab-secrets.json - CipherError (bad decrypt)
I have reinstalled GitLab and forgot to back up the gitlab-secrets.json file.

Now I cannot enable 2FA (was disabled) and I'm seeing this error in the production.log file:

```<code>Completed 500 Internal Server Error in 15ms (ActiveRecord: 1.3ms)

OpenSSL::Cipher::CipherError (bad decrypt):
  app/controllers/profiles/two_factor_auths_controller.rb:5:in `show'
  lib/gitlab/i18n.rb:47:in `with_locale'
  lib/gitlab/i18n.rb:53:in `with_user_locale'
  app/controllers/application_controller.rb:337:in `set_locale'
  lib/gitlab/middleware/multipart.rb:93:in `call'
  lib/gitlab/request_profiler/middleware.rb:14:in `call'
  lib/gitlab/middleware/go.rb:17:in `call'
  lib/gitlab/etag_caching/middleware.rb:11:in `call'
  lib/gitlab/middleware/read_only.rb:30:in `call'
  lib/gitlab/request_context.rb:18:in `call'
  lib/gitlab/metrics/requests_rack_middleware.rb:27:in `call'
</code>```

Is there anything I could do to fix it without losing any data?

GitLab CE ver. 10.1.0

答:
Sorry to say, but you are out of luck if you can't find a backup.

If you ever need to restore a GitLab application backup you need to also restore gitlab-secrets.json. If you do not, GitLab users who are using two-factor authentication will lose access to your GitLab server and 'secure variables' stored in GitLab CI will be lost.

https://docs.gitlab.com/omnibus/settings/backups.html#backup-and-restore-omnibus-gitlab-configuration

Body:
I have reinstalled GitLab and forgot to back up the gitlab-secrets.json file.

Now I cannot enable 2FA (was disabled) and I'm seeing this error in the production.log file:

Completed 500 Internal Server Error in 15ms (ActiveRecord: 1.3ms)

OpenSSL::Cipher::CipherError (bad decrypt):
  app/controllers/profiles/two_factor_auths_controller.rb:5:in `show'
  lib/gitlab/i18n.rb:47:in `with_locale'
  lib/gitlab/i18n.rb:53:in `with_user_locale'
  app/controllers/application_controller.rb:337:in `set_locale'
  lib/gitlab/middleware/multipart.rb:93:in `call'
  lib/gitlab/request_profiler/middleware.rb:14:in `call'
  lib/gitlab/middleware/go.rb:17:in `call'
  lib/gitlab/etag_caching/middleware.rb:11:in `call'
  lib/gitlab/middleware/read_only.rb:30:in `call'
  lib/gitlab/request_context.rb:18:in `call'
  lib/gitlab/metrics/requests_rack_middleware.rb:27:in `call'

Is there anything I could do to fix it without losing any data?

GitLab CE ver. 10.1.0


问:
Display MNIST image using matplotlib
I am using tensorflow to import some MNIST input data. I followed this tutorial...https://www.tensorflow.org/get_started/mnist/beginners

I am importing them as so...

```<code>from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
</code>```

I want to be able to display any of the images from the training set. I know the location of the images is mnist.train.images, so I try to access the first images and display it like so...

```<code>with tf.Session() as sess:
    #access first image
    first_image = mnist.train.images[0]

    first_image = np.array(first_image, dtype='uint8')
    pixels = first_image.reshape((28, 28))
    plt.imshow(pixels, cmap='gray')
</code>```

I a attempt to convert the image to a 28 by 28 numpy array because I know that each image is 28 by 28 pixels.

However, when I run the code all I get is the following...

Clearly I am doing something wrong. When I print out the matrix, everything seems to look good, but I think I am incorrectly reshaping it.

答:
Here is the complete code for showing image using matplotlib</p>

```<code>from matplotlib import pyplot as plt
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data', one_hot = True)
first_image = mnist.test.images[0]
first_image = np.array(first_image, dtype='float')
pixels = first_image.reshape((28, 28))
plt.imshow(pixels, cmap='gray')
plt.show()
</code>```

Title: Display MNIST image using matplotlib

Body:
I am using tensorflow to import some MNIST input data. I followed this tutorial...https://www.tensorflow.org/get_started/mnist/beginners

I am importing them as so...

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

I want to be able to display any of the images from the training set. I know the location of the images is mnist.train.images, so I try to access the first images and display it like so...

with tf.Session() as sess:
    #access first image
    first_image = mnist.train.images[0]

    first_image = np.array(first_image, dtype='uint8')
    pixels = first_image.reshape((28, 28))
    plt.imshow(pixels, cmap='gray')

I a attempt to convert the image to a 28 by 28 numpy array because I know that each image is 28 by 28 pixels.

However, when I run the code all I get is the following...

Clearly I am doing something wrong. When I print out the matrix, everything seems to look good, but I think I am incorrectly reshaping it.

Body:
Here is the complete code for showing image using matplotlib

from matplotlib import pyplot as plt
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data', one_hot = True)
first_image = mnist.test.images[0]
first_image = np.array(first_image, dtype='float')
pixels = first_image.reshape((28, 28))
plt.imshow(pixels, cmap='gray')
plt.show()


问:
Trying to concatenate strings and add integers to a sum separately
I posted this earlier and trying to figure out if this works better in terms of presentation. I am trying to concatenate strings and sum the integers from a list separately. For some reason, I am not getting the output I expected</p>

```<code>l = ['magical unicorns', 19, 'hello', 98.98, 'world']

comb_str = ''
comb_int = 0

for i in l:
    if type(i) is 'str':
        comb_str = comb_str + 'i'
    elif type(i) is 'int':
        comb_int += i
    else:
        pass

print comb_str
print comb_int
</code>```

答:
For concatenating strings:

```<code>print "".join(filter(lambda x: isinstance(x, basestring), l))
</code>```

Output:

```<code>'magical unicornshelloworld'
</code>```

For sum the integers:

```<code>import numbers
print sum(filter(lambda x: isinstance(x, numbers.Number), l))
</code>```

Output:

```<code>117.98
</code>```

Body:
I posted this earlier and trying to figure out if this works better in terms of presentation. I am trying to concatenate strings and sum the integers from a list separately. For some reason, I am not getting the output I expected

l = ['magical unicorns', 19, 'hello', 98.98, 'world']

comb_str = ''
comb_int = 0

for i in l:
    if type(i) is 'str':
        comb_str = comb_str + 'i'
    elif type(i) is 'int':
        comb_int += i
    else:
        pass

print comb_str
print comb_int

Body:
For concatenating strings:

print "".join(filter(lambda x: isinstance(x, basestring), l))

Output:

'magical unicornshelloworld'

For sum the integers:

import numbers
print sum(filter(lambda x: isinstance(x, numbers.Number), l))

Output:

117.98


问:
Cant update data in sql azure with email in xamarin forms
I Want to make update data in xamarin forms with email not id, so if the email is null its create new data but when there is email with the same name it will be updating the data. but when i do that i dont know why its shows error message, here is the error code

```<code>Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).
</code>```

here is my insert and update code

```<code>     public async Task SaveTaskAsync(Member member)
            {
                if (member.email == null)
                {
                    await _membertable.InsertAsync(member);
                }
                else
                {
                    await _membertable.UpdateAsync(member);
                }
            }
</code>```

and here is my Save/Update button

```<code> private async void BtnSave_OnClicked(object sender, EventArgs e)
        {

                var member = new Member()
                {
                    email = txtemail.Text,
                    fullname = txtfullname.Text,
                    phone = txtphone.Text,
                    birthday = txtdate.Date.ToString(),
                    alamat = txtalamat.Text
                };
                await _membermanager.SaveTaskAsync(member);

                await DisplayAlert("Keterangan", "Data Mu Berhasil disimpan !", "OK");

        }
</code>```

and my table is id, fullname, email, phone, birthday, alamat
Primary Key is in my 'id' , and imake my 'email' as unique key

and here is my Member model

```<code>namespace KGVC.Models
{
    public class Member
    {
        private string _id;
        [JsonProperty(PropertyName = "id")]
        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }

        private string _email;
        [JsonProperty(PropertyName = "email")]
        public string email
        {
            get { return _email; }
            set { _email = value; }
        }

        private string _fullname;
        [JsonProperty(PropertyName = "fullname")]
        public string fullname
        {
            get { return _fullname; }
            set { _fullname = value; }
        }

        private string _phone;
        [JsonProperty(PropertyName = "phone")]
        public string phone
        {
            get { return _phone; }
            set { _phone = value; }
        }

        private string _birthday;
        [JsonProperty(PropertyName = "birthday")]
        public string birthday
        {
            get { return _birthday; }
            set { _birthday = value; }
        }

        private string _alamat;
        [JsonProperty(PropertyName = "alamat")]
        public string alamat
        {
            get { return _alamat; }
            set { _alamat = value; }
        }

        [Version]
        public string Version { get; set; }
    }
}
</code>```

what make me cant update the user data via email, is there anything wrong here ?

答: According to your description, I assumed that you are using the online client against your remote table. For IMobileServiceTable<T>.InsertAsync, if you do not specify the id property, then the backend would automatically generate it for you. For IMobileServiceTable<T>.UpdateAsync, you need to specific the id property, or you would get the error response. You could leverage fiddler to capture the network traces when you calling the related methods. Moreover, I would recommend you follow adrian hall's book about The Mobile Client.

Body:
I Want to make update data in xamarin forms with email not id, so if the email is null its create new data but when there is email with the same name it will be updating the data. but when i do that i dont know why its shows error message, here is the error code

Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).

here is my insert and update code

     public async Task SaveTaskAsync(Member member)
            {
                if (member.email == null)
                {
                    await _membertable.InsertAsync(member);
                }
                else
                {
                    await _membertable.UpdateAsync(member);
                }
            }

and here is my Save/Update button

 private async void BtnSave_OnClicked(object sender, EventArgs e)
        {

                var member = new Member()
                {
                    email = txtemail.Text,
                    fullname = txtfullname.Text,
                    phone = txtphone.Text,
                    birthday = txtdate.Date.ToString(),
                    alamat = txtalamat.Text
                };
                await _membermanager.SaveTaskAsync(member);

                await DisplayAlert("Keterangan", "Data Mu Berhasil disimpan !", "OK");

        }

and my table is id, fullname, email, phone, birthday, alamat
Primary Key is in my 'id' , and imake my 'email' as unique key

and here is my Member model

namespace KGVC.Models
{
    public class Member
    {
        private string _id;
        [JsonProperty(PropertyName = "id")]
        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }

        private string _email;
        [JsonProperty(PropertyName = "email")]
        public string email
        {
            get { return _email; }
            set { _email = value; }
        }

        private string _fullname;
        [JsonProperty(PropertyName = "fullname")]
        public string fullname
        {
            get { return _fullname; }
            set { _fullname = value; }
        }

        private string _phone;
        [JsonProperty(PropertyName = "phone")]
        public string phone
        {
            get { return _phone; }
            set { _phone = value; }
        }

        private string _birthday;
        [JsonProperty(PropertyName = "birthday")]
        public string birthday
        {
            get { return _birthday; }
            set { _birthday = value; }
        }

        private string _alamat;
        [JsonProperty(PropertyName = "alamat")]
        public string alamat
        {
            get { return _alamat; }
            set { _alamat = value; }
        }

        [Version]
        public string Version { get; set; }
    }
}

what make me cant update the user data via email, is there anything wrong here ?


问:
i want to include a switch case in dynamic HTML block
I want to include a switch condition in this dynamic HTML block. How can I do that?</p>

```<code>editQuestionBlockHTML=' <div class="addQuestionBlock" >'
      +'<div  class="selectQnLabel"><p class="selectQnLabel">Select a type of question</p>'
      +'<p class="questionTypes">';

       switch(questionType)
      {
      case "Radio":
      editQuestionBlockHTML += +' <select id="EditQuestionType" onchange="changeQuestionType();">'
             +' <option value="radioBtn" selected="selected">Radio Button</option>'

            +' <option value="checkBox">Check Box </option>'
            +'  <option value="pullDownMenu">Pull Down Menu</option>'
            +'  <option value="ratingScale"> Rating Scale</option>'
            +'  <option value="commentBox"> Comment Box</option>'
            +'  <option value="singleTextBox"> Single Text Box</option>'
            +' </select>';
      break;

       }

     editQuestionBlockHTML+=+'</p></div>'

      +'<div  style="float:left;width:100%;">'
      +' <p class="selectQnLabel">Enter Question</p>'
      +' <p><textarea "EditQuestionTitle-'+questionId+'" class="inputBox" rows="4" cols="65" >'+questionText+'</textarea></p>'
      +'<div style="clear:both;">'

       +'</div>'
      +'</div>'
      +'<div  style="float:left;width:100%;">'
      +' <p class="selectQnLabel">Enter Choices (Each choice on a separate line)</p>'
      +' <p><textarea id="editQuestionChoiceList-'+questionId+'" class="inputBox" rows="4" cols="65">'
      +choicelist
      +'</textarea></p>'
      +'<div style="clear:both;">'

       +'</div>'
      +'</div>'

      +'</div>'
      +'</div>';
      return editQuestionBlockHTML;
</code>```

答:
http://www.w3schools.com/js/js_switch.asp

Here's some documentation.

Body:
I want to include a switch condition in this dynamic HTML block. How can I do that?

editQuestionBlockHTML='
'
      +'

Select a type of question
'
      +'
';

       switch(questionType)
      {
      case "Radio":
      editQuestionBlockHTML += +' <select id="EditQuestionType" onchange="changeQuestionType();">'
             +' <option value="radioBtn" selected="selected">Radio Button</option>'

            +' <option value="checkBox">Check Box </option>'
            +'  <option value="pullDownMenu">Pull Down Menu</option>'
            +'  <option value="ratingScale"> Rating Scale</option>'
            +'  <option value="commentBox"> Comment Box</option>'
            +'  <option value="singleTextBox"> Single Text Box</option>'
            +' </select>';
      break;

       }

     editQuestionBlockHTML+=+'

'

      +'
'
      +'
Enter Question
'
      +'
<textarea "EditQuestionTitle-'+questionId+'" class="inputBox" rows="4" cols="65" >'+questionText+'</textarea>
'
      +'
'

       +'
'
      +'
'
      +'
'
      +'
Enter Choices (Each choice on a separate line)
'
      +'
<textarea id="editQuestionChoiceList-'+questionId+'" class="inputBox" rows="4" cols="65">'
      +choicelist
      +'</textarea>
'
      +'
'

       +'
'
      +'
'

      +'
'
      +'
';
      return editQuestionBlockHTML;


问:
Can't find SSIS project in Visual Studio 2015
I've recently installed SQL Server 2017 developer and Visual studio 2015. However, I can't seem to find the SSIS project in visual studio 2015. Any ideas?</p>

答:
I think you'll need download and install SSDT (SQL Server Data Tools).
It's an official addon for Visual Studio which adds templates for SSIS and SSAS projects.

https://learn.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt


问:
Unresolved external symbol in object files
During coding in Visual Studio I got an unresolved external symbol error
and I've got no idea what to do. I don't know what's wrong.
Could you please decipher me? Where should I be looking for what kind of errors?</p>

```<code>1>Form.obj : error LNK2019: unresolved external symbol "public: class Field * __thiscall Field::addField(class Field *)" (?addField@Field@@QAEPAV1@PAV1@@Z) referenced in function "public: void __thiscall Form::parse(class std::basic_stringstream<char,struct std::char_traits<char>,class std::allocator<char> > &)" (?parse@Form@@QAEXAAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)
1>Form.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall Field::parse(class std::basic_stringstream<char,struct std::char_traits<char>,class std::allocator<char> > &)" (?parse@Field@@UAEXAAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "public: __thiscall InputField::InputField(class std::basic_stringstream<char,struct std::char_traits<char>,class std::allocator<char> > &)" (??0InputField@@QAE@AAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Field::prompt(void)" (?prompt@Field@@UAEXXZ)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall Field::getName(void)" (?getName@Field@@UAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall Field::getType(void)" (?getType@Field@@UAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Field::describe(void)" (?describe@Field@@UAEXXZ)
1>C:\Users\tomy\Documents\Visual Studio 2010\Projects\zapoctovkac++\Debug\zapoctovkac++.exe : fatal error LNK1120: 6 unresolved externals
</code>```

答: Make sure that you are not trying to overload the insertion or extraction operators as inline functions. I had this problem and it only went away when i removed that keyword.</p>

Body:
During coding in Visual Studio I got an unresolved external symbol error
and I've got no idea what to do. I don't know what's wrong.
Could you please decipher me? Where should I be looking for what kind of errors?

1>Form.obj : error LNK2019: unresolved external symbol "public: class Field * __thiscall Field::addField(class Field *)" (?addField@Field@@QAEPAV1@PAV1@@Z) referenced in function "public: void __thiscall Form::parse(class std::basic_stringstream<char,struct std::char_traits<char>,class std::allocator<char> > &)" (?parse@Form@@QAEXAAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)
1>Form.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall Field::parse(class std::basic_stringstream<char,struct std::char_traits<char>,class std::allocator<char> > &)" (?parse@Field@@UAEXAAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function "public: __thiscall InputField::InputField(class std::basic_stringstream<char,struct std::char_traits<char>,class std::allocator<char> > &)" (??0InputField@@QAE@AAV?$basic_stringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Field::prompt(void)" (?prompt@Field@@UAEXXZ)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall Field::getName(void)" (?getName@Field@@UAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall Field::getType(void)" (?getType@Field@@UAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
1>Form.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Field::describe(void)" (?describe@Field@@UAEXXZ)
1>C:\Users\tomy\Documents\Visual Studio 2010\Projects\zapoctovkac++\Debug\zapoctovkac++.exe : fatal error LNK1120: 6 unresolved externals


问:
Getting PHP to receive AJAX data
I'm trying to send data (such as the value of a HTML input element) from one script to another (or to the same script if possible) without any HTML form element, instead using a JavaScript event and a XMLHttpRequest (no jQuery please).

I've tried different headers and content types.

I've tried GET, POST, PATCH, and PUT methods.

I've tried receiving with $_SESSION, $_POST, $_SERVER['REQUEST_METHOD'], etc. and even file_get_contents('php://input').

I've tried var_dump, print_r, json_decode, etc.

I've poured through solutions, details, and gotchas from similar questions, other websites and blogs, and various books. While I've learned a ton, this still isn't working...

I could be mistaken, but according to the Chrome and Firefox dev tools at least, it appears the data is being sent just fine from the client-side, so I believe the issue is with PHP (or perhaps my hosting provider's server config?).

If I could just get the PHP script to receive the data, I'll be good to go. From there, I know how to process it, insert it into a MySQL database, etc.

What I'm looking for: a simple, working example of JSON data sent to a PHP script (initiated by, say, a JS click event).

Thank you

答:
Recheck the name for the input value you sent from your script, then recheck the method either post or delete etc. Make sure the receiving party accept using the same name, and the same method. Have you tried receiving using $_REQUEST['input_name']?
Are you sure you send to the right url/action?

Title: Getting PHP to receive AJAX data