问:
JavaScript - How do i check execution of my command finished or not?
I want to make a 3D matrix and fill it with values from a text file then make a grid with size 180*90, and color it with respect to values from my matrix,

for example: blue for negative values, red for positive and white for zero values.

I want to store what i read from my text file in a 3D matrix.

but i have problem, when i execute my html file and use
 console.log(myMatrix) it shows me undefined and when i copy-paste for-loop in console,

for example
 console.log(myMatrix[0][0][4]) shows me correct answer which is 90.

so i guess maybe the problem is related to javaScript, because js read all code and when i try console.log(myMatrix[0][0][4]) it shows me undefined because reading file and store in array does not complete but when i use console command because it is in RAM, I can see correct answer.

therefore, i decided to check if reading the file and store it in an array completed, then execute my for-loop to store values from an array to myMatrix. But i do not know how can i do this?

i tried use setTimeout but i thought maybe execution time in my system is different from other system or also network.Also i thought for Callback function but i did not achieved anything. I hope you help me.

this is my code:

```<code><!DOCTYPE html>
<html>
    <head>
        <script src="https://d3js.org/d3.v5.min.js"></script>
    </head>
    <body>

        <div id="grid"></div>
        <script>
        //creat 1670 numbers of matrices with size of 180*90
                var myMatrix = new Array(1670)
                for (var i=0; i<1670; i++){
                    myMatrix[i] = twodmatrix()
                }

                function twodmatrix(){
                    var myMat = new Array(180)
                    for (var i=0; i<180; i++){
                        myMat[i] = new Array(90)
                    }
                    return(myMat)
                }

                var myGrid = new Array(1670)
                for (var i=0; i<1670; i++){
                    myGrid[i] = twodmatrix()}

                var array = new Array()

                    xmlhttp = new XMLHttpRequest();
                    xmlhttp.open("GET", "tempanomaly_new.txt", true);
                    xmlhttp.send();
                    xmlhttp.onreadystatechange=function() {
                        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                            parse(xmlhttp.responseText);
                        }
                    }
                function parse (text) {
                     array = text.split(",");
                     return array
                    //Do something

                }

                function treeDmatrix(){
                var n=0;
                for(var i=0;i<1670;i++){
                    for(var j=0;j<180;j++){
                        for(var k=0; k<90; k++){myMatrix[i][j][k]= array[n];
                                                n +=1;}}}

                }

                /*var mycolor;

                for(var i=0; i<array.length; i++){
                    if (array[i] == 0){ function white(){  mycolor = d3.scalelinear().domain([1,5]).range(["white"])}}
                    else if (array[i] > 0 ){ function red(){ mycolor = d3.scalelinear().domain([1,5]).range(["red"])}}
                    else if (array[i] < 0 ){function blue(){ mycolor = d3.scalelinear().domain([1,5]).range(["blue"])}}
                }

                /* Start make a grid and color it */
                /*
                const BLOCK_SIZE = 30;
                const BLOCK_SPACE = 5;
                const ROW_SIZE = 90;
                const COL_SIZE = 180;

                gridData = new Array(COL_SIZE);
                for (var i = 0; i < COL_SIZE; i++) {
                    gridData[i] = new Array(ROW_SIZE);
                    for (var j = 0; j < ROW_SIZE; j++) {
                        gridData[i][j] = {
                            x: (i + 1) * BLOCK_SIZE + BLOCK_SPACE,
                            y: (j + 1) * BLOCK_SIZE + BLOCK_SPACE,
                            size: BLOCK_SIZE,
                            }}}

    var grid = d3.select("#grid")
    .append("svg")
    .attr("width", "100%")
    .attr("height", "100%")
    .style("color", "#b2b2b2");

    var row = grid.selectAll(".row")
    .data(gridData)
    .enter().append("g")
    .attr("class", "row");

    var column = row.selectAll(".square")
    .data(function(data) { return data; })
    .enter()
    .append("rect")
    .attr("class", "square")
    .attr("x", function(data) { return data.x; })
    .attr("y", function(data) { return data.y; })
    .attr("width", function(data) { return data.size; })
    .attr("height", function(data) { return data.size; })
    .style("stroke", "#222")
    .style("fill", function(data) { return mycolor(data)});*/
        </script>
    </body>
</html>
</code>```

答:
XMLHTTPRequest is asynchronous. This means the JS will just initiate the data request and continue processing the rest of your code. When the requested data arrives (I would say for the simplicity), it fires the onreadystatechange function.

Now, this is the moment you should fill your array and start processing it. Put your loop inside a function named buildMatrix and execute the function once the data is arrived.

```<code>xmlhttp.onreadystatechange=function() {
                        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                            var d = parse(xmlhttp.responseText);
                            buildMatrix(d);
                        }
                    }
</code>```

And log the matrix to the console after all these are over. The last line to execute in your code therefore is

```<code>buildMatrix(d)
console.log(myMatrix)
</code>```

Body:
I want to make a 3D matrix and fill it with values from a text file then make a grid with size 180*90, and color it with respect to values from my matrix,

for example: blue for negative values, red for positive and white for zero values.

I want to store what i read from my text file in a 3D matrix.

but i have problem, when i execute my html file and use
 console.log(myMatrix) it shows me undefined and when i copy-paste for-loop in console,

for example
 console.log(myMatrix[0][0][4]) shows me correct answer which is 90.

so i guess maybe the problem is related to javaScript, because js read all code and when i try console.log(myMatrix[0][0][4]) it shows me undefined because reading file and store in array does not complete but when i use console command because it is in RAM, I can see correct answer.

therefore, i decided to check if reading the file and store it in an array completed, then execute my for-loop to store values from an array to myMatrix. But i do not know how can i do this?

i tried use setTimeout but i thought maybe execution time in my system is different from other system or also network.Also i thought for Callback function but i did not achieved anything. I hope you help me.

this is my code:

<!DOCTYPE html>

Body:
XMLHTTPRequest is asynchronous. This means the JS will just initiate the data request and continue processing the rest of your code. When the requested data arrives (I would say for the simplicity), it fires the onreadystatechange function.

Now, this is the moment you should fill your array and start processing it. Put your loop inside a function named buildMatrix and execute the function once the data is arrived.

xmlhttp.onreadystatechange=function() {
                        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                            var d = parse(xmlhttp.responseText);
                            buildMatrix(d);
                        }
                    }

And log the matrix to the console after all these are over. The last line to execute in your code therefore is

buildMatrix(d)
console.log(myMatrix)


来源: stackexchange

问:
mongoose validation error occurs even though required field is given
```<code>    // Assign unique krypter id
    assignKrypterID = () =>
    {
      let id = Math.floor(Math.random()*(999999-100000)+100000);
      console.log(id);
      Krypter
        .findOne({krypter_id: id.toString()})
        .then(krypter => {
          if (krypter)
            assignKrypterID()
          else
            return id.toString()
        })
        .catch(err => console.log(err))
    }

    const newKrypter = new Krypter({
      handle: req.body.handle,
      password: req.body.password, // plain text
      krypter_id: assignKrypterID()
    });

    // Hashes the plaintext password and saves it
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(newKrypter.password, salt, (err, hash) => {
        if (err) throw err;
        newKrypter.password = hash; // encrypted password
        newKrypter
          .save()
          .then(krypter => res.json(krypter))
          .catch(err => console.log(err));
      })
    });
</code>```

I tried to assign a unique 6 digit id to each user during registration using the function 'assignKrypterID()'. But the following error is obtained:

This is my schema:

```<code>const KrypterSchema = new Schema({
  handle: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  krypter_id: {
    type: String,
    required: true
  }
});
</code>```

Can't this be achieved using recursion? Or is recursion a bad move here?

Help me how to modify this to find whether the randomly generated Id is alrady assigned to an object.

答:
assignKrypterID = async() => {
  try {
    let krypter_ids = await Krypter.find({}).map(obj => obj.krypter_id)
    let flag = true
    while (flag) {
      let id = Math.floor(Math.random() * (999999 - 100000) + 100000);
      console.log(id);
      if (krypter_ids.includes(id)) {
        continue;
      } else {
        flag = false
        return id.toString()
      }
    }
  } catch (err) {
    throw err
    console.log(err)
  }
}
async function foo() {
  try {
    let krypter_id = (await assignKrypterID()) || ""
    const newKrypter = new Krypter({
      handle: req.body.handle,
      password: req.body.password, // plain text
      krypter_id: krypter_id
    });

    // Hashes the plaintext password and saves it
    let salt = await bcrypt.genSalt(10)
    let hash = await bcrypt.hash(newKrypter.password, salt)
    newKrypter.password = hash; // encrypted password
    let krypter = await newKrypter.save()
    res.json(krypter)
  } catch (err) {
    console.log(err)
    throw err
  }

}

foo()```

ContentLicense: CC BY-SA 4.0

Body:
    // Assign unique krypter id
    assignKrypterID = () =>
    {
      let id = Math.floor(Math.random()*(999999-100000)+100000);
      console.log(id);
      Krypter
        .findOne({krypter_id: id.toString()})
        .then(krypter => {
          if (krypter)
            assignKrypterID()
          else
            return id.toString()
        })
        .catch(err => console.log(err))
    }

    const newKrypter = new Krypter({
      handle: req.body.handle,
      password: req.body.password, // plain text
      krypter_id: assignKrypterID()
    });

    // Hashes the plaintext password and saves it
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(newKrypter.password, salt, (err, hash) => {
        if (err) throw err;
        newKrypter.password = hash; // encrypted password
        newKrypter
          .save()
          .then(krypter => res.json(krypter))
          .catch(err => console.log(err));
      })
    });

I tried to assign a unique 6 digit id to each user during registration using the function 'assignKrypterID()'. But the following error is obtained:

This is my schema:

const KrypterSchema = new Schema({
  handle: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  krypter_id: {
    type: String,
    required: true
  }
});

Can't this be achieved using recursion? Or is recursion a bad move here?

Help me how to modify this to find whether the randomly generated Id is alrady assigned to an object.


问:
what exactly is a token, in relation to parsing
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

```<code>bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}
</code>```

答: A token is the smallest unit of a programming language that has a meaning. A parenthesis (, a name foo, an integer 123, are all tokens. Reducing a text to a series of tokens is generally the first step of parsing it.

ContentLicense: CC BY-SA 3.0

Body:
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is.  one of my function/operations is to check to see if there are more tokens to produce

bool Parser::hasMoreTokens()

how exactly do i go about this, please help

SO!

I am opening a text file with text in it, all words are lowercased.  How do i go about checking to see if it hasmoretokens?

This is what i have

bool Parser::hasMoreTokens() {

while(source.peek()!=NULL){
    return true;
}
    return false;
}


问:
Mysql Dump Empty File
I tried to follow the many guides online to create a script that makes a backup of SQL database, but unfortunately I find myself with an error in the SQL command because I go to create a file is where I say, and as I say, but it is completely empty ..!
The syntax that use is as follows:

```<code>exec('mysqldump –opt -user=' . $db_user . ' -password=' . $db_pass . ' --host=' . $db_host . ' ' . $db_nome . ' > ' . $db_filename);
</code>```

and this:

```<code>exec('mysqldump --user=' . $db_user . ' --password=' . $db_pass . ' --host=' . $db_host . ' ' . $db_nome . ' > ' . $db_filename);
echo 'mysqldump –opt -user=' . $db_user . ' -password=' . $db_pass . ' --host=' . $db_host . ' ' . $db_nome . ' > ' . $db_filename;
</code>```

You see mistakes?

答:
You have to specify full path to mysqldump:

```<code>exec('/usr/bin/mysqldump –opt -user=' . $db_user . ' -password=' . $db_pass . ' --host=' . $db_host . ' ' . $db_nome . ' > ' . $db_filename);
</code>```

Title: Mysql Dump Empty File

Body:
I tried to follow the many guides online to create a script that makes a backup of SQL database, but unfortunately I find myself with an error in the SQL command because I go to create a file is where I say, and as I say, but it is completely empty ..!
The syntax that use is as follows:

exec('mysqldump –opt -user=' . $db_user . ' -password=' . $db_pass . ' --host=' . $db_host . ' ' . $db_nome . ' > ' . $db_filename);

and this:

exec('mysqldump --user=' . $db_user . ' --password=' . $db_pass . ' --host=' . $db_host . ' ' . $db_nome . ' > ' . $db_filename);
echo 'mysqldump –opt -user=' . $db_user . ' -password=' . $db_pass . ' --host=' . $db_host . ' ' . $db_nome . ' > ' . $db_filename;

You see mistakes?

Body:
You have to specify full path to mysqldump:

exec('/usr/bin/mysqldump –opt -user=' . $db_user . ' -password=' . $db_pass . ' --host=' . $db_host . ' ' . $db_nome . ' > ' . $db_filename);


问:
How to remove TextInputLayout drawable padding?
I am using ExitText inside TextInputLayout and have enable ``

```<code>app:passwordToggleEnabled="true"
</code>```

And getting Toggle view as below

I want to remove Right Padding of the toggle but somehow not able to.
I have all set everything 0dp, but no success.

```<code><com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true"
    android:layout_margin="0dp"
    android:padding="0dp">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="0dp"
        android:layout_margin="0dp"
        android:drawablePadding="0dp"/>

</com.google.android.material.textfield.TextInputLayout>
</code>```

There are some naive solutions like setting negative margin, but as I don't know the size of padding I can't do that either. Any suggestion?

答:
You can also use this code</p>

```<code><android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleEnabled="true">

    <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:inputType="textPassword"/>

</android.support.design.widget.TextInputLayout>
</code>```

Body:
I am using ExitText inside TextInputLayout and have enable ``

app:passwordToggleEnabled="true"

And getting Toggle view as below

I want to remove Right Padding of the toggle but somehow not able to.
I have all set everything 0dp, but no success.

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true"
    android:layout_margin="0dp"
    android:padding="0dp">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="0dp"
        android:layout_margin="0dp"
        android:drawablePadding="0dp"/>

</com.google.android.material.textfield.TextInputLayout>

There are some naive solutions like setting negative margin, but as I don't know the size of padding I can't do that either. Any suggestion?

Body:
You can also use this code

<android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleEnabled="true">

    <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:inputType="textPassword"/>

</android.support.design.widget.TextInputLayout>


问:
Find & Replace text within an xml file
I am trying to create a batch-file which will install an agent in a silent manner. Once the agent has installed I will need to navigate into the agent directory and edit a file called agent.xml.

The agent.xml file looks like the below:

```<code><?xml version="1.0" encoding="utf-16"?>
<Details xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Proxy />
<ProxyDomain />
<ProxyUsername />
<ProxyPassword />
<UseNewHub>true</UseNewHub>
<Thumbprint />
<Url>https://localhost/api/</Url>
<U>agent</U>
<P />
<E1>gr\atga\rgr\zergeesfsdgfsg245325252sgsgsdfgssdgs3535353</E1>
</Details>
</code>```

I am trying to replace the

```<code><Thumbprint />
</code>```

line with this:

```<code><Thumbprint>213GARFASF131231FAAAF2</Thumbprint>
</code>```

Can anyone help me implement a command that will find and replace that thumbprint line?

答:
First of all, this link has numerous methods of doing this flexibly.

If you want a quick method, assuming that what you want to replace will always be in the form of <Thumbprint />, and there's no ! in your file, you can use this:

```<code>setlocal enabledelayedexpansion
for /f "delims=" %%a in (input.xml) do (
    set line=%%a
    echo !line:Thumbprint /=Thumbprint^>213GARFASF131231FAAF2^</Thumbprint^!>>output.xml
)
</code>```

Replacing input.xml and output.xml.

Title: Find & Replace text within an xml file

Body:
I am trying to create a batch-file which will install an agent in a silent manner. Once the agent has installed I will need to navigate into the agent directory and edit a file called agent.xml.

The agent.xml file looks like the below:

<?xml version="1.0" encoding="utf-16"?>

<Proxy />
<ProxyDomain />
<ProxyUsername />
<ProxyPassword />
<UseNewHub>true</UseNewHub>
<Thumbprint />
<Url>https://localhost/api/</Url>
agent

<E1>gr\atga\rgr\zergeesfsdgfsg245325252sgsgsdfgssdgs3535353</E1>

I am trying to replace the

<Thumbprint />

line with this:

<Thumbprint>213GARFASF131231FAAAF2</Thumbprint>

Can anyone help me implement a command that will find and replace that thumbprint line?

Body:
First of all, this link has numerous methods of doing this flexibly.

If you want a quick method, assuming that what you want to replace will always be in the form of <Thumbprint />, and there's no ! in your file, you can use this:

setlocal enabledelayedexpansion
for /f "delims=" %%a in (input.xml) do (
    set line=%%a
    echo !line:Thumbprint /=Thumbprint^>213GARFASF131231FAAF2^</Thumbprint^!>>output.xml
)

Replacing input.xml and output.xml.


问:
How can I make several random weights for portfolios?
I am learning investment portfolios, but I need to know how I can generate many random weights for portfolios.

To achieve multiply them with the returns of several shares and also obtain volatility and return for each different weights. The weights must add 1 in total, to achieve the results shown in the images.

Here, for example, I generate a weight for the actions of my portfolio, but I need to generate more weights randomly, to simulate more portfolios and achieve the results of the images.

```<code>import random
n=9
weights = [random.random() for _ in range(n)]
sum_weights = sum(weights)
weights = [w/sum_weights for w in weights]
</code>```

答:
You can use numpy broadcasting for easier computation

```<code>import numpy as np
import pandas as pd

# Set Seed for reproducibility
np.random.seed(0)

# Set your n

n = 9
# Randomize a Numpy Array with 100 x n array
rand_nos = np.random.rand(100, n)
</code>```

Now, to get the sum per row,

```<code>rand_nos.sum(axis=1)
</code>```

Now you have a 100 x n array. To broadcast array operations, you have to match the the column count in the left array to the row count of the right array. So to match, we use the .transpose() method of a numpy.ndarray. That will result into a n x 100 array. In order to bring it back to a 100 x n array, we just apply the .transpose() method on the resulting array. Code will look like so:

```<code>onehundred_by_n = rand_nos.transpose() / rand_nos.sum(axis=1) # This is a 100 x 1 array
n_by_onehundred = onehundred_by_n.transpose() # This is now a n x 100 array
</code>```

Once you have n_by_onehundred, it's easy to read it into a dataframe (since pandas.DataFrames are essentially numpy.ndarrays). Add a columns keyword argument and you're set with your randomized dataframe.

```<code>df = pd.DataFrame(
    n_by_onehundred,
    columns=[
    'AAPL weight', 'MSFT weight', 'XOM weight',
    'JNJ weight', 'JPM weight', 'AMZN weight',
    'GE weight', 'FB weight', 'T weight',
]
)
</code>```

Just for completeness, if you want to check that each row in df sums up to 1, just run:

```<code>df.sum(axis=1) # This sums each row
</code>```

You should get 100 1s representing each row

Body:
I am learning investment portfolios, but I need to know how I can generate many random weights for portfolios.

To achieve multiply them with the returns of several shares and also obtain volatility and return for each different weights. The weights must add 1 in total, to achieve the results shown in the images.

Here, for example, I generate a weight for the actions of my portfolio, but I need to generate more weights randomly, to simulate more portfolios and achieve the results of the images.

import random
n=9
weights = [random.random() for _ in range(n)]
sum_weights = sum(weights)
weights = [w/sum_weights for w in weights]

Body:
You can use numpy broadcasting for easier computation

import numpy as np
import pandas as pd

# Set Seed for reproducibility
np.random.seed(0)

# Set your n

n = 9
# Randomize a Numpy Array with 100 x n array
rand_nos = np.random.rand(100, n)

Now, to get the sum per row,

rand_nos.sum(axis=1)

Now you have a 100 x n array. To broadcast array operations, you have to match the the column count in the left array to the row count of the right array. So to match, we use the .transpose() method of a numpy.ndarray. That will result into a n x 100 array. In order to bring it back to a 100 x n array, we just apply the .transpose() method on the resulting array. Code will look like so:

onehundred_by_n = rand_nos.transpose() / rand_nos.sum(axis=1) # This is a 100 x 1 array
n_by_onehundred = onehundred_by_n.transpose() # This is now a n x 100 array

Once you have n_by_onehundred, it's easy to read it into a dataframe (since pandas.DataFrames are essentially numpy.ndarrays). Add a columns keyword argument and you're set with your randomized dataframe.

df = pd.DataFrame(
    n_by_onehundred,
    columns=[
    'AAPL weight', 'MSFT weight', 'XOM weight',
    'JNJ weight', 'JPM weight', 'AMZN weight',
    'GE weight', 'FB weight', 'T weight',
]
)

Just for completeness, if you want to check that each row in df sums up to 1, just run:

df.sum(axis=1) # This sums each row

You should get 100 1s representing each row


问:
Automating git pull process on dev/QA server on commit
I have my rails application hosted on github. Whenever a commit happens on 'dev' branch I would like to do git pull on the dev box and also invoke '/etc/init.d/apache2 restart' command. Is this something I can do with Capistrano deployment or I can write some kind of custom shell script and somehow hook in my rails app to call that shell script?</p>

答:
You will need a post-receive hook on the git server that causes a git pull on the dev box. A quick DAFS for "git deploy with post-receive" found quite a few resources, like http://ryanflorence.com/deploying-websites-with-a-tiny-git-hook

I would personally prefer using a build system like Jenkins for this as it gives you more control and visibility. We have set up a continuous deployment system using Jenkins and github post-receive hooks with relatively little fuss. Another advantage is that you can run your tests before automatically deploying (if they pass) by chaining jobs.


问:
Entering additional rows in dataframe as mid points between values of adjacent existing rows
Say you have the following time series dataset in r:

```<code>n <- 3
set.seed(1)
df <- data.frame(Day = rep("Mon", n),
           Time = 1:n,
           Temper = round(rnorm(n, 4, 2), 0))
print(df)

  Day Time Temper
  Mon    1      3
  Mon    2      4
  Mon    3      2
</code>```

Now say you wish to add midpoints between adjacent existing values as extra rows in the data frame. For example, say you wish to add the exact midpoint between every pair of adjacent values, to produce the following new dataframe:

```<code>  Day Time Temper
  Mon    1      3
  Mon  1.5    3.5
  Mon    2      4
  Mon  2.5      3
  Mon    3      2
</code>```

What would be some efficient R code that could accomplish this on much larger datasets?

It would be great if this code could also populate the dataframe with values which are not just the exact midpoints, for example the 'one-third' datapoint:

```<code>  Day Time Temper
  Mon    1      3
  Mon 1.33   3.33
  Mon    2      4
  Mon 2.33   3.33
  Mon    3      2
</code>```

答:
Here is an idea using dplyr and purrr. We first rbind rows of NA and we then fill those NAs, i.e.

```<code>library(tidyverse)

df %>%
  group_by(Day) %>%
  map_dfr(rbind, NA) %>%
  fill(Day) %>%
  mutate_at(vars(c(2, 3)), funs(replace(., is.na(.), (1/2) * (lag(.) + lead(.))[is.na(.)] ))) %>%
  na.omit()
</code>```

which gives,

```<code># A tibble: 5 x 3
    Day  Time Temper
  <int> <dbl>  <dbl>
1     1   1      3
2     1   1.5    3.5
3     1   2      4
4     1   2.5    3
5     1   3      2
</code>```

Body:
Say you have the following time series dataset in r:

n <- 3
set.seed(1)
df <- data.frame(Day = rep("Mon", n),
           Time = 1:n,
           Temper = round(rnorm(n, 4, 2), 0))
print(df)

  Day Time Temper
  Mon    1      3
  Mon    2      4
  Mon    3      2

Now say you wish to add midpoints between adjacent existing values as extra rows in the data frame. For example, say you wish to add the exact midpoint between every pair of adjacent values, to produce the following new dataframe:

  Day Time Temper
  Mon    1      3
  Mon  1.5    3.5
  Mon    2      4
  Mon  2.5      3
  Mon    3      2

What would be some efficient R code that could accomplish this on much larger datasets?

It would be great if this code could also populate the dataframe with values which are not just the exact midpoints, for example the 'one-third' datapoint:

  Day Time Temper
  Mon    1      3
  Mon 1.33   3.33
  Mon    2      4
  Mon 2.33   3.33
  Mon    3      2

Body:
Here is an idea using dplyr and purrr. We first rbind rows of NA and we then fill those NAs, i.e.

library(tidyverse)

df %>%
  group_by(Day) %>%
  map_dfr(rbind, NA) %>%
  fill(Day) %>%
  mutate_at(vars(c(2, 3)), funs(replace(., is.na(.), (1/2) * (lag(.) + lead(.))[is.na(.)] ))) %>%
  na.omit()

which gives,

# A tibble: 5 x 3
    Day  Time Temper
  <int> <dbl>  <dbl>
1     1   1      3
2     1   1.5    3.5
3     1   2      4
4     1   2.5    3
5     1   3      2


问:
Exclude k8s nodes from grafana monitoring
We have a kubernetes cluster made up of 5 nodes.  2 of the nodes are only used for KIAM and the other 3 are for container deployments.

I have prometheus and grafana deployed and configured and I need to configure monitoring for CPU, memory and pod usage. However I want to totally exclude the nodes hosting KIAM from any stats or alert thresholds.

The only thing I can see being returned by prometheus that can identify the nodes i need is label_workload="gp" from the kube_node_labels metric.  What I don't know how to do is to get grafana to only use these nodes in it's calculations.

Perhaps it's possible to have some sort of query join or subselect to identify the node names to include??

I'd appreciate any help on this!!!

答:
I believe the node_uname_info metrics is a better metric to get all your node infos. So I will explain using that metric.

You have two options:

Option 1: You hard-code the nodenames into your Grafana dashboard. Your query should look something like this node_uname_info{nodename=~"node1|node2|node3"} then. node1-3 are the nodes which you want to have the metrics for.

Option 2: You create a variable and allow the user to select the nodes. Let's say the variable name is $nodes and the query should be label_values(node_uname_info, nodename). It should be allowed to select multiple values. Next in your query you can then do node_uname_info{nodename=~"$nodes"} to only show metrics for selected nodes.


问:
Comparing different length VARCHAR2 in Oracle SQL Developer
A new table was added where I work to process payments through a new system. The problem is it contains only some information, so I need to match it up with another table to get full information.
Basically, the column that could match the transactions together is of type varchar2(20) in the old table, but it's varchar2(80) in the new table.

The new table (let's call it Z) can hold anything from an 11 digit reference to a 30-40 character reference (can be digits/letters/some special characters). What I am trying to achieve is match it to the old table (let's call it X) which only contains 11 digit reference numbers.

So, let's say Z table looks like:

```<code>TransactionType Reference
Purchase        abcd-efgh-1923-aa22
Refund          12345678910
</code>```

And table X looks like:

```<code>Purchase Reference
Shoes    12345678910
Jacket   10987654321
</code>```

Realistically, I would want to find for a refund and a given reference, what the purchase was.

I am quite new to SQL and I've been trying to see what cast/convert might do, but I'm a bit lost here as I've tried both cast and convert.

I tried:

```<code>select purchase from x, z
where x.reference=z.reference;

select purchase from x,z
where to_number(x.reference)=to_number(z.reference);

select purchase from x,z
where x.reference=cast(z.reference as varchar2(20)); --- and viceversa, casting x to varchar2(80)
</code>```

There is no output, although when I check for let's say refunds on a day and then the purchases on the same day, there will be some references that match. So let's say, for a day I would have expected 5 rows being returned, yet no rows are returned.

答:
The TO_CHAR function should cover you here:

```<code>SELECT x.Purchase, x.Reference
FROM X x
INNER JOIN Z z
    ON TO_CHAR(x.Reference) = TO_CHAR(z.Reference)
WHERE z.TransactionType = 'Refund';
</code>```

If you want to restrict to a certain reference, then just include that requirement in the WHERE clause.

Note that I refactored your joins to use a modern explicit inner join.  This is the preferred way of writing SQL code.

Body:
A new table was added where I work to process payments through a new system. The problem is it contains only some information, so I need to match it up with another table to get full information.
Basically, the column that could match the transactions together is of type varchar2(20) in the old table, but it's varchar2(80) in the new table.

The new table (let's call it Z) can hold anything from an 11 digit reference to a 30-40 character reference (can be digits/letters/some special characters). What I am trying to achieve is match it to the old table (let's call it X) which only contains 11 digit reference numbers.

So, let's say Z table looks like:

TransactionType Reference
Purchase        abcd-efgh-1923-aa22
Refund          12345678910

And table X looks like:

Purchase Reference
Shoes    12345678910
Jacket   10987654321

Realistically, I would want to find for a refund and a given reference, what the purchase was.

I am quite new to SQL and I've been trying to see what cast/convert might do, but I'm a bit lost here as I've tried both cast and convert.

I tried:

select purchase from x, z
where x.reference=z.reference;

select purchase from x,z
where to_number(x.reference)=to_number(z.reference);

select purchase from x,z
where x.reference=cast(z.reference as varchar2(20)); --- and viceversa, casting x to varchar2(80)

There is no output, although when I check for let's say refunds on a day and then the purchases on the same day, there will be some references that match. So let's say, for a day I would have expected 5 rows being returned, yet no rows are returned.

Body:
The TO_CHAR function should cover you here:

SELECT x.Purchase, x.Reference
FROM X x
INNER JOIN Z z
    ON TO_CHAR(x.Reference) = TO_CHAR(z.Reference)
WHERE z.TransactionType = 'Refund';

If you want to restrict to a certain reference, then just include that requirement in the WHERE clause.

Note that I refactored your joins to use a modern explicit inner join.  This is the preferred way of writing SQL code.


问:
Flash animation in OpenLayers is not continously rendered
I am using Open Layers 5 to show a flashing animation for points in a map.
The animation should restart after a random, limited amount of time. In order to do this, I added a timeout function that calls the animation function after about 3 seconds.

The code is similar to the open layers example:
https://openlayers.org/en/latest/examples/feature-animation.html
The only difference is that I do not add features in the interval, I set a timer for each feature that runs the animation.

The first time the feature is added I can see the animation, but afterwards it doesn't seem to be rendered anymore.
The animation shows only when dragging the map, so I'm guessing that the map isn't automatically rendered when it's running on the timeout thread, even though map.render is called.

答:
When a feature is added the map will automatically re-render so the flash function doesn't need to force an initial render.  If flash is to be called randomly you will need to force a render after setting the listener.</p>

```<code>var listenerKey = map.on('postcompose', animate);
map.render();
</code>```

Body:
When a feature is added the map will automatically re-render so the flash function doesn't need to force an initial render.  If flash is to be called randomly you will need to force a render after setting the listener.

var listenerKey = map.on('postcompose', animate);
map.render();


问:
How to make serialization run in parallel
guys,
If I have a tree structure, and I want to serialize the tree and sub nodes. how to do the serialization for each nodes in parallel.
If I assign each node with a independent task, the output data will be disordered.
Is there some pattern for concurrent serialization?

Edit: If the structure is not a tree, but a DAG? How to handle this structure? How to serialize DAG and make the serialization to be concurrent.

答:
Running parallel jobs on a DAG is what most build tools do to compile your software.  In a single-thread/process environment, the classic solution is to order the tasks using a topological sort and then process the jobs in that order.

In a multi-thread/process environment, however, you must make sure that a node's task is not processed before it's dependencies are finished.  This means that you have to maintain a queue with blocking workers.  You also have to maintain the invariant that nodes in the queue are ready (their dependencies are finished processing).

One possible implementation is to maintain a dependency counter for each node; when one of its dependencies is completed, decrease the counter.  If the counter reaches 0, insert the node in the queue.


问:
How to export smart PDF form data to an excel format without images?
I have a very large amount of PDF forms (with the same format) that I want to export to a filterable excel file. These forms contain images embedded throughout. When exporting with adobe standard, the .csv file obtained includes massive amounts of random characters as the 'image data'. Since I have so many pdf forms I obviously do not want to include this. When importing the files into excel, it generates massive columns and rows of random characters due to the image data

I've been writing a bit in VBA to try and exclude the columns of nonsense, but my code is too specific and too slow. I want a more efficient way to do this.

```<code>Sub OpenCSV()

Application.ScreenUpdating = False

Dim FilePath As String, rownumber As Integer, j As Integer

'Select The File

FilePath = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Select CSV file")

Open FilePath For Input As #1

rownumber = 0

' Loop continues until End Of File

Do Until EOF(1)

Line Input #1, LineFromFile

'Make an array from the file

LineItems = Split(LineFromFile, ",")

j = 0
    For i = 0 To 314

' This If statement removes the images (only works if report is in exact same format)

If i <> 86 And i <> 87 And i <> 88 And i <> 89 Then

Cells(1, 1).Offset(rownumber, j).Value = LineItems(i)

j = j + 1

End If

Next i

rownumber = rownumber + 1
Loop

Close #1

End Sub
</code>```

This runs slowly and usually results in an error if there is a missing form entry etc. I am open to improving this code, or abandoning it if there is some sort of software solution existing.

答: Using VBA, you can extract only the form information and not the images. See example here: https://github.com/pdftables/vba-pdftables-api/blob/master/pdftables.vba</p>

Body:
I have a very large amount of PDF forms (with the same format) that I want to export to a filterable excel file. These forms contain images embedded throughout. When exporting with adobe standard, the .csv file obtained includes massive amounts of random characters as the 'image data'. Since I have so many pdf forms I obviously do not want to include this. When importing the files into excel, it generates massive columns and rows of random characters due to the image data

I've been writing a bit in VBA to try and exclude the columns of nonsense, but my code is too specific and too slow. I want a more efficient way to do this.

Sub OpenCSV()

Application.ScreenUpdating = False

Dim FilePath As String, rownumber As Integer, j As Integer

'Select The File

FilePath = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Select CSV file")

Open FilePath For Input As #1

rownumber = 0

' Loop continues until End Of File

Do Until EOF(1)

Line Input #1, LineFromFile

'Make an array from the file

LineItems = Split(LineFromFile, ",")

j = 0
    For i = 0 To 314

' This If statement removes the images (only works if report is in exact same format)

If i <> 86 And i <> 87 And i <> 88 And i <> 89 Then

Cells(1, 1).Offset(rownumber, j).Value = LineItems(i)

j = j + 1

End If

Next i

rownumber = rownumber + 1
Loop

Close #1

End Sub

This runs slowly and usually results in an error if there is a missing form entry etc. I am open to improving this code, or abandoning it if there is some sort of software solution existing.


问:
Convert curl command into RestTemplate
I have the following curl expression:

```<code>curl --data 'api_key=API_Key' --data-urlencode 'event=[{"user_id":"12345", "event_type":"buy_song"}]' https://someapi
</code>```

which should be converted into RestTemplate.postForEntity call. I do conversion this way:

```<code>HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("api_key", "API_Key");
params.add("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));

// send
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
ResponseEntity<String> response = restTemplate.postForEntity("https://someapi", request, String.class);
</code>```

Server returns 400 Bad request

I confirm that Jackson's objectmapper serializes the object correctly objectMapper.writeValueAsString(Collections.singletonList(e))

I suspect that I cannot correctly handle the mix of --data and --data-urlencode from example curl in RestTemplate.

Could you please suggest what am I doing wrong?

答:
Works fine for me:

Here is the code with client and request, please ignore request signatures

```<code>curl -X GET \
  http://localhost:8080/article/so \
  -H 'cache-control: no-cache' \
  -d 'api_key=API_Key&event=%5B%7B%22user_id%22%3A%2212345%22%2C%20%22event_type%22%3A%22buy_song%22%7D%5D'
</code>```

controller:
First request will trigger your code:

```<code>// This is just to trigger, you can ignore it.

    @RequestMapping(value = "/article/so", method = RequestMethod.GET)
    public void addArticle1() throws UnsupportedEncodingException, JsonProcessingException {
        articleServiceImpl.test();
    }
</code>```

Above request will go to service layer where code is same as of yours.

```<code>
    public void test() throws JsonProcessingException, UnsupportedEncodingException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        Event e = new Event();
        e.setEvent_type("buy_song");
        e.setUser_id("12345");

        params.add("api_key", "API_Key");
        String encode = URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8");
        params.add("event", encode);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
        ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/article/so", request, String.class);
        System.out.println(response);//<200,[Content-Length:"0", Date:"Fri, 31 May 2019 09:26:24 GMT"]>
    }
</code>```

Then the controller again, just to check whether controller accepts String object or Event object from the caller. Here Event is passed as URLEncodedString, which I am getting here as output.

```<code>    @RequestMapping(value = "/article/so", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void addArticle2(@RequestParam String api_key,@RequestParam String event) {
        System.out.println(api_key); // API_Key
        System.out.println(event); // %5B%7B%22user_id%22%3A%2212345%22%2C%22event_type%22%3A%22buy_song%22%7D%5D
    }

</code>```

Title: Convert curl command into RestTemplate

Body:
I have the following curl expression:

curl --data 'api_key=API_Key' --data-urlencode 'event=[{"user_id":"12345", "event_type":"buy_song"}]' https://someapi

which should be converted into RestTemplate.postForEntity call. I do conversion this way:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("api_key", "API_Key");
params.add("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));

// send
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
ResponseEntity<String> response = restTemplate.postForEntity("https://someapi", request, String.class);

Server returns 400 Bad request

I confirm that Jackson's objectmapper serializes the object correctly objectMapper.writeValueAsString(Collections.singletonList(e))

I suspect that I cannot correctly handle the mix of --data and --data-urlencode from example curl in RestTemplate.

Could you please suggest what am I doing wrong?

Body:
Works fine for me:

Here is the code with client and request, please ignore request signatures

curl -X GET \
  http://localhost:8080/article/so \
  -H 'cache-control: no-cache' \
  -d 'api_key=API_Key&event=%5B%7B%22user_id%22%3A%2212345%22%2C%20%22event_type%22%3A%22buy_song%22%7D%5D'

controller:
First request will trigger your code:

// This is just to trigger, you can ignore it.

    @RequestMapping(value = "/article/so", method = RequestMethod.GET)
    public void addArticle1() throws UnsupportedEncodingException, JsonProcessingException {
        articleServiceImpl.test();
    }

Above request will go to service layer where code is same as of yours.

    public void test() throws JsonProcessingException, UnsupportedEncodingException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        Event e = new Event();
        e.setEvent_type("buy_song");
        e.setUser_id("12345");

        params.add("api_key", "API_Key");
        String encode = URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8");
        params.add("event", encode);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
        ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/article/so", request, String.class);
        System.out.println(response);//<200,[Content-Length:"0", Date:"Fri, 31 May 2019 09:26:24 GMT"]>
    }

Then the controller again, just to check whether controller accepts String object or Event object from the caller. Here Event is passed as URLEncodedString, which I am getting here as output.

    @RequestMapping(value = "/article/so", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void addArticle2(@RequestParam String api_key,@RequestParam String event) {
        System.out.println(api_key); // API_Key
        System.out.println(event); // %5B%7B%22user_id%22%3A%2212345%22%2C%22event_type%22%3A%22buy_song%22%7D%5D
    }


问:
android UI elements' visibilty not changing
I've been writing an app for FTP file transfer and i need to hide a few UI elements and make a few visible on a button click.The visibility settings remain the same as when the app starts.They do not change.Any idea why?

here are my elements:

ip= (EditText) findViewById(R.id.ipadd);
portt=(EditText) findViewById(R.id.port);
conn= (Button) findViewById(R.id.connectb);
pb= (ProgressBar) findViewById(R.id.pb);
trans=(TextView) findViewById(R.id.transfer);
```

<p>here are the settings at the starting of the app(onCreate):</p>

<pre class="lang-java prettyprint-override"><code>pb.setVisibility(View.INVISIBLE);
trans.setVisibility(View.INVISIBLE);
ip.setVisibility(View.VISIBLE);
portt.setVisibility(View.VISIBLE);
conn.setVisibility(View.VISIBLE);
</code>```

These settings are applied.
And this is the code for the function when the button is clicked:

Ftp ftp;
errflag=false;
ip.setVisibility(View.INVISIBLE);
portt.setVisibility(View.INVISIBLE);
conn.setVisibility(View.INVISIBLE);
trans.setVisibility(View.VISIBLE);
pb.setVisibility(View.VISIBLE);
while(!errflag) {
    try{
      ftp=new Ftp();
      String result = ftp.execute("hi").get();
      if(result.equals("Finished"))
          break;
    } catch(Exception e){
        e.printStackTrace();
    }
}
```

<p>Everything in the code works fine except for the visibility of these elements.
The control enters the while loop and exits properly but doesn't change the visibility of the elements.And yes the function is invoked on button click,so it is in the UI thread,but i've still tried wrapping up the code in runOnUIThread method which doesn't seem to make any changes.
Any comments will be appreciated.</p>

<p>Asynctask code:</p>

```public class Ftp extends AsyncTask<String ,String,String>
{

    protected String doInBackground(String... urls)
    {
        try
        {
            String ipadd= ip.getText().toString();
            int port =Integer.parseInt(portt.getText().toString());
            Socket socket=new Socket(ipadd,port);
            //Button conn=(Button) findViewById(R.id.connectb);

            //conn.setEnabled(false);
            BufferedReader br= new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedOutputStream bo= new BufferedOutputStream(socket.getOutputStream());
            PrintWriter pw= new PrintWriter(bo,true);
            String file=br.readLine();
            if(file.equals("Finished"))
                return file;
            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
            File f= new File(path, "/" + file);
            byte[] buff= new byte[1024];
            int len;
                pw.println("done");
                DataInputStream is= new DataInputStream(socket.getInputStream());
                FileOutputStream fos= new FileOutputStream(f);

            Thread.sleep(1);
            publishProgress(file);
                while((len=is.read(buff))!=-1)
                {

                    fos.write(buff,0,len);

                }
            Log.i("status","Finsihed");

           /* else
            {
                Toast.makeText(MainActivity.this,"File already exists!",Toast.LENGTH_LONG).show();
            }*/
        }catch(NumberFormatException nfe)
        {
            errflag=true;
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            nfe.printStackTrace();

        }
        catch(java.net.UnknownHostException un)
        {
            errflag=true;
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            //Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
            un.printStackTrace();
        }
        catch(java.net.NoRouteToHostException no)
        {errflag=true;

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"There is no active server at the specified IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            no.printStackTrace();
        }
        catch(Exception e)

        {
            errflag=true;
            Log.i("this","error");
            e.printStackTrace();
        }
        return "Not Yet";
    }
    protected void onProgressUpdate(String... para)
    {
        super.onProgressUpdate(para);
        trans.setText("Transfering file: "+para[0]);

    }

}`
```

<p>Then i made a new thread:</p>

```public class MyThread extends Thread
{
    public void run() {
        while (!errflag) {
            try {
                Ftp ftp = new Ftp();
                String res = ftp.execute("hi").get();
                if (res.equals("Finished"))
                    break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
```

<p>and changed the function code to:</p>

```errflag=false;
            ip.setVisibility(View.INVISIBLE);
            portt.setVisibility(View.INVISIBLE);
            conn.setVisibility(View.INVISIBLE);
            trans.setVisibility(View.VISIBLE);
            pb.setVisibility(View.VISIBLE);

        /*ftp=new Ftp();
        String result = ftp.execute("hi").get();
        if(result.equals("Finished"))
            break;*/

        try {
            MyThread t = new MyThread();
            t.start();
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
```

答:
Please try to run only following in main thread and see if it helps.</p>

```<code>ip.setVisibility(View.INVISIBLE);
portt.setVisibility(View.INVISIBLE);
conn.setVisibility(View.INVISIBLE);
trans.setVisibility(View.VISIBLE);
pb.setVisibility(View.VISIBLE);
</code>```

Body:
I've been writing an app for FTP file transfer and i need to hide a few UI elements and make a few visible on a button click.The visibility settings remain the same as when the app starts.They do not change.Any idea why?

here are my elements:

ip= (EditText) findViewById(R.id.ipadd);
portt=(EditText) findViewById(R.id.port);
conn= (Button) findViewById(R.id.connectb);
pb= (ProgressBar) findViewById(R.id.pb);
trans=(TextView) findViewById(R.id.transfer);

here are the settings at the starting of the app(onCreate):

pb.setVisibility(View.INVISIBLE);
trans.setVisibility(View.INVISIBLE);
ip.setVisibility(View.VISIBLE);
portt.setVisibility(View.VISIBLE);
conn.setVisibility(View.VISIBLE);

These settings are applied.
And this is the code for the function when the button is clicked:

Ftp ftp;
errflag=false;
ip.setVisibility(View.INVISIBLE);
portt.setVisibility(View.INVISIBLE);
conn.setVisibility(View.INVISIBLE);
trans.setVisibility(View.VISIBLE);
pb.setVisibility(View.VISIBLE);
while(!errflag) {
    try{
      ftp=new Ftp();
      String result = ftp.execute("hi").get();
      if(result.equals("Finished"))
          break;
    } catch(Exception e){
        e.printStackTrace();
    }
}

Everything in the code works fine except for the visibility of these elements.
The control enters the while loop and exits properly but doesn't change the visibility of the elements.And yes the function is invoked on button click,so it is in the UI thread,but i've still tried wrapping up the code in runOnUIThread method which doesn't seem to make any changes.
Any comments will be appreciated.

Asynctask code:

public class Ftp extends AsyncTask<String ,String,String>
{

    protected String doInBackground(String... urls)
    {
        try
        {
            String ipadd= ip.getText().toString();
            int port =Integer.parseInt(portt.getText().toString());
            Socket socket=new Socket(ipadd,port);
            //Button conn=(Button) findViewById(R.id.connectb);

            //conn.setEnabled(false);
            BufferedReader br= new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedOutputStream bo= new BufferedOutputStream(socket.getOutputStream());
            PrintWriter pw= new PrintWriter(bo,true);
            String file=br.readLine();
            if(file.equals("Finished"))
                return file;
            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
            File f= new File(path, "/" + file);
            byte[] buff= new byte[1024];
            int len;
                pw.println("done");
                DataInputStream is= new DataInputStream(socket.getInputStream());
                FileOutputStream fos= new FileOutputStream(f);

            Thread.sleep(1);
            publishProgress(file);
                while((len=is.read(buff))!=-1)
                {

                    fos.write(buff,0,len);

                }
            Log.i("status","Finsihed");

           /* else
            {
                Toast.makeText(MainActivity.this,"File already exists!",Toast.LENGTH_LONG).show();
            }*/
        }catch(NumberFormatException nfe)
        {
            errflag=true;
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            nfe.printStackTrace();

        }
        catch(java.net.UnknownHostException un)
        {
            errflag=true;
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            //Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
            un.printStackTrace();
        }
        catch(java.net.NoRouteToHostException no)
        {errflag=true;

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this,"There is no active server at the specified IP and port!",Toast.LENGTH_LONG).show();
                }
            });
            no.printStackTrace();
        }
        catch(Exception e)

        {
            errflag=true;
            Log.i("this","error");
            e.printStackTrace();
        }
        return "Not Yet";
    }
    protected void onProgressUpdate(String... para)
    {
        super.onProgressUpdate(para);
        trans.setText("Transfering file: "+para[0]);

    }

}`

Then i made a new thread:

public class MyThread extends Thread
{
    public void run() {
        while (!errflag) {
            try {
                Ftp ftp = new Ftp();
                String res = ftp.execute("hi").get();
                if (res.equals("Finished"))
                    break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

and changed the function code to:

errflag=false;
            ip.setVisibility(View.INVISIBLE);
            portt.setVisibility(View.INVISIBLE);
            conn.setVisibility(View.INVISIBLE);
            trans.setVisibility(View.VISIBLE);
            pb.setVisibility(View.VISIBLE);

        /*ftp=new Ftp();
        String result = ftp.execute("hi").get();
        if(result.equals("Finished"))
            break;*/

        try {
            MyThread t = new MyThread();
            t.start();
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }

Body:
Please try to run only following in main thread and see if it helps.

ip.setVisibility(View.INVISIBLE);
portt.setVisibility(View.INVISIBLE);
conn.setVisibility(View.INVISIBLE);
trans.setVisibility(View.VISIBLE);
pb.setVisibility(View.VISIBLE);


问:
splitting long long
How could one "split" i.e. long long type, so that first part of it is in var of type long and second part is also in var of type long.

```<code>long long long_type = 0xaaaabbbbccccdddd;
</code>```

and in first int I would like to have first half(doesn't matter from what side) of the long_type var and in second var int second half.

答:
```<code>long a = long_type;
long b = (static_cast<unsigned long long>(long_type) >> 32);
</code>```

Title: splitting long long

Body:
How could one "split" i.e. long long type, so that first part of it is in var of type long and second part is also in var of type long.

long long long_type = 0xaaaabbbbccccdddd;

and in first int I would like to have first half(doesn't matter from what side) of the long_type var and in second var int second half.


问:
make a button to scroll horizontally in div
I have a website where I have a div with images in it, set to overflow:auto; white-space: nowrap; So you can scroll horizontally in the div to see all the images in it.

Can I make two buttons (left and right) to scroll this div horizontally? I ask this because when I have a touchscreen or trackpad, I can scroll in the div but when I am on a desktop with only a mouse there is no option to scroll the div. And I hear you thinking just use the scrollbar but I have hidden those using CSS because they look different on different computers and browsers and were just a complete pain and didn't look clean enough for me. Here is my site (I made a page where I explain the problem again).

I have watched for carousel plugins but want to know if there's a way with CSS.

.blackbackgroundscroll {
   background: #fff;
   padding: 8px 8px 8px 8px;
   margin: 12px 0px 5px 0px;
   box-shadow: 0 0px 0px 0 rgba(0,0,0,0.0);
   border: 1px solid #dadce0;
   border-top-left-radius: 2px;
   border-top-right-radius: 2px;
   border-bottom-right-radius: 2px;
   border-bottom-left-radius: 2px;
   overflow: auto;
   white-space: nowrap;
   -webkit-overflow-scrolling: touch;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="blackbackgroundscroll">

  <img src="https://tuberadar.nl/wp-content/uploads/PAUW-thumbnail.png" alt="" width="210" height="119" class="alignleft size-full wp-image-16930" />

</div></code>```

I have no idea where to start, because I also have the feeling this is going to need some JavaScript and I have no experience with JS.

答:
You can scroll using Element.scrollLeft property to which you can
  provide the amount to scroll as an integer value.

Here is a basic example:
JavaScript + CSS + HTML

    const buttonRight = document.getElementById('slideRight');
    const buttonLeft = document.getElementById('slideLeft');

    buttonRight.onclick = function () {
      document.getElementById('container').scrollLeft += 20;
    };
    buttonLeft.onclick = function () {
      document.getElementById('container').scrollLeft -= 20;
    };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    #container {
      width: 145px;
      height: 100px;
      border: 1px solid #ccc;
      overflow-x: scroll;
    }

    #content {
      width: 250px;
      background-color: #ccc;
    }</code>```

Click the buttons to slide horizontally!

    <button id="slideLeft" type="button">Slide left</button>
    <button id="slideRight" type="button">Slide right</button>```

Body:
I have a website where I have a div with images in it, set to overflow:auto; white-space: nowrap; So you can scroll horizontally in the div to see all the images in it.

Can I make two buttons (left and right) to scroll this div horizontally? I ask this because when I have a touchscreen or trackpad, I can scroll in the div but when I am on a desktop with only a mouse there is no option to scroll the div. And I hear you thinking just use the scrollbar but I have hidden those using CSS because they look different on different computers and browsers and were just a complete pain and didn't look clean enough for me. Here is my site (I made a page where I explain the problem again).

I have watched for carousel plugins but want to know if there's a way with CSS.

.blackbackgroundscroll {
   background: #fff;
   padding: 8px 8px 8px 8px;
   margin: 12px 0px 5px 0px;
   box-shadow: 0 0px 0px 0 rgba(0,0,0,0.0);
   border: 1px solid #dadce0;
   border-top-left-radius: 2px;
   border-top-right-radius: 2px;
   border-bottom-right-radius: 2px;
   border-bottom-left-radius: 2px;
   overflow: auto;
   white-space: nowrap;
   -webkit-overflow-scrolling: touch;
 }

I have no idea where to start, because I also have the feeling this is going to need some JavaScript and I have no experience with JS.

Body:
You can scroll using Element.scrollLeft property to which you can
  provide the amount to scroll as an integer value.

Here is a basic example:
JavaScript + CSS + HTML

    const buttonRight = document.getElementById('slideRight');
    const buttonLeft = document.getElementById('slideLeft');

    buttonRight.onclick = function () {
      document.getElementById('container').scrollLeft += 20;
    };
    buttonLeft.onclick = function () {
      document.getElementById('container').scrollLeft -= 20;
    };

    #container {
      width: 145px;
      height: 100px;
      border: 1px solid #ccc;
      overflow-x: scroll;
    }

    #content {
      width: 250px;
      background-color: #ccc;
    }

    <div id="container">
      <div id="content">Click the buttons to slide horizontally!</div>
    </div>
    <button id="slideLeft" type="button">Slide left</button>
    <button id="slideRight" type="button">Slide right</button>


问:
Change the side menu's background image on mouseover using css
I have a side menu in my web page.

Now I need to highlight selected menu using some color or a background image on mouseover using css. Is it possible? If possible how?

答:
If you are just looking for a change of style on mouseover, use the :hover pseudo selector.</p>

```<code>a:hover {
   background-color: #FFF8B2;
}
</code>```

Body:
If you are just looking for a change of style on mouseover, use the :hover pseudo selector.

a:hover {
   background-color: #FFF8B2;
}


问:
how to identify query statement has a subquery in it?
Developing an C# project for SQL Training and giving different exercises based on training on each topic. One of the exercise is to write a query using Sub-Query.  which needs to be evaluated whether the user has used/implemented Sub query in the Query Statment.

Q: Write a sql query to show the SalesOrderID,LineTotal,average LineTotal from the Sales.SalesOrderDetail table using Sub query

```<code>Select SalesOrderID,LineTotal [LineTotal],
(Select AVG(LineTotal) from Sales.SalesOrderDetail) as [AverageLineTotal]
from Sales.SalesOrderDetail
</code>```

[AverageLineTotal] is an sub query.

Can we identify it by any means?? like execution plan Or SP to identify it has an sub query in the statement

Is there any way to identify it through execution Plans??

答:
If this is a c# project you can parse the query with regex to find if the query contains (select {any other text}).</p>

```<code>public static void Main()
{
    var sql = @"Select SalesOrderID,LineTotal [LineTotal],(Select AVG(LineTotal) from Sales.SalesOrderDetail) as [AverageLineTotal] from Sales.SalesOrderDetail";
    Console.WriteLine(DoesSqlContainSubquery(sql));
}

public bool DoesSqlContainSubquery(string sql)
{
    var regexTest = new Regex(@"\( *Select .*\)", RegexOptions.IgnoreCase);
    var containsSubquery = regexTest.IsMatch(sql);
    return containsSubquery;
}
</code>```

Body:
Developing an C# project for SQL Training and giving different exercises based on training on each topic. One of the exercise is to write a query using Sub-Query.  which needs to be evaluated whether the user has used/implemented Sub query in the Query Statment.

Q: Write a sql query to show the SalesOrderID,LineTotal,average LineTotal from the Sales.SalesOrderDetail table using Sub query

Select SalesOrderID,LineTotal [LineTotal],
(Select AVG(LineTotal) from Sales.SalesOrderDetail) as [AverageLineTotal]
from Sales.SalesOrderDetail

[AverageLineTotal] is an sub query.

Can we identify it by any means?? like execution plan Or SP to identify it has an sub query in the statement

Is there any way to identify it through execution Plans??

Body:
If this is a c# project you can parse the query with regex to find if the query contains (select {any other text}).

public static void Main()
{
    var sql = @"Select SalesOrderID,LineTotal [LineTotal],(Select AVG(LineTotal) from Sales.SalesOrderDetail) as [AverageLineTotal] from Sales.SalesOrderDetail";
    Console.WriteLine(DoesSqlContainSubquery(sql));
}

public bool DoesSqlContainSubquery(string sql)
{
    var regexTest = new Regex(@"\( *Select .*\)", RegexOptions.IgnoreCase);
    var containsSubquery = regexTest.IsMatch(sql);
    return containsSubquery;
}


问:
Create new Column in Power Bi with RegEx
I'm relatively new to Power BI and want to generate a new one based on a column. The contents of the new column should be based on the first value of another column. For example:

```<code>ColumnA NewColumn
1123 Argentinia
5644 Brazil
5555 Brazil
3334 Denmark
1124 Argentinia
</code>```

As you can see, the first value of the number decides which country will be added to the new column.
In SQL I know that I can use something like this:

```<code>`select * from table where column LIKE '%[2]`%'
</code>```

and so on but is this possible with Power BI? Thanks a lot.

Edit:

My additional list looks like this:

```<code>ID Country
1  Argentina
2  Swiss
3  Denmark
4  Norway
5  Brazil
</code>```

and so on...

I thougt I could use somethin like this:

```<code>NewColumn = IF('table'[ColumnA] = "%[1]`%"
THEN "Argentinia"
ELSE if IF('table'[ColumnA] = "%[2]`%
THEN Swiss
ELSE "No Country")
</code>```

答:
Add your Number / Country List to a new table. Let's assume you call it Countries.

Now you can add a column to your original table (let's assume you've called that one Fact Table), using something like:

```<code>Country =
LOOKUPVALUE (
    Countries[Country],
    Countries[ID],
    VALUE ( LEFT ( 'Fact Table'[ColumnA], 1 ) )
)
</code>```

See https://pwrbi.com/so_56391689/ for worked example.

Body:
I'm relatively new to Power BI and want to generate a new one based on a column. The contents of the new column should be based on the first value of another column. For example:

ColumnA NewColumn
1123 Argentinia
5644 Brazil
5555 Brazil
3334 Denmark
1124 Argentinia

As you can see, the first value of the number decides which country will be added to the new column.
In SQL I know that I can use something like this:

`select * from table where column LIKE '%[2]`%'

and so on but is this possible with Power BI? Thanks a lot.

Edit:

My additional list looks like this:

ID Country
1  Argentina
2  Swiss
3  Denmark
4  Norway
5  Brazil

and so on...

I thougt I could use somethin like this:

NewColumn = IF('table'[ColumnA] = "%[1]`%"
THEN "Argentinia"
ELSE if IF('table'[ColumnA] = "%[2]`%
THEN Swiss
ELSE "No Country")

Body:
Add your Number / Country List to a new table. Let's assume you call it Countries.

Now you can add a column to your original table (let's assume you've called that one Fact Table), using something like:

Country =
LOOKUPVALUE (
    Countries[Country],
    Countries[ID],
    VALUE ( LEFT ( 'Fact Table'[ColumnA], 1 ) )
)

See https://pwrbi.com/so_56391689/ for worked example.


问:
Why LESS css width results in MORE visual width?
I have an html like this:

```<code><!doctype html>
<head>
<style>
body { background-color: #eee; }

.container {
  display: table;
  border-spacing: 1.5em 0;
 }

.cell {
  display: table-cell;
  background-color: orange;
  border-radius: .5em;
  padding: 1em;
  width: 50%;
}
</style>
</head>
<body>
  <div class="container">
    <div class="cell">Left cell</div>
    <div class="cell">#</div>
  </div>
</body>
</code>```

and I'm baffled with the width property. The value 10% produces more visual width than value 50%. Why?

NOTE: I deliberately miss out css width property for .container, so to observe how/why CSS behaves this way.

See image below:

# # # # # #

# # # # # #

答:
The problem is your container's display: table style. It's unwise to mix table structure along with its cells' individual width property.
So, either use div layout or control the width of cell's from your container's style.width property.
Please note, typical table style maintain's its cell's width ratio in its own way.
Also, I will suggest to add a width property to your container. Then you can play with cell's style.width and see for yourself how tables work.

Body:
I have an html like this:

<!doctype html>

Left cell

#

and I'm baffled with the width property. The value 10% produces more visual width than value 50%. Why?

NOTE: I deliberately miss out css width property for .container, so to observe how/why CSS behaves this way.

See image below:

# # # # # #

# # # # # #


问:
Conversion of string to integer, then again to string
I am on a project developing an app on Android. Here I have to find a sum between two numbers defined as Strings and then display them on a textview. But my app is crashing. Below is my code. Is it optimal?

```<code>      String price=Place_View.prices[spinner1.getSelectedItemPosition()];
            String fare=Cars.SUVFare[spinner2.getSelectedItemPosition()];
            String result="";
            int calc1=Integer.parseInt(price);
            int calc2=Integer.parseInt(fare);
            int calc3=calc1+calc2;
            result=Integer.toString(calc3);
            Price.setText(result);

        }
    });
</code>```

spinner1:

```<code>public class Place_View {
public static final String[] locName = {"Sivasagar", "Jorhat", "Tinsukia", "Mohanbari", "Pasighat", "Digboi", "Majuli"};

public static final String[] prices = {"2625.00","3200.00","2000.00","500.00","4000.00","2800.00","4000.00"};
}
</code>```

spinner 2:

```<code>public class Cars {
             public static final String[] SUV = {"Mahindra XUV", "Renault Duster", "Hyundai Creta", "Nissan Terrano", "Maruti Suzuki Brezza"};
                 public static final String[] SUVFare={"1000","800","800","750","650"};
}
</code>```

Now I have to add the values of the strings prices and SUVFare when selected one of the both and put them on the TextView Price. Don't know how to post logcat so put the classes I made custom.

答:
Please try this to convert an int to String in Android:

```<code> int number = 78;
 String numberAsString = String.valueOf(number);
</code>```

Body:
I am on a project developing an app on Android. Here I have to find a sum between two numbers defined as Strings and then display them on a textview. But my app is crashing. Below is my code. Is it optimal?

      String price=Place_View.prices[spinner1.getSelectedItemPosition()];
            String fare=Cars.SUVFare[spinner2.getSelectedItemPosition()];
            String result="";
            int calc1=Integer.parseInt(price);
            int calc2=Integer.parseInt(fare);
            int calc3=calc1+calc2;
            result=Integer.toString(calc3);
            Price.setText(result);

        }
    });

spinner1:

public class Place_View {
public static final String[] locName = {"Sivasagar", "Jorhat", "Tinsukia", "Mohanbari", "Pasighat", "Digboi", "Majuli"};

public static final String[] prices = {"2625.00","3200.00","2000.00","500.00","4000.00","2800.00","4000.00"};
}

spinner 2:

public class Cars {
             public static final String[] SUV = {"Mahindra XUV", "Renault Duster", "Hyundai Creta", "Nissan Terrano", "Maruti Suzuki Brezza"};
                 public static final String[] SUVFare={"1000","800","800","750","650"};
}

Now I have to add the values of the strings prices and SUVFare when selected one of the both and put them on the TextView Price. Don't know how to post logcat so put the classes I made custom.

Body:
Please try this to convert an int to String in Android:

 int number = 78;
 String numberAsString = String.valueOf(number);


问:
Unexpected error occurred in scheduled task.: java.lang.NoSuchFieldError: ADJUST_DATES_TO_CONTEXT_TIME_ZONE
I'm working on take a JSON object and persist it in a relational database:
entity:

```<code>import java.time.ZonedDateTime;

...

private ZonedDateTime zonedDateTime ;
public ZonedDateTime getZonedDateTime () {
        return zonedDateTime ;
    }
public void setZonedDateTime (ZonedDateTime zonedDateTime ) {
        this.zonedDateTime = zonedDateTime ;
    }
</code>```

I have add dependency on pom.xml:

```<code><dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
</code>```

but when I call the Service:

```<code>ERROR [org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler] (ThreadPoolTaskScheduler-7) Unexpected error occurred in
 scheduled task.: java.lang.NoSuchFieldError: ADJUST_DATES_TO_CONTEXT_TIME_ZONE
    at com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer.createContextual(InstantDeserializer.java:231)
    at com.fasterxml.jackson.databind.DeserializationContext.handleSecondaryContextualization(DeserializationContext.java:685)
    at com.fasterxml.jackson.databind.DeserializationContext.findContextualValueDeserializer(DeserializationContext.java:446)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer.findDeserializer(StdDeserializer.java:948)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:446)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:296)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.hasValueDeserializerFor(DeserializerCache.java:191)
    at com.fasterxml.jackson.databind.DeserializationContext.hasValueDeserializerFor(DeserializationContext.java:422)
    at com.fasterxml.jackson.databind.ObjectMapper.canDeserialize(ObjectMapper.java:2664)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.canRead(AbstractJackson2HttpMessageConverter.java:162)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.canRead(AbstractJackson2HttpMessageConverter.java:149)
    at org.springframework.web.client.RestTemplate$AcceptHeaderRequestCallback.doWithRequest(RestTemplate.java:765)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:650)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:128)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)
</code>```

Here the same problem http://qaru.site/questions/13631592/nosuchfielderror-adjustdatestocontexttimezone-when-trying-to-parse-json

答:
You need to update version "jackson-datatype-jsr310" >=2.8

Alexey Bychkov (joxerTMD@github)

  * Contributed #80: Add Support for
  JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE    (2.8.0)
  /**
       * Flag for JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE
       *
       * @since 2.8
       *

To solve it:
 in pom.xml:

```<code><dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.8.11</version>
</dependency>
</code>```

Body:
I'm working on take a JSON object and persist it in a relational database:
entity:

import java.time.ZonedDateTime;

...

private ZonedDateTime zonedDateTime ;
public ZonedDateTime getZonedDateTime () {
        return zonedDateTime ;
    }
public void setZonedDateTime (ZonedDateTime zonedDateTime ) {
        this.zonedDateTime = zonedDateTime ;
    }

I have add dependency on pom.xml:

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

but when I call the Service:

ERROR [org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler] (ThreadPoolTaskScheduler-7) Unexpected error occurred in
 scheduled task.: java.lang.NoSuchFieldError: ADJUST_DATES_TO_CONTEXT_TIME_ZONE
    at com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer.createContextual(InstantDeserializer.java:231)
    at com.fasterxml.jackson.databind.DeserializationContext.handleSecondaryContextualization(DeserializationContext.java:685)
    at com.fasterxml.jackson.databind.DeserializationContext.findContextualValueDeserializer(DeserializationContext.java:446)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer.findDeserializer(StdDeserializer.java:948)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:446)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:296)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.hasValueDeserializerFor(DeserializerCache.java:191)
    at com.fasterxml.jackson.databind.DeserializationContext.hasValueDeserializerFor(DeserializationContext.java:422)
    at com.fasterxml.jackson.databind.ObjectMapper.canDeserialize(ObjectMapper.java:2664)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.canRead(AbstractJackson2HttpMessageConverter.java:162)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.canRead(AbstractJackson2HttpMessageConverter.java:149)
    at org.springframework.web.client.RestTemplate$AcceptHeaderRequestCallback.doWithRequest(RestTemplate.java:765)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:650)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:128)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)

Here the same problem http://qaru.site/questions/13631592/nosuchfielderror-adjustdatestocontexttimezone-when-trying-to-parse-json

Body:
You need to update version "jackson-datatype-jsr310" >=2.8

Alexey Bychkov (joxerTMD@github)

  * Contributed #80: Add Support for
  JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE    (2.8.0)
  /**
       * Flag for JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE
       *
       * @since 2.8
       *

To solve it:
 in pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.8.11</version>
</dependency>


问:
When I hit ./iiq console in command prompt my Sailpoint says database version doesn't match the system version
I'm trying to run the training modules in sailpoint, where I was following the exercises. I was able to set up the database and all. When I try to run the Identityiq console, using ./iiq console, it flashes the error, the database version and the system version do not match. How do I change the versions to make them match?

I tried changing the schema version to the system version, but it doesn't match as it was checking database version and system version.

in the bin directory, i used the command
$./iiq console

This was the result: System version 6.1-64 doesn't match database version 6.2-32 Attached

答: Try to run command : iiq patch 6.2</p>

Body: Try to run command : iiq patch 6.2


问:
How can I call event.target.playVideo() using npm 'react-youtube' when a parent state changes without re-rendering child?
I feel like this is a simple issue caused by my lack of experience with react, forgive me if I've over-complicated it.

Using npm 'react-youtube', I am trying to call event.target.pauseVideo() on the Video component whenever a specific parent state changes. I have a button which toggles the video component's div display to 'none' or 'block' when clicked, I want this button to also pause or play the video without having to re-render the Video component. I can call event.target.pauseVideo() inside the provided _onReady(){} or _onStateChange(){} with no issues, however I want it to be triggered when I press a button, not on either of those triggers.

I've tried creating my own method in the Video component which calls event.target.pauseVideo(), however I do not know how to trigger this from the parent (I think this is doable using refs, but everywhere I read says refs should not be used 99% of the time.) I've also tried passing event.target.pauseVideo() to the component from the parent, but this seems to try to use an event or target from the parent which doesn't exist instead of the Video component's.

Parent:

```<code>class Window extends React.Component {
  constructor(props){
    super(props)
    this.state={
      currentDisplay: 1,
      isPaused: 0,
    }
  }

  renderVideo(isPaused){
    return <Video isPaused={isPaused}>;
  }

  render() {
    return (
      <div className='window'>

        <div className = 'vid'>
          {this.renderVideo(this.state.isPaused)}
        </div>

        <div className = 'PauseButton'>
          <Pause handleClick={() => {this.togglePause()}}/>
        </div>
      </div>
    );
  }
}
</code>```

togglePause() just changes the pause state from 0 to 1 and vice versa

Pause button Component:

```<code>class PauseButton extends React.Component{
  render(){
    return(
      <button onClick={() =>  {this.props.handleClick()}  }>
        Pause
      </button>
    )
  }
}
</code>```

Video Component:

```<code>class Video extends React.Component{
  _pause(event, isPaused){
    if(isPaused = 1){event.target.pauseVideo()}
  }

  _onReady(event) {
    //event.target.pauseVideo()
  }
  render(){
    const opts = {
      height: '390',
      width: '640',
      playerVars: { // https://developers.google.com/youtube/player_parameters
      autoplay: 1,
      }
    }
    return(
      <YouTube
      videoId= {'21X5lGlDOfg'}
      opts={opts}
      onReady={this._onReady}
      onStateChange={this._onStateChange}
      />
    )
  }
}
</code>```

Currently, the '_pause()' method in the video component is never triggered, but I would like it to be triggered whenever the pause button is clicked.

The code above plays the video without issues, however I am looking for a way to trigger the _pause() method in the Video component without having to re render the component.

答:
Created a code sandbox with Video gettign paused when clicking pause button. Achieved using React Hooks.

https://codesandbox.io/s/elegant-cerf-0os7t

Body:
I feel like this is a simple issue caused by my lack of experience with react, forgive me if I've over-complicated it.

Using npm 'react-youtube', I am trying to call event.target.pauseVideo() on the Video component whenever a specific parent state changes. I have a button which toggles the video component's div display to 'none' or 'block' when clicked, I want this button to also pause or play the video without having to re-render the Video component. I can call event.target.pauseVideo() inside the provided _onReady(){} or _onStateChange(){} with no issues, however I want it to be triggered when I press a button, not on either of those triggers.

I've tried creating my own method in the Video component which calls event.target.pauseVideo(), however I do not know how to trigger this from the parent (I think this is doable using refs, but everywhere I read says refs should not be used 99% of the time.) I've also tried passing event.target.pauseVideo() to the component from the parent, but this seems to try to use an event or target from the parent which doesn't exist instead of the Video component's.

Parent:

class Window extends React.Component {
  constructor(props){
    super(props)
    this.state={
      currentDisplay: 1,
      isPaused: 0,
    }
  }

  renderVideo(isPaused){
    return <Video isPaused={isPaused}>;
  }

  render() {
    return (

          {this.renderVideo(this.state.isPaused)}

          <Pause handleClick={() => {this.togglePause()}}/>

    );
  }
}

togglePause() just changes the pause state from 0 to 1 and vice versa

Pause button Component:

class PauseButton extends React.Component{
  render(){
    return(
      <button onClick={() =>  {this.props.handleClick()}  }>
        Pause
      </button>
    )
  }
}

Video Component:

class Video extends React.Component{
  _pause(event, isPaused){
    if(isPaused = 1){event.target.pauseVideo()}
  }

  _onReady(event) {
    //event.target.pauseVideo()
  }
  render(){
    const opts = {
      height: '390',
      width: '640',
      playerVars: { // https://developers.google.com/youtube/player_parameters
      autoplay: 1,
      }
    }
    return(
      <YouTube
      videoId= {'21X5lGlDOfg'}
      opts={opts}
      onReady={this._onReady}
      onStateChange={this._onStateChange}
      />
    )
  }
}

Currently, the '_pause()' method in the video component is never triggered, but I would like it to be triggered whenever the pause button is clicked.

The code above plays the video without issues, however I am looking for a way to trigger the _pause() method in the Video component without having to re render the component.


问:
Empty files generated from running `mysqldump` using PHP
I keep getting empty files generated from running

```<code>$command = 'mysqldump --opt -h localhost -u username -p \'password\' dbname > \'backup 2009-04-15 09-57-13.sql\'';

command($command);
</code>```

Anyone know what might be causing this? My password has strange characters in it, but works fine with connecting to the db.

I've ran exec($command, $return) and outputted the $return array and it is finding the command. I've also ran it with mysqldump > file.sql and the file contains

```<code>Usage: mysqldump [OPTIONS] database [tables]
OR     mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
OR     mysqldump [OPTIONS] --all-databases [OPTIONS]
For more options, use mysqldump --help
</code>```

So it would seem like the command is working.

答:
You have to specify full path to mysqldump:

```<code>// Linux:
$command = '/usr/bin/mysqldump --opt -h localhost -u username -p \'password\' dbname > \'backup 2009-04-15 09-57-13.sql\'';

// Windows:
$command = 'c:\mysql\bin\mysqldump --opt -h localhost -u username -p \'password\' dbname > \'backup 2009-04-15 09-57-13.sql\'';
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I keep getting empty files generated from running

$command = 'mysqldump --opt -h localhost -u username -p \'password\' dbname > \'backup 2009-04-15 09-57-13.sql\'';

command($command);

Anyone know what might be causing this? My password has strange characters in it, but works fine with connecting to the db.

I've ran exec($command, $return) and outputted the $return array and it is finding the command. I've also ran it with mysqldump > file.sql and the file contains

Usage: mysqldump [OPTIONS] database [tables]
OR     mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
OR     mysqldump [OPTIONS] --all-databases [OPTIONS]
For more options, use mysqldump --help

So it would seem like the command is working.

Body:
You have to specify full path to mysqldump:

// Linux:
$command = '/usr/bin/mysqldump --opt -h localhost -u username -p \'password\' dbname > \'backup 2009-04-15 09-57-13.sql\'';

// Windows:
$command = 'c:\mysql\bin\mysqldump --opt -h localhost -u username -p \'password\' dbname > \'backup 2009-04-15 09-57-13.sql\'';


问:
How to make an ASP.Net page with a C# code behind that will work in Sharepoint
I need to develop a page for Sharepoint.

Basically it is a 3 step process that takes some inputs, gets some data and shows a preview of it, then allows the data to be sent off attached to an email.

I know ASP.Net and C#.Net, and the problem should be reasonably easy to solve with an ASP.Net page and a C# code behind.

However I've never had to work with Sharepoint before, and I don't know what is required to make the page 'work in Sharepoint'.

Is there anything special that needs to be done to make it work in Sharepoint? Is an ASPX page the right approach for this sort of problem?

(I'm developing on an XP machine using Visual Studio 2008.)

答:
You can do an ASPX page with code-behind by putting the ASPX page in the 12 _layout directory and GACing the DLL.  It's not very fun :)

Edit: A tutorial... http://www.codeproject.com/KB/sharepoint/SharePoint2.aspx

Edit again: Noticed you said Windows XP.  SharePoint 2007 will only work on Server 2003.

OwnerDisplayName: Sophia

OwnerDisplayName: Jim

LastEditorDisplayName: Jim


问:
Multi level view: expandablelistview
I am trying to write multi level tree. I did look at expandablelistview, but it only supports two levels. I did look at other questions(SO) & posts and the most promising post i have found is http://mylifewithandroid.blogspot.com/2011/02/3-level-expandable-lists.html

I understand that i will have to write something custom to handle multiple level tree.
What is the best recommended approach to take?
Can i add an exapandablelistview as a child to an exapanablelistview??

Thanks

答:
You can achieve an n-level ExpandableListView, if you use it with your custom BaseExpandableListAdapter.

In this extended adapter, you override the

```<code>public View getGroupView(int groupPosition, boolean isExpanded,
    View convertView, ViewGroup parent)
</code>```

method, assign a BaseExpandableListAdapter instance to the convertView, and return it.

If you have override all the necessary methods in your adapter, this should work.

Title: Multi level view: expandablelistview

Body:
You can achieve an n-level ExpandableListView, if you use it with your custom BaseExpandableListAdapter.

In this extended adapter, you override the

public View getGroupView(int groupPosition, boolean isExpanded,
    View convertView, ViewGroup parent)

method, assign a BaseExpandableListAdapter instance to the convertView, and return it.

If you have override all the necessary methods in your adapter, this should work.


问:
How to insert a random string into the sed 's//' replace string for each line actioned?
This:

echo "    " | tr ' ' '\n' | sed "s|.*|$RANDOM|"

Or this:

echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"

Will print a list of 5 numbers (space is replaced by newline, sed replaces each line with $RANDOM), and those 5 numbers will all be the same:

```<code>$ echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"
21590
21590
21590
21590
21590
</code>```

This is because the replace of $RANDOM to a random value happens only once.

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line. i.e. to provide some "secondary input stream" which differs for each line that sed handles?

I could do it with xargs, but I wonder if there is a way to do it with sed only.

答:
If you want the same random number

```<code>random=$(cat /dev/urandom | tr -cd '0-9' | head -c 5)
echo -e "$random\n$random\n$random\n$random\n$random"
</code>```

If you want a different number each time. The problem here is its harder to set how many characters you get

```<code>echo -e "$RANDOM\n$RANDOM\n$RANDOM\n$RANDOM\n$RANDOM"
</code>```

Or more logically for the same number

```<code>random=$(cat /dev/urandom | tr -cd '0-5' | head -c 8)
x=0
while (($x < 5)); do echo "$random";((x++));done
</code>```

or more logically for a different number

```<code>x=0
while (($x < 5)); do random=$(cat /dev/urandom | tr -cd '0-5' | head -c 8); echo "$random";((x++));done
</code>```

Body:
This:

echo "    " | tr ' ' '\n' | sed "s|.*|$RANDOM|"

Or this:

echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"

Will print a list of 5 numbers (space is replaced by newline, sed replaces each line with $RANDOM), and those 5 numbers will all be the same:

$ echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"
21590
21590
21590
21590
21590

This is because the replace of $RANDOM to a random value happens only once.

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line. i.e. to provide some "secondary input stream" which differs for each line that sed handles?

I could do it with xargs, but I wonder if there is a way to do it with sed only.

Body:
If you want the same random number

random=$(cat /dev/urandom | tr -cd '0-9' | head -c 5)
echo -e "$random\n$random\n$random\n$random\n$random"

If you want a different number each time. The problem here is its harder to set how many characters you get

echo -e "$RANDOM\n$RANDOM\n$RANDOM\n$RANDOM\n$RANDOM"

Or more logically for the same number

random=$(cat /dev/urandom | tr -cd '0-5' | head -c 8)
x=0
while (($x < 5)); do echo "$random";((x++));done

or more logically for a different number

x=0
while (($x < 5)); do random=$(cat /dev/urandom | tr -cd '0-5' | head -c 8); echo "$random";((x++));done


问:
Get number of days balance was negative
I would like to get the number of days the account went to a negative balance.

I have the following Balance table.

```<code>|AccNo |    Amount      | Date
------------------------------------
|1     |    -8775.76    | 2019-05-31
|1     |    -697.05     | 2019-05-30
|1     |    -3504.52    | 2019-05-29
|1     |   +1783.67     | 2019-05-28
|1     |    -14204.55   | 2019-05-27

  SELECT DATEDIFF(DAY, AccountB.Date, GETDATE()) AS DaysInDebit
  FROM (SELECT TOP 1 Date
        FROM Balance WHERE AccNo = 1
        AND Amount > 0
        ORDER BY Date DESC
       ) AS AccountB
  ORDER BY AccountB.Date DESC
</code>```

I am expecting to get 3 days where the account was in debt.
Result set from 2019-05-28 to 2019-05-31. Date Difference = 3

答:
Try this-    </p>

```<code>SELECT
DATEDIFF
(
    DD,
    (
        SELECT
        MAX(Date)
        FROM your_table
        WHERE ID= 1
        AND Amount > 0
    ),
    GETDATE()
)
FROM your_table
WHERE ID = 1
GROUP BY ID
</code>```

Title: Get number of days balance was negative

Body:
I would like to get the number of days the account went to a negative balance.

I have the following Balance table.

|AccNo |    Amount      | Date
------------------------------------
|1     |    -8775.76    | 2019-05-31
|1     |    -697.05     | 2019-05-30
|1     |    -3504.52    | 2019-05-29
|1     |   +1783.67     | 2019-05-28
|1     |    -14204.55   | 2019-05-27

  SELECT DATEDIFF(DAY, AccountB.Date, GETDATE()) AS DaysInDebit
  FROM (SELECT TOP 1 Date
        FROM Balance WHERE AccNo = 1
        AND Amount > 0
        ORDER BY Date DESC
       ) AS AccountB
  ORDER BY AccountB.Date DESC

I am expecting to get 3 days where the account was in debt.
Result set from 2019-05-28 to 2019-05-31. Date Difference = 3

Body:
Try this-

SELECT
DATEDIFF
(
    DD,
    (
        SELECT
        MAX(Date)
        FROM your_table
        WHERE ID= 1
        AND Amount > 0
    ),
    GETDATE()
)
FROM your_table
WHERE ID = 1
GROUP BY ID