问:
Percentage loading indicator that represents function or thread processing state
Problem: When a function is called, google popup says "Running script blahblah" with cancel, dismiss buttons. This green popup gets dismissed after a while(when?), but many cells still show Loading.. state and values are still being populated, meaning the functions are still being run.

Requirement: Need information on some sort of indicator, spinning circle/loading ui or just a simple percentage wise indication of how much processing/function calls have been done, or something that gives the user some indication as to how much loading left, or when it finishes. I realise I'm being vague because I'm unsure if this sort of process monitoring function exists. I visualise it like a thread monitor, that goes green when all processing is complete. But a cell populated with 0-100% value will also do.

Context: When I click on a button, my code executes a lot of functions on a vast range of cells, which require a considerable amount of processing time even with optimisations, during which the state of many cells remain as "Loading..".   After all functions have been executed, and all cells have been populated, only then, the user needs to perform some manual inspection/other activities. But there is no indication given to the user that all processing has been completed, other than manual scrolling and searching for absence of "Loading" indicator in all cells, which is tedious.

Alternative Solutions (in case there is no direct processing indicator function):

Callback or return some value for every function, and validate if all of them have arrived (not feasible I feel, coz the number of times a single function has to be executed changes with user specified input ex: user gives 3 inputs, function executes for 300 cells. Also as explained before, the cell population/Loading state happens even after apparent function execution end)

Function to scan the page for cell display value of "Loading.." and if none, indicate that loading has been completed (This function doesn't work as expected, I'm guessing some sync issues) I know this is most feasible option but I was really looking forward to some kind of value/function that automatically tells me that processing is done.

I don't think code snippet is required for this, as I'm basically asking if a particular feature exists or not. If not, alternatives would be appreciated.

答:
The simplest approach is to display a loading-icon after a button is clicked. My recommendation is something like MaterializeCSS.

I assume there are 2 files:

Front-End HTML which contains the View

Back-End Apps Script File which contains Controller

So in your File #1 you would add the following loading bar:

```<code><!-- this is your existing button -->
<button id="yourTriggerButton">Click here</button>

<!-- in your css file, add #loadingBar{display:none} so that is hidden by default -->
<div class="progress" id="loadingBar">
  <div class="indeterminate"></div>
</div>

// we can also add some output message here
<div id="outputDiv"></div>
</code>```

And at the bottom of your front-end file, within a script tag we state that we want to show the loading element wenn the button is clicked (and your back-end script is running) and the hide it once the process is finished:

```<code>const triggerButton = document.getElementById("yourTriggerButton");
const loadingElement = document.getElementById("loadingBar");
const outputElement = document.getElementById("outputDiv");

triggerButton.addEventListener( "click", function(e){
  // lets show the loading icon when clicked
  loadingElement.style.display = "block";
  google.script.run
    .withSuccessHandler(handleSuccess)
    .backEndFunction()

  // this is called once backEndFunction is finished / returned
  function handleSuccess( returnValueFromBackEnd ){
    // lets hide the loading icon
    loadingElement.style.display = "none";
    // and show the user some feedback
    outputElement.innerText = "Done processing…"; // or you can input something that is returned from the back-end function
  }

});
</code>```

Body:
The simplest approach is to display a loading-icon after a button is clicked. My recommendation is something like MaterializeCSS.

I assume there are 2 files:

Front-End HTML which contains the View

Back-End Apps Script File which contains Controller

So in your File #1 you would add the following loading bar:

<!-- this is your existing button -->
<button id="yourTriggerButton">Click here</button>

<!-- in your css file, add #loadingBar{display:none} so that is hidden by default -->
<div class="progress" id="loadingBar">
  <div class="indeterminate"></div>
</div>

// we can also add some output message here
<div id="outputDiv"></div>

And at the bottom of your front-end file, within a script tag we state that we want to show the loading element wenn the button is clicked (and your back-end script is running) and the hide it once the process is finished:

const triggerButton = document.getElementById("yourTriggerButton");
const loadingElement = document.getElementById("loadingBar");
const outputElement = document.getElementById("outputDiv");

triggerButton.addEventListener( "click", function(e){
  // lets show the loading icon when clicked
  loadingElement.style.display = "block";
  google.script.run
    .withSuccessHandler(handleSuccess)
    .backEndFunction()

  // this is called once backEndFunction is finished / returned
  function handleSuccess( returnValueFromBackEnd ){
    // lets hide the loading icon
    loadingElement.style.display = "none";
    // and show the user some feedback
    outputElement.innerText = "Done processing…"; // or you can input something that is returned from the back-end function
  }

});


来源: stackexchange

问:
Why does Haskell import instances recursively? Why not import all instances only from the specified module?
From Haskell 2010 report, section 5.4. "an instance declaration is in scope if and only if a chain of import declarations leads to the module containing the instance declaration. ".

I indeed checked with a simple program and it does bring in scope instances recursively, that is even if they are not directly in the imported module.

Why is that recursive behavior desirable/necessary? Would it be so bad if it only brought in scope all the instances contained only inside the target module? (I don't want to import one specific instance). Would that really increase the number of imports so much?  Are there some fundamental/compilation/historical reasons it cannot be this way?

My current impression is that a big part of the  hostility regarding orphan instances might be based on that premiss, as a bad risk is that you unintentionally import an undesired orphan from some deeply buried module.

答:
I believe ehird's answer from here Explicitly import instances also provides an answer to this question.
If instances were not imported in a recursive fashion, then it would be possible to achieve the same effect as in their example.

A function could be created with a given Ord instance in some Bar.hs module importing some Data.Ord module. Then that function might be used in some other Baz.hs module which defines its own Ord instance, and doesn't import Data.Ord. Thus it would create undesirable incoherence. I initially thought this problem was just applying to specific instance imports, but it also applies in this case.

It is necessary to avoid that problem that every instance that is imported and in scope of some module, is automatically reexported to any other module, which means transitivity is unavoidable.

ContentLicense: CC BY-SA 4.0


问:
Avoiding Template operator overload collisions for float and non float on the operator first argument
I have a situation where my template modulus operator does play nice between floats and integer-ish types.
As I recall there is a way to make it select the more specific one over the broader scope one, but i can't seem to find or remember how to do this.

Basically I have 2 methods which are coliding (redefinition error.)

What I am trying to do is get the specialized modulus operator overload to be used when its the type (T_COORDS) is float, the the broader one when it's not float.

The specialized one (notice it uses the math fmod function):

```<code>template <size_t N
    , enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0, bool> = false>
friend Coords operator % (const Coords<float,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<float,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] = fmod(result.coords[i], coords1[i%N]);
  return result;
}
</code>```

The broader one (notice it uses the standard float modulus):

```<code>template <std::size_t N
    , std::enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0
    , bool> = false>
friend Coords operator % (const Coords<T_COORDS,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<T_COORDS,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] %= coords1[i%N];
  return result;
}
</code>```

Those overloads are enclosed with a Template class definition:

```<code>template <class T_COORDS, size_t C_COORDS, size_t N_COORDS>
class Coords {
public:

  T_COORDS coords[C_COORDS*N_COORDS];

  // (body in here)

};
</code>```

答:
I couldn't understand your logic but if you want to make your function behavior change upon the type double or not, you can use something like the following..</p>

```<code>#include <type_traits>
#include <iostream>
template <class T>
void func(){
    constexpr static bool isFloat = std::is_floating_point<T>::value;//static in classes
    if (isFloat) std::cout << "f\n";//u can use fmod() here
    else std::cout << "i\n";//use regular % here
}
int main(){
    func<int>();
    func<double>();
}
</code>```

Body:
I have a situation where my template modulus operator does play nice between floats and integer-ish types.
As I recall there is a way to make it select the more specific one over the broader scope one, but i can't seem to find or remember how to do this.

Basically I have 2 methods which are coliding (redefinition error.)

What I am trying to do is get the specialized modulus operator overload to be used when its the type (T_COORDS) is float, the the broader one when it's not float.

The specialized one (notice it uses the math fmod function):

template <size_t N
    , enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0, bool> = false>
friend Coords operator % (const Coords<float,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<float,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] = fmod(result.coords[i], coords1[i%N]);
  return result;
}

The broader one (notice it uses the standard float modulus):

template <std::size_t N
    , std::enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0
    , bool> = false>
friend Coords operator % (const Coords<T_COORDS,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<T_COORDS,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] %= coords1[i%N];
  return result;
}

Those overloads are enclosed with a Template class definition:

template <class T_COORDS, size_t C_COORDS, size_t N_COORDS>
class Coords {
public:

  T_COORDS coords[C_COORDS*N_COORDS];

  // (body in here)

};

Body:
I couldn't understand your logic but if you want to make your function behavior change upon the type double or not, you can use something like the following..

#include <type_traits>
#include <iostream>
template <class T>
void func(){
    constexpr static bool isFloat = std::is_floating_point<T>::value;//static in classes
    if (isFloat) std::cout << "f\n";//u can use fmod() here
    else std::cout << "i\n";//use regular % here
}
int main(){
    func<int>();
    func<double>();
}


问:
android studio get Activity object from service
i have an app with service that works completely background, but sometimes i need to change the content in the foreground activity , for now let's say  i want to show Toast.

first i am checking if the app is opened as foreground

```<code> public boolean isForeground(String myPackage) {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
    ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
    return componentInfo.getPackageName().equals(myPackage);
}
</code>```

then i want to know what is the running activity

```<code>  String PKG_Name = componentInfo.getPackageName();
</code>```

this will give me the name , but what i want is to is get the object Activity ,to do something like this:

```<code>activity.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
    }
});
</code>```

how can i do it? if not possible, is there's a way to is to send a signal or a message to the service to  tell the it?

答:
For that you have two options, if you are fine showing just a Toast and not interact with other elements, you can implement a broadcast reciever and make your custom intent with custom action,
Intent int= new Intent();   int.setAction("Your custom string here");
and then post a toast in your braodcast reciever,

OR

you can use a custom handler to interact with all the objects in foreground and activity, here's some study material for it,
https://developer.android.com/training/multiple-threads/communicate-ui

Body:
i have an app with service that works completely background, but sometimes i need to change the content in the foreground activity , for now let's say  i want to show Toast.

first i am checking if the app is opened as foreground

 public boolean isForeground(String myPackage) {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
    ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
    return componentInfo.getPackageName().equals(myPackage);
}

then i want to know what is the running activity

  String PKG_Name = componentInfo.getPackageName();

this will give me the name , but what i want is to is get the object Activity ,to do something like this:

activity.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
    }
});

how can i do it? if not possible, is there's a way to is to send a signal or a message to the service to  tell the it?


问:
The state variable returned after using useState react hook shows .map is not a function
This code gives me error when I try to map the state variable returned after calling useEffect hook.
On console, when I print the myAppointment it shows two values one is empty ([]) and other (Array[25]) I want to extract the petname values from this array . But getting error "map is not a function" Please look into it and help me!</p>

```<code>function App() {
  const [myAppointment, setmyAppointment] = useState([])
  useEffect(() => {
      fetch('./data.json')
      .then(response=> response.json())
      .then(result=>{
        const apts=result.map(item=>{
          return item
        })
        setmyAppointment(state=>({...state,
          myAppointment:apts
        }))
      })**strong text**
  },[])

  console.log(myAppointment)
  const listItem = myAppointment.map((item)=>{
    return(
      <div>{item.petName}</div>
    )
  })

  return (
    <main className="page bg-white" id="petratings">
    <div className="container">
      <div className="row">
        <div className="col-md-12 bg-white">
          <div className="container">
            {/* {listItem} */}
            <div><AddAppointment /></div>
            <div><SearchAppointment /></div>
            <div><ListAppointment /></div>
          </div>
        </div>
      </div>
    </div>
  </main>
  );
}
</code>```

答:
You have you state as an array. However when you try to update it you convert it into an object with key myAppointment which is the cause of your error.

You must update your state like

```<code>  setmyAppointment(state=> [...state, ...apts]);
</code>```

However since the state is initially empty and you only update it once in useEffect on initialLoad, you could also update it like

```<code> setmyAppointment(apts);
</code>```

Body:
This code gives me error when I try to map the state variable returned after calling useEffect hook.
On console, when I print the myAppointment it shows two values one is empty ([]) and other (Array[25]) I want to extract the petname values from this array . But getting error "map is not a function" Please look into it and help me!

function App() {
  const [myAppointment, setmyAppointment] = useState([])
  useEffect(() => {
      fetch('./data.json')
      .then(response=> response.json())
      .then(result=>{
        const apts=result.map(item=>{
          return item
        })
        setmyAppointment(state=>({...state,
          myAppointment:apts
        }))
      })**strong text**
  },[])

  console.log(myAppointment)
  const listItem = myAppointment.map((item)=>{
    return(

{item.petName}

    )
  })

  return (

            {/* {listItem} */}

<AddAppointment />

<SearchAppointment />

<ListAppointment />

  );
}

Body:
You have you state as an array. However when you try to update it you convert it into an object with key myAppointment which is the cause of your error.

You must update your state like

  setmyAppointment(state=> [...state, ...apts]);

However since the state is initially empty and you only update it once in useEffect on initialLoad, you could also update it like

 setmyAppointment(apts);


问:
Parameter must be an array or an object that implements Countable in process.php on line 45, theres a problem with "if(count($result)==1)"
```<code><?php

session_start();

$mysqli = new mysqli('localhost', 'root', '', 'crud') or die(mysqli_error($mysqli)); //Izveido savienojumu ar datubāzi

//default values
$id = 0;
$update = false;
$name = '';
$age = '';
$mobile = '';
$location = '';

if (isset($_POST['save'])){     //pārbauda vai ir nospiesta save poga
    $name = $_POST['name'];
    $age = $_POST['age'];
    $mobile = $_POST['mobile'];
    $location = $_POST['location'];

    $mysqli->query("INSERT INTO data (name, age, mobile, location) VALUES('$name', '$age', '$mobile', '$location')") or     //ievada datus datubāzē
        die($mysqli->error);

    $_SESSION['message'] = "Record has been saved!";    //iestata sesijas ziņojumu, ja dati tiek saglabāti
    $_SESSION['msg_type'] = "success";

    header('location: crud.php');       //novirza atpakaļ uz crud.php
}

if(isset($_GET['delete'])){     //pārbauda vai ir nospiesta delete poga
    $id = $_GET['delete'];
    $mysqli->query("DELETE FROM data WHERE id=$id") or die($mysqli->error());       //izdzēš datus no datubāzes

    $_SESSION['message'] = "Record has been deleted!";      //iestata sesijas ziņojumu, ja dati tiek izdzēsti
    $_SESSION['msg_type'] = "danger";

    header('location: crud.php');       //novirza atpakaļ uz crud.php
}

if(isset($_GET['edit'])){               //pārbauda vai ir nospiesta edit poga
    $id = $_GET['edit'];
    $update = true;
    $result = $mysqli->query("SELECT * FROM data WHERE id=$id") or die($mysqli->error());   //izvēlās datus no datubāzēs
   if(count($result)==1){                  //ja atrod ierakstu datubāzē
        $row = $result->fetch_array();      //atgriež datus no ieraksta
        $name = $row['name'];
        $age = $row['age'];
        $mobile = $row['mobile'];
        $location = $row['location'];
    }
}

if(isset($_POST['update'])){        //pārbauda vai ir nospiesta update poga
    $id = $_POST['id'];
    $name = $_POST['name'];
    $age = $_POST['age'];
    $mobile = $_POST['mobile'];
    $location = $_POST['location'];

    $mysqli->query("UPDATE data SET name='$name', age='$age', mobile='$mobile', location='$location' WHERE id=$id") or      //atjauno vecos datus uz jaunajiem ievadītajiem datiem
        die($mysqli->error);

   $_SESSION['message'] = "Record has been updated!";       //iestata sesijas ziņojumu, ja dati tiek atjaunotie
   $_SESSION['msg_type'] = "warning";

   header('location: crud.php');    //novirza atpakaļ uz crud.php
}
?>
</code>```

It's telling me that Parameter must be an array or an object that implements Countable in process.php on line 45, theres a problem with "if(count($result)==1)", and I can't find the problem for some reason, probably cos i'm a beginner. Anyway this is a CRUD - Create, Read, Update, Delete - and the Update/Edit function is not working so I'm stuck

答:
```<code>if ($result && $row = $result->fetch_array()){
    $name = $row['name'];
    $age = $row['age'];
    $mobile = $row['mobile'];
    $location = $row['location'];
}
</code>```

Body:
<?php

session_start();

$mysqli = new mysqli('localhost', 'root', '', 'crud') or die(mysqli_error($mysqli)); //Izveido savienojumu ar datubāzi

//default values
$id = 0;
$update = false;
$name = '';
$age = '';
$mobile = '';
$location = '';

if (isset($_POST['save'])){     //pārbauda vai ir nospiesta save poga
    $name = $_POST['name'];
    $age = $_POST['age'];
    $mobile = $_POST['mobile'];
    $location = $_POST['location'];

    $mysqli->query("INSERT INTO data (name, age, mobile, location) VALUES('$name', '$age', '$mobile', '$location')") or     //ievada datus datubāzē
        die($mysqli->error);

    $_SESSION['message'] = "Record has been saved!";    //iestata sesijas ziņojumu, ja dati tiek saglabāti
    $_SESSION['msg_type'] = "success";

    header('location: crud.php');       //novirza atpakaļ uz crud.php
}

if(isset($_GET['delete'])){     //pārbauda vai ir nospiesta delete poga
    $id = $_GET['delete'];
    $mysqli->query("DELETE FROM data WHERE id=$id") or die($mysqli->error());       //izdzēš datus no datubāzes

    $_SESSION['message'] = "Record has been deleted!";      //iestata sesijas ziņojumu, ja dati tiek izdzēsti
    $_SESSION['msg_type'] = "danger";

    header('location: crud.php');       //novirza atpakaļ uz crud.php
}

if(isset($_GET['edit'])){               //pārbauda vai ir nospiesta edit poga
    $id = $_GET['edit'];
    $update = true;
    $result = $mysqli->query("SELECT * FROM data WHERE id=$id") or die($mysqli->error());   //izvēlās datus no datubāzēs
   if(count($result)==1){                  //ja atrod ierakstu datubāzē
        $row = $result->fetch_array();      //atgriež datus no ieraksta
        $name = $row['name'];
        $age = $row['age'];
        $mobile = $row['mobile'];
        $location = $row['location'];
    }
}

if(isset($_POST['update'])){        //pārbauda vai ir nospiesta update poga
    $id = $_POST['id'];
    $name = $_POST['name'];
    $age = $_POST['age'];
    $mobile = $_POST['mobile'];
    $location = $_POST['location'];

    $mysqli->query("UPDATE data SET name='$name', age='$age', mobile='$mobile', location='$location' WHERE id=$id") or      //atjauno vecos datus uz jaunajiem ievadītajiem datiem
        die($mysqli->error);

   $_SESSION['message'] = "Record has been updated!";       //iestata sesijas ziņojumu, ja dati tiek atjaunotie
   $_SESSION['msg_type'] = "warning";

   header('location: crud.php');    //novirza atpakaļ uz crud.php
}
?>

It's telling me that Parameter must be an array or an object that implements Countable in process.php on line 45, theres a problem with "if(count($result)==1)", and I can't find the problem for some reason, probably cos i'm a beginner. Anyway this is a CRUD - Create, Read, Update, Delete - and the Update/Edit function is not working so I'm stuck


问:
How to ignore extra fields in create jira api request payload?
I am doing Jira integration in my application. Different issueType(like Story/Task/Support Incident) have a different set of fields to be added to create an issue of the given issueType.

I got a common POJO having fields for all types of issues. When I hit Jira API to create issue of type Story, it fails saying fields (which are required for issueType Support Incident) are not available on the screen.

```<code>{
    "errorMessages": [],
    "errors": {
        "key1": "Field 'key1' cannot be set. It is not on the appropriate screen, or unknown.",
        "key2": "Field 'key2' cannot be set. It is not on the appropriate screen, or unknown.",
        "customfield_10216": "Field 'customfield_10216' cannot be set. It is not on the appropriate screen, or unknown.",
        "customfield_21263": "Field 'customfield_21263' cannot be set. It is not on the appropriate screen, or unknown.",
        "customfield_10704": "Field 'customfield_10704' cannot be set. It is not on the appropriate screen, or unknown.",
        "customfield_10212": "Field 'customfield_10212' cannot be set. It is not on the appropriate screen, or unknown."
    }
}
</code>```

How can we ignore the unknown fields in Jira APIs?

答:
since you are creating an issue, I assume, you have to add the custom fields to your issue creation screen.

Have a look at your project settings and there on the screens:

( http:///plugins/servlet/project-config//screens )

Then open the screen that is used for creating an issue. Look at the URL. There you can see the screenId.

In that form, you can also add your custom fields to the screen.

https://community.atlassian.com/t5/Jira-questions/quot-Field-customfield-10012-cannot-be-set-It-is-not-on-the/qaq-p/664236

Body:
I am doing Jira integration in my application. Different issueType(like Story/Task/Support Incident) have a different set of fields to be added to create an issue of the given issueType.

I got a common POJO having fields for all types of issues. When I hit Jira API to create issue of type Story, it fails saying fields (which are required for issueType Support Incident) are not available on the screen.

{
    "errorMessages": [],
    "errors": {
        "key1": "Field 'key1' cannot be set. It is not on the appropriate screen, or unknown.",
        "key2": "Field 'key2' cannot be set. It is not on the appropriate screen, or unknown.",
        "customfield_10216": "Field 'customfield_10216' cannot be set. It is not on the appropriate screen, or unknown.",
        "customfield_21263": "Field 'customfield_21263' cannot be set. It is not on the appropriate screen, or unknown.",
        "customfield_10704": "Field 'customfield_10704' cannot be set. It is not on the appropriate screen, or unknown.",
        "customfield_10212": "Field 'customfield_10212' cannot be set. It is not on the appropriate screen, or unknown."
    }
}

How can we ignore the unknown fields in Jira APIs?


问:
Export vs. check out in SVN
What does exporting do in SVN? Are there any major differences between checking out a copy and export?</p>

答:
Exporting strips out all the versioning information and exports a particular revision (typically the latest) to another the specified location.

Copy or Checkout have versioning information with the source code.

If you list contents of the directory after an export you will find that the .svn directories are missing.

Typically something you would do if you were release your code for public download.

ContentLicense: CC BY-SA 3.0

Title: Export vs. check out in SVN


问:
Add/Remove hyphens/dashes from list of specific words with REGEX (American vs British English)
I am trying to add/remove hyphens from a list of very specific words in document, e.g.:

afore-mention, base-line, start-up >>
aforemention, baseline, startup

I would like to write ONE REGEX line for this, as the task and pattern is ALWAYS the same: add/remove a hyphen from a known word-pair. Of course, I can do this using a separate REGEX operation for each pair, but this is very clumsy and resource intensive:

```<code>(afore)-(mention) >> $1$2
(base)-(line) >> $1$2
(start)-(up) >> $1$2
etc.
</code>```

This seems a much simpler approach:

```<code>(?:(afore)-(mention)|(base)-(line)|(start)-(up))    >> $1$2
</code>```

The problem is that this gives a new back reference for every match, which is not useful. I could make two lists, but then I will have weird matches that I don't want, which becomes a problem if the list gets long, and random matches might occur (afore-line >> aforeline, base-up >> baseup, etc.):

```<code>(?:(afore|base|start)-(mentioned|line|up))  >> $1$2
</code>```

Any ideas? Thanks in advance!

答:
You may use named capturing groups using the (?<s>...) or (?'s'...) syntax:

```<code>(?<s>afore)-(?<r>mention)|(?<s>base)-(?<r>line)|(?<s>start)-(?<r>up)
</code>```

Or, to match whole words only, add word boundaries:

```<code>\b(?:(?<s>afore)-(?<r>mention)|(?<s>base)-(?<r>line)|(?<s>start)-(?<r>up))\b
</code>```

Replace with ${s}${r}.

See the regex demo.

Any part before the hyphen will land in the s named capture, and the second part will be in Group r. The named backreference syntax in .NET regex is ```${<strong><em>name</em></strong>}```

Demo screenshot:

Body:
I am trying to add/remove hyphens from a list of very specific words in document, e.g.:

afore-mention, base-line, start-up >>
aforemention, baseline, startup

I would like to write ONE REGEX line for this, as the task and pattern is ALWAYS the same: add/remove a hyphen from a known word-pair. Of course, I can do this using a separate REGEX operation for each pair, but this is very clumsy and resource intensive:

(afore)-(mention) >> $1$2
(base)-(line) >> $1$2
(start)-(up) >> $1$2
etc.

This seems a much simpler approach:

(?:(afore)-(mention)|(base)-(line)|(start)-(up))    >> $1$2

The problem is that this gives a new back reference for every match, which is not useful. I could make two lists, but then I will have weird matches that I don't want, which becomes a problem if the list gets long, and random matches might occur (afore-line >> aforeline, base-up >> baseup, etc.):

(?:(afore|base|start)-(mentioned|line|up))  >> $1$2

Any ideas? Thanks in advance!

Body:
You may use named capturing groups using the (?<s>...) or (?'s'...) syntax:

(?<s>afore)-(?<r>mention)|(?<s>base)-(?<r>line)|(?<s>start)-(?<r>up)

Or, to match whole words only, add word boundaries:

\b(?:(?<s>afore)-(?<r>mention)|(?<s>base)-(?<r>line)|(?<s>start)-(?<r>up))\b

Replace with ${s}${r}.

See the regex demo.

Any part before the hyphen will land in the s named capture, and the second part will be in Group r. The named backreference syntax in .NET regex is
${name}

Demo screenshot:


问:
getForEntity returns null
I try to write java service using spring boot. Here is the my code. The thing is I am getting null all the time. Where is the missing part in my code ?

```<code>@RestController
public class CurrencyConversionController {

    @GetMapping("/currency-converter/from/{from}/to/{to}/quantity/{quantity}")
    public CurrencyConversionBean convertCurrency(@PathVariable String from,
                                                  @PathVariable  String to,
                                                  @PathVariable BigDecimal quantity){

        Map<String,String> uriVariables = new HashMap<>();
        uriVariables.put("from",from);
        uriVariables.put("to",to);
        ResponseEntity<CurrencyConversionBean> responseEntity = new RestTemplate().
                getForEntity("http://localhost:8000/currency-exchange/from/{from}/to/{to}",
                CurrencyConversionBean.class,
                uriVariables);

        CurrencyConversionBean response = responseEntity.getBody();

        return new CurrencyConversionBean(response.getId(),from,to,response.getConvertionMultiple(),quantity,
                quantity.multiply(response.getConvertionMultiple()),
                response.getPort());

            }
}

</code>```

Here is the error I got;

```<code>rror on GET request for "http://localhost:8888/currency-conversion-service/default": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
com.example.currencyconversionservice.CurrencyConversionBean@333fa33b****************************
null---------------------------------
2019-11-12 11:43:26.506 ERROR 3008 --- [nio-8100-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
    at java.base/java.math.BigDecimal.multiply(BigDecimal.java:1512) ~[na:na]
    at com.example.currencyconversionservice.CurrencyConversionController.convertCurrency(CurrencyConversionController.java:35) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108) ~[spring-boot-actuator-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1579) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

com.example.currencyconversionservice.CurrencyConversionBean@43bfd139****************************
null---------------------------------

</code>```

As the error states it gives null pointer exception. I am following udemy course. This code from this course.

This is my first java service application and I could not figure out the problem. Any help is appreciated. Thank you.

答:
It may be bit late for reply, But might be useful for someone hopefully.

Here output of currency-exchange is not able to map to CurrencyConversionBean,

```<code> ResponseEntity<CurrencyConversionBean> responseEntity = new RestTemplate().
                    getForEntity("http://localhost:8000/currency-exchange/from/{from}/to/{to}",
                    CurrencyConversionBean.class,
                    uriVariables);
</code>```

Solution here can be, check bean variables fro both mocroservices, it must be same in order to map its output to CurrencyConversionBean. hopefully this helps.

Title: getForEntity returns null

Body:
I try to write java service using spring boot. Here is the my code. The thing is I am getting null all the time. Where is the missing part in my code ?

@RestController
public class CurrencyConversionController {

    @GetMapping("/currency-converter/from/{from}/to/{to}/quantity/{quantity}")
    public CurrencyConversionBean convertCurrency(@PathVariable String from,
                                                  @PathVariable  String to,
                                                  @PathVariable BigDecimal quantity){

        Map<String,String> uriVariables = new HashMap<>();
        uriVariables.put("from",from);
        uriVariables.put("to",to);
        ResponseEntity<CurrencyConversionBean> responseEntity = new RestTemplate().
                getForEntity("http://localhost:8000/currency-exchange/from/{from}/to/{to}",
                CurrencyConversionBean.class,
                uriVariables);

        CurrencyConversionBean response = responseEntity.getBody();

        return new CurrencyConversionBean(response.getId(),from,to,response.getConvertionMultiple(),quantity,
                quantity.multiply(response.getConvertionMultiple()),
                response.getPort());

            }
}

Here is the error I got;

rror on GET request for "http://localhost:8888/currency-conversion-service/default": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
com.example.currencyconversionservice.CurrencyConversionBean@333fa33b****************************
null---------------------------------
2019-11-12 11:43:26.506 ERROR 3008 --- [nio-8100-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
    at java.base/java.math.BigDecimal.multiply(BigDecimal.java:1512) ~[na:na]
    at com.example.currencyconversionservice.CurrencyConversionController.convertCurrency(CurrencyConversionController.java:35) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108) ~[spring-boot-actuator-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1579) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.27.jar:9.0.27]
    at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

com.example.currencyconversionservice.CurrencyConversionBean@43bfd139****************************
null---------------------------------

As the error states it gives null pointer exception. I am following udemy course. This code from this course.

This is my first java service application and I could not figure out the problem. Any help is appreciated. Thank you.

Body:
It may be bit late for reply, But might be useful for someone hopefully.

Here output of currency-exchange is not able to map to CurrencyConversionBean,

 ResponseEntity<CurrencyConversionBean> responseEntity = new RestTemplate().
                    getForEntity("http://localhost:8000/currency-exchange/from/{from}/to/{to}",
                    CurrencyConversionBean.class,
                    uriVariables);

Solution here can be, check bean variables fro both mocroservices, it must be same in order to map its output to CurrencyConversionBean. hopefully this helps.


问:
Chart.js - loading multiple charts with draggable datapoints into a single HTML Page
We're trying to load multiple line charts into one single page.
There is a simplified instance here - JSFiddle.

Canvases and instances have different names

We have used a JQuery wrapper to isolate the instantiation code.

Issue is that an offset is generated on dragging a data point so that the drag offset changes with each added instance. Just two instances are shown in the fiddle

We notice that the dynamic iframe generated by Chart.JS looks weird (developer tools)
Any comments / tips appreciated

答: It turns out that a different approach worked faultlessly.  It appears that the original code sample we based our approach on was flawed. Thanks very much for looking at this </p>


问:
adminer in a kubernetes pod
I am trying to create a pod with both phpmyadmin and adminer in it. I have the Dockerfile created but I am not sure of the entrypoint needed.

Has anyone accomplished this before? I have everything figured out but the entrypoint...

```<code>FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]

FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]
</code>```

------UPDATE 1 ----------
after read some comments I spilt my Dockerfiles and will create a yml file for the kube pod

```<code>FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]
</code>```

container 2

```<code>FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]
</code>```

I am still not sure what the entrypoint script should be

答: You can't combine two docker images like that. What you've created is a multi-stage build and only the last stage is what ends up in the final image. And even if you used multi-stage copies to carefully fold both into one image, you would need to think through how you will run both things simultaneously. The upstream adminer image uses php -S under the hood.

Title: adminer in a kubernetes pod

Body:
I am trying to create a pod with both phpmyadmin and adminer in it. I have the Dockerfile created but I am not sure of the entrypoint needed.

Has anyone accomplished this before? I have everything figured out but the entrypoint...

FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]

FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]

------UPDATE 1 ----------
after read some comments I spilt my Dockerfiles and will create a yml file for the kube pod

FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]

container 2

FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]

I am still not sure what the entrypoint script should be


问:
JFreechart SeriesException
I am trying to plot a bar chart using timeseries by introducing the beginning and the end date , but i got a problem with the end date it indicate :
Exception in thread "main" org.jfree.data.general.SeriesException: You are attempting to add an observation for the time period 4-mai-2011 but the series already contains an observation for that time period. Duplicates are not permitted.  Try using the addOrUpdate() method.

```<code>final TimeSeries series2 = new TimeSeries("ip max", Day.class);

String datebegin = "04/29/2011 02:00:01";
String dateend = "05/04/2011 02:00:01";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
date = formatter.parse(datebegin);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date);
Date date2;
date2 = (Date) formatter.parse(dateend);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
while (((cal1.compareTo(cal2)) != 0))  {
    cal1.add(Calendar.HOUR, 24);
    String intermediatestringdate = formatter.format(cal1.getTime());
    System.out.println( intermediatestringdate);
    Date intermediatedate = (Date) formatter.parse(dateend);
    series2.add(new Day(intermediatedate),500);
}
</code>```

答:
Assuming you are creating a time-based bar chart using ChartFactory.createXYBarChart() with an IntervalXYDataset, just construct the domain of your TimeSeries with a suitable TimePeriod.

```<code>private static IntervalXYDataset createDataset() {
    TimeSeries series = new TimeSeries("Series");
    RegularTimePeriod day = new Day(29, 4, 2011);
    RegularTimePeriod end = new Day(4, 5, 2011);
    int i = 1;
    while (day.compareTo(end) < 1) {
        series.addOrUpdate(day, i++);
        day = day.next();
    }
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);
    return dataset;
}
</code>```

Also, note that Day.class is no longer required by TimeSeries.

Title: JFreechart SeriesException

Body:
I am trying to plot a bar chart using timeseries by introducing the beginning and the end date , but i got a problem with the end date it indicate :
Exception in thread "main" org.jfree.data.general.SeriesException: You are attempting to add an observation for the time period 4-mai-2011 but the series already contains an observation for that time period. Duplicates are not permitted.  Try using the addOrUpdate() method.

final TimeSeries series2 = new TimeSeries("ip max", Day.class);

String datebegin = "04/29/2011 02:00:01";
String dateend = "05/04/2011 02:00:01";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
date = formatter.parse(datebegin);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date);
Date date2;
date2 = (Date) formatter.parse(dateend);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
while (((cal1.compareTo(cal2)) != 0))  {
    cal1.add(Calendar.HOUR, 24);
    String intermediatestringdate = formatter.format(cal1.getTime());
    System.out.println( intermediatestringdate);
    Date intermediatedate = (Date) formatter.parse(dateend);
    series2.add(new Day(intermediatedate),500);
}

Body:
Assuming you are creating a time-based bar chart using ChartFactory.createXYBarChart() with an IntervalXYDataset, just construct the domain of your TimeSeries with a suitable TimePeriod.

private static IntervalXYDataset createDataset() {
    TimeSeries series = new TimeSeries("Series");
    RegularTimePeriod day = new Day(29, 4, 2011);
    RegularTimePeriod end = new Day(4, 5, 2011);
    int i = 1;
    while (day.compareTo(end) < 1) {
        series.addOrUpdate(day, i++);
        day = day.next();
    }
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);
    return dataset;
}

Also, note that Day.class is no longer required by TimeSeries.


问:
How to use retrofit call for this response?
Response of the API having Get call but how to achieve these values from retrofit Api call in which call is going in the OnFailure function and unable to get respoonse in the Code snippet given after the Response Viz getresponse() function. This function is giving an exception and does not return the values of the Global, Countries and main model class**

```<code>The response of the API showing the object with key and having the values, how should one use Values of the key as it is not achievable by my java code snippet

                     {
                      "Global": {
                        "New": 118196,
                        "Total": 5898252,
                        "NewD": 4785,
                        "TotalD": 367273,
                        "NewR": 65964,
                        "TotalR": 2415401
                      },
                      "Countries": [
                        {
                          "Country": "Afghanistan",
                          "CountryCode": "AF",
                          "Slug": "afghanistan",
                          "Date": "2020-05-29T08:39:18Z"
                        },
                        {
                          "Country": "Belarus",
                          "CountryCode": "BY",
                          "Slug": "belarus",
                          "Date": "2020-05-29T08:39:18Z"
                        },
                        {
                          "Country": "Brazil",
                          "CountryCode": "BR",
                          "Slug": "brazil",
                          "Date": "2020-05-29T08:39:18Z"
                        }
                        ],
                      "Date": "2020-05-29T08:39:18Z"
                    }

                After making 3 models for this response namely Main, Global, Countries, how to get response values from Global i.e-("New": 118196, "Total": 5898252, "NewD": 4785,"TotalD": 367273,"NewR": 65964,"TotalR": 2415401), Countries({"Country": "Afghanistan", "CountryCode": "AF", "Slug":"afghanistan","Date": "2020-05-29T08:39:18Z"
                        }), and Main class(Countries,GLobal and Date).

                    Here is the java function which is-

                    private void getresponse() {
                            Gson gson = new GsonBuilder()
                                    .setLenient()
                                    .create();
                            Retrofit retrofit = new Retrofit.Builder()
                                    .baseUrl(endpointApi.BASE_URL)
                                    .addConverterFactory(GsonConverterFactory.create(gson))
                                    .build();
                            endpointApi api = retrofit.create(endpointApi.class);
                            Call<List<Main>> call = api.getResult();
                            call.enqueue(new Callback<List<Main>>() {
                                @Override
                                public void onResponse(Call<List<Main>> call, Response<List<Main>> response) {
                                    List<Main> heroList = response.body();
                                    for (int i = 0; i < heroList.size(); i++) {
                                        Integer heroes = heroList.get(i).getCountries().size();
                                        Log.i("test111","test111--"+heroes);
                                    }
                                }
                                @Override
                                public void onFailure(Call<List<Example>> call, Throwable t) {
                                    Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
                                    t.printStackTrace();
                                }
                            });
                        }
</code>```

The above java code is for retrofit for getting the response from the API, how to get TotalD from Global and Slung from Countries object in this code snippet. The above code Shows no response and goes to onFailure() function and unable to get the response fro the API as

```<code>        Here is the Interface code snippet-
        public interface endpointApi{
            String BASE_URL = "https://api.something.com/";
            @GET("summary")
            Call<List<Main>> getResult();
        }

            **How to achieve all values in Global i.e, Countries, and Main model class values?**
</code>```

答:
Use this if you only want totalD from Globals and slug from countries

```<code>public class MyResponse {
    private GlobalObj Global; //capital G for variable name
    private List<Country> Countries; //capital C for var name

    //your getter methods here...
}

public class GlobalObj {
    private String TotalD; //capital T for TotalD
    //your getter here
}

public class Country {
    private String Slug; //capital S.
    //your getter
}
</code>```

Then in your Call use this as follows:

```<code>Call<MyResponse> getResult..........
</code>```

Note: The names of your variables must match with those in the response else you'll get null in them. Pay attention to the capital letters of the variable names.
Or you can use @SerialzedName if you don't want capitals

Body:
Response of the API having Get call but how to achieve these values from retrofit Api call in which call is going in the OnFailure function and unable to get respoonse in the Code snippet given after the Response Viz getresponse() function. This function is giving an exception and does not return the values of the Global, Countries and main model class**

The response of the API showing the object with key and having the values, how should one use Values of the key as it is not achievable by my java code snippet

                     {
                      "Global": {
                        "New": 118196,
                        "Total": 5898252,
                        "NewD": 4785,
                        "TotalD": 367273,
                        "NewR": 65964,
                        "TotalR": 2415401
                      },
                      "Countries": [
                        {
                          "Country": "Afghanistan",
                          "CountryCode": "AF",
                          "Slug": "afghanistan",
                          "Date": "2020-05-29T08:39:18Z"
                        },
                        {
                          "Country": "Belarus",
                          "CountryCode": "BY",
                          "Slug": "belarus",
                          "Date": "2020-05-29T08:39:18Z"
                        },
                        {
                          "Country": "Brazil",
                          "CountryCode": "BR",
                          "Slug": "brazil",
                          "Date": "2020-05-29T08:39:18Z"
                        }
                        ],
                      "Date": "2020-05-29T08:39:18Z"
                    }

                After making 3 models for this response namely Main, Global, Countries, how to get response values from Global i.e-("New": 118196, "Total": 5898252, "NewD": 4785,"TotalD": 367273,"NewR": 65964,"TotalR": 2415401), Countries({"Country": "Afghanistan", "CountryCode": "AF", "Slug":"afghanistan","Date": "2020-05-29T08:39:18Z"
                        }), and Main class(Countries,GLobal and Date).

                    Here is the java function which is-

                    private void getresponse() {
                            Gson gson = new GsonBuilder()
                                    .setLenient()
                                    .create();
                            Retrofit retrofit = new Retrofit.Builder()
                                    .baseUrl(endpointApi.BASE_URL)
                                    .addConverterFactory(GsonConverterFactory.create(gson))
                                    .build();
                            endpointApi api = retrofit.create(endpointApi.class);
                            Call<List> call = api.getResult();
                            call.enqueue(new Callback<List>() {
                                @Override
                                public void onResponse(Call<List> call, Response<List> response) {
                                    List heroList = response.body();
                                    for (int i = 0; i < heroList.size(); i++) {
                                        Integer heroes = heroList.get(i).getCountries().size();
                                        Log.i("test111","test111--"+heroes);
                                    }
                                }
                                @Override
                                public void onFailure(Call<List<Example>> call, Throwable t) {
                                    Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
                                    t.printStackTrace();
                                }
                            });
                        }

The above java code is for retrofit for getting the response from the API, how to get TotalD from Global and Slung from Countries object in this code snippet. The above code Shows no response and goes to onFailure() function and unable to get the response fro the API as

        Here is the Interface code snippet-
        public interface endpointApi{
            String BASE_URL = "https://api.something.com/";
            @GET("summary")
            Call<List> getResult();
        }

            **How to achieve all values in Global i.e, Countries, and Main model class values?**

Body:
Use this if you only want totalD from Globals and slug from countries

public class MyResponse {
    private GlobalObj Global; //capital G for variable name
    private List<Country> Countries; //capital C for var name

    //your getter methods here...
}

public class GlobalObj {
    private String TotalD; //capital T for TotalD
    //your getter here
}

public class Country {
    private String Slug; //capital S.
    //your getter
}

Then in your Call use this as follows:

Call<MyResponse> getResult..........

Note: The names of your variables must match with those in the response else you'll get null in them. Pay attention to the capital letters of the variable names.
Or you can use @SerialzedName if you don't want capitals


问:
Run-Time Check Failure #2 - Stack around the variable 'e' was corrupted. occurred
```<code>    #include<iostream>
    #include <list>
    using namespace std;

class Euler {
private:
    int korifes = 0;
    int akmes = 0;
    int* pinakas[];
public:
    void print() { cout << *pinakas[0]; return; }

    Euler(int korifess, int akmess);
    ~Euler() { delete[] *pinakas; }

    void addAkmes(int kor1, int kor2);
};

Euler::Euler(int korifess, int akmess) : akmes(akmess), korifes(korifess) {
    *pinakas = new int(korifes);
    *pinakas[0] = 89;
}

int main() {
    Euler e(2, 1);
    e.print();
}
</code>```

Run-Time Check Failure #2 - Stack around the variable 'e' was corrupted. occurred...i can not find where i am wrong in my code.

答:
There are a number of errors in your code, all related to the nature of the pinakas member variable. As it stands, you are declaring this as an array of pointers (to int), and, furthermore, you are using a non-standard syntax for 'flexible' arrays (the empty []).

I don't normally just paste 'fixed' code as an answer but, in this case, that code (with the added \\\ comments where I've made changes) is likely to be the most succinct way to help you.

Although, as many here will no doubt point out, it is far better to avoid the use of 'raw' pointers and the new and delete operators, and use the std::vector container, instead.

#include <iostream>
#include <list>
//using namespace std;/// This is considered 'bad practice' by many programmers
using std::cout;/// Just use the aspect of the STL that you need!

class Euler {
private:
    int korifes = 0;
    int akmes = 0;
    int* pinakas;/// This will point an 'array' of integers
public:
    void print() {
        cout << pinakas[0]; return;/// No longer any need for the dereference (*)
    }
    Euler(int korifess, int akmess);
    ~Euler() {
        delete[] pinakas;/// No need for the dereference (*)
    }
//  void addAkmes(int kor1, int kor2);/// You haven't provided an actual definition for this, but your never use it!
};

Euler::Euler(int korifess, int akmess) : akmes(akmess), korifes(korifess)/// NOTE: Members are initialized in DECLARATION order!
{
    pinakas = new int[korifes];/// Use "[]" (not "()") to allocate an array!
    pinakas[0] = 89;/// No need for the dereference (*)
}
```

Feel free to ask for any further clarification and/or explanation.

Body:
    #include<iostream>
    #include <list>
    using namespace std;

class Euler {
private:
    int korifes = 0;
    int akmes = 0;
    int* pinakas[];
public:
    void print() { cout << *pinakas[0]; return; }

    Euler(int korifess, int akmess);
    ~Euler() { delete[] *pinakas; }

    void addAkmes(int kor1, int kor2);
};

Euler::Euler(int korifess, int akmess) : akmes(akmess), korifes(korifess) {
    *pinakas = new int(korifes);
    *pinakas[0] = 89;
}

int main() {
    Euler e(2, 1);
    e.print();
}

Run-Time Check Failure #2 - Stack around the variable 'e' was corrupted. occurred...i can not find where i am wrong in my code.

Body:
There are a number of errors in your code, all related to the nature of the pinakas member variable. As it stands, you are declaring this as an array of pointers (to int), and, furthermore, you are using a non-standard syntax for 'flexible' arrays (the empty []).

I don't normally just paste 'fixed' code as an answer but, in this case, that code (with the added \\\ comments where I've made changes) is likely to be the most succinct way to help you.

Although, as many here will no doubt point out, it is far better to avoid the use of 'raw' pointers and the new and delete operators, and use the std::vector container, instead.

#include <iostream>
#include <list>
//using namespace std;/// This is considered 'bad practice' by many programmers
using std::cout;/// Just use the aspect of the STL that you need!

class Euler {
private:
    int korifes = 0;
    int akmes = 0;
    int* pinakas;/// This will point an 'array' of integers
public:
    void print() {
        cout << pinakas[0]; return;/// No longer any need for the dereference (*)
    }
    Euler(int korifess, int akmess);
    ~Euler() {
        delete[] pinakas;/// No need for the dereference (*)
    }
//  void addAkmes(int kor1, int kor2);/// You haven't provided an actual definition for this, but your never use it!
};

Euler::Euler(int korifess, int akmess) : akmes(akmess), korifes(korifess)/// NOTE: Members are initialized in DECLARATION order!
{
    pinakas = new int[korifes];/// Use "[]" (not "()") to allocate an array!
    pinakas[0] = 89;/// No need for the dereference (*)
}

Feel free to ask for any further clarification and/or explanation.


问:
How to pass array as a parameter for rowMode="array" in pg-promise
I would like to get the result of a query using rowMode="array" (as this is a potentially very large table and I don't want it formatted to object format) but I couldn't figure out how to pass in a array/list parameter for use in an IN operator.

const events = await t.manyOrNone({text: `select * from svc.events where user_id in ($1:list);`, rowMode: "array"}, [[1,2]]);
```

<p>However, the above gives an error: syntax error at or near ":"</p>

<p>Removing the :list did not work either:</p>

<pre class="lang-js prettyprint-override"><code>const events = await t.manyOrNone({text: `select * from svc.events where user_id in ($1);`, rowMode: "array"}, [[1,2]]);
</code>```

Error: invalid input syntax for integer: "{"1","2"}"

I understand that this might be because I'm forced to use ParameterizedQuery format for rowMode="array" which does not allow those snazzy modifiers like :list, but this then leads to the question, if I were to use ParameterizedQuery format, then how do I natively pass in a Javascript array so that it is acceptable to the driver?

I guess an alternative formulation to this question is: how do I use arrays as parameters for ParameterizedQuery or PreparedStatements...

答:
Answering my own question as I eventually found an answer to this issue: how to pass in arrays as params for use in the IN operator when using rowMode="array" | ParameterizedQuery | PreparedStatements.

Because this query is being parameterized in the server, we cannot use the IN operator, because the IN operator parameterize items using IN ($1, $2, $3...). Instead we need to use the ANY operator, where ANY($1) where for $1 an array is expected.

So the query that will work is:

```<code>const events = await t.manyOrNone({text: `select * from svc.events where user_id=ANY($1);`, rowMode: "array"}, [[1,2]]);
</code>```

Body:
I would like to get the result of a query using rowMode="array" (as this is a potentially very large table and I don't want it formatted to object format) but I couldn't figure out how to pass in a array/list parameter for use in an IN operator.

const events = await t.manyOrNone({text: `select * from svc.events where user_id in ($1:list);`, rowMode: "array"}, [[1,2]]);

However, the above gives an error: syntax error at or near ":"

Removing the :list did not work either:

const events = await t.manyOrNone({text: `select * from svc.events where user_id in ($1);`, rowMode: "array"}, [[1,2]]);

Error: invalid input syntax for integer: "{"1","2"}"

I understand that this might be because I'm forced to use ParameterizedQuery format for rowMode="array" which does not allow those snazzy modifiers like :list, but this then leads to the question, if I were to use ParameterizedQuery format, then how do I natively pass in a Javascript array so that it is acceptable to the driver?

I guess an alternative formulation to this question is: how do I use arrays as parameters for ParameterizedQuery or PreparedStatements...

Body:
Answering my own question as I eventually found an answer to this issue: how to pass in arrays as params for use in the IN operator when using rowMode="array" | ParameterizedQuery | PreparedStatements.

Because this query is being parameterized in the server, we cannot use the IN operator, because the IN operator parameterize items using IN ($1, $2, $3...). Instead we need to use the ANY operator, where ANY($1) where for $1 an array is expected.

So the query that will work is:

const events = await t.manyOrNone({text: `select * from svc.events where user_id=ANY($1);`, rowMode: "array"}, [[1,2]]);


问:
How to share my web app to different users

I hosted my web app on a server.

The web app is composed of a client part (which will only see users) and an administrative part (which will only see the owner of the restaurant).

Let's assume that the www.food1.com and www.food2.com restaurant want to buy my app.
Is there a way to avoid installing my app on their servers?

I would like my app to be installed only on my server and based on who to access my app (www.food1.com or www.food2.com), access the food1 or food2 database.

If I buy a host, can I create various domains in order to distinguish the various customers?

So the problem is not to host my code on a server that others will buy.

答:
This is a very broad question, you will have to evaluate many factors to decide on the approach, you seem to be having a requirement for a Multi-Tenant application, you can go through the various levels of multi-tenancy.

The option that you can choose is to have a single code base with databases per tenant like (Food1 -> Food1DB, Food2 -> Food2DB), the tenant identification strategy can be to use different domains, preferable to use a subdomain like food2.yourcompany.com, food1.yourcompany.com.

Few factors to guide you to choosing the strategy

Level of data uniqueness per tenant and the data volume expected

Are they going to be geographically distributed

What levels of customizations in your application, the end customers will prefer to

and lots more. Please think through and come up with a specific problem that we can tackle.


问:
how to debug error from stripe API call? need a node.js stacktrace across event emitter?
I have a node webapp that makes various API calls to Stripe using the stripe npm package. Sometimes I get errors like the one below. Notice that the stacktrace is truncated so that I cannot see which stripe API call causes the error and I also cannot see where in my app this API call is made.

Is there anything I can do to get better error stacktraces?

```<code>Error: Missing required param: customer.
    at Function.generate (/home/molsson/dv/foobar/node_modules/stripe/lib/Error.js:39:16)
    at IncomingMessage.<anonymous> (/home/molsson/dv/foobar/node_modules/stripe/lib/StripeResource.js:175:33)
    at Object.onceWrapper (events.js:299:28)
    at IncomingMessage.emit (events.js:215:7)
    at IncomingMessage.EventEmitter.emit (domain.js:476:20)
    at endReadableNT (_stream_readable.js:1183:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
</code>```

Note: the error itself is just an example. I have already fixed it. I just want to get better stacktraces or a better method of debugging these types of errors quickly.

I'm pretty sure my node version has async stacks by default:

```<code>$ node --version
v12.12.0
$ node -p process.versions.v8
7.7.299.13-node.12
</code>```

I tried running with NODE_OPTIONS='--trace-warnings --stack-trace-limit=9999' but it didn't help.

Does it exists some kind of "async stacktraces across event emitters" debugging thing?

答:
I found a good answer to this question myself. The stripe library fires and event before making a new API request, so you can print a stacktrace from there:

```<code>    stripe.on('request', request => {
      const currentStack = (new Error()).stack.replace(/^Error/, '')
      console.log(`Making Stripe HTTP request to ${request.path}, callsite: ${currentStack}`)
    })
</code>```

I added a STRIPE_API_TRACING option to my app that I can turn on if I experience errors without stacks. With the tracing on I can just scroll a bit up in the log and see what API calls was dispatched just before the error happened.

Body:
I have a node webapp that makes various API calls to Stripe using the stripe npm package. Sometimes I get errors like the one below. Notice that the stacktrace is truncated so that I cannot see which stripe API call causes the error and I also cannot see where in my app this API call is made.

Is there anything I can do to get better error stacktraces?

Error: Missing required param: customer.
    at Function.generate (/home/molsson/dv/foobar/node_modules/stripe/lib/Error.js:39:16)
    at IncomingMessage.<anonymous> (/home/molsson/dv/foobar/node_modules/stripe/lib/StripeResource.js:175:33)
    at Object.onceWrapper (events.js:299:28)
    at IncomingMessage.emit (events.js:215:7)
    at IncomingMessage.EventEmitter.emit (domain.js:476:20)
    at endReadableNT (_stream_readable.js:1183:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)

Note: the error itself is just an example. I have already fixed it. I just want to get better stacktraces or a better method of debugging these types of errors quickly.

I'm pretty sure my node version has async stacks by default:

$ node --version
v12.12.0
$ node -p process.versions.v8
7.7.299.13-node.12

I tried running with NODE_OPTIONS='--trace-warnings --stack-trace-limit=9999' but it didn't help.

Does it exists some kind of "async stacktraces across event emitters" debugging thing?

Body:
I found a good answer to this question myself. The stripe library fires and event before making a new API request, so you can print a stacktrace from there:

    stripe.on('request', request => {
      const currentStack = (new Error()).stack.replace(/^Error/, '')
      console.log(`Making Stripe HTTP request to ${request.path}, callsite: ${currentStack}`)
    })

I added a STRIPE_API_TRACING option to my app that I can turn on if I experience errors without stacks. With the tracing on I can just scroll a bit up in the log and see what API calls was dispatched just before the error happened.


问:
OpenCV copying subsection of an image

What I'm trying to do

I'm trying to paste a subsection of one image onto another for part of a project I'm working on. When I tried to view what I had so far, I saw that calling imshow() on both images to check doesn't actually show that both of them have the same BRG values at the points that they should.

What's wrong

The values are almost always wrong and often half of the screen will show up as black.

IE: pixel [0,1] of firstIMG will have [91,21,30] while secondIMG will have some other values when hovering over the pixel in the imshow() screen

The code

// Randomly create an image of 10x10 pixels
Mat firstIMG = Mat(10, 10, CV_8UC3);
randu(firstIMG, Scalar::all(0), Scalar::all(255));
imshow("First", firstIMG);
waitKey();

// Create a second image of same type as the first
Mat secondIMG = Mat::zeros(firstIMG.rows-5, firstIMG.cols-5, firstIMG.type());

// Iterate through all rows of secondIMG
for(int i = 0; i < secondIMG.rows; i++) {

    // Iterate through all columns of secondIMG
    for(int j = 0; j < secondIMG.cols; j++) {
        secondIMG.at<unsigned char>(i, j) = firstIMG.at<unsigned char>(i, j);
    }
}

imshow("Second", secondIMG);
waitKey();
```

<p><br></p>

<h2>What I've tried so far</h2>

<p>It will print out the same exact data for both images if I iterate over every pixel of each image, but when I use <code>imshow()</code> on the <code>secondIMG</code> many if not all of the pixels are incorrect.
<br><br>
Despite that, I've also tried accessing and changing the BRG values for the <code>secondIMG</code> in different ways, [like in this post][1]. That still leads to the same result of completely different values at the points that they share.
<br><br>
Finally, I've also tried just straight up <code>clone()</code> the <code>firstIMG</code> with the same size and everything, also leading to the same error as above.</p>

```  [1]: https://stackoverflow.com/questions/7899108/opencv-get-pixel-channel-value-from-mat-image
```

答:
It should be cv::Vec3b instead of uchar for a color image.

Instead of looping over pixels, you can use optimised built-in functions.

```<code>cv::Mat secondIMG(firstIMG.rows, firstIMG.cols, firstIMG.type());
cv::Rect rect(0, 0, secondIMG.cols, secondIMG.rows);  // x, y, width, height

firstIMG(rect).copyTo(secondIMG);
// or
cv::Mat thirdIMG = firstIMG(rect).clone();
</code>```

Title: OpenCV copying subsection of an image

Body:
What I'm trying to do

I'm trying to paste a subsection of one image onto another for part of a project I'm working on. When I tried to view what I had so far, I saw that calling imshow() on both images to check doesn't actually show that both of them have the same BRG values at the points that they should.

What's wrong

The values are almost always wrong and often half of the screen will show up as black.

IE: pixel [0,1] of firstIMG will have [91,21,30] while secondIMG will have some other values when hovering over the pixel in the imshow() screen

The code

// Randomly create an image of 10x10 pixels
Mat firstIMG = Mat(10, 10, CV_8UC3);
randu(firstIMG, Scalar::all(0), Scalar::all(255));
imshow("First", firstIMG);
waitKey();

// Create a second image of same type as the first
Mat secondIMG = Mat::zeros(firstIMG.rows-5, firstIMG.cols-5, firstIMG.type());

// Iterate through all rows of secondIMG
for(int i = 0; i < secondIMG.rows; i++) {

    // Iterate through all columns of secondIMG
    for(int j = 0; j < secondIMG.cols; j++) {
        secondIMG.at<unsigned char>(i, j) = firstIMG.at<unsigned char>(i, j);
    }
}

imshow("Second", secondIMG);
waitKey();

What I've tried so far

It will print out the same exact data for both images if I iterate over every pixel of each image, but when I use imshow() on the secondIMG many if not all of the pixels are incorrect.

Despite that, I've also tried accessing and changing the BRG values for the secondIMG in different ways, [like in this post][1]. That still leads to the same result of completely different values at the points that they share.

Finally, I've also tried just straight up clone() the firstIMG with the same size and everything, also leading to the same error as above.

  [1]: https://stackoverflow.com/questions/7899108/opencv-get-pixel-channel-value-from-mat-image

Body:
It should be cv::Vec3b instead of uchar for a color image.

Instead of looping over pixels, you can use optimised built-in functions.

cv::Mat secondIMG(firstIMG.rows, firstIMG.cols, firstIMG.type());
cv::Rect rect(0, 0, secondIMG.cols, secondIMG.rows);  // x, y, width, height

firstIMG(rect).copyTo(secondIMG);
// or
cv::Mat thirdIMG = firstIMG(rect).clone();


问:
Sql get latest n rows in sql whose sum is greater than or equal to a value
I have a table  of fb_data of following data

```<code>id sessions created_at

1   25     2020-05-28 12:00:00

2   30     2020-05-28 13:00:00

3   24     2020-05-29 14:00:00
</code>```

I want to get latest rows whose sum creates greater than 40 . For e.g  id 2 and 3 creates the sum greater than 40   . Then I want only 2 and 3 rows excluding the rows 1

答:
You can do something like this :</p>

```<code>select * from (select *,sum(session_name) OVER (ORDER BY Id)x from t1 ) a where x>40
</code>```

Body:
I have a table  of fb_data of following data

id sessions created_at

1   25     2020-05-28 12:00:00

2   30     2020-05-28 13:00:00

3   24     2020-05-29 14:00:00

I want to get latest rows whose sum creates greater than 40 . For e.g  id 2 and 3 creates the sum greater than 40   . Then I want only 2 and 3 rows excluding the rows 1

Body:
You can do something like this :

select * from (select *,sum(session_name) OVER (ORDER BY Id)x from t1 ) a where x>40


问:
Docker doesn't copy assets folder
I don't have a .dockerignore file but Docker doesn't copy assets folder to the images when building.

project:

assets

models

v1

src

venv

Dockerfile

App.py :

```<code>    import numpy as np
    import tensorflow as tf
                                  [...]
    with open('../assets/model/v1/model_architecture_V1.json', 'r') as f:
        model_json = f.read()

    model.load_weights("../assets/model/v1/model_weight_V1.h5")

                                  [...]

    if __name__ == '__main__':
       app.run(host='0.0.0.0', port=4000, debug=True)
</code>```

Dockerfile:

```<code>    FROM python:3

    WORKDIR /app

    COPY requirements.txt ./
    RUN pip install --no-cache-dir -r requirements.txt

    COPY . .

    CMD ["python3","src/app.py"]
</code>```

When I run the project image,Python throws me this error:

When I run the app without Docker there is no problem.

答:
```<code>CMD ["python3","src/app.py"]
</code>```

Observe this statement, you are running the app.py script outside the src folder but not inside the src folder.
So open() function takes the path either the absolute one or the relative one. When it comes to the relative path you need to provide the path from where you are running the python script app.py as you are running outside of the src folder, therefore, your path should also be given the same way. So it will be assests/models/v1/model_architecture_V1.json

There is nothing to do with the docker file or it's the position here. You should understand how the copy and movement to the directories happening in your container and then also understand the nature of python, you need to provide the relative path on the basis of where you are running the script but not with respect to the position of the python script app.py.

Title: Docker doesn't copy assets folder

Body:
I don't have a .dockerignore file but Docker doesn't copy assets folder to the images when building.

project:

assets

models

v1

src

venv

Dockerfile

App.py :

    import numpy as np
    import tensorflow as tf
                                  [...]
    with open('../assets/model/v1/model_architecture_V1.json', 'r') as f:
        model_json = f.read()

    model.load_weights("../assets/model/v1/model_weight_V1.h5")

                                  [...]

    if __name__ == '__main__':
       app.run(host='0.0.0.0', port=4000, debug=True)

Dockerfile:

    FROM python:3

    WORKDIR /app

    COPY requirements.txt ./
    RUN pip install --no-cache-dir -r requirements.txt

    COPY . .

    CMD ["python3","src/app.py"]

When I run the project image,Python throws me this error:

When I run the app without Docker there is no problem.

Body:
CMD ["python3","src/app.py"]

Observe this statement, you are running the app.py script outside the src folder but not inside the src folder.
So open() function takes the path either the absolute one or the relative one. When it comes to the relative path you need to provide the path from where you are running the python script app.py as you are running outside of the src folder, therefore, your path should also be given the same way. So it will be assests/models/v1/model_architecture_V1.json

There is nothing to do with the docker file or it's the position here. You should understand how the copy and movement to the directories happening in your container and then also understand the nature of python, you need to provide the relative path on the basis of where you are running the script but not with respect to the position of the python script app.py.


问:
Remove custom Chart Js tool tip colour square
I have the following data for different months as bellow

```<code>var barChartData = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
        label: 'Task 1',
        backgroundColor: "rgba(220,220,220,0.5)",
        data: [50, 40, 23, 45, 67, 78, 23]
    }, {
        label: 'Task 2',
        backgroundColor: "rgba(151,187,205,0.5)",
        data: [50, 40, 78, 23, 23, 45, 67]
    }, {
        label: 'Task 3',
        backgroundColor: "rgba(82,154,190,0.5)",
        data: [50, 67, 78, 23, 40, 23, 0]
    }]
};
</code>```

I wanted to remove the colour square in front of the total label
Expected Outcome

```<code>var ctx = document.getElementById("canvas").getContext("2d");
var myBar = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
    options: {
        title: {
            display: true,
            text: "Stacked Bar Chart"
        },
        tooltips: {
           intersect : false,
           mode: 'label',
            callbacks: {
                label: function(tooltipItem, data) {

                   var chartLabel = data.datasets[tooltipItem.datasetIndex].label;
                   var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];

                   var total = 0;
                   var label = '';

                   for (var i = 0; i < data.datasets.length; i++) {
                       total += data.datasets[i].data[tooltipItem.index];
                   }

                   if (tooltipItem.datasetIndex != data.datasets.length - 1) {
                      label += chartLabel + " : $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                   } else {
                        label += chartLabel + " : $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                      label = [label, " Total : $" + total];
                   }
                   return label;
                }
            }
        },
        responsive: true,
        scales: {
            xAxes: [{
                stacked: true,
            }],
            yAxes: [{
                stacked: true
            }]
        }
    }
});
</code>```

Here I am displaying the labels one after the other and finally calculating the Total of all three, but Total value generated with the last data set the colour, How we can remove the colour square in front of Total?

答:
Instead of including the total in the tooltips.callbacks.label function, use a tooltips.callbacks.footer function to return the total line.

Please have a look at my answer I gave to a similar question.

Body:
I have the following data for different months as bellow

var barChartData = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
        label: 'Task 1',
        backgroundColor: "rgba(220,220,220,0.5)",
        data: [50, 40, 23, 45, 67, 78, 23]
    }, {
        label: 'Task 2',
        backgroundColor: "rgba(151,187,205,0.5)",
        data: [50, 40, 78, 23, 23, 45, 67]
    }, {
        label: 'Task 3',
        backgroundColor: "rgba(82,154,190,0.5)",
        data: [50, 67, 78, 23, 40, 23, 0]
    }]
};

I wanted to remove the colour square in front of the total label
Expected Outcome

var ctx = document.getElementById("canvas").getContext("2d");
var myBar = new Chart(ctx, {
    type: 'bar',
    data: barChartData,
    options: {
        title: {
            display: true,
            text: "Stacked Bar Chart"
        },
        tooltips: {
           intersect : false,
           mode: 'label',
            callbacks: {
                label: function(tooltipItem, data) {

                   var chartLabel = data.datasets[tooltipItem.datasetIndex].label;
                   var valor = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];

                   var total = 0;
                   var label = '';

                   for (var i = 0; i < data.datasets.length; i++) {
                       total += data.datasets[i].data[tooltipItem.index];
                   }

                   if (tooltipItem.datasetIndex != data.datasets.length - 1) {
                      label += chartLabel + " : $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                   } else {
                        label += chartLabel + " : $" + valor.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
                      label = [label, " Total : $" + total];
                   }
                   return label;
                }
            }
        },
        responsive: true,
        scales: {
            xAxes: [{
                stacked: true,
            }],
            yAxes: [{
                stacked: true
            }]
        }
    }
});

Here I am displaying the labels one after the other and finally calculating the Total of all three, but Total value generated with the last data set the colour, How we can remove the colour square in front of Total?