答:
```<code>data.columns=['Value','Interval']

data['Ingroup'] = (data['Interval'].notnull() + 0)

Use data['Interval'].notnull() to separate the groups...
Use cumsum() to number them with `groupno`...
Use groupby(groupno)..

Finally you want something using apply/idxmax/idxmin to label the max/min

But of course a for-loop as you suggested is the non-Pythonic but possibly simpler hack.
</code>```

Title: Find the highest and lowest value locations within an interval on a column?

Body:
Given this pandas dataframe with two columns, 'Values' and 'Intervals'. How do I get a third column 'MinMax' indicating whether the value is a maximum or a minimum within that interval? The challenge for me is that the interval length and the distance between intervals are not fixed, therefore I post the question.

import pandas as pd
import numpy as np

data = pd.DataFrame([
        [1879.289,np.nan],[1879.281,np.nan],[1879.292,1],[1879.295,1],[1879.481,1],[1879.294,1],[1879.268,1],
        [1879.293,1],[1879.277,1],[1879.285,1],[1879.464,1],[1879.475,1],[1879.971,1],[1879.779,1],
        [1879.986,1],[1880.791,1],[1880.29,1],[1879.253,np.nan],[1878.268,np.nan],[1875.73,1],[1876.792,1],
        [1875.977,1],[1876.408,1],[1877.159,1],[1877.187,1],[1883.164,1],[1883.171,1],[1883.495,1],
        [1883.962,1],[1885.158,1],[1885.974,1],[1886.479,np.nan],[1885.969,np.nan],[1884.693,1],[1884.977,1],
        [1884.967,1],[1884.691,1],[1886.171,1],[1886.166,np.nan],[1884.476,np.nan],[1884.66,1],[1882.962,1],
        [1881.496,1],[1871.163,1],[1874.985,1],[1874.979,1],[1871.173,np.nan],[1871.973,np.nan],[1871.682,np.nan],
        [1872.476,np.nan],[1882.361,1],[1880.869,1],[1882.165,1],[1881.857,1],[1880.375,1],[1880.66,1],
        [1880.891,1],[1880.377,1],[1881.663,1],[1881.66,1],[1877.888,1],[1875.69,1],[1875.161,1],
        [1876.697,np.nan],[1876.671,np.nan],[1879.666,np.nan],[1877.182,np.nan],[1878.898,1],[1878.668,1],[1878.871,1],
        [1878.882,1],[1879.173,1],[1878.887,1],[1878.68,1],[1878.872,1],[1878.677,1],[1877.877,1],
        [1877.669,1],[1877.69,1],[1877.684,1],[1877.68,1],[1877.885,1],[1877.863,1],[1877.674,1],
        [1877.676,1],[1877.687,1],[1878.367,1],[1878.179,1],[1877.696,1],[1877.665,1],[1877.667,np.nan],
        [1878.678,np.nan],[1878.661,1],[1878.171,1],[1877.371,1],[1877.359,1],[1878.381,1],[1875.185,1],
        [1875.367,np.nan],[1865.492,np.nan],[1865.495,1],[1866.995,1],[1866.672,1],[1867.465,1],[1867.663,1],
        [1867.186,1],[1867.687,1],[1867.459,1],[1867.168,1],[1869.689,1],[1869.693,1],[1871.676,1],
        [1873.174,1],[1873.691,np.nan],[1873.685,np.nan]
    ])

In the third column below you can see where the max and min is for each interval.

+-------+----------+-----------+---------+
| index |  Value   | Intervals | Min/Max |
+-------+----------+-----------+---------+
|     0 | 1879.289 | np.nan    |         |
|     1 | 1879.281 | np.nan    |         |
|     2 | 1879.292 | 1         |         |
|     3 | 1879.295 | 1         |         |
|     4 | 1879.481 | 1         |         |
|     5 | 1879.294 | 1         |         |
|     6 | 1879.268 | 1         | min     |
|     7 | 1879.293 | 1         |         |
|     8 | 1879.277 | 1         |         |
|     9 | 1879.285 | 1         |         |
|    10 | 1879.464 | 1         |         |
|    11 | 1879.475 | 1         |         |
|    12 | 1879.971 | 1         |         |
|    13 | 1879.779 | 1         |         |
|    17 | 1879.986 | 1         |         |
|    18 | 1880.791 | 1         | max     |
|    19 |  1880.29 | 1         |         |
|    55 | 1879.253 | np.nan    |         |
|    56 | 1878.268 | np.nan    |         |
|    57 |  1875.73 | 1         |         |
|    58 | 1876.792 | 1         |         |
|    59 | 1875.977 | 1         | min     |
|    60 | 1876.408 | 1         |         |
|    61 | 1877.159 | 1         |         |
|    62 | 1877.187 | 1         |         |
|    63 | 1883.164 | 1         |         |
|    64 | 1883.171 | 1         |         |
|    65 | 1883.495 | 1         |         |
|    66 | 1883.962 | 1         |         |
|    67 | 1885.158 | 1         |         |
|    68 | 1885.974 | 1         | max     |
|    69 | 1886.479 | np.nan    |         |
|    70 | 1885.969 | np.nan    |         |
|    71 | 1884.693 | 1         |         |
|    72 | 1884.977 | 1         |         |
|    73 | 1884.967 | 1         |         |
|    74 | 1884.691 | 1         | min     |
|    75 | 1886.171 | 1         | max     |
|    76 | 1886.166 | np.nan    |         |
|    77 | 1884.476 | np.nan    |         |
|    78 |  1884.66 | 1         | max     |
|    79 | 1882.962 | 1         |         |
|    80 | 1881.496 | 1         |         |
|    81 | 1871.163 | 1         | min     |
|    82 | 1874.985 | 1         |         |
|    83 | 1874.979 | 1         |         |
|    84 | 1871.173 | np.nan    |         |
|    85 | 1871.973 | np.nan    |         |
|    86 | 1871.682 | np.nan    |         |
|    87 | 1872.476 | np.nan    |         |
|    88 | 1882.361 | 1         | max     |
|    89 | 1880.869 | 1         |         |
|    90 | 1882.165 | 1         |         |
|    91 | 1881.857 | 1         |         |
|    92 | 1880.375 | 1         |         |
|    93 |  1880.66 | 1         |         |
|    94 | 1880.891 | 1         |         |
|    95 | 1880.377 | 1         |         |
|    96 | 1881.663 | 1         |         |
|    97 |  1881.66 | 1         |         |
|    98 | 1877.888 | 1         |         |
|    99 |  1875.69 | 1         |         |
|   100 | 1875.161 | 1         | min     |
|   101 | 1876.697 | np.nan    |         |
|   102 | 1876.671 | np.nan    |         |
|   103 | 1879.666 | np.nan    |         |
|   111 | 1877.182 | np.nan    |         |
|   112 | 1878.898 | 1         |         |
|   113 | 1878.668 | 1         |         |
|   114 | 1878.871 | 1         |         |
|   115 | 1878.882 | 1         |         |
|   116 | 1879.173 | 1         | max     |
|   117 | 1878.887 | 1         |         |
|   118 |  1878.68 | 1         |         |
|   119 | 1878.872 | 1         |         |
|   120 | 1878.677 | 1         |         |
|   121 | 1877.877 | 1         |         |
|   122 | 1877.669 | 1         |         |
|   123 |  1877.69 | 1         |         |
|   124 | 1877.684 | 1         |         |
|   125 |  1877.68 | 1         |         |
|   126 | 1877.885 | 1         |         |
|   127 | 1877.863 | 1         |         |
|   128 | 1877.674 | 1         |         |
|   129 | 1877.676 | 1         |         |
|   130 | 1877.687 | 1         |         |
|   131 | 1878.367 | 1         |         |
|   132 | 1878.179 | 1         |         |
|   133 | 1877.696 | 1         |         |
|   134 | 1877.665 | 1         | min     |
|   135 | 1877.667 | np.nan    |         |
|   136 | 1878.678 | np.nan    |         |
|   137 | 1878.661 | 1         | max     |
|   138 | 1878.171 | 1         |         |
|   139 | 1877.371 | 1         |         |
|   140 | 1877.359 | 1         |         |
|   141 | 1878.381 | 1         |         |
|   142 | 1875.185 | 1         | min     |
|   143 | 1875.367 | np.nan    |         |
|   144 | 1865.492 | np.nan    |         |
|   145 | 1865.495 | 1         | max     |
|   146 | 1866.995 | 1         |         |
|   147 | 1866.672 | 1         |         |
|   148 | 1867.465 | 1         |         |
|   149 | 1867.663 | 1         |         |
|   150 | 1867.186 | 1         |         |
|   151 | 1867.687 | 1         |         |
|   152 | 1867.459 | 1         |         |
|   153 | 1867.168 | 1         |         |
|   154 | 1869.689 | 1         |         |
|   155 | 1869.693 | 1         |         |
|   156 | 1871.676 | 1         |         |
|   157 | 1873.174 | 1         | min     |
|   158 | 1873.691 | np.nan    |         |
|   159 | 1873.685 | np.nan    |         |
+-------+----------+-----------+---------+


来源: stackexchange

问:
How do I return my List
This code works according to test cases. I have to get my getList() function to return my List. The problem is that it won't return the list because the size of the List = 0. The size can't increase because according to my test cases the addURLID(int urlID) method can't add to the List until the size of the List is at least 1. Any type of help would be appreciated especially in getList().

```<code>import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Word extends Object implements Serializable {

    private List<Integer> postings = new ArrayList<>();
    static long serialVersionUID = -3696191086353573895L;
    private String word;
    private int urlID;

    public Word(String word, int urlID) {
        this.word = word;
        this.urlID = urlID;
    }

    public void addURLID(int urlID) {
        postings.add(urlID);
    }

    public List<Integer> getList(){
        List<Integer> postings = new ArrayList<>();
        return postings;
    }
}
</code>```

答:
Your getList() method, is creating a completely new list locally and returning it to the calling function. Thus it will always return an empty list.

 instead, you must simply return the existing list (attribute of class)

```<code>public List<Integer> getList(){
    return this.postings;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How do I return my List

Body:
This code works according to test cases. I have to get my getList() function to return my List. The problem is that it won't return the list because the size of the List = 0. The size can't increase because according to my test cases the addURLID(int urlID) method can't add to the List until the size of the List is at least 1. Any type of help would be appreciated especially in getList().

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Word extends Object implements Serializable {

    private List<Integer> postings = new ArrayList<>();
    static long serialVersionUID = -3696191086353573895L;
    private String word;
    private int urlID;

    public Word(String word, int urlID) {
        this.word = word;
        this.urlID = urlID;
    }

    public void addURLID(int urlID) {
        postings.add(urlID);
    }

    public List<Integer> getList(){
        List<Integer> postings = new ArrayList<>();
        return postings;
    }
}

Body:
Your getList() method, is creating a completely new list locally and returning it to the calling function. Thus it will always return an empty list.

 instead, you must simply return the existing list (attribute of class)

public List<Integer> getList(){
    return this.postings;
}


问:
Is there a way to define implicit conversion operators in C# for specific versions of generic types?
I have a generic class, MyClass<T>, and I want to be able to implicitly convert from some type, e.g. bool, to a specific version of the generic type, e.g. MyClass<string>. It seems I cannot use any of the following:

fails because "Using the generic type 'MyClass<T>' requires '1' type argument(s)":

public static implicit operator MyClass(bool value) {
    return new MyClass<string>(value.ToString());
}

fails because "Unbound generic name is not valid in this context" and because "User-defined conversion must convert to or from the enclosing type":

public static implicit operator MyClass<>(bool value) {
    return new MyClass<string>(value.ToString());
}

fails because "User-defined conversion must convert to or from the enclosing type":

public static implicit operator MyClass<string>(bool value) {
    return new MyClass<string>(value.ToString());
}

fails because "Cannot implicitly convert type 'MyClass<string>' to 'MyClass<T>'":

public static implicit operator MyClass<T>(bool value) {
    return new MyClass<string>(value.ToString());
}

Is there any way this can be achieved, or will I just have to live without it (and incur explicit calls to a conversion method everywhere)?

答:
No, you can't do this. The C# specification is clear, your implicit operator must convert either to or from the type in which it's declared. It has to be an exact conversion, and since the declaring type is exactly MyClass<T>, the conversion has to be either to or from that.

See e.g. Can i use a generic implicit or explicit operator? C# and C# Implicit operator with generic.

At the risk of condoning or endorsing an XY Problem, here are a couple of hacky alternatives:

```<code>// Break generics by checking the type explicitly. Requires ugly casting
// and intermediate boxing, though it's possible that with some run-time
// use of Expressions, you could cache a delegate that would handle the
// conversion without the boxing. It'd still be ugly though.
class Class1<T>
{
    public Class1(T t) { }

    public static implicit operator Class1<T>(bool value)
    {
        if (typeof(T) == typeof(string))
        {
            return (Class1<T>)(object)(Class1OfString)value;
        }

        throw new InvalidOperationException("Invalid type T");
    }
}

// Subclass the generic, and declare the conversion there. Of course, then
// to use the conversion, you have to reference this type explicitly. Ugly.
class Class1OfString : Class1<string>
{
    public Class1OfString(string text) : base(text) { }

    public static implicit operator Class1OfString(bool value)
    {
        return new Class1OfString(value.ToString());
    }
}

class A
{
    public static void M()
    {
        // These all compile and execute fine
        Class1OfString c1 = true;
        Class1<string> c2 = (Class1OfString)true;
        Class1<string> c3 = true;
    }
}
</code>```

There are a number of variations on the themes above, but they all will involve circumventing and special casing the type in some way.

It is worth pointing out that, besides the difficulty dealing with the generic vs. specific here, the use of implicit is suspect for other reasons. The documentation states right at the top that one should use implicit only "if the conversion is guaranteed not to cause a loss of data" and implementations "should never throw exceptions". In both cases, this is "so that they can be used safely without the programmer's awareness". In other words, the very nature of implicit is that they get invoked implicitly, without the programmer necessarily even thinking about it. So they must always work, which wouldn't necessarily be the case with some of the examples above (and in one example, you have to use an explicit syntax anyway, so you might as well implement the operator as explicit anyway).

None of these options are ideal. But frankly, neither is the original scenario. It is odd for a generic type to have to deal with concrete types on a specific basis. It calls into question whether the generic type really should be generic in the first place. It is possible that you really should be doing something more like the subclassing example above, only applied further. I.e. use the generic type for whatever base behavior you need, but put all your specializations into a subclass where you know the type parameter T.

I can't offer more advice than that, given the lack of details in the question. But the basic request is shaky enough to suggest that, if only the question had included a broader problem statement and details about what led you to this actual implementation goal, a better and more applicable answer might have been provided.

Body:
No, you can't do this. The C# specification is clear, your implicit operator must convert either to or from the type in which it's declared. It has to be an exact conversion, and since the declaring type is exactly MyClass<T>, the conversion has to be either to or from that.

See e.g. Can i use a generic implicit or explicit operator? C# and C# Implicit operator with generic.

At the risk of condoning or endorsing an XY Problem, here are a couple of hacky alternatives:

// Break generics by checking the type explicitly. Requires ugly casting
// and intermediate boxing, though it's possible that with some run-time
// use of Expressions, you could cache a delegate that would handle the
// conversion without the boxing. It'd still be ugly though.
class Class1<T>
{
    public Class1(T t) { }

    public static implicit operator Class1<T>(bool value)
    {
        if (typeof(T) == typeof(string))
        {
            return (Class1<T>)(object)(Class1OfString)value;
        }

        throw new InvalidOperationException("Invalid type T");
    }
}

// Subclass the generic, and declare the conversion there. Of course, then
// to use the conversion, you have to reference this type explicitly. Ugly.
class Class1OfString : Class1<string>
{
    public Class1OfString(string text) : base(text) { }

    public static implicit operator Class1OfString(bool value)
    {
        return new Class1OfString(value.ToString());
    }
}

class A
{
    public static void M()
    {
        // These all compile and execute fine
        Class1OfString c1 = true;
        Class1<string> c2 = (Class1OfString)true;
        Class1<string> c3 = true;
    }
}

There are a number of variations on the themes above, but they all will involve circumventing and special casing the type in some way.

It is worth pointing out that, besides the difficulty dealing with the generic vs. specific here, the use of implicit is suspect for other reasons. The documentation states right at the top that one should use implicit only "if the conversion is guaranteed not to cause a loss of data" and implementations "should never throw exceptions". In both cases, this is "so that they can be used safely without the programmer's awareness". In other words, the very nature of implicit is that they get invoked implicitly, without the programmer necessarily even thinking about it. So they must always work, which wouldn't necessarily be the case with some of the examples above (and in one example, you have to use an explicit syntax anyway, so you might as well implement the operator as explicit anyway).

None of these options are ideal. But frankly, neither is the original scenario. It is odd for a generic type to have to deal with concrete types on a specific basis. It calls into question whether the generic type really should be generic in the first place. It is possible that you really should be doing something more like the subclassing example above, only applied further. I.e. use the generic type for whatever base behavior you need, but put all your specializations into a subclass where you know the type parameter T.

I can't offer more advice than that, given the lack of details in the question. But the basic request is shaky enough to suggest that, if only the question had included a broader problem statement and details about what led you to this actual implementation goal, a better and more applicable answer might have been provided.


问:
I am unable to debug with VS Code, node.js & SPFx
I completed the HelloWorld webpart in https://dev.office.com/sharepoint/docs/spfx/web-parts/get-started/build-a-hello-world-web-part, and enhanced that webpart to connect to SharePoint following https://dev.office.com/sharepoint/docs/spfx/web-parts/get-started/connect-to-sharepoint. Everything works fine in localhost, but the connection to SharePoint doesn't work in my dev tenant (the basic HelloWorld webpart does work there).

I am using VSCode 1.7.2; Node 6.5.0; Shell 1.3.8; and Renderer 52.0.274382.

I generated a new launch.json using node.js and corrected "program": "${workspaceRoot}\src\webparts\helloworld\HelloWorldWebPart.ts"

When I Launch Program, I get: "Cannot lanch program…; setting the 'outFiles' attribute might help."

I entered "outFiles": ["${workspaceRoot}\lib\webparts\helloworld\HelloWorldWebPart.ts"], but I still get exactly the same error.

Next, I tried Attach to Process: first I ran the command Tasks: Run Task; serve. This opened the localhost page in Chrome. Then I hit Attach to Process. Results:  "Debug: Attach to Process: Cannot connect to runtime process, (timeout. After 10000ms)."

I am using an Azure Windows 10 VM.

Many thanks for your time, effort and generosity!!!

答:
The official documents from the Office Dev team here:
https://dev.office.com/sharepoint/docs/spfx/debug-in-vscode

I found very useful article here:
http://www.eliostruyf.com/how-to-debug-your-sharepoint-framework-web-part

I also created one here:
http://blog.velingeorgiev.pro/how-debug-sharepoint-framework-webpart-visual-studio-code

Gist with the launch.json config here:
https://gist.github.com/VelinGeorgiev/4a7b77ced7198df0a3898420d46f3405

The config pasted here for quick reference:

```<code>// Use Chrome browser to debug SharePoint Framework React webpart with Visual Studio Code on Windows
// - Install "Debugger for Chrome" extension
// - Add this configuration to the launch.json
// - Close all Chrome browser active instances
// - Start the SPFx nodejs server by executing "gulp serve"
// - Go to VS Code debug view (top menu -> View -> Debug)
// - Hit the play (start debugging) button
// Happy debugging!
// Full guides
// http://blog.velingeorgiev.pro/how-debug-sharepoint-framework-webpart-visual-studio-code
// https://dev.office.com/sharepoint/docs/spfx/debug-in-vscode
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "SPFx Local",
            "type": "chrome",
            "request": "launch",
            "url": "https://localhost:4321/temp/workbench.html",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../../*": "${webRoot}/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        },
        {
            "name": "SPFx Online",
            "type": "chrome",
            "request": "launch",
            "url": "https://<your_tenant>.sharepoint.com/sites/<your_site>/SitePages/<your_webpart_page>.aspx",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../../*": "${webRoot}/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        },
        {
            "name": "SPFx Online Workbench",
            "type": "chrome",
            "request": "launch",
            "url": "https://<your_tenant>.sharepoint.com/_layouts/workbench.aspx",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../../*": "${webRoot}/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        }
    ]
}
</code>```

Please let me know if any issues.

Body:
The official documents from the Office Dev team here:
https://dev.office.com/sharepoint/docs/spfx/debug-in-vscode

I found very useful article here:
http://www.eliostruyf.com/how-to-debug-your-sharepoint-framework-web-part

I also created one here:
http://blog.velingeorgiev.pro/how-debug-sharepoint-framework-webpart-visual-studio-code

Gist with the launch.json config here:
https://gist.github.com/VelinGeorgiev/4a7b77ced7198df0a3898420d46f3405

The config pasted here for quick reference:

// Use Chrome browser to debug SharePoint Framework React webpart with Visual Studio Code on Windows
// - Install "Debugger for Chrome" extension
// - Add this configuration to the launch.json
// - Close all Chrome browser active instances
// - Start the SPFx nodejs server by executing "gulp serve"
// - Go to VS Code debug view (top menu -> View -> Debug)
// - Hit the play (start debugging) button
// Happy debugging!
// Full guides
// http://blog.velingeorgiev.pro/how-debug-sharepoint-framework-webpart-visual-studio-code
// https://dev.office.com/sharepoint/docs/spfx/debug-in-vscode
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "SPFx Local",
            "type": "chrome",
            "request": "launch",
            "url": "https://localhost:4321/temp/workbench.html",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../../*": "${webRoot}/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        },
        {
            "name": "SPFx Online",
            "type": "chrome",
            "request": "launch",
            "url": "https://<your_tenant>.sharepoint.com/sites/<your_site>/SitePages/<your_webpart_page>.aspx",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../../*": "${webRoot}/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        },
        {
            "name": "SPFx Online Workbench",
            "type": "chrome",
            "request": "launch",
            "url": "https://<your_tenant>.sharepoint.com/_layouts/workbench.aspx",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../../*": "${webRoot}/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        }
    ]
}

Please let me know if any issues.


问:
Check if variable is of type int/Integer
I am currently using

```<code>if (element instanceof Integer)
    return true;
else
    return false;
</code>```

but if

```<code>String element = "5";
</code>```

it will return true. I only want it to return true if elements TRULY is an integer value.

My motivation for this is an exercise at school where I had to make an abstract super-class ObservableList.java with a List elements, and then my sub-class Observable HighscoreList.java has an acceptElement(Object element) method that returns true if elements is the correct dataype for that subclass, and the method is called from an addResult(int element) method. In my case I need integers, and String or chars masked as an integer value is not ok.

Sub-class methods:

```<code>boolean acceptsElement(Object element) {
    if (element instanceof Integer)
        return true;
    else
        return false;
}

public void addResult(int element) {
    int elementsInt;
    if (acceptsElement(element)) {
        for (int i = 0; i < maxSize; i++) {

            try {
                // parsing to int since elements type Object
                elementsInt = (int) elements.get(i);
            } catch (IndexOutOfBoundsException e) {
                elementsInt = 0;
            }

            // adds element to correct position
            if (element < elementsInt || elementsInt == 0) {
                elements.add(i, element);

                // update listeners with new list and position of change
                for (ObservableListListener listListener : listListeners) {
                    listListener.listChanged(this, i);
                }

                // removes elements outside of maxSize
                if (elements.size() >= maxSize) {
                    for (int j = maxSize; j < elements.size(); j++) {
                        elements.remove(j);
                    }
                }
                break;
            }
        }
    } else
        throw new IllegalArgumentException("!acceptsElement()");
}
</code>```

super-class methods:

```<code>public List<Object> elements;
public List<ObservableListListener> listListeners;

abstract boolean acceptsElement(Object element);

    protected void addElement(int index, Object element) {
        if (this.acceptsElement(element)) {
            elements.add(index, element);

            // update listeners with new list and position of change
            for (ObservableListListener listListener : listListeners) {
                listListener.listChanged(this, index);
            }
        } else
            throw new IllegalArgumentException("!acceptsElements()");
    }
</code>```

I am afraid I am very locked down in terms of how to organize everything. I need to pass a jTest program. It tells me that I should have thrown an IllegalArgumentException for "observableList.addElement("5");"

答:
I was missing the

```<code>else
    throw new IllegalArgumentException("!acceptsElement()");
</code>```

Inside the addElement(Object element)-method. I only had it in the addElement(int index, Object element)-method.

Super-class now looks more like this:

```<code>public List<Object> elements;
public List<ObservableListListener> listListeners;

    abstract boolean acceptsElement(Object element);

    protected void addElement(int index, Object element) {
        if (acceptsElement(element)) {
            elements.add(index, element);

        // update listeners with new list and position of change
        for (ObservableListListener listListener : listListeners) {
            listListener.listChanged(this, index);
        }
    } else
        throw new IllegalArgumentException("!acceptsElement()");
}

protected void addElement(Object element) {
    if (acceptsElement(element)) {
        elements.add(element);

        // update listeners with new list and position of change
        for (ObservableListListener listListener : listListeners) {
            listListener.listChanged(this, elements.indexOf(element));
        }
    } else
        throw new IllegalArgumentException("!acceptsElement()");
}
</code>```

Body:
I am currently using

if (element instanceof Integer)
    return true;
else
    return false;

but if

String element = "5";

it will return true. I only want it to return true if elements TRULY is an integer value.

My motivation for this is an exercise at school where I had to make an abstract super-class ObservableList.java with a List elements, and then my sub-class Observable HighscoreList.java has an acceptElement(Object element) method that returns true if elements is the correct dataype for that subclass, and the method is called from an addResult(int element) method. In my case I need integers, and String or chars masked as an integer value is not ok.

Sub-class methods:

boolean acceptsElement(Object element) {
    if (element instanceof Integer)
        return true;
    else
        return false;
}

public void addResult(int element) {
    int elementsInt;
    if (acceptsElement(element)) {
        for (int i = 0; i < maxSize; i++) {

            try {
                // parsing to int since elements type Object
                elementsInt = (int) elements.get(i);
            } catch (IndexOutOfBoundsException e) {
                elementsInt = 0;
            }

            // adds element to correct position
            if (element < elementsInt || elementsInt == 0) {
                elements.add(i, element);

                // update listeners with new list and position of change
                for (ObservableListListener listListener : listListeners) {
                    listListener.listChanged(this, i);
                }

                // removes elements outside of maxSize
                if (elements.size() >= maxSize) {
                    for (int j = maxSize; j < elements.size(); j++) {
                        elements.remove(j);
                    }
                }
                break;
            }
        }
    } else
        throw new IllegalArgumentException("!acceptsElement()");
}

super-class methods:

public List<Object> elements;
public List<ObservableListListener> listListeners;

abstract boolean acceptsElement(Object element);

    protected void addElement(int index, Object element) {
        if (this.acceptsElement(element)) {
            elements.add(index, element);

            // update listeners with new list and position of change
            for (ObservableListListener listListener : listListeners) {
                listListener.listChanged(this, index);
            }
        } else
            throw new IllegalArgumentException("!acceptsElements()");
    }

I am afraid I am very locked down in terms of how to organize everything. I need to pass a jTest program. It tells me that I should have thrown an IllegalArgumentException for "observableList.addElement("5");"

Body:
I was missing the

else
    throw new IllegalArgumentException("!acceptsElement()");

Inside the addElement(Object element)-method. I only had it in the addElement(int index, Object element)-method.

Super-class now looks more like this:

public List<Object> elements;
public List<ObservableListListener> listListeners;

    abstract boolean acceptsElement(Object element);

    protected void addElement(int index, Object element) {
        if (acceptsElement(element)) {
            elements.add(index, element);

        // update listeners with new list and position of change
        for (ObservableListListener listListener : listListeners) {
            listListener.listChanged(this, index);
        }
    } else
        throw new IllegalArgumentException("!acceptsElement()");
}

protected void addElement(Object element) {
    if (acceptsElement(element)) {
        elements.add(element);

        // update listeners with new list and position of change
        for (ObservableListListener listListener : listListeners) {
            listListener.listChanged(this, elements.indexOf(element));
        }
    } else
        throw new IllegalArgumentException("!acceptsElement()");
}


问:
UISplitScreenController with very many (over 20) detail views
I have inherited an app that I am to update to Swift. It currently contains a TableView that selects one of twenty-six specialized calculators, each in its own ViewController/XIB file.

My first instinct is to use a Master-Detail project template and gain the advantages of the SplitView controller. All examples I have seen for a Swift app of this sort use a storyboard with explicit DetailViewControllers and Segues. It seems wrong for me to storyboard 26 separate view controllers! Is there a way to programmatically select/instantiate the DetailViewController but still use the Master-Detail paradigm?

答: Gilles Major confirms the problems I was encountering. I have therefore abandoned the attempt to use a UISplitViewController for this project, and have instead implemented a UITableViewController with each cell segueing to the appropriate ViewController.</p>


问:
Updating a MySQL table with the COUNT of another
I'm trying to update a column in table Profiles with a COUNT from another table Videos.  All videos are stored in the Videos table, and I want to create a column in Profiles called VideoCount which shows the COUNT of that user's videos in the Videos table.

Basically, I want to run a cron job - so I need to know how to find the COUNT of a user's videos in the Videos table and then UPDATE that user's VideoCount in Profiles with this count number.

To identify who's uploaded which video, Videos.Owner and Profiles.ID should be made to match.  Does anybody know the SQL which I need to run for the PHP file cron job?

答:
```<code>UPDATE Profiles
SET VideoCount = (
   SELECT COUNT(*)
   FROM Videos
   WHERE Videos.Owner = Profiles.ID);
</code>```

as simple as it can be^^

and if you want it fancy: all the triggers you might need:

```<code>DELIMITER //

CREATE TRIGGER increaseVideoCount AFTER INSERT ON Videos
  FOR EACH ROW BEGIN
    UPDATE Profiles SET VideoCount = VideoCount + 1 WHERE ID = NEW.Owner;
  END;
//

CREATE TRIGGER decreaseVideoCount AFTER DELETE ON Videos
  FOR EACH ROW BEGIN
    UPDATE Profiles SET VideoCount = VideoCount - 1 WHERE ID = OLD.Owner;
  END;
//

CREATE TRIGGER checkVideoCount AFTER UPDATE ON Videos
  FOR EACH ROW BEGIN
    IF OLD.Owner <> NEW.Owner THEN
      UPDATE Profiles SET VideoCount = VideoCount + 1 WHERE ID = NEW.Owner;
      UPDATE Profiles SET VideoCount = VideoCount - 1 WHERE ID = OLD.Owner;
    END IF;
  END;
//

DELIMITER ;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
UPDATE Profiles
SET VideoCount = (
   SELECT COUNT(*)
   FROM Videos
   WHERE Videos.Owner = Profiles.ID);

as simple as it can be^^

and if you want it fancy: all the triggers you might need:

DELIMITER //

CREATE TRIGGER increaseVideoCount AFTER INSERT ON Videos
  FOR EACH ROW BEGIN
    UPDATE Profiles SET VideoCount = VideoCount + 1 WHERE ID = NEW.Owner;
  END;
//

CREATE TRIGGER decreaseVideoCount AFTER DELETE ON Videos
  FOR EACH ROW BEGIN
    UPDATE Profiles SET VideoCount = VideoCount - 1 WHERE ID = OLD.Owner;
  END;
//

CREATE TRIGGER checkVideoCount AFTER UPDATE ON Videos
  FOR EACH ROW BEGIN
    IF OLD.Owner <> NEW.Owner THEN
      UPDATE Profiles SET VideoCount = VideoCount + 1 WHERE ID = NEW.Owner;
      UPDATE Profiles SET VideoCount = VideoCount - 1 WHERE ID = OLD.Owner;
    END IF;
  END;
//

DELIMITER ;


问:
How can I place a
 just above the centre using bootstrap behind a background image?
I'm trying to place the picture of mine which is
 on top of the background image which is
 just above the center using bootstrap.

However, the background color and image both appear above my picture. I'm looking for the background image to go behind my picture and for the background color not to be seen at this moment in time.

Please don't delete the background color if you decide to help me as I want to do something with it at a later stage.

Please open the snippet in full screen to see my issue.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code>!DOCTYPE html>
<html lang="en">
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.js"></script>
   </head>

   <body>
      <nav class="navbar navbar-default navbar-fixed-top">
         <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               <span class="sr-only">Toggle navigation</span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               </button>
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
               <ul class="nav navbar-nav">
                  <li>Home
                  </li>
                  <li class="dropdown">
                     About Me <span class="caret"></span>
                     <ul class="dropdown-menu">
                        <li>Action
                        </li>
                        <li>Contact
                        </li>
                        <li>Something else here
                        </li>
                        <li>Separated link
                        </li>
                        <li>One more separated link
                        </li>
                     </ul>
                  </li>
                  <li class="dropdown">
                     Units <span class="caret"></span>
                     <ul class="dropdown-menu">
                        <li>Action
                        </li>
                        <li>Another action
                        </li>
                        <li>Something else here
                        </li>
                        <li>Separated link
                        </li>
                        <li>One more separated link
                        </li>
                     </ul>
                  </li>
                  <li>Clients
                  </li>
                  <li>Contact Me
                  </li>
               </ul>
            </div>
            <!-- /.navbar-collapse -->
         </div>
         <!-- /.container-fluid -->
      </nav>
      <div id="sections">
         <div class="section one">
            <div class="shape"></div>
            <div class="hero"></div>
             <i class="fa fa-angle-down" style="font-size:100px;"></i>
         </div>
         <div class="section two"></div>
             <i class="fa fa-angle-up" style="font-size:100px;"></i>
      </div>
      <script>
         $(document).ready(function() {
           $('#sections').fullpage();
         });
      </script>
   </body>
</html></code>```

答:
You can do this by following the steps below:

add position: absolute to .shape to overlap the hero image.

add z-index: 10 to get .shape on top of .hero image

Now, to center align a positioned element, keep in mind the following trick:

use left: 50% to put the positioned element 50% from the left.

add margin-left: -150px

The 1st step would have worked just fine if the element had width of 1px (.shape will start after 50% from left) but since it has a width of 300px, you will have to add a negative margin-left equal to half the width of the element (300/2 = 150).

Similarly, for vertical alignment you can use top: 50% and a negative margin-top equal to 1/2 of the height.

Note: There was issue on padding-top: ~50px;, remove the ~ as it is invalid token. Also, padding can't be in negative.

.body {
  font-family: 'Roboto', sans-serif;
  color: black;
}

.navbar.navbar-default {
  background-color: #FFFFFF;
  height: 10vh;
  z-index: 100;
}

.navbar.navbar-default ul {
  list-style-type: none;
  text-align: center;
}

.navbar.navbar-default ul li {
  display: inline-block;
}

.dropdown-menu li {
  text-align: center;
}

.dropdown .dropdown-menu {
  background-color: #FFFFFF;
}

.dropdown .dropdown-menu a {
  color: white;
}

.navbar.navbar-default ul li a {
  display: inline-block;
  padding: 3.5vh 8px 4px;
  color: black;
  text-decoration: none;
  font-size: 14pt;
  font-family: 'Roboto', sans-serif;
}

.navbar.navbar-default ul li:after {
  content: '';
  position: absolute;
  right: 50%;
  bottom: 0;
  left: 50%;
  height: 3px;
  background-color: black;
  border-radius: 9px;
  transition: all .2s;
}

.nav.navbar-nav,
.nav.navbar-nav>li {
  float: none;
}

.navbar.navbar-default ul li:hover:after {
  right: 0;
  left: 0;
}

.navbar.navbar-default ul.dropdown-menu li,
.navbar.navbar-default ul.dropdown-menu li a {
  position: relative;
  display: block;
}

.section {
  min-height: 100vh;
}

.one {
  background-color: #c00;
}

.two {
  background: #563D7C;
}

#sections .section {
  padding-top: 50px;
}

.hero {
  background: url("http://mowebusa.nobletechindia.com/wp-content/uploads/2016/05/computer.jpg") center center no-repeat;
  background-attachment: fixed;
  position: relative;
  background-size: cover;
  width: 100%;
  max-width: 100%;
  width: 100vw;
  height: 100%;
}

.shape {
  border-radius: 25px;
  background: #4D5061;
  content: url(http://i1126.photobucket.com/albums/l611/ldocherty1/IMG_0730_zpsiz4dqc47.jpg);
  color: white;
  height: 300px;
  margin: auto;
  padding: 3px;
  width: 300px;

  /* add this */
  position: absolute;
  left: 50%;
  margin-left: -150px;
  z-index: 10;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>!DOCTYPE html>
<html lang="en">

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.js"></script>
</head>

<body>
  <nav class="navbar navbar-default navbar-fixed-top">
    <div class="container-fluid">
      <!-- Brand and toggle get grouped for better mobile display -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               <span class="sr-only">Toggle navigation</span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               </button>
      </div>
      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
          <li>Home
          </li>
          <li class="dropdown">
            About Me <span class="caret"></span>
            <ul class="dropdown-menu">
              <li>Action
              </li>
              <li>Contact
              </li>
              <li>Something else here
              </li>
              <li>Separated link
              </li>
              <li>One more separated link
              </li>
            </ul>
          </li>
          <li class="dropdown">
            Units <span class="caret"></span>
            <ul class="dropdown-menu">
              <li>Action
              </li>
              <li>Another action
              </li>
              <li>Something else here
              </li>
              <li>Separated link
              </li>
              <li>One more separated link
              </li>
            </ul>
          </li>
          <li>Clients
          </li>
          <li>Contact Me
          </li>
        </ul>
      </div>
      <!-- /.navbar-collapse -->
    </div>
    <!-- /.container-fluid -->
  </nav>
  <div id="sections">
    <div class="section one">

      <div class="shape"></div>
      <div class="hero"></div>
       <i class="fa fa-angle-down" style="font-size:100px;"></i>
    </div>
    <div class="section two"></div>
     <i class="fa fa-angle-up" style="font-size:100px;"></i>
  </div>
  <script>
    $(document).ready(function() {
      $('#sections').fullpage();
    });
  </script>
</body>

</html></code>```

Title: How can I place a <div> just above the centre using bootstrap behind a background image?

Body:
I'm trying to place the picture of mine which is
 on top of the background image which is
 just above the center using bootstrap.

However, the background color and image both appear above my picture. I'm looking for the background image to go behind my picture and for the background color not to be seen at this moment in time.

Please don't delete the background color if you decide to help me as I want to do something with it at a later stage.

Please open the snippet in full screen to see my issue.

!DOCTYPE html>

      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               Toggle navigation

               </button>

Home

                     About Me

Action

Contact

Something else here

Separated link

One more separated link

                     Units

Action

Another action

Something else here

Separated link

One more separated link

Clients

Contact Me

Body:
You can do this by following the steps below:

add position: absolute to .shape to overlap the hero image.

add z-index: 10 to get .shape on top of .hero image

Now, to center align a positioned element, keep in mind the following trick:

use left: 50% to put the positioned element 50% from the left.

add margin-left: -150px

The 1st step would have worked just fine if the element had width of 1px (.shape will start after 50% from left) but since it has a width of 300px, you will have to add a negative margin-left equal to half the width of the element (300/2 = 150).

Similarly, for vertical alignment you can use top: 50% and a negative margin-top equal to 1/2 of the height.

Note: There was issue on padding-top: ~50px;, remove the ~ as it is invalid token. Also, padding can't be in negative.

.body {
  font-family: 'Roboto', sans-serif;
  color: black;
}

.navbar.navbar-default {
  background-color: #FFFFFF;
  height: 10vh;
  z-index: 100;
}

.navbar.navbar-default ul {
  list-style-type: none;
  text-align: center;
}

.navbar.navbar-default ul li {
  display: inline-block;
}

.dropdown-menu li {
  text-align: center;
}

.dropdown .dropdown-menu {
  background-color: #FFFFFF;
}

.dropdown .dropdown-menu a {
  color: white;
}

.navbar.navbar-default ul li a {
  display: inline-block;
  padding: 3.5vh 8px 4px;
  color: black;
  text-decoration: none;
  font-size: 14pt;
  font-family: 'Roboto', sans-serif;
}

.navbar.navbar-default ul li:after {
  content: '';
  position: absolute;
  right: 50%;
  bottom: 0;
  left: 50%;
  height: 3px;
  background-color: black;
  border-radius: 9px;
  transition: all .2s;
}

.nav.navbar-nav,
.nav.navbar-nav>li {
  float: none;
}

.navbar.navbar-default ul li:hover:after {
  right: 0;
  left: 0;
}

.navbar.navbar-default ul.dropdown-menu li,
.navbar.navbar-default ul.dropdown-menu li a {
  position: relative;
  display: block;
}

.section {
  min-height: 100vh;
}

.one {
  background-color: #c00;
}

.two {
  background: #563D7C;
}

#sections .section {
  padding-top: 50px;
}

.hero {
  background: url("http://mowebusa.nobletechindia.com/wp-content/uploads/2016/05/computer.jpg") center center no-repeat;
  background-attachment: fixed;
  position: relative;
  background-size: cover;
  width: 100%;
  max-width: 100%;
  width: 100vw;
  height: 100%;
}

.shape {
  border-radius: 25px;
  background: #4D5061;
  content: url(http://i1126.photobucket.com/albums/l611/ldocherty1/IMG_0730_zpsiz4dqc47.jpg);
  color: white;
  height: 300px;
  margin: auto;
  padding: 3px;
  width: 300px;

  /* add this */
  position: absolute;
  left: 50%;
  margin-left: -150px;
  z-index: 10;
}

!DOCTYPE html>
<html lang="en">

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.js"></script>
</head>

<body>
  <nav class="navbar navbar-default navbar-fixed-top">
    <div class="container-fluid">
      <!-- Brand and toggle get grouped for better mobile display -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               <span class="sr-only">Toggle navigation</span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               </button>
      </div>
      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
          <li><a href="#">Home</a>
          </li>
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">About Me <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="#">Action</a>
              </li>
              <li><a href="#section3">Contact</a>
              </li>
              <li><a href="#">Something else here</a>
              </li>
              <li><a href="#">Separated link</a>
              </li>
              <li><a href="#">One more separated link</a>
              </li>
            </ul>
          </li>
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Units <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="#">Action</a>
              </li>
              <li><a href="#">Another action</a>
              </li>
              <li><a href="#">Something else here</a>
              </li>
              <li><a href="#">Separated link</a>
              </li>
              <li><a href="#">One more separated link</a>
              </li>
            </ul>
          </li>
          <li><a href="#">Clients</a>
          </li>
          <li><a href="#contact-me">Contact Me</a>
          </li>
        </ul>
      </div>
      <!-- /.navbar-collapse -->
    </div>
    <!-- /.container-fluid -->
  </nav>
  <div id="sections">
    <div class="section one">

      <div class="shape"></div>
      <div class="hero"></div>
      <a href="#section two"> <i class="fa fa-angle-down" style="font-size:100px;"></i></a>
    </div>
    <div class="section two"></div>
    <a href="#section one"> <i class="fa fa-angle-up" style="font-size:100px;"></i></a>
  </div>
  <script>
    $(document).ready(function() {
      $('#sections').fullpage();
    });
  </script>
</body>

</html>


问:
The requested resource does not support http method 'POST' when sending multipart-form data
I have a controller like below:

```<code>[RoutePrefix("api/File")]
public class FileController : ApiController
{
        [HttpPost]
        [Route("Add")]
        public async Task<HttpResponseMessage> AddFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/temp/uploads");
            var provider = new MultipartFormDataStreamProvider(root);
            var result = await Request.Content.ReadAsMultipartAsync(provider);

            foreach (var key in provider.FormData.AllKeys)
            {
                foreach (var val in provider.FormData.GetValues(key))
                {
                    if (key == "companyName")
                    {
                        var companyName = val;
                    }
                }
            }

            //Do whatever you want to do with your file here

            return this.Request.CreateResponse(HttpStatusCode.OK, "OK");
        }
}
</code>```

If i do a post request in postman like in picture:

WebApiConfig.cs

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.MapHttpAttributeRoutes();

        // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
        // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
        // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
        //config.EnableQuerySupport();

        // To disable tracing in your application, please comment out or remove the following line of code
        // For more information, refer to: http://www.asp.net/web-api
        config.EnableSystemDiagnosticsTracing();
        config.Formatters.Add(new BrowserJsonFormatter());
    }
}
</code>```

The function does not get hit

Any idea what I am doing wrong?

答:
Looks like you are using attribute routing. Check to make sure that attribute routing is enabled.

WebApiConfig.cs

```<code>public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
</code>```

Chances are that you did not have it enabled and the convention-based route was unable to match the route with the HTTP method.

Body:
I have a controller like below:

[RoutePrefix("api/File")]
public class FileController : ApiController
{
        [HttpPost]
        [Route("Add")]
        public async Task<HttpResponseMessage> AddFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/temp/uploads");
            var provider = new MultipartFormDataStreamProvider(root);
            var result = await Request.Content.ReadAsMultipartAsync(provider);

            foreach (var key in provider.FormData.AllKeys)
            {
                foreach (var val in provider.FormData.GetValues(key))
                {
                    if (key == "companyName")
                    {
                        var companyName = val;
                    }
                }
            }

            //Do whatever you want to do with your file here

            return this.Request.CreateResponse(HttpStatusCode.OK, "OK");
        }
}

If i do a post request in postman like in picture:

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.MapHttpAttributeRoutes();

        // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
        // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
        // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
        //config.EnableQuerySupport();

        // To disable tracing in your application, please comment out or remove the following line of code
        // For more information, refer to: http://www.asp.net/web-api
        config.EnableSystemDiagnosticsTracing();
        config.Formatters.Add(new BrowserJsonFormatter());
    }
}

The function does not get hit

Any idea what I am doing wrong?

Body:
Looks like you are using attribute routing. Check to make sure that attribute routing is enabled.

WebApiConfig.cs

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Chances are that you did not have it enabled and the convention-based route was unable to match the route with the HTTP method.


问:
SBT - task to transitively gather subprojects information
I'm trying to implement a simple task (and learn SBT - again - at the same time). After spending about 8 hours trying to figure the solution, hit many dead-end ways, read a lot of SBT docs and SO entries and having built up a massive heap of anger and frustration, I'm posting the question here.

I need to implement a task, transitiveBaseDirectories, that will (in sbt console) allow me to query projects for it's dependening projects tasks in a multi-project build (an example structure is at the end of this post) like this:

projectA/transitiveBaseDirectories

(made up desired output)

Seq(File("./projectA"), File("./projectAA"), File("./projectAAA"), File("./projectAB")))

for this example project

lazy val transitiveBaseDirectories = taskKey[Seq[File]](
    "Returns a list of baseDirectory-ies of all projects a given project transitively depends on."
)

def transitiveBaseDirectoriesImpl = ???

lazy val root = project.dependsOn(projectA, projectB)

lazy val projectA = project.dependsOn(projectAA, projectAB)

lazy val projectAA = project.dependsOn(projectAAA)

lazy val projectAAA = project

lazy val projectAB = project.dependsOn(projectAB)

lazy val projectB = project
```

Then it will be necessary to somehow make transitiveBaseDirectories available for all projects - I also don't know how to do that.

I'm deliberately not showing here all my failed attempts (various takes on Product.extract(state.value), baseDirectory.all(ScopeFilter(inDependencies(...))) etc). On my SBT explorations I've had the "almost-there" feeling on several occasions, followed by waves of confusion and realization that I just don't get the SBT big picture necessary to complete the task, and more frustration. I've given up, again, this is my maybe third occasion to implement a non-trivial task in SBT, and it has never ended well (in the better cases, I've succeeded, but didn't really understand what I did).

I would really appreciate a minimal, but complete solution here, because I've been halfway through too many times, if I'm not asking too much.

Thank you very much.

答:
I'm assuming you want the transitive dependencies for all the projects.

So I'll first make a task to get all the direct project dependencies.

```<code>val directProjectDeps = taskKey[Map[String,Seq[ProjectRef]]]("project dependencies!")

directProjectDeps := {
  val extracted = Project extract state.value
  extracted.structure.allProjects.map { p =>
    val deps = p.dependencies.map(_.project)
    (p.id, deps)
  }.toMap
}
</code>```

Then need to do a bit of graph traversal to get all the transitive dependencies. Here's a simple implementation in a separate task.

```<code>val transitiveProjectDeps = taskKey[Map[String,Seq[ProjectRef]]]("transitive project dependencies!")

transitiveProjectDeps := {
  val deps = directProjectDeps.value

  def transitives(id: String): Seq[ProjectRef] = {
    val direct = deps(id)
    direct ++ direct.flatMap(d => transitives(d.project))
  }

  deps.map{ case(id,_) => (id,transitives(id)) }
}
</code>```

To avoid dealing with dynamic references to tasks, use extracted to access the baseDirectory setting of all the ProjectRefs

```<code>val transitiveProjectDirs = taskKey[Map[String,Seq[File]]]("transitive project dependencies!")
transitiveProjectDirs := {
  val extracted = Project extract state.value
  transitiveProjectDeps.value.mapValues { v =>
    v.map(ref => extracted.get(baseDirectory in ref))
  }
}
</code>```

To get the dirs only for the current project.

```<code>val myTransitiveProjectDirs = taskKey[Seq[File]]("just my dirs")
myTransitiveProjectDirs :=
  transitiveProjectDirs.value.apply(thisProjectRef.value.project)
</code>```

To make all of the tasks available within any subproject, it's probably easiest to put them into a plugin.

Body:
I'm trying to implement a simple task (and learn SBT - again - at the same time). After spending about 8 hours trying to figure the solution, hit many dead-end ways, read a lot of SBT docs and SO entries and having built up a massive heap of anger and frustration, I'm posting the question here.

I need to implement a task, transitiveBaseDirectories, that will (in sbt console) allow me to query projects for it's dependening projects tasks in a multi-project build (an example structure is at the end of this post) like this:

projectA/transitiveBaseDirectories

(made up desired output)

Seq(File("./projectA"), File("./projectAA"), File("./projectAAA"), File("./projectAB")))

for this example project

lazy val transitiveBaseDirectories = taskKey[Seq[File]](
    "Returns a list of baseDirectory-ies of all projects a given project transitively depends on."
)

def transitiveBaseDirectoriesImpl = ???

lazy val root = project.dependsOn(projectA, projectB)

lazy val projectA = project.dependsOn(projectAA, projectAB)

lazy val projectAA = project.dependsOn(projectAAA)

lazy val projectAAA = project

lazy val projectAB = project.dependsOn(projectAB)

lazy val projectB = project

Then it will be necessary to somehow make transitiveBaseDirectories available for all projects - I also don't know how to do that.

I'm deliberately not showing here all my failed attempts (various takes on Product.extract(state.value), baseDirectory.all(ScopeFilter(inDependencies(...))) etc). On my SBT explorations I've had the "almost-there" feeling on several occasions, followed by waves of confusion and realization that I just don't get the SBT big picture necessary to complete the task, and more frustration. I've given up, again, this is my maybe third occasion to implement a non-trivial task in SBT, and it has never ended well (in the better cases, I've succeeded, but didn't really understand what I did).

I would really appreciate a minimal, but complete solution here, because I've been halfway through too many times, if I'm not asking too much.

Thank you very much.

Body:
I'm assuming you want the transitive dependencies for all the projects.

So I'll first make a task to get all the direct project dependencies.

val directProjectDeps = taskKey[Map[String,Seq[ProjectRef]]]("project dependencies!")

directProjectDeps := {
  val extracted = Project extract state.value
  extracted.structure.allProjects.map { p =>
    val deps = p.dependencies.map(_.project)
    (p.id, deps)
  }.toMap
}

Then need to do a bit of graph traversal to get all the transitive dependencies. Here's a simple implementation in a separate task.

val transitiveProjectDeps = taskKey[Map[String,Seq[ProjectRef]]]("transitive project dependencies!")

transitiveProjectDeps := {
  val deps = directProjectDeps.value

  def transitives(id: String): Seq[ProjectRef] = {
    val direct = deps(id)
    direct ++ direct.flatMap(d => transitives(d.project))
  }

  deps.map{ case(id,_) => (id,transitives(id)) }
}

To avoid dealing with dynamic references to tasks, use extracted to access the baseDirectory setting of all the ProjectRefs

val transitiveProjectDirs = taskKey[Map[String,Seq[File]]]("transitive project dependencies!")
transitiveProjectDirs := {
  val extracted = Project extract state.value
  transitiveProjectDeps.value.mapValues { v =>
    v.map(ref => extracted.get(baseDirectory in ref))
  }
}

To get the dirs only for the current project.

val myTransitiveProjectDirs = taskKey[Seq[File]]("just my dirs")
myTransitiveProjectDirs :=
  transitiveProjectDirs.value.apply(thisProjectRef.value.project)

To make all of the tasks available within any subproject, it's probably easiest to put them into a plugin.


问:
Use of ggplot() within another function in R
I'm trying to write a simple plot function, using the ggplot2 library. But the call to ggplot doesn't find the function argument.

Consider a data.frame called means that stores two conditions and two mean values that I want to plot (condition will appear on the X axis, means on the Y).

```<code>library(ggplot2)
m <- c(13.8, 14.8)
cond <- c(1, 2)
means <- data.frame(means=m, condition=cond)
means
# The output should be:
#     means    condition
#   1 13.8     1
#   2 14.8     2

testplot <- function(meansdf)
{
  p <- ggplot(meansdf, aes(fill=meansdf$condition, y=meansdf$means, x = meansdf$condition))
  p + geom_bar(position="dodge", stat="identity")
}

testplot(means)
# This will output the following error:
# Error in eval(expr, envir, enclos) : object 'meansdf' not found
</code>```

So it seems that ggplot is calling eval, which can't find the argument meansdf. Does anyone know how I can successfully pass the function argument to ggplot?

(Note: Yes I could just call the ggplot function directly, but in the end I hope to make my plot function do more complicated stuff! :) )

答:
You don't need anything fancy. Not even dummy variables. You only need to add a print() inside your function, is like using cat() when you want something to show in the console.

myplot <- ggplot(......) + Whatever you want here
print(myplot)

It worked for me more than one time inside the same function

Body:
I'm trying to write a simple plot function, using the ggplot2 library. But the call to ggplot doesn't find the function argument.

Consider a data.frame called means that stores two conditions and two mean values that I want to plot (condition will appear on the X axis, means on the Y).

library(ggplot2)
m <- c(13.8, 14.8)
cond <- c(1, 2)
means <- data.frame(means=m, condition=cond)
means
# The output should be:
#     means    condition
#   1 13.8     1
#   2 14.8     2

testplot <- function(meansdf)
{
  p <- ggplot(meansdf, aes(fill=meansdf$condition, y=meansdf$means, x = meansdf$condition))
  p + geom_bar(position="dodge", stat="identity")
}

testplot(means)
# This will output the following error:
# Error in eval(expr, envir, enclos) : object 'meansdf' not found

So it seems that ggplot is calling eval, which can't find the argument meansdf. Does anyone know how I can successfully pass the function argument to ggplot?

(Note: Yes I could just call the ggplot function directly, but in the end I hope to make my plot function do more complicated stuff! :) )


问:
mysql - group by column but show all the rows
I need help with this query, this is my output:

```<code>idProduccion | hp   | totalHp |
      4      | 40   | 40      |
      4      | 35   | 35      |
      5      | 90   | 90      |
      6      | 2500 | 2500    |
</code>```

how do I do to sum hp columns with the same idProduccion and show all the rows, for exampe:

```<code>idProduccion | hp   | totalHp |
      4      | 40   | 75      |
      4      | 35   | 75      |
      5      | 90   | 90      |
      6      | 2500 | 2500    |
....
</code>```

here is my sql query

```<code>SELECT
    lp.idProduccion,lp.hp, totalHp
FROM
    lotesproduccion lp
        JOIN
    (SELECT
        lp.hp, lp.idlotesproduccion, sum(lp.hp) AS totalHp
    FROM
        lotesproduccion lp
    GROUP BY lp.idlotesproduccion) AS lp1 ON lp.idlotesproduccion = lp1.idlotesproduccion
</code>```

答:
I have changed ur query with group by idproduction

SELECT
    lp.idProduccion,lp.hp, lp1.totalHp
FROM
    lotesproduccion lp
       Left JOIN
    (SELECT
     lp.idProduccion , sum(lp.hp) AS totalHp
    FROM
        lotesproduccion lp
    GROUP BY lp.idProduccion) AS lp1 ON lp.idProduccion = lp1.idProduccion

Body:
I need help with this query, this is my output:

idProduccion | hp   | totalHp |
      4      | 40   | 40      |
      4      | 35   | 35      |
      5      | 90   | 90      |
      6      | 2500 | 2500    |

how do I do to sum hp columns with the same idProduccion and show all the rows, for exampe:

idProduccion | hp   | totalHp |
      4      | 40   | 75      |
      4      | 35   | 75      |
      5      | 90   | 90      |
      6      | 2500 | 2500    |
....

here is my sql query

SELECT
    lp.idProduccion,lp.hp, totalHp
FROM
    lotesproduccion lp
        JOIN
    (SELECT
        lp.hp, lp.idlotesproduccion, sum(lp.hp) AS totalHp
    FROM
        lotesproduccion lp
    GROUP BY lp.idlotesproduccion) AS lp1 ON lp.idlotesproduccion = lp1.idlotesproduccion


问:
Class JavaLaunchHelper is implemented in two places
Today I upgraded my Intellij Idea on macOS Sierra, and now, when I run apps in console I have this error:

objc[3648]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/bin/java (0x10d19c4c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x10ea194e0). One of the two will be used. Which one is undefined.

答: This happened to me when I installed Intellij IDEA 2017, go to menu  Preferences -> Build, Execution, Deployment -> Debugger and disable the option: "Force Classic VM for JDK 1.3.x and earlier".  This works to me.  </p>


问:
XPath Expression: Optional character?
I would like to find:

```<code><div style="text-align:center;" >
<div style="text-align: center;" >
<div style="text-align:center" >
<div style="text-align: center" >
</code>```

So an optional space before center and an optional semicolon at the end.

I can do:

```<code>//div[@style=’text-align:center;’ or @style=’text-align: center;’ or @style=’text-align:center’ or @style=’text-align: center’]
</code>```

But is there a “cleaner” way? And able to take many more optional characters without getting too long?

答:
You can first remove the optional characters f.e space and semicolon, assuming they aren't used in the required text, using translate() function, and then check whether the result equals only the required text f.e 'text-align:center' :

```<code>//div[translate(@style, ' ;', '') = 'text-align:center']
</code>```

Or, when the pattern gets more complex, you can use regex in your XPath via PHP preg_match  :

```<code>$xp->query("//div[php:function('preg_match', '~text-align:\s*center;*~', string(@style))]");
</code>```

See full example demonstrating how to call PHP function from XPath in my older post : Get hrefs that match regex expression using PHP & XPath.

Title: XPath Expression: Optional character?

Body:
I would like to find:

So an optional space before center and an optional semicolon at the end.

I can do:

//div[@style=’text-align:center;’ or @style=’text-align: center;’ or @style=’text-align:center’ or @style=’text-align: center’]

But is there a “cleaner” way? And able to take many more optional characters without getting too long?

Body:
You can first remove the optional characters f.e space and semicolon, assuming they aren't used in the required text, using translate() function, and then check whether the result equals only the required text f.e 'text-align:center' :

//div[translate(@style, ' ;', '') = 'text-align:center']

Or, when the pattern gets more complex, you can use regex in your XPath via PHP preg_match  :

$xp->query("//div[php:function('preg_match', '~text-align:\s*center;*~', string(@style))]");

See full example demonstrating how to call PHP function from XPath in my older post : Get hrefs that match regex expression using PHP & XPath.


问:
Create a time series with a row every 15 minutes
I'm having trouble creating a time series (POSIXct or dttm column) with a row every 15 minutes.

Something that will look like this for every 15 minutes between Jan 1st 2015 and Dec 31st 2016 (here as month/day/year hour:minutes):

```<code>1/15/2015 0:00
1/15/2015 0:15
1/15/2015 0:30
1/15/2015 0:45
1/15/2015 1:00
</code>```

A loop starting date of 01/01/2015 0:00 and then adding 15 minutes until 12/31/2016 23:45?

Does anyone has an idea of how this can be done easily?

答:
Little bit easier to read</p>

```<code>library(lubridate)
seq(ymd_hm('2015-01-01 00:00'),ymd_hm('2016-12-31 23:45'), by = '15 mins')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having trouble creating a time series (POSIXct or dttm column) with a row every 15 minutes.

Something that will look like this for every 15 minutes between Jan 1st 2015 and Dec 31st 2016 (here as month/day/year hour:minutes):

1/15/2015 0:00
1/15/2015 0:15
1/15/2015 0:30
1/15/2015 0:45
1/15/2015 1:00

A loop starting date of 01/01/2015 0:00 and then adding 15 minutes until 12/31/2016 23:45?

Does anyone has an idea of how this can be done easily?

Body:
Little bit easier to read

library(lubridate)
seq(ymd_hm('2015-01-01 00:00'),ymd_hm('2016-12-31 23:45'), by = '15 mins')


问:
How to make the left margin "appear" outside the container div?
Notice how when using Bootstrap, the row div inside the container div have the left margin "appear" outside the container div (the left margin is the yellow part):

I tried to replicate this behavior using the following code:

```<code><!DOCTYPE html>

<html>
    <head>
        <style>
            #div1
            {
                width: 500px;
                height: 400px;
                border: 1px solid black;
                margin-left: auto;
                margin-right: auto;
            }

            #div2
            {
                width: 500px;
                height: 200px;
                background-color: red;
                margin-right: 100px;
                margin-left: 100px;
            }
        </style>
    </head>

    <body>
        <div id="div1">
            <div id="div2">
            </div>
        </div>
    </body>
</html>
</code>```

But it did not work (the left margin stayed inside the container div):

答:
you need the same value for padding-left padding-right on div1 based on negative  margin-left , margin-right value of div2.
check the snippet I have remove added media query and box-sizing for better view. and remove the width for div2 and set inital width

*{
  box-sizing:border-box;
  }
body{
 margin:0;
}
 #div1
        {
            width: 500px;
            height: 400px;
            border: 1px solid black;
            margin-left: auto;
            margin-right: auto;
            padding-right: 100px;
            padding-left:100px;
        }

        #div2
        {

            height: 200px;
            background-color: red;
            margin-right: -100px;
            margin-left: -100px;
        }
@media only screen and (max-width: 768px){

#div1 {
    width: 81.584%;
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div id="div1">
   <div id="div2"></div>
    </div></code>```

Body:
Notice how when using Bootstrap, the row div inside the container div have the left margin "appear" outside the container div (the left margin is the yellow part):

I tried to replicate this behavior using the following code:

<!DOCTYPE html>

But it did not work (the left margin stayed inside the container div):

Body:
you need the same value for padding-left padding-right on div1 based on negative  margin-left , margin-right value of div2.
check the snippet I have remove added media query and box-sizing for better view. and remove the width for div2 and set inital width

*{
  box-sizing:border-box;
  }
body{
 margin:0;
}
 #div1
        {
            width: 500px;
            height: 400px;
            border: 1px solid black;
            margin-left: auto;
            margin-right: auto;
            padding-right: 100px;
            padding-left:100px;
        }

        #div2
        {

            height: 200px;
            background-color: red;
            margin-right: -100px;
            margin-left: -100px;
        }
@media only screen and (max-width: 768px){

#div1 {
    width: 81.584%;
}
}

 <div id="div1">
   <div id="div2"></div>
    </div>


问:
Showing Form Entry on Modal Window Bootstrap / jQuery
I'm creating a form confirmation window with Bootstrap Modal before user submission.

Here is the html part:

```<code><form role="form">
    <div class="form-group">
      <label for="Company" class="col-sm-3 control-label">Company:</label>
      <div class="col-sm-9">
        <input type="text" name="Company" id="Company" size="50" maxlength="100" class="form-control" placeholder="Companyt">
      </div>
    </div>

    <div class="form-group">
      <label for="Department" class="col-sm-3 control-label">Department:</label>
      <div class="col-sm-9">
        <input type="text" name="Department" id="Department" size="50" maxlength="100" class="form-control" placeholder="Department">
      </div>
    </div>

    <div class="form-group">
      <label for="Username" class="col-sm-3 control-label">Name:</label>
      <div class="col-sm-9">
        <input type="text" name="Username" id="Username" size="50" maxlength="100" class="form-control" placeholder="Username">
      </div>
    </div>

    <div class="form-group">
      <label for="Address" class="col-sm-3 control-label">Address:</label>
      <div class="col-sm-9">
        <input type="text" name="Address" id="Address" size="50" maxlength="100" class="form-control" placeholder="Address">
      </div>
    </div>

    <div class="form-group">
      <label for="TEL" class="col-sm-3 control-label">TEL:</label>
      <div class="col-sm-9">
        <input type="text" name="TEL" id="TEL" size="50" maxlength="100" class="form-control" placeholder="TEL">
      </div>
    </div>

    <div class="form-group">
      <label for="Email" class="col-sm-3 control-label">Email:</label>
      <div class="col-sm-9">
        <input type="text" name="Email" id="Email" size="50" maxlength="100" class="form-control" placeholder="Email">
      </div>
    </div>
    <input type="button" class="btn btn-primary btn-block enduserinfobtn" id="submitBtn" data-toggle="modal" data-target="#myModal" value="Submit">
  </form>
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
          <h4 class="modal-title" id="myModalLabel">Confirm your entry</h4>
        </div>
        <div class="modal-body">
          <div class="row">
          <div class="entryname col-xs-3 ">Company:</div>
          <div class="entrydata col-xs-9" id="mCompany"></div>
          </div>
          <div class="row">
          <div class="entryname col-xs-3">Department:</div>
          <div class="entrydata col-xs-9" id="mDepartment"></div>
          </div>
          <div class="row">
          <div class="entryname col-xs-3">Name:</div>
          <div class="entrydata col-xs-9" id="mUsername"></div>
          </div>
          <div class="row">
          <div class="entryname col-xs-3">Address:</div>
          <div class="entrydata col-xs-9" id="mAddress"></div>
          </div>
          <div class="row">
          <div class="entryname col-xs-3">TEL:</div>
          <div class="entrydata col-xs-9" id="mTel"></div>
          </div>
          <div class="row">
          <div class="entryname col-xs-3">Email:</div>
          <div class="entrydata col-xs-9" id="mEmail"></div>
          </div>
          <div class="clearfix"></div>
        </div>
        <div class="modal-footer">
          <div class="col-xs-6"><button class="btn btn-block btn-default" data-dismiss="modal">Cancel</button></div>
          <div class="col-xs-6"><button class="btn btn-block btn-primary">Submit</button></div>
        </div>
      </div>
    </div>
  </div>
</code>```

And here is the jQuery part:

```<code>$('#submitBtn').click(function() {
  $('#mCompany').text($('#Company').val());
  $('#mDepartment').text($('#Department').val());
  $('#mUsername').text($('#Username').val());
  $('#mAddress').text($('#Address').val());
  $('#mTEL').text($('#TEL').val());
  $('#mEmail').text($('#Email').val());
});
</code>```

You can see and try with this
link to JSFiddle.

Not all fields are required, and what I want to do is to show only the entry with data.

For example in the below image, I don't want the red bordered part to show up.

Example Screen Shot

The sample on JSFiddle has only 6 fields but my form has over 30 fields. I'm wondering if there's a way to show only the fields with data.

答:
Remove below part from HTML

```<code><div class="row">
<div class="entryname col-xs-3">Address:</div>
<div class="entrydata col-xs-9" id="mAddress"></div>
</div>
<div class="row">
<div class="entryname col-xs-3">TEL:</div>
<div class="entrydata col-xs-9" id="mTel"></div>
</div>
</code>```

remove below part from jquery

```<code>$('#mAddress').text($('#Address').val());
$('#mTEL').text($('#TEL').val());
</code>```

Body:
I'm creating a form confirmation window with Bootstrap Modal before user submission.

Here is the html part:

<form role="form">

      Company:

        <input type="text" name="Company" id="Company" size="50" maxlength="100" class="form-control" placeholder="Companyt">

      Department:

        <input type="text" name="Department" id="Department" size="50" maxlength="100" class="form-control" placeholder="Department">

      Name:

        <input type="text" name="Username" id="Username" size="50" maxlength="100" class="form-control" placeholder="Username">

      Address:

        <input type="text" name="Address" id="Address" size="50" maxlength="100" class="form-control" placeholder="Address">

      TEL:

        <input type="text" name="TEL" id="TEL" size="50" maxlength="100" class="form-control" placeholder="TEL">

      Email:

        <input type="text" name="Email" id="Email" size="50" maxlength="100" class="form-control" placeholder="Email">

    <input type="button" class="btn btn-primary btn-block enduserinfobtn" id="submitBtn" data-toggle="modal" data-target="#myModal" value="Submit">
  </form>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Confirm your entry

Company:

Department:

Name:

Address:

TEL:

Email:

<button class="btn btn-block btn-default" data-dismiss="modal">Cancel</button>

<button class="btn btn-block btn-primary">Submit</button>

And here is the jQuery part:

$('#submitBtn').click(function() {
  $('#mCompany').text($('#Company').val());
  $('#mDepartment').text($('#Department').val());
  $('#mUsername').text($('#Username').val());
  $('#mAddress').text($('#Address').val());
  $('#mTEL').text($('#TEL').val());
  $('#mEmail').text($('#Email').val());
});

You can see and try with this
link to JSFiddle.

Not all fields are required, and what I want to do is to show only the entry with data.

For example in the below image, I don't want the red bordered part to show up.

Example Screen Shot

The sample on JSFiddle has only 6 fields but my form has over 30 fields. I'm wondering if there's a way to show only the fields with data.

Body:
Remove below part from HTML

<div class="row">
<div class="entryname col-xs-3">Address:</div>
<div class="entrydata col-xs-9" id="mAddress"></div>
</div>
<div class="row">
<div class="entryname col-xs-3">TEL:</div>
<div class="entrydata col-xs-9" id="mTel"></div>
</div>

remove below part from jquery

$('#mAddress').text($('#Address').val());
$('#mTEL').text($('#TEL').val());


问:
getting NaN when trying to cast string to int
I'm getting some very weird results here. I'm trying to convert a string into a integer. Consider the following code below.

```<code>           //Send back to client.
            io.emit('returned message', {
                'message': message,
                'chatid': chatid,
                'userid': userid
            });
            console.log("Returning the data to chat " + chatid);
</code>```

Which is sending data back to client, the console log looks like this:

Returning the data to the chat '5'

and in the client I have

```<code>alert(typeof msg.chatid);
alert(msg.chatid)
var test = Number(msg.chatid);
alert(typeof test)
alert(test);
</code>```

Which produces the following results

String and '5'
  Number and NaN

Please note I've tried Number() and parseInt()

However, trying to code in Jsfiddle, it works fine. I have no idea why I'm getting NaN. Any ideas?

var num = '5';

alert(Number(num));```

答:
You have single quotationmarks around your "int" value.

Returning the data to the chat '5'

Looks like it's escaped before your socket transmission?

Body:
I'm getting some very weird results here. I'm trying to convert a string into a integer. Consider the following code below.

           //Send back to client.
            io.emit('returned message', {
                'message': message,
                'chatid': chatid,
                'userid': userid
            });
            console.log("Returning the data to chat " + chatid);

Which is sending data back to client, the console log looks like this:

Returning the data to the chat '5'

and in the client I have

alert(typeof msg.chatid);
alert(msg.chatid)
var test = Number(msg.chatid);
alert(typeof test)
alert(test);

Which produces the following results

String and '5'
  Number and NaN

Please note I've tried Number() and parseInt()

However, trying to code in Jsfiddle, it works fine. I have no idea why I'm getting NaN. Any ideas?

var num = '5';

alert(Number(num));


问:
Display <> in a pre html tag
How do you display things like  or anything in <> brackets in a html pre tags.

I tried

```<code>```<stdin>```
</code>```

but I get a blank?

答: You have to use < and >  for < and > even in ```

Title: Display <> in a pre html tag

Body:
How do you display things like  or anything in <> brackets in a html pre tags.

I tried

<stdin>

but I get a blank?

Body: You have to use &lt; and &gt;  for < and > even in <pre>


Title: Display <> in a pre html tag

Body: <pre>&lt;stdin&gt;</pre>


问:
How do I resolve the following "NoClassDefFoundError" in my Apache Tika code?
I have a simple class that Utilizes Apache Tika 1.14, and it is shown here:

```<code>import java.io.File;
import java.io.IOException;

import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.apache.tika.mime.*;
import org.xml.sax.SAXException;
import org.apache.tika.config.*;

public class TikaExtraction {

   public static void main(final String[] args) throws IOException, TikaException {

      //Assume sample.txt is in your current directory
      File file = new File("sample.txt");

      //Instantiating Tika facade class
      Tika tika = new Tika();
      String filecontent = tika.parseToString(file);
      System.out.println("Extracted Content: " + filecontent);
   }

}
</code>```

However, when  I try to run it, I am getting the following error message:

Exception in thread "main" java.lang.NoClassDefFoundError:
  org/apache/tika/mime/MimeTypesReader
          at org.apache.tika.mime.MimeTypesFactory.create(MimeTypesFactory.java:158)
          at org.apache.tika.mime.MimeTypes.getDefaultMimeTypes(MimeTypes.java:577)
          at org.apache.tika.config.TikaConfig.getDefaultMimeTypes(TikaConfig.java:73)
          at org.apache.tika.config.TikaConfig.(TikaConfig.java:222)
          at org.apache.tika.config.TikaConfig.getDefaultConfig(TikaConfig.java:345)
          at org.apache.tika.Tika.(Tika.java:116)
          at TikaExtraction.main(TikaExtraction.java:17) Caused by: java.lang.ClassNotFoundException: org.apache.tika.mime.MimeTypesReader
          at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
          at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
          ... 7 more

When I search through the Tika library code, I am not seeing the .class file for the MimeTypesReader class.  Is there a way to comment out some code or fix this  - how would I resolve this error message?

Or could this be an issue with the version of Tika that I'm using (i.e the referenced code was from 1.6, and maybe I have 1.13 or 1.14).

答:
With such type of library errors, it is not removing something, but adding something that is missing, hence the ClassNotFoundError. Most of the time, you are either missing some supporting jar or there are compatibility issues due to library updates. In fact, you said it yourself

When I search through the Tika library code, I am not seeing the .class file for the MimeTypesReader class.

This is the library method that throws the exception:

```<code>/**
 * Creates and returns a MimeTypes instance from the specified document.
 * @throws MimeTypeException if the type configuration is invalid
 */
public static MimeTypes create(Document document) throws MimeTypeException {
    MimeTypes mimeTypes = new MimeTypes();

    //For some reason the MimeTypesReader is missing
    new MimeTypesReader(mimeTypes).read(document);
    mimeTypes.init();
    return mimeTypes;
}
</code>```

Make sure that you have supplied the full library and also the latest for that matter - tika-1.14. You could get it from one of these Apache mirrors.

The source is part of the tika-core.jar, so make sure you have that on too.

Body:
I have a simple class that Utilizes Apache Tika 1.14, and it is shown here:

import java.io.File;
import java.io.IOException;

import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.apache.tika.mime.*;
import org.xml.sax.SAXException;
import org.apache.tika.config.*;

public class TikaExtraction {

   public static void main(final String[] args) throws IOException, TikaException {

      //Assume sample.txt is in your current directory
      File file = new File("sample.txt");

      //Instantiating Tika facade class
      Tika tika = new Tika();
      String filecontent = tika.parseToString(file);
      System.out.println("Extracted Content: " + filecontent);
   }

}

However, when  I try to run it, I am getting the following error message:

Exception in thread "main" java.lang.NoClassDefFoundError:
  org/apache/tika/mime/MimeTypesReader
          at org.apache.tika.mime.MimeTypesFactory.create(MimeTypesFactory.java:158)
          at org.apache.tika.mime.MimeTypes.getDefaultMimeTypes(MimeTypes.java:577)
          at org.apache.tika.config.TikaConfig.getDefaultMimeTypes(TikaConfig.java:73)
          at org.apache.tika.config.TikaConfig.(TikaConfig.java:222)
          at org.apache.tika.config.TikaConfig.getDefaultConfig(TikaConfig.java:345)
          at org.apache.tika.Tika.(Tika.java:116)
          at TikaExtraction.main(TikaExtraction.java:17) Caused by: java.lang.ClassNotFoundException: org.apache.tika.mime.MimeTypesReader
          at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
          at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
          ... 7 more

When I search through the Tika library code, I am not seeing the .class file for the MimeTypesReader class.  Is there a way to comment out some code or fix this  - how would I resolve this error message?

Or could this be an issue with the version of Tika that I'm using (i.e the referenced code was from 1.6, and maybe I have 1.13 or 1.14).

Body:
With such type of library errors, it is not removing something, but adding something that is missing, hence the ClassNotFoundError. Most of the time, you are either missing some supporting jar or there are compatibility issues due to library updates. In fact, you said it yourself

When I search through the Tika library code, I am not seeing the .class file for the MimeTypesReader class.

This is the library method that throws the exception:

/**
 * Creates and returns a MimeTypes instance from the specified document.
 * @throws MimeTypeException if the type configuration is invalid
 */
public static MimeTypes create(Document document) throws MimeTypeException {
    MimeTypes mimeTypes = new MimeTypes();

    //For some reason the MimeTypesReader is missing
    new MimeTypesReader(mimeTypes).read(document);
    mimeTypes.init();
    return mimeTypes;
}

Make sure that you have supplied the full library and also the latest for that matter - tika-1.14. You could get it from one of these Apache mirrors.

The source is part of the tika-core.jar, so make sure you have that on too.


问:
How to bind an amChart (Stock Chart) to a DataTable?
I've managed to bind an amChart Line Chart to a DataTable by assigning the member DataItemsSource of the LineChartGraph to mytable.DefaultView.

I'm trying to do the same with an amChart Stock Chart. However the Graph object does not have a DataItemsSource. It has instead a DataSetID member that points to a DataSet defined as part of the StockChart control. Anyways... Any suggestion?

Thanks!

答:
After some trial and error, it turned out that you can bind ItemsSource to a DataTable. Judging by the number of responses I've gotten... it looks like not that many people use this control. It's surprising b/c it's absolutely great.. and free.</p>

```<code><ams:StockChart ... >
   ...
   <ams:StockChart.DataSets>
      <ams:DataSet ItemsSource="{Binding Table}" ... />
      ...
   </ams:StockChart.DataSets>
   ...
</ams:StockChart>
</code>```

Body:
After some trial and error, it turned out that you can bind ItemsSource to a DataTable. Judging by the number of responses I've gotten... it looks like not that many people use this control. It's surprising b/c it's absolutely great.. and free.

<ams:StockChart ... >
   ...
   <ams:StockChart.DataSets>
      <ams:DataSet ItemsSource="{Binding Table}" ... />
      ...
   </ams:StockChart.DataSets>
   ...
</ams:StockChart>


问:
How to add multiple spaces in VS Code `window.title`?
I want to have more spacing between the two terms in the window title. But adding multiple spaces in settings.json window.title property does not work. It seems to treat multiple spaces as one.

```<code>"window.title": "${activeEditorShort}     ${rootName}",
</code>```

I've also tried various workarounds without success:

copy/pasting the Unicode non-breaking space U+00A0

I'm on a mac, not sure if it's the mac OS that is the problem, or VS Code.

答:
I was able to get this to work by using Unicode em space or en space characters. Those do not get "squashed" into a single space.

An example with 4 em space's:

```<code>"window.title": "${activeEditorShort}    ${rootName}",
</code>```

You can copy the unicode character inside the square brackets:

[ ] U+2003 em space (wider)

[ ] U+2002 en space (narrower)

Body:
I want to have more spacing between the two terms in the window title. But adding multiple spaces in settings.json window.title property does not work. It seems to treat multiple spaces as one.

"window.title": "${activeEditorShort}     ${rootName}",

I've also tried various workarounds without success:

copy/pasting the Unicode non-breaking space U+00A0

I'm on a mac, not sure if it's the mac OS that is the problem, or VS Code.

Body:
I was able to get this to work by using Unicode em space or en space characters. Those do not get "squashed" into a single space.

An example with 4 em space's:

"window.title": "${activeEditorShort}    ${rootName}",

You can copy the unicode character inside the square brackets:

[ ] U+2003 em space (wider)

[ ] U+2002 en space (narrower)