问:
Set Proxy UserName and Password using Wininet in C#
This is my first question in Stack Overflow. I have had great help from this site.

I am working on an application in C# on .NET 2010. I am trying to set system wide proxy server for http requests.
Proxy Server is a Squid based proxy with "basic" authentication enabled.
I have been able to set the proxy of IE.

Now after proxy is set in IE, IE asks for username and password for proxy, and now I am trying to automate this functionality, and for last 1 week I have been unable to get it working and have been searching internet but still no success.

Below is the code I am using to set IE proxy.

```<code>public static bool SetProxy(string strProxy, string username, string password, string exceptions)
    {

        InternetPerConnOptionList list = new InternetPerConnOptionList();

        int optionCount = string.IsNullOrEmpty(strProxy) ? 1 : (string.IsNullOrEmpty(exceptions) ? 2 : 3);
        InternetConnectionOption[] options = new InternetConnectionOption[optionCount];
        // USE a proxy server ...
        options[0].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
        options[0].m_Value.m_Int = (int)((optionCount < 2) ? PerConnFlags.PROXY_TYPE_DIRECT : (PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY));
        // use THIS proxy server
        if (optionCount > 1)
        {
            options[1].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER;
            options[1].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(strProxy);
            // except for these addresses ...
            if (optionCount > 2)
            {
                options[2].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_BYPASS;
                options[2].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(exceptions);
            }
        }

        // default stuff
        list.dwSize = Marshal.SizeOf(list);
        list.szConnection = IntPtr.Zero;
        list.dwOptionCount = options.Length;
        list.dwOptionError = 0;

        int optSize = Marshal.SizeOf(typeof(InternetConnectionOption));
        // make a pointer out of all that ...
        IntPtr optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length);
        // copy the array over into that spot in memory ...
        for (int i = 0; i < options.Length; ++i)
        {
            IntPtr opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize));
            Marshal.StructureToPtr(options[i], opt, false);
        }

        list.options = optionsPtr;

        // and then make a pointer out of the whole list
        IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((Int32)list.dwSize);
        Marshal.StructureToPtr(list, ipcoListPtr, false);

        // and finally, call the API method!
        int returnvalue = NativeMethods.InternetSetOption(IntPtr.Zero,
           InternetOption.INTERNET_OPTION_PER_CONNECTION_OPTION,
           ipcoListPtr, list.dwSize) ? -1 : 0;
        if (returnvalue == 0)
        {  // get the error codes, they might be helpful
            returnvalue = Marshal.GetLastWin32Error();
        }
        // FREE the data ASAP
        Marshal.FreeCoTaskMem(optionsPtr);
        Marshal.FreeCoTaskMem(ipcoListPtr);
        if (returnvalue > 0)
        {  // throw the error codes, they might be helpful
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        return (returnvalue < 0);
    }
}

#region WinInet structures
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct InternetPerConnOptionList
{
    public int dwSize;               // size of the INTERNET_PER_CONN_OPTION_LIST struct
    public IntPtr szConnection;         // connection name to set/query options
    public int dwOptionCount;        // number of options to set/query
    public int dwOptionError;           // on error, which option failed
    //[MarshalAs(UnmanagedType.)]
    public IntPtr options;
};

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct InternetConnectionOption
{
    static readonly int Size;
    public PerConnOption m_Option;
    public InternetConnectionOptionValue m_Value;
    static InternetConnectionOption()
    {
        InternetConnectionOption.Size = Marshal.SizeOf(typeof(InternetConnectionOption));
    }

    // Nested Types
    [StructLayout(LayoutKind.Explicit)]
    public struct InternetConnectionOptionValue
    {
        // Fields
        [FieldOffset(0)]
        public System.Runtime.InteropServices.ComTypes.FILETIME m_FileTime;
        [FieldOffset(0)]
        public int m_Int;
        [FieldOffset(0)]
        public IntPtr m_StringPtr;
    }
}
#endregion

#region WinInet enums
//
// options manifests for Internet{Query|Set}Option
//
public enum InternetOption : uint
{
    INTERNET_OPTION_PER_CONNECTION_OPTION = 75
}

//
// Options used in INTERNET_PER_CONN_OPTON struct
//
public enum PerConnOption
{
    INTERNET_PER_CONN_FLAGS = 1, // Sets or retrieves the connection type. The Value member will contain one or more of the values from PerConnFlags
    INTERNET_PER_CONN_PROXY_SERVER = 2, // Sets or retrieves a string containing the proxy servers.
    INTERNET_PER_CONN_PROXY_BYPASS = 3, // Sets or retrieves a string containing the URLs that do not use the proxy server.
    INTERNET_PER_CONN_AUTOCONFIG_URL = 4//, // Sets or retrieves a string containing the URL to the automatic configuration script.
}

//
// PER_CONN_FLAGS
//
[Flags]
public enum PerConnFlags
{
    PROXY_TYPE_DIRECT = 0x00000001,  // direct to net
    PROXY_TYPE_PROXY = 0x00000002,  // via named proxy
    PROXY_TYPE_AUTO_PROXY_URL = 0x00000004,  // autoproxy URL
    PROXY_TYPE_AUTO_DETECT = 0x00000008   // use autoproxy detection
}
#endregion

internal static class NativeMethods
{
    [DllImport("WinInet.dll", SetLastError = true, CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool InternetSetOption(IntPtr hInternet, InternetOption dwOption, IntPtr lpBuffer, int dwBufferLength);
}
</code>```

Any help in getting this functionality working would be greatly appreciated.

Regards,
Mudasir Mirza.

答:
I got the similar problem with WebBrowser control while dealing with authentication and irritating "Windows security" window. First, set proxy address with WinINET and then call navigate method with your credentials. It helps to store proxy credentials per one process:

```<code>WebBrowser.Navigate("http://user:pass@geoip.hidemyass.com/");
</code>```

WinINET method sets proxy address perfect, however your code uses INTERNET_OPTION_PER_CONNECTION_OPTION which is not suitable for your "global proxy" idea (as @EricLaw said). Try to work around with INTERNET_OPTION_PROXY (documentaion)

Furthermore there are four different approaches with no direct solution. But they are very handy.

Body:
This is my first question in Stack Overflow. I have had great help from this site.

I am working on an application in C# on .NET 2010. I am trying to set system wide proxy server for http requests.
Proxy Server is a Squid based proxy with "basic" authentication enabled.
I have been able to set the proxy of IE.

Now after proxy is set in IE, IE asks for username and password for proxy, and now I am trying to automate this functionality, and for last 1 week I have been unable to get it working and have been searching internet but still no success.

Below is the code I am using to set IE proxy.

public static bool SetProxy(string strProxy, string username, string password, string exceptions)
    {

        InternetPerConnOptionList list = new InternetPerConnOptionList();

        int optionCount = string.IsNullOrEmpty(strProxy) ? 1 : (string.IsNullOrEmpty(exceptions) ? 2 : 3);
        InternetConnectionOption[] options = new InternetConnectionOption[optionCount];
        // USE a proxy server ...
        options[0].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
        options[0].m_Value.m_Int = (int)((optionCount < 2) ? PerConnFlags.PROXY_TYPE_DIRECT : (PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY));
        // use THIS proxy server
        if (optionCount > 1)
        {
            options[1].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER;
            options[1].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(strProxy);
            // except for these addresses ...
            if (optionCount > 2)
            {
                options[2].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_BYPASS;
                options[2].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(exceptions);
            }
        }

        // default stuff
        list.dwSize = Marshal.SizeOf(list);
        list.szConnection = IntPtr.Zero;
        list.dwOptionCount = options.Length;
        list.dwOptionError = 0;

        int optSize = Marshal.SizeOf(typeof(InternetConnectionOption));
        // make a pointer out of all that ...
        IntPtr optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length);
        // copy the array over into that spot in memory ...
        for (int i = 0; i < options.Length; ++i)
        {
            IntPtr opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize));
            Marshal.StructureToPtr(options[i], opt, false);
        }

        list.options = optionsPtr;

        // and then make a pointer out of the whole list
        IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((Int32)list.dwSize);
        Marshal.StructureToPtr(list, ipcoListPtr, false);

        // and finally, call the API method!
        int returnvalue = NativeMethods.InternetSetOption(IntPtr.Zero,
           InternetOption.INTERNET_OPTION_PER_CONNECTION_OPTION,
           ipcoListPtr, list.dwSize) ? -1 : 0;
        if (returnvalue == 0)
        {  // get the error codes, they might be helpful
            returnvalue = Marshal.GetLastWin32Error();
        }
        // FREE the data ASAP
        Marshal.FreeCoTaskMem(optionsPtr);
        Marshal.FreeCoTaskMem(ipcoListPtr);
        if (returnvalue > 0)
        {  // throw the error codes, they might be helpful
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        return (returnvalue < 0);
    }
}

#region WinInet structures
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct InternetPerConnOptionList
{
    public int dwSize;               // size of the INTERNET_PER_CONN_OPTION_LIST struct
    public IntPtr szConnection;         // connection name to set/query options
    public int dwOptionCount;        // number of options to set/query
    public int dwOptionError;           // on error, which option failed
    //[MarshalAs(UnmanagedType.)]
    public IntPtr options;
};

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct InternetConnectionOption
{
    static readonly int Size;
    public PerConnOption m_Option;
    public InternetConnectionOptionValue m_Value;
    static InternetConnectionOption()
    {
        InternetConnectionOption.Size = Marshal.SizeOf(typeof(InternetConnectionOption));
    }

    // Nested Types
    [StructLayout(LayoutKind.Explicit)]
    public struct InternetConnectionOptionValue
    {
        // Fields
        [FieldOffset(0)]
        public System.Runtime.InteropServices.ComTypes.FILETIME m_FileTime;
        [FieldOffset(0)]
        public int m_Int;
        [FieldOffset(0)]
        public IntPtr m_StringPtr;
    }
}
#endregion

#region WinInet enums
//
// options manifests for Internet{Query|Set}Option
//
public enum InternetOption : uint
{
    INTERNET_OPTION_PER_CONNECTION_OPTION = 75
}

//
// Options used in INTERNET_PER_CONN_OPTON struct
//
public enum PerConnOption
{
    INTERNET_PER_CONN_FLAGS = 1, // Sets or retrieves the connection type. The Value member will contain one or more of the values from PerConnFlags
    INTERNET_PER_CONN_PROXY_SERVER = 2, // Sets or retrieves a string containing the proxy servers.
    INTERNET_PER_CONN_PROXY_BYPASS = 3, // Sets or retrieves a string containing the URLs that do not use the proxy server.
    INTERNET_PER_CONN_AUTOCONFIG_URL = 4//, // Sets or retrieves a string containing the URL to the automatic configuration script.
}

//
// PER_CONN_FLAGS
//
[Flags]
public enum PerConnFlags
{
    PROXY_TYPE_DIRECT = 0x00000001,  // direct to net
    PROXY_TYPE_PROXY = 0x00000002,  // via named proxy
    PROXY_TYPE_AUTO_PROXY_URL = 0x00000004,  // autoproxy URL
    PROXY_TYPE_AUTO_DETECT = 0x00000008   // use autoproxy detection
}
#endregion

internal static class NativeMethods
{
    [DllImport("WinInet.dll", SetLastError = true, CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool InternetSetOption(IntPtr hInternet, InternetOption dwOption, IntPtr lpBuffer, int dwBufferLength);
}

Any help in getting this functionality working would be greatly appreciated.

Regards,
Mudasir Mirza.

Body:
I got the similar problem with WebBrowser control while dealing with authentication and irritating "Windows security" window. First, set proxy address with WinINET and then call navigate method with your credentials. It helps to store proxy credentials per one process:

WebBrowser.Navigate("http://user:pass@geoip.hidemyass.com/");

WinINET method sets proxy address perfect, however your code uses INTERNET_OPTION_PER_CONNECTION_OPTION which is not suitable for your "global proxy" idea (as @EricLaw said). Try to work around with INTERNET_OPTION_PROXY (documentaion)

Furthermore there are four different approaches with no direct solution. But they are very handy.


来源: stackexchange

问:
What is the difference between sudo -s and sudo
I'm trying to start JupyterHub using the command sudo jupyterhub. This starts the server but the user is not able to login. But when I switch to the root user using sudo -s and then type jupyterhub, everything works perfectly.

What is the difference between running a command by typing sudo before it and switching to the root user using sudo -s and then running the command.

My main objective is to add this command to /etc/rc.local so that jupyterhub starts automatically on system startup and runs in background. Now how can I add sudo -s there?

答:
Let's say your default shell is zsh and root's shell is bash. When you run sudo -s sudo will launch a zsh rather than bash.

The default shell is configured in /etc/passwd. Please check man sudo.

ContentLicense: CC BY-SA 3.0


问:
How to compile multiple java source files in command line
I know running javac file1.java produces file1.class if file1.java is the only source file, then I can just say java file1 to run it.

However, if I have 2 source files, file1.java and file2.java, then how  do I build the program?

答:
Here is another example, for compiling a java file in a nested directory.

I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example.  -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.

Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'

```<code>% mkdir -p temp/classes
% curl --get \
    http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
        --output commons-collections-3.2.2.jar

% javac -g -classpath commons-collections-3.2.2.jar \
     -sourcepath src/main/java -d temp/classes \
      src/main/java/org/gradle/Person.java

% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
   0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
  69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is another example, for compiling a java file in a nested directory.

I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example.  -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.

Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'

% mkdir -p temp/classes
% curl --get \
    http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
        --output commons-collections-3.2.2.jar

% javac -g -classpath commons-collections-3.2.2.jar \
     -sourcepath src/main/java -d temp/classes \
      src/main/java/org/gradle/Person.java

% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
   0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
  69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
 519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class


问:
.net Core on Windows vs Linux
ASP.Net Core runs on both Windows and Linux Docker containers. Considering Linux hosts are cheaper than Windows hosts, what is the benefit of running your app on IIS/Windows vs Nginx/Linux if one doesn't require the full .Net framework?</p>

答:
There is no clear cut benefit. This is the same argument as why would you want to run rails, jboss, on other platforms. Since you are running the same app, there are not many considerations to account for. There are features in windows that you may wish to have such as dns caching. Of if you would prefer to use web listener, and not kestrel, but that would have to largely depend on what you are doing.

If you really care about your http transports, or which timezone database .net will use, then you can make such a determination. For most users, there is not a major benefit. If you wish to have AD login's then you pretty much have to use windows, and IIS, since you need a server that is part of the active directory domain.

Just remember, linux does have a free option, but most paid enterprise support for linux is usually the same, if not more expensive than windows.

Title: .net Core on Windows vs Linux


问:
Determine if path is inside another path in Go
I would like to delete all path components for a file up to (but not including) an overall base directory.

Example:
/overall/basedir/a/b/c/file

I want to remove "file" and then remove "c", "b" and then "a" if possible (directories not empty).  I do not want to unlink "basedir" or "overall".

filepath.HasPrefix would seem to be a good option but it's apparently deprecated: https://golang.org/pkg/path/filepath/#HasPrefix

What I have now is:

```<code>p := THEPATH

// attempt to remove file and all parent directories up to the basedir
// FIXME: HasPrefix is apparently bad.. a better idea?
for filepath.HasPrefix(p, baseDir) {
    err := os.Remove(p)
    if err != nil {
        break
    }
    // climb up one
    p = filepath.Dir(p)
}
</code>```

Looking for a succinct and reliable way that works on all Go supported platforms.

答:
IMHO, path handling is rather complicated if you want to support all platforms that is supported by golang. Bellow is the solution that I've implemented so far (probably not the simplest one). Notes:

It supports generalized action rather than only os.Remove

Instead of string-based path comparison, function os.SameFile is used to test whether two files/directories are equal.

In the implementation, at first all candidate paths are visited and added to visitedPaths slice. Then, if no error occurs, an action is perform to each candidate path.

The code:

```<code>package pathwalker

import (
    "os"
    "path/filepath"
    "strings"
)

type PathAction func(PathInfo) error
type PathInfo struct {
    FileInfo os.FileInfo
    FullPath string
}
type PathWalker struct {
    pathName     string
    basePath     string
    visitedPaths []PathInfo
    lastFi       os.FileInfo
}

//NewPathWalker creates PathWalker instance
func NewPathWalker(pathName, basePath string) *PathWalker {
    return &PathWalker{
        pathName: pathName,
        basePath: basePath,
    }
}

func (w *PathWalker) visit() (bool, error) {
    //Make sure path ends with separator
    basePath := filepath.Clean(w.basePath + string(filepath.Separator))
    baseInfo, err := os.Lstat(basePath)
    if err != nil {
        return false, err
    }

    //clean path name
    fi, err := os.Lstat(w.pathName)
    if err != nil {
        return false, err
    } else if fi.IsDir() {
        //When pathname is a directory, remove latest separator
        sep := string(filepath.Separator)
        cleanPath := filepath.Clean(w.pathName + sep)
        w.pathName = strings.TrimRight(cleanPath, sep)
    } else {
        w.pathName = filepath.Clean(w.pathName)
    }
    return w.doVisit(w.pathName, baseInfo)
}

//visit path recursively
func (w *PathWalker) doVisit(pathName string, baseInfo os.FileInfo) (bool, error) {
    //Get file info
    fi, err := os.Lstat(pathName)
    if err != nil {
        return false, err
    }

    //Stop when basePath equal to pathName
    if os.SameFile(fi, baseInfo) {
        return true, nil
    }

    //Top directory reached, but does not match baseInfo
    if w.lastFi != nil && os.SameFile(w.lastFi, fi) {
        return false, nil
    }
    w.lastFi = fi

    //Append to visited path list
    w.visitedPaths = append(w.visitedPaths, PathInfo{fi, pathName})

    //Move to upper path
    up := filepath.Dir(pathName)
    if up == "." {
        return false, nil
    }

    //Visit upper directory
    return w.doVisit(up, baseInfo)
}

//Walk perform action then return number of proceed paths and error
func (w *PathWalker) Walk(act PathAction) (int, error) {
    n := 0
    ok, err := w.visit()
    if err != nil {
        return 0, err
    } else if ok && act != nil {
        for _, pi := range w.visitedPaths {
            err := act(pi)
            if err != nil {
                return n, err
            }
            n++
        }
    }
    return n, nil
}

//VisitedPaths return list of visited paths
func (w *PathWalker) VisitedPaths() []PathInfo {
    return w.visitedPaths
}
</code>```

Then if you want to remove file and parent directory under basePath, you can do:

```<code>func remove(pathName, basePath string) {
    act := func(p pathwalker.PathInfo) error {
        if p.FileInfo.IsDir() {
            fmt.Printf("  Removing directory=%s\n", p.FullPath)
            return os.Remove(p.FullPath)
        }

        fmt.Printf("  Removing file=%s\n", p.FullPath)
        return os.Remove(p.FullPath)
    }

    pw := pathwalker.NewPathWalker(pathName, basePath)
    n, err := pw.Walk(act)
    fmt.Printf("Removed: %d/%d, err=%v\n", n, len(pw.VisitedPaths()), err)
}
</code>```

If you just want to test whether a path is inside another path, you can do:

```<code>n, err := pathwalker.NewPathWalker(fileName, basePath).Walk(nil)
if n > 0 && err != nil {
    //is inside another path
}
</code>```

Body:
I would like to delete all path components for a file up to (but not including) an overall base directory.

Example:
/overall/basedir/a/b/c/file

I want to remove "file" and then remove "c", "b" and then "a" if possible (directories not empty).  I do not want to unlink "basedir" or "overall".

filepath.HasPrefix would seem to be a good option but it's apparently deprecated: https://golang.org/pkg/path/filepath/#HasPrefix

What I have now is:

p := THEPATH

// attempt to remove file and all parent directories up to the basedir
// FIXME: HasPrefix is apparently bad.. a better idea?
for filepath.HasPrefix(p, baseDir) {
    err := os.Remove(p)
    if err != nil {
        break
    }
    // climb up one
    p = filepath.Dir(p)
}

Looking for a succinct and reliable way that works on all Go supported platforms.

Body:
IMHO, path handling is rather complicated if you want to support all platforms that is supported by golang. Bellow is the solution that I've implemented so far (probably not the simplest one). Notes:

It supports generalized action rather than only os.Remove

Instead of string-based path comparison, function os.SameFile is used to test whether two files/directories are equal.

In the implementation, at first all candidate paths are visited and added to visitedPaths slice. Then, if no error occurs, an action is perform to each candidate path.

The code:

package pathwalker

import (
    "os"
    "path/filepath"
    "strings"
)

type PathAction func(PathInfo) error
type PathInfo struct {
    FileInfo os.FileInfo
    FullPath string
}
type PathWalker struct {
    pathName     string
    basePath     string
    visitedPaths []PathInfo
    lastFi       os.FileInfo
}

//NewPathWalker creates PathWalker instance
func NewPathWalker(pathName, basePath string) *PathWalker {
    return &PathWalker{
        pathName: pathName,
        basePath: basePath,
    }
}

func (w *PathWalker) visit() (bool, error) {
    //Make sure path ends with separator
    basePath := filepath.Clean(w.basePath + string(filepath.Separator))
    baseInfo, err := os.Lstat(basePath)
    if err != nil {
        return false, err
    }

    //clean path name
    fi, err := os.Lstat(w.pathName)
    if err != nil {
        return false, err
    } else if fi.IsDir() {
        //When pathname is a directory, remove latest separator
        sep := string(filepath.Separator)
        cleanPath := filepath.Clean(w.pathName + sep)
        w.pathName = strings.TrimRight(cleanPath, sep)
    } else {
        w.pathName = filepath.Clean(w.pathName)
    }
    return w.doVisit(w.pathName, baseInfo)
}

//visit path recursively
func (w *PathWalker) doVisit(pathName string, baseInfo os.FileInfo) (bool, error) {
    //Get file info
    fi, err := os.Lstat(pathName)
    if err != nil {
        return false, err
    }

    //Stop when basePath equal to pathName
    if os.SameFile(fi, baseInfo) {
        return true, nil
    }

    //Top directory reached, but does not match baseInfo
    if w.lastFi != nil && os.SameFile(w.lastFi, fi) {
        return false, nil
    }
    w.lastFi = fi

    //Append to visited path list
    w.visitedPaths = append(w.visitedPaths, PathInfo{fi, pathName})

    //Move to upper path
    up := filepath.Dir(pathName)
    if up == "." {
        return false, nil
    }

    //Visit upper directory
    return w.doVisit(up, baseInfo)
}

//Walk perform action then return number of proceed paths and error
func (w *PathWalker) Walk(act PathAction) (int, error) {
    n := 0
    ok, err := w.visit()
    if err != nil {
        return 0, err
    } else if ok && act != nil {
        for _, pi := range w.visitedPaths {
            err := act(pi)
            if err != nil {
                return n, err
            }
            n++
        }
    }
    return n, nil
}

//VisitedPaths return list of visited paths
func (w *PathWalker) VisitedPaths() []PathInfo {
    return w.visitedPaths
}

Then if you want to remove file and parent directory under basePath, you can do:

func remove(pathName, basePath string) {
    act := func(p pathwalker.PathInfo) error {
        if p.FileInfo.IsDir() {
            fmt.Printf("  Removing directory=%s\n", p.FullPath)
            return os.Remove(p.FullPath)
        }

        fmt.Printf("  Removing file=%s\n", p.FullPath)
        return os.Remove(p.FullPath)
    }

    pw := pathwalker.NewPathWalker(pathName, basePath)
    n, err := pw.Walk(act)
    fmt.Printf("Removed: %d/%d, err=%v\n", n, len(pw.VisitedPaths()), err)
}

If you just want to test whether a path is inside another path, you can do:

n, err := pathwalker.NewPathWalker(fileName, basePath).Walk(nil)
if n > 0 && err != nil {
    //is inside another path
}


问:
wordpress count widgets
Hi I am trying to figure out as to how can we get the count of widgets published in a given sidebar position.

For example I have a sidebar called UTILITY which is a horizontal sidebar. I want the width of these widget positions to adjust equally according to the number of widgets published in it.

I want to know that on a given page how many widgets are published in this sidebar so that I can assign a width class according to it.

答: When you are building the sidebar, there should be a list containing the sidebar contents; you are iterating over it to add those items to the generated page.  Just use the count() function on this list to find the number of items you're displaying.

ContentLicense: CC BY-SA 2.5

Title: wordpress count widgets


问:
Extracting sub arrays from a two dimensional array for each element and displaying them in a table using KnockoutJS
I have used below code in PHP to extract data from MySQL :

```<code><?php
require("connect.php");
$sql = "SELECT `inn_lay_list`, `inner_layer` FROM `da_customer_auto_inner`
where `mpcode` = 'qf017'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result)) {
    $data1 = $row['inn_lay_list'];
    $data2 = $row['inner_layer'];
}

$parts1 = explode(';',$data1);
$parts2 = explode(';',$data2);
$layer_cnt = count($parts1);
$array_inner = array_chunk($parts2, 8);

echo json_encode($parts1);
echo json_encode($array_inner);

mysqli_close($conn);
?>
</code>```

I obtained the result as:

["001","011","021","031"]

[["1","2","3","4","5","6","7","8"], ["11","12","13","14","15","16","17","18"], ["21","22","23","24","25","26","27","28"],[31","32","33","34","35","36","37","38"]]

Here for each element in first array there is a sub array in the second array(two dimensional array).
Now I want to display this in HTML page using a table. I am trying to use KnockoutJS “foreach” option with a named template:

```<code><script>
function MyViewModel() {
    this.layer = [{
        name: "<?=@$parts1[0]?>",
        layer_data: "<?=@$array_inner[0]?>"
    },
    {
        name: "<?=@$parts1[1]?>",
        layer_data: "<?=@$array_inner[1]?>"
    },
    {
        name: "<?=@$parts1[2]?>",
        layer_data: "<?=@$array_inner[2]?>"
    },
    {
        name: "<?=@$parts1[3]?>",
        layer_data: "<?=@$array_inner[3]?>"
    }]
}
ko.applyBindings(new MyViewModel());
</script>

<table class="table table-bordered">
    <thead>
    <tr>
      <td>Layer</td>
      <td>P2P</td>
      <td>P2T</td>
      <td>T2T</td>
      <td>Track Width</td>
      <td>PTH To Cu</td>
      <td>NPTH To Cu</td>
      <td>PTH AR</td>
      <td>Via AR</td>
    </tr>
    </thead>
    <tbody data-bind="template:{name:'layer-template', foreach:layer}">
    </tbody>
</table>
<script type="text/html" id="layer-template">
<tr>
    <td data-bind="text: name"></td>
    <td data-bind="text: layer_data[0]"></td>
    <td data-bind="text: layer_data[1]"></td>
    <td data-bind="text: layer_data[2]"></td>
    <td data-bind="text: layer_data[3]"></td>
    <td data-bind="text: layer_data[4]"></td>
    <td data-bind="text: layer_data[5]"></td>
    <td data-bind="text: layer_data[6]"></td>
    <td data-bind="text: layer_data[7]"></td>
</tr>
</script>
</code>```

I want my output as below :

答: As you said in your question that array is in json format,So first of all you need to decode that json to array using json_decode(). then you can directly use $array[0].</p>

Body:
I have used below code in PHP to extract data from MySQL :

<?php
require("connect.php");
$sql = "SELECT `inn_lay_list`, `inner_layer` FROM `da_customer_auto_inner`
where `mpcode` = 'qf017'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result)) {
    $data1 = $row['inn_lay_list'];
    $data2 = $row['inner_layer'];
}

$parts1 = explode(';',$data1);
$parts2 = explode(';',$data2);
$layer_cnt = count($parts1);
$array_inner = array_chunk($parts2, 8);

echo json_encode($parts1);
echo json_encode($array_inner);

mysqli_close($conn);
?>

I obtained the result as:

["001","011","021","031"]

[["1","2","3","4","5","6","7","8"], ["11","12","13","14","15","16","17","18"], ["21","22","23","24","25","26","27","28"],[31","32","33","34","35","36","37","38"]]

Here for each element in first array there is a sub array in the second array(two dimensional array).
Now I want to display this in HTML page using a table. I am trying to use KnockoutJS “foreach” option with a named template:

      Layer
      P2P
      P2T
      T2T
      Track Width
      PTH To Cu
      NPTH To Cu
      PTH AR
      Via AR

I want my output as below :


问:
How to use IF in SELECT statement as a filter
I have simalary (but not identical) report which share the same tables and filters. Instead of writing invidual stored procedures, I'd like to create one and switch between SELECT datasets with a parameter accompanied with a filter.

I've tried something like:

```<code>IF @UseDataGroup = 1 --from ssrs
    BEGIN
    SELECT
        IF transaction_type IN (10, 27)
        .....
    END
IF @UseDataGroup = 2
    BEGIN
    SELECT
        IF transaction_type IN (11)
        .....
    END

    FROM

    WHERE
</code>```

..with unfortunately returns an error  'multi-part identifier transaction_type could not be bound'
Any help would be aprreciated. Thanks.

答:
A sample CASE statement

```<code>DECLARE @UseDataGroup INT
DECLARE @transaction_type INT

SET @UseDataGroup = 1
SET @transaction_type = 10

IF @UseDataGroup = 1 --from ssrs
    BEGIN
    SELECT
        CASE WHEN @transaction_type IN (10, 27)
        THEN 'Success'
        END
    END
</code>```

OR

```<code>SELECT
    CASE WHEN @transaction_type IN (10, 27) AND @UseDataGroup = 1
    THEN 'Success'
    END
</code>```

Body:
I have simalary (but not identical) report which share the same tables and filters. Instead of writing invidual stored procedures, I'd like to create one and switch between SELECT datasets with a parameter accompanied with a filter.

I've tried something like:

IF @UseDataGroup = 1 --from ssrs
    BEGIN
    SELECT
        IF transaction_type IN (10, 27)
        .....
    END
IF @UseDataGroup = 2
    BEGIN
    SELECT
        IF transaction_type IN (11)
        .....
    END

    FROM

    WHERE

..with unfortunately returns an error  'multi-part identifier transaction_type could not be bound'
Any help would be aprreciated. Thanks.

Body:
A sample CASE statement

DECLARE @UseDataGroup INT
DECLARE @transaction_type INT

SET @UseDataGroup = 1
SET @transaction_type = 10

IF @UseDataGroup = 1 --from ssrs
    BEGIN
    SELECT
        CASE WHEN @transaction_type IN (10, 27)
        THEN 'Success'
        END
    END

OR

SELECT
    CASE WHEN @transaction_type IN (10, 27) AND @UseDataGroup = 1
    THEN 'Success'
    END


问:
When to use an object or an array in javascript?
I just found out that Arrays inherit directly from Object in javascript.  I'm finding the difference between an array and an object is fairly minuscule.

How do i know when to use one over the other?

答:
They are just different data structures, they serve different purposes. Array extends Object and provides properties like length and methods like push() and pop().

Think of an object as a hash table and an array as a list.

E.g. you can use arrays as queue or as a stack which would not be possible with objects.

On the other side if you want to store data and want to access a specific datum directly, you would use an object.

In the end it boils down to the question which data structure is the right one for the job. Maybe neither of them is and you would need a tree instead (which can be implemented via objects).


问:
Node package that allows crawling of sites that requires javascript
So i've been searching endlessly for a package that allows crawling of javascript sites. I've been trying selenium but i don't like the whole browser deal.

Is there a solution similar to superagent and request where you do post & get requests, which also has javascript "enabled"?

答:
Take a look at scraperjs dynamicScraper function or phantomjs.
They both allow run js without loading whole browser.
And here an example for how to wait for some events on page </p>


问:
check child the given class in jquery
I want to check the parent div 'tabs' has the child with class 'nav-justified' in jquery .In my html block 'nav-justified' class is exist but shows 'class not exit' due to condition failed.how to check parent div 'tabs ' has the child 'nav-justified' with given class name.

jQuery(document).ready(function($) {
if($('#tabs').children().hasClass('nav-justified'))
{
alert('helloexist');
}else{
alert('class not exist');}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tabs">
 <div class="view view-tabs view-id-tabs view-display-id-block view-dom-id-f25d21847449ac13dbfa35f1bbd014d7">
  <div class="view-content">
   <ul class="nav  nav-justified tabs-section">
    <li>1</li>
    <li>2</li>
    <li>3</li>
   </ul>
  </div>
 </div>
</div></code>```

答:
Here is the change that I mentioned in comment above. You should find by class and check the length:

jQuery(document).ready(function($) {
  if ($('#tabs').find('.nav-justified').length) {
    alert('helloexist');
  } else {
    alert('class not exist');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tabs">
  <div class="view view-tabs view-id-tabs view-display-id-block view-dom-id-f25d21847449ac13dbfa35f1bbd014d7">
    <div class="view-content">
      <ul class="nav  nav-justified tabs-section">
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
    </div>
  </div>
</div></code>```

Title: check child the given class in jquery

Body:
I want to check the parent div 'tabs' has the child with class 'nav-justified' in jquery .In my html block 'nav-justified' class is exist but shows 'class not exit' due to condition failed.how to check parent div 'tabs ' has the child 'nav-justified' with given class name.

jQuery(document).ready(function($) {
if($('#tabs').children().hasClass('nav-justified'))
{
alert('helloexist');
}else{
alert('class not exist');}
});

1

2

3

Body:
Here is the change that I mentioned in comment above. You should find by class and check the length:

jQuery(document).ready(function($) {
  if ($('#tabs').find('.nav-justified').length) {
    alert('helloexist');
  } else {
    alert('class not exist');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tabs">
  <div class="view view-tabs view-id-tabs view-display-id-block view-dom-id-f25d21847449ac13dbfa35f1bbd014d7">
    <div class="view-content">
      <ul class="nav  nav-justified tabs-section">
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
    </div>
  </div>
</div>


问:
While navigation to a path using React Router, the component state value gets reset to default
I'm using React-Routerv4 , and when I login using the login form , i set the app component state value isUser to true from child component login using function setUserLogin, which i can debug correctly in the console after logging in. Also I have specified , that if i migrate to /login path ,it checks isUser value in state to migrate to /home page if user is already logged in(isUser is true) . But that value is now automatically changed to default value false , when i enter /login in the browser and it shows login page instead of home page. Im new to React , so am I missing something here?
Here is the code snippet :

```<code>import React from 'react';
import ReactDom from 'react-dom';
import 'materialize-css/bin/materialize.css'
import 'materialize-css/bin/materialize.js';
import {BrowserRouter as Router, Route , Redirect} from 'react-router-dom';
import {LoginForm} from './components/login';
import {Home} from './components/home';
import {Main} from './components/main';
import {Room} from './components/room';
import "materialize-css";
import 'materialize-css/js/toasts';

class App extends React.Component {
    constructor(props){
        super(props);
        this.state={
            isUser : false
        }
        this.setUserLogin = this.setUserLogin.bind(this);
    }
    setUserLogin(){
        this.setState({isUser:true});
    }
    render() {
        return <Router>
            <div>
                <Route exact path="/" component={Home}/>
                <Route path="/login" render={(props)=>(
                    this.state.isUser ? <Redirect to="/home" /> : <LoginForm history={props.history} setUserLogin = {this.setUserLogin}/>
                )} />
                <Route path="/home" component={Main}/>
                <Route path="/room" component={Room}/>
            </div>
        </Router>
    };
}
ReactDom.render(<App/>, document.getElementById('app'));
</code>```

答:
If I understand your situation, do you expect your state to persist when you manually change your URL in the browser? If you want this, you'll have to store some variable in persistent storage (like localStorage) and check it at some point of component life cycle: constructor, componentDidMount...

When you manually change your browser location, everything restarts including the state, the whole page is redownloaded (or read from cache).

Body:
I'm using React-Routerv4 , and when I login using the login form , i set the app component state value isUser to true from child component login using function setUserLogin, which i can debug correctly in the console after logging in. Also I have specified , that if i migrate to /login path ,it checks isUser value in state to migrate to /home page if user is already logged in(isUser is true) . But that value is now automatically changed to default value false , when i enter /login in the browser and it shows login page instead of home page. Im new to React , so am I missing something here?
Here is the code snippet :

import React from 'react';
import ReactDom from 'react-dom';
import 'materialize-css/bin/materialize.css'
import 'materialize-css/bin/materialize.js';
import {BrowserRouter as Router, Route , Redirect} from 'react-router-dom';
import {LoginForm} from './components/login';
import {Home} from './components/home';
import {Main} from './components/main';
import {Room} from './components/room';
import "materialize-css";
import 'materialize-css/js/toasts';

class App extends React.Component {
    constructor(props){
        super(props);
        this.state={
            isUser : false
        }
        this.setUserLogin = this.setUserLogin.bind(this);
    }
    setUserLogin(){
        this.setState({isUser:true});
    }
    render() {
        return <Router>

                <Route exact path="/" component={Home}/>
                <Route path="/login" render={(props)=>(
                    this.state.isUser ? <Redirect to="/home" /> : <LoginForm history={props.history} setUserLogin = {this.setUserLogin}/>
                )} />
                <Route path="/home" component={Main}/>
                <Route path="/room" component={Room}/>

        </Router>
    };
}
ReactDom.render(<App/>, document.getElementById('app'));


问:
Is it possible to launch another app in iOS 8 using Swift?
Is it possible to launch any app from within another app?

For example, in my application, I want the user to push a button and launch another app (don't close the current app, just open another app and switch to it).

How can I do it in iOS 8 using Swift?

答:
We can do this by creating custom URL of that app and after that we can open custom URL on click event of a button.</p>

```<code>let kCustomURLScheme = "DemoDriver://Daffomac.DemoDriver"

func openCustomApp() {

    let Url = NSURL(string: kCustomURLScheme)
    if UIApplication.shared.canOpenURL(Url! as URL)
    {
        UIApplication.shared.openURL(Url! as URL)

    } else {
        //redirect to safari because the user doesn't have Instagram
        UIApplication.shared.openURL(NSURL(string: kCustomURLScheme)! as URL)
    }

}
</code>```

Body:
We can do this by creating custom URL of that app and after that we can open custom URL on click event of a button.

let kCustomURLScheme = "DemoDriver://Daffomac.DemoDriver"

func openCustomApp() {

    let Url = NSURL(string: kCustomURLScheme)
    if UIApplication.shared.canOpenURL(Url! as URL)
    {
        UIApplication.shared.openURL(Url! as URL)

    } else {
        //redirect to safari because the user doesn't have Instagram
        UIApplication.shared.openURL(NSURL(string: kCustomURLScheme)! as URL)
    }

}


问:
Not able to understand or implement Semaphore
I have written below class to understand SemaPhore. However the result is unexpected. I couldn't understand actual work of SemaPhore. How it is used as a lock, signaling and for counting?

```<code>public class TrySemaPhore
    {
        public static void main(String[] args) {
            ExecutorService executor = Executors.newFixedThreadPool(10);
            Semaphore semaphore = new Semaphore(2);
            Runnable newTask= () -> {
                boolean permit = false;
                try {
                    permit = semaphore.tryAcquire();
                   if(permit)
                   System.out.println("doing work");
                } finally {
                    if(permit){
                        semaphore.release();
                        System.out.println("Work done!!");
                    }
                }
            };
            for(int i=0; i<=4; i++){
                executor.submit(newTask);
                }
            stop(executor);
        }

        private static void stop(ExecutorService executor) {
            /*code to stop executor*/
        }
    }
</code>```

Result

```<code>doing work
Work done!!
doing work
Work done!!
doing work
Work done!!
doing work
Work done!!
doing work
Work done!!
</code>```

I have 10 Fixed number of Threads. I have 5 different tasks(for loop) which needs to complete. I have Semaphore with 2 permits. I want to understand Semaphore and it's benefit in a very simple way (not like theory available through googling).

答:
A counting semaphore.  Conceptually, a semaphore maintains a set of
 permits.  Each acquire blocks if necessary until a permit is
  available, and then takes it.  Each release adds a permit,
  potentially releasing a blocking acquirer.

Before obtaining an item each thread must acquire a permit from
 the semaphore, guaranteeing that an item is available for use. When
  the thread has finished with the item it is returned back to the
 pool and a permit is returned to the semaphore, allowing another
  thread to acquire that item.  Note that no synchronization lock is
 held when acquire is called as that would prevent an item
 from being returned to the pool.  The semaphore encapsulates the
  synchronization needed to restrict access to the pool, separately
 from any synchronization needed to maintain the consistency of the
 pool itself.

Use case:
     1.An unbounded queue requires one semaphore, (to count the queue entries), and a mutex-protected thread-safe queue, (or equivalent lock-free thread-safe queue). The semaphore is intialized to zero. Producers lock the mutex, push an object onto the queue, unlock the mutex and signal the semaphore. Consumers wait on the semaphore, lock the mutex, pop the object and unlock the mutex.

2.Object pool where you can restrict the number of resource using semaphore .Multiple thread try to acquire the object in the pool and you have limited number of object then some thread will wait until some thread releases.

```<code>class Pool {
  private static final int MAX_AVAILABLE = 100;
  private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);

  public Object getItem() throws InterruptedException {
   available.acquire();
   return getNextAvailableItem();
  }

  public void putItem(Object x) {
   if (markAsUnused(x))
    available.release();
  }
</code>```

Body:
I have written below class to understand SemaPhore. However the result is unexpected. I couldn't understand actual work of SemaPhore. How it is used as a lock, signaling and for counting?

public class TrySemaPhore
    {
        public static void main(String[] args) {
            ExecutorService executor = Executors.newFixedThreadPool(10);
            Semaphore semaphore = new Semaphore(2);
            Runnable newTask= () -> {
                boolean permit = false;
                try {
                    permit = semaphore.tryAcquire();
                   if(permit)
                   System.out.println("doing work");
                } finally {
                    if(permit){
                        semaphore.release();
                        System.out.println("Work done!!");
                    }
                }
            };
            for(int i=0; i<=4; i++){
                executor.submit(newTask);
                }
            stop(executor);
        }

        private static void stop(ExecutorService executor) {
            /*code to stop executor*/
        }
    }

Result

doing work
Work done!!
doing work
Work done!!
doing work
Work done!!
doing work
Work done!!
doing work
Work done!!

I have 10 Fixed number of Threads. I have 5 different tasks(for loop) which needs to complete. I have Semaphore with 2 permits. I want to understand Semaphore and it's benefit in a very simple way (not like theory available through googling).

Body:
A counting semaphore.  Conceptually, a semaphore maintains a set of
 permits.  Each acquire blocks if necessary until a permit is
  available, and then takes it.  Each release adds a permit,
  potentially releasing a blocking acquirer.

Before obtaining an item each thread must acquire a permit from
 the semaphore, guaranteeing that an item is available for use. When
  the thread has finished with the item it is returned back to the
 pool and a permit is returned to the semaphore, allowing another
  thread to acquire that item.  Note that no synchronization lock is
 held when acquire is called as that would prevent an item
 from being returned to the pool.  The semaphore encapsulates the
  synchronization needed to restrict access to the pool, separately
 from any synchronization needed to maintain the consistency of the
 pool itself.

Use case:
     1.An unbounded queue requires one semaphore, (to count the queue entries), and a mutex-protected thread-safe queue, (or equivalent lock-free thread-safe queue). The semaphore is intialized to zero. Producers lock the mutex, push an object onto the queue, unlock the mutex and signal the semaphore. Consumers wait on the semaphore, lock the mutex, pop the object and unlock the mutex.

2.Object pool where you can restrict the number of resource using semaphore .Multiple thread try to acquire the object in the pool and you have limited number of object then some thread will wait until some thread releases.

class Pool {
  private static final int MAX_AVAILABLE = 100;
  private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);

  public Object getItem() throws InterruptedException {
   available.acquire();
   return getNextAvailableItem();
  }

  public void putItem(Object x) {
   if (markAsUnused(x))
    available.release();
  }


问:
I don't have headers on my screens but i want to have header only on one screen
I use reactnavigation for navigation. I don't have headers on my screens but i want to have header only on one screen (especially back button).
This is my root navigator:

```<code>...
class RootNavigation extends Component {
  props: Props;

  render() {
    const { isProfileSelect } = this.props;
    const initialRouteName = currentRoute(isProfileSelect);

    const RootStackNav = StackNavigator(
      {
        AppHome: { screen: TabBarNavigator },
        SwitchProfile: { screen: SwitchProfileScreen },
        Pin: { screen: PinScreen },
      },
      {
        initialRouteName,
        headerMode: 'none',
      },
    );

    return <RootStackNav />;
  }
}
...
</code>```

there is headerMode: 'none', it does mean i haven't any header navigator it is good for screens AppHome,SwitchProfile but not for Pin i need back button on header. Because I have to go on SwitchScreen and there i can continue on Pin screen and from Pin screen i sometime need go back to SwitchScreen And i have no back button on IOS. I need set header only in pin screen.

this is navigationOptions for pin screen:

```<code>...
  static navigationOptions = {
    title: I18n.t('screens.pinScreen.navigationOptions.title'),
  };
...
</code>```

but changes haven't any effect

Can you help me to add header only on Pin screen?
Thank you

update:
SOLUTION

```<code>const RootStackNav = StackNavigator(
  {
    AppHome: {
      screen: TabBarNavigator,
      navigationOptions: {
        title: 'Header title',
        headerMode: 'screen',
        header: null,
      },
     },
    SwitchProfile: {
      screen: SwitchProfileScreen,
      navigationOptions: {
        title: 'Header title',
        headerMode: 'screen',
        header: null,
      },
    },
    Pin: {
      screen: PinScreen,
      navigationOptions: {
        title: 'Header title',
        headerMode: 'screen',
        // header: null,
      },
    },
  },
  {
    initialRouteName,
    // headerMode: 'none',
  },
);
</code>```

答:
My case was reverse of yours...
I wanted to disable the header on one screen so I added the following code in that particular screen.

```<code>export default class NoHeaderView extends Component {
static navigationOptions = { header: null }
...
//your constructor, render and other stuff
...
}//
</code>```

Let me know if it works.

Body:
I use reactnavigation for navigation. I don't have headers on my screens but i want to have header only on one screen (especially back button).
This is my root navigator:

...
class RootNavigation extends Component {
  props: Props;

  render() {
    const { isProfileSelect } = this.props;
    const initialRouteName = currentRoute(isProfileSelect);

    const RootStackNav = StackNavigator(
      {
        AppHome: { screen: TabBarNavigator },
        SwitchProfile: { screen: SwitchProfileScreen },
        Pin: { screen: PinScreen },
      },
      {
        initialRouteName,
        headerMode: 'none',
      },
    );

    return <RootStackNav />;
  }
}
...

there is headerMode: 'none', it does mean i haven't any header navigator it is good for screens AppHome,SwitchProfile but not for Pin i need back button on header. Because I have to go on SwitchScreen and there i can continue on Pin screen and from Pin screen i sometime need go back to SwitchScreen And i have no back button on IOS. I need set header only in pin screen.

this is navigationOptions for pin screen:

...
  static navigationOptions = {
    title: I18n.t('screens.pinScreen.navigationOptions.title'),
  };
...

but changes haven't any effect

Can you help me to add header only on Pin screen?
Thank you

update:
SOLUTION

const RootStackNav = StackNavigator(
  {
    AppHome: {
      screen: TabBarNavigator,
      navigationOptions: {
        title: 'Header title',
        headerMode: 'screen',
        header: null,
      },
     },
    SwitchProfile: {
      screen: SwitchProfileScreen,
      navigationOptions: {
        title: 'Header title',
        headerMode: 'screen',
        header: null,
      },
    },
    Pin: {
      screen: PinScreen,
      navigationOptions: {
        title: 'Header title',
        headerMode: 'screen',
        // header: null,
      },
    },
  },
  {
    initialRouteName,
    // headerMode: 'none',
  },
);

Body:
My case was reverse of yours...
I wanted to disable the header on one screen so I added the following code in that particular screen.

export default class NoHeaderView extends Component {
static navigationOptions = { header: null }
...
//your constructor, render and other stuff
...
}//

Let me know if it works.


问:
Regular expressions to add classes to html tags
I am working on a reactjs project and have basic html coming through via json. I need to go back over the markup and append bootstrap classes to it so its styled properly on the page.

the current function

```<code>  const markupFormatting = (html) => {
    html = html.replace(/<p/g, '<p class="paragraph-margin-bottom-10 text--font-size-14 paragraph--justified"')
    html = html.replace(/<a/g, '<a class="text--font-size-14 hyperlink-primary"')
    return html
  }
</code>```

http://jsfiddle.net/0ht35rpb/64/

Is there a cleaner way of doing this?

答:
You could use jQuery to parse the HTML and add the classes

```<code>const $html = $(html);
$html.find('p').addClass('paragraph-margin-bottom-10 text--font-size-14 paragraph--justified');
$html.find('a').addClass('text--font-size-14 hyperlink-primary');
return $html.html();
</code>```

This protects you from a few edge cases, e.g. adding a duplicate class property. This works on the server side as well with the cheerio library.

PS: There is this jewel about using RegEx to work with HTML: RegEx match open tags except XHTML self-contained tags.

Body:
I am working on a reactjs project and have basic html coming through via json. I need to go back over the markup and append bootstrap classes to it so its styled properly on the page.

the current function

  const markupFormatting = (html) => {
    html = html.replace(/<p/g, '<p class="paragraph-margin-bottom-10 text--font-size-14 paragraph--justified"')
    html = html.replace(/<a/g, '<a class="text--font-size-14 hyperlink-primary"')
    return html
  }

http://jsfiddle.net/0ht35rpb/64/

Is there a cleaner way of doing this?

Body:
You could use jQuery to parse the HTML and add the classes

const $html = $(html);
$html.find('p').addClass('paragraph-margin-bottom-10 text--font-size-14 paragraph--justified');
$html.find('a').addClass('text--font-size-14 hyperlink-primary');
return $html.html();

This protects you from a few edge cases, e.g. adding a duplicate class property. This works on the server side as well with the cheerio library.

PS: There is this jewel about using RegEx to work with HTML: RegEx match open tags except XHTML self-contained tags.


问:
Substitute results to an error with cor.test
I am trying to write a loop, which returns linear regression and correlation parameters. When trying to pass substitute through cor.test function, I encounter an unexpected error

```<code>data(iris)
i <- 1
vars <- list(par = as.name(colnames(iris)[1]), expl = as.name(colnames(iris)[2:4][i]))
lm(substitute(par ~ expl, vars), data = iris) # works
lm(Sepal.Length ~ Sepal.Width, data = iris) # works. Result equal to the statement above

cor.test(~Sepal.Length + Sepal.Width, data = iris) # works
cor.test(substitute(~par + expl, vars), data = iris) # does not work
## Error in cor.test.default(substitute(~par + expl, vars), data = iris) :
## argument "y" is missing, with no default
</code>```

To my understanding the cor.test statement should be the same than the manually inputted one.

What is the reason for the error? How can I write a substitute statement for cor.test that works?

答:
The error stems from the fact that the first version is of formula type and the second one is language:

```<code>str(substitute(~par + expl, vars))
# language ~Sepal.Length + Sepal.Width
str(~Sepal.Length + Sepal.Width)
# Class 'formula'  language ~Sepal.Length + Sepal.Width
# ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
</code>```

If you use as.formula on the second version it works:

```<code>cor.test(as.formula(substitute(~par + expl, vars)), data = iris)
# Pearson's product-moment correlation
#
# data:  Sepal.Length and Sepal.Width
# t = -1.4403, df = 148, p-value = 0.1519
# alternative hypothesis: true correlation is not equal to 0
# 95 percent confidence interval:
# -0.27269325  0.04351158
# sample estimates:
# cor
# -0.1175698
</code>```

Body:
I am trying to write a loop, which returns linear regression and correlation parameters. When trying to pass substitute through cor.test function, I encounter an unexpected error

data(iris)
i <- 1
vars <- list(par = as.name(colnames(iris)[1]), expl = as.name(colnames(iris)[2:4][i]))
lm(substitute(par ~ expl, vars), data = iris) # works
lm(Sepal.Length ~ Sepal.Width, data = iris) # works. Result equal to the statement above

cor.test(~Sepal.Length + Sepal.Width, data = iris) # works
cor.test(substitute(~par + expl, vars), data = iris) # does not work
## Error in cor.test.default(substitute(~par + expl, vars), data = iris) :
## argument "y" is missing, with no default

To my understanding the cor.test statement should be the same than the manually inputted one.

What is the reason for the error? How can I write a substitute statement for cor.test that works?

Body:
The error stems from the fact that the first version is of formula type and the second one is language:

str(substitute(~par + expl, vars))
# language ~Sepal.Length + Sepal.Width
str(~Sepal.Length + Sepal.Width)
# Class 'formula'  language ~Sepal.Length + Sepal.Width
# ..- attr(*, ".Environment")=<environment: R_GlobalEnv>

If you use as.formula on the second version it works:

cor.test(as.formula(substitute(~par + expl, vars)), data = iris)
# Pearson's product-moment correlation
#
# data:  Sepal.Length and Sepal.Width
# t = -1.4403, df = 148, p-value = 0.1519
# alternative hypothesis: true correlation is not equal to 0
# 95 percent confidence interval:
# -0.27269325  0.04351158
# sample estimates:
# cor
# -0.1175698


问:
Google maps: display alternate location if address not found
I am trying to display a location on the map using the google maps iframe.

The q parameter value is set to the address+city+state+country fetched from the user data stored in the database.

```<code><iframe src="http://maps.google.com/maps?q=34A (1st Floor), Jalan SS 267, Petaling Jaya, Selangor,Malaysia&layer=tc&t=m&z=15&source=embed&output=svembed"></iframe>
</code>```

However, sometimes if the q parameters can't be displayed, although if is being copied and pasted  in the maps.google.com search field it will appear.

My question: is there are way to display the city and state as an alternate when the address in the q parameters can't be found?

答:
Probably you can create a work around using the Google Maps Embed API, but you will need an additional step.

You should get the latitude and longitude position of the city. For example, using the Geocoding API you can see that 'Petaling Jaya, Selangor,Malaysia' has coordinate 3.1278871,101.5944885

https://google-developers.appspot.com/maps/documentation/utils/geocoder/#q%3DPetaling%2520Jaya%252C%2520Selangor%252CMalaysia

Now you can apply center and zoom parameters of Embed API to center your map at the city. The resulting URL will be

https://www.google.com/maps/embed/v1/place?q=34A%20(1st%20Floor)%2C%20Jalan%20SS%20267%2C%20Petaling%20Jaya%2C%20Selangor%2CMalaysia&center=3.1278871,101.5944885&zoom=13&key=YOUR_API_KEY

Examples

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Embed API</title>

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

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Embed API</title>
</head>
<body>
<iframe

src="https://www.google.com/maps/embed/v1/search?q=267%2C%20Jalan%20SS%202%2F2%2C%20Petaling%20Jaya%2C%20Selangor%2CMalaysia&center=3.1278871%2C101.5944885&zoom=13&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU" width="600" height="400">

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

There is no way to provide alternative address, but you can position a map at the city.

Body:
I am trying to display a location on the map using the google maps iframe.

The q parameter value is set to the address+city+state+country fetched from the user data stored in the database.

However, sometimes if the q parameters can't be displayed, although if is being copied and pasted  in the maps.google.com search field it will appear.

My question: is there are way to display the city and state as an alternate when the address in the q parameters can't be found?

Body:
Probably you can create a work around using the Google Maps Embed API, but you will need an additional step.

You should get the latitude and longitude position of the city. For example, using the Geocoding API you can see that 'Petaling Jaya, Selangor,Malaysia' has coordinate 3.1278871,101.5944885

https://google-developers.appspot.com/maps/documentation/utils/geocoder/#q%3DPetaling%2520Jaya%252C%2520Selangor%252CMalaysia

Now you can apply center and zoom parameters of Embed API to center your map at the city. The resulting URL will be

https://www.google.com/maps/embed/v1/place?q=34A%20(1st%20Floor)%2C%20Jalan%20SS%20267%2C%20Petaling%20Jaya%2C%20Selangor%2CMalaysia&center=3.1278871,101.5944885&zoom=13&key=YOUR_API_KEY

Examples

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Embed API</title>
</head>
<body>
<iframe

src="https://www.google.com/maps/embed/v1/place?q=34A%20(1st%20Floor)%2C%20Jalan%20SS%20267%2C%20Petaling%20Jaya%2C%20Selangor%2CMalaysia&center=3.1278871,101.5944885&zoom=13&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU" width="600" height="400">

</iframe>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Embed API</title>
</head>
<body>
<iframe

src="https://www.google.com/maps/embed/v1/search?q=267%2C%20Jalan%20SS%202%2F2%2C%20Petaling%20Jaya%2C%20Selangor%2CMalaysia&center=3.1278871%2C101.5944885&zoom=13&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU" width="600" height="400">

</iframe>
</body>
</html>

There is no way to provide alternative address, but you can position a map at the city.


问:
Table doesn't exists in Liferay 6
I have defined a data table and associated objects in Liferay 6, but when I run the code it says the table doesn't exists, and it's true. The code runs fine when I create the table by hand just copy-pasting the create table from the model implementation, but I expected the table to be created when deploying.

The user has all the privileges needed to create it.

What I'm missing?

答:
Check values of build.namespace in service.properties file and value of

```<code>select buildNumber from servicecomponent where buildNamespace = <<build.namespace from service.properties>>
</code>```

Now the buildNumber return from query must be lesser than value of build.number propert in service.properties. If it is not then just set the value of build.number to 9999.

Sometimes due to mismatch, changes are not applied to database.

Title: Table doesn't exists in Liferay 6

Body:
Check values of build.namespace in service.properties file and value of

select buildNumber from servicecomponent where buildNamespace = <<build.namespace from service.properties>>

Now the buildNumber return from query must be lesser than value of build.number propert in service.properties. If it is not then just set the value of build.number to 9999.

Sometimes due to mismatch, changes are not applied to database.


问:
ipad web application: How do I prevent the keyboard from popping up on jquery datepicker
I have a form with an date field with a jquery datepicker attached to it.

When I select the date field the datepicker pops up but then the iPad keyboard slides into view and obscures the datepicker.

How do I prevent the keyboard from popping up in this situation?

答:
I used a combination of CDeutsch and Rob's answers to disable the input field when the user clicks the calendar and then enable the field after the date picker closes as follows:

```<code>$(".date").datepicker({
    showOn: "button",
    onClose: function(dateText, inst) { $(this).attr("disabled", false); },
    beforeShow: function(dateText, inst) { $(this).attr("disabled", true); },
    buttonImage: "/images/calendar.png",
    buttonImageOnly: true
});
</code>```

The benefit is that this allows the user to edit the date manually by clicking in the input field which brings up the iPad's keyboard or use the date picker by clicking on the date button.

Again thanks for all of the great input on this problem, I was stuck on this same issue until reading the above posts.

Body:
I used a combination of CDeutsch and Rob's answers to disable the input field when the user clicks the calendar and then enable the field after the date picker closes as follows:

$(".date").datepicker({
    showOn: "button",
    onClose: function(dateText, inst) { $(this).attr("disabled", false); },
    beforeShow: function(dateText, inst) { $(this).attr("disabled", true); },
    buttonImage: "/images/calendar.png",
    buttonImageOnly: true
});

The benefit is that this allows the user to edit the date manually by clicking in the input field which brings up the iPad's keyboard or use the date picker by clicking on the date button.

Again thanks for all of the great input on this problem, I was stuck on this same issue until reading the above posts.


问:
Selected/Clicked UIButton text title color need to change from number of buttons on scrollview programmatically
I added number of UIButtons on scrollview programmatically based on array count, until this much its working fine. Requirement is only selected button text title color should change into brown color remain are blue.  I can’t able to solve this one please some one help using Swift 3. I need only the selected or clicked button text title color need to change remain all are in rest of the color.      </p>

```<code>           for titles in arrayPageTitles {
        var titleSize: CGSize = (titles as AnyObject).size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)])
        titleSize = CGSize(width: CGFloat(ceilf(Float(titleSize.width))), height: CGFloat(ceilf(Float(titleSize.height))));

        /**
            creating top page strip tab Buttons
         */

        buttonTitle = UIButton(type: UIButtonType.custom)
        buttonTitle = UIButton(frame: CGRect(x: buttonPositionX + 5, y: 10, width: titleSize.width+40, height: (scrollViewTop?.frame.size.height)! - 20))
        buttonTitle.setTitle(titles, for: .normal)
        buttonTitle.setTitleColor(UIColor.blue, for: .normal)
        buttonTitle.setTitleColor(UIColor.white, for: .selected

        buttonTitle.clipsToBounds = true
        buttonTitle.layer.masksToBounds = true
        buttonTitle.layer.cornerRadius = 17
        buttonTitle.layer.borderWidth = 1
        buttonTitle.layer.borderColor = UIColor.darkGray.cgColor

        buttonTitle.tag = increaseIndex
        buttonTitle.addTarget(self, action: #selector(buttonTitleAction), for: .touchUpInside)

        arrayTitleButtons .add(buttonTitle)
        scrollViewTop?.addSubview(buttonTitle)
        let currentButtonX:CGFloat = buttonPositionX
        let buttonWidth:CGFloat = buttonTitle.frame.size.width
        buttonPositionX = currentButtonX + buttonWidth + 10

        if arrayPageTitles.first == titles  {

            viewLine.frame = CGRect(x: buttonTitle.frame.origin.x, y: buttonTitle.frame.origin.y, width: buttonTitle.frame.size.width, height: buttonTitle.frame.size.height)

            viewLine.layer.cornerRadius = 17
            viewLine.clipsToBounds = true
            viewLine.layer.masksToBounds = true

            viewLine.backgroundColor = UIColor.red
            scrollViewTop?.addSubview(viewLine)
            scrollViewTop?.addSubview(buttonTitle) // need to fix ... this add only first button
            buttonTitle.setTitleColor(UIColor.white, for: .normal)
        }

        /**
            creating collection views
         */
        let storyBoard = UIStoryboard(name:"Main", bundle:nil)
        let pageStripTypeViewController = storyBoard.instantiateViewController(withIdentifier: "kPageStripVC") as! FirstViewController
</code>```

<p>....</p>

答:
You could change the selection state of the sender in your @IBAction, as follows:</p>

```<code>@IBAction func buttonAction(_ sender: UIButton) {
    // create an array of buttons
    var mybuttonArray: [UIButton] = view.subviews.filter{$0 is UIButton} as! [UIButton]
    // filter it down to buttons that aren't the sender
    mybuttonArray = mybuttonArray.filter{$0 != sender}

    // figure out of it's selected
    mybuttonArray.forEach({ button in
        if button.isSelected {
            // unselected it
            button.isSelected = false
        }
    })

    // select the sender's button
    sender.isSelected = !sender.isSelected

    // whatever else you need to
}
</code>```

Body:
I added number of UIButtons on scrollview programmatically based on array count, until this much its working fine. Requirement is only selected button text title color should change into brown color remain are blue.  I can’t able to solve this one please some one help using Swift 3. I need only the selected or clicked button text title color need to change remain all are in rest of the color.

           for titles in arrayPageTitles {
        var titleSize: CGSize = (titles as AnyObject).size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)])
        titleSize = CGSize(width: CGFloat(ceilf(Float(titleSize.width))), height: CGFloat(ceilf(Float(titleSize.height))));

        /**
            creating top page strip tab Buttons
         */

        buttonTitle = UIButton(type: UIButtonType.custom)
        buttonTitle = UIButton(frame: CGRect(x: buttonPositionX + 5, y: 10, width: titleSize.width+40, height: (scrollViewTop?.frame.size.height)! - 20))
        buttonTitle.setTitle(titles, for: .normal)
        buttonTitle.setTitleColor(UIColor.blue, for: .normal)
        buttonTitle.setTitleColor(UIColor.white, for: .selected

        buttonTitle.clipsToBounds = true
        buttonTitle.layer.masksToBounds = true
        buttonTitle.layer.cornerRadius = 17
        buttonTitle.layer.borderWidth = 1
        buttonTitle.layer.borderColor = UIColor.darkGray.cgColor

        buttonTitle.tag = increaseIndex
        buttonTitle.addTarget(self, action: #selector(buttonTitleAction), for: .touchUpInside)

        arrayTitleButtons .add(buttonTitle)
        scrollViewTop?.addSubview(buttonTitle)
        let currentButtonX:CGFloat = buttonPositionX
        let buttonWidth:CGFloat = buttonTitle.frame.size.width
        buttonPositionX = currentButtonX + buttonWidth + 10

        if arrayPageTitles.first == titles  {

            viewLine.frame = CGRect(x: buttonTitle.frame.origin.x, y: buttonTitle.frame.origin.y, width: buttonTitle.frame.size.width, height: buttonTitle.frame.size.height)

            viewLine.layer.cornerRadius = 17
            viewLine.clipsToBounds = true
            viewLine.layer.masksToBounds = true

            viewLine.backgroundColor = UIColor.red
            scrollViewTop?.addSubview(viewLine)
            scrollViewTop?.addSubview(buttonTitle) // need to fix ... this add only first button
            buttonTitle.setTitleColor(UIColor.white, for: .normal)
        }

        /**
            creating collection views
         */
        let storyBoard = UIStoryboard(name:"Main", bundle:nil)
        let pageStripTypeViewController = storyBoard.instantiateViewController(withIdentifier: "kPageStripVC") as! FirstViewController

....

Body:
You could change the selection state of the sender in your @IBAction, as follows:

@IBAction func buttonAction(_ sender: UIButton) {
    // create an array of buttons
    var mybuttonArray: [UIButton] = view.subviews.filter{$0 is UIButton} as! [UIButton]
    // filter it down to buttons that aren't the sender
    mybuttonArray = mybuttonArray.filter{$0 != sender}

    // figure out of it's selected
    mybuttonArray.forEach({ button in
        if button.isSelected {
            // unselected it
            button.isSelected = false
        }
    })

    // select the sender's button
    sender.isSelected = !sender.isSelected

    // whatever else you need to
}


问:
Angular2,Typescript:How to insert a key:value pair at a PARTICULAR index in an array?
I want to insert a key value pair at a particular index in an array.How do I do that ?

this is my code so far:

```<code>  this.quiz.push(
{
  "question-no":this.no,
  "Ans":this.ans
}
</code>```

I need it in that way because this is to store the choice selected by the user against the particular question. So if the user changes the choice then that has to get replaced at that particular position(index of the array). But now a new element is being created.But I want it to replace the existing one.
But I don't know how to insert it at a particular index.Can anyone help me please ?

Thanks in advance.

答: try to use arr.splice(index, 0, item); at the specified index , 0 item will be deleted.

Body:
I want to insert a key value pair at a particular index in an array.How do I do that ?

this is my code so far:

  this.quiz.push(
{
  "question-no":this.no,
  "Ans":this.ans
}

I need it in that way because this is to store the choice selected by the user against the particular question. So if the user changes the choice then that has to get replaced at that particular position(index of the array). But now a new element is being created.But I want it to replace the existing one.
But I don't know how to insert it at a particular index.Can anyone help me please ?

Thanks in advance.


答:
Use CSS selectors to select specific element, then check the length of the collection:

if ($("#tabs .nav-justified").length) {
  alert("Exist");
} else {
  alert("The class is not exist");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tabs">
  <div class="view view-tabs view-id-tabs view-display-id-block view-dom-id-f25d21847449ac13dbfa35f1bbd014d7">
    <div class="view-content">
      <ul class="nav  nav-justified tabs-section">
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
    </div>
  </div>
</div></code>```

Title: check child the given class in jquery

Body:
I want to check the parent div 'tabs' has the child with class 'nav-justified' in jquery .In my html block 'nav-justified' class is exist but shows 'class not exit' due to condition failed.how to check parent div 'tabs ' has the child 'nav-justified' with given class name.

jQuery(document).ready(function($) {
if($('#tabs').children().hasClass('nav-justified'))
{
alert('helloexist');
}else{
alert('class not exist');}
});

1

2

3

Body:
Use CSS selectors to select specific element, then check the length of the collection:

if ($("#tabs .nav-justified").length) {
  alert("Exist");
} else {
  alert("The class is not exist");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tabs">
  <div class="view view-tabs view-id-tabs view-display-id-block view-dom-id-f25d21847449ac13dbfa35f1bbd014d7">
    <div class="view-content">
      <ul class="nav  nav-justified tabs-section">
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
    </div>
  </div>
</div>


问:
how to avoid test data having categorical value that training data didn`t have
During my spark study, I constantly encounter application crash with some trace like "can not find key xxx".
After struggling with un-clear message from the crash trace, I found it's because the testing data has some value which the training data didn't have.

For example:

There is a categorical feature contains 4 unique value (1,2,3,4).
After split, the data set to training/test data set, the training data only has (1,2,3) of this feature, and the test data set has (..., 4).
After training the model, the application will crash when evaluate the model with the test data set.

Is there any best practice for such situation when data pre-processing or is there a way to avoid such situation?

update with more details:

I am training the decision tree with couple of categorical features and numerical features.

The training/test dataset is 70/30, then the evaluation failed with "Caused by: java.util.NoSuchElementException:  key not found: 5.0"

Then I changed training/test to 100/30, errors gone.

So I think the issue comes from the missing categorical value in training data, I need an approach to avoid this kinda situation.

答:
Use stratified sampling.

You split your data set by label, then sample within each label.

Then you join and shuffle all the labels again afterwards.

You can try the same for categorical attributes. But of course you may eventually observe a unique value you have never seen before. A good implementation should not crash on that!


问:
How to convert sqlDataReader to Task async
I have the following code-can anyone please tell me if I can make this a async Task</p>

```<code>public  MDTO GetIe(MDTO dtoItem)
    {

        string[] Tables = new string[] { "C", "CValue", "SP", "Ar", "P", "CR", "QC", "SR" };
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["tESTp"].ConnectionString))
        {
            using (SqlCommand command = new SqlCommand("GetItem", connection))
            {
                DataSet Result = new DataSet();
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add("@ProjectId", SqlDbType.VarChar);
                command.Parameters["@ProjectId"].Value = dtoItem.ProjectId;

                connection.Open();
                Result.EnforceConstraints = false;
                Result.Load(command.ExecuteReader(CommandBehavior.CloseConnection), LoadOption.OverwriteChanges, Tables);
                dtoItem.SR = Result;
            }
        }
        return dtoItem;
    }
</code>```

答:
Change your command.ExecuteReader to the async version:</p>

```<code>public async Task<MDTO> GetIeAsync(MDTO dtoItem)
{
    ...
    connection.Open();
    Result.EnforceConstraints = false;

    SqlDataReader dataReader = await command.ExecuteReaderAsync(CommandBehavior.CloseConnection);
    Result.Load(dataReader, LoadOption.OverwriteChanges, Tables);
    dtoItem.SR = Result;
    ...
}
</code>```

Body:
I have the following code-can anyone please tell me if I can make this a async Task

public  MDTO GetIe(MDTO dtoItem)
    {

        string[] Tables = new string[] { "C", "CValue", "SP", "Ar", "P", "CR", "QC", "SR" };
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["tESTp"].ConnectionString))
        {
            using (SqlCommand command = new SqlCommand("GetItem", connection))
            {
                DataSet Result = new DataSet();
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add("@ProjectId", SqlDbType.VarChar);
                command.Parameters["@ProjectId"].Value = dtoItem.ProjectId;

                connection.Open();
                Result.EnforceConstraints = false;
                Result.Load(command.ExecuteReader(CommandBehavior.CloseConnection), LoadOption.OverwriteChanges, Tables);
                dtoItem.SR = Result;
            }
        }
        return dtoItem;
    }

Body:
Change your command.ExecuteReader to the async version:

public async Task<MDTO> GetIeAsync(MDTO dtoItem)
{
    ...
    connection.Open();
    Result.EnforceConstraints = false;

    SqlDataReader dataReader = await command.ExecuteReaderAsync(CommandBehavior.CloseConnection);
    Result.Load(dataReader, LoadOption.OverwriteChanges, Tables);
    dtoItem.SR = Result;
    ...
}


问:
IE:11 hover on before not working
My link has below structure:

```<code>a{
  // some css here
}
a:before{
 // contains font icon
}
a:hover{
 text-decoration:underline;
}
a:hover:before{
 text-decoration:none;
}
</code>```

I need to add text-decoration:underline only on hover of a link, not on the before part. My code is working perfectly fine on chrome but on IE 11, text-decoration:none is not working for a:hover:before.

答:
What you can do is put the main content of the  in a span, and underline only the span.

a {
  text-decoration:none;
}
a:before {
 content: '➠ ';
}
a:hover span {                 /* changed */
 text-decoration:underline;
}
a:hover:before {
 text-decoration:none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>Click here</span></code>```

Title: IE:11 hover on before not working

Body:
My link has below structure:

a{
  // some css here
}
a:before{
 // contains font icon
}
a:hover{
 text-decoration:underline;
}
a:hover:before{
 text-decoration:none;
}

I need to add text-decoration:underline only on hover of a link, not on the before part. My code is working perfectly fine on chrome but on IE 11, text-decoration:none is not working for a:hover:before.

Body:
What you can do is put the main content of the <a> in a span, and underline only the span.

a {
  text-decoration:none;
}
a:before {
 content: '➠ ';
}
a:hover span {                 /* changed */
 text-decoration:underline;
}
a:hover:before {
 text-decoration:none;
}

<a href="#"><span>Click here</span></a>


问:
What considerations should I take into account when increasing the size in the Scroll API in Elasticsearch?
I am currently toying around with the Scroll API of Elasticsearch, and want to use it to obtain a large set of data and do some manual processing on it. The processing is performed by an external library and is not of the type that can easily be included as a script.

While this seems to work nicely at the moment, I was wondering what considerations that I should take into account when fine-tuning the scroll size for performing this form of processing. A quick observation seems to indicate that increasing the scroll size will reduce the latency of the operation. While I suspect that larger scroll sizes will generally reduce throughput, I have no idea whether this hypothesis is correct. Also, I have no idea if there are any other consequences that I do not envision right now.

So to summarize, my question is: what impact does changing Elasticsearch's scroll size have, especially on performance, in a scenario where the results are processed for each batch that is obtained?

Thanks in advance!

答:
The one (and the only I know of) consideration is to be able to process batch fast enough to not release scroll context (which is controlled by ?scroll=X parameter).

Assuming that you will consume all the data from query, there, scroll should be tuned based on network and 3rd-party app performance. I.e.

if your app can process data in stream-like manner, bigger chunks is better

if your app processing data in batches (waiting for full ES response first), the upper limit for batch size should guarantee processing time < scroll release time

if you work in poor network environment, less batch size is better to handle overhead of dropped connections/retries

generally, bigger batch is obviously better, as it eliminates some network/ES cpu overhead


问:
RxJS publishReplay vs publishLast
I am implementing caching HTTP results in Angular application. From what I know both of the following code works, but I need to know if they are doing exactly the same thing, or I am missing something important?

publishLast

```<code>getPosts() {
    if( !this.posts$ ) {
      this.posts$ = this.http.get('api').publishLast().refCount();
      return this.posts$;
    }

    return this.posts$;
  }
</code>```

publishReplay

```<code>getPosts() {
  if( !this.posts$ ) {
    this.posts$ = this.http.get('api').publishReplay(1).refCount();
       return this.posts$;
  }

  return this.posts$;
}
</code>```

答:
publishLast shares (as the name suggests) the last emitted value - which can only be determined when the stream completes.

publishReplay(1) shares the latest emitted value, which is done after any emission.

In the case of this.http.get(...) the behavior is the same, because the stream will complete after the result was received, thus the last and the latest value are the same thing.

You will have a different result though for streams that emit more than one value or that do not complete immediately after the emission of this value.

Title: RxJS publishReplay vs publishLast

Body:
I am implementing caching HTTP results in Angular application. From what I know both of the following code works, but I need to know if they are doing exactly the same thing, or I am missing something important?

publishLast

getPosts() {
    if( !this.posts$ ) {
      this.posts$ = this.http.get('api').publishLast().refCount();
      return this.posts$;
    }

    return this.posts$;
  }

publishReplay

getPosts() {
  if( !this.posts$ ) {
    this.posts$ = this.http.get('api').publishReplay(1).refCount();
       return this.posts$;
  }

  return this.posts$;
}


问:
OS X Framework Library not loaded: 'Image not found'
I am trying to create a basic OS X Framework, right now I just have a test framework created: TestMacFramework.framework and I'm trying to import it into a brand new OS X Application project.

I have built the .framework file and imported it into the new project, The framework appears to link okay, and I can reference the public header file I added to the framework build phases section.

However, when I try to run the container Application I get the following Error:

```<code>dyld: Library not loaded: /Library/Frameworks/TestMacFramework.framework/Versions/A/TestMacFramework
  Referenced from: /Users/samharman/Library/Developer/Xcode/DerivedData/TestMacContainer-dzabuelobzfknafuhmgooqhqrgzl/Build/Products/Debug/TestMacContainer.app/Contents/MacOS/TestMacContainer
  Reason: image not found
</code>```

After a bit of googling I realised I needed to add a Copy Files section to my container application build phases, so I have done this and set it up like so...

However, I am still getting the runtime error. I'm obviously doing something wrong here, but the Apple developer library resource for this references Xcode 2, so isn't very helpful!

What have I missed?

UPDATE:

I can see in the build log that my TestMacFramework.framework is being copied into the .app contents/frameworks directory, but it isn't being installed to the Library/Frameworks directory on the HD

UPDATE 2:

The build links correctly if I manually copy the TestMacFramework.framework into the Library/Frameworks directory

答: Got the issue when trying Xcode 9 beta and going back to Xcode 8. A simple Clean on the target resolved the issue.</p>

Body:
I am trying to create a basic OS X Framework, right now I just have a test framework created: TestMacFramework.framework and I'm trying to import it into a brand new OS X Application project.

I have built the .framework file and imported it into the new project, The framework appears to link okay, and I can reference the public header file I added to the framework build phases section.

However, when I try to run the container Application I get the following Error:

dyld: Library not loaded: /Library/Frameworks/TestMacFramework.framework/Versions/A/TestMacFramework
  Referenced from: /Users/samharman/Library/Developer/Xcode/DerivedData/TestMacContainer-dzabuelobzfknafuhmgooqhqrgzl/Build/Products/Debug/TestMacContainer.app/Contents/MacOS/TestMacContainer
  Reason: image not found

After a bit of googling I realised I needed to add a Copy Files section to my container application build phases, so I have done this and set it up like so...

However, I am still getting the runtime error. I'm obviously doing something wrong here, but the Apple developer library resource for this references Xcode 2, so isn't very helpful!

What have I missed?

UPDATE:

I can see in the build log that my TestMacFramework.framework is being copied into the .app contents/frameworks directory, but it isn't being installed to the Library/Frameworks directory on the HD

UPDATE 2:

The build links correctly if I manually copy the TestMacFramework.framework into the Library/Frameworks directory


问:
Foreach loop in CodeIgniter
I'm using the CI framework and I'm trying to make a foreach loop so that all products of my site are displayed.

This is my controller file:

```<code>class AlleCadeausController extends CI_Controller {

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus');
}
</code>```

This is my model file:

```<code><?php
class Allecadeaus_model extends CI_Model {
   public function __construct()
   {
       parent::__construct();
   }
    public function get_cadeaus()
    {
        $query = $this->db->query('SELECT * FROM products');
        $result = $query->result_array();
        return $result;
    }
}
</code>```

this is my view:

```<code><?php
foreach ($cadeaus as $cadeau)
{
    echo $cadeau->product_naam;
}
?>
</code>```

The error is:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cadeaus

Filename: views/allecadeaus.php

Line Number: 3

Backtrace:

File: /home/ubuntu/workspace/application/views/allecadeaus.php Line: 3
  Function: _error_handler

File:
  /home/ubuntu/workspace/application/controllers/AlleCadeausController.php
  Line: 11 Function: view

File: /home/ubuntu/workspace/index.php Line: 315 Function:
  require_once

My table name is products

答:
You havn't passed the $data variable in your controller. Please follow below code:

```<code>$this->load->view('allecadeaus', $data);
</code>```

So, your controller function should be like below.

```<code>public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus', $data);

}
</code>```

Cheers, you are done.

Title: Foreach loop in CodeIgniter

Body:
I'm using the CI framework and I'm trying to make a foreach loop so that all products of my site are displayed.

This is my controller file:

class AlleCadeausController extends CI_Controller {

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus');
}

This is my model file:

<?php
class Allecadeaus_model extends CI_Model {
   public function __construct()
   {
       parent::__construct();
   }
    public function get_cadeaus()
    {
        $query = $this->db->query('SELECT * FROM products');
        $result = $query->result_array();
        return $result;
    }
}

this is my view:

<?php
foreach ($cadeaus as $cadeau)
{
    echo $cadeau->product_naam;
}
?>

The error is:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cadeaus

Filename: views/allecadeaus.php

Line Number: 3

Backtrace:

File: /home/ubuntu/workspace/application/views/allecadeaus.php Line: 3
  Function: _error_handler

File:
  /home/ubuntu/workspace/application/controllers/AlleCadeausController.php
  Line: 11 Function: view

File: /home/ubuntu/workspace/index.php Line: 315 Function:
  require_once

My table name is products

Body:
You havn't passed the $data variable in your controller. Please follow below code:

$this->load->view('allecadeaus', $data);

So, your controller function should be like below.

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus', $data);

}

Cheers, you are done.


问:
How is a random number generated at runtime?
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

```<code>Random.Next()
</code>```

What happens inside?

答:
Knuth covers the topic of randomness very well.

We don't really understand random well.  How can something predictable be random?  And yet pseudo-random sequences can appear to be perfectly random by statistical tests.

There are three categories of Random generators, amplifying on the comment above.

First, you have pseudo random number generators where if you know the current random number, it's easy to compute the next one. This makes it easy to reverse engineer other numbers if you find out a few.

Then, there are cryptographic algorithms that make this much harder.  I believe they still are pseudo random sequences (contrary to what the comment above implies), but with the very important property that knowing a few numbers in the sequence does NOT make it obvious how to compute the rest.  The way it works is that crypto routines tend to hash up the number, so that if one bit changes, every bit is equally likely to change as a result.

Consider a simple modulo generator (similar to some implementations in C rand() )

int rand() {
  return seed = seed * m + a;
}

if m=0 and a=0, this is a lousy generator with period 1: 0, 0, 0, 0, ....
if m=1 and a=1, it's also not very random looking: 0, 1, 2, 3, 4, 5, 6, ...

But if you pick m and a to be prime numbers around 2^16, this will jump around nicely looking very random if you are casually inspecting.  But because both numbers are odd, you would see that the low bit would toggle, ie the number is alternately odd and even.  Not a great random number generator.  And since there are only 2^32 values in a 32 bit number, by definition after 2^32 iterations at most, you will repeat the sequence again, making it obvious that the generator is NOT random.

If you think of the middle bits as nice and scrambled, while the lower ones aren't as random, then you can construct a better random number generator out of a few of these, with the various bits XORed together so that all the bits are covered well.  Something like:

(rand1() >> 8) ^ rand2() ^ (rand3() > 5) ...

Still, every number is flipping in synch, which makes this predictable.  And if you get two sequential values they are correlated, so that if you plot them you will get lines on your screen.  Now imagine you have rules combining the generators, so that sequential values are not the next ones.
For example

v1 = rand1() >> 8 ^ rand2() ...
v2 = rand2() >> 8 ^ rand5() ..

and imagine that the seeds don't always advance.  Now you're starting to make something that's much harder to predict based on reverse engineering, and the sequence is longer.

For example, if you compute rand1() every time, but only advance the seed in rand2() every 3rd time, a generator combining them might not repeat for far longer than the period of either one.

Now imagine that you pump your (fairly predictable) modulo-type random number generator through DES or some other encryption algorithm.  That will scramble up the bits.

Obviously, there are better algorithms, but this gives you an idea.  Numerical Recipes has a lot of algorithms implemented in code and explained.  One very good trick: generate not one but a block of random values in a table.  Then use an independent random number generator to pick one of the generated numbers, generate a new one and replace it.  This breaks up any correlation between adjacent pairs of numbers.

The third category is actual hardware-based random number generators, for example based on atmospheric noise

http://www.random.org/randomness/

This is, according to current science, truly random.  Perhaps someday we will discover that it obeys some underlying rule, but currently, we cannot predict these values, and they are "truly" random as far as we are concerned.

The boost library has excellent C++ implementations of Fibonacci generators, the reigning kings of pseudo-random sequences if you want to see some source code.

Body:
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

Random.Next()

What happens inside?