问:
After uploading file clicking submit button getting Exception IOE
This is My JSP Page I am getting Exception after uploading and click on submit button

Now how should I handle the Exception in JSP page .
java.io.IOException: An exception occurred processing JSP page /upload.jsp at line 41

upload.jsp

```<code><%@page import="com.oreilly.servlet.*,java.sql.*,databaseconnection.*,java.util.*,java.io.*,javax.servlet.*, javax.servlet.http.*"%>
 <%

 String h1=null;
       String saveFile="";

String contentType = request.getContentType();

if((contentType != null)&&(contentType.indexOf("multipart/form-data") >= 0)){
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
 int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;

String file = new String(dataBytes);

saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

fin = new FileInputStream(ff);

while ((ch = fin.read()) != -1)
strContent.append((char) ch);

fin.close();
String ss=(strContent.toString());
//StringBuffer s=new StringBuffer(ss);

String date=(String)session.getAttribute("date");

String keypoints=(String)session.getAttribute("keypoints");
/*
    String[] strArray =null;
    strArray=keypoints.split(",");
 for (String str : strArray) {
// String a="<a href>"+str+" </a>";
//String b="(?i)"+str;
h=ss.replaceAll(str,"<a href>"+str+" </a>");

 }
*/
String text=ss;
String result[]=text.split("\\s");

String[] strArray =keypoints.split(",");
    for(int i=0;i<strArray.length;i++)
    {
        for(int p=0;p<result.length;p++)
        {

            if(strArray[i].equals(result[p])){
            StringBuffer sb1=new StringBuffer();
            sb1.append("<a href=\"search.jsp?search="+strArray[i]+"\">"+strArray[i]+"</a>");
            result[p]=sb1.toString();

            }

        }

    }
    StringBuffer sb=new StringBuffer();
    for(int i=0;i<result.length;i++){
    sb.append(result[i]);
    sb.append(" ");
    }
    String ans=new String(sb);
    session.setAttribute("ans",ans);
out.println(ans);
String id=(String)session.getAttribute("id");

String filename=(String)session.getAttribute("filename");

//int n;
//session.getAttribute("userid", n );

String filesize=null;
String jj="no";

FileInputStream fis;

PreparedStatement psmt1=null;
try
{

Connection con = databasecon.getconnection();
psmt1=con.prepareStatement("insert into file(id,filename,date,file,ff,keypoints) values(?,?,?,?,?,?)");

//File f = new File(h);

psmt1.setString(1,id);
psmt1.setString(2,filename);
psmt1.setString(3,date);
//fis = new FileInputStream(f);

psmt1.setString(4,ans);
//double bytes = file.length();
//filesize=Double.toString(bytes);
psmt1.setString(5,jj);
//sout.println(filesize);
psmt1.setString(6,keypoints);

psmt1.executeUpdate();

response.sendRedirect("suc.jsp?success");

}
catch(Exception ex)
{

out.println("Error in connection : "+ex);

}

}

%>
</code>```

This is the Exception is:
    =========================

```<code> java.io.IOException: An exception occurred processing JSP page /upload.jsp at line 41

38: int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
39: System.out.println(saveFile);
40: File ff = new File(saveFile);
41: FileOutputStream fileOut = new FileOutputStream(ff);
42:
43: fileOut.write(dataBytes, startPos, (endPos - startPos));
44:

Stacktrace:
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2503)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2492)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: springframework-license.txt (Access is denied)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at org.apache.jsp.upload_jsp._jspService(upload_jsp.java:163)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
    ... 27 more
</code>```

答:
Your stacktrace says

"Caused by: java.io.FileNotFoundException: springframework-license.txt
  (Access is denied)"

Apparently the access to the file springframework-license.txt itself or the directory is denied for the user tomcat (or your app) is running under.

Check your path and the file access rights.

Body:
This is My JSP Page I am getting Exception after uploading and click on submit button

Now how should I handle the Exception in JSP page .
java.io.IOException: An exception occurred processing JSP page /upload.jsp at line 41

upload.jsp

<%@page import="com.oreilly.servlet.*,java.sql.*,databaseconnection.*,java.util.*,java.io.*,javax.servlet.*, javax.servlet.http.*"%>
 <%

 String h1=null;
       String saveFile="";

String contentType = request.getContentType();

if((contentType != null)&&(contentType.indexOf("multipart/form-data") >= 0)){
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
 int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;

String file = new String(dataBytes);

saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

fin = new FileInputStream(ff);

while ((ch = fin.read()) != -1)
strContent.append((char) ch);

fin.close();
String ss=(strContent.toString());
//StringBuffer s=new StringBuffer(ss);

String date=(String)session.getAttribute("date");

String keypoints=(String)session.getAttribute("keypoints");
/*
    String[] strArray =null;
    strArray=keypoints.split(",");
 for (String str : strArray) {
// String a=""+str+" ";
//String b="(?i)"+str;
h=ss.replaceAll(str,""+str+" ");

 }
*/
String text=ss;
String result[]=text.split("\\s");

String[] strArray =keypoints.split(",");
    for(int i=0;i<strArray.length;i++)
    {
        for(int p=0;p<result.length;p++)
        {

            if(strArray[i].equals(result[p])){
            StringBuffer sb1=new StringBuffer();
            sb1.append(""+strArray[i]+"");
            result[p]=sb1.toString();

            }

        }

    }
    StringBuffer sb=new StringBuffer();
    for(int i=0;i<result.length;i++){
    sb.append(result[i]);
    sb.append(" ");
    }
    String ans=new String(sb);
    session.setAttribute("ans",ans);
out.println(ans);
String id=(String)session.getAttribute("id");

String filename=(String)session.getAttribute("filename");

//int n;
//session.getAttribute("userid", n );

String filesize=null;
String jj="no";

FileInputStream fis;

PreparedStatement psmt1=null;
try
{

Connection con = databasecon.getconnection();
psmt1=con.prepareStatement("insert into file(id,filename,date,file,ff,keypoints) values(?,?,?,?,?,?)");

//File f = new File(h);

psmt1.setString(1,id);
psmt1.setString(2,filename);
psmt1.setString(3,date);
//fis = new FileInputStream(f);

psmt1.setString(4,ans);
//double bytes = file.length();
//filesize=Double.toString(bytes);
psmt1.setString(5,jj);
//sout.println(filesize);
psmt1.setString(6,keypoints);

psmt1.executeUpdate();

response.sendRedirect("suc.jsp?success");

}
catch(Exception ex)
{

out.println("Error in connection : "+ex);

}

}

%>

This is the Exception is:
    =========================

 java.io.IOException: An exception occurred processing JSP page /upload.jsp at line 41

38: int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
39: System.out.println(saveFile);
40: File ff = new File(saveFile);
41: FileOutputStream fileOut = new FileOutputStream(ff);
42:
43: fileOut.write(dataBytes, startPos, (endPos - startPos));
44:

Stacktrace:
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2503)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2492)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: springframework-license.txt (Access is denied)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
    at org.apache.jsp.upload_jsp._jspService(upload_jsp.java:163)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
    ... 27 more


来源: stackexchange

问:
Event listener without GUI
I need an event listener that starts and quits my script whenever I press a key. So this is a script that lets me know if a key has been pressed:

```<code>import Tkinter as tk

def onKeyPress(event):
    text.insert('end', 'You pressed %s\n' % (event.char, ))

root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()
</code>```

That works great but the problem is that I don't need a GUI. I should be able to press a key wherever I want. How would that be possible?

答:
Like Rawing said, you can use the keyboard library, for example:

```<code>import keyboard
keyboard.add_hotkey('a', lambda: print "a was pressed")
</code>```

Note that for this to work, the keyboard library must be installed, you can do this with $ sudo pip install keyboard

Edit: You might have to use $ sudo python -m pip install keyboard

Edit: Or you might have to use $ sudo py -m pip install keyboard

Edit: Or even $ sudo -H pip install keyboard

Also, note that I'm assuming you're using python 2.7.

Edit: if you wonder why I assumed you were using python 2.7 it was because you used from Tkinter import * in your GUI example, and in python 2.7, the tkinter module is called "Tkinter", whilst in python 3.6, tkinter is called "tkinter" so in python 3 you should use from tkinter import * (Note the lowercase "t" versus the capital "T" in tkinter/Tkinter)

Also, note that the keyboard module doesn't work on Mac (at least their pip page only says they support Windows and Linux, but it might work if you have luck)

Lastly, note that I haven't tried this myself since I currently do not have access to a computer with python installed. If it doesn't work, comment me and I'll try to find another solution :)

Edit: @RezaSaadati approved that it worked.

ContentLicense: CC BY-SA 3.0

Title: Event listener without GUI

Body:
I need an event listener that starts and quits my script whenever I press a key. So this is a script that lets me know if a key has been pressed:

import Tkinter as tk

def onKeyPress(event):
    text.insert('end', 'You pressed %s\n' % (event.char, ))

root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()

That works great but the problem is that I don't need a GUI. I should be able to press a key wherever I want. How would that be possible?

Body:
Like Rawing said, you can use the keyboard library, for example:

import keyboard
keyboard.add_hotkey('a', lambda: print "a was pressed")

Note that for this to work, the keyboard library must be installed, you can do this with $ sudo pip install keyboard

Edit: You might have to use $ sudo python -m pip install keyboard

Edit: Or you might have to use $ sudo py -m pip install keyboard

Edit: Or even $ sudo -H pip install keyboard

Also, note that I'm assuming you're using python 2.7.

Edit: if you wonder why I assumed you were using python 2.7 it was because you used from Tkinter import * in your GUI example, and in python 2.7, the tkinter module is called "Tkinter", whilst in python 3.6, tkinter is called "tkinter" so in python 3 you should use from tkinter import * (Note the lowercase "t" versus the capital "T" in tkinter/Tkinter)

Also, note that the keyboard module doesn't work on Mac (at least their pip page only says they support Windows and Linux, but it might work if you have luck)

Lastly, note that I haven't tried this myself since I currently do not have access to a computer with python installed. If it doesn't work, comment me and I'll try to find another solution :)

Edit: @RezaSaadati approved that it worked.


问:
Saving multiple pages simultaneously in htmlunit
I am currently working on creating functional tests using htmlunit.

On the webpage I am testing, there is an anchor which opens a page in a new tab when clicked. This anchor needs to be clicked to reveal additional check boxes and buttons.

If I wanted to save the page after clicking the anchor it would look something like this:

```<code>HtmlAnchor terms = tb.getFirstByXPath("//*[@id=\"terms_link\"]");

tb = terms.click();
</code>```

However, the above code saves the webpage which is opened in the new tab as opposed to the web page in which the anchor was clicked.

Is there any way for me to save the page in which the anchor was clicked, or possibly save both html pages?

答:
So after a bit of messing around I discovered that any actions which change the page are registered in the browser window regardless of whether or not you save them after an action.

In order to save the popup which occurs after clicking the an action just assign the resulting page to an HtmlPage object.

```<code>HtmlPage page = button.click
</code>```

You can fetch the previous window and save it's modified contents with the following code. If you want to save the popup and the original page just save them to different object names.

```<code>page2 =(HtmlPage)(webClient.getWebWindows().get(0).getEnclosedPage());
</code>```

Body:
I am currently working on creating functional tests using htmlunit.

On the webpage I am testing, there is an anchor which opens a page in a new tab when clicked. This anchor needs to be clicked to reveal additional check boxes and buttons.

If I wanted to save the page after clicking the anchor it would look something like this:

HtmlAnchor terms = tb.getFirstByXPath("//*[@id=\"terms_link\"]");

tb = terms.click();

However, the above code saves the webpage which is opened in the new tab as opposed to the web page in which the anchor was clicked.

Is there any way for me to save the page in which the anchor was clicked, or possibly save both html pages?

Body:
So after a bit of messing around I discovered that any actions which change the page are registered in the browser window regardless of whether or not you save them after an action.

In order to save the popup which occurs after clicking the an action just assign the resulting page to an HtmlPage object.

HtmlPage page = button.click

You can fetch the previous window and save it's modified contents with the following code. If you want to save the popup and the original page just save them to different object names.

page2 =(HtmlPage)(webClient.getWebWindows().get(0).getEnclosedPage());


问:
how to setup the .htaccess for a subdomain on a shared hosting godaddy server
I want to upload my local Laravel project on godaddy but I'm having some error

error

```<code>[Wed Jul 05 21:16:44.858396 2017]
    [autoindex:error] [pid 21796:tid 139689709188864]
    [client 99.240.235.234:57754]
    AH01276:
        Cannot serve directory /home/bugsbunny/public_html/sto.com/:
            No matching DirectoryIndex (/home/bugsbunny/public_html/sto.com/public/index.php)
    found, and server-generated directory index forbidden by Options directive
</code>```

.htaccess

```<code>DirectoryIndex /home/bugsbunny/public_html/sto.com/public/index.php
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ /home/bugsbunny/public_html/sto.com/public/index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
</code>```

steps that I did

I edited the public/.htaccess file

by edited I mean changing the directory on the first line and the line starting by RewriteRule

I cut & paste this file into the root directory

I uploaded the project into godaddy

答:
On Godaddy I find it easier to create/upload a Laravel app with this procedure </p>

```<code>1- Create an addon domain or a sub-domain on Godaddy
2- Install a Laravel app (Quick-install) on this domain/sub-domain
3- Download this app on local (my computer) with Filezilla (or other sftp software)
4- On local disk change the .env database access or (create a user+password+database on phpmyadmin/mysql with the information contain in the .env that Godaddy setup for you)
5- finish up the app (Build the webapp project that you want to do).
6- Upload the app to the server (except the .env) with Filezilla
7- upload the database (mysql) from local to Godaddy
</code>```

<p>So there is no need to change the .htaccess file. </p>

Body:
I want to upload my local Laravel project on godaddy but I'm having some error

error

[Wed Jul 05 21:16:44.858396 2017]
    [autoindex:error] [pid 21796:tid 139689709188864]
    [client 99.240.235.234:57754]
    AH01276:
        Cannot serve directory /home/bugsbunny/public_html/sto.com/:
            No matching DirectoryIndex (/home/bugsbunny/public_html/sto.com/public/index.php)
    found, and server-generated directory index forbidden by Options directive

.htaccess

DirectoryIndex /home/bugsbunny/public_html/sto.com/public/index.php
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ /home/bugsbunny/public_html/sto.com/public/index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

steps that I did

I edited the public/.htaccess file

by edited I mean changing the directory on the first line and the line starting by RewriteRule

I cut & paste this file into the root directory

I uploaded the project into godaddy

Body:
On Godaddy I find it easier to create/upload a Laravel app with this procedure

1- Create an addon domain or a sub-domain on Godaddy
2- Install a Laravel app (Quick-install) on this domain/sub-domain
3- Download this app on local (my computer) with Filezilla (or other sftp software)
4- On local disk change the .env database access or (create a user+password+database on phpmyadmin/mysql with the information contain in the .env that Godaddy setup for you)
5- finish up the app (Build the webapp project that you want to do).
6- Upload the app to the server (except the .env) with Filezilla
7- upload the database (mysql) from local to Godaddy

So there is no need to change the .htaccess file.


问:
Setup.exe and autorun.inf
I have Visual Studio 2008 project on which I added a Setup Project. It generates all files to install the application correctly.

Now I am trying to add an autorun.inf to the cd, which is supposed to start the Setup.exe.
After a lot of attempts and every combinations possible, nothing works, the install don't start. I even tried a batch file which start Setup.exe but no use.

Is there something I missing, because double-clicking on it works.

答: This autorun.inf page may help, especially the link about testing without burning a CD. Also check if autorun is enabled on the PC.</p>

OwnerDisplayName: Sébastien Lachance

ContentLicense: CC BY-SA 2.5

Title: Setup.exe and autorun.inf

LastEditorDisplayName: Jon B

OwnerDisplayName: Kevin Haines


问:
How to update a Rails 3 project to latest gems?
I created a new Ruby on Rails 3.0.1 project, and then globally updated gems to 3.0.3.

After some digging around, I ended up editing the project Gemfile to say "3.0.3" instead of "3.0.1", and then ran "rake rails:update", and now it appears that everything is up-to-date.

However, I can't find any references on the Internet for doing this with Rails 3, so I want to make sure this is the right way of doing things. Confirmation appreciated. Thank you.

答: If you're changing the version in your Gemfile, you should be running bundle update so that all gems are updated to their latest versions specified by the Gemfile. rake rails:update is used for updating things such as the Prototype assets to the latest version.


问:
Windows Help Files
Back in the old days, Help was not trivial but possible: generate some funky .rtf file with special tags, run it through a compiler, and you got a WinHelp file (.hlp) that actually works really well.

Then, Microsoft decided that WinHelp was not hip and cool anymore and switched to CHM, up to the point they actually axed WinHelp from Vista.

Now, CHM maybe nice, but everyone that tried to open a .chm file on the Network will know the nice "Navigation to the webpage was canceled" screen that is caused by security restrictions.

While there are ways to make CHM work off the network, this is hardly a good choice, because when a user presses the Help Button he wants help and not have to make some funky settings

Bottom Line: I find CHM absolutely unusable. But with WinHelp not being an option anymore either, I wonder what the alternatives are, especially when it comes to integrate with my Application (i.e. for WinHelp and CHM there are functions that allow you to directly jump to a topic)?

PDF has the disadvantage of requiring the Adobe Reader (or one of the more lightweight ones that not many people use). I could live with that seeing as this is kind of standard nowadays, but can you tell it reliably to jump to a given page/anchor?

HTML files seem to be the best choice, you then just have to deal with different browsers (CSS and stuff).

Edit: I am looking to create my own Help Files. As I am a fan of the "No Setup, Just Extract and Run" Philosophy, i had that problem many times in the past because many of my users will run it off the network, which causes exactly this problem.

So i am looking for a more robust and future-proof way to provide help to my users without having to code a different help system for each application i make.

CHM is a really nice format, but that Security Stuff makes it unusable, as a Help system is supposed to provide help to the user, not to generate even more problems.

答:
Yep, at some point they want to add behaviour to their help files which makes it a security issue and guess what happens, the remedy being often worse than the threat.

Or it's too simple or too complicated and being replaced by something new without caring for backward compatibility.

If you want it really simple and build for the ages go for .TXT

You didn't specify what your apps are coded in so it depends.

If it's a web app, plain HTML would be the best choice, for a help file you don't need special features or javascript so being browser independant should be straightforward. But also for desktop apps HTML, on- or offline are often used with good results.

PDF is the other general solution, and yes you can jump to specific pages, see this answer. Every pc has (or should) one client or the other installed, I wouldn't worry about that. I myself never choose Acrobat Reader, faster, sompler and often better solutions are available, my favorite is Sumatra.

I'm sure .Net apps have their own help system (no experience here) and many languages have options to display tooltips, windows or pages with help either by pressing a hotkey (F1) or clicking some control dialog.

Title: Windows Help Files


问:
Navigating to another component using setTimeout does not run
I am trying to create a loading screen in React Native that will navigate to a confirmation screen once the time from a setTimeout function has been fulfilled. Currently, the screen loads, but does not navigate to the confirmation screen after the setTimeout interval.

```<code>import React from 'react';
import { Text, View, Image } from 'react-native';
import { Actions as NavigationActions } from 'react-native-router-
flux';

import styles from './styles';

export default class ProcessingLoader extends React.Component {
  constructor(props) {
   super(props);
   this.state = {};
 }

componentDidMount() {
    setTimeout(this.navigateToConfirmation, 3000);
   }

navigateToConfirmation() {
    NavigationActions.checkoutConfirmation({ product: this.props.product, type: 'reset' });
  }

renderLoader() {
    return (
      <View style={styles.textContainer}>
        <Text style={styles.loaderText}>Processing Order ...</Text>
      </View>
    );
  }

 render() {

    return (
      <View style={{ flex: 1 }}>
        {this.renderLoader()}
      </View>
    );
  }
}
</code>```

I've tried using setTimeout in componentDidMount as well as in render. I've also tried using and arrow function vs not using an arrow function. Am I utilizing setTimeout completely wrong here?  I'm afraid that I don't understand why it will not navigate to the next screen after 3 seconds.  Thanks in advance!

答:
You are not invoking the function, use parenthesis to do that.
Also, the first parameter is a callback, so put your invokation inside a function, like this:

```<code>componentDidMount() {
  setTimeout(function(t){t.navigateToConfirmation()}, 3000, this);
}
</code>```

or in an arrow function:

```<code>componentDidMount() {
  setTimeout(() => {this.navigateToConfirmation()}, 3000);
}
</code>```

Body:
I am trying to create a loading screen in React Native that will navigate to a confirmation screen once the time from a setTimeout function has been fulfilled. Currently, the screen loads, but does not navigate to the confirmation screen after the setTimeout interval.

import React from 'react';
import { Text, View, Image } from 'react-native';
import { Actions as NavigationActions } from 'react-native-router-
flux';

import styles from './styles';

export default class ProcessingLoader extends React.Component {
  constructor(props) {
   super(props);
   this.state = {};
 }

componentDidMount() {
    setTimeout(this.navigateToConfirmation, 3000);
   }

navigateToConfirmation() {
    NavigationActions.checkoutConfirmation({ product: this.props.product, type: 'reset' });
  }

renderLoader() {
    return (
      <View style={styles.textContainer}>
        <Text style={styles.loaderText}>Processing Order ...</Text>
      </View>
    );
  }

 render() {

    return (
      <View style={{ flex: 1 }}>
        {this.renderLoader()}
      </View>
    );
  }
}

I've tried using setTimeout in componentDidMount as well as in render. I've also tried using and arrow function vs not using an arrow function. Am I utilizing setTimeout completely wrong here?  I'm afraid that I don't understand why it will not navigate to the next screen after 3 seconds.  Thanks in advance!

Body:
You are not invoking the function, use parenthesis to do that.
Also, the first parameter is a callback, so put your invokation inside a function, like this:

componentDidMount() {
  setTimeout(function(t){t.navigateToConfirmation()}, 3000, this);
}

or in an arrow function:

componentDidMount() {
  setTimeout(() => {this.navigateToConfirmation()}, 3000);
}


问:
Hide second link if the first one is loaded
I have two links :

The first one is:

```<code><a title="Kronos">First link</a>
</code>```

the second one is:

```<code><a title="Portal">Secondlink</a>
</code>```

I want to hide the second one if the first one is loaded with javascript

How can i do it ?

答:
I assume that you're setting/hiding the visibility of the first link, and then changing the visibility of the second link based on that. If that's the case, and you're using JQuery, you can use code like this:

First, you need to give the links some way to be identified.

```<code><a title="Kronos" id="link1">First link</a>
<a title="Portal" id="link2">Secondlink</a>
</code>```

Next, you can use JS:

```<code>if ($('#link1').is(':visible')) {
$('#link2').hide();
}
</code>```

For more info about what I used in the if statement, check out How do I check if an element is hidden in jQuery?

Body:
I have two links :

The first one is:

First link

the second one is:

Secondlink

I want to hide the second one if the first one is loaded with javascript

How can i do it ?

Body:
I assume that you're setting/hiding the visibility of the first link, and then changing the visibility of the second link based on that. If that's the case, and you're using JQuery, you can use code like this:

First, you need to give the links some way to be identified.

<a title="Kronos" id="link1">First link</a>
<a title="Portal" id="link2">Secondlink</a>

Next, you can use JS:

if ($('#link1').is(':visible')) {
$('#link2').hide();
}

For more info about what I used in the if statement, check out How do I check if an element is hidden in jQuery?


问:
Tableview.reloadData doesn't work
I have two controllers and I'd like to pass datas between them:
This is the first controller, a tableviewcontroller.

```<code>class BooksVC: UITableViewController {

var books: [String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Books"

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return books.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = books[indexPath.row]

    return cell
}
}
</code>```

And this is the second controller, a viewcontroller

```<code>class AddController: UIViewController {
@IBOutlet weak var inputField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func done(_ sender: Any) {
    let myVC = storyboard?.instantiateViewController(withIdentifier: "BooksVC") as! BooksVC
    myVC.books.append(inputField.text!)
    myVC.tableView.reloadData()

    dismiss(animated: true, completion: nil)
}
</code>```

}

Reloaddata doesn't work, can you help me I would be very glad.

答:
Alright for second ViewController when doneButton pressed you can

   dissmisstheview
    trasffer data
    self.parentviewController. books.apped(inputField.text!)
    self.dissmissviewcontroller

than in the first VC you can do something like this

```<code>in viewWillAppear func{
tableview.reloadData()
}
</code>```

Title: Tableview.reloadData doesn't work

Body:
I have two controllers and I'd like to pass datas between them:
This is the first controller, a tableviewcontroller.

class BooksVC: UITableViewController {

var books: [String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Books"

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return books.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = books[indexPath.row]

    return cell
}
}

And this is the second controller, a viewcontroller

class AddController: UIViewController {
@IBOutlet weak var inputField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func done(_ sender: Any) {
    let myVC = storyboard?.instantiateViewController(withIdentifier: "BooksVC") as! BooksVC
    myVC.books.append(inputField.text!)
    myVC.tableView.reloadData()

    dismiss(animated: true, completion: nil)
}

}

Reloaddata doesn't work, can you help me I would be very glad.

Body:
Alright for second ViewController when doneButton pressed you can

   dissmisstheview
    trasffer data
    self.parentviewController. books.apped(inputField.text!)
    self.dissmissviewcontroller

than in the first VC you can do something like this

in viewWillAppear func{
tableview.reloadData()
}


问:
How do I `git push` without seeing remote output
Since some update to git a while ago, I believe the ability to see remote build status in realtime was added. Is there a way to silence this?

I'm currently pushing a docker image to a resin project, here's what happens

```<code>$ git push resin master
Counting objects: 8, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (8/8), 1.07 KiB | 0 bytes/s, done.
Total 8 (delta 0), reused 0 (delta 0)

[Info]     Starting build for gh_amingilani/pwnbox, user gh_amingilani
[Info]     Dashboard link: https://dashboard.resin.io/apps/444007/devices
[Info]     Building on 'local'
[Info]     Pulling old image for caching purposes
[Info]     Fetching base image
[==================================================>] 100%
[Info]     Building Standard Dockerfile project
[Build]    Step 1/5 : FROM resin/raspberrypi3-debian:jessie
[Build]     ---> 8fe2e7355e6f
[Build]    Step 2/5 : RUN apt-get update && apt-get upgrade -y
[Build]     ---> Running in be6da38a83c0
[Build]    Ign http://deb.debian.org jessie InRelease
[Build]    Get:1 http://deb.debian.org jessie-updates InRelease [145 kB]
[Build]    Get:2 http://deb.debian.org jessie Release.gpg [2373 B]
[Build]    Get:3 http://deb.debian.org jessie Release [148 kB]
[Build]    Get:4 http://archive.raspbian.org jessie InRelease [14.9 kB]
[Build]    Get:5 http://security.debian.org jessie/updates InRelease [63.1 kB]
[Build]    Get:6 http://archive.raspberrypi.org jessie InRelease [22.9 kB]
[Build]    Get:7 http://deb.debian.org jessie-updates/main armhf Packages [17.8 kB]
...
</code>```

How do I make it so that what I see is

```<code>$ git push resin master
list of known hosts.
    Counting objects: 8, done.
    Delta compression using up to 8 threads.
    Compressing objects: 100% (5/5), done.
    Writing objects: 100% (8/8), 1.07 KiB | 0 bytes/s, done.
    Total 8 (delta 0), reused 0 (delta 0)
To git.resin.io:gh_amingilani/pwnbox.git
   692cd00..4b40c02  master -> master
</code>```

答:
Try</p>

```<code>git push -q --progress resin master
</code>```

Body:
Since some update to git a while ago, I believe the ability to see remote build status in realtime was added. Is there a way to silence this?

I'm currently pushing a docker image to a resin project, here's what happens

$ git push resin master
Counting objects: 8, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (8/8), 1.07 KiB | 0 bytes/s, done.
Total 8 (delta 0), reused 0 (delta 0)

[Info]     Starting build for gh_amingilani/pwnbox, user gh_amingilani
[Info]     Dashboard link: https://dashboard.resin.io/apps/444007/devices
[Info]     Building on 'local'
[Info]     Pulling old image for caching purposes
[Info]     Fetching base image
[==================================================>] 100%
[Info]     Building Standard Dockerfile project
[Build]    Step 1/5 : FROM resin/raspberrypi3-debian:jessie
[Build]     ---> 8fe2e7355e6f
[Build]    Step 2/5 : RUN apt-get update && apt-get upgrade -y
[Build]     ---> Running in be6da38a83c0
[Build]    Ign http://deb.debian.org jessie InRelease
[Build]    Get:1 http://deb.debian.org jessie-updates InRelease [145 kB]
[Build]    Get:2 http://deb.debian.org jessie Release.gpg [2373 B]
[Build]    Get:3 http://deb.debian.org jessie Release [148 kB]
[Build]    Get:4 http://archive.raspbian.org jessie InRelease [14.9 kB]
[Build]    Get:5 http://security.debian.org jessie/updates InRelease [63.1 kB]
[Build]    Get:6 http://archive.raspberrypi.org jessie InRelease [22.9 kB]
[Build]    Get:7 http://deb.debian.org jessie-updates/main armhf Packages [17.8 kB]
...

How do I make it so that what I see is

$ git push resin master
list of known hosts.
    Counting objects: 8, done.
    Delta compression using up to 8 threads.
    Compressing objects: 100% (5/5), done.
    Writing objects: 100% (8/8), 1.07 KiB | 0 bytes/s, done.
    Total 8 (delta 0), reused 0 (delta 0)
To git.resin.io:gh_amingilani/pwnbox.git
   692cd00..4b40c02  master -> master

Body:
Try

git push -q --progress resin master


问:
Limit the number of ID numbers on a single line with a regular expression
I have a single line of text in Notepad++ containing over 250 ID numbers separated by spaces. I want to separate them to only allow a maximum of 25 ID numbers per line.

How can I limit the number of ID numbers on each line using Notepad++'s regex search & replace tool?

答:
You can use Replace to select a certain number of ID numbers in a capturing group and then add a new line after them, e.g.:

```Find what:     ((\d+\s*){25})
Replace with:  \1\n```

Make sure Regular expression is set as search mode and just do Replace all.

Body:
You can use Replace to select a certain number of ID numbers in a capturing group and then add a new line after them, e.g.:

Find what:     ((\d+\s*){25})
Replace with:  \1\n

Make sure Regular expression is set as search mode and just do Replace all.


问:
Symfony JsonResponse : wrong Float precision
The Symfony\Component\HttpFoundation\JsonResponse seems to have an odd reaction.

I retrieve a Doctrine "decimal" parameter from my object list and I try to send an array of them with a JsonResponse. But the decimal value is not the one I expected, the "precision" is really odd, and I'm unable to round it :

My Entity :

```<code>...

/**
 * @var float Local average Grade
 * @ORM\Column(type="decimal", nullable=true, precision=4, scale=2)
 */
private $grade;

...
</code>```

For this example, I will use only a single result of my data.
When I read it from the database, I can read, as expected : 8.30

Here are the tests I've made :

```<code>var_dump(gettype($local->getGrade()));
var_dump($local->getGrade());
var_dump((float) $local->getGrade());
var_dump(round($local->getGrade(), 2));

return new JsonResponse([
    'grade' => $local->getGrade(),
    'roundedGrade' => round($local->getGrade(), 2)
]);
</code>```

And here is the result :

```<code>string(6) "string"
string(4) "8.10"
float(8.1)
float(8.1)

{
    "grade":8.0999999999999996447286321199499070644378662109375,
    "roundedGrade":8.0999999999999996447286321199499070644378662109375
}
</code>```

It doesn't make sense to me. Does anyone have any idea of what is happening here ?

Thank you.

答:
Try this:</p>

```<code>echo number_format((float)$local->getGrade(), 2, '.', ''); //8.10
</code>```

Body:
The Symfony\Component\HttpFoundation\JsonResponse seems to have an odd reaction.

I retrieve a Doctrine "decimal" parameter from my object list and I try to send an array of them with a JsonResponse. But the decimal value is not the one I expected, the "precision" is really odd, and I'm unable to round it :

My Entity :

...

/**
 * @var float Local average Grade
 * @ORM\Column(type="decimal", nullable=true, precision=4, scale=2)
 */
private $grade;

...

For this example, I will use only a single result of my data.
When I read it from the database, I can read, as expected : 8.30

Here are the tests I've made :

var_dump(gettype($local->getGrade()));
var_dump($local->getGrade());
var_dump((float) $local->getGrade());
var_dump(round($local->getGrade(), 2));

return new JsonResponse([
    'grade' => $local->getGrade(),
    'roundedGrade' => round($local->getGrade(), 2)
]);

And here is the result :

string(6) "string"
string(4) "8.10"
float(8.1)
float(8.1)

{
    "grade":8.0999999999999996447286321199499070644378662109375,
    "roundedGrade":8.0999999999999996447286321199499070644378662109375
}

It doesn't make sense to me. Does anyone have any idea of what is happening here ?

Thank you.

Body:
Try this:

echo number_format((float)$local->getGrade(), 2, '.', ''); //8.10


问:
PHP PDO - Uncaught Error: Call to a member function prepare() on null
I am trying to run a query using database credentials from a config file but I keep getting the following error: Uncaught Error: Call to a member function prepare() on null

config.php file:

```<code>$host = 'xxxx';
$dbname = 'xxxx';
$username = 'xxxx';
$password = 'xxxx.';

try {
    $conn = new PDO("mysql:host=$host; dbname=$dbname;", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "$e->getMessage()";
}
</code>```

functions.php

```<code>session_start();
include 'config.php';

    function getAddress(){
       $output = "";
       if (isset($_SESSION['userid'])){
            $userid = $_SESSION['userid'];
            try {
                $stmt = $conn->prepare('SELECT address FROM users WHERE id = :userid');
                $stmt->bindParam(':userid', $userid);
                $stmt->execute();
                $result = $stmt -> fetch();
                if(empty($result)){
                    $output = "Your information cannot be retrieved";
                } else {
                    $output = $result['address'];
                }
            } catch (PDOException $e) {
                $output = $e->getMessage();
            }
            $conn = null;
            } else {
            $output = "An error has occured, please try again";
            }
        return $output;
    }
</code>```

index.php (html page)

```<code><?php
session_start();
include 'functions.php';
?>
...
<p><?php echo getAddress();?></p>
...
</code>```

So my index page runs a function (getAddress()) from the functions.php script which connects to a db using credentials stored in config.php.

答:
Because of the scope of the function call you need to pass in the connection to the function. First, setup the function call to receive the connection:

```<code>function getAddress($conn)
</code>```

$conn here is just a convenient name for the variable which will use what you have in place inside the function. Passing the connection to the function is the preferred method of making a connection available in a function. The global keyword should be avoided.

Now, call the function with your established connection variable:

```<code>echo getAddress($conn);
</code>```

$conn here is the successful connection from your included file. This will put the connection into the scope of your function and your query should be successful if all else is equal.

Body:
I am trying to run a query using database credentials from a config file but I keep getting the following error: Uncaught Error: Call to a member function prepare() on null

config.php file:

$host = 'xxxx';
$dbname = 'xxxx';
$username = 'xxxx';
$password = 'xxxx.';

try {
    $conn = new PDO("mysql:host=$host; dbname=$dbname;", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "$e->getMessage()";
}

functions.php

session_start();
include 'config.php';

    function getAddress(){
       $output = "";
       if (isset($_SESSION['userid'])){
            $userid = $_SESSION['userid'];
            try {
                $stmt = $conn->prepare('SELECT address FROM users WHERE id = :userid');
                $stmt->bindParam(':userid', $userid);
                $stmt->execute();
                $result = $stmt -> fetch();
                if(empty($result)){
                    $output = "Your information cannot be retrieved";
                } else {
                    $output = $result['address'];
                }
            } catch (PDOException $e) {
                $output = $e->getMessage();
            }
            $conn = null;
            } else {
            $output = "An error has occured, please try again";
            }
        return $output;
    }

index.php (html page)

<?php
session_start();
include 'functions.php';
?>
...

<?php echo getAddress();?>

...

So my index page runs a function (getAddress()) from the functions.php script which connects to a db using credentials stored in config.php.

Body:
Because of the scope of the function call you need to pass in the connection to the function. First, setup the function call to receive the connection:

function getAddress($conn)

$conn here is just a convenient name for the variable which will use what you have in place inside the function. Passing the connection to the function is the preferred method of making a connection available in a function. The global keyword should be avoided.

Now, call the function with your established connection variable:

echo getAddress($conn);

$conn here is the successful connection from your included file. This will put the connection into the scope of your function and your query should be successful if all else is equal.


问:
C# Project has auto generated classes, but what auto generated them?
I am working on a project that I was the original developer on, but over the last couple of years two other developers have maintained and upgraded the project.

There are now some class files inside with the following at the top:

```<code>//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.1433
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=2.0.50727.1432.
//
</code>```

Any idea what could have generated these files? There are some issues inside one of them I want to clean up, but it says the changes might be overwritten.

答:
XSD.exe generated them.  It is a tool in the .Net SDK that takes an XSD schema and generates serializable classes that match the schema.

Check the "Pre-Build" step in the properties of the project.  I bet you will find a call to xsd.exe.  If not, it might be a directive defined in the .csproj file (MSBuild).  Do you know for sure that they are being generated at runtime?  Or were they generated by hand and checked in?

If I remember properly, the classes generated are partials, so you can add functionality via partial classes... but you can't modify the classes themselves if they are generated at build time.

If you want to change the classes, you need to modify the XSD file that the app is using to generate the file.

Body:
I am working on a project that I was the original developer on, but over the last couple of years two other developers have maintained and upgraded the project.

There are now some class files inside with the following at the top:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.1433
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=2.0.50727.1432.
//

Any idea what could have generated these files? There are some issues inside one of them I want to clean up, but it says the changes might be overwritten.


问:
Can node prevent an infinite loop?
Since node runs a single threaded model with event looping I wonder how node prevents the entire application to fail if you write a code like:

```<code>while(true){ doSomething()}
</code>```

where doSomething is a synchronous function (a blocking piece of code)

Note that it doesn't make any sense to write a function like doSomething but nothing prevents you to make a mistake

The problem here is that, since it's single threaded, it won't allow any other parts of the application to run (for instance, a web server would stop accepting new connections) because this function would never end. In a Multi threaded environment you would loose this thread alone.

Is there anything that node can do for you to prevent these kind of problems?

答: It doesn't. This seems like less of a question and more an open statement. Node will loop infinitely and all your parallel code will stop running.</p>

ContentLicense: CC BY-SA 4.0

Title: Can node prevent an infinite loop?

Body:
Since node runs a single threaded model with event looping I wonder how node prevents the entire application to fail if you write a code like:

while(true){ doSomething()}

where doSomething is a synchronous function (a blocking piece of code)

Note that it doesn't make any sense to write a function like doSomething but nothing prevents you to make a mistake

The problem here is that, since it's single threaded, it won't allow any other parts of the application to run (for instance, a web server would stop accepting new connections) because this function would never end. In a Multi threaded environment you would loose this thread alone.

Is there anything that node can do for you to prevent these kind of problems?


问:
Automatically dismiss iOS Alerts when automating an app with Appium
I am using Ruby in a Cucumber automation framework to automate my Android and iOS application. I am using Appium 1.6.4 beta as it supports iOS 10.2.

When the Appium server first installs the iOS app on the device it is prompted with an Alert Dialog asking if I want to allow notifications. With Appium  as far as I can tell the "autoAcceptAlerts" capability does not currently work.

My main question is how would I go about checking if the alert dialog is there and then use something like find_element to press the "Allow" button but not have to edit my feature files. Is there a way I can use my "Log in as an Existing User" step to check for the alert and dismiss it if it's there and if not just continue with the login flow?

I tried to use find_element(xpath to OK button).exists? to make an if/else statement but I think I'm just doing it wrong. If the alert is not present the step fails and my test run stops.

I'm sorry if this question was answered somewhere on her but I've been unable to find a good answer for this question myself. Thank you for any help you can provide.

答:
You can use @driver.switch_to.alert.accept to Accept or @driver.switch_to.alert.dismiss to dismiss the Alert.
If you are unsure about the alert, use begin/rescue to handle the exception</p>


问:
kafka foreing key join with last record
i have 2 stream both have the same Type on the key and on the value,

```<code>  - first represent a finantial instrument with key (string) Currency (Eur-USD)
  - second represent a finantial instrument with key (tenor) Eur-3month , Eur-6month , USD-3month

  - first stream: <key, value> = <Eur , { data , .... } >
  - second stream: <key, value> = <Eur-3month , { data .... }>
</code>```

the requirement is that the last of one stream must join the other stream always with the last key received depending on the (month: 3m, 6m, 7m)

```<code>   - i thought that the streams must be K-tables is this the correct way to join them and have in output always the last join on the last updates ?
   - i can have the same results with a stream ?
</code>```

in this statement i have found that the most similar thing i can use is

```<code>   KStream<K, RV> join(final GlobalKTable<GK, GV> globalKTable,
                                 final KeyValueMapper<? super K, ? super V, ? extends GK> keyValueMapper,
                                 final ValueJoiner<? super V, ? super GV, ? extends RV> joiner)
</code>```

Using the KeyValueMapper i could join the keys
but on the left side i have a stream and not a k-table and this will not update the join on "updates" of the left side

答:
Typically you choose the smaller of the streams (the one with fewer distinct keys) and materialize it into a KTable either by just reading it from kafka as a table (KStreamBuilder.table()) or by using .groupByKey() followed by reduce() or aggregate().

Then you join your other stream with that KTable.

Alternatively, you can materialize both your streams into KTables and join them. I didn't exactly understand your use case in detail, hence cannot advise which is better.

See: https://cwiki.apache.org/confluence/display/KAFKA/Kafka+Streams+Join+Semantics

Title: kafka foreing key join with last record

Body:
i have 2 stream both have the same Type on the key and on the value,

  - first represent a finantial instrument with key (string) Currency (Eur-USD)
  - second represent a finantial instrument with key (tenor) Eur-3month , Eur-6month , USD-3month

  - first stream: <key, value> = <Eur , { data , .... } >
  - second stream: <key, value> = <Eur-3month , { data .... }>

the requirement is that the last of one stream must join the other stream always with the last key received depending on the (month: 3m, 6m, 7m)

   - i thought that the streams must be K-tables is this the correct way to join them and have in output always the last join on the last updates ?
   - i can have the same results with a stream ?

in this statement i have found that the most similar thing i can use is

   KStream<K, RV> join(final GlobalKTable<GK, GV> globalKTable,
                                 final KeyValueMapper<? super K, ? super V, ? extends GK> keyValueMapper,
                                 final ValueJoiner<? super V, ? super GV, ? extends RV> joiner)

Using the KeyValueMapper i could join the keys
but on the left side i have a stream and not a k-table and this will not update the join on "updates" of the left side


问:
html format text field as phone number
I have an <input> field that is generated via jQuery(just a call to backend which is returning HTML and updating current page without reload), and I need to show proper formatted phone numbers (pure integers). For example, an integer 1234123235 should be formatted as +1 (234) 123-235

I tried:

```<code><input type='tel' pattern='[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}' title='Phone Number (Format: +99(99)9999-9999)' value="12312312123">
</code>```

But it doesn't work. How can I format this field as telephone number?

Title: html format text field as phone number

Body:
I have an <input> field that is generated via jQuery(just a call to backend which is returning HTML and updating current page without reload), and I need to show proper formatted phone numbers (pure integers). For example, an integer 1234123235 should be formatted as +1 (234) 123-235

I tried:

<input type='tel' pattern='[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}' title='Phone Number (Format: +99(99)9999-9999)' value="12312312123">

But it doesn't work. How can I format this field as telephone number?

Body:
You mean 1215551000 format as 121-555-1000 .if yes you can use substr

var PNO = '1215551000',
formatted = PNO .substr(0, 3) + '-' + PNO .substr(3, 3) + '-' + PNO .substr(6,4)

Output : 121-555-1000

Edited:

<p class="phone">1234123235</p>

$(".phone").text(function(i, text) {
    text = text.replace(/(\d{1})(\d{3})(\d{3})(\d{3})/, "+$1 ($2)-$3-$4");
    return text;
});

Output: +1 (234)-123-235

jsfiddle


问:
JavaFX TableView with different cell types and unknown size
I am trying to create a tableview from various csv files that contain strings and doubles and an unknown number of columns.

With a few minor changes I was able to use the answer here to create dynamic tableviews: https://community.oracle.com/thread/2474328

Along with this, using the tutorial here I was able to create a table view with strings and doubles by column:
http://docs.oracle.com/javafx/2/ui_controls/table-view.htm

However, since I do not know how many columns there are I cannot create a class defining what data I have and since I need to be able to sort based on doubles as well as strings, I cannot use the first solution which uses an ObservableList of StringProperty to define the data. Does anyone have experience with this or have advice for a route I could take? Thank you

答:
The only real strategy here is to read all the data in as Strings, and then to examine the data in each column to determine the type.

Then you can dynamically create the columns according to the detected type.

For the table's items, use a List<Object> as the representation for each row, and then use the detected type to put the correct type of object into each slot in the row.

Here's a quick example:

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javafx.application.Application;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

public class DynamicTableWithTypes extends Application {

    private final Pattern intPattern = Pattern.compile("-?[0-9]+");
    // this could probably be improved: demo purposes only
    private final Pattern doublePattern = Pattern.compile("-?(([0-9]+)|([0-9]*\\.[0-9]+))");

    @Override
    public void start(Stage primaryStage) {
        TableView<List<Object>> table = new TableView<>();
        String[][] rawData = generateTestData();
        int numCols = computeMaxRowLength(rawData);

        Class<?>[] types = new Class<?>[numCols];

        for (int columnIndex = 0 ; columnIndex < numCols ; columnIndex++) {
            String[] column = extractColumn(rawData, columnIndex);
            types[columnIndex] = deduceColumnType(column);
            table.getColumns().add(createColumn(types[columnIndex], columnIndex));
        }

        for (int rowIndex = 0 ; rowIndex < rawData.length ; rowIndex++) {
            List<Object> row = new ArrayList<>();
            for (int columnIndex = 0 ; columnIndex < numCols ; columnIndex++) {
                row.add(getDataAsType(rawData[rowIndex], types[columnIndex], columnIndex));
            }
            table.getItems().add(row);
        }

        Scene scene = new Scene(table, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private Object getDataAsType(String[] row, Class<?> type, int columnIndex) {
        if (type == Integer.class) {
            if (columnIndex < row.length) {
                return Integer.valueOf(row[columnIndex]);
            } else {
                return new Integer(0);
            }
        } else if (type == Double.class) {
            if (columnIndex < row.length) {
                return Double.valueOf(row[columnIndex]);
            } else {
                return new Double(0.0);
            }
        } else {
            if (columnIndex < row.length) {
                return row[columnIndex];
            } else {
                return "" ;
            }
        }
    }

    private TableColumn<List<Object>, ?> createColumn(Class<?> type, int index) {
        String text = "Column "+(index+1);
        if (type==Integer.class) {
            TableColumn<List<Object>, Number> col = new TableColumn<>(text);
            col.setCellValueFactory(data -> new SimpleIntegerProperty((Integer)data.getValue().get(index)));
            return col ;
        } else if (type == Double.class) {
            TableColumn<List<Object>, Number> col = new TableColumn<>(text);
            col.setCellValueFactory(data -> new SimpleDoubleProperty((Double)data.getValue().get(index)));
            return col ;
        } else {
            TableColumn<List<Object>, String> col = new TableColumn<>(text);
            col.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().get(index).toString()));
            return col ;
        }
    }

    private Class<?> deduceColumnType(String[] column) {
        boolean allInts = true ;
        boolean allDoubles = true ;
        for (int i = 0 ; i < column.length ; i++) {
            allInts = allInts && intPattern.matcher(column[i]).matches() ;
            allDoubles = allDoubles && doublePattern.matcher(column[i]).matches() ;
        }
        if (allInts) {
            return Integer.class ;
        }
        if (allDoubles) {
            return Double.class ;
        }
        return String.class ;
    }

    private int computeMaxRowLength(Object[][] array) {
        int maxLength = Integer.MIN_VALUE ;
        for (int i = 0 ; i < array.length ; i++) {
            if (array[i].length > maxLength) {
                maxLength = array[i].length ;
            }
        }
        return maxLength ;
    }

    private String[] extractColumn(String[][] data, int columnIndex) {
        String[] column = new String[data.length];
        for (int i = 0 ; i < data.length ; i++) {
            if (columnIndex < data[i].length) {
                column[i]=data[i][columnIndex];
            } else {
                column[i]="";
            }
        }
        return column ;
    }

    private String[][] generateTestData() {

        // in real life, read from CSV file/database, etc...

        return new String[][] {
            {"A1", "B2", "10", "-5.3"},
            {"A2", "B1", "15", "12.6"},
            {"A3", "B3", "5", "10.2"}
        };
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

As you can see, this sorts correctly:

Body:
The only real strategy here is to read all the data in as Strings, and then to examine the data in each column to determine the type.

Then you can dynamically create the columns according to the detected type.

For the table's items, use a List<Object> as the representation for each row, and then use the detected type to put the correct type of object into each slot in the row.

Here's a quick example:

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javafx.application.Application;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

public class DynamicTableWithTypes extends Application {

    private final Pattern intPattern = Pattern.compile("-?[0-9]+");
    // this could probably be improved: demo purposes only
    private final Pattern doublePattern = Pattern.compile("-?(([0-9]+)|([0-9]*\\.[0-9]+))");

    @Override
    public void start(Stage primaryStage) {
        TableView<List<Object>> table = new TableView<>();
        String[][] rawData = generateTestData();
        int numCols = computeMaxRowLength(rawData);

        Class<?>[] types = new Class<?>[numCols];

        for (int columnIndex = 0 ; columnIndex < numCols ; columnIndex++) {
            String[] column = extractColumn(rawData, columnIndex);
            types[columnIndex] = deduceColumnType(column);
            table.getColumns().add(createColumn(types[columnIndex], columnIndex));
        }

        for (int rowIndex = 0 ; rowIndex < rawData.length ; rowIndex++) {
            List<Object> row = new ArrayList<>();
            for (int columnIndex = 0 ; columnIndex < numCols ; columnIndex++) {
                row.add(getDataAsType(rawData[rowIndex], types[columnIndex], columnIndex));
            }
            table.getItems().add(row);
        }

        Scene scene = new Scene(table, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private Object getDataAsType(String[] row, Class<?> type, int columnIndex) {
        if (type == Integer.class) {
            if (columnIndex < row.length) {
                return Integer.valueOf(row[columnIndex]);
            } else {
                return new Integer(0);
            }
        } else if (type == Double.class) {
            if (columnIndex < row.length) {
                return Double.valueOf(row[columnIndex]);
            } else {
                return new Double(0.0);
            }
        } else {
            if (columnIndex < row.length) {
                return row[columnIndex];
            } else {
                return "" ;
            }
        }
    }

    private TableColumn<List<Object>, ?> createColumn(Class<?> type, int index) {
        String text = "Column "+(index+1);
        if (type==Integer.class) {
            TableColumn<List<Object>, Number> col = new TableColumn<>(text);
            col.setCellValueFactory(data -> new SimpleIntegerProperty((Integer)data.getValue().get(index)));
            return col ;
        } else if (type == Double.class) {
            TableColumn<List<Object>, Number> col = new TableColumn<>(text);
            col.setCellValueFactory(data -> new SimpleDoubleProperty((Double)data.getValue().get(index)));
            return col ;
        } else {
            TableColumn<List<Object>, String> col = new TableColumn<>(text);
            col.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().get(index).toString()));
            return col ;
        }
    }

    private Class<?> deduceColumnType(String[] column) {
        boolean allInts = true ;
        boolean allDoubles = true ;
        for (int i = 0 ; i < column.length ; i++) {
            allInts = allInts && intPattern.matcher(column[i]).matches() ;
            allDoubles = allDoubles && doublePattern.matcher(column[i]).matches() ;
        }
        if (allInts) {
            return Integer.class ;
        }
        if (allDoubles) {
            return Double.class ;
        }
        return String.class ;
    }

    private int computeMaxRowLength(Object[][] array) {
        int maxLength = Integer.MIN_VALUE ;
        for (int i = 0 ; i < array.length ; i++) {
            if (array[i].length > maxLength) {
                maxLength = array[i].length ;
            }
        }
        return maxLength ;
    }

    private String[] extractColumn(String[][] data, int columnIndex) {
        String[] column = new String[data.length];
        for (int i = 0 ; i < data.length ; i++) {
            if (columnIndex < data[i].length) {
                column[i]=data[i][columnIndex];
            } else {
                column[i]="";
            }
        }
        return column ;
    }

    private String[][] generateTestData() {

        // in real life, read from CSV file/database, etc...

        return new String[][] {
            {"A1", "B2", "10", "-5.3"},
            {"A2", "B1", "15", "12.6"},
            {"A3", "B3", "5", "10.2"}
        };
    }

    public static void main(String[] args) {
        launch(args);
    }
}

As you can see, this sorts correctly:


问:
Receiving Passbook's .pkpass from URL without Webview
Hi first of all i have to confess i really don't understand how the whole Passbook topic really works.
So here's my situation:
I have a backend system which creates .pkpass files stores them and creates an URL.
When i open this URL in my browser it directly starts to download the pass file.
How can i receive or open this file with my ios application?

Thanks in advance.

答:
If you host the link to the PKPass item on a website you can check that the page content is really a PKPass item by looking at the mimeType property on HTTPURLResponse, which should be "application/vnd.apple.pkpass".
Once you confirm that, download the .pkpass data with an URLRequest and pass the data to the PKPass initializer like this:</p>

```<code>var error:NSError?
let passBookData = PKPass( data: data, error: &error )

if error != nil
{
    print( "Error opening pkpass file" )
    return
}
let pkPassVC = PKAddPassesViewController( pass: passBookData )
currentVC.present( pkPassVC, animated: true, completion: completion )
</code>```

Body:
If you host the link to the PKPass item on a website you can check that the page content is really a PKPass item by looking at the mimeType property on HTTPURLResponse, which should be "application/vnd.apple.pkpass".
Once you confirm that, download the .pkpass data with an URLRequest and pass the data to the PKPass initializer like this:

var error:NSError?
let passBookData = PKPass( data: data, error: &error )

if error != nil
{
    print( "Error opening pkpass file" )
    return
}
let pkPassVC = PKAddPassesViewController( pass: passBookData )
currentVC.present( pkPassVC, animated: true, completion: completion )


问:
How do I build this block matrix in python?
I want to build a block matrix for a system of equation with n points.
The result is an (2n+2)x(2n+2) matrix. In example, for 2 points the matrix is:

```<code>1 0 0 0 0 0
a b c d 0 0
e f g h 0 0
0 0 a b c d
0 0 e f g h
0 0 0 0 0 1
</code>```

For 3 points the matrix is

```<code>1 0 0 0 0 0 0 0
a b c d 0 0 0 0
e f g h 0 0 0 0
0 0 a b c d 0 0
0 0 e f g h 0 0
0 0 0 0 a b c d
0 0 0 0 e f g h
0 0 0 0 0 0 0 1
</code>```

Here, a, b, c, d, e, f, g, h are float values known ahead of time.
But I don't know value of n ahead of time. Is there a library in python to do this? I've looked at scipy.sparse.diag, scipy.linalg.block_diag and numpy.bat, but these do not achieve what I want.

答:
We can use np.identity to give us a "square" array (same dimensions in both axis) with the ones and zeros as you specified:

```<code>myarr = np.identity(2*n+2)
</code>```

Then, we define our little subset values for a-h:

```<code>subset = np.array([[a,b,c,d],[e,f,g,h]])
</code>```

Now to replace the corresponding values in our larger array:

```<code>for i in range(1, 2*n+2-1, 2):
    myarr[i:i+2, i-1:i+3] = subset
</code>```

EDIT: this is the output for some random values i chose for a-h:

```<code>>>> myarr = np.identity(2*n+2)
>>> subset = np.array([[a,b,c,d],[e,f,g,h]])
>>> for i in range(1, 2*n+2-1, 2):
...     myarr[i:i+2, i-1:i+3] = subset
...
>>> myarr
array([[  1.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [ 11.,   2.,   3.,   4.,   0.,   0.,   0.,   0.],
       [  5.,   6.,   7.,   9.,   0.,   0.,   0.,   0.],
       [  0.,   0.,  11.,   2.,   3.,   4.,   0.,   0.],
       [  0.,   0.,   5.,   6.,   7.,   9.,   0.,   0.],
       [  0.,   0.,   0.,   0.,  11.,   2.,   3.,   4.],
       [  0.,   0.,   0.,   0.,   5.,   6.,   7.,   9.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   1.]])
</code>```

Body:
I want to build a block matrix for a system of equation with n points.
The result is an (2n+2)x(2n+2) matrix. In example, for 2 points the matrix is:

1 0 0 0 0 0
a b c d 0 0
e f g h 0 0
0 0 a b c d
0 0 e f g h
0 0 0 0 0 1

For 3 points the matrix is

1 0 0 0 0 0 0 0
a b c d 0 0 0 0
e f g h 0 0 0 0
0 0 a b c d 0 0
0 0 e f g h 0 0
0 0 0 0 a b c d
0 0 0 0 e f g h
0 0 0 0 0 0 0 1

Here, a, b, c, d, e, f, g, h are float values known ahead of time.
But I don't know value of n ahead of time. Is there a library in python to do this? I've looked at scipy.sparse.diag, scipy.linalg.block_diag and numpy.bat, but these do not achieve what I want.

Body:
We can use np.identity to give us a "square" array (same dimensions in both axis) with the ones and zeros as you specified:

myarr = np.identity(2*n+2)

Then, we define our little subset values for a-h:

subset = np.array([[a,b,c,d],[e,f,g,h]])

Now to replace the corresponding values in our larger array:

for i in range(1, 2*n+2-1, 2):
    myarr[i:i+2, i-1:i+3] = subset

EDIT: this is the output for some random values i chose for a-h:

>>> myarr = np.identity(2*n+2)
>>> subset = np.array([[a,b,c,d],[e,f,g,h]])
>>> for i in range(1, 2*n+2-1, 2):
...     myarr[i:i+2, i-1:i+3] = subset
...
>>> myarr
array([[  1.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [ 11.,   2.,   3.,   4.,   0.,   0.,   0.,   0.],
       [  5.,   6.,   7.,   9.,   0.,   0.,   0.,   0.],
       [  0.,   0.,  11.,   2.,   3.,   4.,   0.,   0.],
       [  0.,   0.,   5.,   6.,   7.,   9.,   0.,   0.],
       [  0.,   0.,   0.,   0.,  11.,   2.,   3.,   4.],
       [  0.,   0.,   0.,   0.,   5.,   6.,   7.,   9.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   1.]])


问:
Array of two datatypes and how to change it
```<code>const AssetSchema = new Schema({
  name: {
    type: String,
    required: [true, 'Name value is required'],
    unique: true
  },
  past:[[Number], Date]
});
</code>```

I'm trying to save an array which holds another array of numbers and a date with each array. Is this doable or not so much?

I'm updating the array with this:

```<code>assets[i].past.push([12,24], new Date(Date.now()).toISOString());
</code>```

But I get the error:

```<code>CastError: Cast to [number] failed for value "["2017-07-06T18:15:23.631Z"]" at path "past"
</code>```

Thanks for the help, Ed.

答:
Maybe I am mistaken, but I don't think you can do past:[[Number], Date]. Mongoose doesn't seem to understand it as it says in the error Cast to [number]

Why not be more explicit and use an array of objects instead?

```<code>path: [{
    numbers: [Number],
    date: Date
}]
</code>```

which is an array of objects where each object contains an array of numbers and a date.

```<code>assets[i].past.push({
    numbers: [12,24],
    date: new Date(Date.now()) // I don't think you need to use .toISOString()
});
</code>```

Body:
const AssetSchema = new Schema({
  name: {
    type: String,
    required: [true, 'Name value is required'],
    unique: true
  },
  past:[[Number], Date]
});

I'm trying to save an array which holds another array of numbers and a date with each array. Is this doable or not so much?

I'm updating the array with this:

assets[i].past.push([12,24], new Date(Date.now()).toISOString());

But I get the error:

CastError: Cast to [number] failed for value "["2017-07-06T18:15:23.631Z"]" at path "past"

Thanks for the help, Ed.

Body:
Maybe I am mistaken, but I don't think you can do past:[[Number], Date]. Mongoose doesn't seem to understand it as it says in the error Cast to [number]

Why not be more explicit and use an array of objects instead?

path: [{
    numbers: [Number],
    date: Date
}]

which is an array of objects where each object contains an array of numbers and a date.

assets[i].past.push({
    numbers: [12,24],
    date: new Date(Date.now()) // I don't think you need to use .toISOString()
});


问:
Running Casablanca program fails with 'openssl/conf.h' file not found on Mac OS
I am trying to setup a Http client and download some data using the example shown here.

When I try to run the program, it fails saying "conf.h" is not found.

```<code>$g++ -std=c++11 BingSearch.cpp
In file included from BingSearch.cpp:1:
In file included from /usr/local/include/cpprest/http_client.h:53:
In file included from /usr/local/include/boost/asio/ssl.hpp:19:
In file included from /usr/local/include/boost/asio/ssl/context.hpp:27:
In file included from /usr/local/include/boost/asio/ssl/context_base.hpp:19:
/usr/local/include/boost/asio/ssl/detail/openssl_types.hpp:20:10: fatal error: 'openssl/conf.h' file not found
#include <openssl/conf.h>
         ^
1 error generated.
</code>```

I looked at other SO posts and I have set the necessary path variables.

```<code>$echo $LDFLAGS
-L/usr/local/opt/openssl/lib
$echo $CPPFLAGS
-I/usr/local/opt/openssl/include
$echo $PKG_CONFIG_PATH
/usr/local/opt/openssl/lib/pkgconfig
</code>```

Also conf.h is located inside openssl directory

```<code>openssl $find /usr/local/opt/openssl/ -name "conf.h"
/usr/local/opt/openssl//include/openssl/conf.h
</code>```

Is there something else that needs to be done to compile the below file? It is got from here.

```<code>#include <cpprest/http_client.h>
#include <cpprest/filestream.h>

using namespace utility;                    // Common utilities like string conversions
using namespace web;                        // Common features like URIs.
using namespace web::http;                  // Common HTTP functionality
using namespace web::http::client;          // HTTP client features
using namespace concurrency::streams;       // Asynchronous streams

int main(int argc, char* argv[])
{
    auto fileStream = std::make_shared<ostream>();

    // Open stream to output file.
    pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
            {
            *fileStream = outFile;

            // Create http_client to send the request.
            http_client client(U("http://www.bing.com/"));

            // Build request URI and start the request.
            uri_builder builder(U("/search"));
            builder.append_query(U("q"), U("cpprestsdk github"));
            return client.request(methods::GET, builder.to_string());
            })

    // Handle response headers arriving.
    .then([=](http_response response)
            {
            printf("Received response status code:%u\n", response.status_code());

            // Write response body into the file.
            return response.body().read_to_end(fileStream->streambuf());
            })

    // Close the file stream.
    .then([=](size_t)
            {
            return fileStream->close();
            });

    // Wait for all the outstanding I/O to complete and handle any exceptions
    try
    {
        requestTask.wait();
    }
    catch (const std::exception &e)
    {
        printf("Error exception:%s\n", e.what());
    }

    return 0;
}
</code>```

答:
I tried @jww's suggestion as below.

```<code>g++ -std=c++11 BingSearch.cpp -lssl -lcrypto -L/usr/local/opt/openssl/lib -I/usr/local/opt/openssl/include
</code>```

This resulted in overcoming 'conf.h' file not found error.

But it still failed with the below error.

```<code>Undefined symbols for architecture x86_64:
  "web::uri_builder::append_query(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, bool)", referenced from:
      web::uri_builder& web::uri_builder::append_query<char [18]>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, char const (&) [18], bool) in BingSearch-582644.o
</code>```

I followed https://github.com/Microsoft/cpprestsdk/issues/264 and it resolved the problem.

I am able to compile the program using the below command.

```<code>g++ -std=c++11 BingSearch.cpp -stdlib=libc++ -lcpprest -lssl -lcrypto -lboost_system -lboost_thread-mt -lboost_chrono-mt -L/usr/local/opt/openssl/lib -I/usr/local/opt/openssl/include
</code>```

My PATH variable is set as follows.

```<code>$echo $PATH
/usr/local/opt/openssl/bin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
</code>```

Body:
I am trying to setup a Http client and download some data using the example shown here.

When I try to run the program, it fails saying "conf.h" is not found.

$g++ -std=c++11 BingSearch.cpp
In file included from BingSearch.cpp:1:
In file included from /usr/local/include/cpprest/http_client.h:53:
In file included from /usr/local/include/boost/asio/ssl.hpp:19:
In file included from /usr/local/include/boost/asio/ssl/context.hpp:27:
In file included from /usr/local/include/boost/asio/ssl/context_base.hpp:19:
/usr/local/include/boost/asio/ssl/detail/openssl_types.hpp:20:10: fatal error: 'openssl/conf.h' file not found
#include <openssl/conf.h>
         ^
1 error generated.

I looked at other SO posts and I have set the necessary path variables.

$echo $LDFLAGS
-L/usr/local/opt/openssl/lib
$echo $CPPFLAGS
-I/usr/local/opt/openssl/include
$echo $PKG_CONFIG_PATH
/usr/local/opt/openssl/lib/pkgconfig

Also conf.h is located inside openssl directory

openssl $find /usr/local/opt/openssl/ -name "conf.h"
/usr/local/opt/openssl//include/openssl/conf.h

Is there something else that needs to be done to compile the below file? It is got from here.

#include <cpprest/http_client.h>
#include <cpprest/filestream.h>

using namespace utility;                    // Common utilities like string conversions
using namespace web;                        // Common features like URIs.
using namespace web::http;                  // Common HTTP functionality
using namespace web::http::client;          // HTTP client features
using namespace concurrency::streams;       // Asynchronous streams

int main(int argc, char* argv[])
{
    auto fileStream = std::make_shared<ostream>();

    // Open stream to output file.
    pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
            {
            *fileStream = outFile;

            // Create http_client to send the request.
            http_client client(U("http://www.bing.com/"));

            // Build request URI and start the request.
            uri_builder builder(U("/search"));
            builder.append_query(U("q"), U("cpprestsdk github"));
            return client.request(methods::GET, builder.to_string());
            })

    // Handle response headers arriving.
    .then([=](http_response response)
            {
            printf("Received response status code:%u\n", response.status_code());

            // Write response body into the file.
            return response.body().read_to_end(fileStream->streambuf());
            })

    // Close the file stream.
    .then([=](size_t)
            {
            return fileStream->close();
            });

    // Wait for all the outstanding I/O to complete and handle any exceptions
    try
    {
        requestTask.wait();
    }
    catch (const std::exception &e)
    {
        printf("Error exception:%s\n", e.what());
    }

    return 0;
}

Body:
I tried @jww's suggestion as below.

g++ -std=c++11 BingSearch.cpp -lssl -lcrypto -L/usr/local/opt/openssl/lib -I/usr/local/opt/openssl/include

This resulted in overcoming 'conf.h' file not found error.

But it still failed with the below error.

Undefined symbols for architecture x86_64:
  "web::uri_builder::append_query(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, bool)", referenced from:
      web::uri_builder& web::uri_builder::append_query<char [18]>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, char const (&) [18], bool) in BingSearch-582644.o

I followed https://github.com/Microsoft/cpprestsdk/issues/264 and it resolved the problem.

I am able to compile the program using the below command.

g++ -std=c++11 BingSearch.cpp -stdlib=libc++ -lcpprest -lssl -lcrypto -lboost_system -lboost_thread-mt -lboost_chrono-mt -L/usr/local/opt/openssl/lib -I/usr/local/opt/openssl/include

My PATH variable is set as follows.

$echo $PATH
/usr/local/opt/openssl/bin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin


问:
C# Winforms Error handling for dynamically created textboxes
I have two textboxes that are created dynamically created on load. The user can click the add button which adds two new text boxes to the interface each time. When these textboxes are added they are also added to a list. I am trying to add error handling to my project to make sure every textbox is filled out before the user can click save. If the text boxes are empty a message box should show : Please fill out all message boxes.
If the textboxes are filled out a message box should show: Are you sure you want to make this change?
If the user clicks yes the changes should be saved and the message box "Changes saved " should show
If the user clicks no then the message box should disappear and the changes not saved.
The message boxes are not acting the way I expected
Here is what I have so far:

Create the text boxes:

```<code> private void ADDUserInfo(int rowCount, string password = "", string username = "")
            var Password = new TextBox();
            Password.Text = password;
            Password.Name = "Password" + rowCount;

            var Username = new TextBox();
            Username.Text = username;
            Username.Name = "Username" + rowCount;

            CaeUsersPanel.Controls.Add(Username);
            CaeUsersPanel.Controls.Add(Password);

            UsernameTextBoxes.Add(Username);
            PasswordTextboxes.Add(Password);
            }
</code>```

Global declaration of the lists of textboxes:

```<code>List<TextBox> UsernameTextBoxes = new List<TextBox>();
List<TextBox> AliasTextBoxes = new List<TextBox>();
List<TextBox> PasswordTextboxes = new List<TextBox>();
</code>```

The save button:

```<code> for (int i = 0; i < UsernameTextBoxes.Count; i++)
            {
                var userName = UsernameTextBoxes[i];
                var password = PasswordTextboxes[i];
                _config.Environment.Users.User.Add(new EnvironmentUsersUser() { alias = aliasName.Text, userName = userName.Text, password = password.text, toDisplay = true });

            }

            configmgr.Serilize<Config>(_configurationTabData._objectSources.getEnviromentFileName, _config);

            for (int i = 0; i < UsernameTextBoxes.Count; i++)
            {
                var userName = UsernameTextBoxes[i];
                var password = PasswordTextboxes[i];
                if (aliasName.Text == "" || userName.Text == "" || password.Text == "")
                {
                    MessageBox.Show("All fields are required!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                  DialogResult result = MessageBox.Show("Are you sure you want to make these changes", "Warning", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                configmgr.Serilize<Config>(_configurationTabData._objectSources.getEnviromentFileName, _config);
                MessageBox.Show("Changes Saved")
            }
           }

            }
</code>```

答:
Maybe something like this, using LinQ?

```<code>if(UsernameTextBoxes.TrueForAll(t => t.Text.Length > 0) &&
    AliasTextBoxes.TrueForAll(t => t.Text.Length > 0) &&
    PasswordTextboxes.TrueForAll(t => t.Text.Length > 0))
{
    //Do stuff when everything is filled
}
else
{
    //Do stuff when one or more is empty
}
</code>```

You might want to group your TextBoxes into a class and make that class check if everythings filled. Then you would just need one List with this class as generic.

Body:
I have two textboxes that are created dynamically created on load. The user can click the add button which adds two new text boxes to the interface each time. When these textboxes are added they are also added to a list. I am trying to add error handling to my project to make sure every textbox is filled out before the user can click save. If the text boxes are empty a message box should show : Please fill out all message boxes.
If the textboxes are filled out a message box should show: Are you sure you want to make this change?
If the user clicks yes the changes should be saved and the message box "Changes saved " should show
If the user clicks no then the message box should disappear and the changes not saved.
The message boxes are not acting the way I expected
Here is what I have so far:

Create the text boxes:

 private void ADDUserInfo(int rowCount, string password = "", string username = "")
            var Password = new TextBox();
            Password.Text = password;
            Password.Name = "Password" + rowCount;

            var Username = new TextBox();
            Username.Text = username;
            Username.Name = "Username" + rowCount;

            CaeUsersPanel.Controls.Add(Username);
            CaeUsersPanel.Controls.Add(Password);

            UsernameTextBoxes.Add(Username);
            PasswordTextboxes.Add(Password);
            }

Global declaration of the lists of textboxes:

List<TextBox> UsernameTextBoxes = new List<TextBox>();
List<TextBox> AliasTextBoxes = new List<TextBox>();
List<TextBox> PasswordTextboxes = new List<TextBox>();

The save button:

 for (int i = 0; i < UsernameTextBoxes.Count; i++)
            {
                var userName = UsernameTextBoxes[i];
                var password = PasswordTextboxes[i];
                _config.Environment.Users.User.Add(new EnvironmentUsersUser() { alias = aliasName.Text, userName = userName.Text, password = password.text, toDisplay = true });

            }

            configmgr.Serilize<Config>(_configurationTabData._objectSources.getEnviromentFileName, _config);

            for (int i = 0; i < UsernameTextBoxes.Count; i++)
            {
                var userName = UsernameTextBoxes[i];
                var password = PasswordTextboxes[i];
                if (aliasName.Text == "" || userName.Text == "" || password.Text == "")
                {
                    MessageBox.Show("All fields are required!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                  DialogResult result = MessageBox.Show("Are you sure you want to make these changes", "Warning", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                configmgr.Serilize<Config>(_configurationTabData._objectSources.getEnviromentFileName, _config);
                MessageBox.Show("Changes Saved")
            }
           }

            }

Body:
Maybe something like this, using LinQ?

if(UsernameTextBoxes.TrueForAll(t => t.Text.Length > 0) &&
    AliasTextBoxes.TrueForAll(t => t.Text.Length > 0) &&
    PasswordTextboxes.TrueForAll(t => t.Text.Length > 0))
{
    //Do stuff when everything is filled
}
else
{
    //Do stuff when one or more is empty
}

You might want to group your TextBoxes into a class and make that class check if everythings filled. Then you would just need one List with this class as generic.


问:
>nul redirection before or after command in batch
In command prompt, the following two lines give the same output, I want to know the usage difference between them. Thanks.

>nul dir

dir >nul

答:
There is no difference, they redirect the same amount of output. You can combine the input and output redirection operators in multiple ways: > out.txt command < in.txt or < in.txt command > out.txt.

As noted in the comments, you have to be careful if something contains the number 1 or 2, you don't want %something%>out.txt to expand to ...2>out.txt and you can do that with a space or by putting it before the rest of the command.