问:
Is it possible, in a Haskell source code, to import a module that has already been compiled in an object file (.o)?
Suppose that i have compiled a module called ModuleA. The GHC compiler generated the .o and .hi files.

Now i want to import ModuleA  in another source file without re-compiling it or installing a new package, i.e. i want the GHC to detect that ModuleA was already compiled and is stored in an .o file.

Is it possible? how?

Until now, i tried to set some GHC flags in order to look at the directory that the .o and .hi files are stored, but the compilation fails because GHC can not find the interface of ModuleA.

答:
GHC should do this for modules in the current directory automatically:

```<code>$ echo "module ModuleA where { a :: Int ; a = 1 }" > ModuleA.hs
$ ghc -c ModuleA.hs
$ echo "module Main where { import ModuleA ; main :: IO () ; main = print a }" > ModuleB.hs
$ ghc ModuleB.hs -o ModuleB
[2 of 2] Compiling Main             ( ModuleB.hs, ModuleB.o )
Linking ModuleB ...
$ ./ModuleB
1
</code>```

(Note the lack of "Compiling ModuleA" line above)

It should only recompile imported modules in the local directory if the source file has changed since
it was last compiled:

```<code>$ echo "module ModuleA where { a :: Int ; a = 2 }" >! ModuleA.hs
$ ghc ModuleB.hs -o ModuleB
[1 of 2] Compiling ModuleA          ( ModuleA.hs, ModuleA.o )
Linking ModuleB ...
$ ./ModuleB
2
</code>```

(Note the "Compiling ModuleA" line above, and the lack of "Compiling Main" line)

The same goes for other locations on the import path:

```<code>$ rm ModuleA.*
$ mkdir foo
$ echo "module ModuleA where { a :: Int ; a = 3 }" > foo/ModuleA.hs
$ ghc -c foo/ModuleA.hs
$ ghc ModuleB.hs -o ModuleB -ifoo
Linking ModuleB ...
$ ./ModuleB
3
</code>```

Body:
GHC should do this for modules in the current directory automatically:

$ echo "module ModuleA where { a :: Int ; a = 1 }" > ModuleA.hs
$ ghc -c ModuleA.hs
$ echo "module Main where { import ModuleA ; main :: IO () ; main = print a }" > ModuleB.hs
$ ghc ModuleB.hs -o ModuleB
[2 of 2] Compiling Main             ( ModuleB.hs, ModuleB.o )
Linking ModuleB ...
$ ./ModuleB
1

(Note the lack of "Compiling ModuleA" line above)

It should only recompile imported modules in the local directory if the source file has changed since
it was last compiled:

$ echo "module ModuleA where { a :: Int ; a = 2 }" >! ModuleA.hs
$ ghc ModuleB.hs -o ModuleB
[1 of 2] Compiling ModuleA          ( ModuleA.hs, ModuleA.o )
Linking ModuleB ...
$ ./ModuleB
2

(Note the "Compiling ModuleA" line above, and the lack of "Compiling Main" line)

The same goes for other locations on the import path:

$ rm ModuleA.*
$ mkdir foo
$ echo "module ModuleA where { a :: Int ; a = 3 }" > foo/ModuleA.hs
$ ghc -c foo/ModuleA.hs
$ ghc ModuleB.hs -o ModuleB -ifoo
Linking ModuleB ...
$ ./ModuleB
3


来源: stackexchange

问:
Why systemd process running in docker container with PID 1 not forwarding SIGTERM to child processes on docker stop
We have Docker container which is running systemd as main process (PID 1). We have also started our worker processes in Docker container through systemd unit. Our Docker containers uses CentOS 7.2.
We have configured the Docker stop timeout so that we can handle the graceful shutdown of worker processes running inside Docker container.
When we are stopping Docker container, we can see SIGTERM is received to systemd process which is running with PID 1 inside container. Also container waits for stop timeout which we have configured.
But systemd process is not forwarding this SIGTERM to our worker processes which we have started using systemd unit.
From logs it looks like when systemd receives SIGTERM it tries to re-executes itself. We have tried with adding KillMode=mixed in our systemd unit file but it didn’t worked for us.

Is there any way to forward SIGTERM from systemd process to the child processes ?

答: Instead of running systemd itself you could also try with a replacement that provides a similar functionality. If you put the docker-systemctl-replacement as the entrypoint of the container then it will look for the systemd unit files you have provided - upon container start it runs ExecStart from unit descriptors and upon receiving SIGSTOP it will run ExecStop from each of the unit descriptors. It sounds like that's the functionality you want anyway.</p>

ContentLicense: CC BY-SA 3.0


问:
Pass function inside string literal to other component
I want to pass a function defined in my actions to an element.

Reducer

```<code>case 'UPDATE_HEADER':
    return Object.assign({}, state, {
        headerChildren: state.headerChildren.concat([action.child])
    });
</code>```

Action.js

```<code>export const deleteHeader = () => {
    return {
        type: 'DELETE_HEADER',
    };
}
</code>```

I am passing this action to my sidebar

```<code>onAddHeader () {
    this.props.addHeader();
    this.props.updateHeader(
        `<Header key='${this.props.childKey}'
             deleteHeader='${this.props.deleteHeader}'/>`,
    );
}
</code>```

The deleteHeader function is being passed to the Header component but the problem is that it is being passed as a string and not as a function.

I am rendering it as this

```<code>`{this.props.headerChildren.map((value, index) => (
    <JsxParser
        key={index}
        components={[Header]}
        jsx={value}
    />
))}`
</code>```

Can someone please guide me through the solution. I have searched a lot and couldn't find a way to do it. If this is not the correct approach to do so, kindly let me know the proper way to do it. I am new to React + Redux so finding it a bit difficult.

Thanks in advance

Body:
I want to pass a function defined in my actions to an element.

Reducer

case 'UPDATE_HEADER':
    return Object.assign({}, state, {
        headerChildren: state.headerChildren.concat([action.child])
    });

Action.js

export const deleteHeader = () => {
    return {
        type: 'DELETE_HEADER',
    };
}

I am passing this action to my sidebar

onAddHeader () {
    this.props.addHeader();
    this.props.updateHeader(
        ``,
    );
}

The deleteHeader function is being passed to the Header component but the problem is that it is being passed as a string and not as a function.

I am rendering it as this

`{this.props.headerChildren.map((value, index) => (
    <JsxParser
        key={index}
        components={[Header]}
        jsx={value}
    />
))}`

Can someone please guide me through the solution. I have searched a lot and couldn't find a way to do it. If this is not the correct approach to do so, kindly let me know the proper way to do it. I am new to React + Redux so finding it a bit difficult.

Thanks in advance

Body:
You don't need to use $ or single quotes when passing props these kind of props.. You just need to enclose the value to be evaluated in {}.. It is only when you need to pass a string literal do you use single quotes.

So use something like this instead

<Header key={this.props.childKey} deleteHeader={this.props.deleteHeader}/>


问:
Can't get date modified From Json
i can get section name , url  web title and headline but i can't get lastmodified date  from parse json this code for Json

{
   "response":{
      "status":"ok",
      "userTier":"developer",
      "total":368,
      "startIndex":1,
      "pageSize":10,
      "currentPage":1,
      "pages":37,
      "orderBy":"relevance",
      "results":[
         {
            "id":"technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "type":"article",
            "sectionId":"technology",
            "sectionName":"Technology",
            "webPublicationDate":"2017-05-24T15:00:24Z",
            "webTitle":"Fitness trackers out of step when measuring calories, research shows",
            "webUrl":"https://www.theguardian.com/technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "apiUrl":"https://content.guardianapis.com/technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "fields":{
               "headline":"Fitness trackers out of step when measuring calories, research shows",
               "lastModified":"2017-05-24T15:02:19Z",
               "thumbnail":"https://media.guim.co.uk/8d3e17604195078ec89e20329e2ddc5027eca8ea/0_213_6362_3817/500.jpg"
            },
            "isHosted":false
         },```
</div>
</div>
</p>

<p>and this my code to parse it.</p>

<p>JSONObject response = root.getJSONObject("response");</p>

```        if(response.has("results")){

            JSONArray results = response.getJSONArray("results");
            for(int i=0;i<results.length();i++){
                long lastModified=0;
                String headline=null;
                JSONObject details=results.getJSONObject(i);
                String sectionName=details.getString("sectionName");
                Log.i(LOG_TAG,sectionName);
                String webUrl=details.getString("webUrl");
                Log.i(LOG_TAG,webUrl);
                if(details.has("fields")){
                JSONObject fields=details.getJSONObject("fields");
                    if(fields.has("headline")){

                 headline =fields.getString("headline");
                Log.i(LOG_TAG,headline);}
                if(fields.has("lastModified")){
                 lastModified =fields.getLong("lastModified");
                Log.i(LOG_TAG, String.valueOf(lastModified));}}
```

i do not know why not get lastmodified date?

答:
You can parse Json and get the lastModified like this,

```<code>public static void parse(String response) {
    try {
        JSONObject baseObject = new JSONObject(response);

        if (baseObject == null) {
            return;
        }

        JSONObject responseObj = baseObject.optJSONObject("response");

        if (response == null) {
            return;
        }

        JSONArray resultsArray = responseObj.getJSONArray("results");

        if (resultsArray == null) {
            return;
        }

        for (int i = 0; i < resultsArray.length(); i++) {
            JSONObject resultObj = resultsArray.getJSONObject(i);

            if (resultObj == null) {
                continue;
            }

            String id = resultObj.optString("id", "");
            String type = resultObj.optString("type", "");
            String sectionId = resultObj.optString("sectionId", "");
            String sectionName = resultObj.optString("sectionName", "");
            String webPublicationDate = resultObj.optString("webPublicationDate", "");
            String webTitle = resultObj.optString("webTitle", "");
            String webUrl = resultObj.optString("webUrl", "");
            String apiUrl = resultObj.optString("apiUrl", "");
            boolean isHosted = resultObj.optBoolean("isHosted", false);

            JSONObject fieldsObj = resultObj.optJSONObject("fields");

            if (fieldsObj == null) {
                 continue;
            }

            String headline = fieldsObj.optString("headline", "");
            String lastModified = fieldsObj.optString("lastModified", "");
            String thumbnail = fieldsObj.optString("thumbnail", "");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
</code>```

To convert the date into specific format

```<code>public static String getDateFromatedString(String inputDate) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");

    Date date = null;
    try {
        date = simpleDateFormat.parse(inputDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if (date == null) {
        return "";
    }

    SimpleDateFormat convetDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    return convetDateFormat.format(date);
}
</code>```

Title: Can't get date modified From Json

Body:
i can get section name , url  web title and headline but i can't get lastmodified date  from parse json this code for Json

{
   "response":{
      "status":"ok",
      "userTier":"developer",
      "total":368,
      "startIndex":1,
      "pageSize":10,
      "currentPage":1,
      "pages":37,
      "orderBy":"relevance",
      "results":[
         {
            "id":"technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "type":"article",
            "sectionId":"technology",
            "sectionName":"Technology",
            "webPublicationDate":"2017-05-24T15:00:24Z",
            "webTitle":"Fitness trackers out of step when measuring calories, research shows",
            "webUrl":"https://www.theguardian.com/technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "apiUrl":"https://content.guardianapis.com/technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "fields":{
               "headline":"Fitness trackers out of step when measuring calories, research shows",
               "lastModified":"2017-05-24T15:02:19Z",
               "thumbnail":"https://media.guim.co.uk/8d3e17604195078ec89e20329e2ddc5027eca8ea/0_213_6362_3817/500.jpg"
            },
            "isHosted":false
         },

and this my code to parse it.

JSONObject response = root.getJSONObject("response");

        if(response.has("results")){

            JSONArray results = response.getJSONArray("results");
            for(int i=0;i<results.length();i++){
                long lastModified=0;
                String headline=null;
                JSONObject details=results.getJSONObject(i);
                String sectionName=details.getString("sectionName");
                Log.i(LOG_TAG,sectionName);
                String webUrl=details.getString("webUrl");
                Log.i(LOG_TAG,webUrl);
                if(details.has("fields")){
                JSONObject fields=details.getJSONObject("fields");
                    if(fields.has("headline")){

                 headline =fields.getString("headline");
                Log.i(LOG_TAG,headline);}
                if(fields.has("lastModified")){
                 lastModified =fields.getLong("lastModified");
                Log.i(LOG_TAG, String.valueOf(lastModified));}}

i do not know why not get lastmodified date?

Body:
You can parse Json and get the lastModified like this,

public static void parse(String response) {
    try {
        JSONObject baseObject = new JSONObject(response);

        if (baseObject == null) {
            return;
        }

        JSONObject responseObj = baseObject.optJSONObject("response");

        if (response == null) {
            return;
        }

        JSONArray resultsArray = responseObj.getJSONArray("results");

        if (resultsArray == null) {
            return;
        }

        for (int i = 0; i < resultsArray.length(); i++) {
            JSONObject resultObj = resultsArray.getJSONObject(i);

            if (resultObj == null) {
                continue;
            }

            String id = resultObj.optString("id", "");
            String type = resultObj.optString("type", "");
            String sectionId = resultObj.optString("sectionId", "");
            String sectionName = resultObj.optString("sectionName", "");
            String webPublicationDate = resultObj.optString("webPublicationDate", "");
            String webTitle = resultObj.optString("webTitle", "");
            String webUrl = resultObj.optString("webUrl", "");
            String apiUrl = resultObj.optString("apiUrl", "");
            boolean isHosted = resultObj.optBoolean("isHosted", false);

            JSONObject fieldsObj = resultObj.optJSONObject("fields");

            if (fieldsObj == null) {
                 continue;
            }

            String headline = fieldsObj.optString("headline", "");
            String lastModified = fieldsObj.optString("lastModified", "");
            String thumbnail = fieldsObj.optString("thumbnail", "");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

To convert the date into specific format

public static String getDateFromatedString(String inputDate) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");

    Date date = null;
    try {
        date = simpleDateFormat.parse(inputDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if (date == null) {
        return "";
    }

    SimpleDateFormat convetDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    return convetDateFormat.format(date);
}


问:
How to make a object instance of a existing instance of a usercontrol?
How to make a object instance of a existing instance of a usercontrol?

```<code>public partial class Rfid : UserControl
</code>```

This is how you would do it with an Window?

```<code>public partial class MainWindow : Window
MainWindow my = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
</code>```

答:
Application.Current.Windows is a collection of all the windows that currently exist in your application. You aren't "making" anything. The window is an object. The window instance is an instance of the window. You're pulling a reference to it out of the collection.

MainWindow my in your question is a reference to an instance of MainWindow.

There is no such collection of all the user controls, or of any controls. You can get the immediate child control of the window, but then you have to recursively look through its children, and their children, and so on.

In the XAML where an instance of the user control is being defined, give it an x:Name attribute. Then, in the parent, you can refer to it by name.

MainWindow.xaml

```<code><local:Rfid
    x:Name="FooBar"
    MyProperty="Some Value"
    />
</code>```

MainWindow.xaml.cs

This is just an example, since you didn't say what you wanted to do with it, or where, or why.

```<code>public void SomeButton_Click(Object sender, RoutedEventArgs e)
{
    FooBar.MyProperty = "Some other value";
}
</code>```

You should really be doing this with MVVM, of course.

Body:
How to make a object instance of a existing instance of a usercontrol?

public partial class Rfid : UserControl

This is how you would do it with an Window?

public partial class MainWindow : Window
MainWindow my = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();

Body:
Application.Current.Windows is a collection of all the windows that currently exist in your application. You aren't "making" anything. The window is an object. The window instance is an instance of the window. You're pulling a reference to it out of the collection.

MainWindow my in your question is a reference to an instance of MainWindow.

There is no such collection of all the user controls, or of any controls. You can get the immediate child control of the window, but then you have to recursively look through its children, and their children, and so on.

In the XAML where an instance of the user control is being defined, give it an x:Name attribute. Then, in the parent, you can refer to it by name.

MainWindow.xaml

<local:Rfid
    x:Name="FooBar"
    MyProperty="Some Value"
    />

MainWindow.xaml.cs

This is just an example, since you didn't say what you wanted to do with it, or where, or why.

public void SomeButton_Click(Object sender, RoutedEventArgs e)
{
    FooBar.MyProperty = "Some other value";
}

You should really be doing this with MVVM, of course.


问:
index syntax ('content['xxx']") for accessing members of .SWF
I was actually looking for the adobe docs online that would cover syntax like the following:

SWFLoader(event.target).content['wrFont']

That's from my own code, so obivously I know it works, its just that after 2 years of Flex programming,  I have still not encountered any sort of formal documentation on the rules governing this access method (i.e. like in the above where I'm accessing the wrFont member of the loaded SWF via an array index syntax and a string.

Specifically, it would be things like, determining if the referenced member even exists - what would be the standard method for doing that (Surely not just a try-catch block right?).  But not just that, but formal Adobe Documentation on all relevant aspects of the above. I've downloaded all zipped adobe docs off of their live docs site - where is all this fully documented.

ON a side note, something that's always bugged me about google, is that with a search string like ".content["  it just ignores the "[" character as irrelevant, though if I could just find that search string I would have my answer.  But google doesnt search for characters like "[" evidently. Neither does Bing.  Does any search engine do this.

答:
If you want to make sure your a given member exists you code test like this :

```<code>if(SWFLoader(event.target).content['wrFont']) = null)
</code>```

But this is not really recommended because your actually don't if the type of the content you are loading actually has this property or not.

What you should do in your case in cast the "content" property of SWFLoader to its actual class, or even better, use an interface to decouple your SWF files :

```<code>public interface IWRFontContainer {
   function get wrFont():Font;
}
</code>```

Make your SWF main/document class implement this interface and then cast the content where you are loading it:

```<code>var swf:IWRFontContainer = SWFLoader(event.target).content as IWRFontContainer;
trace(swf.wrFont);
</code>```

To make sure your content is of type IWRFont, you can check the type using the isto check the type or use a try/catch block.

ContentLicense: CC BY-SA 2.5

Body:
If you want to make sure your a given member exists you code test like this :

if(SWFLoader(event.target).content['wrFont']) = null)

But this is not really recommended because your actually don't if the type of the content you are loading actually has this property or not.

What you should do in your case in cast the "content" property of SWFLoader to its actual class, or even better, use an interface to decouple your SWF files :

public interface IWRFontContainer {
   function get wrFont():Font;
}

Make your SWF main/document class implement this interface and then cast the content where you are loading it:

var swf:IWRFontContainer = SWFLoader(event.target).content as IWRFontContainer;
trace(swf.wrFont);

To make sure your content is of type IWRFont, you can check the type using the isto check the type or use a try/catch block.


问:
Can I use CHAR_BIT as the basis for determining the number of bits in other types?
For example, does the following code make no assumptions that might be incorrect on certain systems?</p>

```<code> // Number of bits in an unsigned long long int:
 const int ULLONG_BIT = sizeof(unsigned long long int) * CHAR_BIT;
</code>```

答:
I agree with PSkocik's comment to the original question. C11 6.2.6 says CHAR_BIT * sizeof (type) yields the number of bits in the object representation of type type, but some of them may be padding bits.

I suspect that your best bet for a "no-assumptions" code is to simply check the value of ULLONG_MAX (or ~0ULL or (unsigned long long)(-1LL), which should all evaluate to the same value):

```<code>#include <limits.h>

static inline int ullong_bit(void)
{
    unsigned long long m = ULLONG_MAX;
    int n = 0, i = 0;
    while (m) {
        n += m & 1;
        i ++;
        m >>= 1;
    }
    if (n == i)
        return i;
    else
        return i-1;
}
</code>```

If the binary pattern for the value is all ones, then the number of bits an unsigned long long can hold is the same as the number of binary digits in the value.

Otherwise, the most significant bit cannot really be used, because the maximum value in binary contains zeros.

Body:
For example, does the following code make no assumptions that might be incorrect on certain systems?

 // Number of bits in an unsigned long long int:
 const int ULLONG_BIT = sizeof(unsigned long long int) * CHAR_BIT;

Body:
I agree with PSkocik's comment to the original question. C11 6.2.6 says CHAR_BIT * sizeof (type) yields the number of bits in the object representation of type type, but some of them may be padding bits.

I suspect that your best bet for a "no-assumptions" code is to simply check the value of ULLONG_MAX (or ~0ULL or (unsigned long long)(-1LL), which should all evaluate to the same value):

#include <limits.h>

static inline int ullong_bit(void)
{
    unsigned long long m = ULLONG_MAX;
    int n = 0, i = 0;
    while (m) {
        n += m & 1;
        i ++;
        m >>= 1;
    }
    if (n == i)
        return i;
    else
        return i-1;
}

If the binary pattern for the value is all ones, then the number of bits an unsigned long long can hold is the same as the number of binary digits in the value.

Otherwise, the most significant bit cannot really be used, because the maximum value in binary contains zeros.


问:
How to Denormalize object with java.util.stream
I have the following objects:

```<code>public class Customer {

    private int id;
    private String name;
    private Collection<Order> orders;

    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public Collection<Order> getOrders() {return orders;}
    public void setOrders(Collection<Order> orders) {this.orders = orders;}
}

public class Order {
    private int id;
    private String item;

    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getItem() {return item;}
    public void setItem(String item) {this.item = item;}
}

public class CustomerOrderDto {
    private int customerId;
    private String customerName;
    private String orderId;
    private String orderItem;

    public int getCustomerId() {return customerId;}
    public void setCustomerId(int customerId) {this.customerId = customerId;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public String getOrderId() {return orderId;}
    public void setOrderId(String orderId) {this.orderId = orderId;}
    public String getOrderItem() {return orderItem;}
    public void setOrderItem(String orderItem) {this.orderItem = orderItem;}
}
</code>```

So if I have a Customer object with two Orders the result would be a list of two CustomerOrderDto objects.

I can obviously do this with for loops, but I am looking for a more elegant solution using Java streams.

My background is .NET where I can easily do this with LINQ, but this my first java project and I wanted to see if I can do something similar here.

答:
If you want access your object with foreach

```<code>orders.forEach((k)->System.out.println("Item : " + k));
</code>```

More examples here.

Body:
I have the following objects:

public class Customer {

    private int id;
    private String name;
    private Collection<Order> orders;

    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public Collection<Order> getOrders() {return orders;}
    public void setOrders(Collection<Order> orders) {this.orders = orders;}
}

public class Order {
    private int id;
    private String item;

    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getItem() {return item;}
    public void setItem(String item) {this.item = item;}
}

public class CustomerOrderDto {
    private int customerId;
    private String customerName;
    private String orderId;
    private String orderItem;

    public int getCustomerId() {return customerId;}
    public void setCustomerId(int customerId) {this.customerId = customerId;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public String getOrderId() {return orderId;}
    public void setOrderId(String orderId) {this.orderId = orderId;}
    public String getOrderItem() {return orderItem;}
    public void setOrderItem(String orderItem) {this.orderItem = orderItem;}
}

So if I have a Customer object with two Orders the result would be a list of two CustomerOrderDto objects.

I can obviously do this with for loops, but I am looking for a more elegant solution using Java streams.

My background is .NET where I can easily do this with LINQ, but this my first java project and I wanted to see if I can do something similar here.

Body:
If you want access your object with foreach

orders.forEach((k)->System.out.println("Item : " + k));

More examples here.


问:
Making text selectable on hover with css
I have a span element that is holding some text. I want to be able to hover over the element and make the text selectable.

The HTML:

```<code><span>Text to copy</span>
</code>```

The SCSS:

```<code>span {

 &:hover {
   border: 1px #000 solid;
   padding: 2px;
   cursor: text;
 }
}
</code>```

However, I have not been able to copy the text.

I tried adding the 'user-select: text' property to the hover but that does not seem to work on chrome.

答:
user-select:text property means user can select the text, it does not select the text.

Two ways to achieve that:

with the help of document.execCommand()

   mouse over on text

mouse over on text

content editable - makes the span editable```
</div>
</div>
</p>

<ol start="2">
<li>with the help of jQuery</li>
</ol>

<p>Note: <code>this.select()</code> works for input and textarea.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$("textarea").mouseover(function(){
  $(this).select();
});</code>```

<textarea>mouseover on text</textarea>```

Body:
I have a span element that is holding some text. I want to be able to hover over the element and make the text selectable.

The HTML:

Text to copy

The SCSS:

span {

 &:hover {
   border: 1px #000 solid;
   padding: 2px;
   cursor: text;
 }
}

However, I have not been able to copy the text.

I tried adding the 'user-select: text' property to the hover but that does not seem to work on chrome.

Body:
user-select:text property means user can select the text, it does not select the text.

Two ways to achieve that:

with the help of document.execCommand()

   <span contenteditable="true" onmouseover="this.focus();document.execCommand('selectAll',false,null);">mouse over on text</span>
<br/>
<span>mouse over on text</span>
<br/>
<span contenteditable="true" onmouseover="this.focus();document.execCommand('selectAll',false,null);">content editable</span> - makes the span editable

with the help of jQuery

Note: this.select() works for input and textarea.

$("textarea").mouseover(function(){
  $(this).select();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>mouseover on text</textarea>


问:
How to use n-grams for multi-label classification?
I am working on a project to identify the nationality of the person based on the manner in which they communicate in English. I have 10 nationalities & 1000 files, 100 for each nationality. I am using n-grams as features & looking to validate my approach. My data structure, would have different n-grams (character n-grams, bi-grams, as columns) as features & nationality as labels (as rows) My Steps are :

Pick up all files for a given nationality (FINE).
1.1. Combine them together to form a text corpus (e.g Combine 100 files into 1 big file). I initially thought for taking one file at a time & updating the count of n-grams based on their occurance. But then for each new n-gram, i would have to do a look up to see if it has already occured & then update its frequency, for a given label. Would this be a better approach ?

Extract bi-grams / tri-grams & get frequency of each gram. (NLTK has FreqDist which gives count for each)

Store this information, so I would use it to classify my test set. (HOW DO I STORE THIS INFORMATION. MORE INFORMATION BELOW)

Question is should I store the n-gram & frequency information in a matrix (a single matrix having all n-grams & labels OR separate matrix for each label) or should I store it as a map (a map for each label, having n-gram & its frequency count). I would like to have a data structure (for storing the extracted information) that would be easy for classifiers to take as input & process them. I cannot foresee, which data structure would be a better option.

答:
1) it shouldn't matter. if you have a way to do it separately and then merge it, it will help if in the future you want to scale to a distributed system (that's usually called map-reduce approach).

2) ok.

3) n-gram and frequency counts are usually not suitable on their own for feature classification. you probably want to have separate matrices/maps for each label and then use something like TF-IDF (https://en.wikipedia.org/wiki/Tf%E2%80%93idf) to identify n-grams that are characteristic of a particular label.

4) when it comes to classification, you'd then build a fixed-length vector where you select a subset of the ngrams identified for each label in the previous step and then use that for training and classification. you'd probably need some sort of normalization for the counts as well.


问:
Couchdb not starting. -- Failure to start Mochiweb: eaddrinuse
I have configure and installed couchdb 1.6.1 on ubuntu 10.04. While configuring and installing it said successfully done. But when I start couchdb it gives me error.

When start first..

```<code>Apache CouchDB 1.6.1 (LogLevel=info) is starting.

Apache CouchDB has started. Time to relax.

**[info] [<0.32.0>] Apache CouchDB has started on http://127.0.0.1:5984/**
</code>```

When starting again

```<code> Apache CouchDB 1.6.1 (LogLevel=info) is starting.

 **Failure to start Mochiweb: eaddrinuse**

[error] [<0.127.0>] {error_report,<0.31.0>,
                    {<0.127.0>,crash_report,[[{initial_call,
                           {mochiweb_socket_server,init,['Argument__1']}},
                       {pid,<0.127.0>},
                       {registered_name,[]},
                       {error_info,
                           {exit,eaddrinuse,
                               [{gen_server,init_it,6},
                                {proc_lib,init_p_do_apply,3}]}},
                       {ancestors,
                           [couch_secondary_services,couch_server_sup,
                            <0.32.0>]},
                       {messages,[]},
                       {links,[<0.95.0>]},
                       {dictionary,[]},
                       {trap_exit,true},
                       {status,running},
                       {heap_size,987},
                       {stack_size,24},
                       {reductions,467}],
                      []]}}
{"init terminating in do_boot",{{badmatch,{error,{bad_return,{{couch_app,start,[normal,["/usr/local/etc/couchdb/default.ini","/usr/local/etc/couchdb/local.ini"]]},{'EXIT',{{badmatch,{error,shutdown}},[{couch_server_sup,start_server,1},{application_master,start_it_old,4}]}}}}}},[{couch,start,0},{init,start_it,1},{init,start_em,1}]}}

Crash dump was written to: erl_crash.dump
init terminating in do_boot ()
</code>```

in local.ini I changed
Port to 5983 and also ip to 0.0.0.0 from 127.0.0.1
Nothing helped

When i run sudo netstat -tulpn

I get following output

tcp        0      0 127.0.0.1:5984          0.0.0.0:*               LISTEN      21688/beam.smp

couchdb -s says Apache CouchDB is not running.

Thanks in advance

答:
I have encountered this error in starting couchdb on ubuntu 16.04

The reason being erlang running on the port 5984, you would be something like below when running the command "netstat -tulpn"

0      0 127.0.0.1:5984          0.0.0.0:*               LISTEN      13967/beam.smp

open the file /etc/couchdb/default.ini in super user mode and change the httpd port to some other port which is available and you would be able to start couchdb without any fail.

Body:
I have configure and installed couchdb 1.6.1 on ubuntu 10.04. While configuring and installing it said successfully done. But when I start couchdb it gives me error.

When start first..

Apache CouchDB 1.6.1 (LogLevel=info) is starting.

Apache CouchDB has started. Time to relax.

**[info] [<0.32.0>] Apache CouchDB has started on http://127.0.0.1:5984/**

When starting again

 Apache CouchDB 1.6.1 (LogLevel=info) is starting.

 **Failure to start Mochiweb: eaddrinuse**

[error] [<0.127.0>] {error_report,<0.31.0>,
                    {<0.127.0>,crash_report,[[{initial_call,
                           {mochiweb_socket_server,init,['Argument__1']}},
                       {pid,<0.127.0>},
                       {registered_name,[]},
                       {error_info,
                           {exit,eaddrinuse,
                               [{gen_server,init_it,6},
                                {proc_lib,init_p_do_apply,3}]}},
                       {ancestors,
                           [couch_secondary_services,couch_server_sup,
                            <0.32.0>]},
                       {messages,[]},
                       {links,[<0.95.0>]},
                       {dictionary,[]},
                       {trap_exit,true},
                       {status,running},
                       {heap_size,987},
                       {stack_size,24},
                       {reductions,467}],
                      []]}}
{"init terminating in do_boot",{{badmatch,{error,{bad_return,{{couch_app,start,[normal,["/usr/local/etc/couchdb/default.ini","/usr/local/etc/couchdb/local.ini"]]},{'EXIT',{{badmatch,{error,shutdown}},[{couch_server_sup,start_server,1},{application_master,start_it_old,4}]}}}}}},[{couch,start,0},{init,start_it,1},{init,start_em,1}]}}

Crash dump was written to: erl_crash.dump
init terminating in do_boot ()

in local.ini I changed
Port to 5983 and also ip to 0.0.0.0 from 127.0.0.1
Nothing helped

When i run sudo netstat -tulpn

I get following output

tcp        0      0 127.0.0.1:5984          0.0.0.0:*               LISTEN      21688/beam.smp

couchdb -s says Apache CouchDB is not running.

Thanks in advance


问:
Count (Distinct ([value)) OVER (Partition by) in SQL Server 2008
I have written this and successfully executed in Oracle

```<code>COUNT (DISTINCT APEC.COURSE_CODE) OVER (
                                            PARTITION BY s.REGISTRATION_NUMBER
                                            ,APEC.APE_ID
                                            ,COV.ACADEMIC_SESSION
                                            ) APE_COURSES_PER_ACADEMIC_YEAR
</code>```

I'm trying to achieve the same result in SQL Server (our source database uses Oracle but our warehouse uses SQL Server).

I know the distinct isn't supported with window functions in SQL Server 2008 - can anyone suggest an alternative?

答:
Here's what I recently came across. I got it from this post. So far it works really well for me.</p>

```<code>DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields ASC) +
DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields DESC) - 1 AS DistinctCount
</code>```

Body:
I have written this and successfully executed in Oracle

COUNT (DISTINCT APEC.COURSE_CODE) OVER (
                                            PARTITION BY s.REGISTRATION_NUMBER
                                            ,APEC.APE_ID
                                            ,COV.ACADEMIC_SESSION
                                            ) APE_COURSES_PER_ACADEMIC_YEAR

I'm trying to achieve the same result in SQL Server (our source database uses Oracle but our warehouse uses SQL Server).

I know the distinct isn't supported with window functions in SQL Server 2008 - can anyone suggest an alternative?

Body:
Here's what I recently came across. I got it from this post. So far it works really well for me.

DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields ASC) +
DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields DESC) - 1 AS DistinctCount


问:
excel interop unable to start server exception after several calls
I have an asp.net MVC Webapplication who uses the excel interop to open a csv in an excel save the file as an xlsx and load the bytes from that file. These bytes are then passed as a download.

So far everything works as expected. but after the 6 download I get the following exception. Unfortunately it's on german, since the server is setup in german. But the exception message is something like "80080005 starting the server failed".

```<code>Die COM-Klassenfactory für die Komponente mit CLSID {00024500-0000-0000-C000-000000000046} konnte aufgrund des folgenden Fehlers nicht abgerufen werden: 80080005 Starten des Servers fehlgeschlagen (Ausnahme von HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).

    Beschreibung: Unbehandelte Ausnahme beim Ausführen der aktuellen Webanforderung. Überprüfen Sie die Stapelüberwachung, um weitere Informationen über diesen Fehler anzuzeigen und festzustellen, wo der Fehler im Code verursacht wurde.

    Ausnahmedetails: System.Runtime.InteropServices.COMException: Die COM-Klassenfactory für die Komponente mit CLSID {00024500-0000-0000-C000-000000000046} konnte aufgrund des folgenden Fehlers nicht abgerufen werden: 80080005 Starten des Servers fehlgeschlagen (Ausnahme von HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).
</code>```

When I restart the website, it works again for the next 5-7 downloads.

here is my code for the excel:

```<code>private byte[] WriteExcel(SelectionResult result)
{
        var csvPath = Path.Combine(Settings.Default.FileGenerationPath, DateTime.Now.ToString("yyMMMddhhmmss") + "_" +new Random().Next(1000, 9999)+".csv");
        var excelPath = Path.Combine(Settings.Default.FileGenerationPath, DateTime.Now.ToString("yyMMMddhhmmss") + "_" + new Random().Next(1000, 9999)+".xlsx");

        var excelApp = new Application();
        File.WriteAllBytes(csvPath, WriteCsv(result, true));

        var excelWorkbooks = excelApp.Workbooks;
        excelWorkbooks.Open(csvPath, Delimiter: ",");
        var workbook = excelApp.ActiveWorkbook;

        workbook.SaveAs(excelPath, XlFileFormat.xlOpenXMLWorkbook);

        excelWorkbooks.Close();
        excelApp.Quit();

        var bytes = File.ReadAllBytes(excelPath);
        File.Delete(csvPath);
        File.Delete(excelPath);
        return bytes;
    }
</code>```

What do I miss?

答:
According to Microsoft Support, that kind of error

You may receive an "Error code 80080005 -- server execution failed." error message when you start many COM+ applications

arise when you are using too many com applications. And you have a pretty much not disposed unmanaged resources. Every time use using statement in you are using input-output operations.

Update No. You don't. Closing an Excel is not releasing COM object while the application is running.

You need to:

```<code>        //include marshal
        using System.Runtime.InteropServices;
        //release objects
        Marshal.ReleaseComObject(excelApp);
        Marshal.ReleaseComObject(excelWorkbooks);
        Marshal.ReleaseComObject(workbook);
</code>```

Body:
I have an asp.net MVC Webapplication who uses the excel interop to open a csv in an excel save the file as an xlsx and load the bytes from that file. These bytes are then passed as a download.

So far everything works as expected. but after the 6 download I get the following exception. Unfortunately it's on german, since the server is setup in german. But the exception message is something like "80080005 starting the server failed".

Die COM-Klassenfactory für die Komponente mit CLSID {00024500-0000-0000-C000-000000000046} konnte aufgrund des folgenden Fehlers nicht abgerufen werden: 80080005 Starten des Servers fehlgeschlagen (Ausnahme von HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).

    Beschreibung: Unbehandelte Ausnahme beim Ausführen der aktuellen Webanforderung. Überprüfen Sie die Stapelüberwachung, um weitere Informationen über diesen Fehler anzuzeigen und festzustellen, wo der Fehler im Code verursacht wurde.

    Ausnahmedetails: System.Runtime.InteropServices.COMException: Die COM-Klassenfactory für die Komponente mit CLSID {00024500-0000-0000-C000-000000000046} konnte aufgrund des folgenden Fehlers nicht abgerufen werden: 80080005 Starten des Servers fehlgeschlagen (Ausnahme von HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).

When I restart the website, it works again for the next 5-7 downloads.

here is my code for the excel:

private byte[] WriteExcel(SelectionResult result)
{
        var csvPath = Path.Combine(Settings.Default.FileGenerationPath, DateTime.Now.ToString("yyMMMddhhmmss") + "_" +new Random().Next(1000, 9999)+".csv");
        var excelPath = Path.Combine(Settings.Default.FileGenerationPath, DateTime.Now.ToString("yyMMMddhhmmss") + "_" + new Random().Next(1000, 9999)+".xlsx");

        var excelApp = new Application();
        File.WriteAllBytes(csvPath, WriteCsv(result, true));

        var excelWorkbooks = excelApp.Workbooks;
        excelWorkbooks.Open(csvPath, Delimiter: ",");
        var workbook = excelApp.ActiveWorkbook;

        workbook.SaveAs(excelPath, XlFileFormat.xlOpenXMLWorkbook);

        excelWorkbooks.Close();
        excelApp.Quit();

        var bytes = File.ReadAllBytes(excelPath);
        File.Delete(csvPath);
        File.Delete(excelPath);
        return bytes;
    }

What do I miss?

Body:
According to Microsoft Support, that kind of error

You may receive an "Error code 80080005 -- server execution failed." error message when you start many COM+ applications

arise when you are using too many com applications. And you have a pretty much not disposed unmanaged resources. Every time use using statement in you are using input-output operations.

Update No. You don't. Closing an Excel is not releasing COM object while the application is running.

You need to:

        //include marshal
        using System.Runtime.InteropServices;
        //release objects
        Marshal.ReleaseComObject(excelApp);
        Marshal.ReleaseComObject(excelWorkbooks);
        Marshal.ReleaseComObject(workbook);


问:
Error in building docker image with perl installation
I am new to docker and i am trying to build the docker image with the perl installation but not sure exactly how to fix this error.

Dockerfile:

```<code>FROM amazonlinux

RUN mkdir /shared
RUN cd /shared

RUN yum -y install sudo
RUN cd /shared
RUN echo "Installing Perl."
RUN sudo yum -y update; yum -y install gcc
RUN yum -y install wget
RUN wget http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz
RUN tar -xzf perl-5.22.1.tar.gz
RUN cd perl-5.22.1
RUN /shared/perl-5.22.1/Configure -des -Dprefix=/opt/perl-5.22.1/localperl
RUN make
RUN make test
RUN make install
RUN echo "Perl installation complete."
</code>```

instead of /shared/perl-5.22.1/Configure i tried to give ./configure as well but i get the same error No such file or directory

Error:

```<code>/bin/sh: /shared/perl-5.22.1/Configure: No such file or directory
The command '/bin/sh -c /shared/perl-5.22.1/Configure -des -Dprefix=/opt/perl-5.22.1/localperl' returned a non-zero code: 127
ish-mac:testanalyse ish$
</code>```

Can anyone tell me how to fix this issue.

答:
Each Dockerfile RUN command runs in its own shell. So, when you do something like RUN cd /shared, the subsequent RUN commands will not be run inside that working directory.

What you want to use in this case is the WORKDIR instruction (https://docs.docker.com/engine/reference/builder/#workdir). You can also combine and shorten some things by taking advantage of the ADD instruction. A more concise Dockerfile to do what you are after might be:

```<code>FROM amazonlinux
WORKDIR /shared
RUN yum -y install gcc
ADD http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz /shared
RUN tar -xzf perl-5.22.1.tar.gz
RUN /shared/perl-5.22.1/Configure -des -Dprefix=/opt/perl-5.22.1/localperl
RUN make -C /shared/perl-5.22.1
RUN make -C /shared/perl-5.22.1 test
RUN make -C /shared/perl-5.22.1 install
</code>```

For example, the build context is already running as root so there is no need for sudo. With ADD we can add directly from URLs and no wget is required. And the make utility has a -C option to specify the working directory for make.

This should get you closer to what you are after. But the build still fails for other reasons (which you should probably open another question for if you are stuck).

Body:
I am new to docker and i am trying to build the docker image with the perl installation but not sure exactly how to fix this error.

Dockerfile:

FROM amazonlinux

RUN mkdir /shared
RUN cd /shared

RUN yum -y install sudo
RUN cd /shared
RUN echo "Installing Perl."
RUN sudo yum -y update; yum -y install gcc
RUN yum -y install wget
RUN wget http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz
RUN tar -xzf perl-5.22.1.tar.gz
RUN cd perl-5.22.1
RUN /shared/perl-5.22.1/Configure -des -Dprefix=/opt/perl-5.22.1/localperl
RUN make
RUN make test
RUN make install
RUN echo "Perl installation complete."

instead of /shared/perl-5.22.1/Configure i tried to give ./configure as well but i get the same error No such file or directory

Error:

/bin/sh: /shared/perl-5.22.1/Configure: No such file or directory
The command '/bin/sh -c /shared/perl-5.22.1/Configure -des -Dprefix=/opt/perl-5.22.1/localperl' returned a non-zero code: 127
ish-mac:testanalyse ish$

Can anyone tell me how to fix this issue.

Body:
Each Dockerfile RUN command runs in its own shell. So, when you do something like RUN cd /shared, the subsequent RUN commands will not be run inside that working directory.

What you want to use in this case is the WORKDIR instruction (https://docs.docker.com/engine/reference/builder/#workdir). You can also combine and shorten some things by taking advantage of the ADD instruction. A more concise Dockerfile to do what you are after might be:

FROM amazonlinux
WORKDIR /shared
RUN yum -y install gcc
ADD http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz /shared
RUN tar -xzf perl-5.22.1.tar.gz
RUN /shared/perl-5.22.1/Configure -des -Dprefix=/opt/perl-5.22.1/localperl
RUN make -C /shared/perl-5.22.1
RUN make -C /shared/perl-5.22.1 test
RUN make -C /shared/perl-5.22.1 install

For example, the build context is already running as root so there is no need for sudo. With ADD we can add directly from URLs and no wget is required. And the make utility has a -C option to specify the working directory for make.

This should get you closer to what you are after. But the build still fails for other reasons (which you should probably open another question for if you are stuck).


问:
get the first 10 google results using googleapi
I need to get the first 10 google results

for example:

```<code>... query = urllib.urlencode({'q' : 'example'})
...
... url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \
... % (query)
... search_results = urllib.urlopen(url)
... json = simplejson.loads(search_results.read())
... results = json['responseData']['results']
</code>```

this will give me the results of the first page, but I`d like to get more google results, do anyone know how to do that?

答:
I've done it in the past, here is complete example (i'm not python guru, but it works):

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, getopt
import urllib
import simplejson

OPTIONS = ("m:", ["min="])

def print_usage():
    s = "usage: " + sys.argv[0] + " "
    for o in OPTIONS[0]:
        if o != ":" : s += "[-" + o + "] "
    print(s + "query_string\n")

def search(query, index, offset, min_count, quiet=False, rs=[]):
    url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&%s&start=%s" % (query, offset)
    result = urllib.urlopen(url)
    json = simplejson.loads(result.read())
    status = json["responseStatus"]
    if status == 200:
        results = json["responseData"]["results"]
        cursor = json["responseData"]["cursor"]
        pages = cursor["pages"]
        for r in results:
            i = results.index(r) + (index -1) * len(results) + 1
            u = r["unescapedUrl"]
            rs.append(u)
            if not quiet:
                print("%3d. %s" % (i, u))
        next_index  = None
        next_offset = None
        for p in pages:
            if p["label"] == index:
                i = pages.index(p)
                if i < len(pages) - 1:
                    next_index  = pages[i+1]["label"]
                    next_offset = pages[i+1]["start"]
                break
        if next_index != None and next_offset != None:
            if int(next_offset) < min_count:
                search(query, next_index, next_offset, min_count, quiet, rs)
    return rs

def main():
    min_count = 64
    try:
        opts, args = getopt.getopt(sys.argv[1:], *OPTIONS)
        for opt, arg in opts:
            if opt in ("-m", "--min"):
                min_count = int(arg)
        assert len(args) > 0
    except:
        print_usage()
        sys.exit(1)
    qs = " ".join(args)
    query = urllib.urlencode({"q" : qs})
    search(query, 1, "0", min_count)

if __name__ == "__main__":
    main()
</code>```

Edit: i've fixed obvious command-line options mishandling; you can call this script as follows:

```<code>python gsearch.py --min=5 vanessa mae
</code>```

--min switch means "at least 5 results" and is optional, you will get maximum allowed result count (64) if it is not specified.

Also, error handling is omitted for brevity.

Body:
I need to get the first 10 google results

for example:

... query = urllib.urlencode({'q' : 'example'})
...
... url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \
... % (query)
... search_results = urllib.urlopen(url)
... json = simplejson.loads(search_results.read())
... results = json['responseData']['results']

this will give me the results of the first page, but I`d like to get more google results, do anyone know how to do that?

Body:
I've done it in the past, here is complete example (i'm not python guru, but it works):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, getopt
import urllib
import simplejson

OPTIONS = ("m:", ["min="])

def print_usage():
    s = "usage: " + sys.argv[0] + " "
    for o in OPTIONS[0]:
        if o != ":" : s += "[-" + o + "] "
    print(s + "query_string\n")

def search(query, index, offset, min_count, quiet=False, rs=[]):
    url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&%s&start=%s" % (query, offset)
    result = urllib.urlopen(url)
    json = simplejson.loads(result.read())
    status = json["responseStatus"]
    if status == 200:
        results = json["responseData"]["results"]
        cursor = json["responseData"]["cursor"]
        pages = cursor["pages"]
        for r in results:
            i = results.index(r) + (index -1) * len(results) + 1
            u = r["unescapedUrl"]
            rs.append(u)
            if not quiet:
                print("%3d. %s" % (i, u))
        next_index  = None
        next_offset = None
        for p in pages:
            if p["label"] == index:
                i = pages.index(p)
                if i < len(pages) - 1:
                    next_index  = pages[i+1]["label"]
                    next_offset = pages[i+1]["start"]
                break
        if next_index != None and next_offset != None:
            if int(next_offset) < min_count:
                search(query, next_index, next_offset, min_count, quiet, rs)
    return rs

def main():
    min_count = 64
    try:
        opts, args = getopt.getopt(sys.argv[1:], *OPTIONS)
        for opt, arg in opts:
            if opt in ("-m", "--min"):
                min_count = int(arg)
        assert len(args) > 0
    except:
        print_usage()
        sys.exit(1)
    qs = " ".join(args)
    query = urllib.urlencode({"q" : qs})
    search(query, 1, "0", min_count)

if __name__ == "__main__":
    main()

Edit: i've fixed obvious command-line options mishandling; you can call this script as follows:

python gsearch.py --min=5 vanessa mae

--min switch means "at least 5 results" and is optional, you will get maximum allowed result count (64) if it is not specified.

Also, error handling is omitted for brevity.


问:
Numpy Array Concatenation Multiplies array... why?
I have been desperately trying to figure out why an array concatenation leads to the array being multiplied by 2 on the first iteration...

This is my code:

```<code>def run(filename, max_iter = 1e6):
    data, fm = data_extraction(filename)

    large_output = None

    iteration_count = 0

    while iteration_count < max_iter:
        iteration_count += 1
        print iteration_count
        results = calculations(data, (0.9,1.1))

        if large_output == None:
            large_output = results[:,1] #stores the energy array
            print large_output
        else:
            large_output = np.c_[ large_output, results[:,1]]
            #large_output = np.vstack([large_output, power_and_energy_var[:,1]])
            print large_output
</code>```

and this is the console output for the print statement and 3 iterations only:

```<code>1
[  3.59891391e+01   5.75841568e+00   ]
2
[[  7.22402719e+01   3.62511328e+01]
 [  1.16726670e+01   5.91425129e+00]]
3
[[  7.22402719e+01   3.62511328e+01   3.70141435e+01]
 [  1.16726670e+01   5.91425129e+00   6.02176042e+00]]
</code>```

As you can see 7.22402719e+01 is about twice 3.59891391e+01, yet it doesn't occur for the successive iterations...

I have no idea why this is happening. I have tried everything I could possibly think off:

1) check what exactly was being executed using print statements
2) reloaded the kernel to erase any lingering variables
3) used np.vstack instead of np.c_ (same error)

Any help would be much welcome !!

答:
Replicating your concatenation with a simple results array:

```<code>In [229]: results = np.arange(12).reshape(2,6)
In [230]: out = results[:,1]
In [231]: out = np.c_[out, results[:,2]]
In [232]: out = np.c_[out, results[:,3]]
In [233]: out
Out[233]:
array([[1, 2, 3],
       [7, 8, 9]])
</code>```

Even though the initial out is 1d, the subsequent ones simply concatenate columns

```<code>In [234]: results[:,1]
Out[234]: array([1, 7])
</code>```

So any funny business between cnt 1 and 2 is the result of unknown behavior in data and calculations.  It's not a problem with the np.c_ concatenation.

That said, the suggestion to build the list first is a good one

```<code>In [237]: out = []
In [238]: out.append(results[:,1])
In [239]: out.append(results[:,2])
In [240]: out.append(results[:,3])
In [241]: out
Out[241]: [array([1, 7]), array([2, 8]), array([3, 9])]
In [242]: np.array(out)
Out[242]:
array([[1, 7],
       [2, 8],
       [3, 9]])
</code>```

Though it probably won't bypass any funny business in creating results.

Body:
I have been desperately trying to figure out why an array concatenation leads to the array being multiplied by 2 on the first iteration...

This is my code:

def run(filename, max_iter = 1e6):
    data, fm = data_extraction(filename)

    large_output = None

    iteration_count = 0

    while iteration_count < max_iter:
        iteration_count += 1
        print iteration_count
        results = calculations(data, (0.9,1.1))

        if large_output == None:
            large_output = results[:,1] #stores the energy array
            print large_output
        else:
            large_output = np.c_[ large_output, results[:,1]]
            #large_output = np.vstack([large_output, power_and_energy_var[:,1]])
            print large_output

and this is the console output for the print statement and 3 iterations only:

1
[  3.59891391e+01   5.75841568e+00   ]
2
[[  7.22402719e+01   3.62511328e+01]
 [  1.16726670e+01   5.91425129e+00]]
3
[[  7.22402719e+01   3.62511328e+01   3.70141435e+01]
 [  1.16726670e+01   5.91425129e+00   6.02176042e+00]]

As you can see 7.22402719e+01 is about twice 3.59891391e+01, yet it doesn't occur for the successive iterations...

I have no idea why this is happening. I have tried everything I could possibly think off:

1) check what exactly was being executed using print statements
2) reloaded the kernel to erase any lingering variables
3) used np.vstack instead of np.c_ (same error)

Any help would be much welcome !!

Body:
Replicating your concatenation with a simple results array:

In [229]: results = np.arange(12).reshape(2,6)
In [230]: out = results[:,1]
In [231]: out = np.c_[out, results[:,2]]
In [232]: out = np.c_[out, results[:,3]]
In [233]: out
Out[233]:
array([[1, 2, 3],
       [7, 8, 9]])

Even though the initial out is 1d, the subsequent ones simply concatenate columns

In [234]: results[:,1]
Out[234]: array([1, 7])

So any funny business between cnt 1 and 2 is the result of unknown behavior in data and calculations.  It's not a problem with the np.c_ concatenation.

That said, the suggestion to build the list first is a good one

In [237]: out = []
In [238]: out.append(results[:,1])
In [239]: out.append(results[:,2])
In [240]: out.append(results[:,3])
In [241]: out
Out[241]: [array([1, 7]), array([2, 8]), array([3, 9])]
In [242]: np.array(out)
Out[242]:
array([[1, 7],
       [2, 8],
       [3, 9]])

Though it probably won't bypass any funny business in creating results.


问:
What exactly does it mean to open a file in "rb" mode?
I just started to learn Python 2.X. I am trying to encrypt a file using Python. Professional users all are using pycrpto, while I am just doing a simple project to explore some of the basics in python's open file in "rb". Here is the code:

```<code>def BinXor(tBIN, kBIN):
    tLength = len(tBIN)
    kLength = len(kBIN)
    if tLength > kLength:
        while True:
            kBIN = kBIN + kBIN
            if not len(kBIN) < tLength:
                break
    kBINXOR = kBIN[:tLength]
    return "".join(["%x" % (int(x, 2) ^ int(y, 2)) for (x, y) in
    zip(tBIN,kBINXOR)])

def question():
    t = open("b.xlsx",'rb').read()
    k = '00101101'
    print BinXor(t,k)
</code>```

The error message is:

File "....py", line 27, in BinXor
    return "".join(["%x" % (int(x, 2) ^ int(y, 2)) for (x, y) in zip(tBIN,kBINXOR)])
ValueError: invalid literal for int() with base 2: 'P'
```

The error is the same if I remove "b" from the open file statement. I have been reading couple of related questions here but still could not get a clue. Can anyone help me here? Why my code is not working? What is exactly inside the result of a file opened in 'rb' mode?

答: Your error is unrelated to open. The error message says explicitly that the problem is with int function being called with 'P' as an argument. Since 'P' does not represent a binary number, int fails.

Body:
I just started to learn Python 2.X. I am trying to encrypt a file using Python. Professional users all are using pycrpto, while I am just doing a simple project to explore some of the basics in python's open file in "rb". Here is the code:

def BinXor(tBIN, kBIN):
    tLength = len(tBIN)
    kLength = len(kBIN)
    if tLength > kLength:
        while True:
            kBIN = kBIN + kBIN
            if not len(kBIN) < tLength:
                break
    kBINXOR = kBIN[:tLength]
    return "".join(["%x" % (int(x, 2) ^ int(y, 2)) for (x, y) in
    zip(tBIN,kBINXOR)])

def question():
    t = open("b.xlsx",'rb').read()
    k = '00101101'
    print BinXor(t,k)

The error message is:

File "....py", line 27, in BinXor
    return "".join(["%x" % (int(x, 2) ^ int(y, 2)) for (x, y) in zip(tBIN,kBINXOR)])
ValueError: invalid literal for int() with base 2: 'P'

The error is the same if I remove "b" from the open file statement. I have been reading couple of related questions here but still could not get a clue. Can anyone help me here? Why my code is not working? What is exactly inside the result of a file opened in 'rb' mode?


问:
"Invalid Host header" when running Angular/cli development server c9.io
Current command: ng serve --host --public $IP:$PORT

Results on my website:

Invalid Host header

答:
Refer to: https://github.com/angular/angular-cli/issues/6070

use the public flag. for example: ng serve --host <workspace>-<username>.c9users.io --public


问:
Disabling 'paste' in a jTextfield
I have an app that is written in Swing, awt.
I want to prevent users from pasting values into the textfields.
is there any way to do this without using action listeners?</p>

答:
```<code>public class PastlessJTextField extends JTextField {

        public PastlessJTextField() {
            super();
        }
        public PastlessJTextField( int columns ){
            super( columns );
        }

        @Override
        public void paste() {
            // do nothing
        }

    }
</code>```

OwnerDisplayName: kilhra

Title: Disabling 'paste' in a jTextfield


问:
EndPointReference method
I am strugglying with a problem that is to access the reference of the end point of a pipe curve to then create a dimension in the model, by the method doc.Create.Dimension().I already tried to use the Curve.EndPointReference(int index) method but it returns only null value. Can anyone help how to access this information ?</p>

答:
Also discussed and answered here by Fair59:

https://forums.autodesk.com/t5/revit-api-forum/endpointreference/td-p/7131328

The answer is also pointed to from The Building Coder:

http://thebuildingcoder.typepad.com/blog/2011/10/retrieving-duct-and-pipe-endpoints.html#comment-3344122037

Fair59's answer:

You probably are using the LocationCurve to find the reference. You need to use the "reference" Curve/Line that is part of the Element.Geometry.

```<code>Selection sel = this.ActiveUIDocument.Selection;
Element elem = doc.GetElement(sel.GetElementIds().FirstOrDefault());
Options opt = new Options();
opt.ComputeReferences = true;
opt.IncludeNonVisibleObjects = true;
opt.View = doc.ActiveView;
Reference ptRef =null;
foreach( var geoObj in elem.get_Geometry(opt) )
{
  Curve cv = geoObj as Curve;
  if (cv==null) continue;
  ptRef = cv.GetEndPointReference(0);
}
if (ptRef!=null)
{
  TaskDialog.Show("debug",ptRef.ConvertToStableRepresentation(doc));
}
</code>```

Title: EndPointReference method

Body:
Also discussed and answered here by Fair59:

https://forums.autodesk.com/t5/revit-api-forum/endpointreference/td-p/7131328

The answer is also pointed to from The Building Coder:

http://thebuildingcoder.typepad.com/blog/2011/10/retrieving-duct-and-pipe-endpoints.html#comment-3344122037

Fair59's answer:

You probably are using the LocationCurve to find the reference. You need to use the "reference" Curve/Line that is part of the Element.Geometry.

Selection sel = this.ActiveUIDocument.Selection;
Element elem = doc.GetElement(sel.GetElementIds().FirstOrDefault());
Options opt = new Options();
opt.ComputeReferences = true;
opt.IncludeNonVisibleObjects = true;
opt.View = doc.ActiveView;
Reference ptRef =null;
foreach( var geoObj in elem.get_Geometry(opt) )
{
  Curve cv = geoObj as Curve;
  if (cv==null) continue;
  ptRef = cv.GetEndPointReference(0);
}
if (ptRef!=null)
{
  TaskDialog.Show("debug",ptRef.ConvertToStableRepresentation(doc));
}


问:
Extract JSON XPath in JavaScript
I have the below JSON data. I would like to extract the HOME phone number. I do not want the work phone number. Would you write for me a JavaScript XPath expression for that?</p>

```<code>{
   "Response":{
      "Details":{
         "MemberDetails":[
            {
               "DateOfBirth":"1969-04-03T00:00:00",
               "FirstName":"MIRIDA",
               "Gender":"M",
               "LastName":"MEARES",
               "MasterId":"rrrrr",
               "PhoneList":[
                  {
                     "number":"7088739304",
                     "type":"Home"
                  },
                  {
                     "number":"7088739304",
                     "type":"Work"
                  }
               ],
               "PlatformPointerList":[
                  {
                     "application":"",
                     "keyType":"AKAName",
                     "keyValue":"xxxxxx",
                     "source":"WPP"
                  },
                  {
                     "application":"",
                     "keyType":"xxxx",
                     "keyValue":"xxx",
                     "source":"xxxx"
                  },
                  {
                     "application":"",
                     "keyType":"xxxxx",
                     "keyValue":"xxxxxx",
                     "source":"ODS"
                  },
                  {
                     "application":"",
                     "keyType":"PERSONID",
                     "keyValue":"xxxxx",
                     "source":"EM"
                  },
                  {
                     "application":"",
                     "keyType":"PERSONID",
                     "keyValue":"xxxxxx",
                     "source":"WPP"
                  }
               ],
               "MemberId":"xxxxx",
               "MemberDependentCode":"xxx",
               "MemberSource":"xx"
            }
         ]
      },
      "MetaData":{
         "CorrelationId":"undefined"
      },
      "Status":{
         "type":"OK",
         "code":"200",

      }
   }
}
</code>```

答:
Using the Saxon-JS library, you could use the XPath 3.1 expression</p>

```<code>map:find(parse-json($input), "PhoneList")?*[?type="Home"]?number
</code>```

Title: Extract JSON XPath in JavaScript

Body:
I have the below JSON data. I would like to extract the HOME phone number. I do not want the work phone number. Would you write for me a JavaScript XPath expression for that?

{
   "Response":{
      "Details":{
         "MemberDetails":[
            {
               "DateOfBirth":"1969-04-03T00:00:00",
               "FirstName":"MIRIDA",
               "Gender":"M",
               "LastName":"MEARES",
               "MasterId":"rrrrr",
               "PhoneList":[
                  {
                     "number":"7088739304",
                     "type":"Home"
                  },
                  {
                     "number":"7088739304",
                     "type":"Work"
                  }
               ],
               "PlatformPointerList":[
                  {
                     "application":"",
                     "keyType":"AKAName",
                     "keyValue":"xxxxxx",
                     "source":"WPP"
                  },
                  {
                     "application":"",
                     "keyType":"xxxx",
                     "keyValue":"xxx",
                     "source":"xxxx"
                  },
                  {
                     "application":"",
                     "keyType":"xxxxx",
                     "keyValue":"xxxxxx",
                     "source":"ODS"
                  },
                  {
                     "application":"",
                     "keyType":"PERSONID",
                     "keyValue":"xxxxx",
                     "source":"EM"
                  },
                  {
                     "application":"",
                     "keyType":"PERSONID",
                     "keyValue":"xxxxxx",
                     "source":"WPP"
                  }
               ],
               "MemberId":"xxxxx",
               "MemberDependentCode":"xxx",
               "MemberSource":"xx"
            }
         ]
      },
      "MetaData":{
         "CorrelationId":"undefined"
      },
      "Status":{
         "type":"OK",
         "code":"200",

      }
   }
}

Body:
Using the Saxon-JS library, you could use the XPath 3.1 expression

map:find(parse-json($input), "PhoneList")?*[?type="Home"]?number


问:
Gradle Implementation vs API configuration
I'm trying to figure out what is the difference between api and implementation configuration while building my dependencies.

In the documentation, it says that implementation has better build time, but, seeing this comment in a similar question I got to wonder if is it true.

Since I'm no expert in Gradle, I hope someone can help. I've read the documentation already but I was wondering about an easy-to-understand explanation.

答:
Gradle compile keyword was deprecated in favor of the api and implementation keywords to configure dependencies.

Using api is the equivalent of using the deprecated compile, so if you replace all compile with api everything will works as always.

To understand the implementation keyword consider the following example.

EXAMPLE

Suppose you have a library called MyLibrary that internally uses another library called InternalLibrary. Something like this:

```<code>// 'InternalLibrary' module
public class InternalLibrary {
    public static String giveMeAString(){
        return "hello";
    }
}
</code>```
```<code>// 'MyLibrary' module
public class MyLibrary {
    public String myString(){
        return InternalLibrary.giveMeAString();
    }
}
</code>```

Suppose the MyLibrary build.gradle uses api configuration in dependencies{} like this:

```<code>dependencies {
    api(project(":InternalLibrary"))
}
</code>```

You want to use MyLibrary in your code so in your app's build.gradle you add this dependency:

```<code>dependencies {
    implementation(project(":MyLibrary"))
}
</code>```

Using the api configuration (or deprecated compile) you can access InternalLibrary in your application code:

```<code>// Access 'MyLibrary' (granted)
MyLibrary myLib = new MyLibrary();
System.out.println(myLib.myString());

// Can ALSO access the internal library too (but you shouldn't)
System.out.println(InternalLibrary.giveMeAString());
</code>```

In this way the module MyLibrary is potentially "leaking" the internal implementation of something.  You shouldn't (be able to) use that because it's not directly imported by you.

The implementation configuration was introduced to prevent this.
So now if you use implementation instead of api in MyLibrary:

```<code>dependencies {
    implementation(project(":InternalLibrary"))
}
</code>```

you won't be able to call InternalLibrary.giveMeAString() in your app code anymore.

This sort of boxing strategy allows Android Gradle plugin to know that if you edit something in InternalLibrary, it must only trigger the recompilation of MyLibrary and not the recompilation of your entire app, because you don't have access to InternalLibrary.

When you have a lot of nested dependencies this mechanism can speed up the build a lot. (Watch the video linked at the end for a full understanding of this)

CONCLUSIONS

When you switch to the new Android Gradle plugin 3.X.X, you should replace all your compile with the implementation keyword *(1). Then try to compile and test your app. If everything it's ok leave the code as is, if you have problems you probably have something wrong with your dependencies or you used something that now is private and not more accessible. *Suggestion by Android Gradle plugin engineer Jerome Dochez (1))

If you are a library mantainer you should use api for every dependency which is needed for the public API of your library, while use implementation for test dependencies or dependencies which must not be used by the final users.

Useful article Showcasing the difference between implementation and api

REFERENCES
(This is the same video splitted up for time saving)

Google I/O 2017 - How speed up Gradle builds (FULL VIDEO)

Google I/O 2017 - How speed up Gradle builds (NEW GRADLE PLUGIN 3.0.0 PART ONLY)

Google I/O 2017 - How speed up Gradle builds (reference to 1*)

Android documentation

ContentLicense: CC BY-SA 4.0

Body:
Gradle compile keyword was deprecated in favor of the api and implementation keywords to configure dependencies.

Using api is the equivalent of using the deprecated compile, so if you replace all compile with api everything will works as always.

To understand the implementation keyword consider the following example.

EXAMPLE

Suppose you have a library called MyLibrary that internally uses another library called InternalLibrary. Something like this:

// 'InternalLibrary' module
public class InternalLibrary {
    public static String giveMeAString(){
        return "hello";
    }
}

// 'MyLibrary' module
public class MyLibrary {
    public String myString(){
        return InternalLibrary.giveMeAString();
    }
}

Suppose the MyLibrary build.gradle uses api configuration in dependencies{} like this:

dependencies {
    api(project(":InternalLibrary"))
}

You want to use MyLibrary in your code so in your app's build.gradle you add this dependency:

dependencies {
    implementation(project(":MyLibrary"))
}

Using the api configuration (or deprecated compile) you can access InternalLibrary in your application code:

// Access 'MyLibrary' (granted)
MyLibrary myLib = new MyLibrary();
System.out.println(myLib.myString());

// Can ALSO access the internal library too (but you shouldn't)
System.out.println(InternalLibrary.giveMeAString());

In this way the module MyLibrary is potentially "leaking" the internal implementation of something.  You shouldn't (be able to) use that because it's not directly imported by you.

The implementation configuration was introduced to prevent this.
So now if you use implementation instead of api in MyLibrary:

dependencies {
    implementation(project(":InternalLibrary"))
}

you won't be able to call InternalLibrary.giveMeAString() in your app code anymore.

This sort of boxing strategy allows Android Gradle plugin to know that if you edit something in InternalLibrary, it must only trigger the recompilation of MyLibrary and not the recompilation of your entire app, because you don't have access to InternalLibrary.

When you have a lot of nested dependencies this mechanism can speed up the build a lot. (Watch the video linked at the end for a full understanding of this)

CONCLUSIONS

When you switch to the new Android Gradle plugin 3.X.X, you should replace all your compile with the implementation keyword *(1). Then try to compile and test your app. If everything it's ok leave the code as is, if you have problems you probably have something wrong with your dependencies or you used something that now is private and not more accessible. *Suggestion by Android Gradle plugin engineer Jerome Dochez (1))

If you are a library mantainer you should use api for every dependency which is needed for the public API of your library, while use implementation for test dependencies or dependencies which must not be used by the final users.

Useful article Showcasing the difference between implementation and api

REFERENCES
(This is the same video splitted up for time saving)

Google I/O 2017 - How speed up Gradle builds (FULL VIDEO)

Google I/O 2017 - How speed up Gradle builds (NEW GRADLE PLUGIN 3.0.0 PART ONLY)

Google I/O 2017 - How speed up Gradle builds (reference to 1*)

Android documentation


问:
How to avoid hard-coding URLS in the static files on Django?
Is there any techniques to avoid hard coding URLs, especially the URLs for Ajax calls in an external static resource file like JavaScript files in Django.</p>

答:
Another way of handling this is to add the URLs to data attributes on a container.

```<code><div data-add-book-url="{% url "book:add" %}">
    ...
</div>
</code>```

Then you pull that URL from that data attribute and use it in the AJAX call.

Body:
Another way of handling this is to add the URLs to data attributes on a container.

<div data-add-book-url="{% url "book:add" %}">
    ...
</div>

Then you pull that URL from that data attribute and use it in the AJAX call.


问:
Jersey 2.13 + Bean Validation
I'm using gradle and the following libs:

```<code>ext.library['jersey'] = "org.glassfish.jersey:project:2.13"
ext.library['jersey_jettison'] = "org.glassfish.jersey.media:jersey-media-json-jettison:2.13"
ext.library['jersey_jackson'] = "org.glassfish.jersey.media:jersey-media-json-jackson1:2.13"
ext.library['jersey_spring'] = "org.glassfish.jersey.ext:jersey-spring3:2.13"
ext.library['jersey_bean_validation'] = "org.glassfish.jersey.ext:jersey-bean-validation:2.13"
</code>```

I created the bean validation structure, but its not validating at all. No error messages, nothing. This is the structure I've created:

The DTO

```<code>public class MergeSchedulesDto {

@NotNull(message = "validation.invalid.mergeFrom")
private Long mergeFrom;

@NotNull(message = "validation.invalid.mergeTo")
@NotEmpty(message = "validation.invalid.mergeTo")
private List<Long> mergeTo;
</code>```

The Service

```<code>@Path("merge")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
public Response merge(@Valid MergeSchedulesDto dto, @QueryParam("units") List<Long> units) {
</code>```

The config

```<code>public class ApplicationJAXRS extends Application {

    public ApplicationJAXRS() {
    }

    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> properties = new HashMap<>();
        properties
                .put("jersey.config.server.provider.packages",
                        "com.sifionsolution.sig.academic.resource.service,com.sifionsolution.sig.integration.resource.filter,com.sifionsolution.sig.academic.param.converter,com.sifionsolution.sig.datatables.resource.service,com.sifionsolution.sig.datatables.converter");

        return properties;
    }

    @Override
    public Set<Object> getSingletons() {
        Set<Object> singletons = new HashSet<>();

        singletons.add(new Jackson1Feature());
        singletons.add(new ValidationExceptionMapper());

        return singletons;
    }
}
</code>```

EDIT I forgot the provider:

```<code>@Provider
public class ValidationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException exception) {
        return Response.status(BAD_REQUEST).entity(exception.getMessage()).build();
    }

}
</code>```

EDIT 2: I removed the JUnit test because I didnt test using Jersey Test Framework.
The problem here is that the ValidationExceptionMapper is not beeing called.

答:
Put "@Valid" in your, like this:

```<code>@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response insert(@Valid T obj) throws Exception{
...
}
</code>```

This works here.

Title: Jersey 2.13 + Bean Validation

Body:
I'm using gradle and the following libs:

ext.library['jersey'] = "org.glassfish.jersey:project:2.13"
ext.library['jersey_jettison'] = "org.glassfish.jersey.media:jersey-media-json-jettison:2.13"
ext.library['jersey_jackson'] = "org.glassfish.jersey.media:jersey-media-json-jackson1:2.13"
ext.library['jersey_spring'] = "org.glassfish.jersey.ext:jersey-spring3:2.13"
ext.library['jersey_bean_validation'] = "org.glassfish.jersey.ext:jersey-bean-validation:2.13"

I created the bean validation structure, but its not validating at all. No error messages, nothing. This is the structure I've created:

The DTO

public class MergeSchedulesDto {

@NotNull(message = "validation.invalid.mergeFrom")
private Long mergeFrom;

@NotNull(message = "validation.invalid.mergeTo")
@NotEmpty(message = "validation.invalid.mergeTo")
private List<Long> mergeTo;

The Service

@Path("merge")
@POST
@Consumes({ MediaType.APPLICATION_JSON })
public Response merge(@Valid MergeSchedulesDto dto, @QueryParam("units") List<Long> units) {

The config

public class ApplicationJAXRS extends Application {

    public ApplicationJAXRS() {
    }

    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> properties = new HashMap<>();
        properties
                .put("jersey.config.server.provider.packages",
                        "com.sifionsolution.sig.academic.resource.service,com.sifionsolution.sig.integration.resource.filter,com.sifionsolution.sig.academic.param.converter,com.sifionsolution.sig.datatables.resource.service,com.sifionsolution.sig.datatables.converter");

        return properties;
    }

    @Override
    public Set<Object> getSingletons() {
        Set<Object> singletons = new HashSet<>();

        singletons.add(new Jackson1Feature());
        singletons.add(new ValidationExceptionMapper());

        return singletons;
    }
}

EDIT I forgot the provider:

@Provider
public class ValidationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException exception) {
        return Response.status(BAD_REQUEST).entity(exception.getMessage()).build();
    }

}

EDIT 2: I removed the JUnit test because I didnt test using Jersey Test Framework.
The problem here is that the ValidationExceptionMapper is not beeing called.

Body:
Put "@Valid" in your, like this:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response insert(@Valid T obj) throws Exception{
...
}

This works here.


问:
Why Python `Memory Error` with list `append()` lots of RAM left
I am building a large data dictionary from a set of text files.  As I read in the lines and process them, I append(dataline) to a list.

At some point the append() generates a Memory Error exception.  However, watching the program run in the Windows Task Manager, at the point of the crash I see 4.3 GB available and 1.1 GB free.

Thus, I do not understand the reason for the exception.

Python version is 2.6.6.  I guess, the only reason is that it is not able to use more of the available RAM.  If this is so, is it possible to increase the allocation?

答:
If you're using a 32-bit build of Python, you might want to try a 64-bit version.

It is possible for a process to address at most 4GB of RAM using 32-bit addresses, but typically (depending on the OS), one gets much less. It sounds like your Python process may be hitting this limit. 64-bit addressing removes this limitation.

edit Since you're asking about Windows, the following page is of relevance: Memory Limits for Windows Releases. As you can see, the limit per 32-bit process is 2, 3 or 4GB depending on the OS version and configuration.


问:
Conflict between Google Analytics Embed API and Google Charts
There seems to be a conflict when I load Google Analytics Embed API and Google Charts on the same page, more specifically when I use Embed API to draw charts, too.

To make it more interesting, the problem only occurs when the charts are of different type, e.g. Embed API: TABLE and Charts: LINE

Embed API chart is loaded first and works as expected.
Charts LINE chart is loaded second and returns this error:

You called the draw() method with the wrong type of data rather than a DataTable or DataView

I have a feeling that Embed API charts override this function:

```<code>google.charts.load('current', {
    packages: ['corechart', 'line', 'table']
});
</code>```

UPDATE

Answer for this question: Google Charts draw() method wrong type when given DataTable suggests removing the reference to http://www.google.com/jsapi, but then Google Embed API charts stop working because window.google.load is no longer defined, instead there is window.google.charts.load which is needed for Google Charts but seems not to work work Embed API charts.

答:
I ran into the same problem and fixed the script loading conflicts.
The solution is to only include the newer chart loader.

Then, before loading the google charts api, run the extra code suggested by Daniel LaLiberte:

```<code>//Handles differences in load functions
google.load = google.load || google.charts.load;
google.setOnLoadCallback = google.setOnLoadCallback || google.charts.setOnLoadCallback;

//Loads the google analytics API
(function (w, d, s, g, js, fs) {
            //if ($('#googleCache').length > 0) return;
            g = w.gapi || (w.gapi = {});
            g.analytics = {
                q: [],
                ready: function (f) {
                    this.q.push(f);
                }
            };
            js = d.createElement(s);
            fs = d.getElementsByTagName(s)[0];
            js.src = 'https://apis.google.com/js/platform.js';
            js.id = "googleCache";
            fs.parentNode.insertBefore(js, fs);
            js.onload = function () {
                g.load('analytics');
            };
}(window, document, 'script'));

//Load the charts you want
google.charts.load('current', { packages: ['corechart', 'table', 'line', 'geochart'] });
</code>```

Body:
There seems to be a conflict when I load Google Analytics Embed API and Google Charts on the same page, more specifically when I use Embed API to draw charts, too.

To make it more interesting, the problem only occurs when the charts are of different type, e.g. Embed API: TABLE and Charts: LINE

Embed API chart is loaded first and works as expected.
Charts LINE chart is loaded second and returns this error:

You called the draw() method with the wrong type of data rather than a DataTable or DataView

I have a feeling that Embed API charts override this function:

google.charts.load('current', {
    packages: ['corechart', 'line', 'table']
});

UPDATE

Answer for this question: Google Charts draw() method wrong type when given DataTable suggests removing the reference to http://www.google.com/jsapi, but then Google Embed API charts stop working because window.google.load is no longer defined, instead there is window.google.charts.load which is needed for Google Charts but seems not to work work Embed API charts.

Body:
I ran into the same problem and fixed the script loading conflicts.
The solution is to only include the newer chart loader.

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

Then, before loading the google charts api, run the extra code suggested by Daniel LaLiberte:

//Handles differences in load functions
google.load = google.load || google.charts.load;
google.setOnLoadCallback = google.setOnLoadCallback || google.charts.setOnLoadCallback;

//Loads the google analytics API
(function (w, d, s, g, js, fs) {
            //if ($('#googleCache').length > 0) return;
            g = w.gapi || (w.gapi = {});
            g.analytics = {
                q: [],
                ready: function (f) {
                    this.q.push(f);
                }
            };
            js = d.createElement(s);
            fs = d.getElementsByTagName(s)[0];
            js.src = 'https://apis.google.com/js/platform.js';
            js.id = "googleCache";
            fs.parentNode.insertBefore(js, fs);
            js.onload = function () {
                g.load('analytics');
            };
}(window, document, 'script'));

//Load the charts you want
google.charts.load('current', { packages: ['corechart', 'table', 'line', 'geochart'] });