问:
Finding the maximum and minimum value out of a list from a dictonary - Interview Question
Given below is the stock data set which shows stock and its predicted price over the next 7 working days/sessions an end-user I want to know what should be my buy price and what should be my sell price for each share so that I can earn maximum profit.

E.g. For RIL, if I buy it in the first session and sell it in the 4th session I will get 200 profit.

Also, what would you do if the maximum price is on the 1st day itself?

Test Case:

```<code>Input:
StockId,PredictedPricr
RIL,[1000,1005,1090,1200,1000,900,890]
HDFC,[890,940,810,730,735,960,980]
INFY,[1001,902,1000,990,1230,1100,1200]

Output:
StockId|BuyPrice|SellPrice|Profit
RIL|1000|1200|200
HDFC|730|980|250
INFY|902|1230|328
</code>```

You can use any language of your choice, I preferably would use python dictionaries for this.

答:
So, I remembered that there is a leetcode question that asks almost exactly your problem. For different solutions and explanations, you can look at the discussion section of the question. The difference is that there you only have to solve the problem for one stock. Here is the solution I used back when I solved it:

```<code>def max_profit(prices):
    p1 = 0
    max_profit = -1
    current_buy = -1
    current_sell = -1

    for p2 in range(1, len(prices)):

        if prices[p2] < prices[p1]:
            p1=p2
        elif prices[p2] - prices[p1] > max_profit:
            current_buy = prices[p1]
            current_sell = prices[p2]
            max_profit = current_sell - current_buy

    return (current_buy, current_sell, max_profit)
</code>```

The input is simply the array of prices that you have for one of the stocks. What you have to do is loop over your stocks and call the method for each of them.

Now, how does the code work? We iterate over the array and try to find the sequence where we have the highest profit. We simply have a start index (p1), where our sequence begins and increase the end pointer (p2). The endpointer is increased to find the highest profit with our start index. If we find a lower price than our start index (via the end pointer) we move the start index to this lower price and simply continue to increase the end pointer. So, the start pointer always points to the lowest prices that we currently know.

Edit: How to apply it on all stocks? As I said we simply have to iterate over the stocks and use the function on each one. How it is handled exactly depends on your input/output format. I assumed you use a dictionary:

input_values = {
    'RIL':[1000,1005,1090,1200,1000,900,890],
    'HDFC':[890,940,810,730,735,960,980],
    'INFY':[1001,902,1000,990,1230,1100,1200],
}

result = []
for k, v in input_values.items():
    buy, sell, profit = max_profit(v)
    result.append([k, buy, sell, profit])

print(result)
```
<p>Output:</p>
```[
    ['RIL', 1000, 1200, 200],
    ['HDFC', 730, 980, 250],
    ['INFY', 902, 1230, 328]
]
```

Body:
Given below is the stock data set which shows stock and its predicted price over the next 7 working days/sessions an end-user I want to know what should be my buy price and what should be my sell price for each share so that I can earn maximum profit.

E.g. For RIL, if I buy it in the first session and sell it in the 4th session I will get 200 profit.

Also, what would you do if the maximum price is on the 1st day itself?

Test Case:

Input:
StockId,PredictedPricr
RIL,[1000,1005,1090,1200,1000,900,890]
HDFC,[890,940,810,730,735,960,980]
INFY,[1001,902,1000,990,1230,1100,1200]

Output:
StockId|BuyPrice|SellPrice|Profit
RIL|1000|1200|200
HDFC|730|980|250
INFY|902|1230|328

You can use any language of your choice, I preferably would use python dictionaries for this.

Body:
So, I remembered that there is a leetcode question that asks almost exactly your problem. For different solutions and explanations, you can look at the discussion section of the question. The difference is that there you only have to solve the problem for one stock. Here is the solution I used back when I solved it:

def max_profit(prices):
    p1 = 0
    max_profit = -1
    current_buy = -1
    current_sell = -1

    for p2 in range(1, len(prices)):

        if prices[p2] < prices[p1]:
            p1=p2
        elif prices[p2] - prices[p1] > max_profit:
            current_buy = prices[p1]
            current_sell = prices[p2]
            max_profit = current_sell - current_buy

    return (current_buy, current_sell, max_profit)

The input is simply the array of prices that you have for one of the stocks. What you have to do is loop over your stocks and call the method for each of them.

Now, how does the code work? We iterate over the array and try to find the sequence where we have the highest profit. We simply have a start index (p1), where our sequence begins and increase the end pointer (p2). The endpointer is increased to find the highest profit with our start index. If we find a lower price than our start index (via the end pointer) we move the start index to this lower price and simply continue to increase the end pointer. So, the start pointer always points to the lowest prices that we currently know.

Edit: How to apply it on all stocks? As I said we simply have to iterate over the stocks and use the function on each one. How it is handled exactly depends on your input/output format. I assumed you use a dictionary:

input_values = {
    'RIL':[1000,1005,1090,1200,1000,900,890],
    'HDFC':[890,940,810,730,735,960,980],
    'INFY':[1001,902,1000,990,1230,1100,1200],
}

result = []
for k, v in input_values.items():
    buy, sell, profit = max_profit(v)
    result.append([k, buy, sell, profit])

print(result)

Output:

[
    ['RIL', 1000, 1200, 200],
    ['HDFC', 730, 980, 250],
    ['INFY', 902, 1230, 328]
]


来源: stackexchange

问:
How to get the id of dynamically generated button when clicked
I am dynamically generating buttons based of text value stored in a SQL Server database table.

How to get the ID value associated with it to show in textbox.text when the button is clicked?

Here is my code

```<code>InitializeComponent();

Connection connection = new Connection();
connection.cn.Open();

SqlCommand cmm = new SqlCommand("SELECT * FROM [dbo].[Groups] WHERE Show_menu = 1 ORDER BY [Group_Name]", connection.cn);

using (SqlDataReader rd = cmm.ExecuteReader())
{
    while (rd.Read())
    {
        Button bt = new Button();

        //this is the buttons name but i also need the id associated with it to show in separated textbox when clicked

        bt.Text = (string)rd["Group_Name"].ToString();
        bt.Size = new Size(257, 57);
        bt.BackColor = ColorTranslator.FromHtml("#2E1E5B");
        bt.Font = new Font("Tahoma", 13f, FontStyle.Bold);
        bt.ForeColor = Color.White;
        bt.AutoSizeMode = AutoSizeMode.GrowAndShrink;
        bt.FlatStyle = FlatStyle.Flat;
        // ....
    }
}
</code>```

答:
I think you mean button Name property not Id because button do not have Id property.
You need to give button Name property, and do this

```<code>InitializeComponent();
Button bt = new Button();
bt.Name = "hello";
bt.Click += (sender, e) =>
{
   textBox1.Text = bt.Name;
};
Controls.Add(bt);
</code>```

Ref: Add events to controls that were added dynamically

ContentLicense: CC BY-SA 4.0

Body:
I am dynamically generating buttons based of text value stored in a SQL Server database table.

How to get the ID value associated with it to show in textbox.text when the button is clicked?

Here is my code

InitializeComponent();

Connection connection = new Connection();
connection.cn.Open();

SqlCommand cmm = new SqlCommand("SELECT * FROM [dbo].[Groups] WHERE Show_menu = 1 ORDER BY [Group_Name]", connection.cn);

using (SqlDataReader rd = cmm.ExecuteReader())
{
    while (rd.Read())
    {
        Button bt = new Button();

        //this is the buttons name but i also need the id associated with it to show in separated textbox when clicked

        bt.Text = (string)rd["Group_Name"].ToString();
        bt.Size = new Size(257, 57);
        bt.BackColor = ColorTranslator.FromHtml("#2E1E5B");
        bt.Font = new Font("Tahoma", 13f, FontStyle.Bold);
        bt.ForeColor = Color.White;
        bt.AutoSizeMode = AutoSizeMode.GrowAndShrink;
        bt.FlatStyle = FlatStyle.Flat;
        // ....
    }
}

Body:
I think you mean button Name property not Id because button do not have Id property.
You need to give button Name property, and do this

InitializeComponent();
Button bt = new Button();
bt.Name = "hello";
bt.Click += (sender, e) =>
{
   textBox1.Text = bt.Name;
};
Controls.Add(bt);

Ref: Add events to controls that were added dynamically


问:
Why do you divide by two when checking prime numbers in Java?
I was looking over this on YouTube and saw some code. I got most of it but didn't understand at all the reason why you the value n divide by two. Could someone please explain it?</p>
```<code>import java.util.ArrayList;

public class Primes {

    public static void main(String[] args) {

        System.out.println(findPrimes(1, 100));

    }

    public static ArrayList<Integer> findPrimes(int start, int end) {

        ArrayList<Integer> primes = new ArrayList<Integer>();

        for(int n = start; n < end; n++) {
            boolean prime = true;

            int i = 2;
            while(i <= n/2) {
                if(n % i == 0) {
                    prime = false;
                    break;
                }
                i++;
            }

            if(prime) {
                primes.add(n);
            }
        }

        return primes;
    }

}
</code>```

答: Here, we are checking till n/2 so that the number of iterations and the load on the system reduces and make the program more efficient. Since the greatest factor which can divide a number (excluding itself) is half of the number, we check only till that point. There is no point of checking beyond that.

Body:
I was looking over this on YouTube and saw some code. I got most of it but didn't understand at all the reason why you the value n divide by two. Could someone please explain it?

import java.util.ArrayList;

public class Primes {

    public static void main(String[] args) {

        System.out.println(findPrimes(1, 100));

    }

    public static ArrayList<Integer> findPrimes(int start, int end) {

        ArrayList<Integer> primes = new ArrayList<Integer>();

        for(int n = start; n < end; n++) {
            boolean prime = true;

            int i = 2;
            while(i <= n/2) {
                if(n % i == 0) {
                    prime = false;
                    break;
                }
                i++;
            }

            if(prime) {
                primes.add(n);
            }
        }

        return primes;
    }

}


问:
PHP categories showing only one item
I'm trying to create a categories list, where user will be able to choose item with certain category, but as soon as I'm opening any of the categories, where "soon = '2'", there is only one item coming up. Everything else works.

The code bellow is for categories, where user can chose which caegory s/he want to see.

```<code>//navbar.php
<!-- Categories -->
              <div class="dropdown-item menu_cat" type="button" id="catMenuButton"><i class="fas fa-caret-left"></i> Categories</div>
              <form method="POST" class="dropdown-menu dropleft categories_menu row" id="cat_dropdown">
                <button class="dropdown-item" name="candle"> Candles</button>
                <button class="dropdown-item" name="cloth"> Clothes</button>
                <button type="submit"class="dropdown-item" name="tech"> Tech</button>
                </form>

</code>```

Than here is everything else, that is suppose to exectute commands that will show products from category that user choose. The issue comes upp where 'if($row["soon"] == "2")' is.

```<code>//products.php

<?php
    if(isset($_POST['candle'])){
      $sql = "SELECT * FROM products WHERE category = 'candle'";
    }else if(isset($_POST['cloth'])){
      $sql = "SELECT * FROM products WHERE category = 'cloth'";
    }else if(isset($_POST['tech'])){
      $sql = "SELECT * FROM products WHERE category = 'tech'";
    }else{
      $sql = "SELECT * FROM products";
    }
  $result = $conn->query($sql);
  if (!empty($result) && $result->num_rows > 0) {
      while ($row = $result->fetch_assoc()){
        if($row["soon"] == "2"){
        ?>
      <div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
        <div class="card-header">
          <h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
        </div>
        <div class="card-body">
          <h2 class="card-title pricing-card-title"> </h2>
          <img class="pic" src="productsImages\<?php echo $row["productID"]; ?>.jpeg" height="150px" width="120px"></img>
          <br>
          <p>
            <?php echo $row["productPrice"]; ?> SEK
          </p>
          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
            <div class="row">
              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
            </div>
          </a>
        </div>
      </div>

      <?php }else if($row['soon'] == "1" && isset($_POST['tech']) || isset($_POST['candle'])){?>
      <div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
        <div class="card-header">
          <h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
        </div>
        <div class="card-body">
          <h2 class="card-title pricing-card-title"> </h2>
          <img class="pic_soon" src="productsImages/comingSoon.png" height="150px" width="120px"></img>
          <style>
          </style>
          <br>
          <p>
            <?php echo $row["productPrice"]; ?> SEK
          </p>
          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
            <div class="row">
              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
            </div>
          </a>
        </div>
      </div>

  <?php

    }
}
}
else if(empty($result) || $result->num_rows == 0){
    echo "<h2 class='col-12'> Sorry! </h2>";
    echo "<h3 class='col-12'> There is not any product in this category yet! </h3>";
  }
  $conn->close();
  ?>
</code>```

答:
products.php</p>
```<code><?php
    if(isset($_POST['candle'])){
      $sql = "SELECT * FROM products WHERE category = 'candle'";
    }else if(isset($_POST['cloth'])){
      $sql = "SELECT * FROM products WHERE category = 'cloth'";
    }else if(isset($_POST['tech'])){
      $sql = "SELECT * FROM products WHERE category = 'tech'";
    }else{
      $sql = "SELECT * FROM products";
    }
  $result = $conn->query($sql);
  if (!empty($result) && $result->num_rows > 0) {
      while ($row = $result->fetch_assoc()){
        if($row["soon"] == "2"){
        ?>
      <div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
        <div class="card-header">
          <h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
        </div>
        <div class="card-body">
          <h2 class="card-title pricing-card-title"> </h2>
          <img class="pic" src="productsImages\<?php echo $row["productID"]; ?>.jpeg" height="150px" width="120px"></img>
          <br>
          <p>
            <?php echo $row["productPrice"]; ?> SEK
          </p>
          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
            <div class="row">
              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
            </div>
          </a>
        </div>
      </div>

      <?php }else if($row['soon'] == "1" && isset($_POST['tech']) || isset($_POST['candle'])){?>
      <div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
        <div class="card-header">
          <h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
        </div>
        <div class="card-body">
          <h2 class="card-title pricing-card-title"> </h2>
          <img class="pic_soon" src="productsImages/comingSoon.png" height="150px" width="120px"></img>
          <style>
          </style>
          <br>
          <p>
            <?php echo $row["productPrice"]; ?> SEK
          </p>
          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
            <div class="row">
              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
            </div>
          </a>
        </div>
      </div>

  <?php

    }
}
}
else if(empty($result) || $result->num_rows == 0){
    echo "<h2 class='col-12'> Sorry! </h2>";
    echo "<h3 class='col-12'> There is not any product in this category yet! </h3>";
  }
  $conn->close();
  ?>
</code>```

Title: PHP categories showing only one item

Body:
I'm trying to create a categories list, where user will be able to choose item with certain category, but as soon as I'm opening any of the categories, where "soon = '2'", there is only one item coming up. Everything else works.

The code bellow is for categories, where user can chose which caegory s/he want to see.

//navbar.php

 Categories

              <form method="POST" class="dropdown-menu dropleft categories_menu row" id="cat_dropdown">
                <button class="dropdown-item" name="candle"> Candles</button>
                <button class="dropdown-item" name="cloth"> Clothes</button>
                <button type="submit"class="dropdown-item" name="tech"> Tech</button>
                </form>

Than here is everything else, that is suppose to exectute commands that will show products from category that user choose. The issue comes upp where 'if($row["soon"] == "2")' is.

//products.php

<?php
    if(isset($_POST['candle'])){
      $sql = "SELECT * FROM products WHERE category = 'candle'";
    }else if(isset($_POST['cloth'])){
      $sql = "SELECT * FROM products WHERE category = 'cloth'";
    }else if(isset($_POST['tech'])){
      $sql = "SELECT * FROM products WHERE category = 'tech'";
    }else{
      $sql = "SELECT * FROM products";
    }
  $result = $conn->query($sql);
  if (!empty($result) && $result->num_rows > 0) {
      while ($row = $result->fetch_assoc()){
        if($row["soon"] == "2"){
        ?>

 <?php echo $row["productName"] ?>

          <img class="pic" src="productsImages\<?php echo $row["productID"]; ?>.jpeg" height="150px" width="120px">

            <?php echo $row["productPrice"]; ?> SEK

          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">

              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product </button>

      <?php }else if($row['soon'] == "1" && isset($_POST['tech']) || isset($_POST['candle'])){?>

 <?php echo $row["productName"] ?>

            <?php echo $row["productPrice"]; ?> SEK

          <a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">

              <button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product </button>

  <?php

    }
}
}
else if(empty($result) || $result->num_rows == 0){
    echo "
 Sorry!
";
    echo "
 There is not any product in this category yet!
";
  }
  $conn->close();
  ?>


问:
Char value to decimal data type in RPGLE
Why when I send a char(CL) value to a decimal data type is converted to (-33)?
I wrote (move  'CL'    NmOfField)
and NmOfField is a decimal data type, so I found the value on NmOfField is (-33)
I want to know why (-33) specifically?</p>

答:
It has to do with the fact that hex representation of 'CL' is X'C3D3' and the fact that NmOfField is a packed decimal type.

Say it's a packed(3:0) and it's value before move is 0. Each pair nibble in 'CL' becomes a digits, so the absolute value is 33, the second to last nibble is considered sign, and in packed decimal D is minus so hexadecimal representation of NmOfField is X'033D' and the numeric value is -33. If NmOfField value had been +123 (X'123F') before move, it would have been -133 after (X'133D') as 'CL' is only two characters long (move works right to left til there is no more room in the result, or no more char in factor 2). If one of the digit nibble had not been a decimal digit, a error would have been raised.

You should avoid using move* operators because of that kind of suprises and some other, and prefer free-form syntax listed here


问:
What are exact requirements on automatic storage duration?
Depending on the compiler the following code:

```<code>int main()
{
   srand( 0 );
   if( rand() ) {
      char buffer[600 * 1024] = {};
      printf( buffer );
   } else {
      char buffer[500 * 1024] = {};
      printf( buffer );
   }
   return 0;
}
</code>```

when ran on a system with maximum stack size equal to 1 megabyte either prints an empty string or crashes with a stack overflow.

The difference is because different compilers allocate automatic storage differently. Most compilers allocate storage for all objects on function start, so in the code above they allocate 600+400=1100 kilobytes and that leads to stack overflow. Some compilers are smarter and they see that those two arrays can never be accessible at the same time so they reuse the same memory and only allocate 600 kilobytes and the program runs fine.

Now The Standard says (3.7/1) that storage duration defines the minimum potential lifetime of the storage and then (3.7.2/1) that the storage for these objects [with automatic duration] lasts until the block in which they are created exists.

I don't understand how 3.7/1 and 3.7.2/1 are to be applied together. One says that duration is minimum potential and the other says explicitly that it lasts until the block exists. Looks like according to the first both allocation strategies are legal, but the second demands that only "reuse" allocation strategy is used.

How do 3.7/1 and 3.7.2/1 co-exist? Is it legal to allocate more memory than the program needs in the worst case (the first strategy)?

答:
I read 3.7/ as an introductory description and definition of the different storage classe (automatic, static, dynamic) and not as the implementation requirement for each... the implementation requirement for automatich is then described in 3.7.2/1 .

Reading 3.7.2/1 it does not forbid that it exists longer than the block exists (that is just the minimum) - IMHO this is an opening for compiler implementors regarding possible optimizations...

ContentLicense: CC BY-SA 3.0

Body:
Depending on the compiler the following code:

int main()
{
   srand( 0 );
   if( rand() ) {
      char buffer[600 * 1024] = {};
      printf( buffer );
   } else {
      char buffer[500 * 1024] = {};
      printf( buffer );
   }
   return 0;
}

when ran on a system with maximum stack size equal to 1 megabyte either prints an empty string or crashes with a stack overflow.

The difference is because different compilers allocate automatic storage differently. Most compilers allocate storage for all objects on function start, so in the code above they allocate 600+400=1100 kilobytes and that leads to stack overflow. Some compilers are smarter and they see that those two arrays can never be accessible at the same time so they reuse the same memory and only allocate 600 kilobytes and the program runs fine.

Now The Standard says (3.7/1) that storage duration defines the minimum potential lifetime of the storage and then (3.7.2/1) that the storage for these objects [with automatic duration] lasts until the block in which they are created exists.

I don't understand how 3.7/1 and 3.7.2/1 are to be applied together. One says that duration is minimum potential and the other says explicitly that it lasts until the block exists. Looks like according to the first both allocation strategies are legal, but the second demands that only "reuse" allocation strategy is used.

How do 3.7/1 and 3.7.2/1 co-exist? Is it legal to allocate more memory than the program needs in the worst case (the first strategy)?


问:
Git -- how to have one file flow into another?
What I need is less than a branch, and submodule doesn't appear to be a fit.

I have a repo with three files:

/foo.bar

/foo1.bar

/foo2.bar

This isn't really production code. It is demonstration code.

foo.bar is a stand alone function, and I will now build a real piece of code from it in /foo3.bar.

In a perforce context, I would branch foo.bar to foo3.bar and then start working on foo3.bar. This would give me all the history of foo.bar, and allow changes to foo.bar to be integrated into foo3.bar.

Another way to say it:
I need to rename foo.bar to foo3.bar. However, live in VCS land and must always retain the full commit history. Imagine further: Over the history of foo9.bar, it has been named foo.bar, foo3.bar, and a few other names before arriving at foo9.bar. How is the full history, including all commits and all renames, done?

(And then my original scenario simply retains one of the earlier files in addition to the subsequent names. For example, foo.bar is renamed to foo3.bar, but then foo3.bar persists into the future and also becomes foo9.bar.)

How do I do this in git?

答:
You're looking for file identity.

Files, in Git, do not have identity.  It's simply not there.  Git has only commit-level identity.  As Kaz notes in comments, Git will do a "best effort" attempt at rediscovering file identity after-the-fact.

Because Git assumes, by default, that files with the same name are "the same file", you can get as close as you like to file identity by ensuring that the file's name never changes.  To make this work with what you're doing, consider giving the file an internal numeric ID as its true name and storing this in, e.g., a hidden directory .source/flatfile1234.  Replace the user-oriented names foo3.bar with symbolic links.

Git doesn't really handle symbolic links terribly well either—they can't be merged—but now you have your file identity.


问:
What the following code prints / with arrays, pointers etc
I have problem solving this problem, so if anyne had a similar problem it would help me a lot.

```<code>short y[2][3]={{0123},{0x12345}},*p=y[1];
printf("01:%x\n", y);
printf("02:%x\n", p);
printf("03:%x\n", sizeof(y));
printf("04:%x\n", sizeof(y[0]));
printf("05:%x\n", sizeof(&y[0]));
printf("06:%x\n", sizeof(*p));
printf("07:%x\n", sizeof(p++));
printf("08:%x\n", *p++);
printf("09:%x\n", *p);
return 0;
</code>```

Can anyone explain to me why the printout is like this?

```<code>01:61ff10
02:61ff16
03:c
04:6
05:4
06:2
07:4
08:2345
09:0
</code>```

My opinion:

```<code>01:Prints the address where the array y begins.
02:Prints the address of the pointer, which points to the second element of the array. Since we have 2 * 3 elements that are of type short, each subsequent element of the zero element will increase by 6.
03:Since we have 2 * 3 elements, which is equal to 6, but the elements of the type are short, so it will print hexadecimal c
04:the number of elements in the zero position is 3, but they are of the short type, so it prints 6
05:prints the sizeof addresses of the first element of the array which is 4
06:I don't know why it prints 2 here
07:Prints the sizeof of the pointer address which is 4, it will increase after printing
08:I do not understand
09:I do not understand
</code>```

Can anyone explain why it prints like this?

答:
OK, let's see:

#01: The address of y.

#02: The value of p, which holds the address of y[1], which is the second element of type short[3]. The size of a short is apparently 2 on your system, so the offset to #01 is 6.

#03: The size of the array y, 2 * 3 * sizeof (short) give 12, in hex c.

#04: The size of the element y[0], which is of type short[3]. 6, as you found.

#05: The size of the address of y[0], and apparently the size of an address is 4 on your system.

#06: The size of the object that p points to. This is a short, so 2.

#07: The size of the expression p++, which is an address, so 4. And no, p is not incremented, since the expression is not evaluated.

#08: The value of the object that p points to, which is y[1][0]. Since the initializing value of 0x12345 is an int too big to be stored in a short, it is truncated to 0x2345. After reading the value, p is incremented.

#09: The element p points to, which is y[1][1]. It was initialized to 0.

Notes:

You should have got warnings from your compiler:

The mentioned initializer is truncated.

The format for pointers/addresses is %p.

The type of the result of sizeof might not match the format %x.

You should take warnings seriously, they are always a hint that you most probably made an error.

Body:
I have problem solving this problem, so if anyne had a similar problem it would help me a lot.

short y[2][3]={{0123},{0x12345}},*p=y[1];
printf("01:%x\n", y);
printf("02:%x\n", p);
printf("03:%x\n", sizeof(y));
printf("04:%x\n", sizeof(y[0]));
printf("05:%x\n", sizeof(&y[0]));
printf("06:%x\n", sizeof(*p));
printf("07:%x\n", sizeof(p++));
printf("08:%x\n", *p++);
printf("09:%x\n", *p);
return 0;

Can anyone explain to me why the printout is like this?

01:61ff10
02:61ff16
03:c
04:6
05:4
06:2
07:4
08:2345
09:0

My opinion:

01:Prints the address where the array y begins.
02:Prints the address of the pointer, which points to the second element of the array. Since we have 2 * 3 elements that are of type short, each subsequent element of the zero element will increase by 6.
03:Since we have 2 * 3 elements, which is equal to 6, but the elements of the type are short, so it will print hexadecimal c
04:the number of elements in the zero position is 3, but they are of the short type, so it prints 6
05:prints the sizeof addresses of the first element of the array which is 4
06:I don't know why it prints 2 here
07:Prints the sizeof of the pointer address which is 4, it will increase after printing
08:I do not understand
09:I do not understand

Can anyone explain why it prints like this?


问:
how to copy to clipboard text between h2 tags in selenium python
what i try to do here is get email code for verification. so I log in to the email, select and copy the 6 digits code from the email and paste it to the other tab. everything is done except i can not double click to select the 6 digit code and copy it to clipboard. the code is between h2 tag and nothing else, like this: 639094 where 639094 is actually the code which i need to be copied. how can i find the code element or whatever and copy it? here is a screen shot of the email and the chrome inspect element if anything helps.

this is the code that I use to copy the code:

```<code>codeID = driver.find_element(By.XPATH,
'//table[@class="main"]//tr//td//p//h2').text

ActionChains = ActionChains(driver)
ActionChains.double_click(codeID).perform()
time.sleep(2)
codeID.send_keys(Keys.CONTROL + 'c')
text = pyperclip.paste()
print(text)
</code>```

screen shot

答:
element is found however looks like can not be copied. the error is Element  is not reachable by keyboard. if i do everything automatically up until the element is selected with double click and copy the element with my actual keyboard the element is copied, however when selenium try to copy i get the error from above. the code i use to double click the element is:

```<code>codeID = driver.find_element(By.XPATH, '//*[@id="message-htmlpart1"]/div/table/tbody/tr/td[2]/div/table/tbody/tr/td/table/tbody/tr/td/h2')
ActionChains = ActionChains(driver)
ActionChains.double_click(codeID).perform()
time.sleep(2)
</code>```

and to do the copy is :

```<code>codeID.send_keys(Keys.CONTROL + 'c')
text = pyperclip.paste()
print(text)
</code>```

this is the part where the error ocur:

```<code>codeID.send_keys(Keys.CONTROL + 'c')
text = pyperclip.paste()
print(text)
</code>```

for some reason it says "Element  is not reachable by keyboard" but the element/code numbers are selected.

if I use print(text) they are also printed in the console.

Body:
what i try to do here is get email code for verification. so I log in to the email, select and copy the 6 digits code from the email and paste it to the other tab. everything is done except i can not double click to select the 6 digit code and copy it to clipboard. the code is between h2 tag and nothing else, like this: 639094 where 639094 is actually the code which i need to be copied. how can i find the code element or whatever and copy it? here is a screen shot of the email and the chrome inspect element if anything helps.

this is the code that I use to copy the code:

codeID = driver.find_element(By.XPATH,
'//table[@class="main"]//tr//td//p//h2').text

ActionChains = ActionChains(driver)
ActionChains.double_click(codeID).perform()
time.sleep(2)
codeID.send_keys(Keys.CONTROL + 'c')
text = pyperclip.paste()
print(text)

screen shot

Body:
element is found however looks like can not be copied. the error is Element  is not reachable by keyboard. if i do everything automatically up until the element is selected with double click and copy the element with my actual keyboard the element is copied, however when selenium try to copy i get the error from above. the code i use to double click the element is:

codeID = driver.find_element(By.XPATH, '//*[@id="message-htmlpart1"]/div/table/tbody/tr/td[2]/div/table/tbody/tr/td/table/tbody/tr/td/h2')
ActionChains = ActionChains(driver)
ActionChains.double_click(codeID).perform()
time.sleep(2)

and to do the copy is :

codeID.send_keys(Keys.CONTROL + 'c')
text = pyperclip.paste()
print(text)

this is the part where the error ocur:

codeID.send_keys(Keys.CONTROL + 'c')
text = pyperclip.paste()
print(text)

for some reason it says "Element  is not reachable by keyboard" but the element/code numbers are selected.

if I use print(text) they are also printed in the console.


问:
Using variable keys to access values in JavaScript objects
The code:

```<code>function updateDashboardData() {
    $.getJSON("includes/system/ajaxDataInterface.php", {recordcount:1}, function(data) {
        $('.stationContainer').each(function(data) {
            var bsID = $(this).attr("id");
            var bsStatus = $(this).children('.stationStatus');
            alert(data[bsID][0].time);
            bsStatus.find('.bs_maxHandsets').text(data[bsID][0].maxHandsets);
            bsStatus.find('.bs_time').text(data[bsID][0].time);
        });
    });
}
</code>```

The object data:

```<code>{
    "A5A50000": [{
        "bsid": "A5A50000",
        "chanCount": 17,
        "time": "2009-05-27 16:36:45",
        "avgInterference": 1.711765,
        "maxInterference": 4.97,
        "avgHandsets": 205.1176,
        "maxHandsets": 315,
        "avgCalls": 6.4118,
        "maxCalls": 13,
        "avgCBA": 3868.98059,
        "maxCBA": 7463,
        "sumSuccessCBA": 197318,
        "sumTimeoutHandoff": 133,
        "sumAttemptHandoff": 1028,
        "sumDeniedHandoff": 216,
        "sumConfirmHandoff": 679,
        "sumHandoffNetwork": 61873,
        "sumJoinNetwork": 96888,
        "sumLeaveNetwork": 93754,
        "sumRcvdKeepalive": 98773,
        "sumTimeoutKeepalive": 19748,
        "sumAttemptUplink": 93689,
        "sumBlockedUplink": 62453
    }]
}
</code>```

The problem:

alert(data.A5A50000[0].time); properly displays "2009-05-27 16:36:45".

alert(bsID); properly displays "A5A50000".

alert(data.bsID[0].time); reports "data.bsID is undefined".

alert(data[bsID][0].time); reports "data[bsID] is undefined".

I'm a little unclear when a variable is/isn't evaluated. Maybe I'm overlooking something silly, but I can't figure out my problem here.

答:
I experienced the same problem with a nested JSON API-response:

```<code>[
    {
        "bj_code": "2019",
        "BJ_PERIODE": [
            {
                "nummer": 1
            },
            {
                "nummer": 2
            }
        ]
    }
]
</code>```

I could evaluate:

```<code>pm.expect(pm.response.json()[0].BJ_PERIODE[1].nummer).to.eql(2);
</code>```

But working with BJ_PERIODE and nummer through a variable didn't work.
Writing it with the bracket method did work, even in this nested JSON, like this:

```<code>const periode = "BJ_PERIODE";
const nr = "nummer";
pm.expect(pm.response.json()[0][periode][1][nr]).to.eql(2);
</code>```

Body:
The code:

function updateDashboardData() {
    $.getJSON("includes/system/ajaxDataInterface.php", {recordcount:1}, function(data) {
        $('.stationContainer').each(function(data) {
            var bsID = $(this).attr("id");
            var bsStatus = $(this).children('.stationStatus');
            alert(data[bsID][0].time);
            bsStatus.find('.bs_maxHandsets').text(data[bsID][0].maxHandsets);
            bsStatus.find('.bs_time').text(data[bsID][0].time);
        });
    });
}

The object data:

{
    "A5A50000": [{
        "bsid": "A5A50000",
        "chanCount": 17,
        "time": "2009-05-27 16:36:45",
        "avgInterference": 1.711765,
        "maxInterference": 4.97,
        "avgHandsets": 205.1176,
        "maxHandsets": 315,
        "avgCalls": 6.4118,
        "maxCalls": 13,
        "avgCBA": 3868.98059,
        "maxCBA": 7463,
        "sumSuccessCBA": 197318,
        "sumTimeoutHandoff": 133,
        "sumAttemptHandoff": 1028,
        "sumDeniedHandoff": 216,
        "sumConfirmHandoff": 679,
        "sumHandoffNetwork": 61873,
        "sumJoinNetwork": 96888,
        "sumLeaveNetwork": 93754,
        "sumRcvdKeepalive": 98773,
        "sumTimeoutKeepalive": 19748,
        "sumAttemptUplink": 93689,
        "sumBlockedUplink": 62453
    }]
}

The problem:

alert(data.A5A50000[0].time); properly displays "2009-05-27 16:36:45".

alert(bsID); properly displays "A5A50000".

alert(data.bsID[0].time); reports "data.bsID is undefined".

alert(data[bsID][0].time); reports "data[bsID] is undefined".

I'm a little unclear when a variable is/isn't evaluated. Maybe I'm overlooking something silly, but I can't figure out my problem here.

Body:
I experienced the same problem with a nested JSON API-response:

[
    {
        "bj_code": "2019",
        "BJ_PERIODE": [
            {
                "nummer": 1
            },
            {
                "nummer": 2
            }
        ]
    }
]

I could evaluate:

pm.expect(pm.response.json()[0].BJ_PERIODE[1].nummer).to.eql(2);

But working with BJ_PERIODE and nummer through a variable didn't work.
Writing it with the bracket method did work, even in this nested JSON, like this:

const periode = "BJ_PERIODE";
const nr = "nummer";
pm.expect(pm.response.json()[0][periode][1][nr]).to.eql(2);


问:
Clicking content below image with higher z-index
I have created a slider using jquery and the slides plugin. I wanted to create an effect where it looks like the slider is circular shaped, so I positioned an image with a transparent circular center absolutely above the slider, with a higher z-index. You can see a working example here:  http://vitaminjdesign.com/example/examples/Standard/index.html

The problem I have having is that you cannot click on anything within the slider, because of the "mask image" which has a higher z-index than the rest of the content. I want to be able to click on the links within the caption area, as well as the entire slide. Does anybody have any good ideas on how to solve this issue?

I cannot give .caption a higher z-index than the mask because then you would see the background pass above the circular mask. BUT I need to be able to click within the transparent area of the image mask. Any ideas?

答:
@JCHASE11 I didnt think i would ever suggest this to anyone.. I just had to do it when i saw your solution.. its just.. suffocating.. but.. how about image mapping? - http://jsfiddle.net/u9cYZ/

Hah.. I started having second thoughts about this.. but it is indeed doable with image map.

Ended up testing it to make sure that im not just throwing around ideas that wont work.. http://jsfiddle.net/u9cYZ/3/ ( In this example IE gets value img position: relative; from somewhere which screws it up and..It's too late I'm off to bed )

So the solution is still a little.. crafty.. but this time it would only cover the wanted area..

This is a bit of a duct tape idea.. But, I was thinking that you could put an empty  in there somewhere, on top of the mask of course and change the href to match the current visible image.

Body:
@JCHASE11 I didnt think i would ever suggest this to anyone.. I just had to do it when i saw your solution.. its just.. suffocating.. but.. how about image mapping? - http://jsfiddle.net/u9cYZ/

Hah.. I started having second thoughts about this.. but it is indeed doable with image map.

Ended up testing it to make sure that im not just throwing around ideas that wont work.. http://jsfiddle.net/u9cYZ/3/ ( In this example IE gets value img position: relative; from somewhere which screws it up and..It's too late I'm off to bed )

So the solution is still a little.. crafty.. but this time it would only cover the wanted area..

This is a bit of a duct tape idea.. But, I was thinking that you could put an empty <a> in there somewhere, on top of the mask of course and change the href to match the current visible image.


问:
How to search a non-primary attribute from DynamoDB with Spring Reactive (Webflux)?
Suppose I have user table with fields userId, userName, password and some other fields where userId is the partition key. How could I write a query to find something from userName and not from userId? I am working with Spring webflux, so it also does not have the ReactiveCrudRepository for DynamoDb. My User table is something like this:

```<code>@Data
@NoArgsConstructor
@AllArgsConstructor
@DynamoDbBean
public class User {

    private String userId;

    private String userName;

    private String password;

    private String firstName;

    private String lastName;

    private String timestamp;

    @DynamoDbPartitionKey
    public String getUserId() {
        return userId;
    }
 }
</code>```

My repo class is:

```<code>@Repository
public class UserRepo {

    private DynamoDbAsyncTable<User> userDynamoDbAsyncTable;

    public UserRepo(DynamoDbAsyncTable<User> userDynamoDbAsyncTable) {
        this.userDynamoDbAsyncTable = userDynamoDbAsyncTable;
    }

    // CREATE
    public CompletableFuture<Void> save(User user) {
        return userDynamoDbAsyncTable.putItem(user);
    }

    // READ
    public CompletableFuture<User> getUserByID(String userId) {
        return userDynamoDbAsyncTable.getItem(getKeyBuild(userId));
    }

    // UPDATE
    public CompletableFuture<User> updateUser(User user) {
        return userDynamoDbAsyncTable.updateItem(user);
    }

    // DELETE
    public CompletableFuture<User> deleteUserById(String userId) {
        return userDynamoDbAsyncTable.deleteItem(getKeyBuild(userId));
    }

    // GET_ALL_ITEM
    public PagePublisher<User> getAllUser() {
        return userDynamoDbAsyncTable.scan();
    }

    private Key getKeyBuild(String userId) {
        return Key.builder().partitionValue(userId).build();
    }
}
</code>```

Is there any way to query database something like findByUserName("John") which returns the User object with "John" as a username?

答:
You can't query without a partition key, if you have the partition key you can combine that with a sortKey, otherwise you will need to make your userName field a sortKey in Dynamo and use a GlobalSecondaryIndex to be able to search by userName alone.

```<code>@DynamoDbSortKey
public String getUserName() {
        return serName;
}
</code>```

You could use table.scan() but that's not recommended, the recommended way is to use a partition key + sortKey or sortKey + GlobalSecondaryIndex with the table method table.query().

Body:
Suppose I have user table with fields userId, userName, password and some other fields where userId is the partition key. How could I write a query to find something from userName and not from userId? I am working with Spring webflux, so it also does not have the ReactiveCrudRepository for DynamoDb. My User table is something like this:

@Data
@NoArgsConstructor
@AllArgsConstructor
@DynamoDbBean
public class User {

    private String userId;

    private String userName;

    private String password;

    private String firstName;

    private String lastName;

    private String timestamp;

    @DynamoDbPartitionKey
    public String getUserId() {
        return userId;
    }
 }

My repo class is:

@Repository
public class UserRepo {

    private DynamoDbAsyncTable<User> userDynamoDbAsyncTable;

    public UserRepo(DynamoDbAsyncTable<User> userDynamoDbAsyncTable) {
        this.userDynamoDbAsyncTable = userDynamoDbAsyncTable;
    }

    // CREATE
    public CompletableFuture<Void> save(User user) {
        return userDynamoDbAsyncTable.putItem(user);
    }

    // READ
    public CompletableFuture<User> getUserByID(String userId) {
        return userDynamoDbAsyncTable.getItem(getKeyBuild(userId));
    }

    // UPDATE
    public CompletableFuture<User> updateUser(User user) {
        return userDynamoDbAsyncTable.updateItem(user);
    }

    // DELETE
    public CompletableFuture<User> deleteUserById(String userId) {
        return userDynamoDbAsyncTable.deleteItem(getKeyBuild(userId));
    }

    // GET_ALL_ITEM
    public PagePublisher<User> getAllUser() {
        return userDynamoDbAsyncTable.scan();
    }

    private Key getKeyBuild(String userId) {
        return Key.builder().partitionValue(userId).build();
    }
}

Is there any way to query database something like findByUserName("John") which returns the User object with "John" as a username?

Body:
You can't query without a partition key, if you have the partition key you can combine that with a sortKey, otherwise you will need to make your userName field a sortKey in Dynamo and use a GlobalSecondaryIndex to be able to search by userName alone.

@DynamoDbSortKey
public String getUserName() {
        return serName;
}

You could use table.scan() but that's not recommended, the recommended way is to use a partition key + sortKey or sortKey + GlobalSecondaryIndex with the table method table.query().


问:
How to implement a function that takes an array and some other arguments then removes the other arguments from that array
Please guys, this is an exercise (exercise 04) from Odin Project. I don't know if there is anything wrong with the code below, it keeps failing the 'npm test' (a test in the terminal) but then i checked it with console.log and it worked.</p>
```<code>const removeFromArray= function(...args) {
    const array = args[0];
        const newArray = [];
             array.forEach((item) => {
                 if(!args.includes(item)) {
                      newArray.push(item);
        }
        });
        return newArray;
    };
</code>```

答:
It seems to me that I have not understood the question very well. But JS has built-in functions that serve the purpose

Array map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Array filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

But from what I see in the code you have to remove the first element from the array.

I suggest you take a look at this question

remove first element from array and return the array minus the first element

Body:
Please guys, this is an exercise (exercise 04) from Odin Project. I don't know if there is anything wrong with the code below, it keeps failing the 'npm test' (a test in the terminal) but then i checked it with console.log and it worked.

const removeFromArray= function(...args) {
    const array = args[0];
        const newArray = [];
             array.forEach((item) => {
                 if(!args.includes(item)) {
                      newArray.push(item);
        }
        });
        return newArray;
    };


问:
Elastic search filter documents that contain array with empty string
I've documents in elastic search and I want to filter out the documents that contain an array of only empty strings or have nothing / empty array.

#doc 1
{
  "_index": "my-index-000001",
  "_type": "_doc",
  "_id": "0",
  "_source": {
    "doc":{
        "field": ["",""]
    }
  }
}

#doc 2
{
  "_index": "my-index-000001",
  "_type": "_doc",
  "_id": "0",
  "_source": {
    "doc":{
        "field": []
    }
  }
}

#doc 3
{
  "_index": "my-index-000001",
  "_type": "_doc",
  "_id": "0",
  "_source": {
    "doc":{
        "field": ["hello",""]
    }
  }
}

```

From the above documents is it possible to filter out only doc 1 and doc 2 as for these, the "field" either contains nothing in the array or only empty string(s).

答:
Please check below query which will return only the document which have empty array or an array with all the empty string.

here first should clause will check if empty string is part of array or not, second clause will check if array field does not exist and must_not with wildcard will remove document from result which have atleast one element in array.

{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "city.keyword": {
              "value": ""
            }
          }
        },
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "city.keyword"
                }
              }
            ]
          }
        }
      ],
      "must_not": [
        {
          "wildcard": {
            "city.keyword": "?*"
          }
        }
      ]
    }
  }
}
```
<p>Below is sample document in my index :</p>
<pre class="lang-json prettyprint-override"><code>{
"hits" : [
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4g3P2H4BrzeQ9ErqJwUL",
        "_score" : 1.0,
        "_source" : {
          "city" : [
            "",
            ""
          ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4w3P2H4BrzeQ9ErqXgWT",
        "_score" : 1.0,
        "_source" : {
          "city" : [ ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "5A3P2H4BrzeQ9ErqhwUI",
        "_score" : 1.0,
        "_source" : {
          "city" : [
            "hello",
            ""
          ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "5Q3q2H4BrzeQ9ErqOAXW",
        "_score" : 1.0,
        "_source" : {
          "city" : [
            "hello",
            "sagar"
          ]
        }
      }
    ]
}
</code>```

Sample output after executing above query:

{
"hits" : [
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4g3P2H4BrzeQ9ErqJwUL",
        "_score" : 0.5619608,
        "_source" : {
          "city" : [
            "",
            ""
          ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4w3P2H4BrzeQ9ErqXgWT",
        "_score" : 0.0,
        "_source" : {
          "city" : [ ]
        }
      }
    ]
}
```

Body:
I've documents in elastic search and I want to filter out the documents that contain an array of only empty strings or have nothing / empty array.

#doc 1
{
  "_index": "my-index-000001",
  "_type": "_doc",
  "_id": "0",
  "_source": {
    "doc":{
        "field": ["",""]
    }
  }
}

#doc 2
{
  "_index": "my-index-000001",
  "_type": "_doc",
  "_id": "0",
  "_source": {
    "doc":{
        "field": []
    }
  }
}

#doc 3
{
  "_index": "my-index-000001",
  "_type": "_doc",
  "_id": "0",
  "_source": {
    "doc":{
        "field": ["hello",""]
    }
  }
}

From the above documents is it possible to filter out only doc 1 and doc 2 as for these, the "field" either contains nothing in the array or only empty string(s).

Body:
Please check below query which will return only the document which have empty array or an array with all the empty string.

here first should clause will check if empty string is part of array or not, second clause will check if array field does not exist and must_not with wildcard will remove document from result which have atleast one element in array.

{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "city.keyword": {
              "value": ""
            }
          }
        },
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "city.keyword"
                }
              }
            ]
          }
        }
      ],
      "must_not": [
        {
          "wildcard": {
            "city.keyword": "?*"
          }
        }
      ]
    }
  }
}

Below is sample document in my index :

{
"hits" : [
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4g3P2H4BrzeQ9ErqJwUL",
        "_score" : 1.0,
        "_source" : {
          "city" : [
            "",
            ""
          ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4w3P2H4BrzeQ9ErqXgWT",
        "_score" : 1.0,
        "_source" : {
          "city" : [ ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "5A3P2H4BrzeQ9ErqhwUI",
        "_score" : 1.0,
        "_source" : {
          "city" : [
            "hello",
            ""
          ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "5Q3q2H4BrzeQ9ErqOAXW",
        "_score" : 1.0,
        "_source" : {
          "city" : [
            "hello",
            "sagar"
          ]
        }
      }
    ]
}

Sample output after executing above query:

{
"hits" : [
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4g3P2H4BrzeQ9ErqJwUL",
        "_score" : 0.5619608,
        "_source" : {
          "city" : [
            "",
            ""
          ]
        }
      },
      {
        "_index" : "arrayindex",
        "_type" : "_doc",
        "_id" : "4w3P2H4BrzeQ9ErqXgWT",
        "_score" : 0.0,
        "_source" : {
          "city" : [ ]
        }
      }
    ]
}


问:
R combine month names with strings
I would like to combine each month name with three strings: 'min', 'max', 'mean'

I tried this:

paste(month.name,rep(c('min','max','mean'),12))
```

but, instead of "January min", "January max", "January mean",... I get a wrong sequence "January min"    "February max"   "March mean" ...

Do you have any suggestions? Thank you

bioglp

答:
Keep it simple ;-)

month <- c("January", "February", "March")
value <- c("min", "max", "mean")
outer(month, value, paste)

     [,1]           [,2]           [,3]
[1,] "January min"  "January max"  "January mean"
[2,] "February min" "February max" "February mean"
[3,] "March min"    "March max"    "March mean"
```
<p>To get it in vector form use <code>c()</code>:</p>
<pre class="lang-r prettyprint-override"><code>c(outer(month, value, paste))

[1] "January min"   "February min"  "March min"     "January max"
[5] "February max"  "March max"     "January mean"  "February mean"
[9] "March mean"

c(t(outer(month, value, paste)))

[1] "January min"   "January max"   "January mean"  "February min"
[5] "February max"  "February mean" "March min"     "March max"
[9] "March mean"
</code>```

Title: R combine month names with strings

Body:
I would like to combine each month name with three strings: 'min', 'max', 'mean'

I tried this:

paste(month.name,rep(c('min','max','mean'),12))

but, instead of "January min", "January max", "January mean",... I get a wrong sequence "January min"    "February max"   "March mean" ...

Do you have any suggestions? Thank you

bioglp

Body:
Keep it simple ;-)

month <- c("January", "February", "March")
value <- c("min", "max", "mean")
outer(month, value, paste)

     [,1]           [,2]           [,3]
[1,] "January min"  "January max"  "January mean"
[2,] "February min" "February max" "February mean"
[3,] "March min"    "March max"    "March mean"

To get it in vector form use c():

c(outer(month, value, paste))

[1] "January min"   "February min"  "March min"     "January max"
[5] "February max"  "March max"     "January mean"  "February mean"
[9] "March mean"

c(t(outer(month, value, paste)))

[1] "January min"   "January max"   "January mean"  "February min"
[5] "February max"  "February mean" "March min"     "March max"
[9] "March mean"


问:
Am I doing something wrong with Delphi 11 and Typecasting?
If I create a simple set of classes as follows:

type
  TBase = class(TObject)
    function BaseFunction : boolean;
  end;

  TBase1 = class(TBase)
    function Base1Function : boolean;
  end;

  TBase2 = class(TBase1)
    function Base2Function : boolean;
  end;
```
<p>Why do I get an <code>Invalid Typecast Error</code> when I try and do the following?</p>
<pre class="lang-pascal prettyprint-override"><code>procedure TForm1.FormCreate(Sender: TObject);
var
  T1 : TBase2;
begin
  T1 := TBase.Create as TBase2;
end;
</code>```

Is it fixable? I feel like I'm missing something so obvious, but I just can't see it. I'm positive this worked in previous Delphi versions.

答:
You cannot cast an instance of a parent to an instance of a child. That's not how it works.

You can cast an instance of a class in a variable of a parent type to the type of the child, as long as the variable is created as an instance of the child.

If we take the usual example of

```<code>TAnimal = CLASS
...
          END;
TDog    = CLASS(TAnimal)
...
          END;
TCat    = CLASS(TAnimal)
...
          END;
</code>```

then the following applies:

```<code>VAR
  Animal : TAnimal;
  Dog    : TDog;
  Cat    : TCat;
...
Animal:=TAnimal.Create;
Dog:=Animal AS TDog; // Cannot work - Animal can be either a Cat or a Dog
...
Animal:=TCat.Create;
Cat:=Animal AS TCat; // Works - Animal *is* a TCat.
Dog:=Animal AS TDog; // Cannot work - you can't convert a Cat to a Dog
...
Cat:=TCat.Create;
Animal:=Cat;         // Works - A Cat *is* an Animal
Dog:=Cat AS TDog;    // Cannot work - you can't convert a Cat to a Dog
</code>```

The important thing is the declared type of a class instance, and the actual type of a class instance. A variable with a declared type of a parent type can potentially point to an actual type of all child classes. It all depends on the type the variable of the parent type declaration is assigned at the construction time (which can be either the parent type or any of the child types).

On the other hand, a variable of the declared type of a child cannot point to an instance of a parent (unless you force it to by hard casting). The type compatibility is only in the downwards (towards children and grandchildren) direction, and not in the upwards (towards parents and grandparents) direction.

What you are attempting is to convert a parent instance (TBase.Create makes the instance a TBase class) to a child class. This is analogous to converting a TAnimal to a TCat or TDog.

And no - the thing you are attempting has never worked in any OO (Object Oriented) language - that's simply not how OO is functioning.

Body:
If I create a simple set of classes as follows:

type
  TBase = class(TObject)
    function BaseFunction : boolean;
  end;

  TBase1 = class(TBase)
    function Base1Function : boolean;
  end;

  TBase2 = class(TBase1)
    function Base2Function : boolean;
  end;

Why do I get an Invalid Typecast Error when I try and do the following?

procedure TForm1.FormCreate(Sender: TObject);
var
  T1 : TBase2;
begin
  T1 := TBase.Create as TBase2;
end;

Is it fixable? I feel like I'm missing something so obvious, but I just can't see it. I'm positive this worked in previous Delphi versions.

Body:
You cannot cast an instance of a parent to an instance of a child. That's not how it works.

You can cast an instance of a class in a variable of a parent type to the type of the child, as long as the variable is created as an instance of the child.

If we take the usual example of

TAnimal = CLASS
...
          END;
TDog    = CLASS(TAnimal)
...
          END;
TCat    = CLASS(TAnimal)
...
          END;

then the following applies:

VAR
  Animal : TAnimal;
  Dog    : TDog;
  Cat    : TCat;
...
Animal:=TAnimal.Create;
Dog:=Animal AS TDog; // Cannot work - Animal can be either a Cat or a Dog
...
Animal:=TCat.Create;
Cat:=Animal AS TCat; // Works - Animal *is* a TCat.
Dog:=Animal AS TDog; // Cannot work - you can't convert a Cat to a Dog
...
Cat:=TCat.Create;
Animal:=Cat;         // Works - A Cat *is* an Animal
Dog:=Cat AS TDog;    // Cannot work - you can't convert a Cat to a Dog

The important thing is the declared type of a class instance, and the actual type of a class instance. A variable with a declared type of a parent type can potentially point to an actual type of all child classes. It all depends on the type the variable of the parent type declaration is assigned at the construction time (which can be either the parent type or any of the child types).

On the other hand, a variable of the declared type of a child cannot point to an instance of a parent (unless you force it to by hard casting). The type compatibility is only in the downwards (towards children and grandchildren) direction, and not in the upwards (towards parents and grandparents) direction.

What you are attempting is to convert a parent instance (TBase.Create makes the instance a TBase class) to a child class. This is analogous to converting a TAnimal to a TCat or TDog.

And no - the thing you are attempting has never worked in any OO (Object Oriented) language - that's simply not how OO is functioning.


问:
How do I average std::chrono::time_point?
Given a vector of std::chrono::time_point<Rep, Period>, how do I find the average time_point?

The usual algorithm to find an average (add all values with std::accumulate, divide by the vector size) does not work because  you can't add two std::chrono::time_point values, nor can you divide a std::chrono::time_point<Rep, Period> by vec.size()

答:
You have to do the calculation in terms of a std::chrono::duration, such as time_since_epoch.

```<code>template<typename TimePoint>
TimePoint mean(auto&& range) {
    auto as_duration = std::views::transform(range, [](auto & tp){ return tp.time_since_epoch(); });
    return { std::accumulate(std::begin(as_duration), std::end(as_duration), {}) / std::size(range) };
}
</code>```

Body:
You have to do the calculation in terms of a std::chrono::duration, such as time_since_epoch.

template<typename TimePoint>
TimePoint mean(auto&& range) {
    auto as_duration = std::views::transform(range, [](auto & tp){ return tp.time_since_epoch(); });
    return { std::accumulate(std::begin(as_duration), std::end(as_duration), {}) / std::size(range) };
}


问:
looking up a deactivated widget's ancestor is unsafe => using Riverpod => using "Navigator.of(context).pushReplacementNamed('/page');"
The scenario which I did and caused this Error: 1. after Login page created when I used hot-reload button 2. when I pressed Login-button and state of the page changed.

Recently I decided to use riverpod package in my flutter application, so I used hooks_riverpod: ^1.0.0-dev.7 with flutter_hooks: ^0.18.0 But when I create my LoginScreen with the help of Riverpod and Hooks I faced with problems which I provided my log in below.

LoginScreen:

```<code>import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:lambda/configs/sizes/index.dart';
import 'package:lambda/configs/strings.dart';
import 'package:lambda/core/validator/src/mobile_number_validator.dart';
import 'package:lambda/presentation/state_notifiers/auth/index.dart';
import 'package:lambda/presentation/utils/input_formatter/index.dart';
import 'package:lambda/presentation/widgets/alert_message/alert_messge.dart';
import 'package:lambda/presentation/widgets/background/background.dart';
import 'package:lambda/presentation/widgets/progress/progress.dart';
import 'package:lambda/presentation/widgets/spacer/spacer.dart';
import 'package:lambda/routes.dart';

class LoginScreen extends HookConsumerWidget with MobileNumberValidator {
  LoginScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context,WidgetRef ref) {
    ref.listen<AuthState>(authStateNotifierProvider, (state) {
      state.maybeWhen(
          orElse: () {},
          otpSent: (mobileNumber) {
            AppNavigator.replaceWith<String>(
                NavigationPaths.verifyLogin, mobileNumber);
          },
          error: (message) {
            AlertMessage(context).warning(message);
          });
    });
    final phoneFieldController = useTextEditingController();

    return NormalBackground(
      child: Scaffold(
        body: Padding(
          padding: EdgeInsets.symmetric(
              horizontal: LayoutSizes(context).responsive(60)),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                Strings.pleaseEnterYourMobileNumberForLoginToTheLambda,
                style: Theme.of(context).textTheme.caption,
                textAlign: TextAlign.center,
              ),
              VSpacer(LayoutSizes(context).marginXXL),
              TextFormField(
                controller: phoneFieldController,
                style: Theme.of(context).textTheme.caption,
                textAlign: TextAlign.center,
                keyboardType: TextInputType.number,
                inputFormatters: [PersianNumberFormatter()],
                decoration: const InputDecoration(
                  hintText: Strings.mobileNumberHint,
                ),
              ),
              VSpacer(LayoutSizes(context).marginL),
              ref.watch(authStateNotifierProvider).maybeMap(
                orElse: () {
                  return ElevatedButton(
                    onPressed: () {
                      if (isValidIRMobileNumber(phoneFieldController.text)) {
                        ref
                            .read(authStateNotifierProvider.notifier)
                            .sendOtp(phoneFieldController.text);
                      } else {
                        AlertMessage(context).warning(
                            Strings.isInvalidInput(Strings.mobileNumber));
                      }
                    },
                    style: ButtonStyle(
                      fixedSize: MaterialStateProperty.all(
                        Size(double.maxFinite,
                            LayoutSizes(context).buttonHeightL),
                      ),
                    ),
                    child: const Text(Strings.next),
                  );
                },
                loading: (_) {
                  return const CircularProgress();
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

</code>```

AuthStateProviderNotifier:

```<code>import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:lambda/configs/strings.dart';
import 'package:lambda/core/extensions/strings.dart';
import 'package:lambda/data/repositories/auth/authentication_repository.dart';
import 'package:lambda/services/http/index.dart';
import 'package:lambda/services/logger/logger.dart';

import 'auth_state.dart';

final authStateNotifierProvider =
    StateNotifierProvider<AuthStateNotifier, AuthState>((ref) {
  final authRepository = ref.read(authRepositoryProvider);
  return AuthStateNotifier(authRepository);
});

class AuthStateNotifier extends StateNotifier<AuthState> {
  final AuthenticationRepository _repository;

  AuthStateNotifier(this._repository) : super(const AuthState.initial());

  Future<void> sendOtp(String mobileNumber) async {
    try {
      state = const AuthState.loading();
      await _repository.sendValidationCode(
          mobileNumber: mobileNumber.convertToEnNum());
      state = AuthState.otpSent(mobileNumber: mobileNumber);
    } catch (e, s) {
      _handleError(e, s);
    }
  }

  Future<void> verifyOtp(String mobileNumber, String code) async {
    try {
      state = const AuthState.loading();
      await _repository.login(
          mobileNumber: mobileNumber.convertToEnNum(),
          verificationCode: code.convertToEnNum());
      state = const AuthState.authenticated();
    } catch (e, s) {
      _handleError(e, s);
    }
  }

  void _handleError(Object e, StackTrace s) {
    Logger().info('error : $e stack: $s');
    if (e is NetworkExceptionX) {
      state = AuthState.error(
          errorMessage: e.messageForUser ?? Strings.someErrorHappened);
    } else {
      state = const AuthState.error(errorMessage: Strings.someErrorHappened);
    }
  }
}

</code>```

Run:

```<code>======== Exception caught by widgets library =======================================================
The following assertion was thrown building LoginScreen(dirty, dependencies: [_LocalizationsScope-[GlobalKey#aacaf], UncontrolledProviderScope, _InheritedTheme], state: _ConsumerState#cf20e, useTextEditingController: TextEditingController#f5c6d(TextEditingValue(text: ┤├, selection: TextSelection(baseOffset: -1, extentOffset: -1, affinity: TextAffinity.downstream, isDirectional: false), composing: TextRange(start: -1, end: -1)))):
Looking up a deactivated widget's ancestor is unsafe.

At this point the state of the widget's element tree is no longer stable.

To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

The relevant error-causing widget was:
  LoginScreen file:///Users/taleb/FlutterProjects/lambda/lib/routes.dart:40:36
When the exception was thrown, this was the stack:
#0      Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> (package:flutter/src/widgets/framework.dart:3944:9)
#1      Element._debugCheckStateIsActiveForAncestorLookup (package:flutter/src/widgets/framework.dart:3958:6)
#2      Element.findAncestorWidgetOfExactType (package:flutter/src/widgets/framework.dart:3996:12)
#3      debugCheckHasMediaQuery.<anonymous closure> (package:flutter/src/widgets/debug.dart:218:50)
#4      debugCheckHasMediaQuery (package:flutter/src/widgets/debug.dart:234:4)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following assertion was thrown building LoginScreen(dirty, dependencies: [_LocalizationsScope-[GlobalKey#aacaf], UncontrolledProviderScope, _InheritedTheme], state: _ConsumerState#cf20e, useTextEditingController: TextEditingController#f5c6d(TextEditingValue(text: ┤├, selection: TextSelection(baseOffset: -1, extentOffset: -1, affinity: TextAffinity.downstream, isDirectional: false), composing: TextRange(start: -1, end: -1)))):
Looking up a deactivated widget's ancestor is unsafe.

At this point the state of the widget's element tree is no longer stable.

To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

The relevant error-causing widget was:
  LoginScreen file:///Users/taleb/FlutterProjects/lambda/lib/routes.dart:40:36
When the exception was thrown, this was the stack:
#0      Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> (package:flutter/src/widgets/framework.dart:3944:9)
#1      Element._debugCheckStateIsActiveForAncestorLookup (package:flutter/src/widgets/framework.dart:3958:6)
#2      Element.findAncestorWidgetOfExactType (package:flutter/src/widgets/framework.dart:3996:12)
#3      debugCheckHasMediaQuery.<anonymous closure> (package:flutter/src/widgets/debug.dart:218:50)
#4      debugCheckHasMediaQuery (package:flutter/src/widgets/debug.dart:234:4)
...
====================================================================================================
</code>```

These errors happened when I used TextField in HookConsumerWidget
class.
I am using HookConsumerWidget instead of StatefullWidget.
I also tried to use StatefullConsumerWidget but the problem was not > solved.(ConsumerStatefulWidget+riverPod).
My question is how can we use Textfield in HookConsumerWidget + Riverpod ????

If you want to run it by yourself, I Provided a sample code of this error on my Github:
smaple_hook_riverpod

答:
I think "Navigator.of (context).pushReplacementNamed" is not the right solution for "Flutter Navigator + Riverpod".

A better solution is an entire navigation stack (which is a List of Page's) to create from a list of immutable objects. The problem of navigation is than reduced to manipulation an immutable collection.

final navigationStackProvider = Provider<>((ref) => [Obj1, Obj2, Obj3]);

[Obj1, Obj2, Obj3] je následně synchronizován s navigation stack, odpovídající [Screen1, Screen2, Screen3]...

I prepared example that implements a simple login logic, where some pages are not available without login.

Example is here: riverpod_navigator_example

Body:
The scenario which I did and caused this Error: 1. after Login page created when I used hot-reload button 2. when I pressed Login-button and state of the page changed.

Recently I decided to use riverpod package in my flutter application, so I used hooks_riverpod: ^1.0.0-dev.7 with flutter_hooks: ^0.18.0 But when I create my LoginScreen with the help of Riverpod and Hooks I faced with problems which I provided my log in below.

LoginScreen:

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:lambda/configs/sizes/index.dart';
import 'package:lambda/configs/strings.dart';
import 'package:lambda/core/validator/src/mobile_number_validator.dart';
import 'package:lambda/presentation/state_notifiers/auth/index.dart';
import 'package:lambda/presentation/utils/input_formatter/index.dart';
import 'package:lambda/presentation/widgets/alert_message/alert_messge.dart';
import 'package:lambda/presentation/widgets/background/background.dart';
import 'package:lambda/presentation/widgets/progress/progress.dart';
import 'package:lambda/presentation/widgets/spacer/spacer.dart';
import 'package:lambda/routes.dart';

class LoginScreen extends HookConsumerWidget with MobileNumberValidator {
  LoginScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context,WidgetRef ref) {
    ref.listen<AuthState>(authStateNotifierProvider, (state) {
      state.maybeWhen(
          orElse: () {},
          otpSent: (mobileNumber) {
            AppNavigator.replaceWith<String>(
                NavigationPaths.verifyLogin, mobileNumber);
          },
          error: (message) {
            AlertMessage(context).warning(message);
          });
    });
    final phoneFieldController = useTextEditingController();

    return NormalBackground(
      child: Scaffold(
        body: Padding(
          padding: EdgeInsets.symmetric(
              horizontal: LayoutSizes(context).responsive(60)),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                Strings.pleaseEnterYourMobileNumberForLoginToTheLambda,
                style: Theme.of(context).textTheme.caption,
                textAlign: TextAlign.center,
              ),
              VSpacer(LayoutSizes(context).marginXXL),
              TextFormField(
                controller: phoneFieldController,
                style: Theme.of(context).textTheme.caption,
                textAlign: TextAlign.center,
                keyboardType: TextInputType.number,
                inputFormatters: [PersianNumberFormatter()],
                decoration: const InputDecoration(
                  hintText: Strings.mobileNumberHint,
                ),
              ),
              VSpacer(LayoutSizes(context).marginL),
              ref.watch(authStateNotifierProvider).maybeMap(
                orElse: () {
                  return ElevatedButton(
                    onPressed: () {
                      if (isValidIRMobileNumber(phoneFieldController.text)) {
                        ref
                            .read(authStateNotifierProvider.notifier)
                            .sendOtp(phoneFieldController.text);
                      } else {
                        AlertMessage(context).warning(
                            Strings.isInvalidInput(Strings.mobileNumber));
                      }
                    },
                    style: ButtonStyle(
                      fixedSize: MaterialStateProperty.all(
                        Size(double.maxFinite,
                            LayoutSizes(context).buttonHeightL),
                      ),
                    ),
                    child: const Text(Strings.next),
                  );
                },
                loading: (_) {
                  return const CircularProgress();
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

AuthStateProviderNotifier:

import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:lambda/configs/strings.dart';
import 'package:lambda/core/extensions/strings.dart';
import 'package:lambda/data/repositories/auth/authentication_repository.dart';
import 'package:lambda/services/http/index.dart';
import 'package:lambda/services/logger/logger.dart';

import 'auth_state.dart';

final authStateNotifierProvider =
    StateNotifierProvider<AuthStateNotifier, AuthState>((ref) {
  final authRepository = ref.read(authRepositoryProvider);
  return AuthStateNotifier(authRepository);
});

class AuthStateNotifier extends StateNotifier<AuthState> {
  final AuthenticationRepository _repository;

  AuthStateNotifier(this._repository) : super(const AuthState.initial());

  Future<void> sendOtp(String mobileNumber) async {
    try {
      state = const AuthState.loading();
      await _repository.sendValidationCode(
          mobileNumber: mobileNumber.convertToEnNum());
      state = AuthState.otpSent(mobileNumber: mobileNumber);
    } catch (e, s) {
      _handleError(e, s);
    }
  }

  Future<void> verifyOtp(String mobileNumber, String code) async {
    try {
      state = const AuthState.loading();
      await _repository.login(
          mobileNumber: mobileNumber.convertToEnNum(),
          verificationCode: code.convertToEnNum());
      state = const AuthState.authenticated();
    } catch (e, s) {
      _handleError(e, s);
    }
  }

  void _handleError(Object e, StackTrace s) {
    Logger().info('error : $e stack: $s');
    if (e is NetworkExceptionX) {
      state = AuthState.error(
          errorMessage: e.messageForUser ?? Strings.someErrorHappened);
    } else {
      state = const AuthState.error(errorMessage: Strings.someErrorHappened);
    }
  }
}

Run:

======== Exception caught by widgets library =======================================================
The following assertion was thrown building LoginScreen(dirty, dependencies: [_LocalizationsScope-[GlobalKey#aacaf], UncontrolledProviderScope, _InheritedTheme], state: _ConsumerState#cf20e, useTextEditingController: TextEditingController#f5c6d(TextEditingValue(text: ┤├, selection: TextSelection(baseOffset: -1, extentOffset: -1, affinity: TextAffinity.downstream, isDirectional: false), composing: TextRange(start: -1, end: -1)))):
Looking up a deactivated widget's ancestor is unsafe.

At this point the state of the widget's element tree is no longer stable.

To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

The relevant error-causing widget was:
  LoginScreen file:///Users/taleb/FlutterProjects/lambda/lib/routes.dart:40:36
When the exception was thrown, this was the stack:
#0      Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> (package:flutter/src/widgets/framework.dart:3944:9)
#1      Element._debugCheckStateIsActiveForAncestorLookup (package:flutter/src/widgets/framework.dart:3958:6)
#2      Element.findAncestorWidgetOfExactType (package:flutter/src/widgets/framework.dart:3996:12)
#3      debugCheckHasMediaQuery.<anonymous closure> (package:flutter/src/widgets/debug.dart:218:50)
#4      debugCheckHasMediaQuery (package:flutter/src/widgets/debug.dart:234:4)
...
====================================================================================================

======== Exception caught by widgets library =======================================================
The following assertion was thrown building LoginScreen(dirty, dependencies: [_LocalizationsScope-[GlobalKey#aacaf], UncontrolledProviderScope, _InheritedTheme], state: _ConsumerState#cf20e, useTextEditingController: TextEditingController#f5c6d(TextEditingValue(text: ┤├, selection: TextSelection(baseOffset: -1, extentOffset: -1, affinity: TextAffinity.downstream, isDirectional: false), composing: TextRange(start: -1, end: -1)))):
Looking up a deactivated widget's ancestor is unsafe.

At this point the state of the widget's element tree is no longer stable.

To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

The relevant error-causing widget was:
  LoginScreen file:///Users/taleb/FlutterProjects/lambda/lib/routes.dart:40:36
When the exception was thrown, this was the stack:
#0      Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> (package:flutter/src/widgets/framework.dart:3944:9)
#1      Element._debugCheckStateIsActiveForAncestorLookup (package:flutter/src/widgets/framework.dart:3958:6)
#2      Element.findAncestorWidgetOfExactType (package:flutter/src/widgets/framework.dart:3996:12)
#3      debugCheckHasMediaQuery.<anonymous closure> (package:flutter/src/widgets/debug.dart:218:50)
#4      debugCheckHasMediaQuery (package:flutter/src/widgets/debug.dart:234:4)
...
====================================================================================================

These errors happened when I used TextField in HookConsumerWidget
class.
I am using HookConsumerWidget instead of StatefullWidget.
I also tried to use StatefullConsumerWidget but the problem was not > solved.(ConsumerStatefulWidget+riverPod).
My question is how can we use Textfield in HookConsumerWidget + Riverpod ????

If you want to run it by yourself, I Provided a sample code of this error on my Github:
smaple_hook_riverpod


问:
Find the n largest occurrences of duplicate values in a column
I have a 7GB csv file from which I need to find the first n values which occurred mostly in the 5th column. The format of my file is as:

```<code>"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","389","65311"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","88","49194"
"instance id","src IP","destination ip","12489","49194"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","63812","389"
</code>```

Using the following command
awk -F , ' !count[$5]++ {save[$5] = $0; next} count[$5] > 0 { print save[$5] " is " count[$5] " times"} ' example.csv
able to find the following output

```<code>"instance id","src IP","destination ip","63812","389" is 1 times
"instance id","src IP","destination ip","389","65311" is 1 times
"instance id","src IP","destination ip","63812","389" is 2 times
"instance id","src IP","destination ip","88","49194" is 1 times
"instance id","src IP","destination ip","12489","49194" is 2 times
"instance id","src IP","destination ip","63812","389" is 3 times
"instance id","src IP","destination ip","63812","389" is 4 times
</code>```

but not able to understand how to get the top 50 rows in which the 5th column entry duplicated most of the time.

Let's suppose if n=2, then my output should be like following:

```<code>"instance id","src IP","destination ip","63812","389" is 4 times
"instance id","src IP","destination ip","12489","49194" is 2 times
</code>```

答:
If I were you, I would alter the output into something like:

```<code>1 times : "instance id","src IP","destination ip","63812","389" is 1 times
1 times : "instance id","src IP","destination ip","389","65311" is 1 times
2 times : "instance id","src IP","destination ip","63812","389" is 2 times
1 times : "instance id","src IP","destination ip","88","49169" is 1 times
2 times : "instance id","src IP","destination ip","12489","49194" is 2 times
3 times : "instance id","src IP","destination ip","63812","389" is 3 times
4 times : "instance id","src IP","destination ip","63812","389" is 4 times
</code>```

And then add | sort -n after your command.

(I've been trying using sort -kx -n but the combination of double quotes, commas and spaces messes up the -k switch of the sort command.)

Body:
I have a 7GB csv file from which I need to find the first n values which occurred mostly in the 5th column. The format of my file is as:

"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","389","65311"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","88","49194"
"instance id","src IP","destination ip","12489","49194"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","63812","389"

Using the following command
awk -F , ' !count[$5]++ {save[$5] = $0; next} count[$5] > 0 { print save[$5] " is " count[$5] " times"} ' example.csv
able to find the following output

"instance id","src IP","destination ip","63812","389" is 1 times
"instance id","src IP","destination ip","389","65311" is 1 times
"instance id","src IP","destination ip","63812","389" is 2 times
"instance id","src IP","destination ip","88","49194" is 1 times
"instance id","src IP","destination ip","12489","49194" is 2 times
"instance id","src IP","destination ip","63812","389" is 3 times
"instance id","src IP","destination ip","63812","389" is 4 times

but not able to understand how to get the top 50 rows in which the 5th column entry duplicated most of the time.

Let's suppose if n=2, then my output should be like following:

"instance id","src IP","destination ip","63812","389" is 4 times
"instance id","src IP","destination ip","12489","49194" is 2 times

Body:
If I were you, I would alter the output into something like:

1 times : "instance id","src IP","destination ip","63812","389" is 1 times
1 times : "instance id","src IP","destination ip","389","65311" is 1 times
2 times : "instance id","src IP","destination ip","63812","389" is 2 times
1 times : "instance id","src IP","destination ip","88","49169" is 1 times
2 times : "instance id","src IP","destination ip","12489","49194" is 2 times
3 times : "instance id","src IP","destination ip","63812","389" is 3 times
4 times : "instance id","src IP","destination ip","63812","389" is 4 times

And then add | sort -n after your command.

(I've been trying using sort -kx -n but the combination of double quotes, commas and spaces messes up the -k switch of the sort command.)


问:
Flutter: Create custom dialog as StatefulWidget?
I'm working on an app that will get only 2 inputs from the user, maybe 3 in the future. So I use showDialog with 2 inputfield and 2 buttons. Very simple. Looks pretty much like this:
enter image description here
It shows up perfectly in the main screen if it's being called as a function. But I would like to use that same dialog in another screen in the app and just change the text on one of the buttons. Since the dialog code it's long and I don't want to repeat it, I want to put it in a new StatefulWidget (to retrieve the information from the input fields and clear them afterwards). Now the problem is that I can't find a way to return the dialog from an external widget. I don't know if it's actually impossible because of the whole async Widget incompatibility or I'm just too stupid to figure this out.

This is the code for my dialog (as a function):

```<code>_dialog() async {
  await showDialog<String>(
    context: context,
    child: ButtonBarTheme(
      data: ButtonBarThemeData(alignment: MainAxisAlignment.center),
      child: AlertDialog(
        contentPadding: const EdgeInsets.all(20.0),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: EdgeInsets.only(bottom: 15),
              child: new TextField(
                // onSubmitted: next,
                autofocus: true,
                controller: _title,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.only(bottom: 2),
                  labelText: 'Title',
                  hintText: 'Example: New Smartphone',
                ),
              ),
            ),
            TextField(
              autofocus: true,
              controller: _codigo,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.zero,
                labelText: 'Code',
                hintText: 'Example: EC20008347607',
              ),
            ),
          ],
        ),
        actions: [
          Row(
            children: [
              Container(
                padding: EdgeInsets.only(right: 35, bottom: 5),
                child: FlatButton(
                    color: Colors.cyan[600],
                    child: const Text('CANCEL'),
                    onPressed: () {
                      Navigator.pop(context);
                    }),
              ),
              Container(
                padding: EdgeInsets.only(left: 15, bottom: 5),
                child: FlatButton(
                  color: Colors.cyan[600],
                  child: const Text('ADD'),
                  onPressed: () {
                    setState(() {
                      _title.text = '';
                      _code.text = '';
                    });
                    Navigator.pop(context);
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    ),
  );
}
</code>```

Thanks in advance for any help. I'm a beginner.

答:
I think we have to build our widget from the ground up as there is no dialog box that exposes the state. Hope this helps:

https://api.flutter.dev/flutter/widgets/StatefulBuilder-class.html

Body:
I'm working on an app that will get only 2 inputs from the user, maybe 3 in the future. So I use showDialog with 2 inputfield and 2 buttons. Very simple. Looks pretty much like this:
enter image description here
It shows up perfectly in the main screen if it's being called as a function. But I would like to use that same dialog in another screen in the app and just change the text on one of the buttons. Since the dialog code it's long and I don't want to repeat it, I want to put it in a new StatefulWidget (to retrieve the information from the input fields and clear them afterwards). Now the problem is that I can't find a way to return the dialog from an external widget. I don't know if it's actually impossible because of the whole async Widget incompatibility or I'm just too stupid to figure this out.

This is the code for my dialog (as a function):

_dialog() async {
  await showDialog<String>(
    context: context,
    child: ButtonBarTheme(
      data: ButtonBarThemeData(alignment: MainAxisAlignment.center),
      child: AlertDialog(
        contentPadding: const EdgeInsets.all(20.0),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: EdgeInsets.only(bottom: 15),
              child: new TextField(
                // onSubmitted: next,
                autofocus: true,
                controller: _title,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.only(bottom: 2),
                  labelText: 'Title',
                  hintText: 'Example: New Smartphone',
                ),
              ),
            ),
            TextField(
              autofocus: true,
              controller: _codigo,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.zero,
                labelText: 'Code',
                hintText: 'Example: EC20008347607',
              ),
            ),
          ],
        ),
        actions: [
          Row(
            children: [
              Container(
                padding: EdgeInsets.only(right: 35, bottom: 5),
                child: FlatButton(
                    color: Colors.cyan[600],
                    child: const Text('CANCEL'),
                    onPressed: () {
                      Navigator.pop(context);
                    }),
              ),
              Container(
                padding: EdgeInsets.only(left: 15, bottom: 5),
                child: FlatButton(
                  color: Colors.cyan[600],
                  child: const Text('ADD'),
                  onPressed: () {
                    setState(() {
                      _title.text = '';
                      _code.text = '';
                    });
                    Navigator.pop(context);
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    ),
  );
}

Thanks in advance for any help. I'm a beginner.


问:
save as dataframe python
I am really new in python, so I am doing a consultd and I want that the results be save  like dataframe instead of be just print in the terminal. Here is my code:

```<code>service = Service("https://www.mousemine.org/mousemine/service")
query = service.new_query("Gene")
query.add_view(
    "primaryIdentifier", "symbol", "organism.name",
    "homologues.homologue.primaryIdentifier", "homologues.homologue.symbol",
    "homologues.homologue.organism.name", "homologues.type",
    "homologues.dataSets.name"
)
query.add_constraint("homologues.type", "NONE OF", ["horizontal gene transfer", "least diverged horizontal gene transfer"], code = "B")
query.add_constraint("Gene", "LOOKUP", "ENSMUSG00000026981,ENSMUSG00000068039,ENSMUSG00000035007,ENSMUSG00000022972,", "M. musculus", code = "A")
query.add_constraint("homologues.homologue.organism.name", "=", "Homo sapiens", code = "C")
query.add_constraint("homologues.dataSets.name", "=", "Mouse/Human Orthologies from MGI", code = "D")

   for row in query.rows():
    print(row["primaryIdentifier"], row["symbol"], row["organism.name"], \
        row["homologues.homologue.primaryIdentifier"],
        row["homologues.homologue.symbol"], \
        row["homologues.homologue.organism.name"], row["homologues.type"], \
        row["homologues.dataSets.name"])
</code>```

And this is the result that I get it

MGI:1915251 Cfap298 Mus musculus 56683 CFAP298 Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:2144506 Rundc1 Mus musculus 146923 RUNDC1 Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:96547 Il1rn Mus musculus 3557 IL1RN Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:98535 Tcp1 Mus musculus 6950 TCP1 Homo sapiens orthologue Mouse/Human Orthologies from MGI

And it is perfectly ok, but I need it in a dataframe. And if I can the consult using a table with all the ID and not have to writing one by one (because there are 14000) that will be amazing.

答:
Using a loop:

   df = pd.DataFrame({})

   for row in query.rows():
    data = {'primaryIdentifier': row["primaryIdentifier"],
            'symbol': row["symbol"],
            'organism.name': row["organism.name"],
            'homologues.homologue.primaryIdentifier': row["homologues.homologue.primaryIdentifier"],
            'homologues.homologue.symbol': row["homologues.homologue.symbol"],
            'homologues.homologue.organism.name': row["homologues.homologue.organism.name"],
            'homologues.type': row["homologues.type"],
            'homologues.dataSets.name': row["homologues.dataSets.name"]}
    df = df.append(pd.DataFrame(data), ignore_index = True)

```

Note that you must do an import pandas as pd and make sure that the data are str.

Title: save as dataframe python

Body:
I am really new in python, so I am doing a consultd and I want that the results be save  like dataframe instead of be just print in the terminal. Here is my code:

service = Service("https://www.mousemine.org/mousemine/service")
query = service.new_query("Gene")
query.add_view(
    "primaryIdentifier", "symbol", "organism.name",
    "homologues.homologue.primaryIdentifier", "homologues.homologue.symbol",
    "homologues.homologue.organism.name", "homologues.type",
    "homologues.dataSets.name"
)
query.add_constraint("homologues.type", "NONE OF", ["horizontal gene transfer", "least diverged horizontal gene transfer"], code = "B")
query.add_constraint("Gene", "LOOKUP", "ENSMUSG00000026981,ENSMUSG00000068039,ENSMUSG00000035007,ENSMUSG00000022972,", "M. musculus", code = "A")
query.add_constraint("homologues.homologue.organism.name", "=", "Homo sapiens", code = "C")
query.add_constraint("homologues.dataSets.name", "=", "Mouse/Human Orthologies from MGI", code = "D")

   for row in query.rows():
    print(row["primaryIdentifier"], row["symbol"], row["organism.name"], \
        row["homologues.homologue.primaryIdentifier"],
        row["homologues.homologue.symbol"], \
        row["homologues.homologue.organism.name"], row["homologues.type"], \
        row["homologues.dataSets.name"])

And this is the result that I get it

MGI:1915251 Cfap298 Mus musculus 56683 CFAP298 Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:2144506 Rundc1 Mus musculus 146923 RUNDC1 Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:96547 Il1rn Mus musculus 3557 IL1RN Homo sapiens orthologue Mouse/Human Orthologies from MGI
MGI:98535 Tcp1 Mus musculus 6950 TCP1 Homo sapiens orthologue Mouse/Human Orthologies from MGI

And it is perfectly ok, but I need it in a dataframe. And if I can the consult using a table with all the ID and not have to writing one by one (because there are 14000) that will be amazing.

Body:
Using a loop:

   df = pd.DataFrame({})

   for row in query.rows():
    data = {'primaryIdentifier': row["primaryIdentifier"],
            'symbol': row["symbol"],
            'organism.name': row["organism.name"],
            'homologues.homologue.primaryIdentifier': row["homologues.homologue.primaryIdentifier"],
            'homologues.homologue.symbol': row["homologues.homologue.symbol"],
            'homologues.homologue.organism.name': row["homologues.homologue.organism.name"],
            'homologues.type': row["homologues.type"],
            'homologues.dataSets.name': row["homologues.dataSets.name"]}
    df = df.append(pd.DataFrame(data), ignore_index = True)

Note that you must do an import pandas as pd and make sure that the data are str.