问:
Update an attribute and remove duplicate element in an array from JavaScript
I've got a problem about some code.
Here's my array

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 1,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 2,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 1,
    numberHoursSpent: 3,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 4,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 3,
    numberHoursSpent: 5,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  }
  ]```
</div>
</div>
</p>

<p>The problem is I need to make my array looks like this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: (1+2+4)/(1+1+1),
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: (3+5)/(1+3),
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

  ]</code>```

which is equivalent to this

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: 2.33,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: 2,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

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

<p>First I find the same objects in array if they have the same "name" attributes.Then I sum all numberHoursSpent attributes and divide them by sum of numberSoldLodgings attributes from those objects.
Then I remove all the same elements, only keep an unique one.
P/S: The objects are the same if they have the same "name" attributes.
Here's what I've tried.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>handleData = arr => {
  var firstElementIndex =0;
  const final = []
  var filteredArray = []
  arr.map((e,i)=>{
    if(final.includes(e.name)){
      var k = k+arr[i].numberHoursSpent;
      firstElementIndex = final.indexOf(e.name);
      arr[firstElementIndex].numberHoursSpent +=  arr[i].numberHoursSpent
      filteredArray= arr.filter(item => item !== arr[i] )
    }
    else{
      final.push(e.name)
    }
    if(i == arr.length-1){
      arr[firstElementIndex].numberHoursSpent /= k
    }
  })

  return filteredArray;
}</code>```

Please help me, thanks.

答:
function foo(arr) {
  let dict = {}
  arr.forEach(x => {
    if (dict[x.name]) {
      let y = dict[x.name]
      dict[x.name]['numberHoursSpent'] = y['numberHoursSpent'] + x['numberHoursSpent']
      dict[x.name]['numberSoldLodging'] = y['numberSoldLodging'] + x['numberSoldLodging']
    } else {
      dict[x.name] = x
    }
  })
  return Object.keys(dict).map(x => {
    dict[x]['numberHoursSpent'] = dict[x]['numberHoursSpent'] / dict[x]['numberSoldLodging']
    return dict[x]
  })
  // return dict
}

let arr = [{
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 1,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 2,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 1,
    numberHoursSpent: 3,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 4,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 3,
    numberHoursSpent: 5,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  }
]

let y = foo(arr)
console.log(y)```

Body:
I've got a problem about some code.
Here's my array

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 1,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 2,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 1,
    numberHoursSpent: 3,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 4,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 3,
    numberHoursSpent: 5,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  }
  ]

The problem is I need to make my array looks like this.

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: (1+2+4)/(1+1+1),
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: (3+5)/(1+3),
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

  ]

which is equivalent to this

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: 2.33,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: 2,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

  ]

First I find the same objects in array if they have the same "name" attributes.Then I sum all numberHoursSpent attributes and divide them by sum of numberSoldLodgings attributes from those objects.
Then I remove all the same elements, only keep an unique one.
P/S: The objects are the same if they have the same "name" attributes.
Here's what I've tried.

handleData = arr => {
  var firstElementIndex =0;
  const final = []
  var filteredArray = []
  arr.map((e,i)=>{
    if(final.includes(e.name)){
      var k = k+arr[i].numberHoursSpent;
      firstElementIndex = final.indexOf(e.name);
      arr[firstElementIndex].numberHoursSpent +=  arr[i].numberHoursSpent
      filteredArray= arr.filter(item => item !== arr[i] )
    }
    else{
      final.push(e.name)
    }
    if(i == arr.length-1){
      arr[firstElementIndex].numberHoursSpent /= k
    }
  })

  return filteredArray;
}

Please help me, thanks.


来源: stackexchange

问:
Using numpy.argpartition ignoring NaNs
I have a large array with approximately 49million items (7000*7000) and in there I need to find the largest N items and their indexes ignoring all the NaNs. I can't remove these NaNs before hand because I need the index values of the largest N items from first array to extract data from another which have NaNs in different indexes compared to the first array. I tried

np.argpartition(first_array, -N)[-N:]

this works very good for an array without NaNs, but if there is NaNs the nan's are coming as the largest item because it is considered as infinity in python.

x = np.array([np.nan, 2, -1, 2, -4, -8, -9, 6, -3]).reshape(3, 3)
y = np.argpartition(x.ravel() , -3)[-3:]
z = x.ravel()[y]
# this is the result I am getting  === [2, 6, nan]
# but I need this ==== [2, 2, 6]
```

答:
Use count of NaNs to offset and thus compute indices and extract values -</p>

```<code>In [200]: N = 3

In [201]: c = np.isnan(x).sum()

In [204]: idx = np.argpartition(x.ravel() , -N-c)[-N-c:-c]

In [207]: val = x.flat[idx]

In [208]: idx,val
Out[208]: (array([1, 3, 7]), array([2., 2., 6.]))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Using numpy.argpartition ignoring NaNs

Body:
Use count of NaNs to offset and thus compute indices and extract values -

In [200]: N = 3

In [201]: c = np.isnan(x).sum()

In [204]: idx = np.argpartition(x.ravel() , -N-c)[-N-c:-c]

In [207]: val = x.flat[idx]

In [208]: idx,val
Out[208]: (array([1, 3, 7]), array([2., 2., 6.]))


问:
Regex for capturing 4 consecutive numbers in an ID
I need a formula to start at a a certain index and then get the next 4 consecutive numbers.  Using REGEX.  And testing whether they are in the range of 0000-4999.

```<code>^.{6}\d{4}$[0000-4999]
</code>```

This is some code I have tried.  Although I'm still new and don't understand regex.

The outcome needs to be as follows:

ID Number:

```<code>9202204720082
</code>```

Get the following 4 numbers:  4720

Starting at index 7 (presuming indexes starts at 1)

So want to get numbers if indexes 7,8,9, and 10.
This is done to determine the gender in an ID.

答:
You don't need to use a regex for this. You could achieve the same result by simply getting a substring. Depending on your programming language you might do something like this:

JavaScript

var string = "9202204720082";
var index = 6;

console.log(string.substring(index, index + 4));```
</div>
</div>
</p>

<h2>Ruby</h2>

<pre class="lang-rb prettyprint-override"><code>string = '9202204720082'
index = 6

string[index, 4]
#=> "4720"
</code>```

Perl

my $string = '9202204720082';
my $index = 6;

substr($string, $index, 4);
#=> "4720"
```

Body:
I need a formula to start at a a certain index and then get the next 4 consecutive numbers.  Using REGEX.  And testing whether they are in the range of 0000-4999.

^.{6}\d{4}$[0000-4999]

This is some code I have tried.  Although I'm still new and don't understand regex.

The outcome needs to be as follows:

ID Number:

9202204720082

Get the following 4 numbers:  4720

Starting at index 7 (presuming indexes starts at 1)

So want to get numbers if indexes 7,8,9, and 10.
This is done to determine the gender in an ID.

Body:
You don't need to use a regex for this. You could achieve the same result by simply getting a substring. Depending on your programming language you might do something like this:

JavaScript

var string = "9202204720082";
var index = 6;

console.log(string.substring(index, index + 4));

Ruby

string = '9202204720082'
index = 6

string[index, 4]
#=> "4720"

Perl

my $string = '9202204720082';
my $index = 6;

substr($string, $index, 4);
#=> "4720"


问:
Is it possible to position background-attachment: fixed relatively to div not viewport?
Is it possible to make a background-attachment:fixed; for div which positioned by div position not with viewport? If not, maybe there are some other alternatives?

CSS

```<code>.zest-ghost {
        width: 302px;
        height: 222px;
        top: 0;
        left: 50%;
        background-image: url(../images/logo-ghost.png);
        background-attachment: fixed;
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
    }
</code>```

HTML

This code makes image fixed relatively to viewport and not with div. I
  need same effect but with the possibility to move the image left or
  right. An image should have its original width and height

答:
We can use background-position property for this. Instead of using center, you can use pixels to actually move the image within a div.

```<code>.zest-ghost {
        width: 302px;
        height: 222px;
        top: 0;
        left: 50%;
        background-image: url(../images/logo-ghost.png);
        background-attachment: fixed;
        background-position: 50% 20px;
        background-repeat: no-repeat;
        background-size: cover;
    }
</code>```

The above will adjust the x-axis cropped content to 50% and moves the image down vertically by 20px.

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to make a background-attachment:fixed; for div which positioned by div position not with viewport? If not, maybe there are some other alternatives?

CSS

.zest-ghost {
        width: 302px;
        height: 222px;
        top: 0;
        left: 50%;
        background-image: url(../images/logo-ghost.png);
        background-attachment: fixed;
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
    }

HTML

This code makes image fixed relatively to viewport and not with div. I
  need same effect but with the possibility to move the image left or
  right. An image should have its original width and height

Body:
We can use background-position property for this. Instead of using center, you can use pixels to actually move the image within a div.

.zest-ghost {
        width: 302px;
        height: 222px;
        top: 0;
        left: 50%;
        background-image: url(../images/logo-ghost.png);
        background-attachment: fixed;
        background-position: 50% 20px;
        background-repeat: no-repeat;
        background-size: cover;
    }

The above will adjust the x-axis cropped content to 50% and moves the image down vertically by 20px.


问:
Fill li with content depending on database results
I'm working with fat free framework and am currently working on a bracket generation for competitions.

What I do is passing multiple competitors (from different "layers") to the view to display them in a tree. The basic styling comes from this codepen.

Now the problem is, that I don't know every field from beginning on, as the result of the first two competitions decide how the next level looks (quarter finals in that case). The problem is though, that if I don't put the fields there, then the complete layout is destroyed, thats why I put empty
 elements for the layer, where the competitors are not clear so far, just like so:

```<code><li class="team-item"> </li>
<li class="team-item"> </li>
<li class="team-item"> </li>
<li class="team-item"> </li>
</code>```

Same for semi finals and finals then, just with 2 and 1
s then.

Now in some of the cells of quarter/seminfinals I already have something in my database. So for example, if there's 8 competitions in "layer1", then I would have 4 empty fields in "layer2", respectively in the quarter finals. These 4 fields have to be predefined in order to keep the layout. Now maybe I only have 1 or 2 of these fields filled already, because the other competitions are not over yet.

So I have to always predefine the fields like in the code above. Now the question is: How do I either replace one empty
 with the filled one or alternatively, how do I fill the empty
 with information, if provided.

```<code><ul class="bracket bracket-2">
      <repeat group="{{ @bracket }}" value="{{ @item }}">
        <check if="{{@item.layer == 2}}">
        <!-- li should be filled with this content, if the condition is true, so if in here -->
        <li class="team-item">{{ @item.Vorname1  }} {{ @item.Name1  }} <a href="/getFighterInformation/{{@item.fighter1ID}}"<i class="fa fa-pencil-alt"></i></a> <i class="fa fa-trophy"></i></li>
      <li class="team-item">{{ @item.Vorname2  }} {{ @item.Name2  }} <a href="/getFighterInformation/{{@item.fighter2ID}}"<i class="fa fa-pencil-alt"></i></a> <i class="fa fa-trophy"></i></li>
  </check>
    </repeat>
  <!-- This should be predefined -->
  <li class="team-item"> </li>
  <li class="team-item"> </li>
  <li class="team-item"> </li>
  <li class="team-item"> </li>
  <!-------------------------------->
    </ul>
</code>```

That's an example for layer 2 with 8 competitions in layer 1.

I hope you get what I mean, but its pretty hard to explain...

So summarized, the question is: Is it possible to predefine list elements and then fill or replace them, if an if-condition matches?

EDIT:

This is what I get from database, filled into the bracket variable:

```<code>array(4){
   [
      0
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "1"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "21"      [
         "Vorname1"
      ]      => string(5) "one"      [
         "Name1"
      ]      => string(4) "one"      [
         "Geburtsdatum1"
      ]      => string(10) "1999-04-04"      [
         "fighter1Pos"
      ]      => string(1) "0"      [
         "fighter2ID"
      ]      => string(2) "19"      [
         "Vorname2"
      ]      => string(8) "two"      [
         "Name2"
      ]      => string(4) "two"      [
         "Geburtsdatum2"
      ]      => string(10) "1988-12-11"      [
         "fighter2Pos"
      ]      => string(1) "1"      [
         "result"
      ]      => string(1) "0"
   }   [
      1
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "2"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "25"      [
         "Vorname1"
      ]      => string(5) "three"      [
         "Name1"
      ]      => string(4) "three"      [
         "Geburtsdatum1"
      ]      => string(10) "1988-08-18"      [
         "fighter1Pos"
      ]      => string(1) "2"      [
         "fighter2ID"
      ]      => string(2) "24"      [
         "Vorname2"
      ]      => string(5) "four"      [
         "Name2"
      ]      => string(4) "four"      [
         "Geburtsdatum2"
      ]      => string(10) "1985-08-17"      [
         "fighter2Pos"
      ]      => string(1) "3"      [
         "result"
      ]      => string(1) "0"
   }   [
      2
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "3"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "23"      [
         "Vorname1"
      ]      => string(5) "five"      [
         "Name1"
      ]      => string(4) "five"      [
         "Geburtsdatum1"
      ]      => string(10) "1966-06-16"      [
         "fighter1Pos"
      ]      => string(1) "4"      [
         "fighter2ID"
      ]      => string(2) "20"      [
         "Vorname2"
      ]      => string(8) "six"      [
         "Name2"
      ]      => string(4) "six"      [
         "Geburtsdatum2"
      ]      => string(10) "1966-03-03"      [
         "fighter2Pos"
      ]      => string(1) "5"      [
         "result"
      ]      => string(1) "0"
   }   [
      3
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "4"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "18"      [
         "Vorname1"
      ]      => string(6) "seven"      [
         "Name1"
      ]      => string(4) "seven"      [
         "Geburtsdatum1"
      ]      => string(10) "1985-08-17"      [
         "fighter1Pos"
      ]      => string(1) "6"      [
         "fighter2ID"
      ]      => string(2) "22"      [
         "Vorname2"
      ]      => string(9) "eight"      [
         "Name2"
      ]      => string(4) "eight"      [
         "Geburtsdatum2"
      ]      => string(10) "1995-09-15"      [
         "fighter2Pos"
      ]      => string(1) "7"      [
         "result"
      ]      => string(1) "0"
   }
}
</code>```

One box should contain one fighter only, not two fighters. So each array element represents one fight, containing two fighters (referencable by fighter1ID/fighter2ID, respectively Name1, Name2, etc.). fighter1Pos and fighter2Pos then, together with the value "ebene", which is the layer (3, 2, 1 or 0), determine the position in the bracket, so layer 3 with fighter1Pos 7 would be the last "box" in the layer 3 (counting from 0 - 7).

答:
I think you're approaching the problem in the wrong way: if an element doesn't have any content or meaning, then... the element should be removed!

It makes no sense at all having a long list of empty LI elements; if what you want is that in the layout of the page the list is never shorter that x lines, then you should add something like

```<code>ul {min-height:10em;}
</code>```

in your style sheet.

Adding elements to the HTML only to achieve a specific layout is never a good idea, and trying to add placeholder elements just to then remove them afterwards is a bad idea, not only for the semantic aspect of your HTML code but also for the responsiveness of your user interface to user commands! :)

Body:
I'm working with fat free framework and am currently working on a bracket generation for competitions.

What I do is passing multiple competitors (from different "layers") to the view to display them in a tree. The basic styling comes from this codepen.

Now the problem is, that I don't know every field from beginning on, as the result of the first two competitions decide how the next level looks (quarter finals in that case). The problem is though, that if I don't put the fields there, then the complete layout is destroyed, thats why I put empty
 elements for the layer, where the competitors are not clear so far, just like so:

Same for semi finals and finals then, just with 2 and 1
s then.

Now in some of the cells of quarter/seminfinals I already have something in my database. So for example, if there's 8 competitions in "layer1", then I would have 4 empty fields in "layer2", respectively in the quarter finals. These 4 fields have to be predefined in order to keep the layout. Now maybe I only have 1 or 2 of these fields filled already, because the other competitions are not over yet.

So I have to always predefine the fields like in the code above. Now the question is: How do I either replace one empty
 with the filled one or alternatively, how do I fill the empty
 with information, if provided.

      <repeat group="{{ @bracket }}" value="{{ @item }}">
        <check if="{{@item.layer == 2}}">

{{ @item.Vorname1  }} {{ @item.Name1  }} <a href="/getFighterInformation/{{@item.fighter1ID}}"

{{ @item.Vorname2  }} {{ @item.Name2  }} <a href="/getFighterInformation/{{@item.fighter2ID}}"

  </check>
    </repeat>

That's an example for layer 2 with 8 competitions in layer 1.

I hope you get what I mean, but its pretty hard to explain...

So summarized, the question is: Is it possible to predefine list elements and then fill or replace them, if an if-condition matches?

EDIT:

This is what I get from database, filled into the bracket variable:

array(4){
   [
      0
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "1"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "21"      [
         "Vorname1"
      ]      => string(5) "one"      [
         "Name1"
      ]      => string(4) "one"      [
         "Geburtsdatum1"
      ]      => string(10) "1999-04-04"      [
         "fighter1Pos"
      ]      => string(1) "0"      [
         "fighter2ID"
      ]      => string(2) "19"      [
         "Vorname2"
      ]      => string(8) "two"      [
         "Name2"
      ]      => string(4) "two"      [
         "Geburtsdatum2"
      ]      => string(10) "1988-12-11"      [
         "fighter2Pos"
      ]      => string(1) "1"      [
         "result"
      ]      => string(1) "0"
   }   [
      1
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "2"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "25"      [
         "Vorname1"
      ]      => string(5) "three"      [
         "Name1"
      ]      => string(4) "three"      [
         "Geburtsdatum1"
      ]      => string(10) "1988-08-18"      [
         "fighter1Pos"
      ]      => string(1) "2"      [
         "fighter2ID"
      ]      => string(2) "24"      [
         "Vorname2"
      ]      => string(5) "four"      [
         "Name2"
      ]      => string(4) "four"      [
         "Geburtsdatum2"
      ]      => string(10) "1985-08-17"      [
         "fighter2Pos"
      ]      => string(1) "3"      [
         "result"
      ]      => string(1) "0"
   }   [
      2
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "3"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "23"      [
         "Vorname1"
      ]      => string(5) "five"      [
         "Name1"
      ]      => string(4) "five"      [
         "Geburtsdatum1"
      ]      => string(10) "1966-06-16"      [
         "fighter1Pos"
      ]      => string(1) "4"      [
         "fighter2ID"
      ]      => string(2) "20"      [
         "Vorname2"
      ]      => string(8) "six"      [
         "Name2"
      ]      => string(4) "six"      [
         "Geburtsdatum2"
      ]      => string(10) "1966-03-03"      [
         "fighter2Pos"
      ]      => string(1) "5"      [
         "result"
      ]      => string(1) "0"
   }   [
      3
   ]   => array(15)   {
      [
         "ID"
      ]      => string(1) "4"      [
         "eventID"
      ]      => string(1) "1"      [
         "kategorie"
      ]      => string(4) "FA62"      [
         "ebene"
      ]      => string(1) "3"      [
         "fighter1ID"
      ]      => string(2) "18"      [
         "Vorname1"
      ]      => string(6) "seven"      [
         "Name1"
      ]      => string(4) "seven"      [
         "Geburtsdatum1"
      ]      => string(10) "1985-08-17"      [
         "fighter1Pos"
      ]      => string(1) "6"      [
         "fighter2ID"
      ]      => string(2) "22"      [
         "Vorname2"
      ]      => string(9) "eight"      [
         "Name2"
      ]      => string(4) "eight"      [
         "Geburtsdatum2"
      ]      => string(10) "1995-09-15"      [
         "fighter2Pos"
      ]      => string(1) "7"      [
         "result"
      ]      => string(1) "0"
   }
}

One box should contain one fighter only, not two fighters. So each array element represents one fight, containing two fighters (referencable by fighter1ID/fighter2ID, respectively Name1, Name2, etc.). fighter1Pos and fighter2Pos then, together with the value "ebene", which is the layer (3, 2, 1 or 0), determine the position in the bracket, so layer 3 with fighter1Pos 7 would be the last "box" in the layer 3 (counting from 0 - 7).

Body:
I think you're approaching the problem in the wrong way: if an element doesn't have any content or meaning, then... the element should be removed!

It makes no sense at all having a long list of empty LI elements; if what you want is that in the layout of the page the list is never shorter that x lines, then you should add something like

ul {min-height:10em;}

in your style sheet.

Adding elements to the HTML only to achieve a specific layout is never a good idea, and trying to add placeholder elements just to then remove them afterwards is a bad idea, not only for the semantic aspect of your HTML code but also for the responsiveness of your user interface to user commands! :)


问:
Is it possible to determine if a named window is open in JavaScript?
I'm working on an inter-site single-sign-on project and have had a pretty little problem dropped in my lap.  When a user logs out of the "parent" site, a particular page needs to be loaded in the popup window containing the "child" site.  However, I can't store a reference to the return value of window.open(…), because the user must be allowed to navigate wherever they like on each site before logging out.

This would be easy if I could assume that the child site is always open, as another window.open(…) to the same named window would change its URL.  However, the popup cannot be caused to appear if it isn't already open (not all users have access to the child site).

I think this gives me two conflicting scenarios.  When the user visits the child site:

User logs in to parent site.

User clicks link for child site

Child site appears in a window named "child_popup".

User browses far and wide in the parent site, forgetting that the child window exists.

User logs out of parent site.

Child popup is redirected to the child site's logout page.

And when the user does not or cannot visit the child site:

User logs in to parent site.

User browses far and wide in the parent site.

User logs out of the parent site.

No popup should appear!

So my limitations are:

I cannot store a reference to the window in JS, as the user may navigate to any number of pages between visiting the child site and logging out.

I have zero control over the contents of the child site (my employer runs the parent site).

The parent site cannot be converted to frames to provide a "global" JS scope. :-)

I was not able to find any relevant resources on Google or SO.  Is there a way to accomplish this?

答:
It sounds like you are in control of the contents of the child window...  If so, you could try setting "window.opener.some_attr = true", when you first load the child window.

Thus your code in the parent window could do "if (window.some_attr) window.open(...)" or the converse "if (!window.some_attr) alert('no access')..."

OwnerDisplayName: Ben Blank

ContentLicense: CC BY-SA 2.5


问:
Size-limited queue that holds last N elements in Java
A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.

Of course, it's trivial to implement it manually:

```<code>import java.util.LinkedList;

public class LimitedQueue<E> extends LinkedList<E> {
    private int limit;

    public LimitedQueue(int limit) {
        this.limit = limit;
    }

    @Override
    public boolean add(E o) {
        super.add(o);
        while (size() > limit) { super.remove(); }
        return true;
    }
}
</code>```

As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?

答:
You can use a MinMaxPriorityQueue from Google Guava, from the javadoc:

A min-max priority queue can be configured with a maximum size. If so, each time the size of the queue exceeds that value, the queue automatically removes its greatest element according to its comparator (which might be the element that was just added). This is different from conventional bounded queues, which either block or reject new elements when full.

Body:
A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.

Of course, it's trivial to implement it manually:

import java.util.LinkedList;

public class LimitedQueue<E> extends LinkedList<E> {
    private int limit;

    public LimitedQueue(int limit) {
        this.limit = limit;
    }

    @Override
    public boolean add(E o) {
        super.add(o);
        while (size() > limit) { super.remove(); }
        return true;
    }
}

As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?


问:
Flutter: Play sound on button press
I'm very new to programing and especially flutter. I want to write an soundboard, basically a list of buttons and the job of each button is to play a sound that i have on my PC when they are pressed. I've already done the design with a list view and some material buttons but I don't know how to make them play sounds when I press them. Can some one help me?</p>

答:
Add audioplayers as a dependency and your audio file to pubspec.yaml file like this:

dependencies:
  audioplayers: ^1.0.1

flutter:
  assets:
    - assets/audio/my_audio.mp3
```
<p><strong>Full code (Null-safe):</strong></p>
<pre class="lang-dart prettyprint-override"><code>class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ElevatedButton(
        onPressed: () => AudioPlayer().play(AssetSource('audio/my_audio.mp3'));
        child: Text('Play'),
      ),
    );
  }
}
</code>```

Title: Flutter: Play sound on button press

Body:
Add audioplayers as a dependency and your audio file to pubspec.yaml file like this:

dependencies:
  audioplayers: ^1.0.1

flutter:
  assets:
    - assets/audio/my_audio.mp3

Full code (Null-safe):

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ElevatedButton(
        onPressed: () => AudioPlayer().play(AssetSource('audio/my_audio.mp3'));
        child: Text('Play'),
      ),
    );
  }
}


问:
Removing the duplicates from an array of objects
Duplicate values are being storing into an array of object

Based on the given userID need to out the duplicate userId,
if it exist do nothing, else push that userIdinto the teamSocketsList array

But with the below piece of code duplicate values are being stored into an array teamSocketsList

```<code>var  TeamUser = {
    userId : userID,
    socketId : socket.id
}

var i = $.inArray( userID, teamSocketsList );
if(i == -1){
    teamSocketsList.push(TeamUser);
}else{
        teamSocketsList = jQuery.grep(teamSocketsList, function(value) {
        return value != userID;
    });
}
</code>```

Actual Result:

```<code>[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
</code>```

Expected Result:

```<code>[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
]
</code>```

Edit:

Here I'm expecting userID to be pushed in to an array teamSocketsList based on the condition, if at all the given userID matches in the present list should return false or do nothing. Otherwise, (iff, it's not at all included then) store it into an array with the auto-generated socketId value

The logic which I had tried to implement was to check whether if that array is empty or not and then, traverse all the elements in the array list so that whenever userID were given as an input it must check the condition and then push that element.

Based on the present answers put up, it'll store the duplicate values and then sort it on and assign it back to teamSocketsList, that's fine.

答:
How about this function where you pass in your array and the key to get your result

        const convertArrayToObjecByID = ({ array, key }) =>
          array.reduce((obj, item) => {
                return { ...obj, [item[key]]: item };
              }, {})

        const input = [
            {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
            {"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
            {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
            {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
        ]
        const myObject = convertArrayToObjecByID({ array:input, key:'userId' })
console.log({myObject})
//then if you want it as an array
    console.log(Object.keys(myObject).map(item => myObject[item]))
        ```

Body:
Duplicate values are being storing into an array of object

Based on the given userID need to out the duplicate userId,
if it exist do nothing, else push that userIdinto the teamSocketsList array

But with the below piece of code duplicate values are being stored into an array teamSocketsList

var  TeamUser = {
    userId : userID,
    socketId : socket.id
}

var i = $.inArray( userID, teamSocketsList );
if(i == -1){
    teamSocketsList.push(TeamUser);
}else{
        teamSocketsList = jQuery.grep(teamSocketsList, function(value) {
        return value != userID;
    });
}

Actual Result:

[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]

Expected Result:

[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
]

Edit:

Here I'm expecting userID to be pushed in to an array teamSocketsList based on the condition, if at all the given userID matches in the present list should return false or do nothing. Otherwise, (iff, it's not at all included then) store it into an array with the auto-generated socketId value

The logic which I had tried to implement was to check whether if that array is empty or not and then, traverse all the elements in the array list so that whenever userID were given as an input it must check the condition and then push that element.

Based on the present answers put up, it'll store the duplicate values and then sort it on and assign it back to teamSocketsList, that's fine.


问:
How do i fix " Dictionary literal contains duplicate keys "?
I am trying to sent my parameter through alamofire and in my parameters, there is a duplicate key. I need that key to be passed but whenever i try it , the error pops up.

```<code>let param : [String: Any] = ["contactPerson": [ "email":[ "email": contactemail], "markedForSendingRezInfo": false,"preferred": false,"shareMarketInd": false], "personName": ["givenName": contactname,"shareMarketInd": false,"surname": contactlastname],"phoneNumber":["countryCode": contactcountrycode,"markedForSendingRezInfo": false,"preferred": false,"shareMarketInd": false,"subscriberNumber": contactphone],"shareMarketInd": false,"useForInvoicing": false,"curr":"USD","flight1" : selectedflightjson,"flight1" : selectedflightjsonRM,"passengers":[passengerparameterarray],"pwd": password,"requestPurpose": "MODIFY_PERMANENTLY_AND_CALC","unm": username
        ]
</code>```

This is my code and "email" : ["email".. comes twice. How do i fix it? i went to few questions in StackOverflow but they all talk about getting this kind of response from server. But here i am trying to sent it to the server.

So how do i fix this?

```<code>{
    "contactPerson": {
        "email": {
            "email": "a@gmail.com",
            "markedForSendingRezInfo": false,
            "preferred": false,
            "shareMarketInd": false
        },
        "personName": {
            "givenName": "v",
            "shareMarketInd": false,
            "surname": "j"
        },
        "phoneNumber": {
            "countryCode": "1",
            "markedForSendingRezInfo": false,
            "preferred": false,
            "shareMarketInd": false,
            "subscriberNumber": "123456789"
        },
        "shareMarketInd": false,
        "useForInvoicing": false
    },

</code>```

This is a part of my json.  Also [passengerparameterarray] has the same issue, will it work if i covert  [passengerparameterarray] into a json and pass it to this parameters? Im already passing 'selectedflightjson' as a Json, since this is a soap api.

Thanks.

答:
You have to manage your object as follows:</p>

```<code>    let param : [String: Any] =
        [
            "contactPerson": [
                "email": [
                    "email": contactemail,
                    "markedForSendingRezInfo": false,
                    "preferred": false,
                    "shareMarketInd": false
                ],
            "personName": [
                "givenName": contactname,
                "shareMarketInd": false,
                "surname": contactlastname
            ],
            "phoneNumber": [
                "countryCode": contactcountrycode,
                "markedForSendingRezInfo": false,
                "preferred": false,
                "shareMarketInd": false,
                "subscriberNumber": contactphone
            ],
            "passengers": [
                passengerparameterarray
            ],
            "shareMarketInd": false,
            "useForInvoicing": false,
            "curr": "USD",
            "flight1": selectedflightjson,
            "flight2": selectedflightjsonRM,
            "pwd": password,
            "requestPurpose": "MODIFY_PERMANENTLY_AND_CALC",
            "unm": username
    ]
</code>```

Body:
I am trying to sent my parameter through alamofire and in my parameters, there is a duplicate key. I need that key to be passed but whenever i try it , the error pops up.

let param : [String: Any] = ["contactPerson": [ "email":[ "email": contactemail], "markedForSendingRezInfo": false,"preferred": false,"shareMarketInd": false], "personName": ["givenName": contactname,"shareMarketInd": false,"surname": contactlastname],"phoneNumber":["countryCode": contactcountrycode,"markedForSendingRezInfo": false,"preferred": false,"shareMarketInd": false,"subscriberNumber": contactphone],"shareMarketInd": false,"useForInvoicing": false,"curr":"USD","flight1" : selectedflightjson,"flight1" : selectedflightjsonRM,"passengers":[passengerparameterarray],"pwd": password,"requestPurpose": "MODIFY_PERMANENTLY_AND_CALC","unm": username
        ]

This is my code and "email" : ["email".. comes twice. How do i fix it? i went to few questions in StackOverflow but they all talk about getting this kind of response from server. But here i am trying to sent it to the server.

So how do i fix this?

{
    "contactPerson": {
        "email": {
            "email": "a@gmail.com",
            "markedForSendingRezInfo": false,
            "preferred": false,
            "shareMarketInd": false
        },
        "personName": {
            "givenName": "v",
            "shareMarketInd": false,
            "surname": "j"
        },
        "phoneNumber": {
            "countryCode": "1",
            "markedForSendingRezInfo": false,
            "preferred": false,
            "shareMarketInd": false,
            "subscriberNumber": "123456789"
        },
        "shareMarketInd": false,
        "useForInvoicing": false
    },

This is a part of my json.  Also [passengerparameterarray] has the same issue, will it work if i covert  [passengerparameterarray] into a json and pass it to this parameters? Im already passing 'selectedflightjson' as a Json, since this is a soap api.

Thanks.

Body:
You have to manage your object as follows:

    let param : [String: Any] =
        [
            "contactPerson": [
                "email": [
                    "email": contactemail,
                    "markedForSendingRezInfo": false,
                    "preferred": false,
                    "shareMarketInd": false
                ],
            "personName": [
                "givenName": contactname,
                "shareMarketInd": false,
                "surname": contactlastname
            ],
            "phoneNumber": [
                "countryCode": contactcountrycode,
                "markedForSendingRezInfo": false,
                "preferred": false,
                "shareMarketInd": false,
                "subscriberNumber": contactphone
            ],
            "passengers": [
                passengerparameterarray
            ],
            "shareMarketInd": false,
            "useForInvoicing": false,
            "curr": "USD",
            "flight1": selectedflightjson,
            "flight2": selectedflightjsonRM,
            "pwd": password,
            "requestPurpose": "MODIFY_PERMANENTLY_AND_CALC",
            "unm": username
    ]


问:
replace spaces with null value using regexp_replace if i have multiple
How to replace spaces with Null if i have spaces in multiple column.

```<code>Input Dataset which i have
+---+-----++----+
| Id|col_1|col_2|
+---+-----+-----+
|  0|104  |     |
|  1|     |     |
+---+-----+-----+
</code>```

```<code>import org.apache.spark.sql.functions._

val test = df.withColumn("col_1","col_2", regexp_replace(df("col_1","col_1"), "^\\s*", lit(Null)))
test.filter("col_1,col_2 is null").show()
</code>```

Output Dataset:

```<code>+---+-----++----+
| Id|col_1|col_2|
+---+-----+-----+
|  0|104  | Null|
|  1|Null | Null|
+---+-----+-----+
</code>```

答:
use one withColumn for each column:

```<code>import org.apache.spark.sql.functions._
val df = List(("0", "104", "    "), ("1", " ", "")).toDF("Id","col_1", "col_2")

val test = df
  .withColumn("col_1", when(regexp_replace (col("col_1"), "\\s+", "") === "", null).otherwise(col("col_1")))
  .withColumn("col_2", when(regexp_replace (col("col_2"), "\\s+", "") === "", null).otherwise(col("col_2")))
  .show
</code>```

Result

```<code>+---+-----+-----+
| Id|col_1|col_2|
+---+-----+-----+
|  0|  104| null|
|  1| null| null|
+---+-----+-----+
</code>```

Body:
How to replace spaces with Null if i have spaces in multiple column.

Input Dataset which i have
+---+-----++----+
| Id|col_1|col_2|
+---+-----+-----+
|  0|104  |     |
|  1|     |     |
+---+-----+-----+

import org.apache.spark.sql.functions._

val test = df.withColumn("col_1","col_2", regexp_replace(df("col_1","col_1"), "^\\s*", lit(Null)))
test.filter("col_1,col_2 is null").show()

Output Dataset:

+---+-----++----+
| Id|col_1|col_2|
+---+-----+-----+
|  0|104  | Null|
|  1|Null | Null|
+---+-----+-----+

Body:
use one withColumn for each column:

import org.apache.spark.sql.functions._
val df = List(("0", "104", "    "), ("1", " ", "")).toDF("Id","col_1", "col_2")

val test = df
  .withColumn("col_1", when(regexp_replace (col("col_1"), "\\s+", "") === "", null).otherwise(col("col_1")))
  .withColumn("col_2", when(regexp_replace (col("col_2"), "\\s+", "") === "", null).otherwise(col("col_2")))
  .show

Result

+---+-----+-----+
| Id|col_1|col_2|
+---+-----+-----+
|  0|  104| null|
|  1| null| null|
+---+-----+-----+


问:
#1044 - access denied for user 'id9605813_band'@'%' to database 'information_schema'
I tried to move my data base from the localhost of phpmyadmin to another phpmyadmin using a free webhost,"000webhost" to be precise.

I tried just some simple code

```<code>CREATE TABLE `products` (
  `id` int(10) NOT NULL,
  `name` varchar(250) NOT NULL,
  `code` varchar(100) NOT NULL,
  `price` double(9,2) NOT NULL,
  `image` varchar(250) NOT NULL,
  `stock` int(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

and the only thing i get is this:

1044 - Access denied for user 'id9605813_band'@'% to database 'information_schema'

What can I do to fix this?

答: Your user doesn't have the correct user permissions to create edits/writes to the respective database. </p>

Body:
I tried to move my data base from the localhost of phpmyadmin to another phpmyadmin using a free webhost,"000webhost" to be precise.

I tried just some simple code

CREATE TABLE `products` (
  `id` int(10) NOT NULL,
  `name` varchar(250) NOT NULL,
  `code` varchar(100) NOT NULL,
  `price` double(9,2) NOT NULL,
  `image` varchar(250) NOT NULL,
  `stock` int(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

and the only thing i get is this:

1044 - Access denied for user 'id9605813_band'@'% to database 'information_schema'

What can I do to fix this?


问:
Nested classes with EMF/ecore
The ecore model editor does not allow adding classes as children to classes; doing so manually as in

```<code>...
<eClassifiers xsi:type="ecore:EClass" name="Test_Class">
    <eClassifiers xsi:type="ecore:EClass" name="Nested_Class"></eClassifiers>
    ...
</code>```

results in

```<code>org.eclipse.emf.ecore.xmi.FeatureNotFoundException: Feature 'eClassifiers' not found. (platform:/resource/EMFTestProject/model/My.ecore, 5, 62)
</code>```

Is there any way to model something like nested classes in ecore files?

答:
For creating a containment reference between two EClass objects in a metamodel you have to create A EReference ereference=EcoreFactory.eInstance.create and add is the the mother class : motherclass.getEReferences().add(ereference)

and put the children class as EType of the ereference. ereference.setEType()

Title: Nested classes with EMF/ecore

Body:
The ecore model editor does not allow adding classes as children to classes; doing so manually as in

...
<eClassifiers xsi:type="ecore:EClass" name="Test_Class">
    <eClassifiers xsi:type="ecore:EClass" name="Nested_Class"></eClassifiers>
    ...

results in

org.eclipse.emf.ecore.xmi.FeatureNotFoundException: Feature 'eClassifiers' not found. (platform:/resource/EMFTestProject/model/My.ecore, 5, 62)

Is there any way to model something like nested classes in ecore files?


问:
ArrayList Find First and Last Element
Good Evening,

I have an ArrayList (instantiated as ld_data) and I iterate forward and back looking / displaying to the user the element data. In this process I need to know when I am at the first element and the last. Detecting when I am at the last element I do as such:

```<code>if((index + 1) <= ld_data.size())
{
    ....
}
</code>```

This works because the size property also is the upper bound of the ArrayList. However detecting when I am at the first element is not as easy for me. The best I've been able to figure out is this which seems rather lame....but it works.

```<code>if((index - 1) >= (ld_data.size() - ld_data.size()))
{
    ....
}
</code>```

In the C# .NET world we have ArrayList.UpperBound or ArrayList.LowerBound is there something similiar in Java?

JB

EDIT: Further details. So for more information I am bound to a ListView. So when the user has scrolled to the first element of the list I want to show a msg "At start of list" and when they reach the end show "End of list". I know there is a scrollbar that makes this obvious I'm just trying to give an example of what I'm doing. So this check occurs in the "OnScroll" event.

答:
I would suggest you to use Google Guava for that. The getLast method will throw NoSuchElementException if the list is empty:

```<code>lastElement = Iterables.getLast(iterableList);
</code>```

And to get the first element:

```<code>firstElement = Iterables.getFirst(iterable, defaultValue)
</code>```

For more information about Java Collections, check it out.

Title: ArrayList Find First and Last Element

Body:
Good Evening,

I have an ArrayList (instantiated as ld_data) and I iterate forward and back looking / displaying to the user the element data. In this process I need to know when I am at the first element and the last. Detecting when I am at the last element I do as such:

if((index + 1) <= ld_data.size())
{
    ....
}

This works because the size property also is the upper bound of the ArrayList. However detecting when I am at the first element is not as easy for me. The best I've been able to figure out is this which seems rather lame....but it works.

if((index - 1) >= (ld_data.size() - ld_data.size()))
{
    ....
}

In the C# .NET world we have ArrayList.UpperBound or ArrayList.LowerBound is there something similiar in Java?

JB

EDIT: Further details. So for more information I am bound to a ListView. So when the user has scrolled to the first element of the list I want to show a msg "At start of list" and when they reach the end show "End of list". I know there is a scrollbar that makes this obvious I'm just trying to give an example of what I'm doing. So this check occurs in the "OnScroll" event.

Body:
I would suggest you to use Google Guava for that. The getLast method will throw NoSuchElementException if the list is empty:

lastElement = Iterables.getLast(iterableList);

And to get the first element:

firstElement = Iterables.getFirst(iterable, defaultValue)

For more information about Java Collections, check it out.


问:
Should I use Inner Join in this case?
I am working on a student attendance mini-project, and I don't know how to proceed for my database. I'm new to SQL and databases in general so this might seem dumb to you.

So, I want to do a database containing the table student, which contains :  student_id (primary key) , name (string) and attendance(boolean) (that's the bare minimum, i'll add more afterwards) and I want to register the daily attendance of the students. So I want to have all the students tied to every date of the week.

I created a date table in phpMyadmin but I don't know how to proceed to link them, i've tried an Inner Join and it was successful.

The problem is : If i want to add another line to the student table my table won't update, so is there a way to "automatically" tie all the students to the date table ?

Sorry if this seems confused I've tried my best to summarize it !

答:
Lets have some idea about tables should be there to implement a proper Student Attendance system in place. I have copied create script for some of my tables that used for maintaining Students record per course. I hope following sample Table scripts with relation will help you understanding regarding table structure and also to solve your issue.

Please be noted, That this table structures for your your reference only. You can add/remove tables/columns as per your requirement once you get an overall idea from this post.

```<code>CREATE TABLE `staff` (
  `id` int(11) NOT NULL,
  `type` varchar(200) DEFAULT NULL,
  `first_name` varchar(200) DEFAULT NULL,
  `last_name` varchar(200) DEFAULT NULL,
  `emal` varchar(200) DEFAULT NULL,
  `contact` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `batch` (
  `id` int(11) NOT NULL,
  `department` varchar(200) DEFAULT NULL,
  `details` varchar(200) DEFAULT NULL,
  `staff_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `batch_staff_idx` (`staff_id`),
  CONSTRAINT `batch_staff` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `student` (
  `id` int(11) NOT NULL,
  `batch_id` int(11) DEFAULT NULL,
  `first_name` varchar(200) DEFAULT NULL,
  `last_name` varchar(200) DEFAULT NULL,
  `email` varchar(200) DEFAULT NULL,
  `contact` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `batch_student_idx` (`batch_id`),
  CONSTRAINT `batch_student` FOREIGN KEY (`batch_id`) REFERENCES `batch` (`batch_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `course` (
  `id` int(11) NOT NULL,
  `name` varchar(200) DEFAULT NULL,
  `details` varchar(200) DEFAULT NULL,
  `staff_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `course_staff_idx` (`staff_id`),
  CONSTRAINT `course_staff` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `attendence` (
  `course_id` int(11) NOT NULL,
  `student_id` int(11) DEFAULT NULL,
  `class_date` date DEFAULT NULL,
  KEY `att_course_idx` (`course_id`),
  KEY `att_student_idx` (`student_id`),
  CONSTRAINT `att_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `att_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

Your required data will finally store into table Attendance. From this table data, you will be able to find list of students absent/present per date and per course. Remember, the attendance table should enrich daily from a automated OR a manual process.

Title: Should I use Inner Join in this case?

Body:
Lets have some idea about tables should be there to implement a proper Student Attendance system in place. I have copied create script for some of my tables that used for maintaining Students record per course. I hope following sample Table scripts with relation will help you understanding regarding table structure and also to solve your issue.

Please be noted, That this table structures for your your reference only. You can add/remove tables/columns as per your requirement once you get an overall idea from this post.

CREATE TABLE `staff` (
  `id` int(11) NOT NULL,
  `type` varchar(200) DEFAULT NULL,
  `first_name` varchar(200) DEFAULT NULL,
  `last_name` varchar(200) DEFAULT NULL,
  `emal` varchar(200) DEFAULT NULL,
  `contact` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `batch` (
  `id` int(11) NOT NULL,
  `department` varchar(200) DEFAULT NULL,
  `details` varchar(200) DEFAULT NULL,
  `staff_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `batch_staff_idx` (`staff_id`),
  CONSTRAINT `batch_staff` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `student` (
  `id` int(11) NOT NULL,
  `batch_id` int(11) DEFAULT NULL,
  `first_name` varchar(200) DEFAULT NULL,
  `last_name` varchar(200) DEFAULT NULL,
  `email` varchar(200) DEFAULT NULL,
  `contact` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `batch_student_idx` (`batch_id`),
  CONSTRAINT `batch_student` FOREIGN KEY (`batch_id`) REFERENCES `batch` (`batch_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `course` (
  `id` int(11) NOT NULL,
  `name` varchar(200) DEFAULT NULL,
  `details` varchar(200) DEFAULT NULL,
  `staff_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `course_staff_idx` (`staff_id`),
  CONSTRAINT `course_staff` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `attendence` (
  `course_id` int(11) NOT NULL,
  `student_id` int(11) DEFAULT NULL,
  `class_date` date DEFAULT NULL,
  KEY `att_course_idx` (`course_id`),
  KEY `att_student_idx` (`student_id`),
  CONSTRAINT `att_course` FOREIGN KEY (`course_id`) REFERENCES `course` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `att_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Your required data will finally store into table Attendance. From this table data, you will be able to find list of students absent/present per date and per course. Remember, the attendance table should enrich daily from a automated OR a manual process.


问:
Installing R 3.6 on Ubuntu disco 19.04
I have the new Ubuntu disco 19.04, and I followed the instructions here to install the new R 3.6.

However, after installing the key and adding the repository through:

```<code>sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu disco-cran35/'
</code>```

And running:

```<code>sudo apt update
sudo apt install r-base
</code>```

I get:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 r-base : Depends: r-base-core (>= 3.6.0-1cosmic) but 3.5.2-1build1 is to be installed
          Depends: r-recommended (= 3.6.0-1cosmic) but 3.5.2-1build1 is to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

I could install R through

```<code>sudo apt install r-base
</code>```

before adding the aforementioned repository, but version 3.5.2 is installed.

Does anyone have an idea how to install it without having to compile from source?

答:
I followed the same instructions, got R 3.5 as well.
Adding the repo's pubkey before running apt update got me R 3.6.

These should be the steps to install R 3.6 into a fresh Ubuntu 19.04:

```<code>sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu disco-cran35/'
sudo apt update
sudo apt install r-base-dev
</code>```

Changing the repository details allows installation onto other Ubuntu versions i.e. replace 'disco' with 'xenial' for Ubuntu 16.04.

Update Oct 2020: In the same vein (add repo, add repo keys, update, install), follow this tutorial at thinkr.fr by Sébastien Rochette to update Ubuntu to 20.* and R to 4.*
As a bonus, it comes with installation tips for dependencies of spatial packages.

Title: Installing R 3.6 on Ubuntu disco 19.04

Body:
I have the new Ubuntu disco 19.04, and I followed the instructions here to install the new R 3.6.

However, after installing the key and adding the repository through:

sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu disco-cran35/'

And running:

sudo apt update
sudo apt install r-base

I get:

Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 r-base : Depends: r-base-core (>= 3.6.0-1cosmic) but 3.5.2-1build1 is to be installed
          Depends: r-recommended (= 3.6.0-1cosmic) but 3.5.2-1build1 is to be installed
E: Unable to correct problems, you have held broken packages.

I could install R through

sudo apt install r-base

before adding the aforementioned repository, but version 3.5.2 is installed.

Does anyone have an idea how to install it without having to compile from source?

Body:
I followed the same instructions, got R 3.5 as well.
Adding the repo's pubkey before running apt update got me R 3.6.

These should be the steps to install R 3.6 into a fresh Ubuntu 19.04:

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu disco-cran35/'
sudo apt update
sudo apt install r-base-dev

Changing the repository details allows installation onto other Ubuntu versions i.e. replace 'disco' with 'xenial' for Ubuntu 16.04.

Update Oct 2020: In the same vein (add repo, add repo keys, update, install), follow this tutorial at thinkr.fr by Sébastien Rochette to update Ubuntu to 20.* and R to 4.*
As a bonus, it comes with installation tips for dependencies of spatial packages.


问:
Incorrect syntax near the keyword 'DECLARE' in view
Can someone please confirm how to get rid of the following error.</p>

```<code>DECLARE @StartDate DATETIME, @EndDate DATETIME
SET @StartDate = DATEADD(mm, DATEDIFF(mm, 0, getdate()) - 1, 0)
SET @EndDate = DATEADD(mm, 1, @StartDate)
SELECT
dbo.General_Ledger_Detail.Accounting_ID,
dbo.General_Ledger_Detail.Cost_Centre,
dbo.General_Ledger_Detail.Product_ID,

dbo.General_Ledger_Detail.Accounted_Amount AS Amount,
dbo.General_Ledger_Detail.Account_Name,
dbo.General_Ledger_Detail.Accounting_Date,

dbo.Account_Codes_Sales_OPEX$.[Opex Type],
dbo.LogSolOpexCC.Logistic_Solutions_Type

FROM
dbo.General_Ledger_Detail
INNER JOIN dbo.Account_Codes_Sales_OPEX$
ON dbo.General_Ledger_Detail.Accounting_ID =
    dbo.Account_Codes_Sales_OPEX$.[Account Code]
INNER JOIN dbo.LogSolOpexCC
ON dbo.General_Ledger_Detail.Cost_Centre = dbo.LogSolOpexCC.Cost_Centre

GROUP BY dbo.General_Ledger_Detail.Accounting_ID,
dbo.General_Ledger_Detail.Cost_Centre,
dbo.General_Ledger_Detail.Product_ID,

dbo.General_Ledger_Detail.Accounted_Amount,
dbo.General_Ledger_Detail.Account_Name,
dbo.General_Ledger_Detail.Accounting_Date,

dbo.Account_Codes_Sales_OPEX$.[Opex Type],
dbo.LogSolOpexCC.Logistic_Solutions_Type

HAVING (dbo.General_Ledger_Detail.Accounting_Date BETWEEN @startdate AND @enddate)
</code>```

答:
```<code>SELECT        dbo.General_Ledger_Detail.Accounting_ID, dbo.General_Ledger_Detail.Cost_Centre, dbo.General_Ledger_Detail.Product_ID,
                         dbo.General_Ledger_Detail.Accounted_Amount AS Amount, dbo.General_Ledger_Detail.Account_Name, dbo.General_Ledger_Detail.Accounting_Date,
                         dbo.Account_Codes_Sales_OPEX$.[Opex Type], dbo.LogSolOpexCC.Logistic_Solutions_Type
FROM            dbo.General_Ledger_Detail INNER JOIN
                         dbo.Account_Codes_Sales_OPEX$ ON dbo.General_Ledger_Detail.Accounting_ID = dbo.Account_Codes_Sales_OPEX$.[Account Code] INNER JOIN
                         dbo.LogSolOpexCC ON dbo.General_Ledger_Detail.Cost_Centre = dbo.LogSolOpexCC.Cost_Centre
GROUP BY dbo.General_Ledger_Detail.Accounting_ID, dbo.General_Ledger_Detail.Cost_Centre, dbo.General_Ledger_Detail.Product_ID,
                         dbo.General_Ledger_Detail.Accounted_Amount, dbo.General_Ledger_Detail.Account_Name, dbo.General_Ledger_Detail.Accounting_Date,
                         dbo.Account_Codes_Sales_OPEX$.[Opex Type], dbo.LogSolOpexCC.Logistic_Solutions_Type
HAVING        (dbo.General_Ledger_Detail.Accounting_Date BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0) AND DATEADD(mm, 1, GETDATE()))
</code>```

Body:
Can someone please confirm how to get rid of the following error.

DECLARE @StartDate DATETIME, @EndDate DATETIME
SET @StartDate = DATEADD(mm, DATEDIFF(mm, 0, getdate()) - 1, 0)
SET @EndDate = DATEADD(mm, 1, @StartDate)
SELECT
dbo.General_Ledger_Detail.Accounting_ID,
dbo.General_Ledger_Detail.Cost_Centre,
dbo.General_Ledger_Detail.Product_ID,

dbo.General_Ledger_Detail.Accounted_Amount AS Amount,
dbo.General_Ledger_Detail.Account_Name,
dbo.General_Ledger_Detail.Accounting_Date,

dbo.Account_Codes_Sales_OPEX$.[Opex Type],
dbo.LogSolOpexCC.Logistic_Solutions_Type

FROM
dbo.General_Ledger_Detail
INNER JOIN dbo.Account_Codes_Sales_OPEX$
ON dbo.General_Ledger_Detail.Accounting_ID =
    dbo.Account_Codes_Sales_OPEX$.[Account Code]
INNER JOIN dbo.LogSolOpexCC
ON dbo.General_Ledger_Detail.Cost_Centre = dbo.LogSolOpexCC.Cost_Centre

GROUP BY dbo.General_Ledger_Detail.Accounting_ID,
dbo.General_Ledger_Detail.Cost_Centre,
dbo.General_Ledger_Detail.Product_ID,

dbo.General_Ledger_Detail.Accounted_Amount,
dbo.General_Ledger_Detail.Account_Name,
dbo.General_Ledger_Detail.Accounting_Date,

dbo.Account_Codes_Sales_OPEX$.[Opex Type],
dbo.LogSolOpexCC.Logistic_Solutions_Type

HAVING (dbo.General_Ledger_Detail.Accounting_Date BETWEEN @startdate AND @enddate)


问:
Type 'string' is not assignable to type '"inherit" | "initial" | "unset" | "fixed" | "absolute" | "static" | "relative" | "sticky"'
I get the following error in my application (npm 5.4.2, react 15.4, typescript 2.5.3, webpack 2.2.1, webpack-dev-server 2.4.1).

This will work:

```<code><div style={{position: 'absolute'}}>working</div>
</code>```

This will not compile:

```<code>const mystyle = {
    position: 'absolute'
}

<div style={mystyle}>not working</div>
</code>```

The compile error is:

```<code>ERROR in ./src/components/Resource.tsx
(61,18): error TS2322: Type '{ style: { position: string; }; children: string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.
  Type '{ style: { position: string; }; children: string; }' is not assignable to type 'HTMLAttributes<HTMLDivElement>'.
    Types of property 'style' are incompatible.
      Type '{ position: string; }' is not assignable to type 'CSSProperties'.
        Types of property 'position' are incompatible.
          Type 'string' is not assignable to type '"inherit" | "initial" | "unset" | "fixed" | "absolute" | "static" | "relative" | "sticky"'.
webpack: Failed to compile.
</code>```

But what't the difference?
I can fix it with:

```<code>const mystyle = {
    position: 'absolute' as 'absolute'
}
</code>```

but is this a good solution?

I don't have this problem with other style/css properties.

I found a similar problem on github:
https://github.com/Microsoft/TypeScript/issues/11465
but if understand it right, it was a typescript bug in an ealier version.

Any help appreciated.

答:
Use the React.CSSProperties type:

```<code>import React, { CSSProperties } from "react";

const myStyles: CSSProperties = {
  position: 'absolute',
}
</code>```

Then just use the style as normal:

```<code><div style={myStyles} />
</code>```

Body:
I get the following error in my application (npm 5.4.2, react 15.4, typescript 2.5.3, webpack 2.2.1, webpack-dev-server 2.4.1).

This will work:

working

This will not compile:

const mystyle = {
    position: 'absolute'
}

not working

The compile error is:

ERROR in ./src/components/Resource.tsx
(61,18): error TS2322: Type '{ style: { position: string; }; children: string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.
  Type '{ style: { position: string; }; children: string; }' is not assignable to type 'HTMLAttributes<HTMLDivElement>'.
    Types of property 'style' are incompatible.
      Type '{ position: string; }' is not assignable to type 'CSSProperties'.
        Types of property 'position' are incompatible.
          Type 'string' is not assignable to type '"inherit" | "initial" | "unset" | "fixed" | "absolute" | "static" | "relative" | "sticky"'.
webpack: Failed to compile.

But what't the difference?
I can fix it with:

const mystyle = {
    position: 'absolute' as 'absolute'
}

but is this a good solution?

I don't have this problem with other style/css properties.

I found a similar problem on github:
https://github.com/Microsoft/TypeScript/issues/11465
but if understand it right, it was a typescript bug in an ealier version.

Any help appreciated.

Body:
Use the React.CSSProperties type:

import React, { CSSProperties } from "react";

const myStyles: CSSProperties = {
  position: 'absolute',
}

Then just use the style as normal:

<div style={myStyles} />


问:
Executing generic delegate prototype
I'm trying to write a utility class that will execute defined static methods to try and cut down on the boiler code and increase readability.

My idea stems from my current project of rewriting our aspx web services to a WCF service where all methods have a uniform boiler code pattern excluding the service request. The static methods don't currently exist on our existing objects as most of the logic lives within the web service method itself but should be easily transferable.

An example of what I have so far is below.

```<code>[DataContract]
public CustomObject CreateItem(int id, string name)
{
    return ExecuteMethod<CustomObject>(CustomObject.CreateItem, id, name);
}

protected static T ExecuteMethod<T>(Delegate methodToExecute, params object[] parameters)
{
    // Do some basic logging
    // Authenticate user

    try
    {
        if (methodToExecute == null)
        {
            throw new Exception();
        }

        if (methodToExecute.Method.ReturnType != typeof(T))
        {
            throw new Exception();
        }

        if (methodToExecute.Method.GetParameters().Length != parameters.Length)
        {
            throw new Exception();
        }

        return (T)methodToExecute.Method.Invoke(methodToExecute, parameters);
    }
    catch
    {
        throw new SoapException("There was an error", SoapException.ClientFaultCode);
    }
}

public class CustomObject
{
    [DataMemeber]
    public int Id { get; set; }
    [DataMember]
    pubic string Name { get; set; }

    internal static Delegate CreateItem = new Func<int, string, CustomObject>(
        (id, name) =>
        {
            return new CustomObject() { Id = 1, Name = name };
        }
    );
}
</code>```

My example above should illustrate what I'm trying to achieve. However, where I feel this approach is failing so far is that the parameters passed to the generic method are not typed and could result in runtime errors (both for return type and parameter types)

I have added some basic checks such as checking the return type of the methodInfo is of the same type as T and that the number of parameters of the method is equal to the number of parameters passed in but it doesn't feel 'safe'.

Am I on the right track or should I look into an alternative solution?

This is just a prototype at the moment as I'm just starting to think about the re-design.

答:
It looks to me as if the only benefit of calling it through your method is to translate any exception into a SoapException. You can do that more easily like this:

```<code>protected static T ExecuteMethod<T>(Func<T> function)
{
    try
    {
        return function();
    }
    catch
    {
        throw new SoapException("There was an error",
                                SoapException.ClientFaultCode);
    }
}
</code>```

Then the calling code would look like this:

```<code>public CustomObject CreateItem(int id, string name)
{
    return ExecuteMethod(() => CustomObject.CreateItem(id, name));
}
</code>```

(I hope in the real code you've got some logging for the exception case, btw.)

Title: Executing generic delegate prototype

Body:
I'm trying to write a utility class that will execute defined static methods to try and cut down on the boiler code and increase readability.

My idea stems from my current project of rewriting our aspx web services to a WCF service where all methods have a uniform boiler code pattern excluding the service request. The static methods don't currently exist on our existing objects as most of the logic lives within the web service method itself but should be easily transferable.

An example of what I have so far is below.

[DataContract]
public CustomObject CreateItem(int id, string name)
{
    return ExecuteMethod<CustomObject>(CustomObject.CreateItem, id, name);
}

protected static T ExecuteMethod<T>(Delegate methodToExecute, params object[] parameters)
{
    // Do some basic logging
    // Authenticate user

    try
    {
        if (methodToExecute == null)
        {
            throw new Exception();
        }

        if (methodToExecute.Method.ReturnType != typeof(T))
        {
            throw new Exception();
        }

        if (methodToExecute.Method.GetParameters().Length != parameters.Length)
        {
            throw new Exception();
        }

        return (T)methodToExecute.Method.Invoke(methodToExecute, parameters);
    }
    catch
    {
        throw new SoapException("There was an error", SoapException.ClientFaultCode);
    }
}

public class CustomObject
{
    [DataMemeber]
    public int Id { get; set; }
    [DataMember]
    pubic string Name { get; set; }

    internal static Delegate CreateItem = new Func<int, string, CustomObject>(
        (id, name) =>
        {
            return new CustomObject() { Id = 1, Name = name };
        }
    );
}

My example above should illustrate what I'm trying to achieve. However, where I feel this approach is failing so far is that the parameters passed to the generic method are not typed and could result in runtime errors (both for return type and parameter types)

I have added some basic checks such as checking the return type of the methodInfo is of the same type as T and that the number of parameters of the method is equal to the number of parameters passed in but it doesn't feel 'safe'.

Am I on the right track or should I look into an alternative solution?

This is just a prototype at the moment as I'm just starting to think about the re-design.

Body:
It looks to me as if the only benefit of calling it through your method is to translate any exception into a SoapException. You can do that more easily like this:

protected static T ExecuteMethod<T>(Func<T> function)
{
    try
    {
        return function();
    }
    catch
    {
        throw new SoapException("There was an error",
                                SoapException.ClientFaultCode);
    }
}

Then the calling code would look like this:

public CustomObject CreateItem(int id, string name)
{
    return ExecuteMethod(() => CustomObject.CreateItem(id, name));
}

(I hope in the real code you've got some logging for the exception case, btw.)


问:
How to Fix 'Key Errors' in pandas lib
I'm trying to import a csv file, using the pandas library. And then I want to create a data frame with two columns of the original file. One I want to name is volume and other trades. The 'preco_ordem' column is the one I want to turn into trades. But the following error happens: KeyError: 'preco_ordem'

I've changed the name of the variables and it worked with the volume data.frame.

```<code>from itertools import zip_longest
import itertools
import pandas
import numpy as np
import matplotlib.pyplot as plt

all_trades = pandas.read_csv('./ccmx18hf .csv', parse_dates={'Date': [0,1]}, index_col=0, encoding = 'unicode_escape')
print (all_trades.head())

volume = (all_trades['quant_total'])
print(volume.head())
trades = (all_trades['preco_ordem'])

def cleanup(x):
    if isinstance(x, str) and 'e-' in x:
        return 0
    else:
        return float(x)

volume = volume.apply(lambda x: cleanup(x))
volume = volume.astype(np.float32)
</code>```

This is my data

```<code>                 order_side preÂ�o_ordem  quant_total  quant_neg status
Date
02/07/2018 08:58:25   Sell       39,36            4        0.0   New
02/07/2018 08:59:53   Sell          40            1        0.0   New
02/07/2018 08:59:56   Sell       39,93            1        0.0   New
02/07/2018 09:00:22    Buy        39,1           10        0.0   New
02/07/2018 09:00:26    Buy       39,11            1        0.0   New
Date
02/07/2018 08:58:25     4
02/07/2018 08:59:53     1
02/07/2018 08:59:56     1
02/07/2018 09:00:22    10
02/07/2018 09:00:26     1
Name: quant_total, dtype: int64
</code>```

This is my error

```<code>Traceback (most recent call last):
  File "/home/operacao/miniconda2/envs/py3env/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2657, in get_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'preco_ordem'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "ccmx.py", line 15, in <module>
    trades = (all_trades['preco_ordem'])
  File "/home/operacao/miniconda2/envs/py3env/lib/python3.7/site-packages/pandas/core/frame.py", line 2927, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/home/operacao/miniconda2/envs/py3env/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2659, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'preco_ordem'
</code>```

答:
Check your column name using below:

all_trades.columns
```

Title: How to Fix 'Key Errors' in pandas lib

Body:
I'm trying to import a csv file, using the pandas library. And then I want to create a data frame with two columns of the original file. One I want to name is volume and other trades. The 'preco_ordem' column is the one I want to turn into trades. But the following error happens: KeyError: 'preco_ordem'

I've changed the name of the variables and it worked with the volume data.frame.

from itertools import zip_longest
import itertools
import pandas
import numpy as np
import matplotlib.pyplot as plt

all_trades = pandas.read_csv('./ccmx18hf .csv', parse_dates={'Date': [0,1]}, index_col=0, encoding = 'unicode_escape')
print (all_trades.head())

volume = (all_trades['quant_total'])
print(volume.head())
trades = (all_trades['preco_ordem'])

def cleanup(x):
    if isinstance(x, str) and 'e-' in x:
        return 0
    else:
        return float(x)

volume = volume.apply(lambda x: cleanup(x))
volume = volume.astype(np.float32)

This is my data

                 order_side preÂ�o_ordem  quant_total  quant_neg status
Date
02/07/2018 08:58:25   Sell       39,36            4        0.0   New
02/07/2018 08:59:53   Sell          40            1        0.0   New
02/07/2018 08:59:56   Sell       39,93            1        0.0   New
02/07/2018 09:00:22    Buy        39,1           10        0.0   New
02/07/2018 09:00:26    Buy       39,11            1        0.0   New
Date
02/07/2018 08:58:25     4
02/07/2018 08:59:53     1
02/07/2018 08:59:56     1
02/07/2018 09:00:22    10
02/07/2018 09:00:26     1
Name: quant_total, dtype: int64

This is my error

Traceback (most recent call last):
  File "/home/operacao/miniconda2/envs/py3env/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2657, in get_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'preco_ordem'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "ccmx.py", line 15, in <module>
    trades = (all_trades['preco_ordem'])
  File "/home/operacao/miniconda2/envs/py3env/lib/python3.7/site-packages/pandas/core/frame.py", line 2927, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/home/operacao/miniconda2/envs/py3env/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2659, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'preco_ordem'


问:
Why is asyncio queue await get() blocking?
Why is await queue.get() blocking?

import asyncio

async def producer(queue, item):
    await queue.put(item)

async def consumer(queue):
    val = await queue.get()
    print("val = %d" % val)

async def main():
    queue = asyncio.Queue()
    await consumer(queue)
    await producer(queue, 1)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```

<p>If I call the <strong>producer()</strong> before <strong>consumer()</strong>, it works fine
That is to say, the following works fine.</p>

<pre class="lang-py prettyprint-override"><code>async def main():
    queue = asyncio.Queue()
    await producer(queue, 1)
    await consumer(queue)
</code>```

Why isn't await queue.get() yielding control back to the event loop so that the producer coroutine can run which will populate the queue so that queue.get() can return.

答:
You should use .run_until_complete() with .gather()

Here is your updated code:

```<code>import asyncio

async def producer(queue, item):
    await queue.put(item)

async def consumer(queue):
    val = await queue.get()
    print("val = %d" % val)

queue = asyncio.Queue()
loop = asyncio.get_event_loop()
loop.run_until_complete(
    asyncio.gather(consumer(queue), producer(queue, 1))
)
loop.close()
</code>```

Out:

```<code>val = 1
</code>```

Also you could use .run_forever() with .create_task()

So your code snippet will be:

```<code>import asyncio

async def producer(queue, item):
    await queue.put(item)

async def consumer(queue):
    val = await queue.get()
    print("val = %d" % val)

queue = asyncio.Queue()
loop = asyncio.get_event_loop()
loop.create_task(consumer(queue))
loop.create_task(producer(queue, 1))
try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.close()
</code>```

Out:

```<code>val = 1
</code>```

Body:
Why is await queue.get() blocking?

import asyncio

async def producer(queue, item):
    await queue.put(item)

async def consumer(queue):
    val = await queue.get()
    print("val = %d" % val)

async def main():
    queue = asyncio.Queue()
    await consumer(queue)
    await producer(queue, 1)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

If I call the producer() before consumer(), it works fine
That is to say, the following works fine.

async def main():
    queue = asyncio.Queue()
    await producer(queue, 1)
    await consumer(queue)

Why isn't await queue.get() yielding control back to the event loop so that the producer coroutine can run which will populate the queue so that queue.get() can return.

Body:
You should use .run_until_complete() with .gather()

Here is your updated code:

import asyncio

async def producer(queue, item):
    await queue.put(item)

async def consumer(queue):
    val = await queue.get()
    print("val = %d" % val)

queue = asyncio.Queue()
loop = asyncio.get_event_loop()
loop.run_until_complete(
    asyncio.gather(consumer(queue), producer(queue, 1))
)
loop.close()

Out:

val = 1

Also you could use .run_forever() with .create_task()

So your code snippet will be:

import asyncio

async def producer(queue, item):
    await queue.put(item)

async def consumer(queue):
    val = await queue.get()
    print("val = %d" % val)

queue = asyncio.Queue()
loop = asyncio.get_event_loop()
loop.create_task(consumer(queue))
loop.create_task(producer(queue, 1))
try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.close()

Out:

val = 1


问:
Java get value by key in JSON data
```<code>[
{
    "boylam":31.8039,
    "enlem":40.5906,
    "il":"",
    "ilPlaka":"",
    "ilce":"",
    "oncelik":0,
    "yukseklik":2052,
    "aciklama":"",
    "modelId":124774,
    "gps":0
}]
</code>```

Hi I have such a JSON data in my hand. I had a hard time getting the data out of here. For example, how do I print the "boylam" option in JSON data?

答:
using com.google.gson.Gson class, you can do this.</p>

```<code>Gson gson= new Gson();

JSONObject json=new JSONObject();
json.put("boylam", "31.8039"); // this is your json object

Map map=gson.fromJson(json.toString(), Map.class);
System.out.println(map.get("boylam")); //ouput 31.8039
</code>```

Title: Java get value by key in JSON data

Body:
[
{
    "boylam":31.8039,
    "enlem":40.5906,
    "il":"",
    "ilPlaka":"",
    "ilce":"",
    "oncelik":0,
    "yukseklik":2052,
    "aciklama":"",
    "modelId":124774,
    "gps":0
}]

Hi I have such a JSON data in my hand. I had a hard time getting the data out of here. For example, how do I print the "boylam" option in JSON data?

Body:
using com.google.gson.Gson class, you can do this.

Gson gson= new Gson();

JSONObject json=new JSONObject();
json.put("boylam", "31.8039"); // this is your json object

Map map=gson.fromJson(json.toString(), Map.class);
System.out.println(map.get("boylam")); //ouput 31.8039


问:
webpack-dev-server set cookie via proxy
We have setup our development environment with webpack-dev-server. We use its proxy config to communicate with the backend.

We have a common login page in the server which we use in all our applications. We it is called, it sets a session cookie which expected to passed with subsequent requests. We have used the following config but the cookie is not set in the browser for some reason. I can see it in response header in the network tab of dev tool.

```<code>const config = {
  devServer: {
     index: "/",
     proxy: {
     "/rest_end_point/page": {
           target: "https://middleware_server",
           secure : false
     },
     "/": {
           target: "https://middleware_server/app/login",
           secure : false
    },
}
</code>```

The https://middleware_server/app/login endpoint returns the login page with the set-cookie header.

The proxy is used to avoid CORS errors when accessing login pages and API calls.

Upto this point no code from the application is executed. Do we have to do something in the coomon login page to get the cookie set?

the application is written with React.

Any help would be appreciated.

答:
I have the same use case and this is what I have done.

In my case, I have multiple proxy targets so I have configured the JSON (ProxySession.json) accordingly.

Note: This approach is not dynamic. you need to get JSESSIONID manually(session ID) for the proxy the request.

login into an application where you want your application to proxy.
Get the JSESSIONID and add it in JSON file or replace directly in onProxyReq function and then run your dev server.

Example:

Webpack-dev.js

```<code> // Webpack-dev.js
const ProxySession = require("./ProxySession");

config = {
  output: {..........},
  plugins: [.......],
  resolve: {......},
  module: {
    rules: [......]
  },
  devServer: {
    port: 8088,
    host: "0.0.0.0",
    disableHostCheck: true,
    proxy: {
        "/service/**": {
            target: ProxySession.proxyTarget,
            changeOrigin: true,
            onProxyReq: function(proxyReq) {
                proxyReq.setHeader("Cookie", "JSESSIONID=" + ProxySession[buildType].JSESSIONID + ";msa=" + ProxySession[buildType].msa + ";msa_rmc=" + ProxySession[buildType].msa_rmc + ";msa_rmc_disabled=" + ProxySession[buildType].msa_rmc);
            }
        },
        "/j_spring_security_check": {
            target: ProxySession.proxyTarget,
            changeOrigin: true
        },
        "/app_service/websock/**": {
            target: ProxySession.proxyTarget,
            changeOrigin: true,
            onProxyReq: function(proxyReq) {
                proxyReq.setHeader("Cookie", "JSESSIONID=" + ProxySession[buildType].JSESSIONID + ";msa=" + ProxySession[buildType].msa + ";msa_rmc=" + ProxySession[buildType].msa_rmc + ";msa_rmc_disabled=" + ProxySession[buildType].msa_rmc);
            }
        }
    }
}
</code>```

ProxySession.json

```<code> //ProxySession.json
{
  "proxyTarget": "https://t.novare.me/",
  "build-type-1": {
     "JSESSIONID": "....",
     "msa": "....",
     "msa_rmc": ...."
   },
   "build-type-2": {
       "JSESSIONID": ".....",
       "msa": ".....",
       "msa_rmc":"....."
   }
}
</code>```

Title: webpack-dev-server set cookie via proxy

Body:
We have setup our development environment with webpack-dev-server. We use its proxy config to communicate with the backend.

We have a common login page in the server which we use in all our applications. We it is called, it sets a session cookie which expected to passed with subsequent requests. We have used the following config but the cookie is not set in the browser for some reason. I can see it in response header in the network tab of dev tool.

const config = {
  devServer: {
     index: "/",
     proxy: {
     "/rest_end_point/page": {
           target: "https://middleware_server",
           secure : false
     },
     "/": {
           target: "https://middleware_server/app/login",
           secure : false
    },
}

The https://middleware_server/app/login endpoint returns the login page with the set-cookie header.

The proxy is used to avoid CORS errors when accessing login pages and API calls.

Upto this point no code from the application is executed. Do we have to do something in the coomon login page to get the cookie set?

the application is written with React.

Any help would be appreciated.

Body:
I have the same use case and this is what I have done.

In my case, I have multiple proxy targets so I have configured the JSON (ProxySession.json) accordingly.

Note: This approach is not dynamic. you need to get JSESSIONID manually(session ID) for the proxy the request.

login into an application where you want your application to proxy.
Get the JSESSIONID and add it in JSON file or replace directly in onProxyReq function and then run your dev server.

Example:

Webpack-dev.js

 // Webpack-dev.js
const ProxySession = require("./ProxySession");

config = {
  output: {..........},
  plugins: [.......],
  resolve: {......},
  module: {
    rules: [......]
  },
  devServer: {
    port: 8088,
    host: "0.0.0.0",
    disableHostCheck: true,
    proxy: {
        "/service/**": {
            target: ProxySession.proxyTarget,
            changeOrigin: true,
            onProxyReq: function(proxyReq) {
                proxyReq.setHeader("Cookie", "JSESSIONID=" + ProxySession[buildType].JSESSIONID + ";msa=" + ProxySession[buildType].msa + ";msa_rmc=" + ProxySession[buildType].msa_rmc + ";msa_rmc_disabled=" + ProxySession[buildType].msa_rmc);
            }
        },
        "/j_spring_security_check": {
            target: ProxySession.proxyTarget,
            changeOrigin: true
        },
        "/app_service/websock/**": {
            target: ProxySession.proxyTarget,
            changeOrigin: true,
            onProxyReq: function(proxyReq) {
                proxyReq.setHeader("Cookie", "JSESSIONID=" + ProxySession[buildType].JSESSIONID + ";msa=" + ProxySession[buildType].msa + ";msa_rmc=" + ProxySession[buildType].msa_rmc + ";msa_rmc_disabled=" + ProxySession[buildType].msa_rmc);
            }
        }
    }
}

ProxySession.json

 //ProxySession.json
{
  "proxyTarget": "https://t.novare.me/",
  "build-type-1": {
     "JSESSIONID": "....",
     "msa": "....",
     "msa_rmc": ...."
   },
   "build-type-2": {
       "JSESSIONID": ".....",
       "msa": ".....",
       "msa_rmc":"....."
   }
}


问:
Retrieving Java list from ruby
My service(written in Java) returns me an output in the format:

```<code> "serviceMetricList":
  [
    {"MetricDataList":
      {"metricDataList":
        [
          {"metricDate": "2011-04-05T14:50:00.000Z",
           "metricValue": "427448.0"},
          {"metricDate": "2011-04-12T14:30:00.000Z",
           "metricValue": "430089.0"}
        ]
      },
     "urlSerialNo": "1"}
     }
  ]
</code>```

I need to retrieve the values metricDate and metricValue from my Ruby client. Am not sure about how this can be done. Any help in this regard will be great.

答:
If you want to parse this data format, you first need to know what data format it is. It doesn't appear to be any well-known data format and it's not any format I know. It's obviously not JSON, nor is it YAML and definitely not XML.

So, you'll probably have to write your own parser. Or a preprocessor which converts the data into a more well-known format, for wich a parser already exists.

For example, if you were to convert the example to YAML, it would look something like this:

```<code>"serviceMetricList":
  [
    {"MetricDataList":
      {"metricDataList":
        [
          {"metricDate": "2011-04-05T14:50:00.000Z",
           "metricValue": "427448.0"},
          {"metricDate": "2011-04-12T14:30:00.000Z",
           "metricValue": "430089.0"}
        ]
      },
     "urlSerialNo": "1"
    }
  ]
</code>```

And you could parse it like this:

```<code>require 'yaml'
h = YAML.load(your_java_data)

Date.parse(h['serviceMetricList'][0]['MetricDataList']['metricDataList'][0]['metricDate'])
# => #<Date: 2011-04-05 (4911313/2,0,2299161)>

Float(h['serviceMetricList'][0]['MetricDataList']['metricDataList'][0]['metricValue'])
# => 427448.0

# or maybe, if you don't like to lose precision:
require 'bigdecimal'

BigDecimal(h['serviceMetricList'][0]['MetricDataList']['metricDataList'][0]['metricValue'])
# => #<BigDecimal:eb8240,'0.427448E6',8(12)>
</code>```

Title: Retrieving Java list from ruby

Body:
My service(written in Java) returns me an output in the format:

 "serviceMetricList":
  [
    {"MetricDataList":
      {"metricDataList":
        [
          {"metricDate": "2011-04-05T14:50:00.000Z",
           "metricValue": "427448.0"},
          {"metricDate": "2011-04-12T14:30:00.000Z",
           "metricValue": "430089.0"}
        ]
      },
     "urlSerialNo": "1"}
     }
  ]

I need to retrieve the values metricDate and metricValue from my Ruby client. Am not sure about how this can be done. Any help in this regard will be great.

Body:
If you want to parse this data format, you first need to know what data format it is. It doesn't appear to be any well-known data format and it's not any format I know. It's obviously not JSON, nor is it YAML and definitely not XML.

So, you'll probably have to write your own parser. Or a preprocessor which converts the data into a more well-known format, for wich a parser already exists.

For example, if you were to convert the example to YAML, it would look something like this:

"serviceMetricList":
  [
    {"MetricDataList":
      {"metricDataList":
        [
          {"metricDate": "2011-04-05T14:50:00.000Z",
           "metricValue": "427448.0"},
          {"metricDate": "2011-04-12T14:30:00.000Z",
           "metricValue": "430089.0"}
        ]
      },
     "urlSerialNo": "1"
    }
  ]

And you could parse it like this:

require 'yaml'
h = YAML.load(your_java_data)

Date.parse(h['serviceMetricList'][0]['MetricDataList']['metricDataList'][0]['metricDate'])
# => #<Date: 2011-04-05 (4911313/2,0,2299161)>

Float(h['serviceMetricList'][0]['MetricDataList']['metricDataList'][0]['metricValue'])
# => 427448.0

# or maybe, if you don't like to lose precision:
require 'bigdecimal'

BigDecimal(h['serviceMetricList'][0]['MetricDataList']['metricDataList'][0]['metricValue'])
# => #<BigDecimal:eb8240,'0.427448E6',8(12)>