问:
Sticky header inside accordion-like display
I'm trying to create something accordion like, which only turns into an accordion on lower resolutions, as you'll see by resizing the snippet attached to this question. I'm trying to use flex to create a sticky header,  currently only applied to the "Developer" label i'm using position:sticky; but unfortunately that doesn't seem to be doing the trick. Rather new to flex but i'm just trying to use it for the sticky function it has, any tips or tricks would be appreciated! I'm trying to stick to purely HTML/CSS as well.

.featured-table-container {
  display: flex;
  flex-direction: column;
}

.featured-table-collapse {
  cursor: pointer;
  display: block;
  background: #cdf;
}

.featured-table-collapse+input {
  display: none;
  /* hide the checkboxes */
}

.featured-sticky {
  position: sticky;
}

/*** Text/Content Style ***/

.featured-table-content {
  font-size: 20px;
  /*to fill out content so I can test sticky */
}

/*** MEDIA QUERIES ***/

@media only screen and (max-width: 760px) {
  /** Makes table collapse **/
  .featured-table-collapse+input+.featured-table-content {
    display: none;
  }
  .featured-table-collapse+input:checked+.featured-table-content {
    display: block;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="featured-table-container">
  <!-- Container that applies flex -->

  <label class="featured-table-collapse featured-sticky" for="_1">
 <!-- class = featured-sticky for position:sticky; -->
  Developer
</label>
  <input id="_1" type="checkbox">
  <div class="featured-table-content">
    The standard Lorem Ipsum passage, used since the 1500s "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
    ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
    architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia
    dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid
    ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" 1914 translation by H. Rackham "But I must explain to
    you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one
    rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires
    to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain
    some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" Section 1.10.33 of "de Finibus Bonorum et Malorum",
    written by Cicero in 45 BC "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in
    culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere
    possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur
    a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." 1914 translation by H. Rackham "On the other hand, we denounce with righteous indignation and dislike men who are so beguiled
    and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same
    as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is
    to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always
    holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains." The standard Lorem Ipsum passage, used since the 1500s "Lorem ipsum dolor sit amet, consectetur
    adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
    esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC "Sed ut perspiciatis
    unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur
    aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore
    et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse
    quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" 1914 translation by H. Rackham "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give
    you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do
    not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which
    toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure
    that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis
    praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis
    est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis
    debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores
    repellat." 1914 translation by H. Rackham "On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain
    and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a
    free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations
    of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else
    he endures pains to avoid worse pains."
  </div>

  <label class="featured-table-collapse" for="_2">
  Foundation
</label>
  <input id="_2" type="checkbox">
  <div class="featured-table-content">Content 2</div>

  <label class="featured-table-collapse" for="_3">
  Accelerator
</label>
  <input id="_3" type="checkbox">
  <div class="featured-table-content">Content 3</div>

  <label class="featured-table-collapse" for="_4">
  Enterprise
</label>
  <input id="_4" type="checkbox">
  <div class="featured-table-content">Content 4</div>

  <!-- Table container end -->
  </div</code>```

答:
You need to use Top property to stick to its position.</p>

```<code>.featured-sticky {
  position: sticky;
  top: 0px;
}
</code>```

Body:
I'm trying to create something accordion like, which only turns into an accordion on lower resolutions, as you'll see by resizing the snippet attached to this question. I'm trying to use flex to create a sticky header,  currently only applied to the "Developer" label i'm using position:sticky; but unfortunately that doesn't seem to be doing the trick. Rather new to flex but i'm just trying to use it for the sticky function it has, any tips or tricks would be appreciated! I'm trying to stick to purely HTML/CSS as well.

.featured-table-container {
  display: flex;
  flex-direction: column;
}

.featured-table-collapse {
  cursor: pointer;
  display: block;
  background: #cdf;
}

.featured-table-collapse+input {
  display: none;
  /* hide the checkboxes */
}

.featured-sticky {
  position: sticky;
}

/*** Text/Content Style ***/

.featured-table-content {
  font-size: 20px;
  /*to fill out content so I can test sticky */
}

/*** MEDIA QUERIES ***/

@media only screen and (max-width: 760px) {
  /** Makes table collapse **/
  .featured-table-collapse+input+.featured-table-content {
    display: none;
  }
  .featured-table-collapse+input:checked+.featured-table-content {
    display: block;
  }
}

  Developer

  <input id="_1" type="checkbox">

    The standard Lorem Ipsum passage, used since the 1500s "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
    ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
    architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia
    dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid
    ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" 1914 translation by H. Rackham "But I must explain to
    you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one
    rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires
    to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain
    some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" Section 1.10.33 of "de Finibus Bonorum et Malorum",
    written by Cicero in 45 BC "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in
    culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere
    possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur
    a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." 1914 translation by H. Rackham "On the other hand, we denounce with righteous indignation and dislike men who are so beguiled
    and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same
    as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is
    to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always
    holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains." The standard Lorem Ipsum passage, used since the 1500s "Lorem ipsum dolor sit amet, consectetur
    adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
    esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC "Sed ut perspiciatis
    unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur
    aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore
    et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse
    quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" 1914 translation by H. Rackham "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give
    you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do
    not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which
    toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure
    that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis
    praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis
    est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis
    debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores
    repellat." 1914 translation by H. Rackham "On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain
    and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a
    free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations
    of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else
    he endures pains to avoid worse pains."

  Foundation

  <input id="_2" type="checkbox">

Content 2

  Accelerator

  <input id="_3" type="checkbox">

Content 3

  Enterprise

  <input id="_4" type="checkbox">

Content 4

  </div

Body:
You need to use Top property to stick to its position.

.featured-sticky {
  position: sticky;
  top: 0px;
}


来源: stackexchange

问:
jq: Turn json object values into arrays
I have got the following array of objects (this is just an excerpt, also the objects are bigger):

```<code>[{
    "DATE": "10.10.2017 01:00",
    "ID": "X",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "X",
    "VALUE_ONE": 30,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "X",
    "VALUE_ONE": 25,
    "VALUE_TWO": 2
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Y",
    "VALUE_ONE": 10,
    "VALUE_TWO": 9
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Y",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Y",
    "VALUE_ONE": 50,
    "VALUE_TWO": 5
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Z",
    "VALUE_ONE": 55,
    "VALUE_TWO": 3
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Z",
    "VALUE_ONE": 60,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Z",
    "VALUE_ONE": 15,
    "VALUE_TWO": 7
  }
]
</code>```

To simplify this for a web application, and also to reduce file size, I would like to convert the "VALUE_ONE","VALUE_TWO" and "DATE" values to arrays for each "ID" just like this:

```<code>[{
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "X",
    "VALUE_ONE": [20, 30, 25],
    "VALUE_TWO": [5, 7, 2]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Y",
    "VALUE_ONE": [10, 20, 50],
    "VALUE_TWO": [9, 5, 5]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Z",
    "VALUE_ONE": [55, 60, 15],
    "VALUE_TWO": [3, 7, 7]
  }
]
</code>```

Here it is important that you need to be able find the values that are linked to a certain time (date). As the input values for "DATE" are consecutive, you most probably do not need the DATE value anymore to find the requested "VALUE.." value. You can probably just use the index of the array for that (index=0 is always 10.10.2017 01:00, index=1 is ... 02:00 etc.).
Is it possible to do it like that? This would keep the file size even smaller.
Thanks!

答:
The following solution avoids group_by for two reasons:

efficiency

the sort used by group_by in jq version 1.5 might not be stable, which complicates things.

Instead we use bucketize defined as follows:

```<code>def bucketize(f): reduce .[] as $x ({}; .[$x|f] += [$x] );
</code>```

To keep things simple, we will also define the following helper function:

```<code># compactify an array with a single ID
def compact:
  . as $in
  | reduce (.[0]|keys_unsorted[]) as $key ({};
      . + {($key): $in|map(.[$key])})
    + {"ID": .[0].ID}
    ;
</code>```

Solution

```<code>[bucketize(.ID)[] | compact]
</code>```

This will ensure things are OK even if the set of dates differ across IDs, and even if the JSON objects are not grouped initially by date.

(If you want to drop "DATE" altogether in the final results, then replace the call to compact by compact | del(.DATE) in the line above.)

Output

```<code>[
  {
    "DATE": [
      "10.10.2017 01:00",
      "10.10.2017 02:00",
      "10.10.2017 03:00"
    ],
    "ID": "X",
    "VALUE_ONE": [
      20,
      30,
      25
    ],
    "VALUE_TWO": [
      5,
      7,
      2
    ]
  },
  {
    "DATE": [
      "10.10.2017 01:00",
      "10.10.2017 02:00",
      "10.10.2017 03:00"
    ],
    "ID": "Y",
    "VALUE_ONE": [
      10,
      20,
      50
    ],
    "VALUE_TWO": [
      9,
      5,
      5
    ]
  },
  {
    "DATE": [
      "10.10.2017 01:00",
      "10.10.2017 02:00",
      "10.10.2017 03:00"
    ],
    "ID": "Z",
    "VALUE_ONE": [
      55,
      60,
      15
    ],
    "VALUE_TWO": [
      3,
      7,
      7
    ]
  }
]
</code>```

ContentLicense: CC BY-SA 3.0

Title: jq: Turn json object values into arrays

Body:
I have got the following array of objects (this is just an excerpt, also the objects are bigger):

[{
    "DATE": "10.10.2017 01:00",
    "ID": "X",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "X",
    "VALUE_ONE": 30,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "X",
    "VALUE_ONE": 25,
    "VALUE_TWO": 2
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Y",
    "VALUE_ONE": 10,
    "VALUE_TWO": 9
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Y",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Y",
    "VALUE_ONE": 50,
    "VALUE_TWO": 5
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Z",
    "VALUE_ONE": 55,
    "VALUE_TWO": 3
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Z",
    "VALUE_ONE": 60,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Z",
    "VALUE_ONE": 15,
    "VALUE_TWO": 7
  }
]

To simplify this for a web application, and also to reduce file size, I would like to convert the "VALUE_ONE","VALUE_TWO" and "DATE" values to arrays for each "ID" just like this:

[{
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "X",
    "VALUE_ONE": [20, 30, 25],
    "VALUE_TWO": [5, 7, 2]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Y",
    "VALUE_ONE": [10, 20, 50],
    "VALUE_TWO": [9, 5, 5]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Z",
    "VALUE_ONE": [55, 60, 15],
    "VALUE_TWO": [3, 7, 7]
  }
]

Here it is important that you need to be able find the values that are linked to a certain time (date). As the input values for "DATE" are consecutive, you most probably do not need the DATE value anymore to find the requested "VALUE.." value. You can probably just use the index of the array for that (index=0 is always 10.10.2017 01:00, index=1 is ... 02:00 etc.).
Is it possible to do it like that? This would keep the file size even smaller.
Thanks!

Body:
The following solution avoids group_by for two reasons:

efficiency

the sort used by group_by in jq version 1.5 might not be stable, which complicates things.

Instead we use bucketize defined as follows:

def bucketize(f): reduce .[] as $x ({}; .[$x|f] += [$x] );

To keep things simple, we will also define the following helper function:

# compactify an array with a single ID
def compact:
  . as $in
  | reduce (.[0]|keys_unsorted[]) as $key ({};
      . + {($key): $in|map(.[$key])})
    + {"ID": .[0].ID}
    ;

Solution

[bucketize(.ID)[] | compact]

This will ensure things are OK even if the set of dates differ across IDs, and even if the JSON objects are not grouped initially by date.

(If you want to drop "DATE" altogether in the final results, then replace the call to compact by compact | del(.DATE) in the line above.)

Output

[
  {
    "DATE": [
      "10.10.2017 01:00",
      "10.10.2017 02:00",
      "10.10.2017 03:00"
    ],
    "ID": "X",
    "VALUE_ONE": [
      20,
      30,
      25
    ],
    "VALUE_TWO": [
      5,
      7,
      2
    ]
  },
  {
    "DATE": [
      "10.10.2017 01:00",
      "10.10.2017 02:00",
      "10.10.2017 03:00"
    ],
    "ID": "Y",
    "VALUE_ONE": [
      10,
      20,
      50
    ],
    "VALUE_TWO": [
      9,
      5,
      5
    ]
  },
  {
    "DATE": [
      "10.10.2017 01:00",
      "10.10.2017 02:00",
      "10.10.2017 03:00"
    ],
    "ID": "Z",
    "VALUE_ONE": [
      55,
      60,
      15
    ],
    "VALUE_TWO": [
      3,
      7,
      7
    ]
  }
]


问:
Pinterest API : is it possible to get secret boards?
Is there a way to fetch the list of the logged user's secret boards using the Pinterest API ?

I can't find it and I suppose it does not support it (which is odd); but I just want to be sure !

Also, if I have a Pinterest (secret) board ID; will the API be able to retrieve its pins ?

Thanks

答:
As of today, Pinterest does not support secret boards with APIs.
https://developers.pinterest.com/docs/api/boards/</p>


问:
How to check 2 charAt(i)
I have this lines:

```<code>812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 10
812.12 135.14 646.20 10
812.12 135.14 646.21 100
812.12 135.14 646.22 100
</code>```

I want to delete only the last group so I did code like this:

```<code>if(lines[i].charAt(lines[i].length())-1>= '0'&&lines[i].charAt(lines[i].length()-1)<= '9'){
    lines[i] = lines[i].substring(0, lines[i].length()-1);
   }

   else if(lines[i].charAt(lines[i].length())>='10'+c&&lines[i].charAt(lines[i].length()-1)<='99'){
   lines[i] = lines[i].substring(0, lines[i].length()-2);
        }

   else if(lines[i].charAt(lines[i].length())>='100'&&lines[i].charAt(lines[i].length()-1)<='999){
   lines[i] = lines[i].substring(0, lines[i].length()-3);
 }
</code>```

And it's now working for me I need help please

答:
You have characters and trying to compare them as numbers. It doesn't work that way.

A char in most higher-level (Java, .NET languages...etc) programming languages follows UTF-16 format by default. Since each char size is 2 bytes it can follow any encoding you need.

You cannot compare a char to string and you cannot attempt to put string in char like '10'. Those are two characters, not one, it's a string.

Now based on your desired output, you would like to remove everything after the last space. To do that, you can use the following code:

```<code>static void updateLines(String[] lines){
    for(int i=0;i<lines.length; i++){
        // get index of the last space
        int index = lines[i].lastIndexOf(" ");

        // remove everything after the last space
        lines[i] = lines[i].substring(0, index);
    }
}

public static void main(String[] args) {
    String[] lines = new String[]{
      "812.12 135.14 646.17 1",
      "812.12 135.14 646.18 1",
      "812.12 135.14 646.19 10",
      "812.12 135.14 646.20 10",
      "812.12 135.14 646.21 100",
      "812.12 135.14 646.22 100",
      "812.12 135.14 646.23 1000",
      "812.12 135.14 646.24 1000"
    };

    updateLines(lines);

    for(int i=0;i<lines.length;i++)
        System.out.println(lines[i]);
}
</code>```

Output:

```<code>812.12 135.14 646.17
812.12 135.14 646.18
812.12 135.14 646.19
812.12 135.14 646.20
812.12 135.14 646.21
812.12 135.14 646.22
812.12 135.14 646.23
812.12 135.14 646.24
</code>```

Is this enough or do you need to compare numbers?

Title: How to check 2 charAt(i)

Body:
I have this lines:

812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 10
812.12 135.14 646.20 10
812.12 135.14 646.21 100
812.12 135.14 646.22 100

I want to delete only the last group so I did code like this:

if(lines[i].charAt(lines[i].length())-1>= '0'&&lines[i].charAt(lines[i].length()-1)<= '9'){
    lines[i] = lines[i].substring(0, lines[i].length()-1);
   }

   else if(lines[i].charAt(lines[i].length())>='10'+c&&lines[i].charAt(lines[i].length()-1)<='99'){
   lines[i] = lines[i].substring(0, lines[i].length()-2);
        }

   else if(lines[i].charAt(lines[i].length())>='100'&&lines[i].charAt(lines[i].length()-1)<='999){
   lines[i] = lines[i].substring(0, lines[i].length()-3);
 }

And it's now working for me I need help please

Body:
You have characters and trying to compare them as numbers. It doesn't work that way.

A char in most higher-level (Java, .NET languages...etc) programming languages follows UTF-16 format by default. Since each char size is 2 bytes it can follow any encoding you need.

You cannot compare a char to string and you cannot attempt to put string in char like '10'. Those are two characters, not one, it's a string.

Now based on your desired output, you would like to remove everything after the last space. To do that, you can use the following code:

static void updateLines(String[] lines){
    for(int i=0;i<lines.length; i++){
        // get index of the last space
        int index = lines[i].lastIndexOf(" ");

        // remove everything after the last space
        lines[i] = lines[i].substring(0, index);
    }
}

public static void main(String[] args) {
    String[] lines = new String[]{
      "812.12 135.14 646.17 1",
      "812.12 135.14 646.18 1",
      "812.12 135.14 646.19 10",
      "812.12 135.14 646.20 10",
      "812.12 135.14 646.21 100",
      "812.12 135.14 646.22 100",
      "812.12 135.14 646.23 1000",
      "812.12 135.14 646.24 1000"
    };

    updateLines(lines);

    for(int i=0;i<lines.length;i++)
        System.out.println(lines[i]);
}

Output:

812.12 135.14 646.17
812.12 135.14 646.18
812.12 135.14 646.19
812.12 135.14 646.20
812.12 135.14 646.21
812.12 135.14 646.22
812.12 135.14 646.23
812.12 135.14 646.24

Is this enough or do you need to compare numbers?


问:
i made a function what is meant to check if the format of the date of birth the user enters is correct but i can't get it to work
```<code>def checkdob():
    while True:
        dob = input("Date of Birth")
        try:
            dob == datetime.datetime.strptime(dob, '%d-%m-%y')
            break
        except:
            print("Incorrect data format, should be DD-MM-YYYY")
checkdob()
</code>```

答:
I did the following and it works fine. I wonder what you enter as a DOB as an input. Otherwise, it seems to be working fine.</p>

```<code>>>> from datetime import datetime
>>> dob = '31-12-99'
>>> if dob:
...   dt_obj = datetime.strptime(dob, '%d-%m-%y')
...
>>> print dt_obj
1999-12-31 00:00:00
</code>```

Body:
I did the following and it works fine. I wonder what you enter as a DOB as an input. Otherwise, it seems to be working fine.

>>> from datetime import datetime
>>> dob = '31-12-99'
>>> if dob:
...   dt_obj = datetime.strptime(dob, '%d-%m-%y')
...
>>> print dt_obj
1999-12-31 00:00:00


问:
Delete row from php array
How can I remove an element from an array?

For example:

```<code>$data = Array('first' , 'second' , 'third');
array_delete($data[2]);

#$data would now read Array('first', 'second')
</code>```

Does such a built-in function exist?
Thanks.

答:
The above answers work. But here is what i got from the site listed below. I think its cool.

```<code>//deletes a number on index $idx in array and returns the new array
function array_delete($idx,$array) {
    unset($array[$idx]);
    return (is_array($array)) ? array_values($array) : null;
}
</code>```

http://dev.kafol.net/2009/02/php-array-delete.html

ContentLicense: CC BY-SA 2.5

Title: Delete row from php array

Body:
How can I remove an element from an array?

For example:

$data = Array('first' , 'second' , 'third');
array_delete($data[2]);

#$data would now read Array('first', 'second')

Does such a built-in function exist?
Thanks.

Body:
The above answers work. But here is what i got from the site listed below. I think its cool.

//deletes a number on index $idx in array and returns the new array
function array_delete($idx,$array) {
    unset($array[$idx]);
    return (is_array($array)) ? array_values($array) : null;
}

http://dev.kafol.net/2009/02/php-array-delete.html


问:
how to compare results in for-loop in python
I created a class, it has some initial variable like coefficient and error. And in my method, I have a for loop to calculate something, in each run, I will get a number which is named as error. And in each run, I got a error and also have a coefficient number. What I want to do is, at the first run, I can get a error and a coefficient set. At the second run, I will compare error with the previous error, if it is smaller than previous one, then, update error to the smaller error, and also update the coefficient. Else, keep the previous error and coefficient.

```<code>class getMinError():
def __init__(self):
    self.error = 0
    self.ce1 = 0
    self.ce2 = 0

def process(self):
     for i in range(any number):
        run to get error, ce1,and ce2
        save the first run's result to self.error, self.ce1,and self.ce2
</code>```

or just save it without update to the initial variables.

compare in the next loops, and
update only when error is smaller than previous ones.

答:
I think you can try this </p>

```<code>class getMinError():
def __init__(self):
    self.error = 0
    self.ce1 = 0
    self.ce2 = 0
 run to get error, ce1,and ce2

def process(self):
     for i in range(2:n):
        run to get error, ce1,and ce2
        if error<self.error :
           self.error=error
           self.ce1=ce1
           self.ce2=ce2
</code>```

<p>Hope that will be helpful . </p>

Body:
I created a class, it has some initial variable like coefficient and error. And in my method, I have a for loop to calculate something, in each run, I will get a number which is named as error. And in each run, I got a error and also have a coefficient number. What I want to do is, at the first run, I can get a error and a coefficient set. At the second run, I will compare error with the previous error, if it is smaller than previous one, then, update error to the smaller error, and also update the coefficient. Else, keep the previous error and coefficient.

class getMinError():
def __init__(self):
    self.error = 0
    self.ce1 = 0
    self.ce2 = 0

def process(self):
     for i in range(any number):
        run to get error, ce1,and ce2
        save the first run's result to self.error, self.ce1,and self.ce2

or just save it without update to the initial variables.

compare in the next loops, and
update only when error is smaller than previous ones.

Body:
I think you can try this

class getMinError():
def __init__(self):
    self.error = 0
    self.ce1 = 0
    self.ce2 = 0
 run to get error, ce1,and ce2

def process(self):
     for i in range(2:n):
        run to get error, ce1,and ce2
        if error<self.error :
           self.error=error
           self.ce1=ce1
           self.ce2=ce2

Hope that will be helpful .


问:
Entity Framework Core 2.0 call stored procedure
How can I call a stored procedure using Entity Framework Core 2.0? Asp.net core 2.0 site in C#</p>

答:
csproj file:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
  </ItemGroup>

</Project>
</code>```

program.cs:

```<code>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace EfExperiment
{
    class Program
    {
        public class Record
        {
            public int Id { get; set; }
            public DateTime Date { get; set; }
            public decimal Value { get; set; }
        }

        public class RecordsDbContext : DbContext
        {
            public DbSet<Record> Records { get; set; }

            public List<Record> RecordsByDateRange(DateTime fromDate, DateTime toDate)
            {
                var fromDateParam = new SqlParameter("fromDate", fromDate);
                var toDateParam = new SqlParameter("toDate", toDate);

                return Records
                    .FromSql("EXECUTE dbo.RecordsByDateRange @fromDate, @toDate", fromDateParam, toDateParam)
                    .ToList();
            }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=RecordsDb;Trusted_Connection=True;");
            }
        }

        static void Main(string[] args)
        {
            using (var dbc = new RecordsDbContext())
            {
                var records = dbc.RecordsByDateRange(DateTime.Now.AddMonths(-1), DateTime.Now);
                Console.WriteLine($"{records.Count} records loaded");

                foreach (var record in records)
                {
                    Console.WriteLine($"[{record.Id}] [{record.Date}] {record.Value}");
                }
            }

            Console.WriteLine("Press <enter>");
            Console.ReadLine();
        }
    }
}
</code>```

Body:
csproj file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
  </ItemGroup>

</Project>

program.cs:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace EfExperiment
{
    class Program
    {
        public class Record
        {
            public int Id { get; set; }
            public DateTime Date { get; set; }
            public decimal Value { get; set; }
        }

        public class RecordsDbContext : DbContext
        {
            public DbSet<Record> Records { get; set; }

            public List<Record> RecordsByDateRange(DateTime fromDate, DateTime toDate)
            {
                var fromDateParam = new SqlParameter("fromDate", fromDate);
                var toDateParam = new SqlParameter("toDate", toDate);

                return Records
                    .FromSql("EXECUTE dbo.RecordsByDateRange @fromDate, @toDate", fromDateParam, toDateParam)
                    .ToList();
            }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=RecordsDb;Trusted_Connection=True;");
            }
        }

        static void Main(string[] args)
        {
            using (var dbc = new RecordsDbContext())
            {
                var records = dbc.RecordsByDateRange(DateTime.Now.AddMonths(-1), DateTime.Now);
                Console.WriteLine($"{records.Count} records loaded");

                foreach (var record in records)
                {
                    Console.WriteLine($"[{record.Id}] [{record.Date}] {record.Value}");
                }
            }

            Console.WriteLine("Press <enter>");
            Console.ReadLine();
        }
    }
}


问:
Convert database date to short date with Javascript
I have a SQL lookup a date that feeds into a field, but the date format contains time, I need to convert it to short date (mm/dd/yyyy). The MSSQL outputs this format (m/d/yyyy 12:00:00 AM) notice that the time is always '12:00:00 AM'. How do I remove the time?

```<code>$('#q60').change(function () {
    var date = $('#q60 input').val();   //looking up the field that contains the date fed from SQL.

    date = date.substring(0, date.indexOf(' '));
  });
</code>```

I have tried using split but while it output the correct thing it doesn't actually change the value in the field for some reason. I have also attempted using the .format similar to this post: Format a date string in javascript
But I am stuck!

答:
with date = date.substring(0, date.indexOf(' ')); you're just storing splitted value in to date variable. to change the value of the input field add $('#q60 input').val(date) at the end of your function.

also in JS there's a whole Date object, with it you can format your date as you please. you can find more about it here and here

Body:
I have a SQL lookup a date that feeds into a field, but the date format contains time, I need to convert it to short date (mm/dd/yyyy). The MSSQL outputs this format (m/d/yyyy 12:00:00 AM) notice that the time is always '12:00:00 AM'. How do I remove the time?

$('#q60').change(function () {
    var date = $('#q60 input').val();   //looking up the field that contains the date fed from SQL.

    date = date.substring(0, date.indexOf(' '));
  });

I have tried using split but while it output the correct thing it doesn't actually change the value in the field for some reason. I have also attempted using the .format similar to this post: Format a date string in javascript
But I am stuck!


问:
MySQL updating many records and columns in a table using a UPDATE and a SELECT
I've added the last three fields to this table, but they are blank. All of the records have the top three filled in. The table definition is,

mysql> describe nh3tk;

```<code>+-----------------+-------------+------+-----+---------+-------+
| Field           | Type        | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+-------+
| spectra         | varchar(50) | NO   | PRI | NULL    |       |
| value           | float       | NO   |     | NULL    |       |
| error           | float       | NO   |     | NULL    |       |
| nonthermal_FWHM | double      | YES  |     | NULL    |       |
| sound_speed     | double      | YES  |     | NULL    |       |
+-----------------+-------------+------+-----+---------+-------+
</code>```

The Select query, which works is,

```<code>select nh3tk.spectra,
  pow((pow(2.35*nh3lw.sd_lw,2)-1.38065e-23*8*ln(2)*nh3tk.value/2.82e-26),0.5) as nonthermal_FWHM,
  pow(1.38065e-23*nh3tk.value/(2.33*3.348e-27),0.5) as sound_speed
from nh3tk
 left join nh3lw on nh3tk.spectra=nh3lw.spectra;
</code>```

Now I just need to take the two calculated fields from that query and put them in the right fields in nh3tk, where the spectra match.

Any help would be gratefully appreciated.

Best regards
James

答:
```<code>UPDATE  nh3tk
JOIN    nh3lw
ON      nh3lw.spectra = nh3tk.spectra
SET     nonthermal_FWHM = pow((pow(2.35*nh3lw.sd_lw,2)-1.38065e-23*8*ln(2)*nh3tk.value/2.82e-26),0.5),
        sound_speed = pow(1.38065e-23*nh3tk.value/(2.33*3.348e-27),0.5)
</code>```

Not sure about the error, since you don't select it in your query.

Body:
I've added the last three fields to this table, but they are blank. All of the records have the top three filled in. The table definition is,

mysql> describe nh3tk;

+-----------------+-------------+------+-----+---------+-------+
| Field           | Type        | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+-------+
| spectra         | varchar(50) | NO   | PRI | NULL    |       |
| value           | float       | NO   |     | NULL    |       |
| error           | float       | NO   |     | NULL    |       |
| nonthermal_FWHM | double      | YES  |     | NULL    |       |
| sound_speed     | double      | YES  |     | NULL    |       |
+-----------------+-------------+------+-----+---------+-------+

The Select query, which works is,

select nh3tk.spectra,
  pow((pow(2.35*nh3lw.sd_lw,2)-1.38065e-23*8*ln(2)*nh3tk.value/2.82e-26),0.5) as nonthermal_FWHM,
  pow(1.38065e-23*nh3tk.value/(2.33*3.348e-27),0.5) as sound_speed
from nh3tk
 left join nh3lw on nh3tk.spectra=nh3lw.spectra;

Now I just need to take the two calculated fields from that query and put them in the right fields in nh3tk, where the spectra match.

Any help would be gratefully appreciated.

Best regards
James

Body:
UPDATE  nh3tk
JOIN    nh3lw
ON      nh3lw.spectra = nh3tk.spectra
SET     nonthermal_FWHM = pow((pow(2.35*nh3lw.sd_lw,2)-1.38065e-23*8*ln(2)*nh3tk.value/2.82e-26),0.5),
        sound_speed = pow(1.38065e-23*nh3tk.value/(2.33*3.348e-27),0.5)

Not sure about the error, since you don't select it in your query.


问:
GemFire entry Time-To-Live is not getting set using spring-cache
Following is the code snippet which is successful in persisting the data in a remote GemFire cluster and successfully keeping local spring-cache updated. However, the entries are not getting DESTROY-ed as expected when I tried using ExpirationAttributes. I've referred to this and related links.

```<code>import org.springframework.data.gemfire.ExpirationActionType;
import org.springframework.data.gemfire.ExpirationAttributesFactoryBean;
import org.springframework.data.gemfire.RegionAttributesFactoryBean;
import org.springframework.data.gemfire.client.ClientCacheFactoryBean;
import org.springframework.data.gemfire.client.ClientRegionFactoryBean;
import org.springframework.data.gemfire.support.ConnectionEndpoint;
import org.springframework.data.gemfire.support.GemfireCacheManager;

import com.gemstone.gemfire.cache.ExpirationAttributes;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientRegionShortcut;
import com.gemstone.gemfire.pdx.ReflectionBasedAutoSerializer;

@Configuration
@Profile("local")
public class GemFireCachingConfig {

    @Bean
    Properties gemfireProperties(...) {

        //Sets gemfire properties and return
        return gemfireProperties;
    }

    @Bean
    @Primary
    ReflectionBasedAutoSerializer reflectionBasedAutoSerializer() {
        return new ReflectionBasedAutoSerializer("pkg.containing.cacheable.object");
    }

    @Bean
    @Primary
    ClientCacheFactoryBean clientCacheFactory(String injectedGemFirehost,
            int injectedGemfirePort, Properties gemfireProperties,
            ReflectionBasedAutoSerializer reflectionBasedAutoSerializer) {

        ClientCacheFactoryBean cachefactoryBean = new ClientCacheFactoryBean();
        cachefactoryBean.setProperties(gemfireProperties);
        cachefactoryBean.setClose(true);
        cachefactoryBean.setPdxSerializer(reflectionBasedAutoSerializer);
        cachefactoryBean.setPdxReadSerialized(false);
        cachefactoryBean.setPdxIgnoreUnreadFields(true);

        ConnectionEndpoint[] locators = new ConnectionEndpoint[1];
        locators[0] = new ConnectionEndpoint(injectedGemFirehost, injectedGemfirePort);
        cachefactoryBean.setLocators(locators);

        return cachefactoryBean;

    }

    @Bean
    public ExpirationAttributesFactoryBean entryTtlExpirationAttributes(
            int injectedTimeoutInSecs) {

        ExpirationAttributesFactoryBean expirationAttributes = new ExpirationAttributesFactoryBean();

        expirationAttributes.setAction(ExpirationActionType.DESTROY.getExpirationAction());
        expirationAttributes.setTimeout(injectedTimeoutInSecs);

        return expirationAttributes;
    }

    @Bean
    @Autowired
    public RegionAttributesFactoryBean regionAttributes(
            @Qualifier("entryTtlExpirationAttributes") ExpirationAttributes entryTtl) {

        RegionAttributesFactoryBean regionAttributes = new RegionAttributesFactoryBean();
        regionAttributes.setStatisticsEnabled(true);
        regionAttributes.setEntryTimeToLive(entryTtl);

        return regionAttributes;
    }

    @Bean
    @Primary
    ClientRegionFactoryBean<String, Object> regionFactoryBean(ClientCache gemfireCache,
            @Qualifier("regionAttributes") RegionAttributes<String, Object> regionAttributes) {

        ClientRegionFactoryBean<String, Object> regionFactoryBean = new ClientRegionFactoryBean<>();

        regionFactoryBean.setAttributes(regionAttributes);
        regionFactoryBean.setCache(gemfireCache);
        regionFactoryBean.setClose(false);
        regionFactoryBean.setPersistent(false);
        regionFactoryBean.setRegionName(regionName);
        regionFactoryBean.setShortcut(ClientRegionShortcut.CACHING_PROXY_HEAP_LRU);

        return regionFactoryBean;
    }

    @Bean
    GemfireCacheManager cacheManager(ClientCache gemfireCache) {
        GemfireCacheManager cacheManager = new GemfireCacheManager();
        cacheManager.setCache(gemfireCache);

        return cacheManager;
    }

}
</code>```

答:
Just curious how you think the injectedTimeoutInSeconds is "injected" into your entryTtlExpirationAttributes bean definition in your Spring config; this...

```<code>@Bean
public ExpirationAttributesFactoryBean entryTtlExpirationAttributes(
        int injectedTimeoutInSecs) {

    ExpirationAttributesFactoryBean expirationAttributes =
        new ExpirationAttributesFactoryBean();

    expirationAttributes.setAction(
        ExpirationActionType.DESTROY.getExpirationAction());
    expirationAttributes.setTimeout(injectedTimeoutInSecs);

    return expirationAttributes;
}
</code>```

You need to annotate your entryTtlExpirationAttributes bean definition method parameter (i.e. injectedTimeoutInSecs) with Spring's @Value annotation, like so...

```<code>@Bean
public ExpirationAttributesFactoryBean entryTtlExpirationAttributes(
        @Value("${gemfire.cache.expiration.ttl.timeout:600}")
            int injectedTimeoutInSecs) {
</code>```

Then, in your Spring Boot application.properties file, you can set a value for the property (gemfire.cache.expiration.ttl.timeout)...

```<code>#application.properties
gemfire.cache.expiration.ttl.timeout = 300
</code>```

The @Value annotation can supply a default if the property is not explicitly set...

@Value({${property:defaultValue}")

Additionally, you need to supply a propertySourcePlaceholderConfigurer bean definition in your Spring Java config to enable Spring to "replace" property placeholder values...

```<code>@Bean
static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}
</code>```

You can see a similar configuration to what you have above here.

Finally, you can simplify your entire Spring, GemFire Java configuration class to this...

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

import org.apache.geode.cache.ExpirationAttributes;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.pdx.ReflectionBasedAutoSerializer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.gemfire.RegionAttributesFactoryBean;
import org.springframework.data.gemfire.cache.config.EnableGemfireCaching;
import org.springframework.data.gemfire.client.ClientRegionFactoryBean;
import org.springframework.data.gemfire.config.annotation.ClientCacheApplication;
import org.springframework.data.gemfire.config.annotation.ClientCacheConfigurer;
import org.springframework.data.gemfire.config.annotation.EnablePdx;
import org.springframework.data.gemfire.expiration.ExpirationActionType;
import org.springframework.data.gemfire.expiration.ExpirationAttributesFactoryBean;
import org.springframework.data.gemfire.support.ConnectionEndpoint;

@ClientCacheApplication
@EnableGemfireCaching
@EnablePdx(ignoreUnreadFields = true, readSerialized = false,
  serializerBeanName = "reflectionBasedAutoSerializer")
@Profile("local")
public class GemFireCachingConfig {

  @Bean
  static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
  }

  // NOTE: you can externalize Pivotal GemFire properties in a gemfire.properties file,
  // placed in the root of your application classpath.
  //
  // Alternatively, you can use Spring Boot's application.properties to set GemFire properties
  // using the corresponding Spring Data GemFire (annotation-based) property (e.g. spring.data.gemfire.cache.log-level)
  //
  // See here...
  // https://docs.spring.io/spring-data/gemfire/docs/current/api/org/springframework/data/gemfire/config/annotation/ClientCacheApplication.html#logLevel--

  @Bean
  @Primary
  ReflectionBasedAutoSerializer reflectionBasedAutoSerializer() {
    return new ReflectionBasedAutoSerializer("pkg.containing.cacheable.object");
  }

  @Bean
  ClientCacheConfigurer clientCacheHostPortConfigurer(
      @Value("gemfire.locator.host") String locatorHost,
      @Value("gemfire.locator.port") int locatorPort) {

    return (beanName, clientCacheFactoryBean) ->
      clientCacheFactoryBean.setLocators(Collections.singletonList(
        new ConnectionEndpoint(locatorHost, locatorPort)));
  }

  @Bean("RegionNameHere")
  ClientRegionFactoryBean<String, Object> regionFactoryBean(GemFireCache gemfireCache,
      @Qualifier("regionAttributes") RegionAttributes<String, Object> regionAttributes) {

    ClientRegionFactoryBean<String, Object> clientRegionFactory = new ClientRegionFactoryBean<>();

    clientRegionFactory.setAttributes(regionAttributes);
    clientRegionFactory.setCache(gemfireCache);
    clientRegionFactory.setClose(false);
    clientRegionFactory.setShortcut(ClientRegionShortcut.CACHING_PROXY_HEAP_LRU);

    return clientRegionFactory;
  }

  @Bean
  public RegionAttributesFactoryBean regionAttributes(
      @Qualifier("entryTtlExpirationAttributes") ExpirationAttributes expirationAttributes) {

    RegionAttributesFactoryBean regionAttributes = new RegionAttributesFactoryBean();

    regionAttributes.setStatisticsEnabled(true);
    regionAttributes.setEntryTimeToLive(expirationAttributes);

    return regionAttributes;
  }

  @Bean
  public ExpirationAttributesFactoryBean entryTtlExpirationAttributes(
      @Value("${gemfire.cache.expiration:600") int timeoutInSeconds) {

    ExpirationAttributesFactoryBean expirationAttributes = new ExpirationAttributesFactoryBean();

    expirationAttributes.setAction(ExpirationActionType.DESTROY.getExpirationAction());
    expirationAttributes.setTimeout(timeoutInSeconds);

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

Of course, this configuration is based on Spring Data GemFire 2.0.1.RELEASE (Kay-SR1).

Notice the @ClientCacheApplication annotation, which replaces the need for your clientCacheFactory bean definition.

I also used the new @EnablePdx annotation to configure GemFire's PDX serialization behavior.

I declared a ClientCacheConfigurer typed bean definition (clientCacheHostPortConfigurer) to dynamically adjust the Locator host and port configuration based on property placeholders.

I defined a PropertySourcesPlaceholderConfigurer to handle the property placeholders used in the @Value annotations throughout the Spring, Java-based configuration meta-data.

I also used the new @EnableGemfireCaching annotation which replaces the need to explicitly define a gemfireCacheManager bean definition.  It also enables Spring's Cache Abstraction (specifying @EnableCaching for you).

Anyway, SDG's new Annotation-based configuration model makes it easier to do everything.  But again, you need to be using Spring Data GemFire 2.0+ (SD Kay) with Pivotal GemFire 9.1.x.

Hope this helps!

-John

ContentLicense: CC BY-SA 4.0

Body:
Following is the code snippet which is successful in persisting the data in a remote GemFire cluster and successfully keeping local spring-cache updated. However, the entries are not getting DESTROY-ed as expected when I tried using ExpirationAttributes. I've referred to this and related links.

import org.springframework.data.gemfire.ExpirationActionType;
import org.springframework.data.gemfire.ExpirationAttributesFactoryBean;
import org.springframework.data.gemfire.RegionAttributesFactoryBean;
import org.springframework.data.gemfire.client.ClientCacheFactoryBean;
import org.springframework.data.gemfire.client.ClientRegionFactoryBean;
import org.springframework.data.gemfire.support.ConnectionEndpoint;
import org.springframework.data.gemfire.support.GemfireCacheManager;

import com.gemstone.gemfire.cache.ExpirationAttributes;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientRegionShortcut;
import com.gemstone.gemfire.pdx.ReflectionBasedAutoSerializer;

@Configuration
@Profile("local")
public class GemFireCachingConfig {

    @Bean
    Properties gemfireProperties(...) {

        //Sets gemfire properties and return
        return gemfireProperties;
    }

    @Bean
    @Primary
    ReflectionBasedAutoSerializer reflectionBasedAutoSerializer() {
        return new ReflectionBasedAutoSerializer("pkg.containing.cacheable.object");
    }

    @Bean
    @Primary
    ClientCacheFactoryBean clientCacheFactory(String injectedGemFirehost,
            int injectedGemfirePort, Properties gemfireProperties,
            ReflectionBasedAutoSerializer reflectionBasedAutoSerializer) {

        ClientCacheFactoryBean cachefactoryBean = new ClientCacheFactoryBean();
        cachefactoryBean.setProperties(gemfireProperties);
        cachefactoryBean.setClose(true);
        cachefactoryBean.setPdxSerializer(reflectionBasedAutoSerializer);
        cachefactoryBean.setPdxReadSerialized(false);
        cachefactoryBean.setPdxIgnoreUnreadFields(true);

        ConnectionEndpoint[] locators = new ConnectionEndpoint[1];
        locators[0] = new ConnectionEndpoint(injectedGemFirehost, injectedGemfirePort);
        cachefactoryBean.setLocators(locators);

        return cachefactoryBean;

    }

    @Bean
    public ExpirationAttributesFactoryBean entryTtlExpirationAttributes(
            int injectedTimeoutInSecs) {

        ExpirationAttributesFactoryBean expirationAttributes = new ExpirationAttributesFactoryBean();

        expirationAttributes.setAction(ExpirationActionType.DESTROY.getExpirationAction());
        expirationAttributes.setTimeout(injectedTimeoutInSecs);

        return expirationAttributes;
    }

    @Bean
    @Autowired
    public RegionAttributesFactoryBean regionAttributes(
            @Qualifier("entryTtlExpirationAttributes") ExpirationAttributes entryTtl) {

        RegionAttributesFactoryBean regionAttributes = new RegionAttributesFactoryBean();
        regionAttributes.setStatisticsEnabled(true);
        regionAttributes.setEntryTimeToLive(entryTtl);

        return regionAttributes;
    }

    @Bean
    @Primary
    ClientRegionFactoryBean<String, Object> regionFactoryBean(ClientCache gemfireCache,
            @Qualifier("regionAttributes") RegionAttributes<String, Object> regionAttributes) {

        ClientRegionFactoryBean<String, Object> regionFactoryBean = new ClientRegionFactoryBean<>();

        regionFactoryBean.setAttributes(regionAttributes);
        regionFactoryBean.setCache(gemfireCache);
        regionFactoryBean.setClose(false);
        regionFactoryBean.setPersistent(false);
        regionFactoryBean.setRegionName(regionName);
        regionFactoryBean.setShortcut(ClientRegionShortcut.CACHING_PROXY_HEAP_LRU);

        return regionFactoryBean;
    }

    @Bean
    GemfireCacheManager cacheManager(ClientCache gemfireCache) {
        GemfireCacheManager cacheManager = new GemfireCacheManager();
        cacheManager.setCache(gemfireCache);

        return cacheManager;
    }

}

Body:
Just curious how you think the injectedTimeoutInSeconds is "injected" into your entryTtlExpirationAttributes bean definition in your Spring config; this...

@Bean
public ExpirationAttributesFactoryBean entryTtlExpirationAttributes(
        int injectedTimeoutInSecs) {

    ExpirationAttributesFactoryBean expirationAttributes =
        new ExpirationAttributesFactoryBean();

    expirationAttributes.setAction(
        ExpirationActionType.DESTROY.getExpirationAction());
    expirationAttributes.setTimeout(injectedTimeoutInSecs);

    return expirationAttributes;
}

You need to annotate your entryTtlExpirationAttributes bean definition method parameter (i.e. injectedTimeoutInSecs) with Spring's @Value annotation, like so...

@Bean
public ExpirationAttributesFactoryBean entryTtlExpirationAttributes(
        @Value("${gemfire.cache.expiration.ttl.timeout:600}")
            int injectedTimeoutInSecs) {

Then, in your Spring Boot application.properties file, you can set a value for the property (gemfire.cache.expiration.ttl.timeout)...

#application.properties
gemfire.cache.expiration.ttl.timeout = 300

The @Value annotation can supply a default if the property is not explicitly set...

@Value({${property:defaultValue}")

Additionally, you need to supply a propertySourcePlaceholderConfigurer bean definition in your Spring Java config to enable Spring to "replace" property placeholder values...

@Bean
static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

You can see a similar configuration to what you have above here.

Finally, you can simplify your entire Spring, GemFire Java configuration class to this...

import java.util.Collections;

import org.apache.geode.cache.ExpirationAttributes;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.pdx.ReflectionBasedAutoSerializer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.gemfire.RegionAttributesFactoryBean;
import org.springframework.data.gemfire.cache.config.EnableGemfireCaching;
import org.springframework.data.gemfire.client.ClientRegionFactoryBean;
import org.springframework.data.gemfire.config.annotation.ClientCacheApplication;
import org.springframework.data.gemfire.config.annotation.ClientCacheConfigurer;
import org.springframework.data.gemfire.config.annotation.EnablePdx;
import org.springframework.data.gemfire.expiration.ExpirationActionType;
import org.springframework.data.gemfire.expiration.ExpirationAttributesFactoryBean;
import org.springframework.data.gemfire.support.ConnectionEndpoint;

@ClientCacheApplication
@EnableGemfireCaching
@EnablePdx(ignoreUnreadFields = true, readSerialized = false,
  serializerBeanName = "reflectionBasedAutoSerializer")
@Profile("local")
public class GemFireCachingConfig {

  @Bean
  static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
  }

  // NOTE: you can externalize Pivotal GemFire properties in a gemfire.properties file,
  // placed in the root of your application classpath.
  //
  // Alternatively, you can use Spring Boot's application.properties to set GemFire properties
  // using the corresponding Spring Data GemFire (annotation-based) property (e.g. spring.data.gemfire.cache.log-level)
  //
  // See here...
  // https://docs.spring.io/spring-data/gemfire/docs/current/api/org/springframework/data/gemfire/config/annotation/ClientCacheApplication.html#logLevel--

  @Bean
  @Primary
  ReflectionBasedAutoSerializer reflectionBasedAutoSerializer() {
    return new ReflectionBasedAutoSerializer("pkg.containing.cacheable.object");
  }

  @Bean
  ClientCacheConfigurer clientCacheHostPortConfigurer(
      @Value("gemfire.locator.host") String locatorHost,
      @Value("gemfire.locator.port") int locatorPort) {

    return (beanName, clientCacheFactoryBean) ->
      clientCacheFactoryBean.setLocators(Collections.singletonList(
        new ConnectionEndpoint(locatorHost, locatorPort)));
  }

  @Bean("RegionNameHere")
  ClientRegionFactoryBean<String, Object> regionFactoryBean(GemFireCache gemfireCache,
      @Qualifier("regionAttributes") RegionAttributes<String, Object> regionAttributes) {

    ClientRegionFactoryBean<String, Object> clientRegionFactory = new ClientRegionFactoryBean<>();

    clientRegionFactory.setAttributes(regionAttributes);
    clientRegionFactory.setCache(gemfireCache);
    clientRegionFactory.setClose(false);
    clientRegionFactory.setShortcut(ClientRegionShortcut.CACHING_PROXY_HEAP_LRU);

    return clientRegionFactory;
  }

  @Bean
  public RegionAttributesFactoryBean regionAttributes(
      @Qualifier("entryTtlExpirationAttributes") ExpirationAttributes expirationAttributes) {

    RegionAttributesFactoryBean regionAttributes = new RegionAttributesFactoryBean();

    regionAttributes.setStatisticsEnabled(true);
    regionAttributes.setEntryTimeToLive(expirationAttributes);

    return regionAttributes;
  }

  @Bean
  public ExpirationAttributesFactoryBean entryTtlExpirationAttributes(
      @Value("${gemfire.cache.expiration:600") int timeoutInSeconds) {

    ExpirationAttributesFactoryBean expirationAttributes = new ExpirationAttributesFactoryBean();

    expirationAttributes.setAction(ExpirationActionType.DESTROY.getExpirationAction());
    expirationAttributes.setTimeout(timeoutInSeconds);

    return expirationAttributes;
  }
}

Of course, this configuration is based on Spring Data GemFire 2.0.1.RELEASE (Kay-SR1).

Notice the @ClientCacheApplication annotation, which replaces the need for your clientCacheFactory bean definition.

I also used the new @EnablePdx annotation to configure GemFire's PDX serialization behavior.

I declared a ClientCacheConfigurer typed bean definition (clientCacheHostPortConfigurer) to dynamically adjust the Locator host and port configuration based on property placeholders.

I defined a PropertySourcesPlaceholderConfigurer to handle the property placeholders used in the @Value annotations throughout the Spring, Java-based configuration meta-data.

I also used the new @EnableGemfireCaching annotation which replaces the need to explicitly define a gemfireCacheManager bean definition.  It also enables Spring's Cache Abstraction (specifying @EnableCaching for you).

Anyway, SDG's new Annotation-based configuration model makes it easier to do everything.  But again, you need to be using Spring Data GemFire 2.0+ (SD Kay) with Pivotal GemFire 9.1.x.

Hope this helps!

-John


问:
Simple DOM changes, very weird error
Here's the problem:

Change the 3 divs below (they're not visible) to be 50x50 red squares

```<code><div class="empty"></div>
<div class="empty"></div>
<div class="empty"></div>
</code>```

Built in class that we are changing to:

```<code><style media="screen">
  .red{
    width:50px;
    height:50px;
    background:red;
  }
</code>```

This solution only acts on the first and last div, leaving the middle out:

```<code>let boxes = document.getElementsByClassName('empty');

function addThree(boxes) {
  for (let i = 0; i < boxes.length; i++) {
    boxes[i].className = 'red';
 }
}
addThree(boxes);
</code>```

Solution that does work on all three divs;

```<code>let boxes = document.getElementsByClassName('empty');

function addThree(boxes) {
  for (let i = 0; i < boxes.length; i++) {
    boxes[i].classList.add('red');
 }
}
addThree(boxes);
</code>```

Not really sure what the difference here is, if anyone could give a explanation that would be awesome!

答:
The problem is that document.getElementsByClassName('empty') returns live HTMLCollection. It means the it automatically updates itself when DOM changes. So when you assign (you wipe away previous class empty)

```<code>boxes[0].className = 'red';
</code>```

to the first element that has been empty before, the collection boxes is no longer 3 element, but now only 2.

On the other hand, boxes[i].classList.add('red') won't affect boxes collection length because red class gets added to element (so it becomes empty red - still empty), not overwrites all previous classes.

Title: Simple DOM changes, very weird error

Body:
Here's the problem:

Change the 3 divs below (they're not visible) to be 50x50 red squares

Built in class that we are changing to:

Body:
The problem is that document.getElementsByClassName('empty') returns live HTMLCollection. It means the it automatically updates itself when DOM changes. So when you assign (you wipe away previous class empty)

boxes[0].className = 'red';

to the first element that has been empty before, the collection boxes is no longer 3 element, but now only 2.

On the other hand, boxes[i].classList.add('red') won't affect boxes collection length because red class gets added to element (so it becomes empty red - still empty), not overwrites all previous classes.


问:
Spring get ServletContext and provide it as a Bean

I want to get the ServletContext in a Java Spring Webproject and use
  it to get the absolute path of my web-application project. I'm still a
  beginner in JavaEE and Spring, so maybe I've got some concepts wrong.
  In the java class, in which I want to use the ServletContext, I got
  only an empty object when using   @Autowired ServletContext context;
  But in my RestConfiguartion class, which extends the
  WebMvcConfigurerAdapter class, I got the ServletContext and I'm able
  to use it in a Java Bean, with the return type of ServletContext. But I
  have no idea, how I can use the Bean in another class to get the
  ServletContext, is this possible?

```<code>@Configuration
@EnableWebMvc
@Import({ ServiceConfiguration.class, SecurityConfiguration.class })
@ComponentScan(basePackages = { "de.rest", "de.security" })
public class RestConfiguration extends WebMvcConfigurerAdapter {

  @Autowired
  ServletContext context;

  @Bean
  public ServletContext getServletContext() {
    System.out.println("*** Context path: *** " + context.getRealPath("/"));
    return context;
  }}
</code>```

答:
Thanks to your help I've solved it, by adding the package of my target class to @ComponentScan, declared my target class @Component and inserted the Bean I used before. Theses are the resulting code snippets: </p>

```<code>...
@ComponentScan(basePackages = { "de.rest", "de.security", "de.targetPackage" })
public class RestConfiguration extends WebMvcConfigurerAdapter {
...

@Component
public class targetClass {

  private static String absoluteServletContextPath;

  @Autowired
  ServletContext context;

  @Bean
  public ServletContext getServletContext() {
    absoluteServletContextPath = context.getRealPath("/");
    System.out.println(absoluteServletContextPath);
    return context;
  }

  @Override
  public void myMethod {

        absoluteServletContextPath = absoluteServletContextPath.replaceAll("webapp\\\\", "")
          .replaceAll("\\\\", "/");}}
</code>```

Body:
I want to get the ServletContext in a Java Spring Webproject and use
  it to get the absolute path of my web-application project. I'm still a
  beginner in JavaEE and Spring, so maybe I've got some concepts wrong.
  In the java class, in which I want to use the ServletContext, I got
  only an empty object when using   @Autowired ServletContext context;
  But in my RestConfiguartion class, which extends the
  WebMvcConfigurerAdapter class, I got the ServletContext and I'm able
  to use it in a Java Bean, with the return type of ServletContext. But I
  have no idea, how I can use the Bean in another class to get the
  ServletContext, is this possible?

@Configuration
@EnableWebMvc
@Import({ ServiceConfiguration.class, SecurityConfiguration.class })
@ComponentScan(basePackages = { "de.rest", "de.security" })
public class RestConfiguration extends WebMvcConfigurerAdapter {

  @Autowired
  ServletContext context;

  @Bean
  public ServletContext getServletContext() {
    System.out.println("*** Context path: *** " + context.getRealPath("/"));
    return context;
  }}

Body:
Thanks to your help I've solved it, by adding the package of my target class to @ComponentScan, declared my target class @Component and inserted the Bean I used before. Theses are the resulting code snippets:

...
@ComponentScan(basePackages = { "de.rest", "de.security", "de.targetPackage" })
public class RestConfiguration extends WebMvcConfigurerAdapter {
...

@Component
public class targetClass {

  private static String absoluteServletContextPath;

  @Autowired
  ServletContext context;

  @Bean
  public ServletContext getServletContext() {
    absoluteServletContextPath = context.getRealPath("/");
    System.out.println(absoluteServletContextPath);
    return context;
  }

  @Override
  public void myMethod {

        absoluteServletContextPath = absoluteServletContextPath.replaceAll("webapp\\\\", "")
          .replaceAll("\\\\", "/");}}


问:
VBA Multiple Passwords excel
Afternoon, first off, VBA noob here so take it easy on me and please spell out answers or provide full code as I am not familiar enough to just insert chunks as needed. I need a little more context.

What I am trying to do, is have multiple correct passwords but each password will do something different. This is as far as I have gotten and its current operation is as follows:

```<code>    Sub zebra()

Dim MyPassword As String
    MyPassword = "Zebra" ' Change this to alter password
    If InputBox("Please enter password to continue.", "Enter Password") <> MyPassword Then

    Dim Ans As Boolean
    Const Pword As String = "Zebra" ' This should match password

    Ans = False

    Do While Ans = False
        If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
            Ans = True
        End If
    Loop
Exit Sub
End If

       Sheets("Level 3").Visible = True ' This selects what sheet should become visible

    End Sub
</code>```

Essentially, pop-up window, enter Zebra password, loop if wrong, unlock sheet "level 3 if correct". What I would like is if it could have the password Zebra unlock Level 3 but another password such as "Tiger" would unlock another sheet such as "Level 2".

In the end, what ever the password is, I need a specific and basically unique answer but am unsure how to code multiple passwords.
PLEASE NOTE: I would like to avoid writing multiple codes because the user interface needs to be simple enough for any level of proficiency to click a button, enter a password, and receive the correct information with ALL other information being hidden as it is highly confidential.

答:
This should work, however, you should definitely not use this for sensitive data. If you want to restrict access to diferent sheets for each user, I recommend simply having a separate workbook for each user and having yourself a master file that collects data from all of these workbooks.</p>

```<code>Sub testy2ElectricBoogaloo()
    dim i as long, ans as boolean
    Dim mystr As String
    ans = False
    ReDim arr(1 To Worksheets.Count, 1 To 2)
    For i = 1 To UBound(arr)
     arr(i, 1) = Worksheets(i).Name
    'My code makes every password simply the sheet name followed by a smiley face.
    'Adjust to fit your actual passwords.
     arr(i, 2) = Worksheets(i).Name & " :)"
    Next i
    Do While ans = False
        mystr = InputBox("Please enter password to continue.", "Enter Password")
        If mystr = vbNullString Then Exit Sub
        For i = 1 To ThisWorkbook.Worksheets.Count
        If mystr = arr(i, 2) Then ans = True: Worksheets(arr(i, 1)).Visible = True: Exit For
        Next i
    Loop
End Sub
</code>```

Title: VBA Multiple Passwords excel

Body:
Afternoon, first off, VBA noob here so take it easy on me and please spell out answers or provide full code as I am not familiar enough to just insert chunks as needed. I need a little more context.

What I am trying to do, is have multiple correct passwords but each password will do something different. This is as far as I have gotten and its current operation is as follows:

    Sub zebra()

Dim MyPassword As String
    MyPassword = "Zebra" ' Change this to alter password
    If InputBox("Please enter password to continue.", "Enter Password") <> MyPassword Then

    Dim Ans As Boolean
    Const Pword As String = "Zebra" ' This should match password

    Ans = False

    Do While Ans = False
        If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
            Ans = True
        End If
    Loop
Exit Sub
End If

       Sheets("Level 3").Visible = True ' This selects what sheet should become visible

    End Sub

Essentially, pop-up window, enter Zebra password, loop if wrong, unlock sheet "level 3 if correct". What I would like is if it could have the password Zebra unlock Level 3 but another password such as "Tiger" would unlock another sheet such as "Level 2".

In the end, what ever the password is, I need a specific and basically unique answer but am unsure how to code multiple passwords.
PLEASE NOTE: I would like to avoid writing multiple codes because the user interface needs to be simple enough for any level of proficiency to click a button, enter a password, and receive the correct information with ALL other information being hidden as it is highly confidential.

Body:
This should work, however, you should definitely not use this for sensitive data. If you want to restrict access to diferent sheets for each user, I recommend simply having a separate workbook for each user and having yourself a master file that collects data from all of these workbooks.

Sub testy2ElectricBoogaloo()
    dim i as long, ans as boolean
    Dim mystr As String
    ans = False
    ReDim arr(1 To Worksheets.Count, 1 To 2)
    For i = 1 To UBound(arr)
     arr(i, 1) = Worksheets(i).Name
    'My code makes every password simply the sheet name followed by a smiley face.
    'Adjust to fit your actual passwords.
     arr(i, 2) = Worksheets(i).Name & " :)"
    Next i
    Do While ans = False
        mystr = InputBox("Please enter password to continue.", "Enter Password")
        If mystr = vbNullString Then Exit Sub
        For i = 1 To ThisWorkbook.Worksheets.Count
        If mystr = arr(i, 2) Then ans = True: Worksheets(arr(i, 1)).Visible = True: Exit For
        Next i
    Loop
End Sub


问:
python implemented in assembly
Am just being curious but I would like to know whether python can be implemented in assembly and if not why has it not been done to help for speed issues. forgive my naivete in matters of programming languages.</p>

答:
The main implementation is written in C, and that's compiled to machine code (i.e. assembly made readable for the CPU). So writing it assembly is certainly possible, and if it's possible for a compiler, it's possible for humans - in theory. In practice, it is not even remotely practical. Not only asm is even more low-level than C (increasing development time significantly, perhaps even expotentially to the project size), it's also highly platform-specific, so each port takes a huge lot of work (and maintaince is multiplied by the number of supported platforms - quite a few in the case of CPython).

Apart from that, it's highly questionable if this would give a notable speed bonus. Writing it closer to the metal doesn't make stuff go faster magically (the contrary can be the case - you'd be hard-pressed to find a programmer who can consistently write better assembly than the four or five well-known C compilers). And much of Python's slowness comes from the many many abstractions and indirections the language consists of, not from a sloppy implementation of these.

A more promising approach (which is indeed followed by several alternative implementations) is a clever Just In Time-Compiler (JIT), which preserves all the dynamicness but exploits the fact that most Python programs make little use of that dynamicness by recognizing the most common paths at runtime and optimizing for these. Such complex programs are again not written in asm.

Title: python implemented in assembly


问:
system("foo.exe") requires to close foo in order to continue my program
I don't know if my question is clear, let me explain.

I call this in my main() function:

```<code>system("foo.exe")
</code>```

But, in order to execute following commands, I first need to manually close the foo.exe window.

I tried to use:

```<code>system("taskkill /F /im foo.exe")
</code>```

But it doesn't work.

Does anyone have an idea what to do?

答:
A simple solution:</p>

```<code>std::system("start foo.exe")
</code>```

Body:
I don't know if my question is clear, let me explain.

I call this in my main() function:

system("foo.exe")

But, in order to execute following commands, I first need to manually close the foo.exe window.

I tried to use:

system("taskkill /F /im foo.exe")

But it doesn't work.

Does anyone have an idea what to do?

Body:
A simple solution:

std::system("start foo.exe")


问:
Play Framework and Docker production configuration
I use PlayFramework 2.6 with Docker. I build and publish image with sbt:dockerPublish and then deploy it with Ansible to Amazon EC2 Instance.
I want to get powerful instance for production and my question is:

Do I need to change configuration for docker and play to achieve best performance?

I want instance with 4 CPU cores and 16 GB RAM. I had issues before running Play on plain Ubuntu with 1GB RAM without swap, would I run into same memory issues with Docker even there will be 16GB?

答:
Memory

You'll need some memory for the OS—say 100MB. Inside the Java VM you'll need some basic memory for Play—say 32MB. The rest of the memory in your VM will depend on your application: how many concurrent users, how memory-intensive its work is, how much you've optimised it.

If your machine/VM/container has 1GB of RAM then set the Java VM max heap size to less than this using Java's -Xmx768M option so that you don't cause your machine to swap.

CPU

Play is designed to use all cores by default. If needed you can tune it further. The configuration is documented here:

https://www.playframework.com/documentation/2.6.x/ThreadPools#Configuring-the-default-thread-pool


答:
Here is another example </p>

```<code>Option Base 1
Sub CheckPassword()
Dim allPasswords(3)
allPasswords(1) = "Zebra"
allPasswords(2) = "Tiger"
allPasswords(3) = "Monkey"

Dim passwordEntered As String
Dim iChanceCount As Integer
Dim ws As Worksheet

Do While True
    passwordEntered = InputBox("Please enter password to continue.", "Enter Password")
    If passwordEntered = allPasswords(1) Then
        Set ws = Sheets("Level 1")
    Else
        If passwordEntered = allPasswords(2) Then
            Set ws = Sheets("Level 2")
        Else
            If passwordEntered = allPasswords(3) Then
                Set ws = Sheets("Level 3")
            End If
        End If
    End If
    'see if we set the worksheet
    If ws Is Nothing Then
        iChanceCount = iChanceCount + 1
        'give them 5 tries then exit
        If iChanceCount >= 5 Then Exit Sub
    Else
        'we have a worksheet so make it visible and exit
        ws.Visible = xlSheetVisible
        Exit Sub
    End If

Loop

End Sub
</code>```

Title: VBA Multiple Passwords excel

Body:
Here is another example

Option Base 1
Sub CheckPassword()
Dim allPasswords(3)
allPasswords(1) = "Zebra"
allPasswords(2) = "Tiger"
allPasswords(3) = "Monkey"

Dim passwordEntered As String
Dim iChanceCount As Integer
Dim ws As Worksheet

Do While True
    passwordEntered = InputBox("Please enter password to continue.", "Enter Password")
    If passwordEntered = allPasswords(1) Then
        Set ws = Sheets("Level 1")
    Else
        If passwordEntered = allPasswords(2) Then
            Set ws = Sheets("Level 2")
        Else
            If passwordEntered = allPasswords(3) Then
                Set ws = Sheets("Level 3")
            End If
        End If
    End If
    'see if we set the worksheet
    If ws Is Nothing Then
        iChanceCount = iChanceCount + 1
        'give them 5 tries then exit
        If iChanceCount >= 5 Then Exit Sub
    Else
        'we have a worksheet so make it visible and exit
        ws.Visible = xlSheetVisible
        Exit Sub
    End If

Loop

End Sub


答:
You are CHANGING the class on each element mid-loop. So once you've changed the first class, your boxes array shortens in length, and skips the first element.

You either want to ADD the class 'red' or if you want to change it, first push the divs into a different array and iterate over that

Title: Simple DOM changes, very weird error


问:
Self-referencing models in Rails 3
I have an Entity model and I want to display connections between the Entities. ie, Entity 1 is connected to Entity 2.

My thinking, right now, is to create a join model between the two called Connection and have it work like a traditional rails join table. Except have the columns be entity_one_id and entity_two_id, then establish a many-to-many relationship between Entity and Connection.

This seems like a really not-elegant way to do this. I was wondering if anyone had any better ideas? Maybe something more rails-esque that I'm just not seeing?

答:
You could use this implementation:</p>

```<code>class User < ActiveRecord::Base
  has_many :friends, :through => :friendships, :conditions => "status = 'accepted'"
  has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at
  has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at
  has_many :friendships, :dependent => :destroy
end

class Friendship < ActiveRecord::Base
   belongs_to :user
   belongs_to :friend, :class_name => "User"
end
</code>```

Title: Self-referencing models in Rails 3

Body:
You could use this implementation:

class User < ActiveRecord::Base
  has_many :friends, :through => :friendships, :conditions => "status = 'accepted'"
  has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at
  has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at
  has_many :friendships, :dependent => :destroy
end

class Friendship < ActiveRecord::Base
   belongs_to :user
   belongs_to :friend, :class_name => "User"
end