问:
Nginx, React, Node & Let's Encrypt... How to point Nginx at my React app
I have a React app that I need to talk to a Node server running on port 5000(via pm2) and be the root
directory of my site. The Node server fetches some data from an API and returns it to the client. Right now I have Nginx pointing right at port 5000 (I followed a tutorial to get to this point as a test).

Say my React app is located at /www/ReactApp/dist/, how do I point Nginx at that instead of my Node server on port 5000?

Basically all I need is the contents of /www/ReactApp/dist/ served when you visit myapp.com but with the existing SSL certificate.

The Node server.js will just run in the background and my React app will make calls to it to get data.

Here is the contents of my /etc/nginx/sites-enabled/default:

```<code># HTTP — redirect all traffic to HTTPS
server {
    listen 80;
    listen [::]:80 default_server ipv6only=on;
    return 301 https://$host$request_uri;
}

# HTTPS — proxy all requests to the Node app
server {
    # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name myapp.com;

    # Use the Let’s Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/myapp.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/myapp.com/privkey.pem;

    # Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://localhost:5000/;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}
</code>```

答:
From what I understand, you're basically asking how to serve static files from a directory. In order for a React app (client-side) to call the Node backend (server-side), both need to be exposed. You should add a NGINX directive like so:

```<code>location / {
    # Set this to the directory containing your React app's index.html.
    root /var/www/;
    try_files $uri /index.html;
}
</code>```

Then, for the Node server you would keep what you have but put it at a different path, like so:

```<code>location /api {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:5000/;
    proxy_ssl_session_reuse off;
    proxy_set_header Host $http_host;
    proxy_cache_bypass $http_upgrade;
    proxy_redirect off;
}
</code>```

This proxies /api to your Node server while serving the static contents of /var/www as the root route (/).

NOTE: You might need to change your React configuration to reflect the /api addition.

Body:
I have a React app that I need to talk to a Node server running on port 5000(via pm2) and be the root
directory of my site. The Node server fetches some data from an API and returns it to the client. Right now I have Nginx pointing right at port 5000 (I followed a tutorial to get to this point as a test).

Say my React app is located at /www/ReactApp/dist/, how do I point Nginx at that instead of my Node server on port 5000?

Basically all I need is the contents of /www/ReactApp/dist/ served when you visit myapp.com but with the existing SSL certificate.

The Node server.js will just run in the background and my React app will make calls to it to get data.

Here is the contents of my /etc/nginx/sites-enabled/default:

# HTTP — redirect all traffic to HTTPS
server {
    listen 80;
    listen [::]:80 default_server ipv6only=on;
    return 301 https://$host$request_uri;
}

# HTTPS — proxy all requests to the Node app
server {
    # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name myapp.com;

    # Use the Let’s Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/myapp.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/myapp.com/privkey.pem;

    # Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://localhost:5000/;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}

Body:
From what I understand, you're basically asking how to serve static files from a directory. In order for a React app (client-side) to call the Node backend (server-side), both need to be exposed. You should add a NGINX directive like so:

location / {
    # Set this to the directory containing your React app's index.html.
    root /var/www/;
    try_files $uri /index.html;
}

Then, for the Node server you would keep what you have but put it at a different path, like so:

location /api {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://localhost:5000/;
    proxy_ssl_session_reuse off;
    proxy_set_header Host $http_host;
    proxy_cache_bypass $http_upgrade;
    proxy_redirect off;
}

This proxies /api to your Node server while serving the static contents of /var/www as the root route (/).

NOTE: You might need to change your React configuration to reflect the /api addition.


来源: stackexchange

问:
How to create a zip file in Java
I have a dynamic text file that picks content from a database according to the user's query. I have to write this content into a text file and zip it in a folder in a servlet. How should I do this?</p>

答:
Here is an example code to compress a Whole Directory(including sub files and sub directories), it's using the walk file tree feature of Java NIO.

```<code>import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipCompress {
    public static void compress(String dirPath) {
        final Path sourceDir = Paths.get(dirPath);
        String zipFileName = dirPath.concat(".zip");
        try {
            final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
            Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
                    try {
                        Path targetFile = sourceDir.relativize(file);
                        outputStream.putNextEntry(new ZipEntry(targetFile.toString()));
                        byte[] bytes = Files.readAllBytes(file);
                        outputStream.write(bytes, 0, bytes.length);
                        outputStream.closeEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

To use this, just call

```<code>ZipCompress.compress("target/directoryToCompress");
</code>```

and you'll get a zip file directoryToCompress.zip

ContentLicense: CC BY-SA 2.5

Title: How to create a zip file in Java

Body:
Here is an example code to compress a Whole Directory(including sub files and sub directories), it's using the walk file tree feature of Java NIO.

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipCompress {
    public static void compress(String dirPath) {
        final Path sourceDir = Paths.get(dirPath);
        String zipFileName = dirPath.concat(".zip");
        try {
            final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
            Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
                    try {
                        Path targetFile = sourceDir.relativize(file);
                        outputStream.putNextEntry(new ZipEntry(targetFile.toString()));
                        byte[] bytes = Files.readAllBytes(file);
                        outputStream.write(bytes, 0, bytes.length);
                        outputStream.closeEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

To use this, just call

ZipCompress.compress("target/directoryToCompress");

and you'll get a zip file directoryToCompress.zip

ContentLicense: CC BY-SA 4.0


问:
How do I return a unsure type?
I have a parent Class named 'Shape' and write a method in it
I want any class extends from it can call the bigger method for other use.
simple logic like this:

```<code>public abstract Class Shape{
    public int size;
    public Shape() {}
    public Class<? extends Shape> bigger() {
        this.size += 1;
        return this; // ← Here,How can I return it with unsure type?
    }
}
</code>```

but how can I return a unsure type in here ?
thanks for any ideas!

====

and if I have a class Square extends Shape;

and I want use it like this:

```<code>Square S = new Square().bigger();
</code>```

And it will return a Shape Class, not a Square Class.

but I don't wanna use: (Square) new Square.bigger();

I hope it can automatic recognize what Class a using this method

And return the correct type.

答:
im not sure what is the "unsure" type, but in java we have the Generic type which is Java can return any class regardless what they are.

for example

```<code>public interface dbDao<T>{

    public T t; //this is generic class, all class can use this method

}
</code>```

i hope you understand what im trying to say.

ContentLicense: CC BY-SA 3.0

Title: How do I return a unsure type?

Body:
I have a parent Class named 'Shape' and write a method in it
I want any class extends from it can call the bigger method for other use.
simple logic like this:

public abstract Class Shape{
    public int size;
    public Shape() {}
    public Class<? extends Shape> bigger() {
        this.size += 1;
        return this; // ← Here,How can I return it with unsure type?
    }
}

but how can I return a unsure type in here ?
thanks for any ideas!

====

and if I have a class Square extends Shape;

and I want use it like this:

Square S = new Square().bigger();

And it will return a Shape Class, not a Square Class.

but I don't wanna use: (Square) new Square.bigger();

I hope it can automatic recognize what Class a using this method

And return the correct type.

Body:
im not sure what is the "unsure" type, but in java we have the Generic type which is Java can return any class regardless what they are.

for example

public interface dbDao<T>{

    public T t; //this is generic class, all class can use this method

}

i hope you understand what im trying to say.


问:
Prevent a user from closing a browser window using "X"?
Can I tell, using javascript, whether a user has clicked on the "X" icon on a browser dialog, or the "OK"/"Cancel" buttons? I have code I need to run when the window closes, but it will only run when OK or Cancel are clicked.

I currently capture the onunload event of the window. How can i accomplish this?

```<code>window.onunload = function() { alert("unloading"); }
</code>```

答:
It is impossible to catch the closing of the browser and handle every other event that also causes a post back. You can try and many people have before you and failed.

Your best bet is to use onbeforeunload and learn how to deal with session timeouts on your serverside to clean up data.

OwnerDisplayName: Pwninstein

Body:
Can I tell, using javascript, whether a user has clicked on the "X" icon on a browser dialog, or the "OK"/"Cancel" buttons? I have code I need to run when the window closes, but it will only run when OK or Cancel are clicked.

I currently capture the onunload event of the window. How can i accomplish this?

window.onunload = function() { alert("unloading"); }

OwnerDisplayName: epascarello


问:
Flickr Authentication inside Colorbox?
I know that flickr cannot be authenticated inside an iframe, however I am wondering if it is possible to create a popup colorbox (or another javascript popup) to authenticate.

I need to be able to authenticate for flickr from a colorbox or popup. But turning off iframe for a colorbox doesn't work. Is there any other method anyone can think of?

答:
You could create a pop-up window which closes on the completion of the authentication.

If you are unable to use iFrames to authenticate, then any form on in-page inclusion is not going to work, therefore the authentication page has to be opened in a separate browser window.

Title: Flickr Authentication inside Colorbox?


问:
encoding error when calling FileUtils.copy_entry in Ruby
I'm writing code for copy and paste recursively.

But I got an encoding error when calling FileUtils.copy_entry

Error Messages :

```<code>C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1535:in `join': incompatible character encodings: CP949 and UTF-8 (Encoding::CompatibilityError)
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1535:in `join'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1218:in `path'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:463:in `block in copy_entry'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1485:in `call'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1485:in `wrap_traverse'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1488:in `block in wrap_traverse'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1487:in `each'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1487:in `wrap_traverse'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1488:in `block in wrap_traverse'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1487:in `each'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1487:in `wrap_traverse'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:460:in `copy_entry'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:435:in `block in cp_r'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1558:in `block in fu_each_src_dest'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1574:in `fu_each_src_dest0'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1556:in `fu_each_src_dest'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:434:in `cp_r'
    from copy_test.rb:11:in `copy_files'
    from copy_test.rb:81:in `block in <main>'
    from copy_test.rb:76:in `each'
    from copy_test.rb:76:in `<main>'
</code>```

I'm calling copy_entry like this.

```<code>def copy_files(src, dst)
  FileUtils.mkdir_p(File.dirname(dst))
  FileUtils.copy_entry(src, dst)
end
</code>```

There are some sub-folders and files named with my local language in src.

So I think (Encoding::CompatibilityError) occurs because of these sub-folders and files with local language (not English).

When I tested with only Enlgish folders and files, It worked.

But, I need non-English folders and files too.

How can I solve this problem?

Should I define a new method replacing copy_entry?

My Codes ADDED:

# -*- encoding: cp949 -*-
require 'fileutils'

LIST_FILE = "backup_target_list.txt"
DEST_FILE = "backup_dest.txt"

def copy_files(src, dst)
  FileUtils.mkdir_p(File.dirname(dst))
  FileUtils.copy_entry(src, dst)
end

def get_dst_base_name()
  cur_date = Time.now.to_s[0..9]
  return "backup_#{cur_date}"
end

def get_backup_list(list_file)
  if !File.exist?(list_file) then
    return nil
  end

  path_arr = []

  File.open(list_file, "r") do |f|
    f.each_line { |line|
      path_arr.push(make_path(line.gsub("\n", "")))
    }
  end

  return path_arr
end

def get_dest(dest_file)
  if !File.exist?(dest_file) then
    return nil
  end

  return File.open(dest_file, "r").readline
end

def make_path(*str)
  path_new = nil

  str.each do |item|
    if item.class == Array then
      path_new = (path_new == nil ? File.join(item) : File.join(path_new, item))
    else
      if item.include?(File::ALT_SEPARATOR) then
        path_new = (path_new == nil ? File.join(item.split(File::ALT_SEPARATOR)) : File.join(path_new, item.split(File::ALT_SEPARATOR)))
      else
        path_new = (path_new == nil ? File.join(item) : File.join(path_new, item))
      end
    end
  end

  return path_new
end

get_backup_list(LIST_FILE).each do |path|
  src = path
  tmp = src.split(File::SEPARATOR)
  dst = make_path(get_dest(DEST_FILE), get_dst_base_name, tmp[1..tmp.length])
  print "src: #{src}\n=> dst: #{dst}\n"
  copy_files(src, dst)
end
```

答:
I saw you are using cp949 encoding, and the raised error tells CP949 and UTF-8 are incompatible, so why you just using UTF-8 encoding? So replace the shebang with

```<code># coding: UTF-8
</code>```

And to ensure all the characters read from LIST_FILE are utf-8 encoded, add the following:

```<code>line.force_encoding('utf-8')
</code>```

Body:
I'm writing code for copy and paste recursively.

But I got an encoding error when calling FileUtils.copy_entry

Error Messages :

C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1535:in `join': incompatible character encodings: CP949 and UTF-8 (Encoding::CompatibilityError)
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1535:in `join'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1218:in `path'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:463:in `block in copy_entry'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1485:in `call'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1485:in `wrap_traverse'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1488:in `block in wrap_traverse'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1487:in `each'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1487:in `wrap_traverse'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1488:in `block in wrap_traverse'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1487:in `each'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1487:in `wrap_traverse'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:460:in `copy_entry'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:435:in `block in cp_r'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1558:in `block in fu_each_src_dest'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1574:in `fu_each_src_dest0'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:1556:in `fu_each_src_dest'
    from C:/Ruby200/lib/ruby/2.0.0/fileutils.rb:434:in `cp_r'
    from copy_test.rb:11:in `copy_files'
    from copy_test.rb:81:in `block in '
    from copy_test.rb:76:in `each'
    from copy_test.rb:76:in `'

I'm calling copy_entry like this.

def copy_files(src, dst)
  FileUtils.mkdir_p(File.dirname(dst))
  FileUtils.copy_entry(src, dst)
end

There are some sub-folders and files named with my local language in src.

So I think (Encoding::CompatibilityError) occurs because of these sub-folders and files with local language (not English).

When I tested with only Enlgish folders and files, It worked.

But, I need non-English folders and files too.

How can I solve this problem?

Should I define a new method replacing copy_entry?

My Codes ADDED:

# -*- encoding: cp949 -*-
require 'fileutils'

LIST_FILE = "backup_target_list.txt"
DEST_FILE = "backup_dest.txt"

def copy_files(src, dst)
  FileUtils.mkdir_p(File.dirname(dst))
  FileUtils.copy_entry(src, dst)
end

def get_dst_base_name()
  cur_date = Time.now.to_s[0..9]
  return "backup_#{cur_date}"
end

def get_backup_list(list_file)
  if !File.exist?(list_file) then
    return nil
  end

  path_arr = []

  File.open(list_file, "r") do |f|
    f.each_line { |line|
      path_arr.push(make_path(line.gsub("\n", "")))
    }
  end

  return path_arr
end

def get_dest(dest_file)
  if !File.exist?(dest_file) then
    return nil
  end

  return File.open(dest_file, "r").readline
end

def make_path(*str)
  path_new = nil

  str.each do |item|
    if item.class == Array then
      path_new = (path_new == nil ? File.join(item) : File.join(path_new, item))
    else
      if item.include?(File::ALT_SEPARATOR) then
        path_new = (path_new == nil ? File.join(item.split(File::ALT_SEPARATOR)) : File.join(path_new, item.split(File::ALT_SEPARATOR)))
      else
        path_new = (path_new == nil ? File.join(item) : File.join(path_new, item))
      end
    end
  end

  return path_new
end

get_backup_list(LIST_FILE).each do |path|
  src = path
  tmp = src.split(File::SEPARATOR)
  dst = make_path(get_dest(DEST_FILE), get_dst_base_name, tmp[1..tmp.length])
  print "src: #{src}\n=> dst: #{dst}\n"
  copy_files(src, dst)
end

Body:
I saw you are using cp949 encoding, and the raised error tells CP949 and UTF-8 are incompatible, so why you just using UTF-8 encoding? So replace the shebang with

# coding: UTF-8

And to ensure all the characters read from LIST_FILE are utf-8 encoded, add the following:

line.force_encoding('utf-8')


问:
Detect 64-bit or 32-bit Windows from Google Web Toolkit
How can I detect the OS version (32-bit or 64-bit) in Google Web Toolkit?

答:
You can use the Window.Navigator getUserAgent() method. That string will have some clue as to the OS. Here are some examples for various browsers:

Chrome: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"

Firefox: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0

IE11: "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; rv:11.0) like Gecko"

Edge: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393

All of the have Windows in the name, and either Win64 or WOW64. The latter means a 32 bit browser running on a 64 bit Windows OS.

```<code>public boolean isWindows(){
  return Window.Navigator.getUserAgent().indexOf('Windows') != -1;
}

public boolean isWin64(){
  return isWindows() && (
    Window.Navigator.getUserAgent().indexOf('Win64') != -1 ||
    Window.Navigator.getUserAgent().indexOf('WOW64') != -1);
}
</code>```

It is usually a bad idea to query for OS, but there are some valid use cases, for example to offer a user the correct download for their platform.

Body:
You can use the Window.Navigator getUserAgent() method. That string will have some clue as to the OS. Here are some examples for various browsers:

Chrome: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"

Firefox: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0

IE11: "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; rv:11.0) like Gecko"

Edge: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393

All of the have Windows in the name, and either Win64 or WOW64. The latter means a 32 bit browser running on a 64 bit Windows OS.

public boolean isWindows(){
  return Window.Navigator.getUserAgent().indexOf('Windows') != -1;
}

public boolean isWin64(){
  return isWindows() && (
    Window.Navigator.getUserAgent().indexOf('Win64') != -1 ||
    Window.Navigator.getUserAgent().indexOf('WOW64') != -1);
}

It is usually a bad idea to query for OS, but there are some valid use cases, for example to offer a user the correct download for their platform.


问:
NullPointerException at java.awt.EventQueue.getCurrentEventImpl
I've migrated a Swing application to Java 8 and recently we see the following NPE exception.

```<code>java.lang.NullPointerException
at java.awt.EventQueue.getCurrentEventImpl(EventQueue.java:848)
at java.awt.EventQueue.getCurrentEvent(EventQueue.java:842)
at java.awt.Component.requestFocusHelper(Component.java:7628)
at java.awt.Component.requestFocusHelper(Component.java:7620)
at java.awt.Component.requestFocus(Component.java:7495)
at javax.swing.JComponent.requestFocus(JComponent.java:1504)
at javax.swing.plaf.basic.BasicPopupMenuUI$MenuKeyboardHelper.stateChanged(BasicPopupMenuUI.java:1173)
at javax.swing.MenuSelectionManager.fireStateChanged(MenuSelectionManager.java:202)
at javax.swing.MenuSelectionManager.setSelectedPath(MenuSelectionManager.java:129)
at javax.swing.JPopupMenu.setVisible(JPopupMenu.java:784)
at javax.swing.JPopupMenu.show(JPopupMenu.java:965)
at org.tbee.swing.StandardComponentPopupMenu.showJTableMenu(StandardComponentPopupMenu.java:555)
at org.tbee.swing.StandardComponentPopupMenu$2.run(StandardComponentPopupMenu.java:175)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

Migrating back to J7 is a problem, because lambda's are being used, so I cannot easily confirm that this really is a J8 issue. But the code in question has been running for several years now, surviving Java 5, 6 and 7. So chances are it is J8 specific.

The reason for the exception is that currentEvent in EventQueue is not set. This is done by its setCurrentEventAndMostRecentTimeImpl(AWTEvent e). However, if I trace back in the stack, I see that in EventQueue:756 (Java 1.8.0u45) the dispatch is done after exactly that method is called.

```<code>    if (event instanceof ActiveEvent) {
        // This could become the sole method of dispatching in time.
        setCurrentEventAndMostRecentTimeImpl(event);
        ((ActiveEvent)event).dispatch();
</code>```

I'm in the dark why that variable is null. Debugging is close to impossible, because of all the events being handled by that piece of code.

Is anyone aware of changes in Swing's event handling in J8?

答:
Below works fine :</p>

```<code>   SwingUtilities.invokeLater(new Runnable() {
                  @Override
                  public void run() {
                      Toolkit.getDefaultToolkit().getSystemEventQueue().push(Customized Event);
                  }
              });
</code>```

Body:
I've migrated a Swing application to Java 8 and recently we see the following NPE exception.

java.lang.NullPointerException
at java.awt.EventQueue.getCurrentEventImpl(EventQueue.java:848)
at java.awt.EventQueue.getCurrentEvent(EventQueue.java:842)
at java.awt.Component.requestFocusHelper(Component.java:7628)
at java.awt.Component.requestFocusHelper(Component.java:7620)
at java.awt.Component.requestFocus(Component.java:7495)
at javax.swing.JComponent.requestFocus(JComponent.java:1504)
at javax.swing.plaf.basic.BasicPopupMenuUI$MenuKeyboardHelper.stateChanged(BasicPopupMenuUI.java:1173)
at javax.swing.MenuSelectionManager.fireStateChanged(MenuSelectionManager.java:202)
at javax.swing.MenuSelectionManager.setSelectedPath(MenuSelectionManager.java:129)
at javax.swing.JPopupMenu.setVisible(JPopupMenu.java:784)
at javax.swing.JPopupMenu.show(JPopupMenu.java:965)
at org.tbee.swing.StandardComponentPopupMenu.showJTableMenu(StandardComponentPopupMenu.java:555)
at org.tbee.swing.StandardComponentPopupMenu$2.run(StandardComponentPopupMenu.java:175)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Migrating back to J7 is a problem, because lambda's are being used, so I cannot easily confirm that this really is a J8 issue. But the code in question has been running for several years now, surviving Java 5, 6 and 7. So chances are it is J8 specific.

The reason for the exception is that currentEvent in EventQueue is not set. This is done by its setCurrentEventAndMostRecentTimeImpl(AWTEvent e). However, if I trace back in the stack, I see that in EventQueue:756 (Java 1.8.0u45) the dispatch is done after exactly that method is called.

    if (event instanceof ActiveEvent) {
        // This could become the sole method of dispatching in time.
        setCurrentEventAndMostRecentTimeImpl(event);
        ((ActiveEvent)event).dispatch();

I'm in the dark why that variable is null. Debugging is close to impossible, because of all the events being handled by that piece of code.

Is anyone aware of changes in Swing's event handling in J8?

Body:
Below works fine :

   SwingUtilities.invokeLater(new Runnable() {
                  @Override
                  public void run() {
                      Toolkit.getDefaultToolkit().getSystemEventQueue().push(Customized Event);
                  }
              });


问:
unabe to Reload data in tableview via userdefault
I am a newbie and learning  ios programming. I have made a custom table view cell. I am trying to append data in it via user defaults but its not storing the data, every time i go back the app refreshes  making the table view blank screen.

```<code>// data sent from here

class ViewController: UIViewController {

    @IBOutlet weak var textfield: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func submit(_ sender: AnyObject) {

        performSegue(withIdentifier: "move", sender: nil)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destination = segue.destination as? secondviewcontroller

        destination?.list.append(textfield.text!)

        let defaults = UserDefaults.standard
        defaults.set(destination?.list, forKey: "listarray")
        UserDefaults.standard.synchronize()

    }
}

// here i want to retreive
class secondviewcontroller: UIViewController {

    @IBOutlet weak var tblView: UITableView!
    var list = ["fahad","Ali","tahir"]

   var abc = ""

override func viewDidLoad() {
    super.viewDidLoad()
    tblView.dataSource  = self;
    tblView.delegate = self;

    let storedarray = UserDefaults.standard.object(forKey: "listarray")

    print("hi\(storedarray)")
}

override func viewDidAppear(_ animated: Bool) {
     tblView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    tblView.reloadData()
}

@IBAction func backbtn(_ sender: AnyObject) {
    dismiss(animated: true, completion: nil)
}
</code>```

}

import UIKit

class secondviewcontroller: UIViewController {

```<code>@IBOutlet weak var tblView: UITableView!
var list = ["fahad","Ali","tahir"]
</code>```

var abc = ""

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    tblView.dataSource  = self;
    tblView.delegate = self;

}

override func viewDidAppear(_ animated: Bool) {
     tblView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    let storedarray = UserDefaults.standard.object(forKey: "listarray")

    print("hi\(storedarray)")
    tblView.reloadData()
}

@IBAction func backbtn(_ sender: AnyObject) {
    dismiss(animated: true, completion: nil)
}
</code>```

}

extension secondviewcontroller : UITableViewDataSource , UITableViewDelegate{

```<code>func numberOfSections(in tableView: UITableView) -> Int {

    return 1;
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print (list)
    return list.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell;
    cell.textlabel.text = list[indexPath.row];

    return cell;

}
</code>```

}

```<code>// my custom table view
import UIKit

class   TableViewCell: UITableViewCell {

    @IBOutlet weak var textlabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
    }
}
</code>```

My UI storyboardgetting this error

答:
These lines recreates the same list with an new element without considering the saved items:

```<code>    destination?.list.append(textfield.text!)

    let defaults = UserDefaults.standard
    defaults.set(destination?.list, forKey: "listarray")
    UserDefaults.standard.synchronize()
</code>```

You should instead:

```<code>let newEntry = textfield.text!
let defaults = UserDefaults.standard
if destination?.list.count == 3 {  //3 because you hardcoded 3 items in next controller
      destination?.list.append(newEntry)
} else {
      let obj = defaults.object(forKey: "listarray") as? [String] ?? [String]()
      destination?.list = obj.append(newEntry)
}
defaults.set(destination?.list, forKey: "listarray")
UserDefaults.standard.synchronize()
</code>```

Body:
I am a newbie and learning  ios programming. I have made a custom table view cell. I am trying to append data in it via user defaults but its not storing the data, every time i go back the app refreshes  making the table view blank screen.

// data sent from here

class ViewController: UIViewController {

    @IBOutlet weak var textfield: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func submit(_ sender: AnyObject) {

        performSegue(withIdentifier: "move", sender: nil)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destination = segue.destination as? secondviewcontroller

        destination?.list.append(textfield.text!)

        let defaults = UserDefaults.standard
        defaults.set(destination?.list, forKey: "listarray")
        UserDefaults.standard.synchronize()

    }
}

// here i want to retreive
class secondviewcontroller: UIViewController {

    @IBOutlet weak var tblView: UITableView!
    var list = ["fahad","Ali","tahir"]

   var abc = ""

override func viewDidLoad() {
    super.viewDidLoad()
    tblView.dataSource  = self;
    tblView.delegate = self;

    let storedarray = UserDefaults.standard.object(forKey: "listarray")

    print("hi\(storedarray)")
}

override func viewDidAppear(_ animated: Bool) {
     tblView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    tblView.reloadData()
}

@IBAction func backbtn(_ sender: AnyObject) {
    dismiss(animated: true, completion: nil)
}

}

import UIKit

class secondviewcontroller: UIViewController {

@IBOutlet weak var tblView: UITableView!
var list = ["fahad","Ali","tahir"]

var abc = ""

override func viewDidLoad() {
    super.viewDidLoad()
    tblView.dataSource  = self;
    tblView.delegate = self;

}

override func viewDidAppear(_ animated: Bool) {
     tblView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    let storedarray = UserDefaults.standard.object(forKey: "listarray")

    print("hi\(storedarray)")
    tblView.reloadData()
}

@IBAction func backbtn(_ sender: AnyObject) {
    dismiss(animated: true, completion: nil)
}

}

extension secondviewcontroller : UITableViewDataSource , UITableViewDelegate{

func numberOfSections(in tableView: UITableView) -> Int {

    return 1;
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print (list)
    return list.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell;
    cell.textlabel.text = list[indexPath.row];

    return cell;

}

}

// my custom table view
import UIKit

class   TableViewCell: UITableViewCell {

    @IBOutlet weak var textlabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
    }
}

My UI storyboardgetting this error

Body:
These lines recreates the same list with an new element without considering the saved items:

    destination?.list.append(textfield.text!)

    let defaults = UserDefaults.standard
    defaults.set(destination?.list, forKey: "listarray")
    UserDefaults.standard.synchronize()

You should instead:

let newEntry = textfield.text!
let defaults = UserDefaults.standard
if destination?.list.count == 3 {  //3 because you hardcoded 3 items in next controller
      destination?.list.append(newEntry)
} else {
      let obj = defaults.object(forKey: "listarray") as? [String] ?? [String]()
      destination?.list = obj.append(newEntry)
}
defaults.set(destination?.list, forKey: "listarray")
UserDefaults.standard.synchronize()


问:
Hangfire Error `Connection string is missing for the SQL error log
I am busy trying to add hangfire to my MVC project. I am following the Quick Start Guide

I have added this to my startup.cs file

```<code>   public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);

        //Hangfire
        GlobalConfiguration.Configuration.UseSqlServerStorage("data source=ip;initial catalog=Name;user id=Hangfire;password=Password;");
        app.UseHangfireDashboard();
        app.UseHangfireServer();
    }
</code>```

However when I run my project I get the following error:  (it highlights the GlobalConfiguration.Configuration.UseSqlServerStorage line in my startup.cs class)

```<code>Connection string is missing for the SQL error log.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Elmah.ApplicationException: Connection string is missing for the SQL error log.
</code>```

答:
I believe you have your current logger as Elmah and Hangfire trying to pickup the Elmah logging to log the execution process of Hangfire jobs. If you look at the Elmah config and check if you have anything like <logger name="*" minlevel="Trace" writeTo="network" /> - here instead of * you can specify your application's Elmah logger name, so that Hangfire cannot use this. This solution is to avoid Hangfire logging to your application related log.

However if you wish to fix the issue you are facing, check the ELmah config and see if the required connection string is properly set.

Body:
I am busy trying to add hangfire to my MVC project. I am following the Quick Start Guide

I have added this to my startup.cs file

   public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);

        //Hangfire
        GlobalConfiguration.Configuration.UseSqlServerStorage("data source=ip;initial catalog=Name;user id=Hangfire;password=Password;");
        app.UseHangfireDashboard();
        app.UseHangfireServer();
    }

However when I run my project I get the following error:  (it highlights the GlobalConfiguration.Configuration.UseSqlServerStorage line in my startup.cs class)

Connection string is missing for the SQL error log.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Elmah.ApplicationException: Connection string is missing for the SQL error log.


问:
How to call a function, but not receive a response until there is a value?
I have a function that queries the DOM and returns an array of data attributes.

```<code>var getUIDs = function () {

    $list = $('.foo');

    if ( $list.length ) {

        // loop through all the .foos and build an array
        return fooArray;

    } else {

        setTimeout(function(){
            getUIDs()
        }, 500);

    }

}
</code>```

This function can sometimes be called prior to .foo being present in the DOM. That's why if I check every half second or so, within a few seconds the array will exist and I could send it back.

My question is, is there an established pattern I should follow that allows a function to be called, but will not receive a return value until there is one?

答:
MutationObserver

Here's a demonstration using MutationObserver – but it's pretty bare metal and awkward to interact with. If we want to use this, we'll want to make our own function to abstract away some of the complexity

var target =
  document.getElementById('main')

var observer =
  new MutationObserver(muts =>
    muts.forEach(m => console.log(m)))

observer.observe(target, {childList: true});

setTimeout(() => {
  var span1 = document.createElement('span')
  span1.textContent = 'cat'
  target.appendChild(span1)
}, 1000)

// { Mutation }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main"></div></code>```

taming MutationObserver into a sane API

We can make our own nextMutation function which takes a document query selector and returns a Promise of the next added child

const nextMutation = sel =>
  new Promise((resolve,_) => {
    const obs = new MutationObserver(muts => {
      for (const {addedNodes} of muts)
        if (addedNodes.length > 0) {
          resolve(addedNodes[0])
          obs.disconnect() // stop observing
          return           // stop iterating
        }
    })
    obs.observe(document.querySelector(sel), {childList: true})
  })

// demo mutation: add some element to #main in 1 second
setTimeout(() => {
  var span1 = document.createElement('span')
  span1.textContent = 'cat'
  document.querySelector('#main').appendChild(span1)
}, 1000)

nextMutation('#main')
  .then(child => console.log('added child', child)) // added child: cat
  .catch(console.error)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main"></div></code>```

timeout after waiting for too long

The above nextMutation will wait indefinitely until a child node is added to the target. What if we want to spit out an error if the child isn't added within X seconds? Of course we can augment our nextMutation function to do this

This code snippet also demonstrates that you can attach multiple observers to the same target. Below, an element is added to the target 1 second after domReady. The observer that waits up to 2 seconds will catch this mutation successfully – however, the observer that only waits .5 seconds will throw an error because it no mutation was observed

const nextMutation = sel =>
  new Promise((resolve, reject) => {
    const obs = new MutationObserver(muts => {
      for (const {addedNodes} of muts)
        if (addedNodes.length > 0) {
          resolve(addedNodes[0])
          obs.disconnect()
          return
        }
    })
    obs.observe(document.querySelector(sel), {childList: true})
  })

const awaitNextMutation = (sel, ms) =>
  Promise.race([
    nextMutation(sel),
    new Promise((_,reject) =>
      setTimeout(reject, ms, Error('awaitNextMutation timeout')))
  ])

// demo mutation: add some element to #main in 1 second
setTimeout(() => {
  var span1 = document.createElement('span')
  span1.textContent = 'cat'
  document.querySelector('#main').appendChild(span1)
}, 1000)

// wait for up to 2 seconds; since the child is added within
// 1 second, this promise will resolve just fine
awaitNextMutation('#main', 2000)
  .then(child => console.log('added child', child)) // added child: cat
  .catch(console.error)

// this one only waits 500 ms so an Error will throw
awaitNextMutation('#main', 500)
  .then(child => console.log('added child', child))
  .catch(console.error) // => Error awaitNextMutation timeout```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main"></div></code>```

Body:
I have a function that queries the DOM and returns an array of data attributes.

var getUIDs = function () {

    $list = $('.foo');

    if ( $list.length ) {

        // loop through all the .foos and build an array
        return fooArray;

    } else {

        setTimeout(function(){
            getUIDs()
        }, 500);

    }

}

This function can sometimes be called prior to .foo being present in the DOM. That's why if I check every half second or so, within a few seconds the array will exist and I could send it back.

My question is, is there an established pattern I should follow that allows a function to be called, but will not receive a return value until there is one?

Body:
MutationObserver

Here's a demonstration using MutationObserver – but it's pretty bare metal and awkward to interact with. If we want to use this, we'll want to make our own function to abstract away some of the complexity

var target =
  document.getElementById('main')

var observer =
  new MutationObserver(muts =>
    muts.forEach(m => console.log(m)))

observer.observe(target, {childList: true});

setTimeout(() => {
  var span1 = document.createElement('span')
  span1.textContent = 'cat'
  target.appendChild(span1)
}, 1000)

// { Mutation }

<div id="main"></div>

taming MutationObserver into a sane API

We can make our own nextMutation function which takes a document query selector and returns a Promise of the next added child

const nextMutation = sel =>
  new Promise((resolve,_) => {
    const obs = new MutationObserver(muts => {
      for (const {addedNodes} of muts)
        if (addedNodes.length > 0) {
          resolve(addedNodes[0])
          obs.disconnect() // stop observing
          return           // stop iterating
        }
    })
    obs.observe(document.querySelector(sel), {childList: true})
  })

// demo mutation: add some element to #main in 1 second
setTimeout(() => {
  var span1 = document.createElement('span')
  span1.textContent = 'cat'
  document.querySelector('#main').appendChild(span1)
}, 1000)

nextMutation('#main')
  .then(child => console.log('added child', child)) // added child: <span>cat</span>
  .catch(console.error)

<div id="main"></div>

timeout after waiting for too long

The above nextMutation will wait indefinitely until a child node is added to the target. What if we want to spit out an error if the child isn't added within X seconds? Of course we can augment our nextMutation function to do this

This code snippet also demonstrates that you can attach multiple observers to the same target. Below, an element is added to the target 1 second after domReady. The observer that waits up to 2 seconds will catch this mutation successfully – however, the observer that only waits .5 seconds will throw an error because it no mutation was observed

const nextMutation = sel =>
  new Promise((resolve, reject) => {
    const obs = new MutationObserver(muts => {
      for (const {addedNodes} of muts)
        if (addedNodes.length > 0) {
          resolve(addedNodes[0])
          obs.disconnect()
          return
        }
    })
    obs.observe(document.querySelector(sel), {childList: true})
  })

const awaitNextMutation = (sel, ms) =>
  Promise.race([
    nextMutation(sel),
    new Promise((_,reject) =>
      setTimeout(reject, ms, Error('awaitNextMutation timeout')))
  ])

// demo mutation: add some element to #main in 1 second
setTimeout(() => {
  var span1 = document.createElement('span')
  span1.textContent = 'cat'
  document.querySelector('#main').appendChild(span1)
}, 1000)

// wait for up to 2 seconds; since the child is added within
// 1 second, this promise will resolve just fine
awaitNextMutation('#main', 2000)
  .then(child => console.log('added child', child)) // added child: <span>cat</span>
  .catch(console.error)

// this one only waits 500 ms so an Error will throw
awaitNextMutation('#main', 500)
  .then(child => console.log('added child', child))
  .catch(console.error) // => Error awaitNextMutation timeout

<div id="main"></div>


问:
PHP methods outputting HTML with incorrect structure?
I have a strange situation that I've never encountered where the returned HTML from my class methods doesn't output in the correct structure. For some unknown reason, everything is nested inside the HTML within the first loop, second loop, etc.

index.php

```<code><body>
some html...
<div class="usb-port-container">
<?= $generate->output('short_name',id,'hostname'); ?>
</div>
some html...
<div class="usb-port-container">
<?= $generate->output('short_name',id,'hostname'); ?>
</div>
some html...
</body>
</code>```

class.generate.php

```<code>function __construct() {
    $this->getCopy = new getCopyData();
    $this->getDrive = new getDriveData();
    $this->helper = new helper();

}

function output ($short_name,$id,$hostname) {

    $portCount = $this->getCopy->portCount($hostname, 'total');

    for ($port = 0; $port < $portCount; ++$port) {
        if ($this->getCopy->probePort($hostname,$port)) {
            $default = $this->usbPortDefault($short_name,$id,$hostname,$port);

            return $default;
        } else {
            $details = $this->usbPortDetails($short_name,$id,$hostname,$port);

            return $details;
        }
    }
}

function usbPortDefault($short_name,$id,$hostname,$port) {

    $port_details =  '<div>
                        <div>----</div>
                        <div>----</div>
                    </div>';

    return $port_details;
}

function outputRecords($hostname,$port) {

    //get records data from database
    $records = $this->getCopy->records($hostname,$port);

    //create empty variable for HTML
    $records_html = "";

    foreach ($records as $key => $value) {
        if ($value) {
            $records_html .= '<div><span class="copy-group">' .$key. '</span><span class="copy-instance">' .$value. '</span></div>';
        } else {
            return '<div>Unable to get any group or instance</div>';
        }
    }

    return $records_html;
}

function usbPortDetails($short_name,$id,$hostname,$port) {

  $port_info = '';
  $port_info .= 'bunch of HTML';
  $port_info .= $this->outputRecords($hostname,$port);
  $port_info .= 'bunch of HTML';

  return $port_info;

}
</code>```

My best guess as to the problem, is that there is an issue with the way I am returning the HTML or something with output buffering. I actually don't know if I need it within my class, but I've taken it out and issue is the same. I've also tried adding output buffering to index.html.

Here is a snippet of the source HTML. The first discrepancy I notice is that the

 highlighted in blue doesn't belong there, it should be inside

 and adjacent to the prior

. After port-data-left should be port-data-right but it's nowhere to be found. I'm almost convinced at this point that there's a missing closing tag somewhere but I can't find it. It's been several years since I seriously did any development :D

EDIT: After further investigation, it appears that the final $port_info is not outputting and may be causing this problem. Is there an issue with $port_info .= $this->outputRecords($hostname,$port); being there?

答:
Since you reuse you object instance using $generate, the constructor and destructor methods are only called once in this script.

The constructor starts a new output buffer using ob_start(), which means everything outputted by the output method will be buffered until you flush it.

The issue is, the flush only happens in the destructor, with ob_end_flush(), which is only executed once, after the last output call.

Because you echo the result of the method and start a buffer at the same time, the output must indeed be weird and some nesting / repetition occurs because the next output still adds to the buffer.

As pointed out in the comment, the easiest solution is to turn off the output buffering in the class.

You also need to clear $port_info at the beginning of the method to make this work, although it should be fine, unless $port_info is a global var?

This was probably not cleared in the initial Class in order to make it work when called several times, to concatenate the results (and buffer them, before outputting them all at once)

A good usage of buffers in the middle of a page is to redirect the output of a function to a variable.

For example, you could have a function that echoes code but you don't want it echoed.

You could then do something like:

```<code>Some HTML
<?php
ob_start();
call_to_some_function_that_normally_outputs_code();
$myvar = ob_get_clean();
?>
Rest of the HTML
</code>```

Body:
I have a strange situation that I've never encountered where the returned HTML from my class methods doesn't output in the correct structure. For some unknown reason, everything is nested inside the HTML within the first loop, second loop, etc.

index.php

some html...

<?= $generate->output('short_name',id,'hostname'); ?>

some html...

<?= $generate->output('short_name',id,'hostname'); ?>

some html...

class.generate.php

function __construct() {
    $this->getCopy = new getCopyData();
    $this->getDrive = new getDriveData();
    $this->helper = new helper();

}

function output ($short_name,$id,$hostname) {

    $portCount = $this->getCopy->portCount($hostname, 'total');

    for ($port = 0; $port < $portCount; ++$port) {
        if ($this->getCopy->probePort($hostname,$port)) {
            $default = $this->usbPortDefault($short_name,$id,$hostname,$port);

            return $default;
        } else {
            $details = $this->usbPortDetails($short_name,$id,$hostname,$port);

            return $details;
        }
    }
}

function usbPortDefault($short_name,$id,$hostname,$port) {

    $port_details =  '

----

----

';

    return $port_details;
}

function outputRecords($hostname,$port) {

    //get records data from database
    $records = $this->getCopy->records($hostname,$port);

    //create empty variable for HTML
    $records_html = "";

    foreach ($records as $key => $value) {
        if ($value) {
            $records_html .= '
' .$key. '' .$value. '
';
        } else {
            return '
Unable to get any group or instance
';
        }
    }

    return $records_html;
}

function usbPortDetails($short_name,$id,$hostname,$port) {

  $port_info = '';
  $port_info .= 'bunch of HTML';
  $port_info .= $this->outputRecords($hostname,$port);
  $port_info .= 'bunch of HTML';

  return $port_info;

}

My best guess as to the problem, is that there is an issue with the way I am returning the HTML or something with output buffering. I actually don't know if I need it within my class, but I've taken it out and issue is the same. I've also tried adding output buffering to index.html.

Here is a snippet of the source HTML. The first discrepancy I notice is that the

 highlighted in blue doesn't belong there, it should be inside

 and adjacent to the prior

. After port-data-left should be port-data-right but it's nowhere to be found. I'm almost convinced at this point that there's a missing closing tag somewhere but I can't find it. It's been several years since I seriously did any development :D

EDIT: After further investigation, it appears that the final $port_info is not outputting and may be causing this problem. Is there an issue with $port_info .= $this->outputRecords($hostname,$port); being there?

Body:
Since you reuse you object instance using $generate, the constructor and destructor methods are only called once in this script.

The constructor starts a new output buffer using ob_start(), which means everything outputted by the output method will be buffered until you flush it.

The issue is, the flush only happens in the destructor, with ob_end_flush(), which is only executed once, after the last output call.

Because you echo the result of the method and start a buffer at the same time, the output must indeed be weird and some nesting / repetition occurs because the next output still adds to the buffer.

As pointed out in the comment, the easiest solution is to turn off the output buffering in the class.

You also need to clear $port_info at the beginning of the method to make this work, although it should be fine, unless $port_info is a global var?

This was probably not cleared in the initial Class in order to make it work when called several times, to concatenate the results (and buffer them, before outputting them all at once)

A good usage of buffers in the middle of a page is to redirect the output of a function to a variable.

For example, you could have a function that echoes code but you don't want it echoed.

You could then do something like:

Some HTML
<?php
ob_start();
call_to_some_function_that_normally_outputs_code();
$myvar = ob_get_clean();
?>
Rest of the HTML


问:
google map Cannot read property 'open' of undefined

$(document).on("click", "#searchRankingLocation", function() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 37.402040,
            lng: 127.107296
        }, //usepace
        zoom: 7
    });
    for (var i = 0; i < locationList.length; i++) {
        markers[i] = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: locationList[i],
            title: rankingInfoList[i].name
        });
        infoList[i] = 'this area will changed.'

        windowNames[i] = new google.maps.InfoWindow({
            content: infoList[i]
        });
        google.maps.event.addListener(markers[i], 'click', function() {
            windowNames[i].open(map, markers[i]);
        });

    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script></code>```

This is my source.

I can't show you windows, I tried to find a lot of solution but they did not help me!

答:
In your original code, the var i essentially makes the i variables scope outside of the loop, therefore by the time the click event happens, i would be locationList.length - so, obviously windowNames[i] would be undefined

3 ways to overcome this

using a function (I called it doInfo in this code )

```<code>$(document).on("click", "#searchRankingLocation", function() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 37.402040,
            lng: 127.107296
        }, //usepace
        zoom: 7
    });
    function doInfo(marker, windowName) {
        google.maps.event.addListener(marker, 'click', function() {
            windowName.open(map, marker);
        });
    }
    for (var i = 0; i < locationList.length; i++) {
        markers[i] = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: locationList[i],
            title: rankingInfoList[i].name
        });
        infoList[i] = 'this area will changed.'

        windowNames[i] = new google.maps.InfoWindow({
            content: infoList[i]
        });
        doInfo(markers[i], windowNames[i]);
    }
});
</code>```

in this case, the function receives the current marker/windowName, so the value of i is now irrelevant

using an IIFE (Immediately invoked function expression)

```<code>$(document).on("click", "#searchRankingLocation", function() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 37.402040,
            lng: 127.107296
        }, //usepace
        zoom: 7
    });
    for (var i = 0; i < locationList.length; i++) {
        markers[i] = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: locationList[i],
            title: rankingInfoList[i].name
        });
        infoList[i] = 'this area will changed.'

        windowNames[i] = new google.maps.InfoWindow({
            content: infoList[i]
        });
        (function(x) { // the IIFE
            google.maps.event.addListener(markers[x], 'click', function() {
                windowNames[x].open(map, markers[x]);
            });

        })(i); //pass in the current value of i, used as x in the body of the IIFE
    }
});
</code>```

This is very similar to the first case, just that the function is "inline" so could be considered more readable by some - x is the "captured" value of i for each iteration - alternatively you could also do

```<code>        (function(marker, windowName) { // the IIFE
            google.maps.event.addListener(marker, 'click', function() {
                windowName.open(map, marker);
            });

        })(markers[i], windowNames[i]);
</code>```

So, you can see how this is almost identical to the first answer

Using ES2015 let - this will only work (without transpiling) in modern browsers (so, forget internet explorer)

```<code>$(document).on("click", "#searchRankingLocation", function() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 37.402040,
            lng: 127.107296
        }, //usepace
        zoom: 7
    });
    for (let i = 0; i < locationList.length; i++) {
        markers[i] = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: locationList[i],
            title: rankingInfoList[i].name
        });
        infoList[i] = 'this area will changed.'

        windowNames[i] = new google.maps.InfoWindow({
            content: infoList[i]
        });
        google.maps.event.addListener(markers[i], 'click', function() {
            windowNames[i].open(map, markers[i]);
        });
    }
});
</code>```

let i means that each iteration of the loop, the value of i is "captured" for that iteration

again, this can also be done as:

```<code>        // ...
        let marker = markers[i];
        let windowName = windowNames[i];

        google.maps.event.addListener(marker, 'click', function() {
            windowName.open(map, marker);
        });
        // ...
</code>```

So, you can see all methods are identical in end result when it comes down to it

Body:
$(document).on("click", "#searchRankingLocation", function() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 37.402040,
            lng: 127.107296
        }, //usepace
        zoom: 7
    });
    for (var i = 0; i < locationList.length; i++) {
        markers[i] = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: locationList[i],
            title: rankingInfoList[i].name
        });
        infoList[i] = 'this area will changed.'

        windowNames[i] = new google.maps.InfoWindow({
            content: infoList[i]
        });
        google.maps.event.addListener(markers[i], 'click', function() {
            windowNames[i].open(map, markers[i]);
        });

    }
});

This is my source.

I can't show you windows, I tried to find a lot of solution but they did not help me!

Body:
In your original code, the var i essentially makes the i variables scope outside of the loop, therefore by the time the click event happens, i would be locationList.length - so, obviously windowNames[i] would be undefined

3 ways to overcome this

using a function (I called it doInfo in this code )

$(document).on("click", "#searchRankingLocation", function() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 37.402040,
            lng: 127.107296
        }, //usepace
        zoom: 7
    });
    function doInfo(marker, windowName) {
        google.maps.event.addListener(marker, 'click', function() {
            windowName.open(map, marker);
        });
    }
    for (var i = 0; i < locationList.length; i++) {
        markers[i] = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: locationList[i],
            title: rankingInfoList[i].name
        });
        infoList[i] = 'this area will changed.'

        windowNames[i] = new google.maps.InfoWindow({
            content: infoList[i]
        });
        doInfo(markers[i], windowNames[i]);
    }
});

in this case, the function receives the current marker/windowName, so the value of i is now irrelevant

using an IIFE (Immediately invoked function expression)

$(document).on("click", "#searchRankingLocation", function() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 37.402040,
            lng: 127.107296
        }, //usepace
        zoom: 7
    });
    for (var i = 0; i < locationList.length; i++) {
        markers[i] = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: locationList[i],
            title: rankingInfoList[i].name
        });
        infoList[i] = 'this area will changed.'

        windowNames[i] = new google.maps.InfoWindow({
            content: infoList[i]
        });
        (function(x) { // the IIFE
            google.maps.event.addListener(markers[x], 'click', function() {
                windowNames[x].open(map, markers[x]);
            });

        })(i); //pass in the current value of i, used as x in the body of the IIFE
    }
});

This is very similar to the first case, just that the function is "inline" so could be considered more readable by some - x is the "captured" value of i for each iteration - alternatively you could also do

        (function(marker, windowName) { // the IIFE
            google.maps.event.addListener(marker, 'click', function() {
                windowName.open(map, marker);
            });

        })(markers[i], windowNames[i]);

So, you can see how this is almost identical to the first answer

Using ES2015 let - this will only work (without transpiling) in modern browsers (so, forget internet explorer)

$(document).on("click", "#searchRankingLocation", function() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 37.402040,
            lng: 127.107296
        }, //usepace
        zoom: 7
    });
    for (let i = 0; i < locationList.length; i++) {
        markers[i] = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: locationList[i],
            title: rankingInfoList[i].name
        });
        infoList[i] = 'this area will changed.'

        windowNames[i] = new google.maps.InfoWindow({
            content: infoList[i]
        });
        google.maps.event.addListener(markers[i], 'click', function() {
            windowNames[i].open(map, markers[i]);
        });
    }
});

let i means that each iteration of the loop, the value of i is "captured" for that iteration

again, this can also be done as:

        // ...
        let marker = markers[i];
        let windowName = windowNames[i];

        google.maps.event.addListener(marker, 'click', function() {
            windowName.open(map, marker);
        });
        // ...

So, you can see all methods are identical in end result when it comes down to it


问:
Using jQuery AJAX to communicate with server, can I set a cookie/session?
In my example, I am sending login details to a server-side script via AJAX that in turn sets a session/cookie variable.

My question is will the cookie/session be set after I get a response, or do I actually have to visit the server-side script the regular way to set them?

Thanks!

答: Yes. Your cookie/session will be set. You can try it by send another request.</p>


问:
How to remove all characters not inside parentheses using regex
I have a string that contains commas both inside and outside of a parentheses block:
    foo(bat,foo),bat

How can I use regex to replace the comma not inside parentheses?
                                                                  foo(bat,foo)bat

答:
Assuming that there are no nested parentheses and there are no invalid pairings of parentheses, you can do this with a regex based on the fact that a comma will only be outside a pair of parentheses if and only if there are an even number of ( and ) symbols that follow it. Thus, you can use a lookahead regex to achieve this.

```<code>,(?![^(]*\))
</code>```

If there are nested parentheses, it becomes a context-free grammar and you cannot capture this with a regular expression alone. You are better off just using split methods.

example:

```<code>import re
ori_str = "foo(bat,foo),bat  foo(bat,foo),bat";
rep_str = re.sub(r',(?![^(]*\))', '', ori_str)
print(rep_str)
</code>```

Body:
Assuming that there are no nested parentheses and there are no invalid pairings of parentheses, you can do this with a regex based on the fact that a comma will only be outside a pair of parentheses if and only if there are an even number of ( and ) symbols that follow it. Thus, you can use a lookahead regex to achieve this.

,(?![^(]*\))

If there are nested parentheses, it becomes a context-free grammar and you cannot capture this with a regular expression alone. You are better off just using split methods.

example:

import re
ori_str = "foo(bat,foo),bat  foo(bat,foo),bat";
rep_str = re.sub(r',(?![^(]*\))', '', ori_str)
print(rep_str)


问:
Generic jquery function for cascading dropdownlists (asp.net mvc)
I'm working on a medical appointment system and I'm using a jquery function to filter the items in my cascading dropdownlists. Is there a way of writing a 'generic' to handle all the dropdownlists instead of writing the same thing several times?

 $(document).ready(function () {
            $('#ddlIl').change(function () {
                $.ajax({
                    type: "post",
                    url: "/Users/GetIlce",
                    data: { Id: $('#ddlIl').val() },
                    datatype: "json",
                    traditional: true,
                    success: function (data) {
                        var ilce = "<select id='ddlIlce'>";
                        ilce = ilce + '<option value="">--Seçin--</option>';
                        for (var i = 0; i < data.length; i++) {
                            ilce = ilce + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
                        }
                        ilce = ilce + '</select>';
                        $('#ddlIlce').html(ilce);
                    }
                });
            });
        });```

I have the following dropdownlists: State, City, Department, Hospital, and Doctor

答:
If you want to wrap the AJAX call in a function to serve all dropdownlists in view, probably this code below apply for them:

```<code>/*
 *  @param url = URL to fetch data (i.e. controller action method
 *               returning IEnumerable<SelectListItem> or SelectList)
 *  @param source = source dropdownlist name
 *  @param target = target dropdownlist name
 */
function cascadeDropDownList(url, source, target) {
    $.ajax({
        type: 'POST',
        url: url,
        data: { Id: $('#' + source).val() },
        dataType: 'json',
        traditional: true,
        success: function (data) {
            // remove previous option contents first
            $('#' + target + ' option').each(function() {
                $(this).remove();
            });

            // add new option contents
            var options = '<option value="">--Seçin--</option>';
            for (var i = 0; i < data.length; i++) {
                options += '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
            }
            $('#' + target).html(options);
        }
    });
}
</code>```

Usage in change event:

```<code>$(document).ready(function () {
    $('#ddlIl').change(function () {
        var url = '/Users/GetIlce'; // recommended: '@Url.Action("GetIlce", "Users")'
        var source = $(this).attr('id');
        cascadeDropDownList(url, source, 'ddlIlce');
    });
});
</code>```

NB: The function above assumes target dropdownlist has already created in view page and you just want to insert option element values without recreating select element. If you want to create new target dropdownlist instead, modify the function like below:

```<code>/*
 *  @param url = URL to fetch data (i.e. controller action method
 *               returning IEnumerable<SelectListItem> or SelectList)
 *  @param source = source dropdownlist name
 *  @param target = target element (e.g. div)
 *  @param ddlName = target dropdownlist name
 */
function cascadeDropDownList(url, source, target, ddlName) {
    $.ajax({
        type: 'POST',
        url: url,
        data: { Id: $('#' + source).val() },
        dataType: 'json',
        traditional: true,
        success: function (data) {
            var ddl = "<select id='" + ddlName + "'>";
            ddl += '<option value="">--Seçin--</option>';
            for (var i = 0; i < data.length; i++) {
                ddl += '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
            }
            ddl += '</select>';
            $('#' + target).html(ddl);
        }
    });
}
</code>```

Usage:

```<code>$(document).ready(function () {
    $('#ddlIl').change(function () {
        var url = '/Users/GetIlce'; // recommended: '@Url.Action("GetIlce", "Users")'
        var source = $(this).attr('id');
        var target = $('#targetdiv').attr('id');
        cascadeDropDownList(url, source, target, 'ddlIlce');
    });
});
</code>```

Working example: .NET Fiddle

Body:
I'm working on a medical appointment system and I'm using a jquery function to filter the items in my cascading dropdownlists. Is there a way of writing a 'generic' to handle all the dropdownlists instead of writing the same thing several times?

 $(document).ready(function () {
            $('#ddlIl').change(function () {
                $.ajax({
                    type: "post",
                    url: "/Users/GetIlce",
                    data: { Id: $('#ddlIl').val() },
                    datatype: "json",
                    traditional: true,
                    success: function (data) {
                        var ilce = "<select id='ddlIlce'>";
                        ilce = ilce + '<option value="">--Seçin--</option>';
                        for (var i = 0; i < data.length; i++) {
                            ilce = ilce + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
                        }
                        ilce = ilce + '</select>';
                        $('#ddlIlce').html(ilce);
                    }
                });
            });
        });

I have the following dropdownlists: State, City, Department, Hospital, and Doctor

Body:
If you want to wrap the AJAX call in a function to serve all dropdownlists in view, probably this code below apply for them:

/*
 *  @param url = URL to fetch data (i.e. controller action method
 *               returning IEnumerable<SelectListItem> or SelectList)
 *  @param source = source dropdownlist name
 *  @param target = target dropdownlist name
 */
function cascadeDropDownList(url, source, target) {
    $.ajax({
        type: 'POST',
        url: url,
        data: { Id: $('#' + source).val() },
        dataType: 'json',
        traditional: true,
        success: function (data) {
            // remove previous option contents first
            $('#' + target + ' option').each(function() {
                $(this).remove();
            });

            // add new option contents
            var options = '<option value="">--Seçin--</option>';
            for (var i = 0; i < data.length; i++) {
                options += '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
            }
            $('#' + target).html(options);
        }
    });
}

Usage in change event:

$(document).ready(function () {
    $('#ddlIl').change(function () {
        var url = '/Users/GetIlce'; // recommended: '@Url.Action("GetIlce", "Users")'
        var source = $(this).attr('id');
        cascadeDropDownList(url, source, 'ddlIlce');
    });
});

NB: The function above assumes target dropdownlist has already created in view page and you just want to insert option element values without recreating select element. If you want to create new target dropdownlist instead, modify the function like below:

/*
 *  @param url = URL to fetch data (i.e. controller action method
 *               returning IEnumerable<SelectListItem> or SelectList)
 *  @param source = source dropdownlist name
 *  @param target = target element (e.g. div)
 *  @param ddlName = target dropdownlist name
 */
function cascadeDropDownList(url, source, target, ddlName) {
    $.ajax({
        type: 'POST',
        url: url,
        data: { Id: $('#' + source).val() },
        dataType: 'json',
        traditional: true,
        success: function (data) {
            var ddl = "<select id='" + ddlName + "'>";
            ddl += '<option value="">--Seçin--</option>';
            for (var i = 0; i < data.length; i++) {
                ddl += '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
            }
            ddl += '</select>';
            $('#' + target).html(ddl);
        }
    });
}

Usage:

$(document).ready(function () {
    $('#ddlIl').change(function () {
        var url = '/Users/GetIlce'; // recommended: '@Url.Action("GetIlce", "Users")'
        var source = $(this).attr('id');
        var target = $('#targetdiv').attr('id');
        cascadeDropDownList(url, source, target, 'ddlIlce');
    });
});

Working example: .NET Fiddle


问:
PHP mail() function not working despite confirmation
I have created a form that allows people to send an email from a website. The HTML code (see attached) calls a PHP script (see attached), and the email is supposed to be sent. The webpage displays the message "Email successfully sent", but I never actually received the email (it's not in spam either).

I have reached out to my hosting service (awaiting reply) to check whether PHP is supported or not. In the meantime, I would like to ensure that my code has no errors.

HTML:

```<code><form action="message.php" method="post">
    <fieldset>
        <p>Name <span class="requiredAsterisk">*</span></p>
        <input name="name"/>
        <p>Email <span class="requiredAsterisk">*</span></p>
        <input name="email"/>
        <p>Message <span class="requiredAsterisk">*</span></p>
        <textarea name="message"></textarea>
    </fieldset>
    <fieldset>
        <input class="sendMessage w3-large" type="submit" value="Send Message"/>
    </fieldset>
  </form>
</code>```

PHP:

```<code><?php
$header = 'From: ' .$_POST['name'] ."\r\n" .'Reply-to: ' .$_POST['email'] ."\r\n" .'X-Mailer: PHP/' .phpversion();
if (mail("email@mail.com", "Email from website", $_POST['message'], $header)) {
    echo ("<p>Email successfully sent</p>");
} else {
    echo ("<p>Email failed</p>");
}
?>
</code>```

Thanks in advance

答:
(I would probably comment this, but my rep is too low) You should use
$message = wordwrap($_POST['message'], 70, "\r\n"); so your message follows the documentation on mail(). Besides this, your code seems to be fine. As you mentioned, it is probably related to your hosting provider, as it is common place for them to block the mail function. Also see this question on it for some extras which may the cause of your problem.

Body:
I have created a form that allows people to send an email from a website. The HTML code (see attached) calls a PHP script (see attached), and the email is supposed to be sent. The webpage displays the message "Email successfully sent", but I never actually received the email (it's not in spam either).

I have reached out to my hosting service (awaiting reply) to check whether PHP is supported or not. In the meantime, I would like to ensure that my code has no errors.

HTML:

<form action="message.php" method="post">
    <fieldset>

Name *

        <input name="name"/>

Email *

        <input name="email"/>

Message *

        <textarea name="message"></textarea>
    </fieldset>
    <fieldset>
        <input class="sendMessage w3-large" type="submit" value="Send Message"/>
    </fieldset>
  </form>

PHP:

<?php
$header = 'From: ' .$_POST['name'] ."\r\n" .'Reply-to: ' .$_POST['email'] ."\r\n" .'X-Mailer: PHP/' .phpversion();
if (mail("email@mail.com", "Email from website", $_POST['message'], $header)) {
    echo ("
Email successfully sent
");
} else {
    echo ("
Email failed
");
}
?>

Thanks in advance


问:
Squirrel client not opening
I have been using Squirrel SQL client to access Vertica (on a Windows 7 machine). It was working fine until last week but I am unable to open the Squirrel anymore and it throws an error

```<code>    "error occurred initializing plugin: oracle".
</code>```

I haven't installed any additional plugins and this has been working fine until last week. Can someone let me know how to debug this error?

答:
Delete codecompletionprefs.xml file, hope it will be better. My problem has been solved.
C:\Users[Your user name].squirrel-sql\plugins\codecompletion</p>

Title: Squirrel client not opening

Body:
I have been using Squirrel SQL client to access Vertica (on a Windows 7 machine). It was working fine until last week but I am unable to open the Squirrel anymore and it throws an error

    "error occurred initializing plugin: oracle".

I haven't installed any additional plugins and this has been working fine until last week. Can someone let me know how to debug this error?


问:
docker run long time make cache connection timedout
I built my app with docker-compose , one container is database use mariadb image ,one php to run Laravel (I installed php-memcached or php-redis extension for my app), one cache container built on redis  docker image .
at first everything goes on well , but after running 2 or 3 days , I got  the php exception : Connection timed out [tcp://redis:6379];
I monitor the cpu and memory and network use zabbix installed by myself on host server , but I got these error :

monitor CPU

monitor memory

I changed cache container to memcached and 2 or 3 days same thing happen,
the only way I found to solve this problem  is to restart system , and it can run another 2 or 3 days before getting the same error. you know it's not possible to restart system on production, so any one can suggest me where to solve the problem other than restarting system ?
Thanks!

答:
I think you are facing problem with redis docker container. This type of error comes when memory is exhausted. You need to set max memory parameter of redis server.

Advice: Please try to use another image of redis.


问:
Full background image not displaying on mobile device
The full background image isn't displaying properly on mobile. How can I have the full background image display?

```<code>body {
background-color: #000;
background-image: url(http://godwellontheloose.com/IMG_0463bwssww.jpg);
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

a {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}
</code>```

答:
Define the HTML and body to be 100% height and width first.

```<code>html,body{width:100%; height:100%;}
</code>```

Once this is added any element set to 100% height will show it at 100% height. A working example is below, run the code and click on full screen.

html,body{width:100%; height:100%;}
body{margin:0px; padding:0px;}
.background{background-image:url('https://media-cdn.tripadvisor.com/media/photo-s/0e/85/48/e6/seven-mile-beach-grand.jpg');width:100%; height:100%;
background-color: #000;
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="background"></div></code>```

Body:
The full background image isn't displaying properly on mobile. How can I have the full background image display?

body {
background-color: #000;
background-image: url(http://godwellontheloose.com/IMG_0463bwssww.jpg);
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

a {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}

Body:
Define the HTML and body to be 100% height and width first.

html,body{width:100%; height:100%;}

Once this is added any element set to 100% height will show it at 100% height. A working example is below, run the code and click on full screen.

html,body{width:100%; height:100%;}
body{margin:0px; padding:0px;}
.background{background-image:url('https://media-cdn.tripadvisor.com/media/photo-s/0e/85/48/e6/seven-mile-beach-grand.jpg');width:100%; height:100%;
background-color: #000;
background-repeat: no-repeat;
background-position: center;
background-attachment: fixed;
webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

<div class="background"><a href="#test"></a></div>


问:
Having trouble displaying output
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that where among 4 numbers the largest is outputted. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.

HTML

```<code><html>
<head>
  <meta charset="UTF-8">
  <script src="Main.js" type="text/javascript"></script>
  <link href="Main.css" rel="stylesheet" type="text/css"/>
</head>
<body>

    <form id="Awesome">
            <label>Input Numbers Here: </label><input type="text"
id="txtBox">
            <br><br>
            <label>Dec to Roman #: </label><input type="text" id="Results">
            <br><br>
            <input type="button" value="Calculate" id="Execute"
onclick="largestOfFour()">
    </form>

</body>
</html>
</code>```

Javascript

```<code>function largestOfFour(arr) {
var largestNumbers = [];
var currentLargest;
for (var x =0; x <arr.length; x++) {
    currentLargest = 0;
    for (var y = 0; y < arr [x].length; y++) {
        if (arr[x][y] > currentLargest) {
            currentLargest = arr[x][y];
        }
    }
    largestNumbers.push(currentLargest);
}
return largestNumbers;

document.getElementById('Results').value = largestNumbers;

}
</code>```

答:
After entering the numbers in an input box, we can read its value as a string. Splitting that string with a space give us the numbers array. We will compare each number in that array to each other and save the biggest number in largest. Then we display its value in a Result box.

function largestOfFour() {
  // get string from the input
  var s = document.getElementById('txtBox').value;
  var numbers = s.split(' ');
  var largest = 0;
  for (var x = 0; x < numbers.length; x++) {
    var current = parseInt(numbers[x])
    if (current > largest)
      largest = current;
  }
  // display the largest number
  document.getElementById('Results').value = largest;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="Awesome">
  <label>Input 4 Numbers (space separated): </label>
  <input type="text" id="txtBox">
  <br><br>
  <label>Max #: </label>
  <input type="text" id="Results" readonly>
  <br><br>
  <input type="button" value="Calculate" id="Execute" onclick="largestOfFour()">
</form></code>```

Title: Having trouble displaying output

Body:
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that where among 4 numbers the largest is outputted. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.

HTML

  <meta charset="UTF-8">

  <link href="Main.css" rel="stylesheet" type="text/css"/>

    <form id="Awesome">
            Input Numbers Here: <input type="text"
id="txtBox">

            Dec to Roman #: <input type="text" id="Results">

            <input type="button" value="Calculate" id="Execute"
onclick="largestOfFour()">
    </form>

Javascript

function largestOfFour(arr) {
var largestNumbers = [];
var currentLargest;
for (var x =0; x <arr.length; x++) {
    currentLargest = 0;
    for (var y = 0; y < arr [x].length; y++) {
        if (arr[x][y] > currentLargest) {
            currentLargest = arr[x][y];
        }
    }
    largestNumbers.push(currentLargest);
}
return largestNumbers;

document.getElementById('Results').value = largestNumbers;

}

Body:
After entering the numbers in an input box, we can read its value as a string. Splitting that string with a space give us the numbers array. We will compare each number in that array to each other and save the biggest number in largest. Then we display its value in a Result box.

function largestOfFour() {
  // get string from the input
  var s = document.getElementById('txtBox').value;
  var numbers = s.split(' ');
  var largest = 0;
  for (var x = 0; x < numbers.length; x++) {
    var current = parseInt(numbers[x])
    if (current > largest)
      largest = current;
  }
  // display the largest number
  document.getElementById('Results').value = largest;
}

<form id="Awesome">
  <label>Input 4 Numbers (space separated): </label>
  <input type="text" id="txtBox">
  <br><br>
  <label>Max #: </label>
  <input type="text" id="Results" readonly>
  <br><br>
  <input type="button" value="Calculate" id="Execute" onclick="largestOfFour()">
</form>