答:
Firstly, fix the keys within the JSON column by adding quotes for each, and values by adding quotes for some which starts with zeroes and go on with other digits.

Then apply :

```<code>UPDATE tab
   SET Col = JSON_SET(
       Col,
       "$.people.Man.Employee", "50",
       "$.people.Man.Employee", "51"
       )
 WHERE ID = 1234567890;
</code>```

Demo

Title: Update nested Json in Mysql/Mariadb

Body:
{
  "people": {
    "Man": {
      "Employee": "50",
      "Student": "91",
      "Artist": "80",
      "Clark": "50"
    },
    "Woman": {
      "Employee": "21",
      "Student": "01",
      "Artist": "00",
      "k3": "30",
      "Clark": "68"
    }
  }
}

How can I Update Employee Value From Man Object. I want something similar to below mysql query.

UPDATE TABLE
   SET Column = JSON_SET(Column, '$.people.Man.Employee', '51')
  WHERE Id=1234567890;

MariaDB [**********]> SELECT VERSION();

+--------------------------------------------+
| VERSION()                                  |
+--------------------------------------------+
| 10.3.17-MariaDB-1:10.3.17+maria~bionic-log |
+--------------------------------------------+

Body:
Firstly, fix the keys within the JSON column by adding quotes for each, and values by adding quotes for some which starts with zeroes and go on with other digits.

Then apply :

UPDATE tab
   SET Col = JSON_SET(
       Col,
       "$.people.Man.Employee", "50",
       "$.people.Man.Employee", "51"
       )
 WHERE ID = 1234567890;

Demo


来源: stackexchange

问:
run a javascript function for specific css .class selectors
I have a JavaScript library and it uses this function for example to convert English numbers to Persian:

```<code>persianJs("345").englishNumber().toString(); //returns: ۳۴۵
</code>```

I have an html structure to show some dynamic numerical values like this:

```<code><span class="price"><!-- price amount  --></span>
</code>```

How can I run the JavaScript function in header or footer to display any price amount in Persian format?

答:
you can use  document.getElementsByClassName("price")[0].innerText

//var pNumber =persianJs("345").englishNumber().toString(); //returns: ۳۴۵
var pNumber="۳۴۵";
document.getElementsByClassName("price")[0].innerText=pNumber;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="price"><!-- price amount  --></span></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a JavaScript library and it uses this function for example to convert English numbers to Persian:

persianJs("345").englishNumber().toString(); //returns: ۳۴۵

I have an html structure to show some dynamic numerical values like this:

How can I run the JavaScript function in header or footer to display any price amount in Persian format?

Body:
you can use  document.getElementsByClassName("price")[0].innerText

//var pNumber =persianJs("345").englishNumber().toString(); //returns: ۳۴۵
var pNumber="۳۴۵";
document.getElementsByClassName("price")[0].innerText=pNumber;

<span class="price"><!-- price amount  --></span>


问:
input file Update images inside database
So im trying to change the image thats already inside the database but i cant seem to make it work i kept looking at tutorials and other related questions but couldnt find the exact solution.

this is what i have in php

```<code>// Als de knop van de formulier is ingedrukt update de data dat van de database afkomt

if (isset($_POST['update'])) {

if (isset($_GET['id'])) {
          $chauffeurs_id = $_GET['id'];
        }

if (isset($_POST['Chauffeurs_foto'])) {
            $Chauffeurs_foto = $_POST['Chauffeurs_foto'];
        }

$sql = "SELECT * FROM chauffeurs ORDER BY 'chauffeurs_geboortedatum ASC";
        $sql = "UPDATE `chauffeurs`
        SET `Chauffeurs_foto`=$Chauffeurs_foto
        WHERE `id`='$chauffeurs_id'";

$result = $conn->query($sql);

        if ($result == TRUE){
            echo "Aanpassingen zijn voltooid.";
        }else{
            echo "Error:" . $sql . "<br>" . $conn->error;
        }
    }

if (isset($_GET['id'])) {
      $id = $_GET['id'];

$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $id = $row['id'];
            $chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];
</code>```

Here is my html code:

```<code><!-- Formulier waar alles in komt om te veranderen -->
<form action="" method="post" enctype='multipart/form-data' >
          <fieldset>
           <legend>Gegevens chauffeur:</legend>
             <div class="form-group col-md-4">

//I did it like this so i could style the input file

<input type="file" name="file" id="file"  class="inputfile" value="data:image/jpeg;base64, <?php.base64_encode($row['chauffeurs_foto']).?>" />
<label class="btn btn primary"for="file">Choose a file</label>

<input type="submit" value="Chauffeur Aanpassen" name="update">
</fieldset>
</form>
</div>
</code>```

If anyone of you has a solution i would greatly appreciate it cause i need to finish it for my internship if not i'm just going to keep searching.

答:
Assuming this is for a real application, you should properly escape SQL values for security reasons. Never trust user input! I'm going to assume you're using mysqli, so I'm using mysql::real_escape_string().

Also, you should properly embed your variables in the query, like so:

if (isset($_GET['id'])) {
  $chauffeurs_id = $conn->real_escape_string($_GET['id']);
}

if (isset($_POST['Chauffeurs_foto'])) {
  $Chauffeurs_foto = $conn->real_escape_string($_POST['Chauffeurs_foto']);
}

$sql = "SELECT * FROM chauffeurs ORDER BY `chauffeurs_geboortedatum` ASC"; // This statement can you remove, it will never be used in this way
$sql = "UPDATE `chauffeurs` SET `Chauffeurs_foto` = '{$Chauffeurs_foto}' WHERE `id`='{$chauffeurs_id}'";
```

Succes ermee.

Body:
So im trying to change the image thats already inside the database but i cant seem to make it work i kept looking at tutorials and other related questions but couldnt find the exact solution.

this is what i have in php

// Als de knop van de formulier is ingedrukt update de data dat van de database afkomt

if (isset($_POST['update'])) {

if (isset($_GET['id'])) {
          $chauffeurs_id = $_GET['id'];
        }

if (isset($_POST['Chauffeurs_foto'])) {
            $Chauffeurs_foto = $_POST['Chauffeurs_foto'];
        }

$sql = "SELECT * FROM chauffeurs ORDER BY 'chauffeurs_geboortedatum ASC";
        $sql = "UPDATE `chauffeurs`
        SET `Chauffeurs_foto`=$Chauffeurs_foto
        WHERE `id`='$chauffeurs_id'";

$result = $conn->query($sql);

        if ($result == TRUE){
            echo "Aanpassingen zijn voltooid.";
        }else{
            echo "Error:" . $sql . "
" . $conn->error;
        }
    }

if (isset($_GET['id'])) {
      $id = $_GET['id'];

$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $id = $row['id'];
            $chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];

Here is my html code:

<form action="" method="post" enctype='multipart/form-data' >
          <fieldset>
           <legend>Gegevens chauffeur:</legend>

//I did it like this so i could style the input file

<input type="file" name="file" id="file"  class="inputfile" value="data:image/jpeg;base64, <?php.base64_encode($row['chauffeurs_foto']).?>" />
Choose a file

<input type="submit" value="Chauffeur Aanpassen" name="update">
</fieldset>
</form>

If anyone of you has a solution i would greatly appreciate it cause i need to finish it for my internship if not i'm just going to keep searching.

Body:
Assuming this is for a real application, you should properly escape SQL values for security reasons. Never trust user input! I'm going to assume you're using mysqli, so I'm using mysql::real_escape_string().

Also, you should properly embed your variables in the query, like so:

if (isset($_GET['id'])) {
  $chauffeurs_id = $conn->real_escape_string($_GET['id']);
}

if (isset($_POST['Chauffeurs_foto'])) {
  $Chauffeurs_foto = $conn->real_escape_string($_POST['Chauffeurs_foto']);
}

$sql = "SELECT * FROM chauffeurs ORDER BY `chauffeurs_geboortedatum` ASC"; // This statement can you remove, it will never be used in this way
$sql = "UPDATE `chauffeurs` SET `Chauffeurs_foto` = '{$Chauffeurs_foto}' WHERE `id`='{$chauffeurs_id}'";

Succes ermee.


问:
android: ZoomPicker breaks onTouchListener
I've got a webview which makes use of the built in zoom controls, as follows:

```<code>wv = new WebView(this);
wv.getSettings().setBuiltInZoomControls(true);
</code>```

Note: this activates two main functions - pinch-to-zoom and invokeZoomPicker() (the latter is only called when a swiping action is done on the view, a simple touch doesn't enable it)

and i also want things to happen when touch events occur, using the following

```<code>wv.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        Log.i("touch", "touched!");
        return false;
    }
});
</code>```

When the WebView loads, and I tap the screen, the log states "touched" every time I interact with the screen, as expected. However, if I do something that would set off invokeZoomPicker() (pinch to zoom doesn't seem to cause this problem, as long as the zoom widget doesn't appear), onTouchListener stops responding to my taps (even after a few seconds, when the widget disappears from view).

To make sure it was invokeZoomPicker(), I edited the second segment of my code as follows:

```<code>wv.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        wv.invokeZoomPicker();
        Log.i("touch", "touched!");
        return false;
    }
});
</code>```

This new onTouch method now only triggers once (as a result of which the zoomwidget appears on the view - and disappears a few seconds later), and then the onTouch method doesn't get called again until the view is reloaded - so it is definitely a problem with the invokeZoomPicker()/Zoom widget

Have I missed some vital piece of code that allows them to coexist, or do I just have to choose which one I can live without?

答:
I think there is some exclusivity, for example, for a 500x500 web view and you zoom it in to 1000x1000, then you touched on it, now what position should it report?

But I really need to get them working together.

ContentLicense: CC BY-SA 2.5

Body:
I've got a webview which makes use of the built in zoom controls, as follows:

wv = new WebView(this);
wv.getSettings().setBuiltInZoomControls(true);

Note: this activates two main functions - pinch-to-zoom and invokeZoomPicker() (the latter is only called when a swiping action is done on the view, a simple touch doesn't enable it)

and i also want things to happen when touch events occur, using the following

wv.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        Log.i("touch", "touched!");
        return false;
    }
});

When the WebView loads, and I tap the screen, the log states "touched" every time I interact with the screen, as expected. However, if I do something that would set off invokeZoomPicker() (pinch to zoom doesn't seem to cause this problem, as long as the zoom widget doesn't appear), onTouchListener stops responding to my taps (even after a few seconds, when the widget disappears from view).

To make sure it was invokeZoomPicker(), I edited the second segment of my code as follows:

wv.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        wv.invokeZoomPicker();
        Log.i("touch", "touched!");
        return false;
    }
});

This new onTouch method now only triggers once (as a result of which the zoomwidget appears on the view - and disappears a few seconds later), and then the onTouch method doesn't get called again until the view is reloaded - so it is definitely a problem with the invokeZoomPicker()/Zoom widget

Have I missed some vital piece of code that allows them to coexist, or do I just have to choose which one I can live without?

ContentLicense: CC BY-SA 3.0


问:
Vertical align the child elements with different height
I am trying to achieve a vertically aligned child elements which have different heights.

Following is what I want to implement. Currently I set a different negative top margin on both buttons. I feel this can be done in a more cleaner way with a single generic ruling. Please share your thoughts.

Following is the code to illustrate the problem:

.container {
  padding: 35px 2px;
  border: 1px solid gray;
}

.title {
  font-size: 18px;
}

.action-button {
  float: right;
  height: 50px;
  width: 100px;

}

.small-screen {
  width: 160px;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>HTML:

<div class="container">

  <span class="title">
    Card header
  </span>

  <button class="action-button">
    Action
  </button>

</div>

<br/>

<div class="container">

  <span class="title small-screen">
    Card header title here is longer
  </span>

  <button class="action-button">
    Action
  </button>

</div></code>```

Link to JSFiddle

答:
You could use absolute positioning instead of floating.

Add the line position: relative to your .container class to make sure that the buttons are positioned within this element.

Then remove the float from the .action-button class and instead add:

margin: 0;
position: absolute;
right: 20px;
top: 50%;
-ms-transform: translateY(-50%);
transform: translateY(-50%);
```

<p>Here is the full working code snippet:</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-css lang-css prettyprint-override"><code>.container {
  padding: 35px 2px;
  border: 1px solid gray;

  position: relative;
}

.title {
  font-size: 18px;
}

.action-button {
  height: 50px;
  width: 100px;

  margin: 0;
  position: absolute;
  right: 20px;
  top: 50%;
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);

}

.small-screen {
  width: 160px;
  display: inline-block;
}</code>```

    Card header

  <button class="action-button">
    Action
  </button>

    Card header title here is longer

  <button class="action-button">
    Action
  </button>

```

Body:
I am trying to achieve a vertically aligned child elements which have different heights.

Following is what I want to implement. Currently I set a different negative top margin on both buttons. I feel this can be done in a more cleaner way with a single generic ruling. Please share your thoughts.

Following is the code to illustrate the problem:

.container {
  padding: 35px 2px;
  border: 1px solid gray;
}

.title {
  font-size: 18px;
}

.action-button {
  float: right;
  height: 50px;
  width: 100px;

}

.small-screen {
  width: 160px;
  display: inline-block;
}

HTML:

    Card header

  <button class="action-button">
    Action
  </button>

    Card header title here is longer

  <button class="action-button">
    Action
  </button>

Link to JSFiddle

Body:
You could use absolute positioning instead of floating.

Add the line position: relative to your .container class to make sure that the buttons are positioned within this element.

Then remove the float from the .action-button class and instead add:

margin: 0;
position: absolute;
right: 20px;
top: 50%;
-ms-transform: translateY(-50%);
transform: translateY(-50%);

Here is the full working code snippet:

.container {
  padding: 35px 2px;
  border: 1px solid gray;

  position: relative;
}

.title {
  font-size: 18px;
}

.action-button {
  height: 50px;
  width: 100px;

  margin: 0;
  position: absolute;
  right: 20px;
  top: 50%;
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);

}

.small-screen {
  width: 160px;
  display: inline-block;
}

<div class="container">

  <span class="title">
    Card header
  </span>

  <button class="action-button">
    Action
  </button>

</div>

<br/>

<div class="container">

  <span class="title small-screen">
    Card header title here is longer
  </span>

  <button class="action-button">
    Action
  </button>

</div>


问:
Grouping a collection with the related objects
I have a group of tasks where a task may be linked to another one via the runs_with field as shown below.

```<code><Task id: 'abc', name: 'paint the fance', progressive: 1, runs_with: nil>
<Task id: 'def', name: 'mow the lawn', progressive: 2, runs_with: 1>
<Task id: 'ghi', name: 'wash the dishes', progressive: 3, runs_with: nil>
<Task id: 'xyz', name: 'take out the trash', progressive: 4, runs_with: 3>
<Task id: 'qur', name: 'wash the car', progressive: 5, runs_with: 2>
<Task id: 'gbj', name: 'walk the dog', progressive: 6, runs_with: 3>
</code>```

Now I need to group them so all the linked ones end up in a group (an array).

```<code>[[<Task id: 'abc', name: 'paint the fance', progressive: 1, runs_with: nil>,
  <Task id: 'def', name: 'mow the lawn', progressive: 2, runs_with: 1>,
  <Task id: 'qur', name: 'wash the car', progressive: 5, runs_with: 2>],
 [<Task id: 'ghi', name: 'wash the dishes', progressive: 3, runs_with: nil>,
  <Task id: 'xyz', name: 'take out the trash', progressive: 4, runs_with: 3>,
  <Task id: 'gbj', name: 'walk the dog', progressive: 6, runs_with: 3>]]
</code>```

My initial idea is to

partition on runs_with.

create a group for each task that can run alone.

loop through the other tasks and append them to the group including the linked task.

Wondering if there is any more idiomatic way to group them.

答:
Here's how I would approach it. Given a Task class and an array of tasks:

```<code>class Task
  ATTRIBUTES = [:id, :name, :progressive, :runs_with]
  attr_accessor *ATTRIBUTES
  include ActiveModel::Model

  def inspect
    '<Task %s>' % ATTRIBUTES.map { |a| '%s: %s' % [a, send(a).inspect] }.join(', ')
  end
end

tasks = [
  Task.new(id: 'abc', name: 'paint the fance', progressive: 1, runs_with: nil),
  Task.new(id: 'def', name: 'mow the lawn', progressive: 2, runs_with: 1),
  Task.new(id: 'ghi', name: 'wash the dishes', progressive: 3, runs_with: nil),
  Task.new(id: 'xyz', name: 'take out the trash', progressive: 4, runs_with: 3),
  Task.new(id: 'qur', name: 'wash the car', progressive: 5, runs_with: 2),
  Task.new(id: 'gbj', name: 'walk the dog', progressive: 6, runs_with: 3)
]
</code>```

I would create a hash where each value would be the task wrapped in an array with its number as the key:

```<code>hash = tasks.group_by(&:progressive)

{
  1 => [<Task id: "abc", name: "paint the fance", progressive: 1, runs_with: nil>],
  2 => [<Task id: "def", name: "mow the lawn", progressive: 2, runs_with: 1>],
  3 => [<Task id: "ghi", name: "wash the dishes", progressive: 3, runs_with: nil>],
  4 => [<Task id: "xyz", name: "take out the trash", progressive: 4, runs_with: 3>],
  5 => [<Task id: "qur", name: "wash the car", progressive: 5, runs_with: 2>],
  6 => [<Task id: "gbj", name: "walk the dog", progressive: 6, runs_with: 3>]
}
</code>```

Then I would traverse the original tasks array and for each task with a runs_with attribute, merge the task's array with the corresponding task's array into one:

```<code>tasks.each do |task|
  if task.runs_with
    hash[task.runs_with].concat(hash[task.progressive])
    hash[task.progressive] = hash[task.runs_with]
  end
end
</code>```

This will effectively merge the arrays and reduce the number of arrays along the way. The hash however will refer to those (identical) arrays from different keys, so in the end we have to fetch the hash's unique values:

```<code>hash.values.uniq
#=> [[<Task id: "abc", name: "paint the fance", progressive: 1, runs_with: nil>,
#     <Task id: "def", name: "mow the lawn", progressive: 2, runs_with: 1>,
#     <Task id: "qur", name: "wash the car", progressive: 5, runs_with: 2>],
#    [<Task id: "ghi", name: "wash the dishes", progressive: 3, runs_with: nil>,
#     <Task id: "xyz", name: "take out the trash", progressive: 4, runs_with: 3>,
#     <Task id: "gbj", name: "walk the dog", progressive: 6, runs_with: 3>]]
</code>```

Body:
I have a group of tasks where a task may be linked to another one via the runs_with field as shown below.

<Task id: 'abc', name: 'paint the fance', progressive: 1, runs_with: nil>
<Task id: 'def', name: 'mow the lawn', progressive: 2, runs_with: 1>
<Task id: 'ghi', name: 'wash the dishes', progressive: 3, runs_with: nil>
<Task id: 'xyz', name: 'take out the trash', progressive: 4, runs_with: 3>
<Task id: 'qur', name: 'wash the car', progressive: 5, runs_with: 2>
<Task id: 'gbj', name: 'walk the dog', progressive: 6, runs_with: 3>

Now I need to group them so all the linked ones end up in a group (an array).

[[<Task id: 'abc', name: 'paint the fance', progressive: 1, runs_with: nil>,
  <Task id: 'def', name: 'mow the lawn', progressive: 2, runs_with: 1>,
  <Task id: 'qur', name: 'wash the car', progressive: 5, runs_with: 2>],
 [<Task id: 'ghi', name: 'wash the dishes', progressive: 3, runs_with: nil>,
  <Task id: 'xyz', name: 'take out the trash', progressive: 4, runs_with: 3>,
  <Task id: 'gbj', name: 'walk the dog', progressive: 6, runs_with: 3>]]

My initial idea is to

partition on runs_with.

create a group for each task that can run alone.

loop through the other tasks and append them to the group including the linked task.

Wondering if there is any more idiomatic way to group them.

Body:
Here's how I would approach it. Given a Task class and an array of tasks:

class Task
  ATTRIBUTES = [:id, :name, :progressive, :runs_with]
  attr_accessor *ATTRIBUTES
  include ActiveModel::Model

  def inspect
    '<Task %s>' % ATTRIBUTES.map { |a| '%s: %s' % [a, send(a).inspect] }.join(', ')
  end
end

tasks = [
  Task.new(id: 'abc', name: 'paint the fance', progressive: 1, runs_with: nil),
  Task.new(id: 'def', name: 'mow the lawn', progressive: 2, runs_with: 1),
  Task.new(id: 'ghi', name: 'wash the dishes', progressive: 3, runs_with: nil),
  Task.new(id: 'xyz', name: 'take out the trash', progressive: 4, runs_with: 3),
  Task.new(id: 'qur', name: 'wash the car', progressive: 5, runs_with: 2),
  Task.new(id: 'gbj', name: 'walk the dog', progressive: 6, runs_with: 3)
]

I would create a hash where each value would be the task wrapped in an array with its number as the key:

hash = tasks.group_by(&:progressive)

{
  1 => [<Task id: "abc", name: "paint the fance", progressive: 1, runs_with: nil>],
  2 => [<Task id: "def", name: "mow the lawn", progressive: 2, runs_with: 1>],
  3 => [<Task id: "ghi", name: "wash the dishes", progressive: 3, runs_with: nil>],
  4 => [<Task id: "xyz", name: "take out the trash", progressive: 4, runs_with: 3>],
  5 => [<Task id: "qur", name: "wash the car", progressive: 5, runs_with: 2>],
  6 => [<Task id: "gbj", name: "walk the dog", progressive: 6, runs_with: 3>]
}

Then I would traverse the original tasks array and for each task with a runs_with attribute, merge the task's array with the corresponding task's array into one:

tasks.each do |task|
  if task.runs_with
    hash[task.runs_with].concat(hash[task.progressive])
    hash[task.progressive] = hash[task.runs_with]
  end
end

This will effectively merge the arrays and reduce the number of arrays along the way. The hash however will refer to those (identical) arrays from different keys, so in the end we have to fetch the hash's unique values:

hash.values.uniq
#=> [[<Task id: "abc", name: "paint the fance", progressive: 1, runs_with: nil>,
#     <Task id: "def", name: "mow the lawn", progressive: 2, runs_with: 1>,
#     <Task id: "qur", name: "wash the car", progressive: 5, runs_with: 2>],
#    [<Task id: "ghi", name: "wash the dishes", progressive: 3, runs_with: nil>,
#     <Task id: "xyz", name: "take out the trash", progressive: 4, runs_with: 3>,
#     <Task id: "gbj", name: "walk the dog", progressive: 6, runs_with: 3>]]


问:
How to start jenkins on different port rather than 8080 using command prompt in Windows?
I have jenkins.war and I started it from command prompt in Windows as:

```<code>java -jar jenkins.war
</code>```

It was started well and easily browsed as http://localhost:8080

I want to start on 9090 port. How can I do that?

答:
Open Command Prompt as Administrator in Windows .
Go to the directory where Jenkins is installed.
and stop the Jenkins service first, using jenkins.exe stop

type the command to change the port using, java -jar jenkins.war --httpPort=9090 (enter the port number you want to use).

and at-last, restart the Jenkins services, using jenkins.exe restart

Body:
I have jenkins.war and I started it from command prompt in Windows as:

java -jar jenkins.war

It was started well and easily browsed as http://localhost:8080

I want to start on 9090 port. How can I do that?


问:
React Cannot read property 'lastName' of undefined
I'm trying to merge data from two API in the new API but I'm getting error Uncaught TypeError: Cannot read property 'lastName' of undefined. This is happening because is not finding lastName when it missing in API2. In this case, I want to initialize it as empty string if not able to find that in the merged API.

API 1 look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
}
}
</code>```

API2 look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1'
 }
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3'
}
}
</code>```

Merged API look:

```<code>data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second Test' //lastName from API 2 + name from API 1
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
lastName: '' //lastName from API 2 + name from API 1
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1 Test 2' //lastName from API 2 + name from API 1
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3 Test 3' //lastName from API 2 + name from API 1
}
</code>```

Fetched data:

```<code>const [api1, setApi1] = useState([]);
const [api2, setApi2] = useState([]);
const [mergeApi, setMergeAPi] = useState([]);

useEffect(() => {
  fetch('api1')
  .then((response) => {
    setApi1(response);
  });
});

useEffect(() => {
  fetch('api2')
  .then((response) => {
    setApi2(response);
  });
});

useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name;
    });
    return {
      ...api1,
      // name: `${d.name} - ${d.lastName}`
      name: d ? `${d.name} - ${d.lastName}` : ""; // solution there
    }
  });
});
</code>```

答:
Try something like this.
1) api1 and api2 data look like object, have Object.values to get array of values.

2) Change to find function. Checking obj2.name === obj1.name

3) check for d value before using.

const api1 = {
  0: {
    id: 1234,
    company: "String",
    name: "Test"
  },
  1: {
    id: 2345,
    company: "String1",
    name: "Test 1"
  },
  2: {
    id: 3456,
    company: "String2",
    name: "Test 2"
  },
  3: {
    id: 4567,
    company: "String3",
    name: "Test 3"
  }
};

const api2 = {
  0: {
    id: 1234,
    company: "String",
    name: "Test",
    lastName: "Second"
  },
  1: {
    id: 2345,
    company: "String1",
    name: "Test 1"
  },
  2: {
    id: 3456,
    company: "String2",
    name: "Test 2",
    lastName: "Second 1"
  },
  3: {
    id: 4567,
    company: "String3",
    name: "Test 3",
    lastName: "Second 3"
  }
};

const data = Object.values(api1).map(obj1 => {
  const d = Object.values(api2).find(obj2 => obj2.name === obj1.name);
  return {
    ...obj1,
    name: d ? `${d.name} - ${d.lastName}` : obj1
  };
});

console.log(data);```

Body:
I'm trying to merge data from two API in the new API but I'm getting error Uncaught TypeError: Cannot read property 'lastName' of undefined. This is happening because is not finding lastName when it missing in API2. In this case, I want to initialize it as empty string if not able to find that in the merged API.

API 1 look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
}
}

API2 look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1'
 }
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3'
}
}

Merged API look:

data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second Test' //lastName from API 2 + name from API 1
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
lastName: '' //lastName from API 2 + name from API 1
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1 Test 2' //lastName from API 2 + name from API 1
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3 Test 3' //lastName from API 2 + name from API 1
}

Fetched data:

const [api1, setApi1] = useState([]);
const [api2, setApi2] = useState([]);
const [mergeApi, setMergeAPi] = useState([]);

useEffect(() => {
  fetch('api1')
  .then((response) => {
    setApi1(response);
  });
});

useEffect(() => {
  fetch('api2')
  .then((response) => {
    setApi2(response);
  });
});

useEffect(() => {
  const data = api1.map(getData => {
    const d = api2.find((object) => {
      // return  object.name === api1.name;
      return  object.name === getData.name;
    });
    return {
      ...api1,
      // name: `${d.name} - ${d.lastName}`
      name: d ? `${d.name} - ${d.lastName}` : ""; // solution there
    }
  });
});


问:
Searching For Existing Values in Array
I have been trying to search for an existing value in an array like below

```<code>var values = []
values.push(localStorage.getItem('items'));

console.log(values);

if (values.includes(2)) {
  alert('Already Exists.');
}
</code>```

When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.

My challenge is how to find the value 2 in the array values ?

答:
Hope this help you.

    var names_arr = '["1,2,3,4,5,6"]';
names_arr = names_arr.replace("'",'');

function checkValue(value,arr){
  var status = 'Not exist';

  for(var i=0; i<arr.length; i++){
    var name = arr[i];
    if(name == value){
      status = 'Exist';
      break;
    }
  }

  return status;
}
console.log('status : ' + checkValue('3', names_arr) );
console.log('status : ' + checkValue('10', names_arr) );```

Title: Searching For Existing Values in Array

Body:
I have been trying to search for an existing value in an array like below

var values = []
values.push(localStorage.getItem('items'));

console.log(values);

if (values.includes(2)) {
  alert('Already Exists.');
}

When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.

My challenge is how to find the value 2 in the array values ?


问:
How to use template-ized value in the range function in Helm
I am using helm chart for Prometheus and am planning to provide different set of alert manager files for different environments.
Extracted portion of existing Chart:

```<code>{{- $root := . -}}
{{- range $key, $value := .Values.alertmanagerFiles }}
  {{ $key }}: |
{{ toYaml $value | default "{}" | indent 4 }}
{{- end -}}
</code>```

To override this part, I have a defined template variable

```<code>{{- define "prometheus.alertmanagerFiles" -}}
{{- if .Values.alertmanagerFiles.custom -}}
    {{- printf "alertmanagerFiles_%s" .Values.cluster.env }}
{{- else -}}
    {{- default "default" .Values.alertmanagerFiles -}}
{{- end -}}
{{- end -}}
</code>```

With this, I have a new variable per environment - example: alertmanagerFiles_dev for development but am clueless because of my lack of knowledge, I don't know about how to use template-ized variable in the range function.

Tried this but does not work:

```<code>{{- $root := . -}}
{{- range $key, $value := template "prometheus.alertmanagerFiles" . }}
  {{ $key }}: |
{{ toYaml $value | default "{}" | indent 4 }}
{{- end -}}
</code>```

any help, clue or direction will help me here.

答:
You don't need to customize the chart for this.  Instead, you can provide a different set of values per environment when you helm install or helm upgrade the chart

```<code>helm upgrade prometheus stable/prometheus --install -f values.dev.yaml
</code>```

This is generally much easier and preferable to putting a layer of indirection inside the template code.

If you do want to use the layer of indirection as you've shown, you're limited by the possible return types of the Go templating.  The standard Go template directive only writes to output and never returns anything.  Helm has an include function that instead returns the content of the rendered template as a string.  That's the only thing it's possible to return from a template, though.

In your case the prometheus.alertmanagerFiles template produces a string, so you can include it to get the name of the top-level value you want to include.  Then you can use the standard Go template index function to pluck that item out of .Values.  This roughly looks like:

```<code>{{- $fileKey := include "prometheus.alertmanagerFiles" . }}
{{- range $key, $value := index .Values $fileKey }}
...
{{- end -}}
</code>```

Body:
I am using helm chart for Prometheus and am planning to provide different set of alert manager files for different environments.
Extracted portion of existing Chart:

{{- $root := . -}}
{{- range $key, $value := .Values.alertmanagerFiles }}
  {{ $key }}: |
{{ toYaml $value | default "{}" | indent 4 }}
{{- end -}}

To override this part, I have a defined template variable

{{- define "prometheus.alertmanagerFiles" -}}
{{- if .Values.alertmanagerFiles.custom -}}
    {{- printf "alertmanagerFiles_%s" .Values.cluster.env }}
{{- else -}}
    {{- default "default" .Values.alertmanagerFiles -}}
{{- end -}}
{{- end -}}

With this, I have a new variable per environment - example: alertmanagerFiles_dev for development but am clueless because of my lack of knowledge, I don't know about how to use template-ized variable in the range function.

Tried this but does not work:

{{- $root := . -}}
{{- range $key, $value := template "prometheus.alertmanagerFiles" . }}
  {{ $key }}: |
{{ toYaml $value | default "{}" | indent 4 }}
{{- end -}}

any help, clue or direction will help me here.

Body:
You don't need to customize the chart for this.  Instead, you can provide a different set of values per environment when you helm install or helm upgrade the chart

helm upgrade prometheus stable/prometheus --install -f values.dev.yaml

This is generally much easier and preferable to putting a layer of indirection inside the template code.

If you do want to use the layer of indirection as you've shown, you're limited by the possible return types of the Go templating.  The standard Go template directive only writes to output and never returns anything.  Helm has an include function that instead returns the content of the rendered template as a string.  That's the only thing it's possible to return from a template, though.

In your case the prometheus.alertmanagerFiles template produces a string, so you can include it to get the name of the top-level value you want to include.  Then you can use the standard Go template index function to pluck that item out of .Values.  This roughly looks like:

{{- $fileKey := include "prometheus.alertmanagerFiles" . }}
{{- range $key, $value := index .Values $fileKey }}
...
{{- end -}}


答:
localStorage can only hold strings. As such you need to convert the value you retrieve in to an array, which can be done using split().

Also note that the resulting array will contain string values, so you need to use includes('2'). Try this:

var values = "1,2,3".split(','); // just for this demo
//var values = localStorage.getItem('items').split(',');
console.log(values);

if (values.includes("2")) {
  console.log('Already Exists.');
}```

Title: Searching For Existing Values in Array


问:
using sinonjs to test a function that calls new on a dependency
I'm terribly confused and would love some help.

I don't think this code is poorly designed, but correct me if you see a flaw.

I can't seem to figure out how to test a function that calls new on a dependency.  Here are my boiled down classes....with irrelevant business logic stripped.

MyWrapper.js

```<code>const SomeLib = require('SomeLib');

module.exports.MyWrapper = class MyWrapper {
    constructor(username, password) {
        this._someLib = new SomeLib(username, password);
    }

    async getFoo(id) {
        // other business logic omitted
        // which was tested in the MyWrapper.spec.js
        return this._someLib.findById(id)
    }

    async saveFoo(object) {
        // other business logic omitted
        // which was tested in the MyWrapper.spec.js
        return this._someLib.save(object)
    }
}
</code>```

MyApp.js

```<code>const MyWrapper = require('MyWrapper');

const process = async (message) => {
    const wrapper = new MyWrapper(process.env.username, process.env.password)
    // some business logic around the message...omitted
    const data = wrapper.getFoo(message.id);
    if(data) {
       // do stuff with the data
       wrapper.saveFoo(data);
    } else {
       console.log('no data found for message', message);
    }
}
module.exports = { process }
</code>```

MyApp.spec.js

```<code>const sut = require('MyApp');

describe('MyApp', function(){
    describe('process', function(){
        it('should not call save when no data found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return "undefined"
             const msg = {......};
             await sut.process(msg);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was *NOT* called
        });

        it('should call save when data is found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return some JSON
             const msg = {......};
             await sut.process(msg);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was called
        });
    });
});
</code>```

答:
We probably need to install and include proxyquire library to stub MyWrapper implementation.

MyApp.spec.js

const proxyquire = require("proxyquire"); // include the library here
const sinon = require("sinon");
const chai = require("chai");
const sinonChai = require("sinon-chai");
chai.should();
chai.use(sinonChai);

describe("MyApp", function() {
  describe("process", function() {
    beforeEach(() => {
      sinon.restore(); // best practice to always restore stub
    });

    it("should not call save when no data found", async function() {
      // stub getFoo to return undefined
      const getFooStub = sinon.stub().returns(undefined);
      const saveFooStub = sinon.stub();

      // create wrapper function to return stub
      function MyWrapperStub() {
        return {
          getFoo: getFooStub,
          saveFoo: saveFooStub
        };
      }

      // I don't know why your code use require('MyWrapper'), it should be prefixed with `./`
      // Here is basically we override `./MyWrapper` in our `MyApp.js` with the stub
      const sut = proxyquire("./MyApp", { "./MyWrapper": MyWrapperStub });

      const msg = { id: "123" };
      await sut.process(msg);

      getFooStub.should.have.been.calledWith("123");
      saveFooStub.should.not.have.been.called;
    });

    it("should call save when data is found", async function() {
      // stub getFoo to return json data
      const data = { name: "something" };
      const getFooStub = sinon.stub().returns(data);
      const saveFooStub = sinon.stub();

      function MyWrapperStub() {
        return {
          getFoo: getFooStub,
          saveFoo: saveFooStub
        };
      }
      const sut = proxyquire("./MyApp", { "./MyWrapper": MyWrapperStub });

      const msg = { id: "123" };
      await sut.process(msg);

      getFooStub.should.have.been.calledWith("123");
      saveFooStub.should.have.been.calledWith(data);
    });
  });
});

```

<p>In <code>MyApp.js</code>, I changed the implementation of require to be</p>

<pre class="lang-js prettyprint-override"><code>const MyWrapper = require('./MyWrapper');
</code>```

If you keep insisting to use require('MyWrapper') then in the test file, proxyquire must be set to proxyquire("./MyApp", { "MyWrapper": MyWrapperStub });

Screenshot:

Hope it helps

Ref:

https://www.npmjs.com/package/proxyquire

Body:
I'm terribly confused and would love some help.

I don't think this code is poorly designed, but correct me if you see a flaw.

I can't seem to figure out how to test a function that calls new on a dependency.  Here are my boiled down classes....with irrelevant business logic stripped.

MyWrapper.js

const SomeLib = require('SomeLib');

module.exports.MyWrapper = class MyWrapper {
    constructor(username, password) {
        this._someLib = new SomeLib(username, password);
    }

    async getFoo(id) {
        // other business logic omitted
        // which was tested in the MyWrapper.spec.js
        return this._someLib.findById(id)
    }

    async saveFoo(object) {
        // other business logic omitted
        // which was tested in the MyWrapper.spec.js
        return this._someLib.save(object)
    }
}

MyApp.js

const MyWrapper = require('MyWrapper');

const process = async (message) => {
    const wrapper = new MyWrapper(process.env.username, process.env.password)
    // some business logic around the message...omitted
    const data = wrapper.getFoo(message.id);
    if(data) {
       // do stuff with the data
       wrapper.saveFoo(data);
    } else {
       console.log('no data found for message', message);
    }
}
module.exports = { process }

MyApp.spec.js

const sut = require('MyApp');

describe('MyApp', function(){
    describe('process', function(){
        it('should not call save when no data found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return "undefined"
             const msg = {......};
             await sut.process(msg);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was *NOT* called
        });

        it('should call save when data is found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return some JSON
             const msg = {......};
             await sut.process(msg);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was called
        });
    });
});

Body:
We probably need to install and include proxyquire library to stub MyWrapper implementation.

MyApp.spec.js

const proxyquire = require("proxyquire"); // include the library here
const sinon = require("sinon");
const chai = require("chai");
const sinonChai = require("sinon-chai");
chai.should();
chai.use(sinonChai);

describe("MyApp", function() {
  describe("process", function() {
    beforeEach(() => {
      sinon.restore(); // best practice to always restore stub
    });

    it("should not call save when no data found", async function() {
      // stub getFoo to return undefined
      const getFooStub = sinon.stub().returns(undefined);
      const saveFooStub = sinon.stub();

      // create wrapper function to return stub
      function MyWrapperStub() {
        return {
          getFoo: getFooStub,
          saveFoo: saveFooStub
        };
      }

      // I don't know why your code use require('MyWrapper'), it should be prefixed with `./`
      // Here is basically we override `./MyWrapper` in our `MyApp.js` with the stub
      const sut = proxyquire("./MyApp", { "./MyWrapper": MyWrapperStub });

      const msg = { id: "123" };
      await sut.process(msg);

      getFooStub.should.have.been.calledWith("123");
      saveFooStub.should.not.have.been.called;
    });

    it("should call save when data is found", async function() {
      // stub getFoo to return json data
      const data = { name: "something" };
      const getFooStub = sinon.stub().returns(data);
      const saveFooStub = sinon.stub();

      function MyWrapperStub() {
        return {
          getFoo: getFooStub,
          saveFoo: saveFooStub
        };
      }
      const sut = proxyquire("./MyApp", { "./MyWrapper": MyWrapperStub });

      const msg = { id: "123" };
      await sut.process(msg);

      getFooStub.should.have.been.calledWith("123");
      saveFooStub.should.have.been.calledWith(data);
    });
  });
});

In MyApp.js, I changed the implementation of require to be

const MyWrapper = require('./MyWrapper');

If you keep insisting to use require('MyWrapper') then in the test file, proxyquire must be set to proxyquire("./MyApp", { "MyWrapper": MyWrapperStub });

Screenshot:

Hope it helps

Ref:

https://www.npmjs.com/package/proxyquire


问:
sum values with case insensitive join not grouping correctly
I have two tables I want to join in a case insensitive way. Thanks to other topics on SO this is working using lower(). However, the result is not grouped by the lower case values but still appears to be case sensitive. How do I adjust the query so that the grouping is case insensitive?

Example data:
Table 1 (only using 1 column right now of this table, there is more metadata though ;):

```<code>keyword
TEST
ABC
ASF
QWERTY
</code>```

Table 2:

```<code>Date - term - value
2020-01-01 - test - 3
2020-01-01 - Test - 2
2020-01-03 - TEST - 4
2020-01-01 - abc - 6
2020-01-02 - ABC - 7
2020-01-02 - abc - 3
</code>```

Desired output:

```<code>keyword - sum(value)
test - 9
abc - 16
</code>```

Current output:

```<code>keyword - sum(value)
test - 3
test - 2
test - 4
abc - 9
abc - 7
</code>```

Query I'm using:

```<code>select distinct lower(keyword), value
FROM Table1 t1
join (select lower(term) term, sum(value) value from Table2 group by term) t2 on lower(t1.keyword) = lower(t2.term)
GROUP BY t2.term, t1.keyword, t2.value
</code>```

It seems all the output needs is (another) group by, but whether I group or not it doesn't change the result. What am I missing here?

答:
One simple option here would be to just lowercase both sides of the join condition:

```<code>SELECT
    t1.keyword,
    SUM(t2.value) AS total
FROM table1 t1
LEFT JOIN table2 t2
    ON LOWER(t1.keyword) = LOWER(t2.term)
GROUP BY
    t1.keyword;
</code>```

Note that using LOWER in multiple places of the join probably means that your query would not be able to use any index.  For best performance, consider storing your keyword/term data in the same case everywhere.

Body:
I have two tables I want to join in a case insensitive way. Thanks to other topics on SO this is working using lower(). However, the result is not grouped by the lower case values but still appears to be case sensitive. How do I adjust the query so that the grouping is case insensitive?

Example data:
Table 1 (only using 1 column right now of this table, there is more metadata though ;):

keyword
TEST
ABC
ASF
QWERTY

Table 2:

Date - term - value
2020-01-01 - test - 3
2020-01-01 - Test - 2
2020-01-03 - TEST - 4
2020-01-01 - abc - 6
2020-01-02 - ABC - 7
2020-01-02 - abc - 3

Desired output:

keyword - sum(value)
test - 9
abc - 16

Current output:

keyword - sum(value)
test - 3
test - 2
test - 4
abc - 9
abc - 7

Query I'm using:

select distinct lower(keyword), value
FROM Table1 t1
join (select lower(term) term, sum(value) value from Table2 group by term) t2 on lower(t1.keyword) = lower(t2.term)
GROUP BY t2.term, t1.keyword, t2.value

It seems all the output needs is (another) group by, but whether I group or not it doesn't change the result. What am I missing here?

Body:
One simple option here would be to just lowercase both sides of the join condition:

SELECT
    t1.keyword,
    SUM(t2.value) AS total
FROM table1 t1
LEFT JOIN table2 t2
    ON LOWER(t1.keyword) = LOWER(t2.term)
GROUP BY
    t1.keyword;

Note that using LOWER in multiple places of the join probably means that your query would not be able to use any index.  For best performance, consider storing your keyword/term data in the same case everywhere.


问:
What is 'X-SCHEMA' in ApacheDS schema?
We are implementing LDAP client for ApacheDS. As part of implementation we are retrieving and parsing schema. As part of objectClasses schema we have X-SCHEMA. If we consider pwcPolicy object it has definition like ( 1.3.6.1.4.1.42.2.27.8.2.1 NAME 'pwdPolicy' DESC 'class to hold the PasswordPolicy parameters' SUP top AUXILIARY MUST pwdAttribute MAY ( pwdMinAge $ pwdMaxAge $ pwdInHistory $ pwdCheckQuality $ pwdMinLength $ pwdMaxLength $ pwdExpireWarning $ pwdGraceAuthNLimit $ pwdGraceExpire $ pwdLockout $ pwdLockoutDuration $ pwdMaxFailure $ pwdFailureCountInterval $ pwdMustChange $ pwdAllowUserChange $ pwdSafeModify $ pwdMinDelay $ pwdMaxDelay $ pwdMaxIdle ) X-SCHEMA 'pwdpolicy' )which has X-SCHEMA with value as pwdpolicy.

Could anyone provide inputs on what is X-SCHEMA and how it can be used in the LDAP client implementation.

Thanks in advance.

答:
Per LDAP RFCs, the objectClasses syntax is extensible, and the policy is to identify extensions with the X- prefix.
The X-SCHEMA is a tag to be able to group objectClass and attributes that are part of the same schema origin.

OpenDJ (and ForgeRock Directory Services) use another extension (for the same schema):  X-ORIGIN 'draft-behera-ldap-password-policy'

Title: What is 'X-SCHEMA' in ApacheDS schema?


问:
git.exe error for android studio
Recently I am trying to connect git hub repository to android studio but it shows following the error:

答:
I know this might sound stupid but yes, it is as stupid as it is!

I had this same error on Linux and was searching for a solution for two days! Then one day was trying to solve this, by chance, I cleared the path specified in android studio and Voilà! Android studio auto detected my git (facepalm)! And the interesting thing is it was not the path I was pointing to (bin/usr/git), and not the path returned by which git command (same path), it was /app/bin/git

For intellij idea and other products of JetBrains is quite the same issue, but the path detected by the two is different! Intellij idea was pointiong to /usr/bin/git!

For people still having this error even if their git is installed and android studio is pointing to its path,
go to Settings -> Version Control -> Git and delete everything inside the text box with the label Path to Git executable, your android studio or what ever JetBrains product you're using, will auto-detect it.

Title: git.exe error for android studio


答:
I'm not sure that I'm on the same page with you, but I think you need to specify the function that will be triggered each time when you need, and this function should query all places where you need to change the price amount.

For instance:

```<code>function updatePrice() {
   return persianJs("345").englishNumber().toString();
};

window.onload = function(){
    let elements = document.querySelectorAll('.price');
      if(elements && elements.length) {
         elements.forEach(el => el.textContent = updatePrice())
      }
}
</code>```

It's just my vision of your problem, but again I'm not sure that I correctly understand you...

Title: run a javascript function for specific css .class selectors

Body:
I have a JavaScript library and it uses this function for example to convert English numbers to Persian:

persianJs("345").englishNumber().toString(); //returns: ۳۴۵

I have an html structure to show some dynamic numerical values like this:

How can I run the JavaScript function in header or footer to display any price amount in Persian format?

Body:
I'm not sure that I'm on the same page with you, but I think you need to specify the function that will be triggered each time when you need, and this function should query all places where you need to change the price amount.

For instance:

function updatePrice() {
   return persianJs("345").englishNumber().toString();
};

window.onload = function(){
    let elements = document.querySelectorAll('.price');
      if(elements && elements.length) {
         elements.forEach(el => el.textContent = updatePrice())
      }
}

It's just my vision of your problem, but again I'm not sure that I correctly understand you...


问:
How to use more than one class modifier in django admin?
i have already wrote a class to customize my model in django admin (extends from admin.ModelAdmin),but now i want to use a rich-text editor for my TextFields in that model(needs to extends from SummernoteModelAdmin), i don't know how to apply both of them.

in admin.py

```<code>admin.site.register(my_model, my_modelA)
</code>```

i've tried this:

```<code>admin.site.register(my_model, my_modelA, my_modelB)
</code>```

but it shows an error:

```<code>TypeError: register() takes from 2 to 3 positional arguments but 4 were given
</code>```

how can i use both of those classes ?
Thanks~

答:
If i got it right my_modelA & my_modelB are subclasses of admin.ModelAdmin and you want your my_model's admin to inherit from both.

You could implement a third admin class my_modelC like this:

class my_modelC(my_modelA, my_modelB):
   pass

admin.site.register(my_model, my_modelC)
```

Body:
i have already wrote a class to customize my model in django admin (extends from admin.ModelAdmin),but now i want to use a rich-text editor for my TextFields in that model(needs to extends from SummernoteModelAdmin), i don't know how to apply both of them.

in admin.py

admin.site.register(my_model, my_modelA)

i've tried this:

admin.site.register(my_model, my_modelA, my_modelB)

but it shows an error:

TypeError: register() takes from 2 to 3 positional arguments but 4 were given

how can i use both of those classes ?
Thanks~


问:
Why is \b not working for the last indexed character of the string?

I am working on python escape characters. I found that \b is
not working for the last indexed character of the string  in
Python 3.8.Why is it so?

Input :

print("abc#\bde#\bf#\bghi#\bjklmn#\bop\b#\b")

Output :

abcdefghijklmno#

答:
This is got to do with how the terminal interprets escape characters.
It had been reported for Python 2 a few years back.
Quoting:

Python itself doesn’t treat backspace specially. What you are probably seeing is the terminal interpreting the backspace specially by moving the cursor left (without erasing anything).

This means that, if you have a character after \b, the terminal will move the cursor left and "overwrite" the original character with the new one.
If there are no other characters, nothing will overwrite the old character.

Trying piping the output to hexdump using your example shows:

```<code>$ python3.8 -c
'print("abc#\bde#\bf#\bghi#\bjklmn#\bop\b")' | hexdump -C
00000000  61 62 63 23 08 64 65 23  08 66 23 08 67 68 69 23  |abc#.de#.f#.ghi#|
00000010  08 6a 6b 6c 6d 6e 23 08  6f 70 08 0a              |.jklmn#.op..|
0000001c
</code>```

You can notice the 08 character there (\b).

Body:
This is got to do with how the terminal interprets escape characters.
It had been reported for Python 2 a few years back.
Quoting:

Python itself doesn’t treat backspace specially. What you are probably seeing is the terminal interpreting the backspace specially by moving the cursor left (without erasing anything).

This means that, if you have a character after \b, the terminal will move the cursor left and "overwrite" the original character with the new one.
If there are no other characters, nothing will overwrite the old character.

Trying piping the output to hexdump using your example shows:

$ python3.8 -c
'print("abc#\bde#\bf#\bghi#\bjklmn#\bop\b")' | hexdump -C
00000000  61 62 63 23 08 64 65 23  08 66 23 08 67 68 69 23  |abc#.de#.f#.ghi#|
00000010  08 6a 6b 6c 6d 6e 23 08  6f 70 08 0a              |.jklmn#.op..|
0000001c

You can notice the 08 character there (\b).


问:
Delete local folder when project is deleted in TFS?
We just started using TFS and it works great. I have one question though, if we delete a folder it's not deleted on my local workspace. We are currently reorganizing a project and I wish to not have heaps of unused folders on my local drive.

Where can I configure this?

Thanks in advance.

答:
In you have the Visual Studio Power Tools (http://visualstudiogallery.msdn.microsoft.com/c255a1e4-04ba-4f68-8f4e-cd473d6b971f) you can use the command line tools tfpt to clean up all your workspaces.

In a shell window

change directory to your workspace root

type \tfpt.exe treeclean /recurse .

This will remove any file or folder not in source control.


问:
Proxy support via ChromeOptions on Selenium Java
```<code>System.setProperty("webdriver.chrome.driver","C:\\Users\\xxxx\\IdeaProjects\\chromedriver.exe\\");

ChromeOptions options = new ChromeOptions();

Proxy proxy = new Proxy();
proxy.setHttpProxy("107.175.153.215:3128");

options.setCapability("proxy", proxy);

ChromeDriver driver = new ChromeDriver(options);

driver.get("https://www.ipinfo.io");
</code>```

I've been trying to figure out why this isn't working. I've also tried with geckodriver, and haven't had any success. It used to be fine a year ago, so not sure as to what's wrong/different.

I see this being iterated in the console for a bit, and then it stops.:

```<code>[1582009560.815][SEVERE]: Timed out receiving message from renderer: 0.100
</code>```

Thank you.

答:
Seems you were close. Since Selenium v3.6.0, the ChromeOptions class in java client also implements the Capabilities interface, allowing you to specify other WebDriver capabilities not specific to ChromeDriver. So may you need to:

Instead of using the ChromeDriver class, use the WebDriver interface.

Additionally, you need to remove the trailing escaped back slash i.e. \\ from the chromedriver.exe path.

Your effective code block will be:

```<code>System.setProperty("webdriver.chrome.driver","C:\\Users\\xxxx\\IdeaProjects\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.setHttpProxy("107.175.153.215:3128");
options.setCapability("proxy", proxy);
ChromeDriver driver = new ChromeDriver(options);
driver.get("https://www.ipinfo.io");
</code>```

Body:
System.setProperty("webdriver.chrome.driver","C:\\Users\\xxxx\\IdeaProjects\\chromedriver.exe\\");

ChromeOptions options = new ChromeOptions();

Proxy proxy = new Proxy();
proxy.setHttpProxy("107.175.153.215:3128");

options.setCapability("proxy", proxy);

ChromeDriver driver = new ChromeDriver(options);

driver.get("https://www.ipinfo.io");

I've been trying to figure out why this isn't working. I've also tried with geckodriver, and haven't had any success. It used to be fine a year ago, so not sure as to what's wrong/different.

I see this being iterated in the console for a bit, and then it stops.:

[1582009560.815][SEVERE]: Timed out receiving message from renderer: 0.100

Thank you.

Body:
Seems you were close. Since Selenium v3.6.0, the ChromeOptions class in java client also implements the Capabilities interface, allowing you to specify other WebDriver capabilities not specific to ChromeDriver. So may you need to:

Instead of using the ChromeDriver class, use the WebDriver interface.

Additionally, you need to remove the trailing escaped back slash i.e. \\ from the chromedriver.exe path.

Your effective code block will be:

System.setProperty("webdriver.chrome.driver","C:\\Users\\xxxx\\IdeaProjects\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
Proxy proxy = new Proxy();
proxy.setHttpProxy("107.175.153.215:3128");
options.setCapability("proxy", proxy);
ChromeDriver driver = new ChromeDriver(options);
driver.get("https://www.ipinfo.io");


问:
error loading jupyter notebook permission denied: ipynb
I was working in a jupyter notebook until it froze. It wouldn't save or shut down so I restarted my computer. I launched jupyter notebook from an anaconda prompt, my folder directory opens per usual. When i tried to open the notebook from before, I get an error loading screen that says permission denied: (name of notebook).ipynb. I hit close and the notebook shuts down.

I checked the folder permissions, I have full control. I can create a new ipynb without any issues. I can open other notebooks without any problem in the same folder. I tried to run a trust notebook through the anaconda prompt and it says the notebook is missing.

I need to recover this particular notebook as it has all my work. Help! Any ideas? Thanks in advance.

I work in the anaconda prompt in an environment other than the root, so this answer using sudo chmod doesn't work for me.

答:
I had possibly the same problem. In my case the problem was that jupyter notebook must have crashed or had some problem whilst autosaving.

As a result, in the folder where the notebook is saved there's a temporary file called ".~nameofnotebook.ipynb".

This file didn't show up in jupyter notebook, but only in the explorer. I deleted the notebook file and renamed the temporary file to delete the ".~" prefix. Make sure to save a copy of the notebook file before deleting anything in case your problem is different.

The renamed temporary file opens fine and none of my data was lost.


问:
How to get text content of one h3 at a time in javascript?
I am having difficulty to get text content of h1 at a time when I click on any button element . Can anyone help me out please?     </p>

```<code>    <div id="makeSelection" ><h1>Text Content 1</h1>
    <button onclick="eveent()">Click Me</button>
    </div>
    <div id="makeSelection" ><h1>Text Content 2</h1>
        <button onclick="eveent()">Click Me</button>
    </div>
    <div id="makeSelection" ><h1>Text Content 3</h1>
        <button onclick="eveent()">Click Me</button>
    </div>

     function eveent(){

        var text = document.getElementById('makeSelection').textContent;

        console.log(text);

                    }
</code>```

答:
This is one way how you could do it:

Give ID-s to the headings.

Call the click event with the id of the desired heading.

Do your thing with the element content. (In this example, you console log it's text content)

function clickEvent (target){
  var heading = document.querySelector(target);
  if (heading) {
    console.log(heading.textContent);
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h1 id="heading-1">Text Content 1</h1>
  <button onclick="clickEvent('#heading-1')">Click Me</button>
</div>
<div>
  <h1 id="heading-2">Text Content 2</h1>
  <button onclick="clickEvent('#heading-2')">Click Me</button>
</div>
<div>
  <h1 id="heading-3">Text Content 3</h1>
  <button onclick="clickEvent('#heading-3')">Click Me</button>
</div></code>```

Note: I removed the duplicate ids from the divs, as they are not required and also duplicate IDs are not valid in HTML.

Body:
I am having difficulty to get text content of h1 at a time when I click on any button element . Can anyone help me out please?

Text Content 1

    <button onclick="eveent()">Click Me</button>

Text Content 2

        <button onclick="eveent()">Click Me</button>

Text Content 3

        <button onclick="eveent()">Click Me</button>

     function eveent(){

        var text = document.getElementById('makeSelection').textContent;

        console.log(text);

                    }

Body:
This is one way how you could do it:

Give ID-s to the headings.

Call the click event with the id of the desired heading.

Do your thing with the element content. (In this example, you console log it's text content)

function clickEvent (target){
  var heading = document.querySelector(target);
  if (heading) {
    console.log(heading.textContent);
  }
};

<div>
  <h1 id="heading-1">Text Content 1</h1>
  <button onclick="clickEvent('#heading-1')">Click Me</button>
</div>
<div>
  <h1 id="heading-2">Text Content 2</h1>
  <button onclick="clickEvent('#heading-2')">Click Me</button>
</div>
<div>
  <h1 id="heading-3">Text Content 3</h1>
  <button onclick="clickEvent('#heading-3')">Click Me</button>
</div>

Note: I removed the duplicate ids from the divs, as they are not required and also duplicate IDs are not valid in HTML.


问:
After deploying React app to Heroku from dev env, Fetch requests broken - all GET requests returning index.html - others are 404
I have just deployed my Create-React-App project to Heroku. In development, I was running two separate ports - the local HTML + JS were being served from the React WebpackDevServer using the npm/yarn start scripts on Port 3000. The Backend was Express + NodeJS running on port 3001. I configured all fetch requests to use mode:'cors' and provided a handler on the API so to avoid CORS errors.
A typical fetch request would look like this:

When I deployed to Heroku, everything is now kept together on a single Dyno, and the Express app serves the React files (bundle + index.html) and also handles backend routing logic.

Here is a sample of my API code so-far:

```<code>const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const bodyParser = require('body-parser');
const config = require('./models/config');
require('dotenv').config()
const app = express();
const server = require('http').createServer(app);

const storeItems= require('./controllers/storeItems')
const authorize= require('./controllers/authorize')
const router = express.Router();

mongoose.Promise = global.Promise;
mongoose.connect(`mongodb://${process.env.MLABS_USER}:${process.env.MLABS_PW}@ds113000.mlab.com:13000/omninova`, { useMongoClient: true });

app.use(bodyParser.json());

// Middleware to handle CORS in development:

app.use('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, x-access-token, x-user-pathway, x-mongo-key, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
  next();
});

app.use(express.static(path.join(__dirname, 'client/build')));

router.route('/api/storeItem/')
    .get(storeItems.getAllStoreItems)
    .post(storeItems.createNewStoreItem);

router.route('/authorize')
    .post(authorize.login);

// Catch-All Handler should send Client index.html for any request that does not match previous routes

router.route('*')
    .get((req, res) => {
        res.sendFile(path.join(__dirname+'/client/build/index.html'));
    });

app.use('/', router);

server.listen(config.port);
module.exports = app;
</code>```

I'm having some issues, ALL of my get requests are returning my index.html page with the following Error: Unexpected token < in JSON at position 0

I have the following Fetch Request:

```<code>    return fetch(`/api/storeItem`, {
        headers:{
            'Content-Type': 'application/json',
        },
        method: 'GET',
        mode: 'no-cors',
    })
    .then(response => response.ok ? response.json() : Promise.reject(response))
    .then(json => {
        dispatch(receiveItems(json))
    })
    .catch(err => console.log(err))
</code>```

This is failing, because instead of triggering the Express Middleware that should be running storeItems.getAllStoreItems on the backend, It's passing that route and triggering the catch-all handler, which I use to serve the index.html upon initial request:

```<code>router.route('*')
    .get((req, res) => {
        res.sendFile(path.join(__dirname+'/client/build/index.html'));
    });
</code>```

Another confusion is that this following fetch request returns a 404, even though the /authorize route is expecting a POST request in the API code:

```<code>export function attemptLogIn(credentials) {
    return dispatch => {
        return fetch('/authorize', {
        headers:{
            'Content-Type': 'application/json'
        },
        method: 'POST',
        mode: 'no-cors'
        body: JSON.stringify(credentials)
        })
        .then(response => response.ok ? response.json() : Promise.reject(response.statusText))
        .then(json => {
            dispatch(routeUserAfterLogin(json.accountType))
        })
        .catch(err => dispatch(authFail(err.message)))
    }
}
</code>```

Any help with this would be highly appreciated. I assume I am doing something wrong with the Express Router, since the authorize route is just not being picked up.

I followed the instructions in this blog post to help me set up my new project: https://daveceddia.com/deploy-react-express-app-heroku/

Edit: This is Fetch code from my Development branch. This successfully logs the user in, without returning a 404. However, I do not use the catch-all handler at all, or the express.static middleware:

```<code>return fetch('http://localhost:3001/authorize', {
    headers:{
        'Content-Type': 'application/json'
    },
    method: 'POST',
    mode: 'cors',
    body: JSON.stringify(credentials)
})
</code>```

Edit: I just changed the URL which points to the bundle.js to
app.use(express.static(path.join(__dirname, '/../../build')));
I'm not sure how I was even sending out the HTML before, since that's the actual location of build files..I'm not sure how they were being found before.

Edit2: Found my problem, I left in the start script for my React project (which actually started the webpack dev server...)

答:
This should fix the problem. Instead of "*" there should be "/". Now my GET request works like the POST on Heroku.

https://stackoverflow.com/a/37878281/12839684

Body:
I have just deployed my Create-React-App project to Heroku. In development, I was running two separate ports - the local HTML + JS were being served from the React WebpackDevServer using the npm/yarn start scripts on Port 3000. The Backend was Express + NodeJS running on port 3001. I configured all fetch requests to use mode:'cors' and provided a handler on the API so to avoid CORS errors.
A typical fetch request would look like this:

When I deployed to Heroku, everything is now kept together on a single Dyno, and the Express app serves the React files (bundle + index.html) and also handles backend routing logic.

Here is a sample of my API code so-far:

const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const bodyParser = require('body-parser');
const config = require('./models/config');
require('dotenv').config()
const app = express();
const server = require('http').createServer(app);

const storeItems= require('./controllers/storeItems')
const authorize= require('./controllers/authorize')
const router = express.Router();

mongoose.Promise = global.Promise;
mongoose.connect(`mongodb://${process.env.MLABS_USER}:${process.env.MLABS_PW}@ds113000.mlab.com:13000/omninova`, { useMongoClient: true });

app.use(bodyParser.json());

// Middleware to handle CORS in development:

app.use('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, x-access-token, x-user-pathway, x-mongo-key, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
  next();
});

app.use(express.static(path.join(__dirname, 'client/build')));

router.route('/api/storeItem/')
    .get(storeItems.getAllStoreItems)
    .post(storeItems.createNewStoreItem);

router.route('/authorize')
    .post(authorize.login);

// Catch-All Handler should send Client index.html for any request that does not match previous routes

router.route('*')
    .get((req, res) => {
        res.sendFile(path.join(__dirname+'/client/build/index.html'));
    });

app.use('/', router);

server.listen(config.port);
module.exports = app;

I'm having some issues, ALL of my get requests are returning my index.html page with the following Error: Unexpected token < in JSON at position 0

I have the following Fetch Request:

    return fetch(`/api/storeItem`, {
        headers:{
            'Content-Type': 'application/json',
        },
        method: 'GET',
        mode: 'no-cors',
    })
    .then(response => response.ok ? response.json() : Promise.reject(response))
    .then(json => {
        dispatch(receiveItems(json))
    })
    .catch(err => console.log(err))

This is failing, because instead of triggering the Express Middleware that should be running storeItems.getAllStoreItems on the backend, It's passing that route and triggering the catch-all handler, which I use to serve the index.html upon initial request:

router.route('*')
    .get((req, res) => {
        res.sendFile(path.join(__dirname+'/client/build/index.html'));
    });

Another confusion is that this following fetch request returns a 404, even though the /authorize route is expecting a POST request in the API code:

export function attemptLogIn(credentials) {
    return dispatch => {
        return fetch('/authorize', {
        headers:{
            'Content-Type': 'application/json'
        },
        method: 'POST',
        mode: 'no-cors'
        body: JSON.stringify(credentials)
        })
        .then(response => response.ok ? response.json() : Promise.reject(response.statusText))
        .then(json => {
            dispatch(routeUserAfterLogin(json.accountType))
        })
        .catch(err => dispatch(authFail(err.message)))
    }
}

Any help with this would be highly appreciated. I assume I am doing something wrong with the Express Router, since the authorize route is just not being picked up.

I followed the instructions in this blog post to help me set up my new project: https://daveceddia.com/deploy-react-express-app-heroku/

Edit: This is Fetch code from my Development branch. This successfully logs the user in, without returning a 404. However, I do not use the catch-all handler at all, or the express.static middleware:

return fetch('http://localhost:3001/authorize', {
    headers:{
        'Content-Type': 'application/json'
    },
    method: 'POST',
    mode: 'cors',
    body: JSON.stringify(credentials)
})

Edit: I just changed the URL which points to the bundle.js to
app.use(express.static(path.join(__dirname, '/../../build')));
I'm not sure how I was even sending out the HTML before, since that's the actual location of build files..I'm not sure how they were being found before.

Edit2: Found my problem, I left in the start script for my React project (which actually started the webpack dev server...)


问:
Apache-camel: How to process a json object (sent by curl) into headers?
I have a springboot application with apache camel. In it I have a camel-context.
I am trying to send json through curl with a key pair value and processing it through a route.

Sending the data:

```<code>curl --header "Content-Type: application/json" -X POST -d '{"msgId=EB2C7265-EF68-4F8F-A709-BEE2C52E842B", "ticket":"ERR001"}' http://lcalhost:8888/api/erroradmin
</code>```

Camel-context.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
        <camelContext xmlns="http://camel.apache.org/schema/spring" useMDCLogging="true">
            <properties>
                <property key="CamelLogEipName" value="ThisLogger"/>
            </properties>
            <dataFormats>
                <!-- here we define a Json data format with the id jack and that it should use the TestPojo as the class type when
                     doing unmarshal. The unmarshalTypeName is optional, if not provided Camel will use a Map as the type -->
                <json id="jack" library="Jackson" unmarshalTypeName="java.util.HashMap"/>
            </dataFormats>

            <restConfiguration component="jetty" port="8888" bindingMode="json">
                <dataFormatProperty key="prettyPrint" value="true"/>
            </restConfiguration>

            <rest path="/api/erroradmin">
                <get uri="{id}">
                    <to uri="direct:processErrorAdminGet"/>
                </get>
                <post>
                    <to uri="direct:processErrorAdminPost"/>
                </post>
            </rest>

            <route id="processErrorAdminPost">
                <from uri="direct:processErrorAdminPost"/>
                <log message="Route(processErrorAdminPost): ${body}"/>
                <unmarshal>
                    <custom ref="jack"/>
                </unmarshal>
                <log message="Route(processErrorAdminPost): ${body}"/>

            </route>
        </camelContext>
    </beans>
</code>```

I am getting the following Stacktrace:

org.apache.camel.InvalidPayloadException: No body available of type: java.io.InputStream but has value: {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001} of type: java.util.LinkedHashMap on: HttpMessage@0x28c1a31a. Caused by: No type converter available to convert from type: java.util.LinkedHashMap to the required type: java.io.InputStream with value {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001}. Exchange[09395660-c947-47f1-b00f-d0d3030a39d1]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: java.util.LinkedHashMap to the required type: java.io.InputStream with value {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001}]

答:
Welcome to Stackoverflow!
I strongly believe the mention of bindingMode="json" at Line 13, is the root cause of this failure.
The manual says

When using binding you must also configure what POJO type to map to. This is mandatory for incoming messages, and optional for outgoing.

I am really scared of the XML DSL but, here is an approximate equivalent rest DSL in Java.

```<code>@Component
@Slf4j
public class MySpringBootRouter extends RouteBuilder {

    @Override
    public void configure() {

        restConfiguration()
                .component("undertow")
                .host("127.0.0.1")
                .port(9090)
                //This works only when a POJO mapping is possible - Ref: https://camel.apache.org/manual/latest/rest-dsl.html
                //<quote>When using binding you must also configure what POJO type to map to. This is mandatory for incoming messages, and optional for outgoing.</quote>
                //.bindingMode(RestBindingMode.json)
                .dataFormatProperty("prettyPrint", "true");

        rest("/api")
                .post("/erroradmin")
                .to("direct:postError")

                .get("/erroradmin/{id}").to("direct:getError");

        from("direct:getError")
                .process(exchange -> {
                    exchange.getMessage().setBody(("{'messageID':'" + UUID.randomUUID().toString() + "','ticketID':'1234'}"));
                });

        from("direct:postError")
                .unmarshal()
                .json(JsonLibrary.Jackson)
                .process(exchange -> {
                    log.info("Type of incoming body:{}", exchange.getIn().getBody().getClass().getName());
                    log.info("Incoming body:{}", exchange.getIn().getBody());
                }).transform().constant("{'httpResponse:200':'OK'}");
    }

}
</code>```

Once it is up, and I send the payload with cURL as below

curl -d '{"msgId":"EB2C7265-EF68-4F8F-A709-BEE2C52E842B", "ticket":"ERR001"}' -H "Content-Type: application/json" -X POST http://localh
ost:9090/api/erroradmin
```

<p>You'll see something like the below in the logs</p>

<pre class="lang-sh prettyprint-override"><code>2020-02-18 11:44:13.032  INFO 2708 --- [  XNIO-1 task-4] o.a.c.community.so.MySpringBootRouter    : Type of incoming body:java.util.LinkedHashMap
2020-02-18 11:44:13.032  INFO 2708 --- [  XNIO-1 task-4] o.a.c.community.so.MySpringBootRouter    : Incoming body:{msgId=EB2C7265-EF68-4F8F-A709-BEE2C52E842B, ticket=ERR001}

</code>```

Oh btw, your original JSON payload was malformed.
The entire Java project is available here, if you wish to play around

Edit: Additional header processing step

```<code>        from("direct:postError")
                .unmarshal()
                .json(JsonLibrary.Jackson)
                .process(exchange -> {
                    LinkedHashMap map = exchange.getIn().getBody(LinkedHashMap.class);
                    map.keySet().stream().forEach( item -> exchange.getIn().setHeader(item.toString(),map.get(item)));
                })
//This step is just to print the Headers. Doesnt do anything useful
                .process( exchange -> {
                    log.info(String.valueOf(exchange.getIn().getHeaders()));
                })
                .transform().constant("{'httpResponse:200':'OK'}");
</code>```

Body:
I have a springboot application with apache camel. In it I have a camel-context.
I am trying to send json through curl with a key pair value and processing it through a route.

Sending the data:

curl --header "Content-Type: application/json" -X POST -d '{"msgId=EB2C7265-EF68-4F8F-A709-BEE2C52E842B", "ticket":"ERR001"}' http://lcalhost:8888/api/erroradmin

Camel-context.xml:

<?xml version="1.0" encoding="utf-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
        <camelContext xmlns="http://camel.apache.org/schema/spring" useMDCLogging="true">
            <properties>
                <property key="CamelLogEipName" value="ThisLogger"/>
            </properties>
            <dataFormats>

                <json id="jack" library="Jackson" unmarshalTypeName="java.util.HashMap"/>
            </dataFormats>

            <restConfiguration component="jetty" port="8888" bindingMode="json">
                <dataFormatProperty key="prettyPrint" value="true"/>
            </restConfiguration>

            <rest path="/api/erroradmin">
                <get uri="{id}">
                    <to uri="direct:processErrorAdminGet"/>
                </get>
                <post>
                    <to uri="direct:processErrorAdminPost"/>
                </post>
            </rest>

            <route id="processErrorAdminPost">
                <from uri="direct:processErrorAdminPost"/>
                <log message="Route(processErrorAdminPost): ${body}"/>
                <unmarshal>
                    <custom ref="jack"/>
                </unmarshal>
                <log message="Route(processErrorAdminPost): ${body}"/>

            </route>
        </camelContext>
    </beans>

I am getting the following Stacktrace:

org.apache.camel.InvalidPayloadException: No body available of type: java.io.InputStream but has value: {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001} of type: java.util.LinkedHashMap on: HttpMessage@0x28c1a31a. Caused by: No type converter available to convert from type: java.util.LinkedHashMap to the required type: java.io.InputStream with value {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001}. Exchange[09395660-c947-47f1-b00f-d0d3030a39d1]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: java.util.LinkedHashMap to the required type: java.io.InputStream with value {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001}]

Body:
Welcome to Stackoverflow!
I strongly believe the mention of bindingMode="json" at Line 13, is the root cause of this failure.
The manual says

When using binding you must also configure what POJO type to map to. This is mandatory for incoming messages, and optional for outgoing.

I am really scared of the XML DSL but, here is an approximate equivalent rest DSL in Java.

@Component
@Slf4j
public class MySpringBootRouter extends RouteBuilder {

    @Override
    public void configure() {

        restConfiguration()
                .component("undertow")
                .host("127.0.0.1")
                .port(9090)
                //This works only when a POJO mapping is possible - Ref: https://camel.apache.org/manual/latest/rest-dsl.html
                //<quote>When using binding you must also configure what POJO type to map to. This is mandatory for incoming messages, and optional for outgoing.</quote>
                //.bindingMode(RestBindingMode.json)
                .dataFormatProperty("prettyPrint", "true");

        rest("/api")
                .post("/erroradmin")
                .to("direct:postError")

                .get("/erroradmin/{id}").to("direct:getError");

        from("direct:getError")
                .process(exchange -> {
                    exchange.getMessage().setBody(("{'messageID':'" + UUID.randomUUID().toString() + "','ticketID':'1234'}"));
                });

        from("direct:postError")
                .unmarshal()
                .json(JsonLibrary.Jackson)
                .process(exchange -> {
                    log.info("Type of incoming body:{}", exchange.getIn().getBody().getClass().getName());
                    log.info("Incoming body:{}", exchange.getIn().getBody());
                }).transform().constant("{'httpResponse:200':'OK'}");
    }

}

Once it is up, and I send the payload with cURL as below

curl -d '{"msgId":"EB2C7265-EF68-4F8F-A709-BEE2C52E842B", "ticket":"ERR001"}' -H "Content-Type: application/json" -X POST http://localh
ost:9090/api/erroradmin

You'll see something like the below in the logs

2020-02-18 11:44:13.032  INFO 2708 --- [  XNIO-1 task-4] o.a.c.community.so.MySpringBootRouter    : Type of incoming body:java.util.LinkedHashMap
2020-02-18 11:44:13.032  INFO 2708 --- [  XNIO-1 task-4] o.a.c.community.so.MySpringBootRouter    : Incoming body:{msgId=EB2C7265-EF68-4F8F-A709-BEE2C52E842B, ticket=ERR001}

Oh btw, your original JSON payload was malformed.
The entire Java project is available here, if you wish to play around

Edit: Additional header processing step

        from("direct:postError")
                .unmarshal()
                .json(JsonLibrary.Jackson)
                .process(exchange -> {
                    LinkedHashMap map = exchange.getIn().getBody(LinkedHashMap.class);
                    map.keySet().stream().forEach( item -> exchange.getIn().setHeader(item.toString(),map.get(item)));
                })
//This step is just to print the Headers. Doesnt do anything useful
                .process( exchange -> {
                    log.info(String.valueOf(exchange.getIn().getHeaders()));
                })
                .transform().constant("{'httpResponse:200':'OK'}");


问:
nativescript-angular - radcalendar - keep today's date selected
I've implemented RadCalendar in my Nativescript Angular project.

```<code><GridLayout>
    <ScrollView class="page">
        <StackLayout class="home-panel">
            <Button text="Clear" (tap)="onClearTap()"></Button>
            <RadCalendar height="1000px" [viewMode]="viewMode" #mainCalendar
                [selectionMode]="selectionMode" [eventSource]="calEvents"
                (loaded)="calendarLoaded($event)"
                [eventsViewMode]="eventsViewMode"
                [selectedDate]="selectedDate" [displayedDate]="selectedDate">
            </RadCalendar>
        </StackLayout>
    </ScrollView>
</GridLayout>
</code>```

From the constructor, I'm adding an event for today's date.

```<code>constructor() {
    let eventDate = new Date();
    eventDate.setDate(eventDate.getDate());
    let event = new CalendarEvent("XXX", eventDate, eventDate, true);
    this.calEvents.push(event);
    this.mainCalendar.selectedDate = eventDate;
}
</code>```

I am trying to keep today's date selected by default and events under it listed when a user visits the calendar.
Now a user has to click on today's date to see the events under it.

I tried to keep today's date selected using selectedDate but it's no working.

Can anyone tell me how to do it? Thanks!

Here's a playground link

答:
The constructor code should be moved to NgOnInit.</p>

```<code>ngOnInit(): void {
    let eventDate = new Date();
    eventDate.setDate(eventDate.getDate());
    let event = new CalendarEvent("XXX", eventDate, eventDate, true);
    this.calEvents.push(event);
    this.mainCalendar.selectedDate = eventDate;
}
</code>```

Body:
I've implemented RadCalendar in my Nativescript Angular project.

<GridLayout>
    <ScrollView class="page">
        <StackLayout class="home-panel">
            <Button text="Clear" (tap)="onClearTap()"></Button>
            <RadCalendar height="1000px" [viewMode]="viewMode" #mainCalendar
                [selectionMode]="selectionMode" [eventSource]="calEvents"
                (loaded)="calendarLoaded($event)"
                [eventsViewMode]="eventsViewMode"
                [selectedDate]="selectedDate" [displayedDate]="selectedDate">
            </RadCalendar>
        </StackLayout>
    </ScrollView>
</GridLayout>

From the constructor, I'm adding an event for today's date.

constructor() {
    let eventDate = new Date();
    eventDate.setDate(eventDate.getDate());
    let event = new CalendarEvent("XXX", eventDate, eventDate, true);
    this.calEvents.push(event);
    this.mainCalendar.selectedDate = eventDate;
}

I am trying to keep today's date selected by default and events under it listed when a user visits the calendar.
Now a user has to click on today's date to see the events under it.

I tried to keep today's date selected using selectedDate but it's no working.

Can anyone tell me how to do it? Thanks!

Here's a playground link

Body:
The constructor code should be moved to NgOnInit.

ngOnInit(): void {
    let eventDate = new Date();
    eventDate.setDate(eventDate.getDate());
    let event = new CalendarEvent("XXX", eventDate, eventDate, true);
    this.calEvents.push(event);
    this.mainCalendar.selectedDate = eventDate;
}


问:
How set hover for featured image? How change hover?
I would like to set the gif file in the featured image. I would like it to run when I hover over it with the mouse.

I know I should set this in functions.php file

Together with the code:

```<code>add_theme_support ('post-thumbnails');
</code>```

Unfortunately, I have no idea how to do it. I create my blog and I have never done such things. Could someone help me how to do it?
Thank you for your help!

答:
When you upload an animated GIF to WordPress, it does all of it’s resizing magic to make the various thumbnail sizes (defaults are thumbnail, medium and large, in addition to the original full). When it does this, the resized versions lose their animation.

If your theme displays featured images at any size other than full, you’ll thusly lose your GIF’s animation.

If you definitely know that you want to display the animated version, though, there’s a little trick you can use.

```<code><?php $thumb_url = get_the_post_thumbnail_url();
      $thumb_low = strtolower($thumb_url);
      if (strpos($thumb_low, '.gif') === false) {
        $thumb_size = 'large';
      } else {
        $thumb_size = 'full';
      }
?>
</code>```

What am I doing here is getting the URL of our featured image, then I make sure it’s all lower case letters (WordPress may do this anyway, but just to be safe), then I check to see if .gif is present in the thumbnail’s URL, and finally, if it is, I set the thumbnail size I use to ‘large’. Doing so will allow me to use the original image, which retains it’s animation.

Then, I just need to tell our call to the_post_thumbnail() to use the variable thumbnail size we set, like this:

```<code>the_post_thumbnail($thumb_size)
</code>```

Body:
I would like to set the gif file in the featured image. I would like it to run when I hover over it with the mouse.

I know I should set this in functions.php file

Together with the code:

add_theme_support ('post-thumbnails');

Unfortunately, I have no idea how to do it. I create my blog and I have never done such things. Could someone help me how to do it?
Thank you for your help!

Body:
When you upload an animated GIF to WordPress, it does all of it’s resizing magic to make the various thumbnail sizes (defaults are thumbnail, medium and large, in addition to the original full). When it does this, the resized versions lose their animation.

If your theme displays featured images at any size other than full, you’ll thusly lose your GIF’s animation.

If you definitely know that you want to display the animated version, though, there’s a little trick you can use.

<?php $thumb_url = get_the_post_thumbnail_url();
      $thumb_low = strtolower($thumb_url);
      if (strpos($thumb_low, '.gif') === false) {
        $thumb_size = 'large';
      } else {
        $thumb_size = 'full';
      }
?>

What am I doing here is getting the URL of our featured image, then I make sure it’s all lower case letters (WordPress may do this anyway, but just to be safe), then I check to see if .gif is present in the thumbnail’s URL, and finally, if it is, I set the thumbnail size I use to ‘large’. Doing so will allow me to use the original image, which retains it’s animation.

Then, I just need to tell our call to the_post_thumbnail() to use the variable thumbnail size we set, like this:

the_post_thumbnail($thumb_size)