问:
Align image in div & give div space from card
So I am trying to make a little "card", to show information about products. Now I want a little picture of each product at the top, but I need to center it verticle and horizontally.

I also need to give the image/div a little space, tried doing margin-top: 1em; but didn't do anything at all.

Here is my HTML code:

```<code><div class="container">
  <div class="row">
    {% for auction in auctions%}
    <div class="col-sm-4">
      <div class="auction-item">
        <div class="img-container">
          <img
            src="/static/img/grass.png"
            alt="Grass Block"
            class="item-icon"
          />
        </div>
        <h2>{{ auction.name }}</h2>
        <div class="average-price">
          <h3>Average Price: {{ auction.start_bid }}</h3>
        </div>
        <div class="time-left">
          <h3>Time Left: time</h3>
        </div>
        <div class="graph-div">
          <a class="graph-tag" href="#">Show Graph</a>
        </div>
      </div>
    </div>
    {% endfor %}
  </div>
</div>
</code>```

CSS can be found here:

```<code>.img-container {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background-color: #333;
  margin-top: 1em;
  margin: auto;
  text-align: center;
}

.item-icon {
  width: 80%;
}

.auction-item {
  width: 275px;
  height: 320px;
  background-color: blue;
  border-radius: 25px;
  margin: 3em;
}

.auction-item h2 {
  color: white;
  font-size: 24px;
  text-align: center;
  padding-top: 1em;
}

.auction-item h3 {
  color: white;
  font-size: 20px;
  text-align: center;
  padding-top: 1em;
}

.graph-div {
  text-align: center;
  padding-top: 1em;
}

.graph-tag {
  color: white;
  font-size: 20px;
}
</code>```

And here is how it looks right now:

答:
Add (position: relative) in your container css

```<code>.img-container {
width: 64px;
height: 64px;
border-radius: 50%;
background-color: #333;
margin-top: 1em;
margin: auto;
text-align: center;
position: relative;
</code>```

}

and your image class add

```<code>.item-icon {
width: 80%;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
position: absolute;
</code>```

}

Body:
So I am trying to make a little "card", to show information about products. Now I want a little picture of each product at the top, but I need to center it verticle and horizontally.

I also need to give the image/div a little space, tried doing margin-top: 1em; but didn't do anything at all.

Here is my HTML code:

    {% for auction in auctions%}

{{ auction.name }}

Average Price: {{ auction.start_bid }}

Time Left: time

          Show Graph

    {% endfor %}

CSS can be found here:

.img-container {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background-color: #333;
  margin-top: 1em;
  margin: auto;
  text-align: center;
}

.item-icon {
  width: 80%;
}

.auction-item {
  width: 275px;
  height: 320px;
  background-color: blue;
  border-radius: 25px;
  margin: 3em;
}

.auction-item h2 {
  color: white;
  font-size: 24px;
  text-align: center;
  padding-top: 1em;
}

.auction-item h3 {
  color: white;
  font-size: 20px;
  text-align: center;
  padding-top: 1em;
}

.graph-div {
  text-align: center;
  padding-top: 1em;
}

.graph-tag {
  color: white;
  font-size: 20px;
}

And here is how it looks right now:

Body:
Add (position: relative) in your container css

.img-container {
width: 64px;
height: 64px;
border-radius: 50%;
background-color: #333;
margin-top: 1em;
margin: auto;
text-align: center;
position: relative;

}

and your image class add

.item-icon {
width: 80%;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
position: absolute;

}


来源: stackexchange

问:
How to send data to a specified connection while using node.js
I am using node.js building a TCP server, just like the example in the doc. The server establishes persistent connections and handle client requests. But I also need to send data to any specified connection, which means this action is not client driven. How to do that?</p>

答:
Your server could maintain a data structure of active connections by adding on the server "connection" event and removing on the stream "close" event.  Then you can pick the desired connection from that data structure and write data to it whenever you want.

Here is a simple example of a time server that sends the current time to all connected clients every second:

```<code>var net = require('net')
  , clients = {}; // Contains all active clients at any time.

net.createServer().on('connection', function(sock) {
  clients[sock.fd] = sock; // Add the client, keyed by fd.
  sock.on('close', function() {
    delete clients[sock.fd]; // Remove the client.
  });
}).listen(5555, 'localhost');

setInterval(function() { // Write the time to all clients every second.
  var i, sock;
  for (i in clients) {
    sock = clients[i];
    if (sock.writable) { // In case it closed while we are iterating.
      sock.write(new Date().toString() + "\n");
    }
  }
}, 1000);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Your server could maintain a data structure of active connections by adding on the server "connection" event and removing on the stream "close" event.  Then you can pick the desired connection from that data structure and write data to it whenever you want.

Here is a simple example of a time server that sends the current time to all connected clients every second:

var net = require('net')
  , clients = {}; // Contains all active clients at any time.

net.createServer().on('connection', function(sock) {
  clients[sock.fd] = sock; // Add the client, keyed by fd.
  sock.on('close', function() {
    delete clients[sock.fd]; // Remove the client.
  });
}).listen(5555, 'localhost');

setInterval(function() { // Write the time to all clients every second.
  var i, sock;
  for (i in clients) {
    sock = clients[i];
    if (sock.writable) { // In case it closed while we are iterating.
      sock.write(new Date().toString() + "\n");
    }
  }
}, 1000);


问:
Bubble Chart using R - x axis variables are not in numerical order + Scaling of axis
I have the following R code which contains some dummy data. I am trying to create a bubble chart where the size of the bubble is dependent on the amount and is positioned based on the profitability (as a % of the amount) on the x-axis and the volatility (as a % of the amount) on the y-axis. Code is as follows:

```<code> rio_csv <- import("~/Desktop/R/Dummy Data.csv")

# Select columns to go into df

df <- data.frame("Volpc" = rio_csv[,6],"Profitpc"= rio_csv[,5],"Amount"= rio_csv[,4])

#Plot Bubble Chart

plot <- ggplot(df, aes(x = Profitpc, y = Volpc, size = Amount)) +
geom_point(alpha = 0.2) + scale_size(range = c(5,15)) + xlab("Profitability %") +
ylab("Volatility %")

plot
</code>```

The profitability measure on the x-axis is a percentage and the volatility on the y-axis is a percentage. They both have the data type 'character'.

My first problem is when i run the code a bubble chart appears but the x-axis is not in numerical order, the y-axis is in numerical order.

I tried to use the code df$Profitpc <- as.numeric(df$Profitpc) but this causes all the values in the column to go NA with the warning 'NAs introduced by coercion'.

Is there a way of ordering the x-axis so it is in numerical order (increasing)?

My second problem is that the scaling of both axes are not suitably scaled. Ideally i would like a situation where both axes have appropriate scaling such as 0 to the max % value. Is there a way to do this also? I am sorry if this is obvious. I have attached a picture of the chart to illustrate the issues.

答:
I second @Limey. Still what you could try is check whether Profitpc is a factor and if yes convert it to character like this:

```<code>ggplot(df, aes(x = as.character(Profitpc), y = (Volpc), size = Amount)) +
  geom_point(alpha = 0.2) + scale_size(range = c(5,15)) + xlab("Profitability %") +
  ylab("Volatility %")
</code>```

Still does not guarantee that the order will be right, therefore I would also convert the variables to numeric variables. You could use parse_number() from the readr package like this:

```<code>ggplot(df, aes(x = parse_number(Profitpc), y = parse_number(Volpc), size = Amount)) +
  geom_point(alpha = 0.2) + scale_size(range = c(5,15)) + xlab("Profitability %") +
  ylab("Volatility %")
</code>```

Data

```<code>df <- tibble::tribble(
        ~Profitpc,   ~Volpc, ~Amount,
            "10%",    "30%",     10L,
         "15.50%",    "20%",     15L,
            "81.40%", "80.30%",      6L,
         "50%",  "30.3&",     12L
        )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following R code which contains some dummy data. I am trying to create a bubble chart where the size of the bubble is dependent on the amount and is positioned based on the profitability (as a % of the amount) on the x-axis and the volatility (as a % of the amount) on the y-axis. Code is as follows:

 rio_csv <- import("~/Desktop/R/Dummy Data.csv")

# Select columns to go into df

df <- data.frame("Volpc" = rio_csv[,6],"Profitpc"= rio_csv[,5],"Amount"= rio_csv[,4])

#Plot Bubble Chart

plot <- ggplot(df, aes(x = Profitpc, y = Volpc, size = Amount)) +
geom_point(alpha = 0.2) + scale_size(range = c(5,15)) + xlab("Profitability %") +
ylab("Volatility %")

plot

The profitability measure on the x-axis is a percentage and the volatility on the y-axis is a percentage. They both have the data type 'character'.

My first problem is when i run the code a bubble chart appears but the x-axis is not in numerical order, the y-axis is in numerical order.

I tried to use the code df$Profitpc <- as.numeric(df$Profitpc) but this causes all the values in the column to go NA with the warning 'NAs introduced by coercion'.

Is there a way of ordering the x-axis so it is in numerical order (increasing)?

My second problem is that the scaling of both axes are not suitably scaled. Ideally i would like a situation where both axes have appropriate scaling such as 0 to the max % value. Is there a way to do this also? I am sorry if this is obvious. I have attached a picture of the chart to illustrate the issues.

Body:
I second @Limey. Still what you could try is check whether Profitpc is a factor and if yes convert it to character like this:

ggplot(df, aes(x = as.character(Profitpc), y = (Volpc), size = Amount)) +
  geom_point(alpha = 0.2) + scale_size(range = c(5,15)) + xlab("Profitability %") +
  ylab("Volatility %")

Still does not guarantee that the order will be right, therefore I would also convert the variables to numeric variables. You could use parse_number() from the readr package like this:

ggplot(df, aes(x = parse_number(Profitpc), y = parse_number(Volpc), size = Amount)) +
  geom_point(alpha = 0.2) + scale_size(range = c(5,15)) + xlab("Profitability %") +
  ylab("Volatility %")

Data

df <- tibble::tribble(
        ~Profitpc,   ~Volpc, ~Amount,
            "10%",    "30%",     10L,
         "15.50%",    "20%",     15L,
            "81.40%", "80.30%",      6L,
         "50%",  "30.3&",     12L
        )


问:
tablesorter js in html (404 not found)
```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="{{ url_for('static',filename='favicon.ico') }}">
    <link rel="stylesheet" href="{{ url_for('static',filename='styles.css') }}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="lib/tablesorter-master/js/jquery.tablesorter.js" type="text/javascript"></script>
...
</code>```

My folder structure is..

```<code>home
   <-lib/tablesorter-master/js/jquery.tablesorter.js
   <-templates/index.html
   <-static/styles.css
</code>```

I'm running a flask application and the py script is in the home directory.

I keep getting a "404/NOT FOUND" when the html loads on my browser (Chrome - localhost). I have read through similar threads here and elsewhere, but cannot seem to get this to work (most topic threads were around folder structures).

Any help would be appreciated.

答: The error message was straight-forward....the browser was expecting the file to be served via the flask server, which is not the normal way of doing this. I've used href in the same way as I'd use it to serve static files, and the browser does not complain now. </p>

Title: tablesorter js in html (404 not found)

Body:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hello World</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="{{ url_for('static',filename='favicon.ico') }}">
    <link rel="stylesheet" href="{{ url_for('static',filename='styles.css') }}">

...

My folder structure is..

home
   <-lib/tablesorter-master/js/jquery.tablesorter.js
   <-templates/index.html
   <-static/styles.css

I'm running a flask application and the py script is in the home directory.

I keep getting a "404/NOT FOUND" when the html loads on my browser (Chrome - localhost). I have read through similar threads here and elsewhere, but cannot seem to get this to work (most topic threads were around folder structures).

Any help would be appreciated.


问:
Syscall library in windows
Is it possible to translate the following functions in syscall into something in windows.h? If so, someone with information can help me, I can't find anything on google.

```<code>static inline int __setns(int fd, int nstype) {
    return syscall(__NR_setns, fd, nstype);

}

static inline int __unshare(int flags) {
    return syscall(__NR_unshare, flags);
}

static inline int __accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) {
    return syscall(__NR_accept4, sockfd, addr, addrlen, flags);
}

static inline int __dup3(int oldfd, int newfd, int flags) {
    return syscall(__NR_dup3, oldfd, newfd, flags);
}

static inline ssize_t __readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
    return syscall(__NR_readlinkat, dirfd, pathname, buf, bufsiz);
}

static inline int __symlinkat(const char *target, int newdirfd, const char *linkpath) {
    return syscall(__NR_symlinkat, target, newdirfd, linkpath);
}

static inline int __linkat(int olddirfd, const char *oldpath,
        int newdirfd, const char *newpath, int flags) {
    return syscall(__NR_linkat, olddirfd, oldpath, newdirfd, newpath, flags);
}

static inline int __inotify_init1(int flags) {
    return syscall(__NR_inotify_init1, flags);
}

static inline int __faccessat(int dirfd, const char *pathname, int mode, int flags) {
    return syscall(__NR_faccessat, dirfd, pathname, mode, flags);
}
</code>```

答:
No, it's not possible. Those are Linux specific system calls, and there is no direct "translation" on other operating systems.

The only thing you can do under Windows is to try and emulate those system calls, but that can only go so far and you will not be able to emulate all of them. A great example of this is Cygwin, which emulates a lot of standard Linux syscalls on windows, providing the the unistd.h header just like in any Linux system.

If you want to translate something outside the unistd.h header provided by Cygwin I'd say that's not possible unfortunately. You could try writing similar wrappers, but you're not going to really get the same syscall.

Title: Syscall library in windows

Body:
Is it possible to translate the following functions in syscall into something in windows.h? If so, someone with information can help me, I can't find anything on google.

static inline int __setns(int fd, int nstype) {
    return syscall(__NR_setns, fd, nstype);

}

static inline int __unshare(int flags) {
    return syscall(__NR_unshare, flags);
}

static inline int __accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) {
    return syscall(__NR_accept4, sockfd, addr, addrlen, flags);
}

static inline int __dup3(int oldfd, int newfd, int flags) {
    return syscall(__NR_dup3, oldfd, newfd, flags);
}

static inline ssize_t __readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {
    return syscall(__NR_readlinkat, dirfd, pathname, buf, bufsiz);
}

static inline int __symlinkat(const char *target, int newdirfd, const char *linkpath) {
    return syscall(__NR_symlinkat, target, newdirfd, linkpath);
}

static inline int __linkat(int olddirfd, const char *oldpath,
        int newdirfd, const char *newpath, int flags) {
    return syscall(__NR_linkat, olddirfd, oldpath, newdirfd, newpath, flags);
}

static inline int __inotify_init1(int flags) {
    return syscall(__NR_inotify_init1, flags);
}

static inline int __faccessat(int dirfd, const char *pathname, int mode, int flags) {
    return syscall(__NR_faccessat, dirfd, pathname, mode, flags);
}


问:
Why does this pattern not match after the “-”?
I have the following pattern which should work in C++ regex, perl and grep.  Does anyone know why the string of 0000 is not matching after the minus sign -?</p>

```<code>$ echo AB 00000-0000 | grep -Po "(\w{2}\s*\d{5}(−\d{4})?)"
AB 00000
$ echo AB00000-0000 | grep -Po "(\w{2}\s*\d{5}(−\d{4})?)"
AB00000
</code>```

答:
Your minus sign isn't what you think it is.  When I copy and paste your code into my shell, I see:

```<code>echo AB00000-0000 | grep -Po "(\w{2}\s*\d{5}(\342\210\222\d{4})?)"
</code>```

When I use a plain old minus sign (instead of \342\210\222, this is what I get:

```<code>$ echo AB00000-0000 | grep -Po "(\w{2}\s*\d{5}-\d{4}?)"
AB00000-0000
</code>```

Body:
I have the following pattern which should work in C++ regex, perl and grep.  Does anyone know why the string of 0000 is not matching after the minus sign -?

$ echo AB 00000-0000 | grep -Po "(\w{2}\s*\d{5}(−\d{4})?)"
AB 00000
$ echo AB00000-0000 | grep -Po "(\w{2}\s*\d{5}(−\d{4})?)"
AB00000

Body:
Your minus sign isn't what you think it is.  When I copy and paste your code into my shell, I see:

echo AB00000-0000 | grep -Po "(\w{2}\s*\d{5}(\342\210\222\d{4})?)"

When I use a plain old minus sign (instead of \342\210\222, this is what I get:

$ echo AB00000-0000 | grep -Po "(\w{2}\s*\d{5}-\d{4}?)"
AB00000-0000


问:
Pyspark groupBy - multiply and divide gives wrong results
Data :

```<code>Profit  Amount  Rate    Accunt  Status  Yr
0.3065  56999   1   Acc3    S1  1
0.3956  57000   1   Acc3    S1  1
0.3065  57001   1   Acc3    S1  1
0.3956  57002   1   Acc3    S1  1
0.3065  57003   1   Acc3    S1  2
0.3065  57004   0.89655 Acc3    S1  3
0.3956  57005   0.89655 Acc3    S1  3
0.2984  57006   0.89655 Acc3    S1  3
0.3956  57007   1   Acc3    S2  2
0.3956  57008   1   Acc3    S2  2
0.2984  57009   1   Acc3    S2  2
0.2984  57010   1   Acc1    S1  1
0.3956  57011   1   Acc1    S1  1
0.3065  57012   1   Acc1    S1  1
0.3065  57013   1   Acc1    S1  1
0.3065  57013   1   Acc1    S1  1
</code>```

Code:

```<code>df = df1\
.join(df12,(df12.code == df2.code),how = 'left').drop(df2.code).filter(col('Date') == '20Jan2019')\
.join(df3,df1.id== df3.id,how = 'left').drop(df3.id)\
.join(df4,df1.id == df4.id,how = 'left').drop(df4.id)\
.join(df5,df1.id2 == df5.id2,how ='left').drop(df5.id2)\
.withColumn("Account",concat(trim(df3.name1),trim(df4name1)))\
.withColumn("Status",when(df1.FB_Ind == 1,"S1").otherwise("S2"))\
.withColumn('Year',((df1['date'].substr(6, 4))+df1['Year']))

df6 = df.distinct()
df7 = df6.groupBy('Yr','Status','Account')\
.agg(sum((Profit * amount)/Rate).alias('output'))
</code>```

The output I am receiving is in decimals such as 0.234 instead in thousands 23344.2
Converting Sum((Profit*amount)/Rate) as Output code in pyspark

答:
This is how you should be writing your code. Also, I did not get it why are you adding df1['Year']?

```<code>df = df1\
.join(df12,"code",how = 'left') \
.filter(col('Date') == '20Jan2019') \
.join(df3,df1.id== df3.id,how = 'left') \
.drop(df3.id)\
.join(df4,"id",how = 'left') \
.join(df5,"id2",how ='left') \
.withColumn("Account",F.concat(F.trim(df3.name1), F.trim(df4name1)))\
.withColumn("Status",F.when(df1.FB_Ind == 1, "S1").otherwise("S2"))\
.withColumn('Year',F.substr(F.col('date'), 6, 4)+F.col('Year'))

df6 = df.distinct()
df7 = df6.groupBy('Yr', 'Status', 'Account')\
         .agg(F.sum(F.col("Profit") * F.col("amount"))/F.col("Rate")).alias('output'))
</code>```

For details on how do we apply groupby, partitonby and other functions in pyspark, please refer to - Analysis using Pyspark

Body:
Data :

Profit  Amount  Rate    Accunt  Status  Yr
0.3065  56999   1   Acc3    S1  1
0.3956  57000   1   Acc3    S1  1
0.3065  57001   1   Acc3    S1  1
0.3956  57002   1   Acc3    S1  1
0.3065  57003   1   Acc3    S1  2
0.3065  57004   0.89655 Acc3    S1  3
0.3956  57005   0.89655 Acc3    S1  3
0.2984  57006   0.89655 Acc3    S1  3
0.3956  57007   1   Acc3    S2  2
0.3956  57008   1   Acc3    S2  2
0.2984  57009   1   Acc3    S2  2
0.2984  57010   1   Acc1    S1  1
0.3956  57011   1   Acc1    S1  1
0.3065  57012   1   Acc1    S1  1
0.3065  57013   1   Acc1    S1  1
0.3065  57013   1   Acc1    S1  1

Code:

df = df1\
.join(df12,(df12.code == df2.code),how = 'left').drop(df2.code).filter(col('Date') == '20Jan2019')\
.join(df3,df1.id== df3.id,how = 'left').drop(df3.id)\
.join(df4,df1.id == df4.id,how = 'left').drop(df4.id)\
.join(df5,df1.id2 == df5.id2,how ='left').drop(df5.id2)\
.withColumn("Account",concat(trim(df3.name1),trim(df4name1)))\
.withColumn("Status",when(df1.FB_Ind == 1,"S1").otherwise("S2"))\
.withColumn('Year',((df1['date'].substr(6, 4))+df1['Year']))

df6 = df.distinct()
df7 = df6.groupBy('Yr','Status','Account')\
.agg(sum((Profit * amount)/Rate).alias('output'))

The output I am receiving is in decimals such as 0.234 instead in thousands 23344.2
Converting Sum((Profit*amount)/Rate) as Output code in pyspark

Body:
This is how you should be writing your code. Also, I did not get it why are you adding df1['Year']?

df = df1\
.join(df12,"code",how = 'left') \
.filter(col('Date') == '20Jan2019') \
.join(df3,df1.id== df3.id,how = 'left') \
.drop(df3.id)\
.join(df4,"id",how = 'left') \
.join(df5,"id2",how ='left') \
.withColumn("Account",F.concat(F.trim(df3.name1), F.trim(df4name1)))\
.withColumn("Status",F.when(df1.FB_Ind == 1, "S1").otherwise("S2"))\
.withColumn('Year',F.substr(F.col('date'), 6, 4)+F.col('Year'))

df6 = df.distinct()
df7 = df6.groupBy('Yr', 'Status', 'Account')\
         .agg(F.sum(F.col("Profit") * F.col("amount"))/F.col("Rate")).alias('output'))

For details on how do we apply groupby, partitonby and other functions in pyspark, please refer to - Analysis using Pyspark


问:
Selecting UITableViewCell programmatically?
I want to make a now playing button for my radio application. So would like to know how can I select a row programmatically I thought of calling didSelectRowAtIndexPath method but apparently we can't call it. </p>

答: There is tableView method like [tableView selectRowAtIndexPath:anIndexPathObject animated:BOOL-Flag]; .By calling this method you can select the row programmatically. But you also need to create an index path object.</p>


问:
Pause splash screen until user responds to permission request in android app
in my android application i have a splash screen that lasts 5 seconds during those 5 seconds i ask the user to grant location permission , I want to pause the splash screen activity until the user grants or denies the permission request.If the activity is not paused until the user responds, the next activity will be activated without having the user's response about the permission request here's my code

SpalshScreen activity:

```<code>public class SplashScreen extends BaseActivity {

    private static int SPLASH_SCREEN_TIME_OUT = 6000;

    some properties ....

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title
        getSupportActionBar().hide(); //hide the title bar
        setContentView(R.layout.activity_splash_screen);

       // This is the method that asks the user for permission
        locationPermGranted = CheckLocationPermission();

        deviceLanguage = Locale.getDefault().getDisplayLanguage();
        DeviceLanguageCode = Locale.getDefault().getLanguage();
        sharedPreferences = getSharedPreferences(getPackageName() + ".prefs", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        codeIntent = new Intent(SplashScreen.this, PhoneVerification.class);
        myIntent = new Intent(SplashScreen.this, ProfileSettings.class);
        loggedIntent = new Intent(SplashScreen.this, Main.class);
        notLoggedIntent = new Intent(SplashScreen.this, Login.class);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                if (!locationPermGranted) {

                    killApp();
                }

                if (sharedPreferences.getString("userLanguage", DeviceLanguageCode) == null) {
                    editor.apply();
                }

                if (sharedPreferences.getBoolean("isRegistered", false)) {

                    if (sharedPreferences.getBoolean("isPhoneVerified", false)) {

                        if (sharedPreferences.getBoolean("isLoggedIn", false)) {
                            // GO TO HOME

                            startActivity(loggedIntent);
                        } else {
                            // GO TO LOGIN
                            editor.apply();
                            startActivity(notLoggedIntent);
                        }

                    } else {
                        editor.apply();
                        startActivity(codeIntent);
                    }
                } else {
                    //GO TO PROFILE SETTINGS
                    editor.apply();
                    startActivity(myIntent);
                }

                finish();

            }
        }, SPLASH_SCREEN_TIME_OUT);

    }
</code>```

答: Surround newHandler().postDelayed method with if-else statement. If the user grants permission then only run the post delay method.

Body:
in my android application i have a splash screen that lasts 5 seconds during those 5 seconds i ask the user to grant location permission , I want to pause the splash screen activity until the user grants or denies the permission request.If the activity is not paused until the user responds, the next activity will be activated without having the user's response about the permission request here's my code

SpalshScreen activity:

public class SplashScreen extends BaseActivity {

    private static int SPLASH_SCREEN_TIME_OUT = 6000;

    some properties ....

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title
        getSupportActionBar().hide(); //hide the title bar
        setContentView(R.layout.activity_splash_screen);

       // This is the method that asks the user for permission
        locationPermGranted = CheckLocationPermission();

        deviceLanguage = Locale.getDefault().getDisplayLanguage();
        DeviceLanguageCode = Locale.getDefault().getLanguage();
        sharedPreferences = getSharedPreferences(getPackageName() + ".prefs", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        codeIntent = new Intent(SplashScreen.this, PhoneVerification.class);
        myIntent = new Intent(SplashScreen.this, ProfileSettings.class);
        loggedIntent = new Intent(SplashScreen.this, Main.class);
        notLoggedIntent = new Intent(SplashScreen.this, Login.class);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                if (!locationPermGranted) {

                    killApp();
                }

                if (sharedPreferences.getString("userLanguage", DeviceLanguageCode) == null) {
                    editor.apply();
                }

                if (sharedPreferences.getBoolean("isRegistered", false)) {

                    if (sharedPreferences.getBoolean("isPhoneVerified", false)) {

                        if (sharedPreferences.getBoolean("isLoggedIn", false)) {
                            // GO TO HOME

                            startActivity(loggedIntent);
                        } else {
                            // GO TO LOGIN
                            editor.apply();
                            startActivity(notLoggedIntent);
                        }

                    } else {
                        editor.apply();
                        startActivity(codeIntent);
                    }
                } else {
                    //GO TO PROFILE SETTINGS
                    editor.apply();
                    startActivity(myIntent);
                }

                finish();

            }
        }, SPLASH_SCREEN_TIME_OUT);

    }


问:
What is the difference between a "Spring transaction" and a "Hibernate transaction"
Could you please explain the difference between the following two types of transactions:

Hibernate transaction

Spring transaction

Also I would like to know about the @Transactional annotation.

答:
Coding level deference

Spring

In Spring, we can perform the transaction as below

```<code>@Transactional(readOnly=”false”)
public int insert(int studentId, String name, int courseId) {
    int outcome = 0;
    outcome = studentDao.insert(studentId, name);
    if (outcome > 0) {
   // re-intialize
        outcome = 0;
        outcome = studentCourseDao.insert(studentId, courseId);
    }
   return outcome;
}
</code>```

After seeing the @Transactional, the Spring IOC container is going to perform the transaction. If both the operation successfully, then commit operation will be performed. If any operation failed then rollback operation will be performed.

Hibernate

In Hibernate we can perform the transaction as below

```<code>    public int insert(Student student, Course course) {
      //it is a flag driven transaction
    boolean flag = false;
    Transaction transaction = null;
    Session session = null;
    SessionFactory sessionFactoryRepo = null;
    try {
        sessionFactoryRepo = SessionFactoryRepo.getsessionFactory();
        session = sessionFactoryRepo.openSession();
        // here we are creating the transaction object
        transaction = session.beginTransaction();

        int outcome = 0;
        outcome =session.save(student);
        if (outcome > 0) {
          // re-intialize
            outcome = 0;
            outcome = session.save(course);
        }
        flag = true;
        return outcome;
    } catch (Exception e) {
        // TODO: handle exception
    }
    finally {
        if (flag == true) {
            transaction.commit();
        } else
            transaction.rollback();
    }
}
</code>```

Body:
Coding level deference

Spring

In Spring, we can perform the transaction as below

@Transactional(readOnly=”false”)
public int insert(int studentId, String name, int courseId) {
    int outcome = 0;
    outcome = studentDao.insert(studentId, name);
    if (outcome > 0) {
   // re-intialize
        outcome = 0;
        outcome = studentCourseDao.insert(studentId, courseId);
    }
   return outcome;
}

After seeing the @Transactional, the Spring IOC container is going to perform the transaction. If both the operation successfully, then commit operation will be performed. If any operation failed then rollback operation will be performed.

Hibernate

In Hibernate we can perform the transaction as below

    public int insert(Student student, Course course) {
      //it is a flag driven transaction
    boolean flag = false;
    Transaction transaction = null;
    Session session = null;
    SessionFactory sessionFactoryRepo = null;
    try {
        sessionFactoryRepo = SessionFactoryRepo.getsessionFactory();
        session = sessionFactoryRepo.openSession();
        // here we are creating the transaction object
        transaction = session.beginTransaction();

        int outcome = 0;
        outcome =session.save(student);
        if (outcome > 0) {
          // re-intialize
            outcome = 0;
            outcome = session.save(course);
        }
        flag = true;
        return outcome;
    } catch (Exception e) {
        // TODO: handle exception
    }
    finally {
        if (flag == true) {
            transaction.commit();
        } else
            transaction.rollback();
    }
}


问:
Why I am getting same answers in gurobi when I am finding multiple solutions?
I am using Gurobi for solving an optimization problem. In my problem, the goal is to analyze the most possible solutions. For this purpose, I am using the parameter:

```<code>PoolSearchMode=2
</code>```

in Gurobi to find multiple solutions. But, when I retrieve the solutions, there are some same results!. For example, if it returns 100 solutions, half of them are the same and actually I have 50 different solutions.

For more detail, I am trying to find some sets of nodes in a graph that have a special feature. So I have set the parameter "PoolSearchMode" to 2 that causes the MIP to do a systematic search for the n best solutions. I have defined a parameter "best" to find solutions that have "objVal" equal to the best one. In the blow there is a part of my code:

```<code>m.Params.PoolSearchMode = 2
m.Params.PoolSolutions = 100

b = m.addVars(Edges, vtype=GRB.BINARY,  name = "b")
.
.
.

if m.status == GRB.Status.OPTIMAL:

     best = 0
     for key in range(m.SolCount):
           m.setParam(GRB.Param.SolutionNumber, key)
           if m.objVal == m.PoolObjVal:
                 best+=1

      optimal_sets = [[] for i in range(best)]

      for key in range(best):
            m.setParam(GRB.Param.SolutionNumber, key)

            for e in (Edges):
                  if b[e].Xn>0 and b[e].varname[2:]=="{}".format(External_node):
                            optimal_sets[key].append(int(b[e].varname[0:2]))

     return optimal_sets
</code>```

I have checked and I found that, if there are not 100 solutions in a graph, it returns fewer solutions. But in these sets also there are same results like:

```<code>[1,2,3],
[1,2,3],
[1,3,5]
</code>```

How can I fix this issue to get different solutions?

答: It seems that Gurobi returns multiple solutions to the MIP that can be mapped to the same solution of your underlying problem. I'm sure that if you checked the entire solution vector all these solutions would indeed be different. You are only looking at a subset of the variables in your set optimal_sets.

Body:
I am using Gurobi for solving an optimization problem. In my problem, the goal is to analyze the most possible solutions. For this purpose, I am using the parameter:

PoolSearchMode=2

in Gurobi to find multiple solutions. But, when I retrieve the solutions, there are some same results!. For example, if it returns 100 solutions, half of them are the same and actually I have 50 different solutions.

For more detail, I am trying to find some sets of nodes in a graph that have a special feature. So I have set the parameter "PoolSearchMode" to 2 that causes the MIP to do a systematic search for the n best solutions. I have defined a parameter "best" to find solutions that have "objVal" equal to the best one. In the blow there is a part of my code:

m.Params.PoolSearchMode = 2
m.Params.PoolSolutions = 100

b = m.addVars(Edges, vtype=GRB.BINARY,  name = "b")
.
.
.

if m.status == GRB.Status.OPTIMAL:

     best = 0
     for key in range(m.SolCount):
           m.setParam(GRB.Param.SolutionNumber, key)
           if m.objVal == m.PoolObjVal:
                 best+=1

      optimal_sets = [[] for i in range(best)]

      for key in range(best):
            m.setParam(GRB.Param.SolutionNumber, key)

            for e in (Edges):
                  if b[e].Xn>0 and b[e].varname[2:]=="{}".format(External_node):
                            optimal_sets[key].append(int(b[e].varname[0:2]))

     return optimal_sets

I have checked and I found that, if there are not 100 solutions in a graph, it returns fewer solutions. But in these sets also there are same results like:

[1,2,3],
[1,2,3],
[1,3,5]

How can I fix this issue to get different solutions?


问:
Search when NOT in OU
I want to search in the AD with LDAP, with a condition that people are not in a specific OU (see example)

```<code>Domain.local
- [OU] Location A
-- [OU] Users
-- [OU] Computers
- [OU] Location B
-- [OU] Users
-- [OU] Computers
- [OU] Location C
-- [OU] Users
-- [OU] Computers
</code>```

In my filter I want all users BUT the users from Location B/Users

is this possible? And if yes, how?

答:
ExtensibleMatch explained here allow to build filters on the DN path, but it's not supported in Active Directory. As far as I know you've got the following solution to do what you want:

Multiple search, one for each OU except the one you don't want

Two search, one global, one for the OU you don't want objects, and you suppress the entries from the second search in the first one.

Use an attribute in AD to make the distinction for users in Location B. For example  the attribute called OU which is inherited from organizationalPerson class. you set it with "locationB" (it's multivaluated)

The third solution is the one I use. My advice in your case is :

Test if OU attribute is used in your Directory for users or inetorgpersons if so select an other attribute

(&(|(objectclass=inetOrgPerson)(objectclass=user))(ou=*))

by scripting, by programming,by using LDIF populate the attribute you choose and keep it in use

If you are programmin with C# you've got the information of "parent" for an object as I explain in a simalary question so you can sort object on this criterium.

Title: Search when NOT in OU

Body:
I want to search in the AD with LDAP, with a condition that people are not in a specific OU (see example)

Domain.local
- [OU] Location A
-- [OU] Users
-- [OU] Computers
- [OU] Location B
-- [OU] Users
-- [OU] Computers
- [OU] Location C
-- [OU] Users
-- [OU] Computers

In my filter I want all users BUT the users from Location B/Users

is this possible? And if yes, how?


问:
opencv save image array
I getting counters ellipses in somw picture.How to crop and save each finded ellipses to file?
Code:</p>

```<code>import numpy as np
import cv2 as cv

hsv_min = np.array((0, 77, 17), np.uint8)
hsv_max = np.array((208, 255, 255), np.uint8)

if __name__ == '__main__':
    fn = 'buttons/bar.png'
    img = cv.imread(fn)
    hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
    thresh = cv.inRange(hsv, hsv_min, hsv_max)
    contours0, hierarchy = cv.findContours(thresh.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    for cnt in contours0:
        if len(cnt) > 4:
            print(cnt)
            ellipse = cv.fitEllipse(cnt)
            cv.ellipse(img, ellipse, (0, 255, 255), 2)

    cv.imshow('contours', img)

    cv.waitKey()
    cv.destroyAllWindows()
</code>```

答:
To save an image in OpenCV, use imwrite:

```<code>filename = 'savedImage.jpg'
cv2.imwrite(filename, img)
</code>```

If you just want to save each ellipse in a separate image, simply create a new image for each ellipse in the for loop and then use imwrite to save them to the newly created image:

```<code>file_num = 0
for cnt in contours0:
    if len(cnt) > 4:
        # create a new image with same dimensions as original image
        ellipse_img = np.zeros((img.shape[0], img.shape[1], 3), dtype = "uint8")
        print(cnt)
        ellipse = cv.fitEllipse(cnt)
        cv.ellipse(ellipse_img, ellipse, (255, 255, 255), 2)

        # save new image
        filename = 'ellipse' + str(file_num) + '.jpg'
        cv.imwrite(filename, ellipse_img)

        # increment counter in filename
        file_num += 1
</code>```

Additionally, if you want to mask the image as well, showing only the areas inside of the ellipses:

```<code>file_num = 0
for cnt in contours0:
    if len(cnt) > 4:
        # create a new image and mask with same dimensions as original image
        ellipse_img = np.zeros_like(img)
        mask = np.zeros_like(img)

        # fit ellipse to the contour, draw filled ellipse on mask, and apply mask to image
        ellipse = cv.fitEllipse(cnt)
        mask = cv.ellipse(mask, ellipse, (255, 255, 255), -1)
        ellipse_img[mask == 255] = img[mask == 255]

        # save masked image
        filename = 'ellipse' + str(file_num) + '.jpg'
        cv.imwrite(filename, ellipse_img)

        # increment counter in filename
        file_num += 1
</code>```

Further resources:

How to crop the internal area of a contour? |
Documentation of ellipse

Title: opencv save image array

Body:
I getting counters ellipses in somw picture.How to crop and save each finded ellipses to file?
Code:

import numpy as np
import cv2 as cv

hsv_min = np.array((0, 77, 17), np.uint8)
hsv_max = np.array((208, 255, 255), np.uint8)

if __name__ == '__main__':
    fn = 'buttons/bar.png'
    img = cv.imread(fn)
    hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
    thresh = cv.inRange(hsv, hsv_min, hsv_max)
    contours0, hierarchy = cv.findContours(thresh.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    for cnt in contours0:
        if len(cnt) > 4:
            print(cnt)
            ellipse = cv.fitEllipse(cnt)
            cv.ellipse(img, ellipse, (0, 255, 255), 2)

    cv.imshow('contours', img)

    cv.waitKey()
    cv.destroyAllWindows()

Body:
To save an image in OpenCV, use imwrite:

filename = 'savedImage.jpg'
cv2.imwrite(filename, img)

If you just want to save each ellipse in a separate image, simply create a new image for each ellipse in the for loop and then use imwrite to save them to the newly created image:

file_num = 0
for cnt in contours0:
    if len(cnt) > 4:
        # create a new image with same dimensions as original image
        ellipse_img = np.zeros((img.shape[0], img.shape[1], 3), dtype = "uint8")
        print(cnt)
        ellipse = cv.fitEllipse(cnt)
        cv.ellipse(ellipse_img, ellipse, (255, 255, 255), 2)

        # save new image
        filename = 'ellipse' + str(file_num) + '.jpg'
        cv.imwrite(filename, ellipse_img)

        # increment counter in filename
        file_num += 1

Additionally, if you want to mask the image as well, showing only the areas inside of the ellipses:

file_num = 0
for cnt in contours0:
    if len(cnt) > 4:
        # create a new image and mask with same dimensions as original image
        ellipse_img = np.zeros_like(img)
        mask = np.zeros_like(img)

        # fit ellipse to the contour, draw filled ellipse on mask, and apply mask to image
        ellipse = cv.fitEllipse(cnt)
        mask = cv.ellipse(mask, ellipse, (255, 255, 255), -1)
        ellipse_img[mask == 255] = img[mask == 255]

        # save masked image
        filename = 'ellipse' + str(file_num) + '.jpg'
        cv.imwrite(filename, ellipse_img)

        # increment counter in filename
        file_num += 1

Further resources:

How to crop the internal area of a contour? |
Documentation of ellipse


问:
How to locate the element within an iframe using Selenium WebDriver through Python
While doing automation testing on this website http://www.scstrade.com/TechnicalAnalysis/tvchart/ i was unable to find the element using selenium.

i want to find the search bar element at the top which is used to search for stocks and then pass the name of desired stock in that bar using selenium.

Here is the xpath for the search bar :

```<code>/html/body/div[1]/div[2]/div/div/div[1]/div/div/div/div/div[1]/div/div/input
</code>```

here is my code:

```<code>from selenium import webdriver
driver = webdriver.Chrome("D:\PyCharm Projects\Web Automation\drivers\chromedriver.exe")
driver.get("http://www.scstrade.com/TechnicalAnalysis/tvchart/")
driver.find_elements_by_xpath('/html/body/div[1]/div[2]/div/div/div[1]/div/div/div/div/div[1]/div/div/input')
Output : []
</code>```

i also tried finding the element using the class name:

```<code>driver.find_element_by_class_name('input-3lfOzLDc-')
</code>```

which gives me this error:

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"input-3lfOzLDc-"}
  (Session info: chrome=83.0.4103.61)
  (Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Windows NT 10.0.17134 x86_64)
</code>```

The element i am trying to access only has the class name so i can't try using the id.
I also tried switching to the frame first but i can't even find the frame element for this website using selenium.

答:
The search bar element at the top left corner is within an  so to invoke send_keys() on the element you have to:

Induce WebDriverWait for the desired frame_to_be_available_and_switch_to_it().

Induce WebDriverWait for the desired element_to_be_clickable().

You can use either of the following  Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[src^='charting_library/static/en-tv-chart']")))
index = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#header-toolbar-symbol-search input")))
index.click()
index.clear()
index.send_keys("KSE 30")
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[starts-with(@src, 'charting_library/static/en-tv-chart')]")))
index = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='header-toolbar-symbol-search']//input")))
index.click()
index.clear()
index.send_keys("KSE 30")
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

References

You can find a couple of relevant discussions in:

Ways to deal with #document under iframe

Switch to an iframe through Selenium and python

Body:
While doing automation testing on this website http://www.scstrade.com/TechnicalAnalysis/tvchart/ i was unable to find the element using selenium.

i want to find the search bar element at the top which is used to search for stocks and then pass the name of desired stock in that bar using selenium.

Here is the xpath for the search bar :

/html/body/div[1]/div[2]/div/div/div[1]/div/div/div/div/div[1]/div/div/input

here is my code:

from selenium import webdriver
driver = webdriver.Chrome("D:\PyCharm Projects\Web Automation\drivers\chromedriver.exe")
driver.get("http://www.scstrade.com/TechnicalAnalysis/tvchart/")
driver.find_elements_by_xpath('/html/body/div[1]/div[2]/div/div/div[1]/div/div/div/div/div[1]/div/div/input')
Output : []

i also tried finding the element using the class name:

driver.find_element_by_class_name('input-3lfOzLDc-')

which gives me this error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"input-3lfOzLDc-"}
  (Session info: chrome=83.0.4103.61)
  (Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Windows NT 10.0.17134 x86_64)

The element i am trying to access only has the class name so i can't try using the id.
I also tried switching to the frame first but i can't even find the frame element for this website using selenium.

Body:
The search bar element at the top left corner is within an <iframe> so to invoke send_keys() on the element you have to:

Induce WebDriverWait for the desired frame_to_be_available_and_switch_to_it().

Induce WebDriverWait for the desired element_to_be_clickable().

You can use either of the following  Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[src^='charting_library/static/en-tv-chart']")))
index = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#header-toolbar-symbol-search input")))
index.click()
index.clear()
index.send_keys("KSE 30")

Using XPATH:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[starts-with(@src, 'charting_library/static/en-tv-chart')]")))
index = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='header-toolbar-symbol-search']//input")))
index.click()
index.clear()
index.send_keys("KSE 30")

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

References

You can find a couple of relevant discussions in:

Ways to deal with #document under iframe

Switch to an iframe through Selenium and python


问:
How to divide bootstrap row into 5 equal parts?
I want to divide bootstrap row into 5 equal parts. It includes 12-col-md, so how i can divide it into equal 5 parts?

Can anyone help me to solve this problem?

答:
I would suggest to use table instead of bootstrap for dividing it into 5 parts and inside each column again you can use bootstrap grid.

This answer may help you this

But if you have any other issues that you can't go with the above way please comment below.


问:
Import only tagged blocks from Ansible role
I want to import into playbook (and execute) only part of Ansible role defined in tagged block.

E.g. I have role some_role containing 3 blocks of tasks tagged as tag1, tag2 and tag3. I could create playbook that imports whole role:

```<code>---
- hosts: some_host
  roles:
    - role: roles/some_role
</code>```

And then execute it from command line specifying single tag:

```<code>$ ansible-playbook -i hosts.yml playbook.yml --tags tag1
</code>```

But I want to move --tags tag1 part into playbook itself to be able to run that single block without providing tags to ansible-playbook.

答:
```<code>- import_role:
      name: myrole
  tags: [ web, foo ]

- import_tasks: foo.yml
  tags: [ web, foo ]
</code>```

You can achieve it using the above code block.

Reference: ansible doc

Body:
I want to import into playbook (and execute) only part of Ansible role defined in tagged block.

E.g. I have role some_role containing 3 blocks of tasks tagged as tag1, tag2 and tag3. I could create playbook that imports whole role:

---
- hosts: some_host
  roles:
    - role: roles/some_role

And then execute it from command line specifying single tag:

$ ansible-playbook -i hosts.yml playbook.yml --tags tag1

But I want to move --tags tag1 part into playbook itself to be able to run that single block without providing tags to ansible-playbook.

Body:
- import_role:
      name: myrole
  tags: [ web, foo ]

- import_tasks: foo.yml
  tags: [ web, foo ]

You can achieve it using the above code block.

Reference: ansible doc


问:
How to configure nginx as basic load balancer
I have a server that I want to setup as a load balancer/reverse proxy.

nginx/1.14.2 running on debian 10

I do not want caching at all, I simply want when people visit the load balancing nginx server it sends the TCP directly to backend servers (based on nginx's ip hash algo) as if they connected to it originally.

I also want to use cloudflare on top of this load balancer for it's CDN and cache.

Here is my current setup:

```<code>upstream backend {
    ip_hash;
    server node1.example.com;
    server node2.example.com;
    keepalive 100;
}

server {
    listen 80;
    listen [::]:80;
    access_log off;

    location / {
        proxy_http_version 1.1;

        proxy_set_header Host $http_host;
        real_ip_header X-Forwarded-For;

        proxy_pass http://backend;
        proxy_redirect off;
        proxy_request_buffering off;
        proxy_buffering off;
    }
}
</code>```

all nodes and the load balancer have this in their conf.d/ (which comes right from cloudflare's recommendation for nginx)

```<code>set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 104.16.0.0/12;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2c0f:f248::/32;
set_real_ip_from 2a06:98c0::/29;
real_ip_header CF-Connecting-IP;
</code>```

Which seem to work fine CF-Connecting-IP is set to the client's Ip.

Issue 1

PHP server running on node1.example.com or node2.example.com is currently reporting the the following  where (a.b.c.d) is the load balancers IP and (w.x.y.z) is the connecting client's IP

```<code>  ["REMOTE_ADDR"]=>  "a.b.c.d"
  ["HTTP_X_FORWARDED_FOR"]=>  "w.x.y.z"
</code>```

I thought the real_ip_header X-Forwarded-For; would use the HTTP_X_FORWARDED_FOR (which comes from cloudflare) and would store it as the real IP, such that php would say REMOTE_ADDR is the same as the HTTP_X_FORWARDED_FOR

So this is what I want

```<code>  ["REMOTE_ADDR"]=> "w.x.y.z"
  ["HTTP_X_FORWARDED_FOR"]=>  "w.x.y.z"
</code>```

How can I accomplish this?

Issue 2

The load balancer is adding the request HTTP header CACHE_CONTROL: max-age=0

Is this correct?  If not, how can I just have the load balancer use whatever CACHE_CONTROL cloudflare sends

Issue 3

The load balancer is making the request HTTP header CONNECTION: closed  but if I access the backend I always get CONNECTION: keep-alive  is this correct?  I set keepalive on the load balancer but it seems to always be closed

答:
Issue 2

The load balancer is adding the request HTTP header
  CACHE_CONTROL: max-age=0 Is this correct? If not, how can I just have
  the load balancer use whatever CACHE_CONTROL cloudflare sends

By default, Nginx's cache does not honour the Cache-Control:no-cache request header,
nor the Pragma:no-cache request header. You must explicitly configure Nginx to bypass
the cache and pass the request onto the origin server when the user agent sends these request headers.

Probably that will help you:

```<code>proxy_cache_bypass $http_pragma;
proxy_cache_bypass $http_cache_control;
</code>```

In this case, the proxy will honour the cache header, sent by the Cloudflare services.

Issue 3

The load balancer is making the request HTTP header CONNECTION: closed but if
  I access the backend I always get CONNECTION: keep-alive is this
  correct? I set keepalive on the load balancer but it seems to always
  be closed

According that docs for http keepalive you should also set:

```<code>proxy_http_version 1.1;
proxy_set_header Connection "";
</code>```

Please note that the default behavior for proxy_http_version is 1.0

And be sure that 100 connection, which you have set is enough keepalive 100;
Because setting too low value could also lead to CONNECTION: closed behavior.

Body:
I have a server that I want to setup as a load balancer/reverse proxy.

nginx/1.14.2 running on debian 10

I do not want caching at all, I simply want when people visit the load balancing nginx server it sends the TCP directly to backend servers (based on nginx's ip hash algo) as if they connected to it originally.

I also want to use cloudflare on top of this load balancer for it's CDN and cache.

Here is my current setup:

upstream backend {
    ip_hash;
    server node1.example.com;
    server node2.example.com;
    keepalive 100;
}

server {
    listen 80;
    listen [::]:80;
    access_log off;

    location / {
        proxy_http_version 1.1;

        proxy_set_header Host $http_host;
        real_ip_header X-Forwarded-For;

        proxy_pass http://backend;
        proxy_redirect off;
        proxy_request_buffering off;
        proxy_buffering off;
    }
}

all nodes and the load balancer have this in their conf.d/ (which comes right from cloudflare's recommendation for nginx)

set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 104.16.0.0/12;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2c0f:f248::/32;
set_real_ip_from 2a06:98c0::/29;
real_ip_header CF-Connecting-IP;

Which seem to work fine CF-Connecting-IP is set to the client's Ip.

Issue 1

PHP server running on node1.example.com or node2.example.com is currently reporting the the following  where (a.b.c.d) is the load balancers IP and (w.x.y.z) is the connecting client's IP

  ["REMOTE_ADDR"]=>  "a.b.c.d"
  ["HTTP_X_FORWARDED_FOR"]=>  "w.x.y.z"

I thought the real_ip_header X-Forwarded-For; would use the HTTP_X_FORWARDED_FOR (which comes from cloudflare) and would store it as the real IP, such that php would say REMOTE_ADDR is the same as the HTTP_X_FORWARDED_FOR

So this is what I want

  ["REMOTE_ADDR"]=> "w.x.y.z"
  ["HTTP_X_FORWARDED_FOR"]=>  "w.x.y.z"

How can I accomplish this?

Issue 2

The load balancer is adding the request HTTP header CACHE_CONTROL: max-age=0

Is this correct?  If not, how can I just have the load balancer use whatever CACHE_CONTROL cloudflare sends

Issue 3

The load balancer is making the request HTTP header CONNECTION: closed  but if I access the backend I always get CONNECTION: keep-alive  is this correct?  I set keepalive on the load balancer but it seems to always be closed

Body:
Issue 2

The load balancer is adding the request HTTP header
  CACHE_CONTROL: max-age=0 Is this correct? If not, how can I just have
  the load balancer use whatever CACHE_CONTROL cloudflare sends

By default, Nginx's cache does not honour the Cache-Control:no-cache request header,
nor the Pragma:no-cache request header. You must explicitly configure Nginx to bypass
the cache and pass the request onto the origin server when the user agent sends these request headers.

Probably that will help you:

proxy_cache_bypass $http_pragma;
proxy_cache_bypass $http_cache_control;

In this case, the proxy will honour the cache header, sent by the Cloudflare services.

Issue 3

The load balancer is making the request HTTP header CONNECTION: closed but if
  I access the backend I always get CONNECTION: keep-alive is this
  correct? I set keepalive on the load balancer but it seems to always
  be closed

According that docs for http keepalive you should also set:

proxy_http_version 1.1;
proxy_set_header Connection "";

Please note that the default behavior for proxy_http_version is 1.0

And be sure that 100 connection, which you have set is enough keepalive 100;
Because setting too low value could also lead to CONNECTION: closed behavior.


问:
Can I use useCallback or useMemo to cache the result of my function?
Let's say there is a function inside a component, for example like this:

```<code>     const MyComponent = ({data}) => {
       const myFunction = a => a+1;
       return <div>
                  data.map(num => myFunction(num))
              </div>
     }
</code>```

I don't want myFunction() to be called again if it already has been called with the same argument.
What is the best practice to add caching here?

答:
No, useCallback and useMemo have different purposes in this specific case read here, you need to create some cache mechanism yourself or take one from 3rd party package:</p>

```<code>const MyComponent = ({data}) => {
  const cacheRef = React.useRef({})
  const myFunction = a => {
    const cache = cacheRef.current;
    if(cache[a]){
      return cache[a];
    } else{
      cache[a] = a+1;
      return cache[a];
    }
  };
  return <div>
          {data.map(num => myFunction(num))}
         </div>
}
</code>```

Body:
Let's say there is a function inside a component, for example like this:

     const MyComponent = ({data}) => {
       const myFunction = a => a+1;
       return

                  data.map(num => myFunction(num))

     }

I don't want myFunction() to be called again if it already has been called with the same argument.
What is the best practice to add caching here?

Body:
No, useCallback and useMemo have different purposes in this specific case read here, you need to create some cache mechanism yourself or take one from 3rd party package:

const MyComponent = ({data}) => {
  const cacheRef = React.useRef({})
  const myFunction = a => {
    const cache = cacheRef.current;
    if(cache[a]){
      return cache[a];
    } else{
      cache[a] = a+1;
      return cache[a];
    }
  };
  return <div>
          {data.map(num => myFunction(num))}
         </div>
}


问:
I have to make the 3 colors (red green blue) cover the original image, but transparently and vertically
The photo produced by my code has just 2 colors, red and blue, but the photo should be covered with 3 colors, red green blue:

How can I do it? I tried a lot, but I couldn't solve the problem. My picture looks like this:

The picture should look like this:

```<code>// write your code here

var img = new SimpleImage('hilton.jpg');
print(img);

var imgW = img.getWidth();
print('Width: ' + imgW);

for (var pixel of img.values()) {

  if (pixel.getX() < imgW / 1.3) {

    pixel.setRed(255);
  } else if ((pixel.getX >= imgW / 1.3) && (pixel.getX <= imgW / 2.3)) {

    pixel.setGreen(255);
  } else if (pixel.getX() > imgW / 2.3) {

    pixel.setBlue(255);
  }
}

print(img);

</code>```

答:
First of all, you're using incorrect divisions to split into thirds. You should be dividing imgW by 3 to split into three segments. Second of all, you typed pixel.getX rather than pixel.getX() in your else if for green pixels, so you were comparing a function to the value rather than the return value of the function:

```<code>var img = new SimpleImage('hilton.jpg');
print(img);

var imgW = img.getWidth();
print('Width: ' + imgW);

for(var pixel of img.values()){
    var third = imgW / 3;

    if(pixel.getX() < third){
        pixel.setRed(255);
    }

    else if((pixel.getX() >= third) && (pixel.getX() <= 2 * third))
    {
        pixel.setGreen(255);
    }

    else if (pixel.getX() > 2 * third){
        pixel.setBlue(255);
    }
}

print(img);
</code>```

Body:
The photo produced by my code has just 2 colors, red and blue, but the photo should be covered with 3 colors, red green blue:

How can I do it? I tried a lot, but I couldn't solve the problem. My picture looks like this:

The picture should look like this:

// write your code here

var img = new SimpleImage('hilton.jpg');
print(img);

var imgW = img.getWidth();
print('Width: ' + imgW);

for (var pixel of img.values()) {

  if (pixel.getX() < imgW / 1.3) {

    pixel.setRed(255);
  } else if ((pixel.getX >= imgW / 1.3) && (pixel.getX <= imgW / 2.3)) {

    pixel.setGreen(255);
  } else if (pixel.getX() > imgW / 2.3) {

    pixel.setBlue(255);
  }
}

print(img);

Body:
First of all, you're using incorrect divisions to split into thirds. You should be dividing imgW by 3 to split into three segments. Second of all, you typed pixel.getX rather than pixel.getX() in your else if for green pixels, so you were comparing a function to the value rather than the return value of the function:

var img = new SimpleImage('hilton.jpg');
print(img);

var imgW = img.getWidth();
print('Width: ' + imgW);

for(var pixel of img.values()){
    var third = imgW / 3;

    if(pixel.getX() < third){
        pixel.setRed(255);
    }

    else if((pixel.getX() >= third) && (pixel.getX() <= 2 * third))
    {
        pixel.setGreen(255);
    }

    else if (pixel.getX() > 2 * third){
        pixel.setBlue(255);
    }
}

print(img);


问:
ReferenceError: render is not defined onChange input React testing library
As a noob I am completely stuck with testing in Jest. Why the terminal is showing referenceErrror, render is not defined. Even when I imported that from @testing-library/react it seems that there is something wrong with my test below. Could some help me pointing to the right direction. I also wrote the SearchBar in a dumb component.

// Searchbar.test.js
import React from 'react'
import { render, fireEvent } from '@testing-library/react';
import { SearchBar } from './SearchBar';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import getData from '../reducers';
import thunk from 'redux-thunk';

const store = createStore(
    getData,
    applyMiddleware(thunk)
);

const setup = () => {
    const utils = render(<Provider store={store}><SearchBar/></Provider>);
    const input = utils.getByLabelText('search-bar');
    return {
        input,
        ...utils
    }
}

test('It should keep a $ in front of the input', () => {
    const { input } = setup()
    fireEvent.change(input, { target: { value: 'search-bar-test' } })
    expect(input.value).toBe('search-bar-test')
})

// SearchBar.js
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import axios from 'axios';
import { generateSearchButtons } from '../actions/index';

export const SearchBar = () => {
    const dispatch = useDispatch();

    useEffect(() => {
        fetchSearchResults()
    })

    const getSearchValue = (e) => {
        const searchResult = e.target.value.toLowerCase();
        fetchSearchResults(searchResult);
    }

    const fetchSearchResults = (query) => {
        if(query == null) {
            query = "";
        }
        const searchUrl = `https://www.themealdb.com/api/json/v1/1/search.php?s=${query}`;

        axios.get(searchUrl)
        .then((res) => {
            dispatch(generateSearchButtons(res.data.meals))
        }).catch((err) => {
            console.log(err);
        })
    }

    return (

            SearchBar
            <input aria-label="search-bar" type="text" onChange={(e) => getSearchValue(e)}/>

    )
}```

答: In your main component file i.e. SearchBar.js you have testing code as well. Remove that from below. See the error trace, the render is not defined error is in SearchBar.js and not in SearchBar.test.js


问:
How to incorporate a variable into a URI?
Basically I'm trying to put a result of a query into a file path, into the image source.

Updated code. Now I actually get the string I want but I still have trouble with interpolating it into the Uri constructor.

```<code> Random rand = new Random();
            var nrand = rand.Next(1, 4);

            using (var db = new DungeonContext())
            {
                var query = db.Rooms.Where(b => b.RoomId == nrand).Select(b => b.RoomName);
                foreach(string name in query)
                {
                    nameOfRoom = name;
                }
            }
</code>```

Somehow I have trouble setting images dir as Resources since I'm missing advancent properties for this folder.

```<code>roomScreen.Source = new BitmapImage(new Uri($"/images/{nameOfRoom}.png", UriKind.Relative));
</code>```

Making Uri relative seemed to stop throwing exceptions, but the intended effect does not happen.

答:
The way you're creating the URI is correct. The trouble is that you're trying to use what is likely meant to be readable text (the name of a room) in a URI and as a flle name. You didn't specify what nameOfRoom is, so I can't tell exactly why it's invalid.

There are ways around it. You could look at this answer which explains how to remove invalid characters from a file name.

But the best solution is not to have the problem. Don't use the name of the room as a file name. Your question indicates that a room has an ID, which is apparently an integer. Using that instead would be much easier:

```<code>using (var db = new DungeonContext())
{
    room = db.Rooms.Where(b => b.RoomId == nrand);
}
</code>```

and then

```<code>roomScreen.Source = new BitmapImage( new Uri($"/images/Room{room.RoomId}.png"));
</code>```

If you want to use your code as-is, that's possible. When you do this:

```<code>nameOfRoom = db.Rooms.Where(b => b.RoomId == nrand).ToString();
</code>```

you're calling ToString() on what is presumably a Room class. Unless you override that method, the result will always be the name of the class. (So it would be the same for every room.)

If you overrode the ToString method:

```<code>public override string ToString()
{
    return $"Room{RoomId}";
}
</code>```

then calling room.ToString() would return "Room1" or "Room2", etc.

String interpolation calls ToString(), so in that case you could just do

roomScreen.Source = new BitmapImage( new Uri($"/images/{room}.png"));

That works. One downside is that it's not explicit. Someone reading that line of code might not know that Room.ToString() is also the value used to create a file name. You might also want to use the ToString() method differently.

If you wanted to be really explicit and clear, you could create an extension method like this:

```<code>public static class RoomFileNameExtensions
{
    public static string GetImageFileName(this Room room)
    {
        return $"Room{room.RoomId}.png";
    }
}
</code>```

Now the Room class isn't responsible for knowing how file names are created. You could do this:

roomScreen.Source = new BitmapImage( new Uri($"/images/{room.GetImageFileName()}"));

You can use that both when creating the file and when reading the file. It ensures that both operations will determine the file name the same way.

Body:
Basically I'm trying to put a result of a query into a file path, into the image source.

Updated code. Now I actually get the string I want but I still have trouble with interpolating it into the Uri constructor.

 Random rand = new Random();
            var nrand = rand.Next(1, 4);

            using (var db = new DungeonContext())
            {
                var query = db.Rooms.Where(b => b.RoomId == nrand).Select(b => b.RoomName);
                foreach(string name in query)
                {
                    nameOfRoom = name;
                }
            }

Somehow I have trouble setting images dir as Resources since I'm missing advancent properties for this folder.

roomScreen.Source = new BitmapImage(new Uri($"/images/{nameOfRoom}.png", UriKind.Relative));

Making Uri relative seemed to stop throwing exceptions, but the intended effect does not happen.

Body:
The way you're creating the URI is correct. The trouble is that you're trying to use what is likely meant to be readable text (the name of a room) in a URI and as a flle name. You didn't specify what nameOfRoom is, so I can't tell exactly why it's invalid.

There are ways around it. You could look at this answer which explains how to remove invalid characters from a file name.

But the best solution is not to have the problem. Don't use the name of the room as a file name. Your question indicates that a room has an ID, which is apparently an integer. Using that instead would be much easier:

using (var db = new DungeonContext())
{
    room = db.Rooms.Where(b => b.RoomId == nrand);
}

and then

roomScreen.Source = new BitmapImage( new Uri($"/images/Room{room.RoomId}.png"));

If you want to use your code as-is, that's possible. When you do this:

nameOfRoom = db.Rooms.Where(b => b.RoomId == nrand).ToString();

you're calling ToString() on what is presumably a Room class. Unless you override that method, the result will always be the name of the class. (So it would be the same for every room.)

If you overrode the ToString method:

public override string ToString()
{
    return $"Room{RoomId}";
}

then calling room.ToString() would return "Room1" or "Room2", etc.

String interpolation calls ToString(), so in that case you could just do

roomScreen.Source = new BitmapImage( new Uri($"/images/{room}.png"));

That works. One downside is that it's not explicit. Someone reading that line of code might not know that Room.ToString() is also the value used to create a file name. You might also want to use the ToString() method differently.

If you wanted to be really explicit and clear, you could create an extension method like this:

public static class RoomFileNameExtensions
{
    public static string GetImageFileName(this Room room)
    {
        return $"Room{room.RoomId}.png";
    }
}

Now the Room class isn't responsible for knowing how file names are created. You could do this:

roomScreen.Source = new BitmapImage( new Uri($"/images/{room.GetImageFileName()}"));

You can use that both when creating the file and when reading the file. It ensures that both operations will determine the file name the same way.


问:
close the application when session is idle for more than 10mins
I want to close the application when my application is idle for more than 10 min.Any one have idea.Give me some solutions.Thanks in adavance</p>

答:
you dealt with this by using the AlarmManager to schedule and cancel timeout action.

Then in the onPause() event of all of your activites, I schedule the alarm. In the onResume() event of all of your activities, You have to check to see if the alarm goes off. If the alarm went off, you will finish your app. If the alarm hasn't gone off yet you cancel it.

You have to create Timeout.java to manage my alarms. When the alarm goes off a intent is fired:

Have a look on the following URL

Lock android app after a certain amount of idle time

Thnaks
Deepak


问:
I'm not able to create react app by “create-react-app”
Getting this on console</p>

```<code>> core-js@2.6.11 postinstall G:\mernbootcamp\testfront\my-app\node_modules\babel-runtime\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"

Aborting installation.
  npm install --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed.

Deleting generated file... node_modules
Deleting generated file... package.json
Deleting my-app/ from G:\mernbootcamp\testfront
Done.
</code>```

答:
the issue is: now we cannot create react app globally. It could be possible that you have some old version installed.

Unstall first

```<code>npm uninstall -g create-react-app
</code>```

Then navigate to your folder where you want to create the react app.
and write this command:

```<code>npx create-react-app my-app

</code>```

Body:
Getting this on console

> core-js@2.6.11 postinstall G:\mernbootcamp\testfront\my-app\node_modules\babel-runtime\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"

Aborting installation.
  npm install --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed.

Deleting generated file... node_modules
Deleting generated file... package.json
Deleting my-app/ from G:\mernbootcamp\testfront
Done.

Body:
the issue is: now we cannot create react app globally. It could be possible that you have some old version installed.

Unstall first

npm uninstall -g create-react-app

Then navigate to your folder where you want to create the react app.
and write this command:

npx create-react-app my-app


问:
Is it possible to make an interface method return the type of another method with a generic type parameters in C#?
So I'm trying to create some fluent code to execute a web request. I want it to look something like this...

```<code>// Result should be of type MyClass
var result = await _webRequests.Get("Api/Route/Here")
                               .Returns<MyClass>()
                               .HasToken("MY_TOKEN")
                               .ExecuteAsync();

// Result should be of type HttpResponseMessage
var result = await _webRequests.Get("Api/Route/Here")
                               .HasToken("MY_TOKEN")
                               .ExecuteAsync();
</code>```

I'm aiming to get it so that if the Returns method is not specified, then it returns a HttpResponseMessage and if it is specified, it returns the type specified.

_webRequests is an interface with some basic HttpMethod calls in there

```<code>IUseRequired Get(string url);
IUseRequired Post(string url);
</code>```

Then the IUseRequired interface has the required methods for the call...

```<code>IUseOptionalOrExecute UsesApi(string apiName);
</code>```

All the UsesApi method does is tell which HTTPClient to use when using IHttpClientFactory.

Now the IUseOptionalOrExecute interface is where the problem starts...

```<code>IUseOptionalOrExecute Returns<TReturn>();
IUseOptionalOrExecute HasToken(string token);
Task<TReturn> ExecuteAsync();
</code>```

I want it to look something like this, so whatever is passed in to the Returns method will be used as the return of the ExecuteAsync method. Of course this doesn't work, because ExecuteAsync has no idea what TReturn is. I've thought about storing the type as a variable when the Returns method is called, but I can't set the return type of Execute to be a variable type. Or can I?
Anyone know a way I can get around this? Thanks!

答:
Is there a good reason for the existence of the Returns<TReturn> function ?

When I implemented my HTTP client I had the return type specified on the ExecuteAsync<TReturn>, since there was no need to know the type beforehand and thus I avoided solving you issue.

If you need the type for some reason, I think you might need to do IUseOptionalOrExecute<TReturn> Returns<TReturn>(); and deal with all the necessary complications.

I can expand on that if ExecuteAsync<TReturn> is not enough to solve your issue.

Body:
So I'm trying to create some fluent code to execute a web request. I want it to look something like this...

// Result should be of type MyClass
var result = await _webRequests.Get("Api/Route/Here")
                               .Returns<MyClass>()
                               .HasToken("MY_TOKEN")
                               .ExecuteAsync();

// Result should be of type HttpResponseMessage
var result = await _webRequests.Get("Api/Route/Here")
                               .HasToken("MY_TOKEN")
                               .ExecuteAsync();

I'm aiming to get it so that if the Returns method is not specified, then it returns a HttpResponseMessage and if it is specified, it returns the type specified.

_webRequests is an interface with some basic HttpMethod calls in there

IUseRequired Get(string url);
IUseRequired Post(string url);

Then the IUseRequired interface has the required methods for the call...

IUseOptionalOrExecute UsesApi(string apiName);

All the UsesApi method does is tell which HTTPClient to use when using IHttpClientFactory.

Now the IUseOptionalOrExecute interface is where the problem starts...

IUseOptionalOrExecute Returns<TReturn>();
IUseOptionalOrExecute HasToken(string token);
Task<TReturn> ExecuteAsync();

I want it to look something like this, so whatever is passed in to the Returns method will be used as the return of the ExecuteAsync method. Of course this doesn't work, because ExecuteAsync has no idea what TReturn is. I've thought about storing the type as a variable when the Returns method is called, but I can't set the return type of Execute to be a variable type. Or can I?
Anyone know a way I can get around this? Thanks!


问:
C++ Multithreading - Writing to different keys in same map causing problems
I have the following function running several times on 6 different threads, with the same nodeMap being passed to each function. I'm sure that the keys being read and written to on each thread are independent (no two threads will have the same histories). Despite this, occasionally this code will output "Preposterous". When working with one thread, this would be impossible, as if nodeMap didn't contain histories[state.currentPlayer], then a node with that key would be added to the map, and it would be found in the last if statement.

```<code>double cfr(std::unordered_map<InfosetHistory, Node>& nodeMap, State& state, const InfosetHistory* histories,
           unsigned char player, std::ranlux24_base& randEngine) {
    ...

    // Find node or create it if it doesn't exist
    if (nodeMap.find(histories[state.currentPlayer]) == nodeMap.end()) {
        if (state.phase == State::DRAW) {
            nodeMap.insert(std::make_pair(histories[state.currentPlayer], Node(state.drawOnlyFromDiscard())));
        } else {
            nodeMap.insert(std::make_pair(histories[state.currentPlayer], Node(state.getAllowedDiscardOptions())));
        }
    }
    if(nodeMap.find(histories[state.currentPlayer]) == nodeMap.end())
        std::cout << "Preposterous" << std::endl;
    ...
</code>```

I'm new to multithreading, so I'm assuming that somehow accessing the same map object from multiple threads is causing problems. I read that as long as the keys are independent, multithreading shouldn't create issues, so I'm unsure what I'm missing.

Any help would be appreciated.

答:
Thanks to everyone in the comments for helping me understand where I was wrong.

I created the following minimal reproducible example to test the issue:

```<code>#include <iostream>
#include <thread>
#include <unordered_map>

const int NUM_THREADS = 6;

void test(std::unordered_map<int, int>& map, int thread) {
    for(int i = thread; i < 1000; i += NUM_THREADS) {
        if (map.find(i) == map.end())
            map.insert(std::make_pair(i, i * i));
        if (map.find(i) == map.end())
            std::cout << "Preposterous" << std::endl;
    }
}

int main() {
    std::unordered_map<int, int> map;

    std::thread threads[NUM_THREADS];
    for(int core = 0; core < NUM_THREADS; core++){
        threads[core] = std::thread(test, std::ref(map), core);
    }
    for(auto & thread : threads){
        thread.join();
    }
    return 0;
}
</code>```

Here 6 threads are running test passing a reference to a map and a thread number. Each thread is writing to independent keys in map (thread 0 writes to i = 0, 6, 12, ...; thread 1 writes to i = 1, 7, 13, ...; and so on). Despite this, the code still leads to undefined behavior, and "Preposterous" is occasionally printed.

The issue is as @SamVarshavchik explained. C++ library containers are not thread safe. Even if the keys are different, when updating maps, maps are not thread safe, and trying to update them on multiple threads leads to undefined behavior.

For my context, since the keys are independent, I'm considering creating maps for each set of independent keys, and then only passing the map that will be changed to a thread when it needs to be changed. As a result, no thread will ever be changing the same map.

Thanks for all the help!

Body:
I have the following function running several times on 6 different threads, with the same nodeMap being passed to each function. I'm sure that the keys being read and written to on each thread are independent (no two threads will have the same histories). Despite this, occasionally this code will output "Preposterous". When working with one thread, this would be impossible, as if nodeMap didn't contain histories[state.currentPlayer], then a node with that key would be added to the map, and it would be found in the last if statement.

double cfr(std::unordered_map<InfosetHistory, Node>& nodeMap, State& state, const InfosetHistory* histories,
           unsigned char player, std::ranlux24_base& randEngine) {
    ...

    // Find node or create it if it doesn't exist
    if (nodeMap.find(histories[state.currentPlayer]) == nodeMap.end()) {
        if (state.phase == State::DRAW) {
            nodeMap.insert(std::make_pair(histories[state.currentPlayer], Node(state.drawOnlyFromDiscard())));
        } else {
            nodeMap.insert(std::make_pair(histories[state.currentPlayer], Node(state.getAllowedDiscardOptions())));
        }
    }
    if(nodeMap.find(histories[state.currentPlayer]) == nodeMap.end())
        std::cout << "Preposterous" << std::endl;
    ...

I'm new to multithreading, so I'm assuming that somehow accessing the same map object from multiple threads is causing problems. I read that as long as the keys are independent, multithreading shouldn't create issues, so I'm unsure what I'm missing.

Any help would be appreciated.

Body:
Thanks to everyone in the comments for helping me understand where I was wrong.

I created the following minimal reproducible example to test the issue:

#include <iostream>
#include <thread>
#include <unordered_map>

const int NUM_THREADS = 6;

void test(std::unordered_map<int, int>& map, int thread) {
    for(int i = thread; i < 1000; i += NUM_THREADS) {
        if (map.find(i) == map.end())
            map.insert(std::make_pair(i, i * i));
        if (map.find(i) == map.end())
            std::cout << "Preposterous" << std::endl;
    }
}

int main() {
    std::unordered_map<int, int> map;

    std::thread threads[NUM_THREADS];
    for(int core = 0; core < NUM_THREADS; core++){
        threads[core] = std::thread(test, std::ref(map), core);
    }
    for(auto & thread : threads){
        thread.join();
    }
    return 0;
}

Here 6 threads are running test passing a reference to a map and a thread number. Each thread is writing to independent keys in map (thread 0 writes to i = 0, 6, 12, ...; thread 1 writes to i = 1, 7, 13, ...; and so on). Despite this, the code still leads to undefined behavior, and "Preposterous" is occasionally printed.

The issue is as @SamVarshavchik explained. C++ library containers are not thread safe. Even if the keys are different, when updating maps, maps are not thread safe, and trying to update them on multiple threads leads to undefined behavior.

For my context, since the keys are independent, I'm considering creating maps for each set of independent keys, and then only passing the map that will be changed to a thread when it needs to be changed. As a result, no thread will ever be changing the same map.

Thanks for all the help!


问:
Instability found in Julia 1.4.1: repeated array constructions cause next "print" or "println" call to break at random
Instability found in Julia 1.4.1 (2020-04-14). (JuliaPro, 64-bit Windows 10, in Juno).

After 3 hours, I've isolated a few minimum working examples:

```<code>using LinearAlgebra
for i in 1:5000000
    [1 2 3; 2 3 4; 3 4 5]
end
print("ONE")
print("TWO")
</code>```

Sometimes "ONE" will print, and sometimes "ONETWO" will print, after running the same code block repeatedly. Changing the code slightly will still work -- for example:

```<code>using LinearAlgebra
for i in 1:1000000
    ones(2,2)-I
end
println("ONE")
println("TWO")
</code>```

This will usually print only "TWO", but sometimes print both.

It isn't just the LinearAlgebra package, either. I got the same error to work with this code (in a fresh Juno session):

```<code>for i in 1:10000000
    [1 1 1; 2 3 4; 1 1 1]
end
println("ONE")
println("TWO")
</code>```

And with this code:

```<code>for i in 1:100000000
    [1]
end
println("ONE")
println("TWO")
</code>```

It only printed "TWO". Changing the maximum of i will result in print or println breaking more often. E. g., after setting it to 50,000 it might take 20 calls of the loop before seeing only a "TWO" instead of a "ONETWO", but setting it to 100,000,000 it will work almost every time. I also noticed that using ones(x,x) resulted in errors more easily. The inconsistency is the strangest part of the whole thing.

I haven't yet tested a different version of Julia since the website has been giving me trouble for the last few hours, but it would be very interesting to know why this is happening and if it happens for anyone else.

答:
I managed to replicate this behavior. This looks like a buffering issue in Juno. I guess you can submit this as a bug.

Meanwhile just use flush(stdout) to flush the standard output such as:

```<code>for i in 1:10000000
    [1 1 1; 2 3 4; 1 1 1]
end
flush(stdout)
println("ONE")
println("TWO")
</code>```

Basically, flushing from time to time the standard output in long running jobs is usually quite useful in many cases (e.g. your job suddenly gets interrupted and you want to know when it ended).

Body:
Instability found in Julia 1.4.1 (2020-04-14). (JuliaPro, 64-bit Windows 10, in Juno).

After 3 hours, I've isolated a few minimum working examples:

using LinearAlgebra
for i in 1:5000000
    [1 2 3; 2 3 4; 3 4 5]
end
print("ONE")
print("TWO")

Sometimes "ONE" will print, and sometimes "ONETWO" will print, after running the same code block repeatedly. Changing the code slightly will still work -- for example:

using LinearAlgebra
for i in 1:1000000
    ones(2,2)-I
end
println("ONE")
println("TWO")

This will usually print only "TWO", but sometimes print both.

It isn't just the LinearAlgebra package, either. I got the same error to work with this code (in a fresh Juno session):

for i in 1:10000000
    [1 1 1; 2 3 4; 1 1 1]
end
println("ONE")
println("TWO")

And with this code:

for i in 1:100000000
    [1]
end
println("ONE")
println("TWO")

It only printed "TWO". Changing the maximum of i will result in print or println breaking more often. E. g., after setting it to 50,000 it might take 20 calls of the loop before seeing only a "TWO" instead of a "ONETWO", but setting it to 100,000,000 it will work almost every time. I also noticed that using ones(x,x) resulted in errors more easily. The inconsistency is the strangest part of the whole thing.

I haven't yet tested a different version of Julia since the website has been giving me trouble for the last few hours, but it would be very interesting to know why this is happening and if it happens for anyone else.

Body:
I managed to replicate this behavior. This looks like a buffering issue in Juno. I guess you can submit this as a bug.

Meanwhile just use flush(stdout) to flush the standard output such as:

for i in 1:10000000
    [1 1 1; 2 3 4; 1 1 1]
end
flush(stdout)
println("ONE")
println("TWO")

Basically, flushing from time to time the standard output in long running jobs is usually quite useful in many cases (e.g. your job suddenly gets interrupted and you want to know when it ended).