问:
Python Calculator and understanding input errors:
I've created a small calculator in python which picks up input errors,  although it only runs once.
I was wondering is there a better way of doing this using While loop or If-else statements rather than using try-catch all the time.  As try-except should only be used in exceptional circumstances -

What I want is when user inputs an incorrect number, i.e. a string.  It errors out and asks again,
the user inputs again the correct number and it works.  But using a while loop or If-statement instead of try-except

The below program works fine although it only runs once,  can you make it continously loop after it finishes.  I can add the other operators in later...

Thanks,

```<code>answer = True

while answer:
    try:
        num1 = int(input ("Enter first number: "))
        break
    except:
        pass
        print ("Please try again: ")

operator = input ("")
num2 = int (input ("Enter second number: "))

if (operator == '+'):
    print (num1 + num2)
answer = False
</code>```

答:
1. Using try/except is correct. Invalid user input is an "exceptional circumstance".

Your code already asks the user over and over for input until they provide a valid input (for the first number). This is correct. You don't need the answer variable, since it's not being used anyway. You can just use while True:

```<code>while True:
    try:
        num1 = int(input ("Enter first number: "))
        break
    except:
        print ("Please try again: ") # You don't need 'pass'
</code>```

You can do this for each input. Also, you can place that code inside a function (e.g. read_number()) and call it for both numeric inputs.

2. To make the program restart after it is over, place the whole thing inside a while True loop:

```<code> while True:
    # Your program here
</code>```

To make things more organized, you can put your calculator code inside a function, and call that function inside the while True loop:

```<code>def calculator():
    while True:
        try:
            num1 = int(input ("Enter first number: "))
            break
        except:
            print ("Please try again: ")

    operator = input ("")

    while True:
        try:
            num2 = int(input ("Enter second number: "))
            break
        except:
            print ("Please try again: ")

    if (operator == '+'):
        print (num1 + num2)

# main program
while True:
    calculator()
</code>```

Body:
I've created a small calculator in python which picks up input errors,  although it only runs once.
I was wondering is there a better way of doing this using While loop or If-else statements rather than using try-catch all the time.  As try-except should only be used in exceptional circumstances -

What I want is when user inputs an incorrect number, i.e. a string.  It errors out and asks again,
the user inputs again the correct number and it works.  But using a while loop or If-statement instead of try-except

The below program works fine although it only runs once,  can you make it continously loop after it finishes.  I can add the other operators in later...

Thanks,

answer = True

while answer:
    try:
        num1 = int(input ("Enter first number: "))
        break
    except:
        pass
        print ("Please try again: ")

operator = input ("")
num2 = int (input ("Enter second number: "))

if (operator == '+'):
    print (num1 + num2)
answer = False

Body:
1. Using try/except is correct. Invalid user input is an "exceptional circumstance".

Your code already asks the user over and over for input until they provide a valid input (for the first number). This is correct. You don't need the answer variable, since it's not being used anyway. You can just use while True:

while True:
    try:
        num1 = int(input ("Enter first number: "))
        break
    except:
        print ("Please try again: ") # You don't need 'pass'

You can do this for each input. Also, you can place that code inside a function (e.g. read_number()) and call it for both numeric inputs.

2. To make the program restart after it is over, place the whole thing inside a while True loop:

 while True:
    # Your program here

To make things more organized, you can put your calculator code inside a function, and call that function inside the while True loop:

def calculator():
    while True:
        try:
            num1 = int(input ("Enter first number: "))
            break
        except:
            print ("Please try again: ")

    operator = input ("")

    while True:
        try:
            num2 = int(input ("Enter second number: "))
            break
        except:
            print ("Please try again: ")

    if (operator == '+'):
        print (num1 + num2)

# main program
while True:
    calculator()


来源: stackexchange

问:
I am applying float to only one element inside a container, yet the CSS applies to all the elements?

.overflow-test {
  background-color: pink;
}

.float-test {
  float: left;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="overflow-test">

  <button class="float-test">News</button>
  <button>About</button>

</div></code>```

I have only targeted the class inside the first button element, yet the CSS applies to both buttons. Why?

答:
Your About-button is not floated left like your News button. Instead, a button element seems to have a default CSS display value of inline-block. Any inline or inline-block elements will behave just like text within their containing element. Therefore, your About-button is placed at the right of the left-floating News-button. Just like text.

.overflow-test {
  background-color: pink;
}

.float-test {
  float: left;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="overflow-test">

  <button class="float-test">News</button>
  Bla bla bla...
  <button>About</button>
  More bla bla bla...
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
.overflow-test {
  background-color: pink;
}

.float-test {
  float: left;
  background-color: red;
}

  <button class="float-test">News</button>
  <button>About</button>

I have only targeted the class inside the first button element, yet the CSS applies to both buttons. Why?

Body:
Your About-button is not floated left like your News button. Instead, a button element seems to have a default CSS display value of inline-block. Any inline or inline-block elements will behave just like text within their containing element. Therefore, your About-button is placed at the right of the left-floating News-button. Just like text.

.overflow-test {
  background-color: pink;
}

.float-test {
  float: left;
  background-color: red;
}

<div class="overflow-test">

  <button class="float-test">News</button>
  Bla bla bla...
  <button>About</button>
  More bla bla bla...
</div>


问:
extract mean of circle patche in python
i have some X/Y coordinates that represent the center of a circle somewhere in an image. From that circle, i want to compoute the mean of all the point contained inside the circle.

currently, i compute the mean of a square patche as follow, but a square is not relevent for the project. Ideally, i would like to do it only with numpy. but if it is not possible, i would concidere something else.

```<code>mean = np.mean(image[Y - margin : Y + margin, X - margin, X + margin])
</code>```

答:
As I understood,

YOU HAVE: (x,y) of the center of the circle

YOU WANT: mean of all the points contained in the circle

Since all the points on the right side should be equal to the number of points on the left side of the center, Wouldn't the mean be the same as the center of the circle !?

Title: extract mean of circle patche in python

Body:
i have some X/Y coordinates that represent the center of a circle somewhere in an image. From that circle, i want to compoute the mean of all the point contained inside the circle.

currently, i compute the mean of a square patche as follow, but a square is not relevent for the project. Ideally, i would like to do it only with numpy. but if it is not possible, i would concidere something else.

mean = np.mean(image[Y - margin : Y + margin, X - margin, X + margin])


问:
How can I get NLog to inject dependencies into a target?
I have a custom NLog log target class that looks like this:

```<code>public class MyTarget : AsyncTaskTarget
{
   public MyTarget() {}

   public MyTarget(INeedThisThingToFunction thing)
   {
      Thing = thing;
   }

   public INeedThisThingToFunction Thing { get; set; }

   public override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken)
   {
      Thing.Use();
      return null;
   }
}
</code>```

I cannot figure out how to ensure that the second constructor gets called. I've done this in Program.cs:

```<code>public static void Main(string[] args)
{
   var host = CreateWebHostBuilder(args).Build();
   ConfigureLogging(host.Services.GetAutofacRoot());
   LogManager.GetCurrentClassLogger().Info("Hi mom");
   host.Run();
}

private static void ConfigureLogging(IComponentContext container) {
   ConfigurationItemFactory.Default.CreateInstance = type =>
   {
      if (type != typeof(MyTarget) return Activator.CreateInstance(type);
      var thing = new ThingTheTargetNeedsToFunction();
      return new MyTarget(thing);
   }
   LogManager.Configuration.Reload();
}
</code>```

I've tried a number of other things, too, but that comes the closest to doing something. When LogManager.Configuration.Reload() is called, the CreateInstance code fires; but when the Info method fires, the Thing property on the target is null.

Is there a better way to do this? Like, a way that works?

Using .NET Core 3, NLog, Autofac.

答:
If the Thing is only available after having built the host, then you can do it like this:

```<code>public static void Main(string[] args)
{
   var host = CreateWebHostBuilder(args).UseNLog().Build();
   ConfigureLogging(host.Services.GetAutofacRoot());
   LogManager.GetCurrentClassLogger().Info("Hi mom");
   host.Run();
}

private static void ConfigureLogging(IComponentContext container)
{
   var defaultConstructor = ConfigurationItemFactory.Default.CreateInstance;
   ConfigurationItemFactory.Default.CreateInstance.CreateInstance = type =>
   {
      if (type == typeof(MyTarget))
      {
          var thing = new ThingTheTargetNeedsToFunction();
          return new MyTarget(thing);
      }

      return defaultConstructor(type);
   };

   // Reload config and assign the newly reloaded config
   LogManager.Configuration = LogManager.Configuration?.Reload();
}
</code>```

Then make sure that your custom MyTarget can handle that it is running in "disabled mode" where Thing is unassigned:

```<code>[Target("MyTarget")]
public class MyTarget : AsyncTaskTarget
{
   public MyTarget() {}

   public MyTarget(INeedThisThingToFunction thing)
   {
      Thing = thing;
   }

   public INeedThisThingToFunction Thing { get; set; }

   public override await Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken)
   {
      if (Thing == null)
         return null; // Handle that `Thing` is unassigned by default-constructor

      await Thing.UseAsync().ConfigureAwait(false);
   }
}
</code>```

Body:
I have a custom NLog log target class that looks like this:

public class MyTarget : AsyncTaskTarget
{
   public MyTarget() {}

   public MyTarget(INeedThisThingToFunction thing)
   {
      Thing = thing;
   }

   public INeedThisThingToFunction Thing { get; set; }

   public override Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken)
   {
      Thing.Use();
      return null;
   }
}

I cannot figure out how to ensure that the second constructor gets called. I've done this in Program.cs:

public static void Main(string[] args)
{
   var host = CreateWebHostBuilder(args).Build();
   ConfigureLogging(host.Services.GetAutofacRoot());
   LogManager.GetCurrentClassLogger().Info("Hi mom");
   host.Run();
}

private static void ConfigureLogging(IComponentContext container) {
   ConfigurationItemFactory.Default.CreateInstance = type =>
   {
      if (type != typeof(MyTarget) return Activator.CreateInstance(type);
      var thing = new ThingTheTargetNeedsToFunction();
      return new MyTarget(thing);
   }
   LogManager.Configuration.Reload();
}

I've tried a number of other things, too, but that comes the closest to doing something. When LogManager.Configuration.Reload() is called, the CreateInstance code fires; but when the Info method fires, the Thing property on the target is null.

Is there a better way to do this? Like, a way that works?

Using .NET Core 3, NLog, Autofac.

Body:
If the Thing is only available after having built the host, then you can do it like this:

public static void Main(string[] args)
{
   var host = CreateWebHostBuilder(args).UseNLog().Build();
   ConfigureLogging(host.Services.GetAutofacRoot());
   LogManager.GetCurrentClassLogger().Info("Hi mom");
   host.Run();
}

private static void ConfigureLogging(IComponentContext container)
{
   var defaultConstructor = ConfigurationItemFactory.Default.CreateInstance;
   ConfigurationItemFactory.Default.CreateInstance.CreateInstance = type =>
   {
      if (type == typeof(MyTarget))
      {
          var thing = new ThingTheTargetNeedsToFunction();
          return new MyTarget(thing);
      }

      return defaultConstructor(type);
   };

   // Reload config and assign the newly reloaded config
   LogManager.Configuration = LogManager.Configuration?.Reload();
}

Then make sure that your custom MyTarget can handle that it is running in "disabled mode" where Thing is unassigned:

[Target("MyTarget")]
public class MyTarget : AsyncTaskTarget
{
   public MyTarget() {}

   public MyTarget(INeedThisThingToFunction thing)
   {
      Thing = thing;
   }

   public INeedThisThingToFunction Thing { get; set; }

   public override await Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken)
   {
      if (Thing == null)
         return null; // Handle that `Thing` is unassigned by default-constructor

      await Thing.UseAsync().ConfigureAwait(false);
   }
}


问:
Not splitting a string properly in scala
I have a string:

```<code>var string = "PRODUCTIDENTIFIER|UTLEVEL10|UTLEVEL10DESCRIPTION|UTLEVEL15|UTLEVEL15DESCRIPTION|UTLEVEL17|UTLEVEL17DESCRIPTION|UTLEVEL20|UTLEVEL20DESCRIPTION|UTLEVEL30|UTLEVEL30DESCRIPTION|ACCT_YR|UTCODE"
</code>```

When I try to do string.split("|"), it ends up giving me all the letters of all words in an array like:

```<code>scala> string.split("|")
res0: Array[String] = Array(|, P, R, O, D, U, C, T, I, D, E, N, T, I, F, I, E, R, |, U, T, L, E, V, E, L, 1, 0, |, U, T, L, E, V, E, L, 1, 0, D, E, S, C, R, I, P, T, I, O, N, |, U, T, L, E, V, E, L, 1, 5, |, U, T, L, E, V, E, L, 1, 5, D, E, S, C, R, I, P, T, I, O, N, |, U, T, L, E, V, E, L, 1, 7, |, U, T, L, E, V, E, L, 1, 7, D, E, S, C, R, I, P, T, I, O, N, |, U, T, L, E, V, E, L, 2, 0, |, U, T, L, E, V, E, L, 2, 0, D, E, S, C, R, I, P, T, I, O, N, |, U, T, L, E, V, E, L, 3, 0, |, U, T, L, E, V, E, L, 3, 0, D, E, S, C, R, I, P, T, I, O, N, |, A, C, C, T, _, Y, R, |, U, T, C, O, D, E)
</code>```

What I actually expected was the string will be split based on the | mark. Any idea as to why this does not work?

答:
You need to escape it:</p>

```<code>scala> string.split("\\|")
res0: Array[String] = Array(PRODUCTIDENTIFIER, UTLEVEL10, UTLEVEL10DESCRIPTION, UTLEVEL15, UTLEVEL15DESCRIPTION, UTLEVEL17, UTLEVEL17DESCRIPTION, UTLEVEL20, UTLEVEL20DESCRIPTION, UTLEVEL30, UTLEVEL30DESCRIPTION, ACCT_YR, UTCODE)
</code>```

Body:
I have a string:

var string = "PRODUCTIDENTIFIER|UTLEVEL10|UTLEVEL10DESCRIPTION|UTLEVEL15|UTLEVEL15DESCRIPTION|UTLEVEL17|UTLEVEL17DESCRIPTION|UTLEVEL20|UTLEVEL20DESCRIPTION|UTLEVEL30|UTLEVEL30DESCRIPTION|ACCT_YR|UTCODE"

When I try to do string.split("|"), it ends up giving me all the letters of all words in an array like:

scala> string.split("|")
res0: Array[String] = Array(|, P, R, O, D, U, C, T, I, D, E, N, T, I, F, I, E, R, |, U, T, L, E, V, E, L, 1, 0, |, U, T, L, E, V, E, L, 1, 0, D, E, S, C, R, I, P, T, I, O, N, |, U, T, L, E, V, E, L, 1, 5, |, U, T, L, E, V, E, L, 1, 5, D, E, S, C, R, I, P, T, I, O, N, |, U, T, L, E, V, E, L, 1, 7, |, U, T, L, E, V, E, L, 1, 7, D, E, S, C, R, I, P, T, I, O, N, |, U, T, L, E, V, E, L, 2, 0, |, U, T, L, E, V, E, L, 2, 0, D, E, S, C, R, I, P, T, I, O, N, |, U, T, L, E, V, E, L, 3, 0, |, U, T, L, E, V, E, L, 3, 0, D, E, S, C, R, I, P, T, I, O, N, |, A, C, C, T, _, Y, R, |, U, T, C, O, D, E)

What I actually expected was the string will be split based on the | mark. Any idea as to why this does not work?

Body:
You need to escape it:

scala> string.split("\\|")
res0: Array[String] = Array(PRODUCTIDENTIFIER, UTLEVEL10, UTLEVEL10DESCRIPTION, UTLEVEL15, UTLEVEL15DESCRIPTION, UTLEVEL17, UTLEVEL17DESCRIPTION, UTLEVEL20, UTLEVEL20DESCRIPTION, UTLEVEL30, UTLEVEL30DESCRIPTION, ACCT_YR, UTCODE)


问:
Using class in another class easily with an example
I have a php class that tells time like this (Time.class.php):

```<code><?PHP
class Time {
    var $timestamp;
    function timestamp () {
    $this->timestamp = date('YmdHis');
    return $this->timestamp;
    }
}
?>
</code>```

What I want to do is to call this time in a different class such as (Test.class.php):

```<code><?PHP
class Test {
    function test (){
    $timestamp = ' '; // <--- the timestamp from the other class
    $hourago = $timestamp - 10000;
    return $hourago;
    }
}
?>
</code>```

I'm new to PHP classes so I didn't understand what I've read on this subject. From what I've read this can be done with global scope (if its called a scope)?? If you could only show me how to use globals or how to solve a problem like this easily I would appreciate it...

答:
You need to create an instance of the Time class first, then call the method on that instance.

```<code>$mytime = new Time();
$timestamp = $mytime->timestamp();
</code>```

Alternately you could look at static class methods.

ContentLicense: CC BY-SA 3.0

Body:
I have a php class that tells time like this (Time.class.php):

<?PHP
class Time {
    var $timestamp;
    function timestamp () {
    $this->timestamp = date('YmdHis');
    return $this->timestamp;
    }
}
?>

What I want to do is to call this time in a different class such as (Test.class.php):

<?PHP
class Test {
    function test (){
    $timestamp = ' '; // <--- the timestamp from the other class
    $hourago = $timestamp - 10000;
    return $hourago;
    }
}
?>

I'm new to PHP classes so I didn't understand what I've read on this subject. From what I've read this can be done with global scope (if its called a scope)?? If you could only show me how to use globals or how to solve a problem like this easily I would appreciate it...

Body:
You need to create an instance of the Time class first, then call the method on that instance.

$mytime = new Time();
$timestamp = $mytime->timestamp();

Alternately you could look at static class methods.


问:
Iterate through an array of characters in C
Recently I saw this while loop condition in C in the example below but I have no idea what the while condition really means and how the compiler knows when it is done. Could someone explain it to me?

This is what I believe it means: while loop iterates through the char array until the ending of the array since there is nothing else then the while loop ends, or am I wrong? I tried to use the same while loop but in another language such as Go, however, the compiler threw an error saying that I cannot use a non-bool.

```<code>// C program to demonstrate
// example of tolower() function.

#include <ctype.h>
#include <stdio.h>

int main()
{
    int j = 0;
    char str[] = "GEEKSFORGEEKS\n";

    // Character to be converted to lowercase
    char ch = 'G';

    // convert ch to lowercase using toLower()
    char ch;

    while (str[j]) { // <- this part, how is this a condition?
        ch = str[j];

        // convert ch to lowercase using toLower()
        putchar(tolower(ch));

        j++;
    }

    return 0;
}
</code>```

答:
the while loop can be understood as "while this string has characters" and as known in C strings or an array of chars contain a '\0' => Null character, in the end, once the while loop achieves it, it will stop the iteration.

So yeap! you are right.

Body:
Recently I saw this while loop condition in C in the example below but I have no idea what the while condition really means and how the compiler knows when it is done. Could someone explain it to me?

This is what I believe it means: while loop iterates through the char array until the ending of the array since there is nothing else then the while loop ends, or am I wrong? I tried to use the same while loop but in another language such as Go, however, the compiler threw an error saying that I cannot use a non-bool.

// C program to demonstrate
// example of tolower() function.

#include <ctype.h>
#include <stdio.h>

int main()
{
    int j = 0;
    char str[] = "GEEKSFORGEEKS\n";

    // Character to be converted to lowercase
    char ch = 'G';

    // convert ch to lowercase using toLower()
    char ch;

    while (str[j]) { // <- this part, how is this a condition?
        ch = str[j];

        // convert ch to lowercase using toLower()
        putchar(tolower(ch));

        j++;
    }

    return 0;
}


问:
How can I change the color to a variable other than cluster number in fviz_silhouette
I am using package factoextra in R to generate a silhouette plot. Currently the silhouette automatically colours your graph via clustering. I want to color by another variable Site which I have defined as x. I have tried both fill and color changing it to the site variable but nothing seems to work. I have also tried using scale_color_manual and scale_fill_discrete. I think the key is in scale_fill_discrete as the source code from another user points out

```<code>mapping <- aes_string(x = "name", y = "sil_width", color = "cluster", fill = "cluster")
</code>```

I basically need to change color="cluster" to colour= "x".

I have reverted the final plotting code back to its most basic form.

```<code>pamspec <- pam(spec, 3, keep.diss = TRUE)
plot(pamspec)

spec <- cbind(pamspec$clustering)
autoplot(pam(spec,3), frame=TRUE, frame.type = "norm")

pamspec$site <- spec$Site
x <- pamspec$site
fviz_silhouette(pamspec, label=TRUE) + theme_classic()
</code>```

答:
I suggest the following modified version of fviz_silhouette with the additional var.col input argument.

```<code>myfviz_silhouette <- function (sil.obj, var.col, label = FALSE, print.summary = TRUE, ...) {
    if (inherits(sil.obj, c("eclust", "hcut", "pam", "clara",
        "fanny"))) {
        df <- as.data.frame(sil.obj$silinfo$widths, stringsAsFactors = TRUE)
    }
    else if (inherits(sil.obj, "silhouette"))
        df <- as.data.frame(sil.obj[, 1:3], stringsAsFactors = TRUE)
    else stop("Don't support an oject of class ", class(sil.obj))
    df <- df[order(df$cluster, -df$sil_width), ]
    if (!is.null(rownames(df)))
        df$name <- factor(rownames(df), levels = rownames(df))
    else df$name <- as.factor(1:nrow(df))
    df$cluster <- as.factor(df$cluster)
    df$var_col <- var.col
    mapping <- aes_string(x = "name", y = "sil_width", color = "var_col",
        fill = "var_col")
    p <- ggplot(df, mapping) + geom_bar(stat = "identity") +
        labs(y = "Silhouette width Si", x = "", title = paste0("Clusters silhouette plot ",
            "\n Average silhouette width: ", round(mean(df$sil_width),
                2))) + ggplot2::ylim(c(NA, 1)) + geom_hline(yintercept = mean(df$sil_width),
        linetype = "dashed", color = "red")
    p <- ggpubr::ggpar(p, ...)
    if (!label)
        p <- p + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())
    else if (label)
        p <- p + theme(axis.text.x = element_text(angle = 45))
    ave <- tapply(df$sil_width, df$cluster, mean)
    n <- tapply(df$cluster, df$cluster, length)
    sil.sum <- data.frame(cluster = names(ave), size = n, ave.sil.width = round(ave,
        2), stringsAsFactors = TRUE)
    if (print.summary)
        print(sil.sum)
    p
}
</code>```

Here is an example of its use:

```<code>library(factoextra)
library(cluster)
pamspec <- pam(iris[,-5], 3, keep.diss = TRUE)

color_var <- iris$Species
myfviz_silhouette(pamspec, color_var, label=TRUE) +
   theme_classic()
</code>```

Body:
I am using package factoextra in R to generate a silhouette plot. Currently the silhouette automatically colours your graph via clustering. I want to color by another variable Site which I have defined as x. I have tried both fill and color changing it to the site variable but nothing seems to work. I have also tried using scale_color_manual and scale_fill_discrete. I think the key is in scale_fill_discrete as the source code from another user points out

mapping <- aes_string(x = "name", y = "sil_width", color = "cluster", fill = "cluster")

I basically need to change color="cluster" to colour= "x".

I have reverted the final plotting code back to its most basic form.

pamspec <- pam(spec, 3, keep.diss = TRUE)
plot(pamspec)

spec <- cbind(pamspec$clustering)
autoplot(pam(spec,3), frame=TRUE, frame.type = "norm")

pamspec$site <- spec$Site
x <- pamspec$site
fviz_silhouette(pamspec, label=TRUE) + theme_classic()

Body:
I suggest the following modified version of fviz_silhouette with the additional var.col input argument.

myfviz_silhouette <- function (sil.obj, var.col, label = FALSE, print.summary = TRUE, ...) {
    if (inherits(sil.obj, c("eclust", "hcut", "pam", "clara",
        "fanny"))) {
        df <- as.data.frame(sil.obj$silinfo$widths, stringsAsFactors = TRUE)
    }
    else if (inherits(sil.obj, "silhouette"))
        df <- as.data.frame(sil.obj[, 1:3], stringsAsFactors = TRUE)
    else stop("Don't support an oject of class ", class(sil.obj))
    df <- df[order(df$cluster, -df$sil_width), ]
    if (!is.null(rownames(df)))
        df$name <- factor(rownames(df), levels = rownames(df))
    else df$name <- as.factor(1:nrow(df))
    df$cluster <- as.factor(df$cluster)
    df$var_col <- var.col
    mapping <- aes_string(x = "name", y = "sil_width", color = "var_col",
        fill = "var_col")
    p <- ggplot(df, mapping) + geom_bar(stat = "identity") +
        labs(y = "Silhouette width Si", x = "", title = paste0("Clusters silhouette plot ",
            "\n Average silhouette width: ", round(mean(df$sil_width),
                2))) + ggplot2::ylim(c(NA, 1)) + geom_hline(yintercept = mean(df$sil_width),
        linetype = "dashed", color = "red")
    p <- ggpubr::ggpar(p, ...)
    if (!label)
        p <- p + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())
    else if (label)
        p <- p + theme(axis.text.x = element_text(angle = 45))
    ave <- tapply(df$sil_width, df$cluster, mean)
    n <- tapply(df$cluster, df$cluster, length)
    sil.sum <- data.frame(cluster = names(ave), size = n, ave.sil.width = round(ave,
        2), stringsAsFactors = TRUE)
    if (print.summary)
        print(sil.sum)
    p
}

Here is an example of its use:

library(factoextra)
library(cluster)
pamspec <- pam(iris[,-5], 3, keep.diss = TRUE)

color_var <- iris$Species
myfviz_silhouette(pamspec, color_var, label=TRUE) +
   theme_classic()


问:
How to run .exe fiile automatically at scheduled time even if system is turned off?
I am working on python project, where at particular time (8 pm) a random number will be displayed. I have converted .py file to .exe using pyinstaller. Now, I want my .exe file to run automatically and display the number, even if I won't open .exe file at 8pm.</p>

答:
Since you're referring to .exe I assume you're on Windows.
You should use the Task Scheduler in Windows to schedule your application to run.

For that you could run it with full path to your python.exe with the .py file as parameter, so conferting to .exe isn't really necessary.

To automagically run this on time when the system is switched off, you will need to check the BIOS settings of your PC at startup to see if you can make the computer switch on all by itself at a certain time. Make sure to set this automatic power on a few minutes before the scheduled task to allow Windows to start up first.


问:
OctoberCMS Responsiv Uploader Plugin, files has null values
I use the uploader plugin to upload pdf files. I have followed the documentation implementing it on the components in the init function. this my following code

```<code>    public function init(){
    $tripFiles = $this->addComponent(
        'Responsiv\Uploader\Components\FileUploader',
        'tripFiles',
        [
            'fileTypes'             => '.jpg, .jpeg, .png, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx',
            'placeholderText'       => "Drag and drop file here or Browse File",
        ],
        ['deferredBinding'       => true]
    );
    $tripFiles->bindModel('files', ($this->property('tripId') ? Trip::find((int)$this->property('tripId')) : new Trip));
}

public function onSave(){
   $data = post();
    var_dump($data);
    $vacation = new Trip;
    $vacation->fill($data);
    $vacation->save(null, post('_session_key'));
}
</code>```

but I found the output with null value on array of _uploader in files.

```<code>array:10 [▼
  "_handler" => "onCreateXXX"
  "_session_key" => "XXXXXXXXXX"
  "_token" => "XXXXXXXXXX"
  "name" => "XXXXX"
  "destination_name" => "XXXX"
  "purpose_id" => "1"
  "purpose" => ""
  "charge_code" => "XXXX"
  "city_id" => "1"
  "_uploader" => array:1 [▼
    "files" => ""
  ]
]
</code>```

FrontEnd

```<code>{{ form_ajax('onSave')}}
   {% component 'tripFiles' %}
  <button type="submit" class="btn btn-primary w-90"> Create Trip </button>
{{ form_close() }}
</code>```

so anyone can help me this problem ??

答:
Here problem is there are 2 models, and yes you wont be able to see file's data in post I guess.

which is used in init either new one or based on tripId

which is again new model in onSave anyhow not related to model which is binded to the widget in init method.

You need to make sure same model is used in both case so, may be create one variable which can hold model and use that in both scenario.

public $vacationModel = null;

public function init() {
    $tripFiles = $this->addComponent(
        'Responsiv\Uploader\Components\FileUploader',
        'tripFiles',
        [
            'fileTypes'             => '.jpg, .jpeg, .png, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx',
            'placeholderText'       => "Drag and drop file here or Browse File",
        ],
        ['deferredBinding'       => true]
    );
    $this->vacationModel = $this->property('tripId')
          ? Trip::find((int)$this->property('tripId'))
          : new Trip;
    $tripFiles->bindModel('files', $this->vacationModel);

}

public function onSave() {
    $data = post();
    $this->vacationModel->fill($data);
    $this->vacationModel->save(null, post('_session_key'));
}
```

This should solve your issue.

if any doubts please comment.

Body:
I use the uploader plugin to upload pdf files. I have followed the documentation implementing it on the components in the init function. this my following code

    public function init(){
    $tripFiles = $this->addComponent(
        'Responsiv\Uploader\Components\FileUploader',
        'tripFiles',
        [
            'fileTypes'             => '.jpg, .jpeg, .png, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx',
            'placeholderText'       => "Drag and drop file here or Browse File",
        ],
        ['deferredBinding'       => true]
    );
    $tripFiles->bindModel('files', ($this->property('tripId') ? Trip::find((int)$this->property('tripId')) : new Trip));
}

public function onSave(){
   $data = post();
    var_dump($data);
    $vacation = new Trip;
    $vacation->fill($data);
    $vacation->save(null, post('_session_key'));
}

but I found the output with null value on array of _uploader in files.

array:10 [▼
  "_handler" => "onCreateXXX"
  "_session_key" => "XXXXXXXXXX"
  "_token" => "XXXXXXXXXX"
  "name" => "XXXXX"
  "destination_name" => "XXXX"
  "purpose_id" => "1"
  "purpose" => ""
  "charge_code" => "XXXX"
  "city_id" => "1"
  "_uploader" => array:1 [▼
    "files" => ""
  ]
]

FrontEnd

{{ form_ajax('onSave')}}
   {% component 'tripFiles' %}
  <button type="submit" class="btn btn-primary w-90"> Create Trip </button>
{{ form_close() }}

so anyone can help me this problem ??

Body:
Here problem is there are 2 models, and yes you wont be able to see file's data in post I guess.

which is used in init either new one or based on tripId

which is again new model in onSave anyhow not related to model which is binded to the widget in init method.

You need to make sure same model is used in both case so, may be create one variable which can hold model and use that in both scenario.

public $vacationModel = null;

public function init() {
    $tripFiles = $this->addComponent(
        'Responsiv\Uploader\Components\FileUploader',
        'tripFiles',
        [
            'fileTypes'             => '.jpg, .jpeg, .png, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx',
            'placeholderText'       => "Drag and drop file here or Browse File",
        ],
        ['deferredBinding'       => true]
    );
    $this->vacationModel = $this->property('tripId')
          ? Trip::find((int)$this->property('tripId'))
          : new Trip;
    $tripFiles->bindModel('files', $this->vacationModel);

}

public function onSave() {
    $data = post();
    $this->vacationModel->fill($data);
    $this->vacationModel->save(null, post('_session_key'));
}

This should solve your issue.

if any doubts please comment.


问:
Show transparent dialog in flutter
I want to disply a image in flutter in an transparent dialog. I've set opaque to false and used MaterialType.transparency. When I open the dialog the background is black.

```<code>class ShowProfileImage extends ModalRoute<void> {
  final String url;

  @override
  Duration get transitionDuration => Duration(milliseconds: 500);

  @override
  bool get opaque => false;

  @override
  bool get barrierDismissible => false;

  @override
  Color get barrierColor => Colors.black;

  @override
  String get barrierLabel => null;

  @override
  bool get maintainState => true;

  VoidCallback onDeleteImage;

  ShowProfileImage(String this.url);

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    // This makes sure that text and other content follows the material style
    return Material(
      type: MaterialType.transparency,
      // make sure that the overlay content is not cut off
      child: SafeArea(
        child: InkWell(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
                height: double.infinity,
                width: double.infinity,
                color: Colors.transparent,
                child: Center(
                    child: Container(
                        width: 300,
                        child: Image(image: NetworkImageWithRetry(url)))))),
      ),
    );
  }
}
</code>```

答:
Try this, here I am showing an image from assets, you can add your code as well if you are fetching from network</p>

```<code>     showDialog(
                context: context,
                builder: (_) => new Dialog(
                  backgroundColor: Colors.transparent,
                  child: new Container(
                    alignment: FractionalOffset.center,
                    height: 80.0,
                    padding: const EdgeInsets.all(20.0),
                    child:  new Image.asset(
                      'assets/images/image.jpg',
                      fit: BoxFit.cover,
                    )
                  ),
                ));
</code>```

Title: Show transparent dialog in flutter

Body:
I want to disply a image in flutter in an transparent dialog. I've set opaque to false and used MaterialType.transparency. When I open the dialog the background is black.

class ShowProfileImage extends ModalRoute<void> {
  final String url;

  @override
  Duration get transitionDuration => Duration(milliseconds: 500);

  @override
  bool get opaque => false;

  @override
  bool get barrierDismissible => false;

  @override
  Color get barrierColor => Colors.black;

  @override
  String get barrierLabel => null;

  @override
  bool get maintainState => true;

  VoidCallback onDeleteImage;

  ShowProfileImage(String this.url);

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    // This makes sure that text and other content follows the material style
    return Material(
      type: MaterialType.transparency,
      // make sure that the overlay content is not cut off
      child: SafeArea(
        child: InkWell(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
                height: double.infinity,
                width: double.infinity,
                color: Colors.transparent,
                child: Center(
                    child: Container(
                        width: 300,
                        child: Image(image: NetworkImageWithRetry(url)))))),
      ),
    );
  }
}

Body:
Try this, here I am showing an image from assets, you can add your code as well if you are fetching from network

     showDialog(
                context: context,
                builder: (_) => new Dialog(
                  backgroundColor: Colors.transparent,
                  child: new Container(
                    alignment: FractionalOffset.center,
                    height: 80.0,
                    padding: const EdgeInsets.all(20.0),
                    child:  new Image.asset(
                      'assets/images/image.jpg',
                      fit: BoxFit.cover,
                    )
                  ),
                ));


问:
Straight line in html
What's the best way to draw a whole single line using html?

What I want is something like this:

but shorter.

I know about the existence [1][2] of ― (―), — (—), &ndash (–), figure dash etc...

But the problem is that they are not cross platform / cross browser: sometimes I get this --- behaviour instead of this ___ but in the middle.

I didn't test all of them, but using the horizontal line does not work on Windows Chrome (while it does on Ubuntu and Android), the em dash works on Windows Chrome but does not work on Firefox and the en dash does not work neither on Android Chrome, Windows Chrome or Firefox.

I know that I could just make a span/div with a border and relatively position it, but the problem is that it would be fixed length, while I need a line which extends based on the content (so that ---this--- could be longer than ---this longer one---), since I have the same content displayed with different languages.

So, is there any character able to draw a cross-browser solid line?

UPDATE: This is what I need

答:
If anyone is interested, I found out a bunch of different lines, some of which are cross browser as far as I could test:

horizontal bar: ――――

em dash: ————

en dash: ––––

hypen: ‐‐‐‐

dash: ‐‐‐‐

box drawings light horizontal: ────

fullwidth low line: ____

minus: −−−−

combining overline: ‾‾‾‾

three-em dash: ⸻⸻⸻⸻

horizontal line extension: ⎯⎯⎯⎯

horizontal scan line 7: ⎼⎼⎼⎼

figure dash: ‒‒‒‒
```

Sources: 1, 2

at the moment ─, _, ‾, ─, ⎯, ⎼ are the only ones which work on every platform.

Please let me know if you find something else or if one of the above does not work on some platforms.

ANyway, for the moment I think I'm going to use @Dominik's solution anyway

Title: Straight line in html

Body:
If anyone is interested, I found out a bunch of different lines, some of which are cross browser as far as I could test:

horizontal bar: &horbar;&horbar;&horbar;&horbar;<br />
em dash: &mdash;&mdash;&mdash;&mdash;<br />
en dash: &ndash;&ndash;&ndash;&ndash;<br />
hypen: &hyphen;&hyphen;&hyphen;&hyphen;<br />
dash: &dash;&dash;&dash;&dash;<br />
box drawings light horizontal: &boxh;&boxh;&boxh;&boxh;<br />
fullwidth low line: &lowbar;&lowbar;&lowbar;&lowbar;<br />
minus: &minus;&minus;&minus;&minus;<br />
combining overline: &oline;&oline;&oline;&oline;<br />
three-em dash: &#11835;&#11835;&#11835;&#11835;<br />
horizontal line extension: &#9135;&#9135;&#9135;&#9135;<br />
horizontal scan line 7: &#9148;&#9148;&#9148;&#9148;<br />
figure dash: &#8210;&#8210;&#8210;&#8210;<br />

Sources: 1, 2

at the moment &boxh;, &lowbar;, &oline;, &#9472;, &#9135;, &#9148; are the only ones which work on every platform.

Please let me know if you find something else or if one of the above does not work on some platforms.

ANyway, for the moment I think I'm going to use @Dominik's solution anyway


问:
Can a single Blazor project contains both WebAssembly part and server-side part?
Now that Blazor WebAssembly is officially released, I gave it a try by creating my first Blazor wasm project using the template, but quickly noticed that one thing is pretty different what I would expect. It appears that there is no "server" part in the template, and the published result consists only of static assets (including all the .dll files). Naturally, I then wonder how may I access my online database? Allowing client-side to have direct access to my database sounds like a terrible idea (if it can be done at all), since I will have to include my connection string somewhere in my client-side code... definitely NO!

And after a quick search on Google, it seems that everyone is using another server to serve the data using API. OK, fine, but wouldn't it be much better if I can include my server part in the same project, and communicate with my client-side also using WebSocket (just like in Blazor server) rather than API? Is that possible?

答:
You can create a WebAseembly Blazor hosted App. If you're using Visual Studio to create your project, you should check out the Hosted checkbox. This create for you 3 projects. One for the WebAseembly Blazor App (Client folder), the second for hosting and serving (Server folder) the client-side Blazor app, and the third ( Shared folder) is for shared object between the two projects, as for instance, database models.

The Server app also contains controller class, which is used to demonstrate how to call a Web Api endpoint from the client Blazor to the Server (Web Api). You may create a dedicated Web Api for enabling access to your database data instead.

Note: As the Blazor client side app runs on the browser, you cannot access your database directly. You should use HTTP calls to your Web Api endpoints, the actions of which methods may retrieve the data directly from the database (not recommended), or indirectly by creating database access services or repositories.

Update:

The Main means of transportation between the client-side and the server-side( or to be more precise web api endpoints) is the Fetch Api; that is, you need to perform HTTP calls to your Web Api. However, you may use SignalR in your client app (Client SignalR). See sample here:


问:
Convert seconds into days, hours, minutes and seconds
I would like to convert a variable $uptime which is seconds, into days, hours, minutes and seconds.

Example:

$uptime = 1640467;
```

<p>Result should be: </p>

<pre class="lang-none prettyprint-override"><code>18 days 23 hours 41 minutes
</code>```

答:
I am editing one of the code to work it well when negative value comes. floor() function is not giving the correct count when the value is negative. So we need to use abs() function before using it in the floor() function.
$inputSeconds variable can be the difference between the current time stamp and the required date.

```<code>/**
 * Convert number of seconds into hours, minutes and seconds
 * and return an array containing those values
 *
 * @param integer $inputSeconds Number of seconds to parse
 * @return array
 */

function secondsToTime($inputSeconds) {

    $secondsInAMinute = 60;
    $secondsInAnHour  = 60 * $secondsInAMinute;
    $secondsInADay    = 24 * $secondsInAnHour;

    // extract days
    $days = abs($inputSeconds / $secondsInADay);
    $days = floor($days);

    // extract hours
    $hourSeconds = $inputSeconds % $secondsInADay;
    $hours = abs($hourSeconds / $secondsInAnHour);
    $hours = floor($hours);

    // extract minutes
    $minuteSeconds = $hourSeconds % $secondsInAnHour;
    $minutes = abs($minuteSeconds / $secondsInAMinute);
    $minutes = floor($minutes);

    // extract the remaining seconds
    $remainingSeconds = $minuteSeconds % $secondsInAMinute;
    $seconds = abs($remainingSeconds);
    $seconds = ceil($remainingSeconds);

    // return the final array
    $obj = array(
        'd' => (int) $days,
        'h' => (int) $hours,
        'm' => (int) $minutes,
        's' => (int) $seconds,
    );
    return $obj;
}
</code>```

Body:
I would like to convert a variable $uptime which is seconds, into days, hours, minutes and seconds.

Example:

$uptime = 1640467;

Result should be:

18 days 23 hours 41 minutes

Body:
I am editing one of the code to work it well when negative value comes. floor() function is not giving the correct count when the value is negative. So we need to use abs() function before using it in the floor() function.
$inputSeconds variable can be the difference between the current time stamp and the required date.

/**
 * Convert number of seconds into hours, minutes and seconds
 * and return an array containing those values
 *
 * @param integer $inputSeconds Number of seconds to parse
 * @return array
 */

function secondsToTime($inputSeconds) {

    $secondsInAMinute = 60;
    $secondsInAnHour  = 60 * $secondsInAMinute;
    $secondsInADay    = 24 * $secondsInAnHour;

    // extract days
    $days = abs($inputSeconds / $secondsInADay);
    $days = floor($days);

    // extract hours
    $hourSeconds = $inputSeconds % $secondsInADay;
    $hours = abs($hourSeconds / $secondsInAnHour);
    $hours = floor($hours);

    // extract minutes
    $minuteSeconds = $hourSeconds % $secondsInAnHour;
    $minutes = abs($minuteSeconds / $secondsInAMinute);
    $minutes = floor($minutes);

    // extract the remaining seconds
    $remainingSeconds = $minuteSeconds % $secondsInAMinute;
    $seconds = abs($remainingSeconds);
    $seconds = ceil($remainingSeconds);

    // return the final array
    $obj = array(
        'd' => (int) $days,
        'h' => (int) $hours,
        'm' => (int) $minutes,
        's' => (int) $seconds,
    );
    return $obj;
}


问:
Swift body method within viewmodifier : puzzled about how the application is different for .shadow() and .font
Why does shadow() can be applied for more than 2 times and get updated every time, while for .font() even though I put different styling arguments and .font() for two times and not updated remaining the same?

struct LabelStyle: ViewModifier { // receive view => style it up =>  return styled view
    func body(content: Content) -> some View {
        return content
                .foregroundColor(Color.white)
                .multilineTextAlignment(.center)
                .font(Font.custom("Arial Rounded MT Bold", size: 18))
                .modifier(Shadow())
                .font(Font.custom("Arial Rounded MT Bold", size: 35)) // not becoming 35-sized
                .modifier(differentStyledShadow()) // shadow gets updated
    }
}
```

答:
shadow() when used the second time does not updates the previous shadow. It creates a new one.

Try changing the offset of the second shadow. Then you can see both the shadows.

You can check view inspector in Xcode while running the app to check how the properties are applied to the view.


问:
JsonArray field in a JsonObject to Java Object
Below is my JSON data. I want to convert this to POJOs to store the Name,id,profession in a header table and the respective Jsonarray field in a child table.

```<code>JSON:
{
  "Name": "Bob",
  "id": 453345,
  "Profession": "Clerk",
  "Orders": [
    {
      "Item": "Milk",
      "Qty": 3
    },
    {
      "Item": "Bread",
      "Qty": 3
    }
  ]
}

Entity classes:

public class User {
        private String name;
        private Integer id;
        private String Profession;
        private JsonArray Orders;
        private UserCart userCart;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getProfession() {
            return Profession;
        }
        public void setProfession(String profession) {
            Profession = profession;
        }
        public JsonArray getOrders() {
            return Orders;
        }
        public void setOrders(JsonArray orders) {
            Orders = orders;
        }
        public UserCart getUserCart() {
            return userCart;
        }
        public void setUserCart(UserCart userCart) {
            this.userCart = userCart;
        }
    }

public class UserCart {
    private String item;
    private Integer qty;
    public String getItem() {
        return item;
    }
    public void setItem(String item) {
        this.item = item;
    }
    public Integer getQty() {
        return qty;
    }
    public void setQty(Integer qty) {
        this.qty = qty;
    }
}
</code>```

But when I do below; I get error

Cannot deserialize instance of org.json.JSONArray out of START_ARRAY
  token

```<code>User user = new User();

JsonNode data = new ObjectMapper().readTree(jsonString);

user = headerMap.readValue(data.toString(), User.class);
</code>```

How do I go about assigning the entire JSON to both the Java objects ?

答:
Use List<UserCart> for array data in json and use @JsonProperty for mapping different json node name to java object field. No need to use extra field (JsonArray Orders) anymore.

```<code>@JsonProperty("Orders")
private List<UserCart> userCart;
</code>```

Body:
Below is my JSON data. I want to convert this to POJOs to store the Name,id,profession in a header table and the respective Jsonarray field in a child table.

JSON:
{
  "Name": "Bob",
  "id": 453345,
  "Profession": "Clerk",
  "Orders": [
    {
      "Item": "Milk",
      "Qty": 3
    },
    {
      "Item": "Bread",
      "Qty": 3
    }
  ]
}

Entity classes:

public class User {
        private String name;
        private Integer id;
        private String Profession;
        private JsonArray Orders;
        private UserCart userCart;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getProfession() {
            return Profession;
        }
        public void setProfession(String profession) {
            Profession = profession;
        }
        public JsonArray getOrders() {
            return Orders;
        }
        public void setOrders(JsonArray orders) {
            Orders = orders;
        }
        public UserCart getUserCart() {
            return userCart;
        }
        public void setUserCart(UserCart userCart) {
            this.userCart = userCart;
        }
    }

public class UserCart {
    private String item;
    private Integer qty;
    public String getItem() {
        return item;
    }
    public void setItem(String item) {
        this.item = item;
    }
    public Integer getQty() {
        return qty;
    }
    public void setQty(Integer qty) {
        this.qty = qty;
    }
}

But when I do below; I get error

Cannot deserialize instance of org.json.JSONArray out of START_ARRAY
  token

User user = new User();

JsonNode data = new ObjectMapper().readTree(jsonString);

user = headerMap.readValue(data.toString(), User.class);

How do I go about assigning the entire JSON to both the Java objects ?

Body:
Use List<UserCart> for array data in json and use @JsonProperty for mapping different json node name to java object field. No need to use extra field (JsonArray Orders) anymore.

@JsonProperty("Orders")
private List<UserCart> userCart;


问:
Efficiently Join Two Tables with Several WHEREs
I meet a problem when I try to join two large tables and select entries with WHERE...OR clause:

```<code>SELECT A.a, B.b
FROM A JOIN B
ON A.equal = B.equal
WHERE A.condition1 > 100 OR B.condition2 > 200
</code>```

Here A and B are very very large tables, and the entries need to match the WHERE...OR conditions in different tables. May I ask if there are any approaches I can optimize this clause?

Thx in advance.

答:
This is a variation on GMB's answer.  But because you care about performance, it is worth highlighting.  You want to use UNION ALL with appropriate indexes:

```<code>SELECT A.a, B.b
FROM A JOIN B ON A.equal = B.equal
WHERE A.condition1 > 100
UNION ALL
SELECT A.a, B.b
FROM A JOIN B ON A.equal = B.equal
WHERE B.condition2 > 100 AND A.condition1 <= 100;
</code>```

The use of UNION ALL removes a step to remove duplicates.

The above assumes that A.condition1 is never NULL.  That is easily handled but just complicates the query a little.

In Hive, this will only really improve performance if one or both of the conditions are quite selective -- by reducing the number of rows that are matched in the JOIN.  If each selects, say, 90% of the rows, then your version is probably pretty similar.

If your database can make use of indexes, then you want:

A(condition1, equal, a)

B(equal, b)

B(condition2, equal, b)

A(equal, a, condition1)

Body:
I meet a problem when I try to join two large tables and select entries with WHERE...OR clause:

SELECT A.a, B.b
FROM A JOIN B
ON A.equal = B.equal
WHERE A.condition1 > 100 OR B.condition2 > 200

Here A and B are very very large tables, and the entries need to match the WHERE...OR conditions in different tables. May I ask if there are any approaches I can optimize this clause?

Thx in advance.

Body:
This is a variation on GMB's answer.  But because you care about performance, it is worth highlighting.  You want to use UNION ALL with appropriate indexes:

SELECT A.a, B.b
FROM A JOIN B ON A.equal = B.equal
WHERE A.condition1 > 100
UNION ALL
SELECT A.a, B.b
FROM A JOIN B ON A.equal = B.equal
WHERE B.condition2 > 100 AND A.condition1 <= 100;

The use of UNION ALL removes a step to remove duplicates.

The above assumes that A.condition1 is never NULL.  That is easily handled but just complicates the query a little.

In Hive, this will only really improve performance if one or both of the conditions are quite selective -- by reducing the number of rows that are matched in the JOIN.  If each selects, say, 90% of the rows, then your version is probably pretty similar.

If your database can make use of indexes, then you want:

A(condition1, equal, a)

B(equal, b)

B(condition2, equal, b)

A(equal, a, condition1)