问:
How to store coordinates to act like a hexagon-esque structure?
I realize that many questions about pixels and hexagons have been asked, but I'm struggling to understand a certain aspect of it. Also, I'm not sure how much of a difference it'll make, but I am working in Java.

Starting off with my comprehension of the matter, I understand a Cartesian grid could be stored in a 2d array so that coordinates on the board are each an entry in the 2d array. But, I want to use a hexagonal sort of grid for a better game grid, like described on Amit's page http://www.redblobgames.com/grids/hexagons/.

I understand the concept after the hexagonal grid has been created (using x, y, z to get neighbors), but am struggling to store my coordinates. Previously, each coordinate had corresponded to an entry in the 2d array (cartesian). Now, I'm not sure how to make it correspond to get a hexagonal relationship between the coordinates.

Following the guide, I tried to offset the coordinates every other row (specifically trying the even row offset example from the link), like so:

In this, the top is the coordinates and the bottom is the visual representation of the array (blank spaces are entries with sentinels to 'skip' over, and 1s are the entries that correspond to the coordinates).

So, the neighbors of each coordinate are { {-1, 1}, {1, 1}, {1, -1}, {-1, -1}, {0, 2}, {0, -2} }. However, I don't think this is properly done? I thought of other ways to implement a hexagonal grid, which were to use a doubly linked list sort of structure and start off from the middle and relate the coordinates as 'nodes', or to hard code a map (which is sort of impossible because I plan for a large map). But, I'd rather stick with the offset idea because it's easier to use.

I think my problem is that each other row should be shifted by 1/2, but I give it 'holes' (sentinel entries). Maybe I'm supposed to convert coordinates to a hexagon using the geometry of hexagons. but I don't understand how I can use those individual hexagons when I want to path find unless they were stored in some data structure. Any code or help would be greatly appreciated.

答:
```<code>        0   1   2   3   4   5
      0   1   2   3   4   5
    0   1   2   3   4   5
  0   1   2   3   4   5
0   1   2   3   4   5
</code>```

If you don't mind your map having somewhat of a diamond shape, you can neatly fit a set of hexagons into a 2-d array.  The math will be consistent for travelling between nodes--

(E/W change x, NE/SW change y, NW/SE change both).

Basically, you're using the coordinate mapping as a reference.  You don't need to actually construct your map onto a two dimensional array.  Rather, you use the coordinate mapping to simplify your relationships.

For example, you could map coordinates into a hashmap like

```<code>map.put("0,2", new Tile(0,2,"Green"));
map.put("0,3", new Tile(0,3,"Yellow"));
map.put("0,4", new Tile(0,4,"Green"));
map.put("0,5", new Tile(0,5,"Green"));
map.put("1,2", new Tile(1,2,"Blue"));
map.put("1,3", new Tile(1,3,"Red"));
map.put("1,4", new Tile(1,4,"Orange"));
map.put("2,1", new Tile(2,1,"Orange"));
</code>```

For any given tile, you could answer whether any given direction is available, and retrieve the tile in that direction in O(1) time by referencing the HashMap.  Your nodes (e.g. Tile objects) wouldn't need any references to neighboring nodes.  Your coordinate system would take care of that.

Body:
        0   1   2   3   4   5
      0   1   2   3   4   5
    0   1   2   3   4   5
  0   1   2   3   4   5
0   1   2   3   4   5

If you don't mind your map having somewhat of a diamond shape, you can neatly fit a set of hexagons into a 2-d array.  The math will be consistent for travelling between nodes--

(E/W change x, NE/SW change y, NW/SE change both).

Basically, you're using the coordinate mapping as a reference.  You don't need to actually construct your map onto a two dimensional array.  Rather, you use the coordinate mapping to simplify your relationships.

For example, you could map coordinates into a hashmap like

map.put("0,2", new Tile(0,2,"Green"));
map.put("0,3", new Tile(0,3,"Yellow"));
map.put("0,4", new Tile(0,4,"Green"));
map.put("0,5", new Tile(0,5,"Green"));
map.put("1,2", new Tile(1,2,"Blue"));
map.put("1,3", new Tile(1,3,"Red"));
map.put("1,4", new Tile(1,4,"Orange"));
map.put("2,1", new Tile(2,1,"Orange"));

For any given tile, you could answer whether any given direction is available, and retrieve the tile in that direction in O(1) time by referencing the HashMap.  Your nodes (e.g. Tile objects) wouldn't need any references to neighboring nodes.  Your coordinate system would take care of that.


来源: stackexchange

问:
How can I enforce a minimum Bluetooth MTU for an Android app?
I'm working with a piece of hardware that sends and receives packets of data over particular BLE characteristics. Currently, each packet has to be an individual read or write.

When talking to the device from iOS, with the MTU negotiated up to 157 bytes, it's easy to observe this limitation. It's also easy to confirm that this MTU negotiation will work on the entire range of Apple devices the app needs to support. Without MTU negotiation, we would be limited to the default 23 byte ATT MTU, meaning we could only send and receive 20 byte packets (due to GATT overhead). The data format used for certain features will not fit in a 20 byte packet.

In the near future we'll be porting the app to Android and eventually releasing it for public consumption. I know that the Android API provides the requestMtu() method for attempting MTU negotiation, but if a user's Android device does not support an ATT MTU higher than the default 23 bytes, we'd like to be able to tell the user as soon as possible that the app will be unable to perform certain functions. Ideally, we'd like to stop the user from installing the app on such a device.

Is there a way to detect (directly or indirectly) the BLE MTU capabilities of an Android device without first requiring the user to connect to a BLE peripheral?

(Note: I've encountered a few anecdotes claiming that assorted Android devices only support the 23 byte default, but these mostly seem to come from developers who don't know about MTU negotiation. It's possible that all extant Android devices support higher MTUs. I don't know whether this is true.)

答:
Can you give an example of an Android device that does not support something higher than the default MTU?

What I have heard all Android devices should support a higher MTU than the default. The only problem is for 4.3 and 4.4 which does not have the requestMtu API, but then you can simply initiate the MTU change from the peripheral instead.

ContentLicense: CC BY-SA 3.0


问:
Setting up a staging environment with an external hosting site?
I've been working for a few years on a project for a friend of mine, and it has slowly grown into a large website. In the early stages, I just did development on my local machine with a local database, then deployed any site and database changes to the live site.

This worked well for a while, but lately we've been having issues with deployment. We'd like to set up a staging environment for testing before we deploy to the production environment.

The site I'm using for hosting doesn't offer a staging environment for the site, so I was wondering what I can do to get a staging environment set up. If my site is www.mysite.com, can I use staging.mysite.com, or do I need to purchase another domain?

I'm curious as to how other people handle this...

答:
Not sure this is an SO question but in case it is:

It would depend on the services offered by your web host, some offer sub-domains, for a price

You could also deploy to a sub-folder, eg www.mysite.com/staging

Purchase another (cheaper?) hosting plan, eg www.mystagingsite.com

If you don't need public access, just deploy to another local machine, either physical or virtual

ContentLicense: CC BY-SA 2.5


问:
Can not get pip3 on ubuntu Linux to install a library
I am trying to create a secure chat using secrets as an import but when I go to install this is all i get from it is

Collecting secrets
  Could not find a version that satisfies the requirement secrets (from versions: )
No matching distribution found for secrets
python 3 version 3.5.1-3
I am using this command to install it on Ubuntu 16.04.sudo pip3 install secretsany one have a clue? I know this library exists its in the python documentation https://docs.python.org/3/library/secrets.html

答:
Since i can't comment on this i'm creating an answer to try and help you.

Secrets seems to be a part of the Standard Library, which means there is no need to pip install it, it should already be importable.

Since this Library is new in Python 3.6 there is a need for you to have said Python version or else you won't be able to use it.

Check your Python version by typing the following into your console.

```<code>python -V
</code>```

Body:
Since i can't comment on this i'm creating an answer to try and help you.

Secrets seems to be a part of the Standard Library, which means there is no need to pip install it, it should already be importable.

Since this Library is new in Python 3.6 there is a need for you to have said Python version or else you won't be able to use it.

Check your Python version by typing the following into your console.

python -V


问:
Inplace versions of set_difference, set_intersection and set_union
I implemented versions of set_union, set_intersection and set_difference that take a sorted container and a sorted range (that must not be within the container), and write the result of the operation into the container.

```<code>template<class Container, class Iter>
void assign_difference(Container& cont, Iter first, Iter last)
{
    auto new_end = std::set_difference( // (1)
        cont.begin(), cont.end(), first, last, cont.begin());
    cont.erase(new_end, cont.end());
}

template<class Container, class Iter>
void assign_intersection(Container& cont, Iter first, Iter last)
{
    auto new_end = std::set_intersection( // (2)
        cont.begin(), cont.end(), first, last, cont.begin());
    cont.erase(new_end, cont.end());
}

template<class Container, class Iter>
void assign_union(Container& cont, Iter first, Iter last)
{
    auto insert_count = last - first;
    cont.resize(cont.size() + insert_count); // T must be default-constructible
    auto rfirst1 = cont.rbegin() + insert_count, rlast1 = cont.rend();
    auto rfirst2 = std::make_reverse_iterator(last);
    auto rlast2 = std::make_reverse_iterator(first);
    rlast1 = std::set_union( // (3)
        rfirst1, rlast1, rfirst2, rlast2, cont.rbegin(), std::greater<>());
    cont.erase(std::copy(rlast1.base(), cont.end(), cont.begin()), cont.end());
}
</code>```

The goal was:

No allocation is performed if the container has enaugh capacity to hold the result.

Otherwise exactly one allocation is performed to give the container the capacity to hold the result.

As you can see in the lines marked (1), (2) and (3), the same container is used as input and output for those STL algorithms. Assuming a usual implementation of those STL algorithms, this code works, since it only writes to parts of the container that have already been processed.

As pointed out in the comments, it's not guaranteed by the standard that this works. set_union, set_intersection and set_difference require that the resulting range doesn't overlap with one of the input ranges.
However, can there be a STL implementation that breaks the code?

If your answer is yes, please provide a conforming implementations of one of the three used STL algorithms that breaks the code.

答:
As rule of thumb I use do not write on a container on which you are iterating. Everything can happen. In general it's odd.

As @Yakk said, it sounds ill. That's it. Something to be removed from your code base an sleep peacefully.

If you really need those functions, I would suggest to write by yourself the inner loop (eg: the inner of std::set_intersection) in order to handle the constraint you need for your algorithm to work.

I don't think that seeking for an STL implementation on which it doesn't work is the right approach. It doesn't sound like a long term solution. For the long term: the standard should be your reference, and as someone already pointed out, your solution doesn't seems to properly deal with it.

My 2 cents

Body:
I implemented versions of set_union, set_intersection and set_difference that take a sorted container and a sorted range (that must not be within the container), and write the result of the operation into the container.

template<class Container, class Iter>
void assign_difference(Container& cont, Iter first, Iter last)
{
    auto new_end = std::set_difference( // (1)
        cont.begin(), cont.end(), first, last, cont.begin());
    cont.erase(new_end, cont.end());
}

template<class Container, class Iter>
void assign_intersection(Container& cont, Iter first, Iter last)
{
    auto new_end = std::set_intersection( // (2)
        cont.begin(), cont.end(), first, last, cont.begin());
    cont.erase(new_end, cont.end());
}

template<class Container, class Iter>
void assign_union(Container& cont, Iter first, Iter last)
{
    auto insert_count = last - first;
    cont.resize(cont.size() + insert_count); // T must be default-constructible
    auto rfirst1 = cont.rbegin() + insert_count, rlast1 = cont.rend();
    auto rfirst2 = std::make_reverse_iterator(last);
    auto rlast2 = std::make_reverse_iterator(first);
    rlast1 = std::set_union( // (3)
        rfirst1, rlast1, rfirst2, rlast2, cont.rbegin(), std::greater<>());
    cont.erase(std::copy(rlast1.base(), cont.end(), cont.begin()), cont.end());
}

The goal was:

No allocation is performed if the container has enaugh capacity to hold the result.

Otherwise exactly one allocation is performed to give the container the capacity to hold the result.

As you can see in the lines marked (1), (2) and (3), the same container is used as input and output for those STL algorithms. Assuming a usual implementation of those STL algorithms, this code works, since it only writes to parts of the container that have already been processed.

As pointed out in the comments, it's not guaranteed by the standard that this works. set_union, set_intersection and set_difference require that the resulting range doesn't overlap with one of the input ranges.
However, can there be a STL implementation that breaks the code?

If your answer is yes, please provide a conforming implementations of one of the three used STL algorithms that breaks the code.


问:
Moving many files in the same bucket
I've got 200k files in a bucket which I need to move into a sub folder within the same bucket, whats the best approach?</p>

答:
I had this same problem and I ended up using aws s3 mv along with a bash for loop.

I did aws ls bucket_name to get all of the files in the bucket. Then I decided which files I wanted to move and added them to file_names.txt.

Then I ran the following snippet to move all of the files:

```<code>for f in $(cat file_names.txt)
do
    aws s3 mv s3://bucket-name/$f s3://bucket-name/subfolder/$f
done
</code>```

Title: Moving many files in the same bucket

Body:
I had this same problem and I ended up using aws s3 mv along with a bash for loop.

I did aws ls bucket_name to get all of the files in the bucket. Then I decided which files I wanted to move and added them to file_names.txt.

Then I ran the following snippet to move all of the files:

for f in $(cat file_names.txt)
do
    aws s3 mv s3://bucket-name/$f s3://bucket-name/subfolder/$f
done


问:
concat overlapping data with pandas
I'm working on merging 2 data frames together that are all structured in the same fashion:

df1:

```<code>DATE   TANK#1 TANK#2 TANK#3 TANK#4 ... TANK#100
9/22   10     30     22     13         62
10/19  5      29     17     13         51
</code>```

df2:

```<code>DATE   TANK#3 TANK#4 TANK#5 TANK#6 ... TANK#120
11/17  10     30     22     13         62
11/29  5      29     17     13         51
</code>```

df1 has the date range 9/22/16 - 10/19/16

df2 has the date range 10/24/17 - 05/28/17

I would like to concat these DataFrames together so all of the dates are in one DataFrame. However, the column headers/tanks are not all the same for each data frame. It is mostly overlap, but some tanks exist in one and not in the other.

I tried

```<code>result = df1.append(df2)
</code>```

But receive the error: Plan shapes are not aligned

What is the best way to merge data shaped like this?

答:
Set 'DATE' as index and combine df1 and df2 using combine_first.</p>

```<code>df1.set_index('DATE').combine_first(df2.set_index('DATE')).reset_index()
</code>```

Title: concat overlapping data with pandas

Body:
I'm working on merging 2 data frames together that are all structured in the same fashion:

df1:

DATE   TANK#1 TANK#2 TANK#3 TANK#4 ... TANK#100
9/22   10     30     22     13         62
10/19  5      29     17     13         51

df2:

DATE   TANK#3 TANK#4 TANK#5 TANK#6 ... TANK#120
11/17  10     30     22     13         62
11/29  5      29     17     13         51

df1 has the date range 9/22/16 - 10/19/16

df2 has the date range 10/24/17 - 05/28/17

I would like to concat these DataFrames together so all of the dates are in one DataFrame. However, the column headers/tanks are not all the same for each data frame. It is mostly overlap, but some tanks exist in one and not in the other.

I tried

result = df1.append(df2)

But receive the error: Plan shapes are not aligned

What is the best way to merge data shaped like this?

Body:
Set 'DATE' as index and combine df1 and df2 using combine_first.

df1.set_index('DATE').combine_first(df2.set_index('DATE')).reset_index()


问:
Log out user by admin Spring Security
I'd like your help to get how implement this function:
admin gets all logged in users using sessionRegistry.getAllPrincipals() and then can log off someone.
I know how to log off current user (session.invalidate()), but have no idea how to force log out other users.

This code gets me all logged in users

```<code>public List<User> getAllLoggedInUsers() {
    List<Object> principals = sessionRegistry.getAllPrincipals();
    List<User> usersNamesList = new ArrayList<>();
    for (Object principal : principals) {
        if (principal instanceof org.springframework.security.core.userdetails.User) {
            usersNamesList.add(dao.findByLogin(((org.springframework.security.core.userdetails.User) principal).getUsername()));
        }
    }
    return usersNamesList;
}
</code>```

Thanks a lot.

EDIT 1: I want next: admin chooses a user, bans it (change info in DB) and then if this user is active - log him off.

答:
suppose you try like this.

```<code>public void logoutUser(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
        Authentication auth = getAuthentication();

    for (int i = 0; i < logoutHandler.length; i++) {
        logoutHandler[i].logout(httpRequest, httpResponse, auth);
    }

        AnonymousAuthenticationToken aat = new AnonymousAuthenticationToken("your key you use",
                "anonymousUser", new GrantedAuthority[]{
                new GrantedAuthorityImpl("ROLE_ANONYMOUS")});
        ((SecurityContext)SecurityContextHolder.getContext()).setAuthentication(aat);
    }
</code>```

Also you can find more approaches in following post1 and post2.

you can also get the current logged users and setSecurityContextHolder.getContext().setAuthentication(null)

Title: Log out user by admin Spring Security

Body:
I'd like your help to get how implement this function:
admin gets all logged in users using sessionRegistry.getAllPrincipals() and then can log off someone.
I know how to log off current user (session.invalidate()), but have no idea how to force log out other users.

This code gets me all logged in users

public List<User> getAllLoggedInUsers() {
    List<Object> principals = sessionRegistry.getAllPrincipals();
    List<User> usersNamesList = new ArrayList<>();
    for (Object principal : principals) {
        if (principal instanceof org.springframework.security.core.userdetails.User) {
            usersNamesList.add(dao.findByLogin(((org.springframework.security.core.userdetails.User) principal).getUsername()));
        }
    }
    return usersNamesList;
}

Thanks a lot.

EDIT 1: I want next: admin chooses a user, bans it (change info in DB) and then if this user is active - log him off.

Body:
suppose you try like this.

public void logoutUser(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
        Authentication auth = getAuthentication();

    for (int i = 0; i < logoutHandler.length; i++) {
        logoutHandler[i].logout(httpRequest, httpResponse, auth);
    }

        AnonymousAuthenticationToken aat = new AnonymousAuthenticationToken("your key you use",
                "anonymousUser", new GrantedAuthority[]{
                new GrantedAuthorityImpl("ROLE_ANONYMOUS")});
        ((SecurityContext)SecurityContextHolder.getContext()).setAuthentication(aat);
    }

Also you can find more approaches in following post1 and post2.

you can also get the current logged users and setSecurityContextHolder.getContext().setAuthentication(null)


问:
Issue with .prop("checked", true)?
I have the following:

```<code>116   $.each(data.entries, function(id, item) {
117       console.log($("input[type=checkbox][value=" + item + "]").is(":checked"));
118       $("input[type=checkbox][value=" + item + "]").prop("checked", true);
119       console.log($("input[type=checkbox][value=" + item + "]").is(":checked"));
120   })
</code>```

For the life of me I can't get my checkbox to check:

```<code>swot-nav.js:117 false
swot-nav.js:119 false
</code>```

This doesn't work either:

```<code>116    $.each(data.entries, function(id, item) {
117        console.log($(":checkbox[value=" + item + "]").is(":checked"));
118        $(":checkbox[value=" + item + "]").prop("checked", "true");
119        console.log($(":checkbox[value=" + item + "]").is(":checked"));
120    })
</code>```

(same result)

What could I be missing?

Edit:

This is taking place in the success function of an Ajax Call.

This is what the data looks like:

data = {'label': 'D1- DC Test 1', 'details': '', 'type': 'D', 'entries': [20, 21, 22]

Here's a fiddle where it's working: https://jsfiddle.net/e3arwp7q/

There must be something wrong deeper in my code. If this looks to everyone like it is supposed to work, then maybe I should look elsewhere.

答: The  problem is that you are passing the wrong argument to the is method. Use .is(':checked') instead.

Title: Issue with .prop("checked", true)?

Body:
I have the following:

116   $.each(data.entries, function(id, item) {
117       console.log($("input[type=checkbox][value=" + item + "]").is(":checked"));
118       $("input[type=checkbox][value=" + item + "]").prop("checked", true);
119       console.log($("input[type=checkbox][value=" + item + "]").is(":checked"));
120   })

For the life of me I can't get my checkbox to check:

swot-nav.js:117 false
swot-nav.js:119 false

This doesn't work either:

116    $.each(data.entries, function(id, item) {
117        console.log($(":checkbox[value=" + item + "]").is(":checked"));
118        $(":checkbox[value=" + item + "]").prop("checked", "true");
119        console.log($(":checkbox[value=" + item + "]").is(":checked"));
120    })

(same result)

What could I be missing?

Edit:

This is taking place in the success function of an Ajax Call.

This is what the data looks like:

data = {'label': 'D1- DC Test 1', 'details': '', 'type': 'D', 'entries': [20, 21, 22]

Here's a fiddle where it's working: https://jsfiddle.net/e3arwp7q/

There must be something wrong deeper in my code. If this looks to everyone like it is supposed to work, then maybe I should look elsewhere.


问:
Configure SSL on Camel rest-component using Spring-Boot with embedded Jetty
Been bashing my head in for a few days trying to get SSL working with an existing rest endpoint. Currently using self-signed certificates in a jks.

We have a rest route (not this route, but very similar):

```<code>@Override
public void configure() {

    restConfiguration()
            .component("jetty")
            .scheme("https")
            .bindingMode(RestBindingMode.off)
            .dataFormatProperty("prettyPrint", "true")
            .port(8443);

    rest("/post")
            .post()
            .consumes("application/json")
            .produces("application/json")
            .to( // next endpoint // );
</code>```

This works perfectly over HTTP. When we set the scheme as HTTPS, Jetty throws a SSL cypher mismatch error when a request is sent to it; I'd imagine this is because no SSL configuration is being picked up.

I've tried some of the examples on the internet (such as configuring Jetty from the application.properties), but that doesn't actually seem to do anything at all.

Any help appreciated, all of the routes in the project are written using the Camel Java DSL, not the XML equivalent.

答:
This has since been fixed. We discovered that the correct method of doing this was by configuring the embedded Jetty itself, rather than modifying the camel route.
This was achievable by instantiating a JettyHttpComponent, and setting the SSLContextParameters on it. </p>

Body:
Been bashing my head in for a few days trying to get SSL working with an existing rest endpoint. Currently using self-signed certificates in a jks.

We have a rest route (not this route, but very similar):

@Override
public void configure() {

    restConfiguration()
            .component("jetty")
            .scheme("https")
            .bindingMode(RestBindingMode.off)
            .dataFormatProperty("prettyPrint", "true")
            .port(8443);

    rest("/post")
            .post()
            .consumes("application/json")
            .produces("application/json")
            .to( // next endpoint // );

This works perfectly over HTTP. When we set the scheme as HTTPS, Jetty throws a SSL cypher mismatch error when a request is sent to it; I'd imagine this is because no SSL configuration is being picked up.

I've tried some of the examples on the internet (such as configuring Jetty from the application.properties), but that doesn't actually seem to do anything at all.

Any help appreciated, all of the routes in the project are written using the Camel Java DSL, not the XML equivalent.


问:
custom input file in bootstrap 4 not show button
When I use Custom input file in bootstrap 4, don't change my input and don't show browse button.

file-browser

```<code><label class="custom-file">
    <input type="file" id="Image" class="custom-file-input">
    <span class="custom-file-control"></span>
</label>
</code>```

.custom-file

```<code>position: relative;
display: inline-block;
max-width: 100%;
height: 2.5rem;
cursor: pointer;
</code>```

.custom-file-input

```<code>min-width: 14rem;
max-width: 100%;
margin: 0;
filter: alpha(opacity=0);
opacity: 0;
</code>```

.custom-file-control

```<code>position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 5;
height: 2.5rem;
padding: .5rem 1rem;
line-height: 1.5;
color: #555;
user-select: none;
background-color: #fff;
border: 1px solid #ddd;
border-radius: .25rem;
</code>```

答:
The documentation states that you should set the language of the document. For example, setting just:

```<code><html lang="en">
</code>```

was enough to get it working, unless like in @masud_moni answer, you have specified another language then use that instead of "en".

Body:
When I use Custom input file in bootstrap 4, don't change my input and don't show browse button.

file-browser

    <input type="file" id="Image" class="custom-file-input">

.custom-file

position: relative;
display: inline-block;
max-width: 100%;
height: 2.5rem;
cursor: pointer;

.custom-file-input

min-width: 14rem;
max-width: 100%;
margin: 0;
filter: alpha(opacity=0);
opacity: 0;

.custom-file-control

position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 5;
height: 2.5rem;
padding: .5rem 1rem;
line-height: 1.5;
color: #555;
user-select: none;
background-color: #fff;
border: 1px solid #ddd;
border-radius: .25rem;

Body:
The documentation states that you should set the language of the document. For example, setting just:

<html lang="en">

was enough to get it working, unless like in @masud_moni answer, you have specified another language then use that instead of "en".


问:
Problems with MSF4J and @MatrixParam
Folks, I have found what seems to be a problem with / (bug in ?) MSF4J as including an @MatrixParam annotated variable in a URI causes the affected (micro)service to either 'hang' indefinitely, or if accessed via a browser, to give a "404 Not Found" message for the path/endpoint, even when correct.

Here is a code fragment that illustrates the problem - it compiles ok (eclipse/maven) and deploys without errors using microservicesrunner() in the usual way.

```<code>package org.test.service;

import javax.ws.rs.GET;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("books")

public class MPTest {   // MatrixParam Test

   @GET
   @Produces(MediaType.TEXT_PLAIN)
   @Path("/query")

   // method to respond to 'GET' requests
   public Response getListOfBooks(@MatrixParam("Author") String author) {

   // do something in here to get book data from DB and sort by titles
   List<String> titles = .......;

   return Response.status(200) .entity("List of Books by " +author+ "ordered by title " + titles).build();
   }
}
</code>```

With this code fragment, accessing the URL "(host:8080)/books/query;Author=MickeyMouse" should cause a list of books by that author to be retrieved from the DB (I have omitted the actual code that does so for clarity, as it is not relevant to this post).

However, it does not get there, so that code isnt executed. As far as I can tell with a debugger, no @MatricParam value is retrieved - it remains null until the process times out. Things like curl and wget just hang until they time out, and from a browser, the best I can get is a 404 not found error for the URI, even though it is valid.

However, if I replace the @MatrixParam with a @PathParam it works perfectly, and can I get the URL string retrieved in its entirity. The URI that I get is as expected - no odd hex characters, no typos, and so forth. The URI entered is what you get back. So, no problem there.

Behaviour is also consistent across platforms (couple of flavours of Linux, and three versions of Windoze), so it is not anything to do with the OS itself. Similarly, I get the same behavior with multiple clients and tools, so it isnt a problem there either.

So, it appears to be a problem within the MSF4J framework / domain, and I could use some support / help / suggestions here as I've reached the point of tearing my hair out.....  Any ideas, folks?

The only reference I can find to a similar problem was closed as 'off topic' without a reply (see Rest API Matrix param annotation) so I think that this needs re-opening as it seems to be a genuine problem....

Regards, and thanks in advance for any help,
Rick

答: @MatrixParam is not supported with MSF4J at the moment. You can create a GitHub issue. So we can implement that support in future releases.

Title: Problems with MSF4J and @MatrixParam

Body:
Folks, I have found what seems to be a problem with / (bug in ?) MSF4J as including an @MatrixParam annotated variable in a URI causes the affected (micro)service to either 'hang' indefinitely, or if accessed via a browser, to give a "404 Not Found" message for the path/endpoint, even when correct.

Here is a code fragment that illustrates the problem - it compiles ok (eclipse/maven) and deploys without errors using microservicesrunner() in the usual way.

package org.test.service;

import javax.ws.rs.GET;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("books")

public class MPTest {   // MatrixParam Test

   @GET
   @Produces(MediaType.TEXT_PLAIN)
   @Path("/query")

   // method to respond to 'GET' requests
   public Response getListOfBooks(@MatrixParam("Author") String author) {

   // do something in here to get book data from DB and sort by titles
   List<String> titles = .......;

   return Response.status(200) .entity("List of Books by " +author+ "ordered by title " + titles).build();
   }
}

With this code fragment, accessing the URL "(host:8080)/books/query;Author=MickeyMouse" should cause a list of books by that author to be retrieved from the DB (I have omitted the actual code that does so for clarity, as it is not relevant to this post).

However, it does not get there, so that code isnt executed. As far as I can tell with a debugger, no @MatricParam value is retrieved - it remains null until the process times out. Things like curl and wget just hang until they time out, and from a browser, the best I can get is a 404 not found error for the URI, even though it is valid.

However, if I replace the @MatrixParam with a @PathParam it works perfectly, and can I get the URL string retrieved in its entirity. The URI that I get is as expected - no odd hex characters, no typos, and so forth. The URI entered is what you get back. So, no problem there.

Behaviour is also consistent across platforms (couple of flavours of Linux, and three versions of Windoze), so it is not anything to do with the OS itself. Similarly, I get the same behavior with multiple clients and tools, so it isnt a problem there either.

So, it appears to be a problem within the MSF4J framework / domain, and I could use some support / help / suggestions here as I've reached the point of tearing my hair out.....  Any ideas, folks?

The only reference I can find to a similar problem was closed as 'off topic' without a reply (see Rest API Matrix param annotation) so I think that this needs re-opening as it seems to be a genuine problem....

Regards, and thanks in advance for any help,
Rick


问:
Ignore Null values from the database ConsoleTvs Charts
So I have a set of data that needs to be displayed on the admin dashboard.
I decided to use laravel charting package ConsoleTvs Charts by Erik Campobadal.

I am using the package above to create charts directly from the database, the issue is, within my table (user's table for example) there are columns with NULL value.

How do I ignore this null values and represent only columns with real values on my chart?

```<code>`
 $chart_print_media = Charts::database(User::all(), 'pie', 'highcharts')
                ->title('Print Media Campaign')
                ->dimensions(450, 300)
                ->groupBy('print_media',null);`
</code>```

答:
Thanks to Eric Campobadal, am just going to post the answer here for anyone that this might help in the future.

`

```<code>$users_print = User::all()->filter(function ($user) {
                return $user->print_media !== null;
            });

            $chart_print_media = Charts::database($users_print, 'pie', 'highcharts')
                ->title('Print Media Campaign')
                ->dimensions(450, 300)
                ->groupBy('print_media');
</code>```

`

I believe this is self-explanatory enough

Body:
So I have a set of data that needs to be displayed on the admin dashboard.
I decided to use laravel charting package ConsoleTvs Charts by Erik Campobadal.

I am using the package above to create charts directly from the database, the issue is, within my table (user's table for example) there are columns with NULL value.

How do I ignore this null values and represent only columns with real values on my chart?

`
 $chart_print_media = Charts::database(User::all(), 'pie', 'highcharts')
                ->title('Print Media Campaign')
                ->dimensions(450, 300)
                ->groupBy('print_media',null);`

Body:
Thanks to Eric Campobadal, am just going to post the answer here for anyone that this might help in the future.

`

$users_print = User::all()->filter(function ($user) {
                return $user->print_media !== null;
            });

            $chart_print_media = Charts::database($users_print, 'pie', 'highcharts')
                ->title('Print Media Campaign')
                ->dimensions(450, 300)
                ->groupBy('print_media');

`

I believe this is self-explanatory enough


问:
Pc going unresponsive when looping over a 10^8 elements in an array
When I execute python code which loops over an array of size 10^8. The pc becomes unresponsive and takes around 10 minutes to execute the code.
After it is done with the script, it stays laggy for a while.

So is that a problem due to a weak processor or is it a Ram problem, and is the only way to fix it, is to upgrade the ram?

The script could be as simple as:

```<code>arr = [x for x in range(pow(10,8))]
for i in range( len(arr) ):
   arr[i]+=1
</code>```

My Specs are:
RAM is 8 GB.
OS is Ubuntu.
Python 3.6.
Processor: Intel Core i7-3632QM 2.20GHZ

More details on what exactly happens: when I run the script I can see the memory usage for the python process keeps getting up. Then the PC becomes unresponsive. It doesn't respond to any action I give. If anything was playing in the background it stops, If i move the mouse, the cursor won't move. Until the script is actually done. Then it becomes responsive but very laggy for a while. if I try to switch the active application to another minimized application it takes quiet some time. As if the PC was just booted up. It takes a bit of time for everything to get back to normal.

答:
The short answer is, your application becomes unresponsive because you've totally saturated your CPU with billions of operations being performed on a large dataset. While your program is stuck in those loops it can't do anything else and appears to lock up.

First, you're creating 100 million items using range(). This operation alone isn't going to be very fast because that's a lot of items.

Next, you're looping over those 100 million items with a list comprehension and building an entirely new list. The comprehension seems pointless since you're just passing the value from range right through, but perhaps you're just simplifying it for the example.

Finally, you're using a for loop to once again loop over all those items in the newly generated list from the comprehension.

That's 3 loops and 3 lists; One for the range(), another for the list comprehension and the third is the for loop. You're doing a lot of work creating huge lists multiple times.

The process of appending items to a list takes several operations and at 100 million items, that's 100Mhz * number-of-operations. For example, if it took 10 operations you're looking at about 1Ghz worth of processing time. These aren't real benchmarks, but they illustrate how doing a lot of little operations like this can quickly add up to a lot of CPU time. Not only that but copying at-minimum 100MB of data around in memory several times is going to take additional time as well. All of this leads to a lack of responsiveness because your CPU is totally saturated.

If you absolutely need to pre-build such a huge list, then make sure you only loop over it once and do all the work you need to do on that item at that time. That'll cut down on the number of times you recreate the list and save on memory since fewer lists will need to be stored in memory at the same time.

If all you really need is an incrementing number, you can use a generator to count up. Generators are far more efficient since they are "lazy"; They only "yield" a single value at a time, rather than returning a whole list at once
. In Python 2, xrange() is a range generator that works exactly like range except that it yields a single value at a time, rather than creating a whole list at once and returning that.

```<code>for i in xrange(pow(10,8)):
    # do some work with the current value of i
</code>```

In Python 3, there is no xrange() since the range() function returns a generator by default (technically it's range type, but it acts generally the same way).

Here's an explanation of the difference between range() and xrange()

http://pythoncentral.io/how-to-use-pythons-xrange-and-range/

Lastly, if you really need to use huge lists like this, the Numpy library has all sorts of optimizations for "sparse lists" which act like regular lists but do some clever tricks to store seemingly millions of items efficiently.

Body:
When I execute python code which loops over an array of size 10^8. The pc becomes unresponsive and takes around 10 minutes to execute the code.
After it is done with the script, it stays laggy for a while.

So is that a problem due to a weak processor or is it a Ram problem, and is the only way to fix it, is to upgrade the ram?

The script could be as simple as:

arr = [x for x in range(pow(10,8))]
for i in range( len(arr) ):
   arr[i]+=1

My Specs are:
RAM is 8 GB.
OS is Ubuntu.
Python 3.6.
Processor: Intel Core i7-3632QM 2.20GHZ

More details on what exactly happens: when I run the script I can see the memory usage for the python process keeps getting up. Then the PC becomes unresponsive. It doesn't respond to any action I give. If anything was playing in the background it stops, If i move the mouse, the cursor won't move. Until the script is actually done. Then it becomes responsive but very laggy for a while. if I try to switch the active application to another minimized application it takes quiet some time. As if the PC was just booted up. It takes a bit of time for everything to get back to normal.

Body:
The short answer is, your application becomes unresponsive because you've totally saturated your CPU with billions of operations being performed on a large dataset. While your program is stuck in those loops it can't do anything else and appears to lock up.

First, you're creating 100 million items using range(). This operation alone isn't going to be very fast because that's a lot of items.

Next, you're looping over those 100 million items with a list comprehension and building an entirely new list. The comprehension seems pointless since you're just passing the value from range right through, but perhaps you're just simplifying it for the example.

Finally, you're using a for loop to once again loop over all those items in the newly generated list from the comprehension.

That's 3 loops and 3 lists; One for the range(), another for the list comprehension and the third is the for loop. You're doing a lot of work creating huge lists multiple times.

The process of appending items to a list takes several operations and at 100 million items, that's 100Mhz * number-of-operations. For example, if it took 10 operations you're looking at about 1Ghz worth of processing time. These aren't real benchmarks, but they illustrate how doing a lot of little operations like this can quickly add up to a lot of CPU time. Not only that but copying at-minimum 100MB of data around in memory several times is going to take additional time as well. All of this leads to a lack of responsiveness because your CPU is totally saturated.

If you absolutely need to pre-build such a huge list, then make sure you only loop over it once and do all the work you need to do on that item at that time. That'll cut down on the number of times you recreate the list and save on memory since fewer lists will need to be stored in memory at the same time.

If all you really need is an incrementing number, you can use a generator to count up. Generators are far more efficient since they are "lazy"; They only "yield" a single value at a time, rather than returning a whole list at once
. In Python 2, xrange() is a range generator that works exactly like range except that it yields a single value at a time, rather than creating a whole list at once and returning that.

for i in xrange(pow(10,8)):
    # do some work with the current value of i

In Python 3, there is no xrange() since the range() function returns a generator by default (technically it's range type, but it acts generally the same way).

Here's an explanation of the difference between range() and xrange()

http://pythoncentral.io/how-to-use-pythons-xrange-and-range/

Lastly, if you really need to use huge lists like this, the Numpy library has all sorts of optimizations for "sparse lists" which act like regular lists but do some clever tricks to store seemingly millions of items efficiently.


问:
How to kill background process from system function call
How can I kill a background process that was executed using a system function call in C language. Like for example I have a compiled application call "fooprocess". Then I want to write a program that will execute the fooprocess application in the background using the system function, please kindly see below the code,

```<code>const char app[] = "fooprocess &";
system(app);
</code>```

As you can see there is a "&" character so that I can run the fooprocess application in the background. How can I kill this fooprocess?

Many thanks.

答: To interact with the process you need its PID. I'm not sure if it's possible with system but one alternative is to fork the process yourself using fork + exec.

Body:
How can I kill a background process that was executed using a system function call in C language. Like for example I have a compiled application call "fooprocess". Then I want to write a program that will execute the fooprocess application in the background using the system function, please kindly see below the code,

const char app[] = "fooprocess &";
system(app);

As you can see there is a "&" character so that I can run the fooprocess application in the background. How can I kill this fooprocess?

Many thanks.


问:
Issues with In-app-billing on React Native
I'm implementing In-app-billing on my React Native project using this.
https://github.com/idehub/react-native-billing

This is the code I'm using.

```<code>InAppBilling.open()
.then(() => InAppBilling.purchase('android.test.purchased'))
.then((details) => {
  console.log("You purchased: ", details)
  return InAppBilling.close()
});
</code>```

and I got this error.

Can anyone help me with the solution? Thanks in advance.

答:
Did you try to uninstall and install app after install the library?
If you just reload the app with the node files will not work. You need to unsinstall and reinstall the app to get the Inappbilling in your application.</p>

Body:
I'm implementing In-app-billing on my React Native project using this.
https://github.com/idehub/react-native-billing

This is the code I'm using.

InAppBilling.open()
.then(() => InAppBilling.purchase('android.test.purchased'))
.then((details) => {
  console.log("You purchased: ", details)
  return InAppBilling.close()
});

and I got this error.

Can anyone help me with the solution? Thanks in advance.


问:
MIPS error - find a maximum in an array
I want to write a program which finds the maximum value in an array.
When I try to start my programm I get the error "Exception occurred at PC=0x0040004c". I have no idea what this means and I have no idea whats wrong with my code.</p>

```<code> .data
 liste: .word 1, 2 ,3 ,41, 5, 6, 7

.text
main:
    la $a0 liste        #adresse des ersten Elements in $a0 gespeichert
    la $a1 28($a0)      #adresse des letzten Elements in $a1 gespeichert
    li $v0 0            #speichere 0 in v0

tester:
    beq $a0 $a1 exit    #test, if we are at the end of the array
    j findmax

findmax:
    la $t0 ($a0)        #copy a0 in t0
speichermax:
    la $v0 ($t0)        #adress of t0 (Maximum) in v0
    lw $v1 ($v0)        #value of the max in v1

loop:
    la $t0 4($t0)       #go to the next field content
    beq $v0 $a1 exit    #end of field is reached
    lw $t1 ($t0)

    sub $t1 $t1 $v1         # t1 = t1 - v1
    bgtz $t1 speichermax
    #bgt $t1 $v1 speichermax    #test if t1>v1 -> yes: save the new max  in v1 (über speichermax)
    j loop

exit:
    lw $a0 ($t0) #print the maximum
    li $v0 1
    syscall

    li $v0 10 #exit
    syscall
</code>```

答:
Skipping the rest of the program I believe that this: la $a1, 28($a0)
 is wrong. Try this: addi $s1, $a0, 28.

Title: MIPS error - find a maximum in an array

Body:
I want to write a program which finds the maximum value in an array.
When I try to start my programm I get the error "Exception occurred at PC=0x0040004c". I have no idea what this means and I have no idea whats wrong with my code.

 .data
 liste: .word 1, 2 ,3 ,41, 5, 6, 7

.text
main:
    la $a0 liste        #adresse des ersten Elements in $a0 gespeichert
    la $a1 28($a0)      #adresse des letzten Elements in $a1 gespeichert
    li $v0 0            #speichere 0 in v0

tester:
    beq $a0 $a1 exit    #test, if we are at the end of the array
    j findmax

findmax:
    la $t0 ($a0)        #copy a0 in t0
speichermax:
    la $v0 ($t0)        #adress of t0 (Maximum) in v0
    lw $v1 ($v0)        #value of the max in v1

loop:
    la $t0 4($t0)       #go to the next field content
    beq $v0 $a1 exit    #end of field is reached
    lw $t1 ($t0)

    sub $t1 $t1 $v1         # t1 = t1 - v1
    bgtz $t1 speichermax
    #bgt $t1 $v1 speichermax    #test if t1>v1 -> yes: save the new max  in v1 (über speichermax)
    j loop

exit:
    lw $a0 ($t0) #print the maximum
    li $v0 1
    syscall

    li $v0 10 #exit
    syscall


问:
Can't import TableComponentJS in TypeScript
im working on a project and i have a problem. Im using Angular2, typescript, webpack 2.2 and im trying to use this table component:
pyrite table

The problem starts when i try to import this component in my component. I installed it with npm and thats work. But when i try to import it i use: import * as Table from "pyrite-table";

And then i try to use Table.load but i get an error: index.js:38 Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

And that line is this:

```<code>export default module.exports = window.pyrite.Table = Table;
</code>```

So my question is, how can i import this component in my project that is using typescript.

答:
I saw in the project repo's readme the following loc:

```<code>import Table from 'pyrite-table';
</code>```

Have you tried this one? Or:

```<code>import { Table } from 'pyrite-table';
</code>```

Body:
im working on a project and i have a problem. Im using Angular2, typescript, webpack 2.2 and im trying to use this table component:
pyrite table

The problem starts when i try to import this component in my component. I installed it with npm and thats work. But when i try to import it i use: import * as Table from "pyrite-table";

And then i try to use Table.load but i get an error: index.js:38 Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

And that line is this:

export default module.exports = window.pyrite.Table = Table;

So my question is, how can i import this component in my project that is using typescript.

Body:
I saw in the project repo's readme the following loc:

import Table from 'pyrite-table';

Have you tried this one? Or:

import { Table } from 'pyrite-table';


问:
Finding a substring that is comprised of both letters and numbers in excel
I'm currently dealing with a mess of a data set that needs analysis. It was uploaded from a legacy database that just concatenated all the fields together, but different fields were empty for different data points, so there is no easy way to split them.

I have determined that I can extract useful information out of it if I can split the string on the first occurrence of a word containing both letters and numbers (eg. abc123). Unfortunately, I'm unable to use a macro enabled workbook for this, so no VBA or regex to make it easy.

Is there anyway to determine if a string or substring has a combination of letters and numbers?

Example data:

2283-332-44543 CAP DDT@ PPL445 HEEN PAX 77820

44372-33-3223 TYYTE CAP BOX 1550 244 BOX PPSSA223 PAX

PRECISE 77 CLEAR BLUE 99WIE BOX 4403 PAX SSKA

答:
The first block (C1:C3) is the source data. The second (C5:K5) after parsing (a copy) of that with Text to Columns, Space delimited. The third block has this horrible formula in C9 (copied across and down to suit):

```<code>   =SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(C5,0,""),1,""),2,""),3,""),4,""),5,""),6,""),7,""),8,""),9,""),"-","")
</code>```

The fourth block under the rest has this in C13, copied across and down to suit:

```<code>=AND(LEN(C9)<>0,LEN(C9)<>LEN(C5))
</code>```

To avoid getting in the way of blocks of unknown length, this:

```<code>=MATCH(TRUE,(C13:K13),0)
</code>```

is in A13 and copied down to suit. The 'output' is in B13 and below, ready for Copy, Paste Special, Values somewhere suitable and then parsing with pipe as the delimiter.

The results from the example should be, in two columns:

```<code>2283-332-44543 CAP DDT@ PPL445                      EEN PAX 77820
44372-33-3223 TYYTE CAP BOX 1550 244 BOX PPSSA223   AX
PRECISE 77 CLEAR BLUE 99WIE                         OX 4403 PAX SSKA
</code>```

Body:
The first block (C1:C3) is the source data. The second (C5:K5) after parsing (a copy) of that with Text to Columns, Space delimited. The third block has this horrible formula in C9 (copied across and down to suit):

   =SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(C5,0,""),1,""),2,""),3,""),4,""),5,""),6,""),7,""),8,""),9,""),"-","")

The fourth block under the rest has this in C13, copied across and down to suit:

=AND(LEN(C9)<>0,LEN(C9)<>LEN(C5))

To avoid getting in the way of blocks of unknown length, this:

=MATCH(TRUE,(C13:K13),0)

is in A13 and copied down to suit. The 'output' is in B13 and below, ready for Copy, Paste Special, Values somewhere suitable and then parsing with pipe as the delimiter.

The results from the example should be, in two columns:

2283-332-44543 CAP DDT@ PPL445                      EEN PAX 77820
44372-33-3223 TYYTE CAP BOX 1550 244 BOX PPSSA223   AX
PRECISE 77 CLEAR BLUE 99WIE                         OX 4403 PAX SSKA


问:
Design-Time Errors in the Windows Forms Designer
I have this classes on the same namespace:

```<code>public partial class BaseForm : Form
{
    bool isNew = false;

    public BaseForm() {}

    public BaseForm(bool isNew)
    {
       InitializeComponent();

       this.isNew = isNew;
    }
    .
    .
    .
}

public partial class BitSetForm : BaseForm
{

    public BitSetForm(bool isNew) : base(isNew)
    {
        InitializeComponent();
    }

    new private void InitializeComponent()
    {
        .
        .
        .
    }
}
</code>```

1) And I got this warning: Could not find type "..BaseForm," Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built using the setting for your current platform or Any CPU.

2) Design-Time Errors in the Windows Forms Designer appears and hiding the design pane of the "BitSetForm" win-form.

What does this mean? What can I do to make the design pane of the "BitSetForm" win-form display again?

答:
You need to add a parameterless constructor to your BaseForm.

It can even be private; it just needs to exist.

Without one, the designer is unable to create an instance of the BaseForm to show in the design surface.

Remember to call InitializeComponent in the constructor.

Body:
I have this classes on the same namespace:

public partial class BaseForm : Form
{
    bool isNew = false;

    public BaseForm() {}

    public BaseForm(bool isNew)
    {
       InitializeComponent();

       this.isNew = isNew;
    }
    .
    .
    .
}

public partial class BitSetForm : BaseForm
{

    public BitSetForm(bool isNew) : base(isNew)
    {
        InitializeComponent();
    }

    new private void InitializeComponent()
    {
        .
        .
        .
    }
}

1) And I got this warning: Could not find type "..BaseForm," Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built using the setting for your current platform or Any CPU.

2) Design-Time Errors in the Windows Forms Designer appears and hiding the design pane of the "BitSetForm" win-form.

What does this mean? What can I do to make the design pane of the "BitSetForm" win-form display again?


问:
Java variable is incremented out of bounds at beginning of for loop
The last for loop in the BowlingTeamDemo2 class increments x to the value of 4 within the first iteration. Stumped...The program will auto fill the names instead of using the scanner, just for testing purposes. I have added a printout of the variable x before and after the inner loop in the last for loop to test the value of x. Before the inner loop, the value is 0, after the inner loop starts, the value is 4.
The loop prints the name of the team correctly, but fails when attempting to access the getMember() method from the BowlingTeam class. This was an example, not an exercise.

The error I get is this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
  at BowlingTeam.getMember(BowlingTeam.java:21)     at
  BowlingTeamDemo2.main(BowlingTeamDemo2.java:41)

```<code>public class BowlingTeam{

    private String teamName;
    private String[] members = new String[4];

    public void setTeamName(String team){
        teamName = team;
    }
    public String getTeamName(){
        return teamName;
    }

    public void setMember(int number, String name){
        members[number] = name;
    }
    public String getMember(int number){
        // We have an issue here!!!!!!
        return members[number];
    }
}

import java.util.*;
public class BowlingTeamDemo2{

    public static void main(String[] args){
        String name;
        final int NUM_TEAMS = 4;
        final int NUM_TEAM_MEMBERS = 4;
        int x;
        int y;

        BowlingTeam[] teams = new BowlingTeam[NUM_TEAMS];

        Scanner input = new Scanner(System.in);

        for(y = 0; y < NUM_TEAMS; ++y){
            teams[y] = new BowlingTeam();
            System.out.println("Enter team name >> ");
            name = "Teams";
            teams[y].setTeamName(name);

            for(x = 0; x < NUM_TEAM_MEMBERS; ++x){
                System.out.println("Enter team members name >> ");
                name = "CoolName";
                teams[y].setMember(x, name);
            }
        }

        x = 0;
        y = 0;

        for(y = 0; y < NUM_TEAMS; ++y){
            System.out.println(x);

            for(x = 0; x < NUM_TEAM_MEMBERS; ++x);{
                System.out.println(x);
                System.out.println("\nMembers of team " +
                                teams[y].getTeamName());
                // We have an issue here!!!!!!
                System.out.print(teams[y].getMember(x) + " ");
            }
        }

        System.out.println();
    }
}
</code>```

答:
Suppose your for loop has wrong syntax and it should be like this.</p>

```<code>for(y = 0; y < NUM_TEAMS; ++y){
        System.out.println(x);

        for(x = 0; x < NUM_TEAM_MEMBERS; ++x){
            System.out.println(x);
            System.out.println("\nMembers of team " +
                            teams[y].getTeamName());
            // We have an issue here!!!!!!
            System.out.print(teams[y].getMember(x) + " ");
        }
    }
</code>```

Body:
The last for loop in the BowlingTeamDemo2 class increments x to the value of 4 within the first iteration. Stumped...The program will auto fill the names instead of using the scanner, just for testing purposes. I have added a printout of the variable x before and after the inner loop in the last for loop to test the value of x. Before the inner loop, the value is 0, after the inner loop starts, the value is 4.
The loop prints the name of the team correctly, but fails when attempting to access the getMember() method from the BowlingTeam class. This was an example, not an exercise.

The error I get is this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
  at BowlingTeam.getMember(BowlingTeam.java:21)     at
  BowlingTeamDemo2.main(BowlingTeamDemo2.java:41)

public class BowlingTeam{

    private String teamName;
    private String[] members = new String[4];

    public void setTeamName(String team){
        teamName = team;
    }
    public String getTeamName(){
        return teamName;
    }

    public void setMember(int number, String name){
        members[number] = name;
    }
    public String getMember(int number){
        // We have an issue here!!!!!!
        return members[number];
    }
}

import java.util.*;
public class BowlingTeamDemo2{

    public static void main(String[] args){
        String name;
        final int NUM_TEAMS = 4;
        final int NUM_TEAM_MEMBERS = 4;
        int x;
        int y;

        BowlingTeam[] teams = new BowlingTeam[NUM_TEAMS];

        Scanner input = new Scanner(System.in);

        for(y = 0; y < NUM_TEAMS; ++y){
            teams[y] = new BowlingTeam();
            System.out.println("Enter team name >> ");
            name = "Teams";
            teams[y].setTeamName(name);

            for(x = 0; x < NUM_TEAM_MEMBERS; ++x){
                System.out.println("Enter team members name >> ");
                name = "CoolName";
                teams[y].setMember(x, name);
            }
        }

        x = 0;
        y = 0;

        for(y = 0; y < NUM_TEAMS; ++y){
            System.out.println(x);

            for(x = 0; x < NUM_TEAM_MEMBERS; ++x);{
                System.out.println(x);
                System.out.println("\nMembers of team " +
                                teams[y].getTeamName());
                // We have an issue here!!!!!!
                System.out.print(teams[y].getMember(x) + " ");
            }
        }

        System.out.println();
    }
}

Body:
Suppose your for loop has wrong syntax and it should be like this.

for(y = 0; y < NUM_TEAMS; ++y){
        System.out.println(x);

        for(x = 0; x < NUM_TEAM_MEMBERS; ++x){
            System.out.println(x);
            System.out.println("\nMembers of team " +
                            teams[y].getTeamName());
            // We have an issue here!!!!!!
            System.out.print(teams[y].getMember(x) + " ");
        }
    }


问:
Is possible to call an overridden method from another plugin?
I'm coding two plugins for a program, one of this plugin is a "library plugin" and contains a lot of classes used by the other plugins, the other is one of the plugin based on this library. All works well except one thing.
In my library plugin I wrote a socket class sintetized to this:

```<code>public class MServerSocket {
    public void initServer(int port) {
        //Code to receive message from client
        execute(input, clientOutput);
    }

    public void execute(String input, DataOutputStream clientOutput) {
        System.out.println(input);
        send(clientOutput, input);
    }

    public void send(DataOutputStream clientOutput, String output) {
        //Code to send message to client
    }
}
</code>```

In the other plugin I extend this class and override the execute method to do something, like this:

```<code>public class MySocketServer extends MServerSocket {
    @Override
    public void execute(String input, DataOutputStream clientOutput) {
        //Do something
        MServerSocket.send(clientOutput, input)
    }
}
</code>```

Now my second plugin should override my library plugin class but it doesn't.
In the second plugin I call it in the main like this:

```<code>public class Main {
    public void onEnable() { //method called to load plugin
        private static MServerSocket socket = new MServerSocket();
        socket.initServer(12980);
    }
}
</code>```

When I send a socket message to my socket it is printed to the console as said in the library execute method.

So here I am, can someone give me an answer and possibly a solution? Thanks in advance

答:
Your code currently constructs a MServerSocket object but if you want the behaviour of your MySocketServer to be executed, you need to construct one of those.

You should also change (at a minimum):

MServerSocket.send(clientOutput, input)

...to

super.send(clientOutput, input)

...as that's the proper way to delegate to a method from the parent class.

Body:
I'm coding two plugins for a program, one of this plugin is a "library plugin" and contains a lot of classes used by the other plugins, the other is one of the plugin based on this library. All works well except one thing.
In my library plugin I wrote a socket class sintetized to this:

public class MServerSocket {
    public void initServer(int port) {
        //Code to receive message from client
        execute(input, clientOutput);
    }

    public void execute(String input, DataOutputStream clientOutput) {
        System.out.println(input);
        send(clientOutput, input);
    }

    public void send(DataOutputStream clientOutput, String output) {
        //Code to send message to client
    }
}

In the other plugin I extend this class and override the execute method to do something, like this:

public class MySocketServer extends MServerSocket {
    @Override
    public void execute(String input, DataOutputStream clientOutput) {
        //Do something
        MServerSocket.send(clientOutput, input)
    }
}

Now my second plugin should override my library plugin class but it doesn't.
In the second plugin I call it in the main like this:

public class Main {
    public void onEnable() { //method called to load plugin
        private static MServerSocket socket = new MServerSocket();
        socket.initServer(12980);
    }
}

When I send a socket message to my socket it is printed to the console as said in the library execute method.

So here I am, can someone give me an answer and possibly a solution? Thanks in advance


问:
Constraining map panning with zoom.translateExtent in D3 v4
I'm trying to display a map of a single state, with zooming and panning constrained to the boundaries of the state. It's mostly working, except for the panning constraint when the state path is scaled to fit a smaller container. I think this comes down to me not understanding what arguments to use for zoom.translateExtent (although I'm very new to this, so it could be something else).

Live example on bl.ocks.org, with links to prior art.

One notable thing is that I'm using a null projection for d3.geoPath, because I used ogr2ogr to generate a shapefile in projected coordinates for each state. That's why I used a zoom transform to fit the map to its container.

答:
@McGiogen's solution is almost correct but misses that MIN needs to vary depending on the zoom scale factor transform.k.

I drew a diagram to see how I needed to constrain my svg to always be contained inside the zoomed view (depicted in my drawing as the LARGER of the boxes, only a portion of which is visible to the user):

(since the constraint x+kw >= w is equivalent to x >= (1-k)w, with a similar argument for y)

thus assuming your svg container size [w, h]:

```<code>function zoomed() {
    var t = d3.event.transform;

    t.x = d3.min([t.x, 0]);
    t.y = d3.min([t.y, 0]);
    t.x = d3.max([t.x, (1-t.k) * w]);
    t.y = d3.max([t.y, (1-t.k) * h]);

    svg.attr("transform", t);
}
</code>```

Body:
@McGiogen's solution is almost correct but misses that MIN needs to vary depending on the zoom scale factor transform.k.

I drew a diagram to see how I needed to constrain my svg to always be contained inside the zoomed view (depicted in my drawing as the LARGER of the boxes, only a portion of which is visible to the user):

(since the constraint x+kw >= w is equivalent to x >= (1-k)w, with a similar argument for y)

thus assuming your svg container size [w, h]:

function zoomed() {
    var t = d3.event.transform;

    t.x = d3.min([t.x, 0]);
    t.y = d3.min([t.y, 0]);
    t.x = d3.max([t.x, (1-t.k) * w]);
    t.y = d3.max([t.y, (1-t.k) * h]);

    svg.attr("transform", t);
}


答:
Ok I think you need to loop through your checkboxs .. the next code will loop through just the unchecked inputs

```<code>$.each(data.entries, function(id, item) {
   $('input[type=checkbox]:not(:checked)').each(function(){
      $(this).filter('[value=' + item + ']').prop("checked", true);
   });
});
</code>```

Note: The above code will work if 1- output of item matching the
  value of checkbox 2- if you have more than one checkbox with the
  same value

The next code will work for all checkbox inputs

```<code>$.each(data.entries, function(id, item) {
   $('input[type=checkbox]').each(function(){
      var checked_or_not = this.checked;
      console.log(checked_or_not);
      if(checked_or_not === false){
        $(this).filter('[value=' + item + ']').prop("checked", true);
      }
      console.log(checked_or_not);
   });
});
</code>```

Title: Issue with .prop("checked", true)?

Body:
I have the following:

116   $.each(data.entries, function(id, item) {
117       console.log($("input[type=checkbox][value=" + item + "]").is(":checked"));
118       $("input[type=checkbox][value=" + item + "]").prop("checked", true);
119       console.log($("input[type=checkbox][value=" + item + "]").is(":checked"));
120   })

For the life of me I can't get my checkbox to check:

swot-nav.js:117 false
swot-nav.js:119 false

This doesn't work either:

116    $.each(data.entries, function(id, item) {
117        console.log($(":checkbox[value=" + item + "]").is(":checked"));
118        $(":checkbox[value=" + item + "]").prop("checked", "true");
119        console.log($(":checkbox[value=" + item + "]").is(":checked"));
120    })

(same result)

What could I be missing?

Edit:

This is taking place in the success function of an Ajax Call.

This is what the data looks like:

data = {'label': 'D1- DC Test 1', 'details': '', 'type': 'D', 'entries': [20, 21, 22]

Here's a fiddle where it's working: https://jsfiddle.net/e3arwp7q/

There must be something wrong deeper in my code. If this looks to everyone like it is supposed to work, then maybe I should look elsewhere.

Body:
Ok I think you need to loop through your checkboxs .. the next code will loop through just the unchecked inputs

$.each(data.entries, function(id, item) {
   $('input[type=checkbox]:not(:checked)').each(function(){
      $(this).filter('[value=' + item + ']').prop("checked", true);
   });
});

Note: The above code will work if 1- output of item matching the
  value of checkbox 2- if you have more than one checkbox with the
  same value

The next code will work for all checkbox inputs

$.each(data.entries, function(id, item) {
   $('input[type=checkbox]').each(function(){
      var checked_or_not = this.checked;
      console.log(checked_or_not);
      if(checked_or_not === false){
        $(this).filter('[value=' + item + ']').prop("checked", true);
      }
      console.log(checked_or_not);
   });
});


问:
IBM bluemix course 3 - deploy chaincode v2.0
I am learning blockchain through IBM's blockchain course 3. When I try to deploy the chaincode it picks up the master code instead of the version 2.0. I saw a related post but it did not help.

Complete JSON:

 {
     "jsonrpc": "2.0",
     "method": "deploy",
     "params": {
         "type": 1,
         "chaincodeID": {
             "path": "https://github.com/dithmarschen96/learn-chaincode.v2/start"
         },
         "ctorMsg": {
             "function": "init",
             "args": [
                 "hi there"
             ]
         },
         "secureContext": "user_type1_1"
     },
     "id": 1
 }```
</div>
</div>
</p>

<p>And the error message (note: it says could not read user name but if I remove ".v2" in the path it works with the same user name).</p>

```"code": -32001,
"message": "Deployment failure",
"data": "Error when deploying chaincode: Error getting chaincode package bytes: Error getting code 'go get' failed with error: \"exit status 1\"\n# cd .; git clone https://github.com/dithmarschen96/learn-chaincode.v2 /opt/gopath/_usercode_/557323755/src/github.com/dithmarschen96/learn-chaincode.v2\nCloning into '/opt/gopath/_usercode_/557323755/src/github.com/dithmarschen96/learn-chaincode.v2'...\nfatal: could not read Username for 'https://github.com': No such device or address\npackage github.com/dithmarschen96/learn-chaincode.v2/start: exit status 128\n"
```

If I remove ".v2" in the path it works fine but I get the master and not the branch.

How do I reference the version 2 in JSON for the post call?

答:
Found it in the doc for the course:

Tip: You can use gopkg.in to provide a URL for the chaincode deploy that uses a GitHub branch
version:
http://gopkg.in//learn-chaincode.v2/finished

Body:
I am learning blockchain through IBM's blockchain course 3. When I try to deploy the chaincode it picks up the master code instead of the version 2.0. I saw a related post but it did not help.

Complete JSON:

 {
     "jsonrpc": "2.0",
     "method": "deploy",
     "params": {
         "type": 1,
         "chaincodeID": {
             "path": "https://github.com/dithmarschen96/learn-chaincode.v2/start"
         },
         "ctorMsg": {
             "function": "init",
             "args": [
                 "hi there"
             ]
         },
         "secureContext": "user_type1_1"
     },
     "id": 1
 }

And the error message (note: it says could not read user name but if I remove ".v2" in the path it works with the same user name).

"code": -32001,
"message": "Deployment failure",
"data": "Error when deploying chaincode: Error getting chaincode package bytes: Error getting code 'go get' failed with error: \"exit status 1\"\n# cd .; git clone https://github.com/dithmarschen96/learn-chaincode.v2 /opt/gopath/_usercode_/557323755/src/github.com/dithmarschen96/learn-chaincode.v2\nCloning into '/opt/gopath/_usercode_/557323755/src/github.com/dithmarschen96/learn-chaincode.v2'...\nfatal: could not read Username for 'https://github.com': No such device or address\npackage github.com/dithmarschen96/learn-chaincode.v2/start: exit status 128\n"

If I remove ".v2" in the path it works fine but I get the master and not the branch.

How do I reference the version 2 in JSON for the post call?


问:
What's the best way to refresh TensorBoard after new events/logs were added?
What is the best way to quickly see the updated graph in the most recent event file in an open TensorBoard session? Re-running my Python app results in a new log file being created with potentially new events/graph. However, TensorBoard does not seem to notice those differences, unless restarted.</p>

答:
My issue is different. Each time I refresh 0.0.0.0:6006, it seems the new graph keep appending to the old one, which is quite annoying.

After trying kill process and delete old log several times, I realized the issue comes from writer.add_graph(sess.graph),  because I didn't reset the graph in jupyter notebook.  After resetting, the tensorboard could show the newest gragh.


问:
Trying to set up Node authentication with express and passport
Im currently in the proccess of trying to build a simple user authentication system with node.js and passport and express for a scheduled SMS application; however, when trying to initialize server, no matter the combination of fixes I have googled and tried, cmdPrompt keeps rendering

$ node appauth C:\Users\zobri\uabcprojects\nodeauth\node_modules\express\lib\router\index.js:458
        throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));
        ^

I have no clue as to why... I have been following a tutorial, but can't seem to figure out what the heck is happening - any help would be greatly appreciated!
Robert

My code:

const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const expHandlebars = require('express-handlebars');
const expValidator = require('express-validator');
const expSession = require('express-session');
const flash = require('connect-flash');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const database = require('mongodb');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/appAuth');
const db = mongoose.connection;

// routes
const routes = require('./routes/index');
const users = require('./routes/users');

// initialize application
const app = express();

// view engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', expHandlebars({ defaultLayout: 'layout' }));
app.set('view engine', 'handlebars');

// body-parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// set static directory
app.use(express.static(path.join(__dirname, 'public')));

// express session
app.use(expSession({
     secret: 'rddremind',
     proxy: true,
     resave: true,
     saveUninitialized: true

}));

// passport init
app.use(passport.initialize());
app.use(passport.session());

// express validator (code snippet courtesy of 'https://github.com/ctavan/express-validator')\\

app.use(expValidator({
     errorFormatter: function(param, msg, value) {
          var namespace = param.split('.'),
               root = namespace.shift(),
               formParam = root;

          while (namespace.length) {
               formParam += '[' + namespace.shift() + ']';
          }
          return {
               param: formParam,
               msg: msg,
               value: value
          };
     }
}));

// connect flash
app.use(flash());

// Global variables
app.use(function(req, res, next) {
          res.locals.success_msg = req.flash('success_msg');
          res.locals.error_msg = req.flash('error_msg');
          res.locals.error = req.flash('error');
          next();

     }),

     app.use('/', routes);
app.use('/users', users);

// set Port
app.set('port', (proccess.env.PORT || 8081));

app.listen(app.get('port'), function() {
     console.log('Server initialized on port ' + app.get('port'));
});```

答:
```<code>app.use('/', routes);
app.use('/users', users);
</code>```

Those two lines are incorrect. You aren't wanting to use Middleware to setup your routes.

```<code>require('./app/routefile1.js')(app, passport);
require('./app/routefile2.js')(app, passport);
</code>```

To setup my routes I use something like the code above. Of course replacing with your paths. If you use this method you shouldn't need the two lines below also.

```<code>const routes = require('./routes/index');
const users = require('./routes/users');
</code>```

When working with code a good debugging trick is to start removing code or commenting it out until you narrow the problem down to a specific part of code. Then work from there.

Body:
app.use('/', routes);
app.use('/users', users);

Those two lines are incorrect. You aren't wanting to use Middleware to setup your routes.

require('./app/routefile1.js')(app, passport);
require('./app/routefile2.js')(app, passport);

To setup my routes I use something like the code above. Of course replacing with your paths. If you use this method you shouldn't need the two lines below also.

const routes = require('./routes/index');
const users = require('./routes/users');

When working with code a good debugging trick is to start removing code or commenting it out until you narrow the problem down to a specific part of code. Then work from there.


问:
Fetching data to a React.js component is not working
I have this quote.jsx file with a React component:

```<code>import React from 'react';
import fetch from 'node-fetch';
import './quotes.css';

export default class Quotes extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      <div className="quotes">
        {
          fetch('/random_quote')
            .then(res => res.json())
            .then(json => json.text())
        }
      </div>
    );
  }
}
</code>```

As you may see, it uses fetch to get a JSON object with data related to a quote (quote text and author) and display some this data.

When I use webpack to bundle my system, I'm getting this warning message:

WARNING in ./fe/~/encoding/lib/iconv-loader.js
  9:12-34 Critical dependency: the request of a dependency is an expression

And when I run my web system and visit the URL who should display this component, I got the following error:

Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Quotes.

There is no error in my back-end and the JSON is being correctly generated and returned. This is not an issue.

I am relatively new to React.js and had never seen this message before.

Can someone help me with this? I've been fighting this error all my Sunday and have no more options to deal with it.

答:
Don't perform the fetch inside render, instead do it in componentDidMount or componentWillMount.

Here is how I would implement it:

```<code>import React from 'react';
import fetch from 'node-fetch';
import './quotes.css';

export default class Quotes extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    fetch('/random_quote')
    .then(res => res.json())
    .then(json => {
      this.setState({text: json.text()});
    });
  }

  render() {
    return(
      <div className="quotes">
        {this.state.text}
      </div>
    );
  }
}
</code>```

Body:
I have this quote.jsx file with a React component:

import React from 'react';
import fetch from 'node-fetch';
import './quotes.css';

export default class Quotes extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(

        {
          fetch('/random_quote')
            .then(res => res.json())
            .then(json => json.text())
        }

    );
  }
}

As you may see, it uses fetch to get a JSON object with data related to a quote (quote text and author) and display some this data.

When I use webpack to bundle my system, I'm getting this warning message:

WARNING in ./fe/~/encoding/lib/iconv-loader.js
  9:12-34 Critical dependency: the request of a dependency is an expression

And when I run my web system and visit the URL who should display this component, I got the following error:

Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Quotes.

There is no error in my back-end and the JSON is being correctly generated and returned. This is not an issue.

I am relatively new to React.js and had never seen this message before.

Can someone help me with this? I've been fighting this error all my Sunday and have no more options to deal with it.

Body:
Don't perform the fetch inside render, instead do it in componentDidMount or componentWillMount.

Here is how I would implement it:

import React from 'react';
import fetch from 'node-fetch';
import './quotes.css';

export default class Quotes extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    fetch('/random_quote')
    .then(res => res.json())
    .then(json => {
      this.setState({text: json.text()});
    });
  }

  render() {
    return(
      <div className="quotes">
        {this.state.text}
      </div>
    );
  }
}


问:
unexpected token error when using onclick
this is my code

```<code>  const products = productArray.map(product =>
`
<tr>
  <td>${product.id}</td>
  <td>${product.type}</td>
  <td>${product.price}</td>
  <td><button onclick="${() => console.log('hello world')}">Examine</button></td>
</tr>
`
  );
  return tableBody.innerHTML = products.join('');
</code>```

I just don't get why I'm getting this unexpected token error, that points to the html. I'm pretty sure It's a very stupid but I just cannot get where it is.

答:
At the end I used this solution, it's a pitty because the other was shorter:</p>

```<code>const products = productArray.map(product => {
    const tr = document.createElement('tr');
    const td1 = document.createElement('td');
    const td2 = document.createElement('td');
    const td3 = document.createElement('td');
    const td4 = document.createElement('button');

    td4.addEventListener('click', () =>
      processSearch(product.id)
    );

    td1.appendChild(document.createTextNode(product.id));
    td2.appendChild(document.createTextNode(product.type));
    td3.appendChild(document.createTextNode(product.price));
    td4.appendChild(document.createTextNode('Examine'));
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);
    tr.appendChild(td4);

    return tableBody.appendChild(tr);
  });
</code>```

Body:
this is my code

  const products = productArray.map(product =>
`

  ${product.id}
  ${product.type}
  ${product.price}
  <button onclick="${() => console.log('hello world')}">Examine</button>

`
  );
  return tableBody.innerHTML = products.join('');

I just don't get why I'm getting this unexpected token error, that points to the html. I'm pretty sure It's a very stupid but I just cannot get where it is.

Body:
At the end I used this solution, it's a pitty because the other was shorter:

const products = productArray.map(product => {
    const tr = document.createElement('tr');
    const td1 = document.createElement('td');
    const td2 = document.createElement('td');
    const td3 = document.createElement('td');
    const td4 = document.createElement('button');

    td4.addEventListener('click', () =>
      processSearch(product.id)
    );

    td1.appendChild(document.createTextNode(product.id));
    td2.appendChild(document.createTextNode(product.type));
    td3.appendChild(document.createTextNode(product.price));
    td4.appendChild(document.createTextNode('Examine'));
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);
    tr.appendChild(td4);

    return tableBody.appendChild(tr);
  });


问:
c++ 2D array row sort based on average row value
Helo,

I'm wondering if there's any working method for this?
I'm trying make this work, but no luck.

```<code>int mat[3][3];

    mat[0][0] = 4;mat[0][1] = 5;mat[0][2] = 3;

    mat[1][0] = 3;mat[1][1] = 2;mat[1][2] = 1;

    mat[2][0] = 1;mat[2][1] = 8;mat[2][2] = 9;
</code>```

Any idea? :)

答:
Put the rows in a multiset and overload the < operator.  Here's a 1D example:

http://bytes.com/topic/c/answers/171028-multiset-example

Body:
Helo,

I'm wondering if there's any working method for this?
I'm trying make this work, but no luck.

int mat[3][3];

    mat[0][0] = 4;mat[0][1] = 5;mat[0][2] = 3;

    mat[1][0] = 3;mat[1][1] = 2;mat[1][2] = 1;

    mat[2][0] = 1;mat[2][1] = 8;mat[2][2] = 9;

Any idea? :)


问:
Calling a procedure or function in a select statement
I have been banging my head once again on HANA syntax. I have been looking for a method of writing either a function or procedure and calling the function or procedure in a select statement to evaluate a column in a table and alter the column based on an if function.

I have created most of the script but the replace function is not working as expected. I am not too familiar with HANA, so any help would be appreciated. Thanks.

Can someone also let me know how can I call the procedure as this seems a bit more complicated in HANA? I am using HANA sp 10.

I am essentially wanting to run the function or procedure using a select statement and output the result as follows

example of what I am trying to achieve

id
string updated
temp_str from function or procedure

1
12212
12,2,12

2
21221
2,12,2,1

3
12212
12,2,12

```<code>create procedure update_str
language sqlscript
as

ip_str varchar:= '21222212';

temp_str varchar(100) := ip_str || ',';
pos integer :=1;

begin

while(length(:temp_str) > 0 ) do

if substr(temp_str,1,1) = '1' and substr (temp_str,2,1) = '2' then
update temp_str := replace(temp_str,'12','12,');
pos := :pos + 1;

elseif substr(temp_str,1,1) = '2' and substr (temp_str,2,1) = '1' then
update temp_str := replace(temp_str,'21','2,1');
pos := :pos + 1;

elseif substr(temp_str,1,1) = '2' and substr (temp_str,2,1) = '2' then
update temp_str := replace(temp_str,'22','2,2');
pos := :pos + 1;

else;

end if;
end if;
end if;

end while;

end;
</code>```

答:
For what you described it is best to use a scalar user-defined function (SUDF).

How to create and use those is explained extensively in the SAP HANA Developer Guide, so I won't go into details here.

I also won't discuss the logic errors in the provided code, instead here is a version that generates the output for your test data:

```<code>drop function update_str;
create function update_str (IN IP_STR varchar(100) )
        returns res_str varchar(200)
language sqlscript
as
begin
declare temp_str varchar(100) := ip_str ;

    -- add a comma behind twelves
    temp_str := replace (:temp_str, '12', '12,');

    -- add a comma between twenty-ones
    temp_str := replace (:temp_str, '21', '2,1');

    -- add a comma between twenty-twos
    temp_str := replace (:temp_str, '21', '2,1');

    -- remove last comma if there is any
    if (right (:temp_str, 1) = ',' ) then
        temp_str =  left (:temp_str, length(:temp_str) -1 );
    end if;

    res_str :=  :temp_str;
end;
</code>```

Check the code:

```<code>with test_data as

          ( select 1 as id, '12212' as str from dummy
union all select 2 as id, '21221' as str from dummy
union all select 3 as id, '12212' as str from dummy)
select id, str, update_str(str)
from test_data;

ID  STR     UPDATE_STR(STR)
1   12212   12,2,12
2   21221   2,12,2,1
3   12212   12,2,12
</code>```

Depending on your actual requirement you might be able to form a regular expression that performs the same transformation. If so, you could also use the REPLACE_REGEXPR function in SAP HANA.

ContentLicense: CC BY-SA 4.0

Body:
I have been banging my head once again on HANA syntax. I have been looking for a method of writing either a function or procedure and calling the function or procedure in a select statement to evaluate a column in a table and alter the column based on an if function.

I have created most of the script but the replace function is not working as expected. I am not too familiar with HANA, so any help would be appreciated. Thanks.

Can someone also let me know how can I call the procedure as this seems a bit more complicated in HANA? I am using HANA sp 10.

I am essentially wanting to run the function or procedure using a select statement and output the result as follows

example of what I am trying to achieve

id
string updated
temp_str from function or procedure

1
12212
12,2,12

2
21221
2,12,2,1

3
12212
12,2,12

create procedure update_str
language sqlscript
as

ip_str varchar:= '21222212';

temp_str varchar(100) := ip_str || ',';
pos integer :=1;

begin

while(length(:temp_str) > 0 ) do

if substr(temp_str,1,1) = '1' and substr (temp_str,2,1) = '2' then
update temp_str := replace(temp_str,'12','12,');
pos := :pos + 1;

elseif substr(temp_str,1,1) = '2' and substr (temp_str,2,1) = '1' then
update temp_str := replace(temp_str,'21','2,1');
pos := :pos + 1;

elseif substr(temp_str,1,1) = '2' and substr (temp_str,2,1) = '2' then
update temp_str := replace(temp_str,'22','2,2');
pos := :pos + 1;

else;

end if;
end if;
end if;

end while;

end;

Body:
For what you described it is best to use a scalar user-defined function (SUDF).

How to create and use those is explained extensively in the SAP HANA Developer Guide, so I won't go into details here.

I also won't discuss the logic errors in the provided code, instead here is a version that generates the output for your test data:

drop function update_str;
create function update_str (IN IP_STR varchar(100) )
        returns res_str varchar(200)
language sqlscript
as
begin
declare temp_str varchar(100) := ip_str ;

    -- add a comma behind twelves
    temp_str := replace (:temp_str, '12', '12,');

    -- add a comma between twenty-ones
    temp_str := replace (:temp_str, '21', '2,1');

    -- add a comma between twenty-twos
    temp_str := replace (:temp_str, '21', '2,1');

    -- remove last comma if there is any
    if (right (:temp_str, 1) = ',' ) then
        temp_str =  left (:temp_str, length(:temp_str) -1 );
    end if;

    res_str :=  :temp_str;
end;

Check the code:

with test_data as

          ( select 1 as id, '12212' as str from dummy
union all select 2 as id, '21221' as str from dummy
union all select 3 as id, '12212' as str from dummy)
select id, str, update_str(str)
from test_data;

ID  STR     UPDATE_STR(STR)
1   12212   12,2,12
2   21221   2,12,2,1
3   12212   12,2,12

Depending on your actual requirement you might be able to form a regular expression that performs the same transformation. If so, you could also use the REPLACE_REGEXPR function in SAP HANA.


问:
Can I use IntelliJ to develop WSO2 ESB API?
I am using the WSO2 Eclipse version to develop my WSO2 ESB project.

I am asking if exist something like of an IntelliJ plugin to develop my WSO2 ESB API into IntelliJ Idea IDE. I mean something that shows the graphical flows.

Is it possible or not?

答: At the moment there is no IdeaJ plugin that you can use. You need to use the WSO2 Developer studio which is based on eclipse</p>


问:
Oracle SQL Calculating Variance
Lets say I have a table like so:

```<code>ID         TYPE          MONTH       AMOUNT
--         ----          ----          ---

abc        Forecast       1           150
def        Forecast       1           225
abc        Budget         1           140
def        Budget         1           250
abc        Forecast       2           190
abc        Budget         2           450
</code>```

What I want to do is insert a record for each ID that is the difference between the Forecast and the Budget for each month.  So result would look like this:

```<code>ID         TYPE          MONTH       AMOUNT
--         ----          ----          ---

abc        Forecast       1           150
def        Forecast       1           225
abc        Budget         1           140
def        Budget         1           250
abc        Forecast       2           190
abc        Budget         2           450
abc        Variance       1           10
abc        Variance       2          -260
def        Variance       1          -25
</code>```

could someone please provide the SQL for this.  Thank you!

答:
You can use conditional aggregation to get the difference and insert the variance rows. (This assumes each id,month combination has Forecast and Budget rows. If not, add else 0 in each max)

```<code>insert into tbl(id,type,month,amount)
select id,'Variance',month,
max(case when type='Forecast' then amount end) - max(case when type='Budget' then amount end)
from tbl
group by id,month
</code>```

Title: Oracle SQL Calculating Variance

Body:
Lets say I have a table like so:

ID         TYPE          MONTH       AMOUNT
--         ----          ----          ---

abc        Forecast       1           150
def        Forecast       1           225
abc        Budget         1           140
def        Budget         1           250
abc        Forecast       2           190
abc        Budget         2           450

What I want to do is insert a record for each ID that is the difference between the Forecast and the Budget for each month.  So result would look like this:

ID         TYPE          MONTH       AMOUNT
--         ----          ----          ---

abc        Forecast       1           150
def        Forecast       1           225
abc        Budget         1           140
def        Budget         1           250
abc        Forecast       2           190
abc        Budget         2           450
abc        Variance       1           10
abc        Variance       2          -260
def        Variance       1          -25

could someone please provide the SQL for this.  Thank you!

Body:
You can use conditional aggregation to get the difference and insert the variance rows. (This assumes each id,month combination has Forecast and Budget rows. If not, add else 0 in each max)

insert into tbl(id,type,month,amount)
select id,'Variance',month,
max(case when type='Forecast' then amount end) - max(case when type='Budget' then amount end)
from tbl
group by id,month