问:
How Can I Convert of String To Integer Value in a List in Python?
This is my code which i did for my project and it takes values from csv file. I got a error from which the data u=in the csv file is taken as string instead of integer. How can i convert it to integer values or float values?

import pandas as pd
proper = []
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper.append([order_id,country])

        #print(proper)

proper = {}
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper[order_id] = country
print(proper)

def get_hash(key):
    hash = 0
    for i in range(key):
        hash += 1
    return hash % 100000
get_hash('8469376')
```

This is the error which I get
TypeError: 'str' object cannot be interpreted as an integer

答:
Change:

```<code>get_hash('8469376')
</code>```

To:

```<code>get_hash(8469376)
</code>```

Since the key param of get_hash function is passed to range function, it must be of type int (and not string as you did).

Body:
This is my code which i did for my project and it takes values from csv file. I got a error from which the data u=in the csv file is taken as string instead of integer. How can i convert it to integer values or float values?

import pandas as pd
proper = []
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper.append([order_id,country])

        #print(proper)

proper = {}
with open("C:\\Users\\krupa\\Downloads\\proper.csv","r") as f:
    for line in f:
        tokens = line.split(',')
        order_id =tokens[0]
        country = tokens[1]

        proper[order_id] = country
print(proper)

def get_hash(key):
    hash = 0
    for i in range(key):
        hash += 1
    return hash % 100000
get_hash('8469376')

This is the error which I get
TypeError: 'str' object cannot be interpreted as an integer

Body:
Change:

get_hash('8469376')

To:

get_hash(8469376)

Since the key param of get_hash function is passed to range function, it must be of type int (and not string as you did).


来源: stackexchange

问:
Matching date and time using regex
I am trying to write a regex that matches the date and time in this format - d/m/Y H:m am/pm. For example, 1/2/2020 1.30pm

This is the regex I am using but it does not match the date and time specified in the example -

```<code>$value = '1/2/2020 1.30pm';
if(preg_match("/^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} (0\d|1[0-2]):([0-5]\d)(?::((?2)))?\h*([ap]m)? $/", $value) === 0) {
     return false;
}else{
     return true;
}
</code>```

Please kindly help correct my mistakes on the regex expression

答:
As others have pointed out, there are lots of ways to validate the date, in addition to matching; you could find some different approaches.  Here is a regex that will match your date, regardless of what you use to separate the numbers.  \W indicates any "non-word character" will match -, or / or anything so long as it isn't a letter, digit or underscore.  The ? will match 0 or 1, and the * will match zero or more.

```<code>^\d+\W\d+\W\d+\s+\d+\W?\d+\w*
</code>```

Will match all of these:

```<code>01/02/2020 11:45am

01-02-2020 10.33pm

1-23-68 2345

09/30/2323 23:15
</code>```

Cheers!
Kylie

ContentLicense: CC BY-SA 4.0

Title: Matching date and time using regex

Body:
I am trying to write a regex that matches the date and time in this format - d/m/Y H:m am/pm. For example, 1/2/2020 1.30pm

This is the regex I am using but it does not match the date and time specified in the example -

$value = '1/2/2020 1.30pm';
if(preg_match("/^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} (0\d|1[0-2]):([0-5]\d)(?::((?2)))?\h*([ap]m)? $/", $value) === 0) {
     return false;
}else{
     return true;
}

Please kindly help correct my mistakes on the regex expression

Body:
As others have pointed out, there are lots of ways to validate the date, in addition to matching; you could find some different approaches.  Here is a regex that will match your date, regardless of what you use to separate the numbers.  \W indicates any "non-word character" will match -, or / or anything so long as it isn't a letter, digit or underscore.  The ? will match 0 or 1, and the * will match zero or more.

^\d+\W\d+\W\d+\s+\d+\W?\d+\w*

Will match all of these:

01/02/2020 11:45am

01-02-2020 10.33pm

1-23-68 2345

09/30/2323 23:15

Cheers!
Kylie


问:
VSCode shortcut for move open editor up / down (not group but open editor)
I don't mean move editor group or viewed file (split editor groups); -- but in the list of open editors in the sidebar.

They can be rearranged by mouse-dragging them into desired position. Can't find the name for shortcut command, if it exists.

For clarity, attaching a screenshot: (it's unfortunately way too large)

Use case is rearranging open editors according to some flow (of data, functions or whatever) to simplify thinking about it.

Thanks!

答:
I do not see any command that would allow you to re-order the Open Editors list directly.

But the order of that list is determined by the order of your opened tabs, so if you move the file tabs around the Open Editors list changes to match.  So these would do what you want:

Move Editor Left:    Ctrl+Shift+PageUp

Move Editor Right:  Ctrl+Shift+PageDown

This works even if you have the setting Editor: Show Tabs disabled so that only a single tab is displayed - you can still move that tab left and right and that is reflected in the Open Editors list!!


问:
How do i put a link in a table
I have a table on my website, which gets data from a database, in the table I have delete buttons on a row, I have just made the table searchable with jQuery, but now I can't figure out how to keep the delete buttons.

index.php:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
    <meta name="description" content="Inventar">
    <meta name="author" content="Martin Eide Bjørndal">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="/src/css/style.css">
       <!-- jQuery library -->
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <!-- Popper JS -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
        <!-- Latest compiled JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

</head>
<body>

    <button class="back" onclick="window.location='../'">
      <img src="/src/icons/back.png">
    </button> <!-- Tilbake knapp -->

    <button class="ny_inventar" onclick="window.location='/admin/brukere/ny'">
      <img src="/src/icons/add.png">
    </button> <!-- Ny Bruker knapp -->

    <div class="container-fluid" id="utskjekkcontainer">
      <div class="row justify-content-center">
        <div class="col-mv-10 bg-light mt-5 rounded p-3">
          <h1 class="text-primary p-2">Brukere</h1>
          <hr>
          <div class="form-inline">
            <label for="search" class="font-weight-bold lead text-dark">Søk</label>
            <input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">
          </div>
          <hr>
          <?php
            include "../../src/fn/init.php";
            $stmt=$conn->prepare("SELECT * FROM brukere");
            $stmt->execute();
            $result=$stmt->get_result();
          ?>
          <table class="table table-hover table-light table-striped" id="table_data">
            <thead>
              <tr>
                <th>#</th>
                <th>Fornavn</th>
                <th>Etternavn</th>
                <th>Utskjekket</th>
                <th>Admin</th>
                <th>Slett</th>
              </tr>
            </thead>
            <tbody>
              <?php while($row=$result->fetch_assoc()){ ?>
                <tr>
                  <td><?php echo $row["id"]; ?></td>
                  <td><?php echo $row["fornavn"]; ?></td>
                  <td><?php echo $row["etternavn"]; ?></td>
                  <td><?php echo $row["utskjekket"]; ?></td>
                  <td><?php echo $row["is_admin"]; ?></td>
                  <td><a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett</a></td>
                </tr>
              <?php }
              $conn->close();
              ?>
             </tbody>

           </table>

        </div>
      </div>
    </div>

    <script type="text/javascript">
      $(document).ready(function(){
        $('#search_text').keyup(function(){
          var search = $(this).val();
          $.ajax({
            url:'action.php',
            method:'post',
            data:{query:search},
            success:function(response){
              $('#table_data').html(response);
            }
          });
        });
      });
    </script>

</body>
</html>
</code>```

action.php:

```<code><?php

    include "../../src/fn/init.php";
    $output = "";

    if(isset($_POST["query"])){
        $search = $_POST["query"];
        $stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
        $stmt->bind_param("sss",$search, $search, $search);
    } else {
        $stmt=$conn->prepare("SELECT * FROM brukere");
    };
    $stmt->execute();
    $result=$stmt->get_result();

    if($result->num_rows>0){
        $output = "<thead>
                    <tr>
                    <th>#</th>
                    <th>Fornavn</th>
                    <th>Etternavn</th>
                    <th>Utskjekket</th>
                    <th>Admin</th>
                    <th>Slett</th>
                    </tr>
                </thead>
                <tbody>";

        while($row=$result->fetch_assoc()){
            $output .= "
                <tr>
                    <td>".$row["id"]."</td>
                    <td>".$row["fornavn"]."</td>
                    <td>".$row["etternavn"]."</td>
                    <td>".$row["utskjekket"]."</td>
                    <td>".$row["is_admin"]."</td>
                    <td>".<a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett</a>."</td>
                </tr>";
        };
        $output .= "</tbody>";
        echo $output;
    } else {
        echo "<h3>No match found!</h3>";
    };

?>
</code>```

This is the search script, the problem is in the while loop where the link is added, I can't figure out how to make it work.

答:
To allow PHP to echo the id from the table result you need to just simply do a php echo

```<code><a href="delete.php?id=<? echo $row['id']; ?>" onclick="return confirm('Er du sikker?');">Slett</a>
</code>```

You don't have to url encode at this stage as you are just simply building the href of an a:link

Title: How do i put a link in a table

Body:
I have a table on my website, which gets data from a database, in the table I have delete buttons on a row, I have just made the table searchable with jQuery, but now I can't figure out how to keep the delete buttons.

index.php:

<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
    <meta name="description" content="Inventar">
    <meta name="author" content="Martin Eide Bjørndal">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="/src/css/style.css">

    <button class="back" onclick="window.location='../'">

    </button>

    <button class="ny_inventar" onclick="window.location='/admin/brukere/ny'">

    </button>

Brukere

            Søk
            <input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">

          <?php
            include "../../src/fn/init.php";
            $stmt=$conn->prepare("SELECT * FROM brukere");
            $stmt->execute();
            $result=$stmt->get_result();
          ?>

                #
                Fornavn
                Etternavn
                Utskjekket
                Admin
                Slett

              <?php while($row=$result->fetch_assoc()){ ?>

                  <?php echo $row["id"]; ?>
                  <?php echo $row["fornavn"]; ?>
                  <?php echo $row["etternavn"]; ?>
                  <?php echo $row["utskjekket"]; ?>
                  <?php echo $row["is_admin"]; ?>
                  <a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett

              <?php }
              $conn->close();
              ?>

action.php:

<?php

    include "../../src/fn/init.php";
    $output = "";

    if(isset($_POST["query"])){
        $search = $_POST["query"];
        $stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
        $stmt->bind_param("sss",$search, $search, $search);
    } else {
        $stmt=$conn->prepare("SELECT * FROM brukere");
    };
    $stmt->execute();
    $result=$stmt->get_result();

    if($result->num_rows>0){
        $output = "

                    #
                    Fornavn
                    Etternavn
                    Utskjekket
                    Admin
                    Slett

";

        while($row=$result->fetch_assoc()){
            $output .= "

                    ".$row["id"]."
                    ".$row["fornavn"]."
                    ".$row["etternavn"]."
                    ".$row["utskjekket"]."
                    ".$row["is_admin"]."
                    ".<a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett."

";
        };
        $output .= "
";
        echo $output;
    } else {
        echo "
No match found!
";
    };

?>

This is the search script, the problem is in the while loop where the link is added, I can't figure out how to make it work.

Body:
To allow PHP to echo the id from the table result you need to just simply do a php echo

<a href="delete.php?id=<? echo $row['id']; ?>" onclick="return confirm('Er du sikker?');">Slett</a>

You don't have to url encode at this stage as you are just simply building the href of an a:link


问:
Wait for Redux props and then do some operations on the props in componentDidMount
I have a ChatBox component for my website, which displays the chat history of a user. The chat history is not ordered in my firestore, so I want to (1) sort it from the most to the least recent in componentDidMount once I get the data via Redux props (this.props.profile.chats_history) and (2) set the field "chatlist" in the state of ChatBox to the sorted array. The problem is that it takes time for props to be received and when the array.sort() method was called the console reported that the array was undefined. I tried to get around it by using async and await keywords but my solution did not work.

My solution

```<code>    async componentDidMount() {
        let chatlist;
        await this.props.profile.chats_history;
        chatlist = this.props.profile.chats_history.sort(function(a, b) {return a.time - b.time});
        this.setState({
            chatlist: chatlist
        })
    }
</code>```

答:
What you can do is wait for chats_history to be updated, using componentDidUpdate instead of componentDidMount. Here I'm doing a deep equal on this.props.chats_history.

```<code>    const _ = require("lodash")
    componentDidUpdate(prevProps, prevState) {
          if (!_.isEqual(prevProps.profile.chats_history, this.props.profile.chats_history)) {
              chatlist = this.props.profile.chats_history.sort(function(a, b) {return a.time - b.time});
              this.setState({
                chatlist: chatlist
              })
       }
    }
</code>```

Basically what's happening here is that as soon as the component mounts, this.props.chats_history will have some value, but it won't contain the actual list of values yet. At some point, this.props.chats_history will be loaded, and this will trigger the component to update.

componentDidUpdate is triggered every time either this.props or this.state is updated. The arguments prevProps and prevState that you see in my code are references to the values of this.props and this.state from immediately before the update occurred that triggered componentDidUpdate.

componentDidUpdate will be triggered many times, and you want to execute your sort function only when it's the loading of this.props.chats_history that has triggered it. To do this, you compare (with _.isEqual) prevProps.chats_history with this.props.chats_history. Is they're not equal, this means that this.props.chats_history was just modified (in this case, loaded), so you call sort only under these circumstances.

The reason I use _.isEqual from the lodash library is that if I did a == or === comparison, it would always return true because this.props.chats_history is an array, and it would therefore be comparing the references rather than the contents of the array. If you use _.isEqual it does a deep comparison and returns true only if each element of this.props.chats_history is equal to each element of prevProps.chats_history.

Since you then call this.setState(), componentDidUpdate will be called again, but the if block will return false and not run the sort code again.

Does that make sense?

Body:
I have a ChatBox component for my website, which displays the chat history of a user. The chat history is not ordered in my firestore, so I want to (1) sort it from the most to the least recent in componentDidMount once I get the data via Redux props (this.props.profile.chats_history) and (2) set the field "chatlist" in the state of ChatBox to the sorted array. The problem is that it takes time for props to be received and when the array.sort() method was called the console reported that the array was undefined. I tried to get around it by using async and await keywords but my solution did not work.

My solution

    async componentDidMount() {
        let chatlist;
        await this.props.profile.chats_history;
        chatlist = this.props.profile.chats_history.sort(function(a, b) {return a.time - b.time});
        this.setState({
            chatlist: chatlist
        })
    }

Body:
What you can do is wait for chats_history to be updated, using componentDidUpdate instead of componentDidMount. Here I'm doing a deep equal on this.props.chats_history.

    const _ = require("lodash")
    componentDidUpdate(prevProps, prevState) {
          if (!_.isEqual(prevProps.profile.chats_history, this.props.profile.chats_history)) {
              chatlist = this.props.profile.chats_history.sort(function(a, b) {return a.time - b.time});
              this.setState({
                chatlist: chatlist
              })
       }
    }

Basically what's happening here is that as soon as the component mounts, this.props.chats_history will have some value, but it won't contain the actual list of values yet. At some point, this.props.chats_history will be loaded, and this will trigger the component to update.

componentDidUpdate is triggered every time either this.props or this.state is updated. The arguments prevProps and prevState that you see in my code are references to the values of this.props and this.state from immediately before the update occurred that triggered componentDidUpdate.

componentDidUpdate will be triggered many times, and you want to execute your sort function only when it's the loading of this.props.chats_history that has triggered it. To do this, you compare (with _.isEqual) prevProps.chats_history with this.props.chats_history. Is they're not equal, this means that this.props.chats_history was just modified (in this case, loaded), so you call sort only under these circumstances.

The reason I use _.isEqual from the lodash library is that if I did a == or === comparison, it would always return true because this.props.chats_history is an array, and it would therefore be comparing the references rather than the contents of the array. If you use _.isEqual it does a deep comparison and returns true only if each element of this.props.chats_history is equal to each element of prevProps.chats_history.

Since you then call this.setState(), componentDidUpdate will be called again, but the if block will return false and not run the sort code again.

Does that make sense?


问:
Write a function in python for temperature conversion named ‘convert_temp’
Write a function for temperature conversion named ‘convert_temp’.

It should be able to handle both Fahrenheit to Celsius conversions as well as Celsius to Fahrenheit conversions.

It must accept and read two arguments that are passed to it: first, the temperature scale of the original temperature (only ‘F’ or ‘C’ should be used) and second, the number of degrees of the original
temperature.

It should then convert the original temperature from Fahrenheit to Celsius or from Celsius to Fahrenheit, as appropriate.

Finally, this function should print out the original temperature and scale as well as the converted temperature and scale.

The function signature should be:

```<code>def convert_temp( scale=None, source_temp=None ):
</code>```

Then write a short program to use the function you wrote (both the function and program should be part of the same file). Your program should prompt the user to enter a temperature scale (assume the user will choose to type ‘F’ or ‘C’) and then prompt the user to enter a number of degrees. Using the values supplied by the user, the program should then call the ‘convert_temp’
function and pass in the two arguments, along these lines:

```<code>convert_temp(scale=F, source_temp=98.6)
</code>```

and the subroutine should produce a line of output that looks like this (for Fahrenheit to Celsius):

```<code>98.6 degrees F is 37.0 degrees C
</code>```

or, for a Celsius to Fahrenheit conversion:

```<code>100.0 degrees C is 212.0 degrees F
</code>```

The first temperature and scale that you should report are those that the user entered, followed by the converted temperature and other scale.

I have the following code so far:

```<code>#!/usr/bin/env python3
def convert_temp(scale=None, source_temp=None):
    if scale == "F":
        return(source_temp - 32.0) * (5.0/9.0)
    elif scale == "C":
        return(source_temp * (9.0/5.0)) + 32.0
    else:
        print("Needs to be (F) or (C)!")

scale = input("Select (F) or (C): " )
source_temp = int(input("What is the temperature: " ))
m = convert_temp(scale, source_temp)
print(source_temp, "degrees", scale, "is", m, "degrees", scale)
</code>```

What need help with, is to add the converted scale (F or C) to my print output.

答:
Just working off the answers above, I gave it a tweak for the benefit of a lazy user - who may not capitalize the F or C at the input part... and instead put "f" or "c" in lower case...
this answer fixes that, and returns scale correctly formatted in title case in the print statement.</p>

```<code>def convert_temp(scale=None, source_temp=None):
if (scale == "F") or (scale == "f"):
    return 'C', (source_temp - 32.0) * (5.0/9.0)
elif (scale == "C") or (scale == "c"):
    return 'F', (source_temp * (9.0/5.0)) + 32.0
else:
    print("Needs to be (F) or (C)!")

scale = input("Select (F) or (C): " )
source_temp = int(input("What is the temperature: " ))
s, m = convert_temp(scale, source_temp)
print(source_temp, "degrees", scale.title(), "is", m, "degrees", s)
</code>```

Body:
Write a function for temperature conversion named ‘convert_temp’.

It should be able to handle both Fahrenheit to Celsius conversions as well as Celsius to Fahrenheit conversions.

It must accept and read two arguments that are passed to it: first, the temperature scale of the original temperature (only ‘F’ or ‘C’ should be used) and second, the number of degrees of the original
temperature.

It should then convert the original temperature from Fahrenheit to Celsius or from Celsius to Fahrenheit, as appropriate.

Finally, this function should print out the original temperature and scale as well as the converted temperature and scale.

The function signature should be:

def convert_temp( scale=None, source_temp=None ):

Then write a short program to use the function you wrote (both the function and program should be part of the same file). Your program should prompt the user to enter a temperature scale (assume the user will choose to type ‘F’ or ‘C’) and then prompt the user to enter a number of degrees. Using the values supplied by the user, the program should then call the ‘convert_temp’
function and pass in the two arguments, along these lines:

convert_temp(scale=F, source_temp=98.6)

and the subroutine should produce a line of output that looks like this (for Fahrenheit to Celsius):

98.6 degrees F is 37.0 degrees C

or, for a Celsius to Fahrenheit conversion:

100.0 degrees C is 212.0 degrees F

The first temperature and scale that you should report are those that the user entered, followed by the converted temperature and other scale.

I have the following code so far:

#!/usr/bin/env python3
def convert_temp(scale=None, source_temp=None):
    if scale == "F":
        return(source_temp - 32.0) * (5.0/9.0)
    elif scale == "C":
        return(source_temp * (9.0/5.0)) + 32.0
    else:
        print("Needs to be (F) or (C)!")

scale = input("Select (F) or (C): " )
source_temp = int(input("What is the temperature: " ))
m = convert_temp(scale, source_temp)
print(source_temp, "degrees", scale, "is", m, "degrees", scale)

What need help with, is to add the converted scale (F or C) to my print output.

Body:
Just working off the answers above, I gave it a tweak for the benefit of a lazy user - who may not capitalize the F or C at the input part... and instead put "f" or "c" in lower case...
this answer fixes that, and returns scale correctly formatted in title case in the print statement.

def convert_temp(scale=None, source_temp=None):
if (scale == "F") or (scale == "f"):
    return 'C', (source_temp - 32.0) * (5.0/9.0)
elif (scale == "C") or (scale == "c"):
    return 'F', (source_temp * (9.0/5.0)) + 32.0
else:
    print("Needs to be (F) or (C)!")

scale = input("Select (F) or (C): " )
source_temp = int(input("What is the temperature: " ))
s, m = convert_temp(scale, source_temp)
print(source_temp, "degrees", scale.title(), "is", m, "degrees", s)


问:
kubernetes: image pull failed due to invalid_token authorization failed
I'm getting this error message on kubernetes when I'm trying to pull an image:

```<code>0s          Normal    Pulling             pod/zeppelin-server-6f5646f56d-6slj2    Pulling image "apache/zeppelin:0.9.0"
0s          Warning   Failed              pod/zeppelin-server-6f5646f56d-6slj2    Failed to pull image "apache/zeppelin:0.9.0": rpc error: code = Unknown desc = failed to pull and unpack image "docker.io/apache/zeppelin:0.9.0": failed to copy: httpReaderSeeker: failed open: server message: invalid_token: authorization failed
0s          Warning   Failed              pod/zeppelin-server-6f5646f56d-6slj2    Error: ErrImagePull
</code>```

Here kubectl get events -w:

```<code><unknown>   Normal    Scheduled           pod/zeppelin                           Successfully assigned zeppelin/zeppelin to k3d-k3s-linkerd-server
47s         Normal    Pulling             pod/zeppelin                           Pulling image "apache/zeppelin:0.9.0"
19s         Warning   Failed              pod/zeppelin-server-6f5646f56d-6slj2   Failed to pull image "apache/zeppelin:0.9.0": rpc error: code = Unknown desc = failed to pull and unpack image "docker.io/apache/zeppelin:0.9.0": failed to copy: httpReaderSeeker: failed open: server message: invalid_token: authorization failed
19s         Warning   Failed              pod/zeppelin-server-6f5646f56d-6slj2   Error: ErrImagePull
</code>```

By other side:

```<code>$ kubectl run zeppelin --image=apache/zeppelin:0.9.0 --restart=Never -v=10
I0531 12:13:29.882735   18907 loader.go:375] Config loaded from file:  /home/jeusdi/.config/k3d/k3s-linkerd/kubeconfig.yaml
I0531 12:13:29.884168   18907 cached_discovery.go:114] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/servergroups.json
I0531 12:13:29.884623   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/autoscaling/v1/serverresources.json
I0531 12:13:29.884623   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/autoscaling/v2beta1/serverresources.json
I0531 12:13:29.884633   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/authentication.k8s.io/v1/serverresources.json
I0531 12:13:29.884693   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/storage.k8s.io/v1/serverresources.json
I0531 12:13:29.884716   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/events.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884728   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/linkerd.io/v1alpha2/serverresources.json
I0531 12:13:29.884773   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/authorization.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884789   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/scheduling.k8s.io/v1/serverresources.json
I0531 12:13:29.884799   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/k3s.cattle.io/v1/serverresources.json
I0531 12:13:29.884826   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/v1/serverresources.json
I0531 12:13:29.884858   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/admissionregistration.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884863   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/apps/v1/serverresources.json
I0531 12:13:29.884868   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/apiextensions.k8s.io/v1/serverresources.json
I0531 12:13:29.884894   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/caching.internal.knative.dev/v1alpha1/serverresources.json
I0531 12:13:29.884922   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/apiextensions.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884929   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/batch/v1/serverresources.json
I0531 12:13:29.884922   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/apiregistration.k8s.io/v1/serverresources.json
I0531 12:13:29.884958   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/storage.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884979   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/networking.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884988   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/policy/v1beta1/serverresources.json
I0531 12:13:29.885002   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/apiregistration.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885008   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/flagger.app/v1beta1/serverresources.json
I0531 12:13:29.885025   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/batch/v1beta1/serverresources.json
I0531 12:13:29.885037   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/admissionregistration.k8s.io/v1/serverresources.json
I0531 12:13:29.885043   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/rbac.authorization.k8s.io/v1/serverresources.json
I0531 12:13:29.885069   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/extensions/v1beta1/serverresources.json
I0531 12:13:29.885076   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/certificates.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885085   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/flagger.app/v1alpha3/serverresources.json
I0531 12:13:29.885109   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/rbac.authorization.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885121   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/networking.k8s.io/v1/serverresources.json
I0531 12:13:29.885152   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/coordination.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885153   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/flagger.app/v1alpha1/serverresources.json
I0531 12:13:29.885182   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/linkerd.io/v1alpha1/serverresources.json
I0531 12:13:29.885182   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/tap.linkerd.io/v1alpha1/serverresources.json
I0531 12:13:29.885222   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/autoscaling/v2beta2/serverresources.json
I0531 12:13:29.885224   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/scheduling.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885247   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/split.smi-spec.io/v1alpha1/serverresources.json
I0531 12:13:29.885255   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/node.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885273   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/authentication.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885297   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/coordination.k8s.io/v1/serverresources.json
I0531 12:13:29.885310   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/discovery.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885311   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/tekton.dev/v1alpha1/serverresources.json
I0531 12:13:29.885363   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/traefik.containo.us/v1alpha1/serverresources.json
I0531 12:13:29.885365   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/tekton.dev/v1beta1/serverresources.json
I0531 12:13:29.885381   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/metrics.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885478   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/authorization.k8s.io/v1/serverresources.json
I0531 12:13:29.885705   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/helm.cattle.io/v1/serverresources.json
I0531 12:13:29.889299   18907 request.go:1068] Request Body: {"kind":"Pod","apiVersion":"v1","metadata":{"name":"zeppelin","creationTimestamp":null,"labels":{"run":"zeppelin"}},"spec":{"containers":[{"name":"zeppelin","image":"apache/zeppelin:0.9.0","resources":{}}],"restartPolicy":"Never","dnsPolicy":"ClusterFirst"},"status":{}}
I0531 12:13:29.889359   18907 round_trippers.go:423] curl -k -v -XPOST  -H "Content-Type: application/json" -H "User-Agent: kubectl/v1.18.3 (linux/amd64) kubernetes/2e7996e" -H "Accept: application/json, */*" -H "Authorization: Basic YWRtaW46NjA4OGZhYmEzNjc3OGFkMGJhNzJiMzhiNzJjZTE5NWQ=" 'https://localhost:6443/api/v1/namespaces/zeppelin/pods'
I0531 12:13:29.912123   18907 round_trippers.go:443] POST https://localhost:6443/api/v1/namespaces/zeppelin/pods 201 Created in 22 milliseconds
I0531 12:13:29.912223   18907 round_trippers.go:449] Response Headers:
I0531 12:13:29.912233   18907 round_trippers.go:452]     Content-Length: 1241
I0531 12:13:29.912244   18907 round_trippers.go:452]     Content-Type: application/json
I0531 12:13:29.912250   18907 round_trippers.go:452]     Date: Sun, 31 May 2020 10:13:29 GMT
I0531 12:13:29.912324   18907 request.go:1068] Response Body: {"kind":"Pod","apiVersion":"v1","metadata":{"name":"zeppelin","namespace":"zeppelin","selfLink":"/api/v1/namespaces/zeppelin/pods/zeppelin","uid":"a01e2b82-2c47-4424-b1e0-d6bedcfe2d50","resourceVersion":"365387","creationTimestamp":"2020-05-31T10:13:29Z","labels":{"run":"zeppelin"}},"spec":{"volumes":[{"name":"default-token-49tq6","secret":{"secretName":"default-token-49tq6","defaultMode":420}}],"containers":[{"name":"zeppelin","image":"apache/zeppelin:0.9.0","resources":{},"volumeMounts":[{"name":"default-token-49tq6","readOnly":true,"mountPath":"/var/run/secrets/kubernetes.io/serviceaccount"}],"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","imagePullPolicy":"IfNotPresent"}],"restartPolicy":"Never","terminationGracePeriodSeconds":30,"dnsPolicy":"ClusterFirst","serviceAccountName":"default","serviceAccount":"default","securityContext":{},"schedulerName":"default-scheduler","tolerations":[{"key":"node.kubernetes.io/not-ready","operator":"Exists","effect":"NoExecute","tolerationSeconds":300},{"key":"node.kubernetes.io/unreachable","operator":"Exists","effect":"NoExecute","tolerationSeconds":300}],"priority":0,"enableServiceLinks":true},"status":{"phase":"Pending","qosClass":"BestEffort"}}
pod/zeppelin created
</code>```

The problem is only with apache/zeppelin. I've deployed other pods:

```<code>$ kubectl get pods
NAME             READY   STATUS              RESTARTS   AGE
spark-master-0   1/1     Running             1          41h
spark-worker-1   1/1     Running             1          41h
spark-worker-0   1/1     Running             1          41h
zeppelin         0/1     ContainerCreating   0          5m14s
</code>```

答: You might want to perform a login into the container registry (docker.io) in your deployment or create a custom dockerfile with your credentials for the registry and store it in the container and then use that image for the deployment.</p>

Body:
I'm getting this error message on kubernetes when I'm trying to pull an image:

0s          Normal    Pulling             pod/zeppelin-server-6f5646f56d-6slj2    Pulling image "apache/zeppelin:0.9.0"
0s          Warning   Failed              pod/zeppelin-server-6f5646f56d-6slj2    Failed to pull image "apache/zeppelin:0.9.0": rpc error: code = Unknown desc = failed to pull and unpack image "docker.io/apache/zeppelin:0.9.0": failed to copy: httpReaderSeeker: failed open: server message: invalid_token: authorization failed
0s          Warning   Failed              pod/zeppelin-server-6f5646f56d-6slj2    Error: ErrImagePull

Here kubectl get events -w:

<unknown>   Normal    Scheduled           pod/zeppelin                           Successfully assigned zeppelin/zeppelin to k3d-k3s-linkerd-server
47s         Normal    Pulling             pod/zeppelin                           Pulling image "apache/zeppelin:0.9.0"
19s         Warning   Failed              pod/zeppelin-server-6f5646f56d-6slj2   Failed to pull image "apache/zeppelin:0.9.0": rpc error: code = Unknown desc = failed to pull and unpack image "docker.io/apache/zeppelin:0.9.0": failed to copy: httpReaderSeeker: failed open: server message: invalid_token: authorization failed
19s         Warning   Failed              pod/zeppelin-server-6f5646f56d-6slj2   Error: ErrImagePull

By other side:

$ kubectl run zeppelin --image=apache/zeppelin:0.9.0 --restart=Never -v=10
I0531 12:13:29.882735   18907 loader.go:375] Config loaded from file:  /home/jeusdi/.config/k3d/k3s-linkerd/kubeconfig.yaml
I0531 12:13:29.884168   18907 cached_discovery.go:114] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/servergroups.json
I0531 12:13:29.884623   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/autoscaling/v1/serverresources.json
I0531 12:13:29.884623   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/autoscaling/v2beta1/serverresources.json
I0531 12:13:29.884633   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/authentication.k8s.io/v1/serverresources.json
I0531 12:13:29.884693   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/storage.k8s.io/v1/serverresources.json
I0531 12:13:29.884716   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/events.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884728   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/linkerd.io/v1alpha2/serverresources.json
I0531 12:13:29.884773   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/authorization.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884789   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/scheduling.k8s.io/v1/serverresources.json
I0531 12:13:29.884799   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/k3s.cattle.io/v1/serverresources.json
I0531 12:13:29.884826   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/v1/serverresources.json
I0531 12:13:29.884858   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/admissionregistration.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884863   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/apps/v1/serverresources.json
I0531 12:13:29.884868   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/apiextensions.k8s.io/v1/serverresources.json
I0531 12:13:29.884894   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/caching.internal.knative.dev/v1alpha1/serverresources.json
I0531 12:13:29.884922   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/apiextensions.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884929   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/batch/v1/serverresources.json
I0531 12:13:29.884922   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/apiregistration.k8s.io/v1/serverresources.json
I0531 12:13:29.884958   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/storage.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884979   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/networking.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.884988   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/policy/v1beta1/serverresources.json
I0531 12:13:29.885002   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/apiregistration.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885008   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/flagger.app/v1beta1/serverresources.json
I0531 12:13:29.885025   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/batch/v1beta1/serverresources.json
I0531 12:13:29.885037   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/admissionregistration.k8s.io/v1/serverresources.json
I0531 12:13:29.885043   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/rbac.authorization.k8s.io/v1/serverresources.json
I0531 12:13:29.885069   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/extensions/v1beta1/serverresources.json
I0531 12:13:29.885076   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/certificates.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885085   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/flagger.app/v1alpha3/serverresources.json
I0531 12:13:29.885109   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/rbac.authorization.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885121   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/networking.k8s.io/v1/serverresources.json
I0531 12:13:29.885152   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/coordination.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885153   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/flagger.app/v1alpha1/serverresources.json
I0531 12:13:29.885182   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/linkerd.io/v1alpha1/serverresources.json
I0531 12:13:29.885182   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/tap.linkerd.io/v1alpha1/serverresources.json
I0531 12:13:29.885222   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/autoscaling/v2beta2/serverresources.json
I0531 12:13:29.885224   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/scheduling.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885247   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/split.smi-spec.io/v1alpha1/serverresources.json
I0531 12:13:29.885255   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/node.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885273   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/authentication.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885297   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/coordination.k8s.io/v1/serverresources.json
I0531 12:13:29.885310   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/discovery.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885311   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/tekton.dev/v1alpha1/serverresources.json
I0531 12:13:29.885363   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/traefik.containo.us/v1alpha1/serverresources.json
I0531 12:13:29.885365   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/tekton.dev/v1beta1/serverresources.json
I0531 12:13:29.885381   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/metrics.k8s.io/v1beta1/serverresources.json
I0531 12:13:29.885478   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/authorization.k8s.io/v1/serverresources.json
I0531 12:13:29.885705   18907 cached_discovery.go:71] returning cached discovery info from /home/jeusdi/.kube/cache/discovery/localhost_6443/helm.cattle.io/v1/serverresources.json
I0531 12:13:29.889299   18907 request.go:1068] Request Body: {"kind":"Pod","apiVersion":"v1","metadata":{"name":"zeppelin","creationTimestamp":null,"labels":{"run":"zeppelin"}},"spec":{"containers":[{"name":"zeppelin","image":"apache/zeppelin:0.9.0","resources":{}}],"restartPolicy":"Never","dnsPolicy":"ClusterFirst"},"status":{}}
I0531 12:13:29.889359   18907 round_trippers.go:423] curl -k -v -XPOST  -H "Content-Type: application/json" -H "User-Agent: kubectl/v1.18.3 (linux/amd64) kubernetes/2e7996e" -H "Accept: application/json, */*" -H "Authorization: Basic YWRtaW46NjA4OGZhYmEzNjc3OGFkMGJhNzJiMzhiNzJjZTE5NWQ=" 'https://localhost:6443/api/v1/namespaces/zeppelin/pods'
I0531 12:13:29.912123   18907 round_trippers.go:443] POST https://localhost:6443/api/v1/namespaces/zeppelin/pods 201 Created in 22 milliseconds
I0531 12:13:29.912223   18907 round_trippers.go:449] Response Headers:
I0531 12:13:29.912233   18907 round_trippers.go:452]     Content-Length: 1241
I0531 12:13:29.912244   18907 round_trippers.go:452]     Content-Type: application/json
I0531 12:13:29.912250   18907 round_trippers.go:452]     Date: Sun, 31 May 2020 10:13:29 GMT
I0531 12:13:29.912324   18907 request.go:1068] Response Body: {"kind":"Pod","apiVersion":"v1","metadata":{"name":"zeppelin","namespace":"zeppelin","selfLink":"/api/v1/namespaces/zeppelin/pods/zeppelin","uid":"a01e2b82-2c47-4424-b1e0-d6bedcfe2d50","resourceVersion":"365387","creationTimestamp":"2020-05-31T10:13:29Z","labels":{"run":"zeppelin"}},"spec":{"volumes":[{"name":"default-token-49tq6","secret":{"secretName":"default-token-49tq6","defaultMode":420}}],"containers":[{"name":"zeppelin","image":"apache/zeppelin:0.9.0","resources":{},"volumeMounts":[{"name":"default-token-49tq6","readOnly":true,"mountPath":"/var/run/secrets/kubernetes.io/serviceaccount"}],"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","imagePullPolicy":"IfNotPresent"}],"restartPolicy":"Never","terminationGracePeriodSeconds":30,"dnsPolicy":"ClusterFirst","serviceAccountName":"default","serviceAccount":"default","securityContext":{},"schedulerName":"default-scheduler","tolerations":[{"key":"node.kubernetes.io/not-ready","operator":"Exists","effect":"NoExecute","tolerationSeconds":300},{"key":"node.kubernetes.io/unreachable","operator":"Exists","effect":"NoExecute","tolerationSeconds":300}],"priority":0,"enableServiceLinks":true},"status":{"phase":"Pending","qosClass":"BestEffort"}}
pod/zeppelin created

The problem is only with apache/zeppelin. I've deployed other pods:

$ kubectl get pods
NAME             READY   STATUS              RESTARTS   AGE
spark-master-0   1/1     Running             1          41h
spark-worker-1   1/1     Running             1          41h
spark-worker-0   1/1     Running             1          41h
zeppelin         0/1     ContainerCreating   0          5m14s


问:
SQL TIMESTAMP DEFAULT CURRENT TIMESTAMP: How to remove miliseconds?
Problem: When I print time in my HTML code it shows like this: 2020-05-31 03:29:50.617897

Code: https://i.stack.imgur.com/HTIXy.png

Question: How to get rid of decimal .617897? Thank you. I'm new to programming.

Body:
Like this?

a = '2020-05-31 03:29:50.617897'
a = a.split('.')[0]
print(a)

Output:

'2020-05-31 03:29:50'


问:
How to access Flask web server from mobile device?
I have FLask web development server running on my Mac @ 127.0.0.1:5000/. Both my mac and my android device are connected to the same WLAN. I am unable to access my flask website by entering the IP address of my mac(192.168.8.103:5000) into the browser of my android device. But I can access the webpage from my apache server running on my Mac by entering 192.168.8.103 into the browser of my android device. Can I access the flask webserver from my mobile?

答:
You need to run the app with your IPv4 address

app.run(debug=True, host= '192.168.8.103') assuming 192.168.8.103 is your IPv4 if not, replace it with your IPv4


问:
C++ Union, garbage value
For the following code

```<code>#include <iostream>

using namespace std;

union type
{
    int a;
    char b ;
};

int main()
{
    type first;
    first.b = 'a';
    cout << first.a << " " << first.b << endl;

}
</code>```

the output is -858993567 a (MSVC) or 4201057 a(g++ MINGW).

but for

```<code>#include <iostream>

using namespace std;

union type
{
    int a;
    char b ;
};

int main()
{
    type first;
    first.a = 0;
    first.b = 'a';
    cout << first.a << " " << first.b << endl;

}
</code>```

the output is 97 a

And these values are fixed under every circumstances (tried rebooting and creating new workspace/file, hence not garbage values).

So, why did the initialization (in the second case) made a difference?

I have tried it both on visual studio (using MSVC) and visual studio code (using g++).

Update 1
I checked on online IDE which probably use Linux g++, and they give the exact expected answer i.e., 97 a, in both the cases.

答:
If you specify first.a in first code sample - you will get fixed, stable value.

You have union with 4 bytes size and initialize only one byte of them.

Title: C++ Union, garbage value

Body:
For the following code

#include <iostream>

using namespace std;

union type
{
    int a;
    char b ;
};

int main()
{
    type first;
    first.b = 'a';
    cout << first.a << " " << first.b << endl;

}

the output is -858993567 a (MSVC) or 4201057 a(g++ MINGW).

but for

#include <iostream>

using namespace std;

union type
{
    int a;
    char b ;
};

int main()
{
    type first;
    first.a = 0;
    first.b = 'a';
    cout << first.a << " " << first.b << endl;

}

the output is 97 a

And these values are fixed under every circumstances (tried rebooting and creating new workspace/file, hence not garbage values).

So, why did the initialization (in the second case) made a difference?

I have tried it both on visual studio (using MSVC) and visual studio code (using g++).

Update 1
I checked on online IDE which probably use Linux g++, and they give the exact expected answer i.e., 97 a, in both the cases.


问:
Add element in sorted array recursively in C
The task is to insert an element into each matrix row in 2 ways: iterative and recoursive. I've completed iterative one, but don't understand how to change it to recoursive. Appreciate any help.
Here is my function, n - number row elements, key - the value to implement in rows:

```<code>void insertSorted(int arr[], int n, int key)
{
    int i;
    for (i = n - 1; (i >= 0 && arr[i] > key); i--)
        arr[i + 1] = arr[i];

    arr[i + 1] = key;
}
</code>```

And here is the code:

```<code>#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#define MAX 10

void insertSorted(int arr[], int n, int key)
{
    int i;
    for (i = n - 1; (i >= 0 && arr[i] > key); i--)
        arr[i + 1] = arr[i];

    arr[i + 1] = key;
}

int main()
{
    int arr[MAX][MAX];
    int row, col;
    int i, key;

    printf("Enter the matrix size:\nRows: ");
    scanf("%d", &row);
    printf("Cols: ");
    scanf("%d", &col);

    printf("\nEnter %dx%d matrix with sorted rows:\n", row, col);
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)
            scanf("%d", &arr[i][j]);

    printf("\nBefore Insertion:\n");
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++)
            printf("%d  ", arr[i][j]);
        puts(" ");
    }
    printf("\nEnter the number to insert in rows: ");
    scanf("%d", &key);

    for (int i = 0; i < row; i++)
        insertSorted(arr[i], col, key);
    col++;

    printf("\nAfter Insertion:\n");
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++)
            printf("%d  ", arr[i][j]);
        puts("");
    }
    return 0;
}
</code>```

答:
```<code>void RecursiveInsertSorted(int arr[], int n, int key)
{
    if(n==0)
        arr[n]=key;
        return;
    if(arr[n-1]>key){
        arr[n]=arr[n-1];
        RecursiveInsertSorted(arr,n-1,key);
    }
    else{
        arr[n]=key;
        return;
    }
}
</code>```

Body:
The task is to insert an element into each matrix row in 2 ways: iterative and recoursive. I've completed iterative one, but don't understand how to change it to recoursive. Appreciate any help.
Here is my function, n - number row elements, key - the value to implement in rows:

void insertSorted(int arr[], int n, int key)
{
    int i;
    for (i = n - 1; (i >= 0 && arr[i] > key); i--)
        arr[i + 1] = arr[i];

    arr[i + 1] = key;
}

And here is the code:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#define MAX 10

void insertSorted(int arr[], int n, int key)
{
    int i;
    for (i = n - 1; (i >= 0 && arr[i] > key); i--)
        arr[i + 1] = arr[i];

    arr[i + 1] = key;
}

int main()
{
    int arr[MAX][MAX];
    int row, col;
    int i, key;

    printf("Enter the matrix size:\nRows: ");
    scanf("%d", &row);
    printf("Cols: ");
    scanf("%d", &col);

    printf("\nEnter %dx%d matrix with sorted rows:\n", row, col);
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)
            scanf("%d", &arr[i][j]);

    printf("\nBefore Insertion:\n");
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++)
            printf("%d  ", arr[i][j]);
        puts(" ");
    }
    printf("\nEnter the number to insert in rows: ");
    scanf("%d", &key);

    for (int i = 0; i < row; i++)
        insertSorted(arr[i], col, key);
    col++;

    printf("\nAfter Insertion:\n");
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++)
            printf("%d  ", arr[i][j]);
        puts("");
    }
    return 0;
}


问:
Time complexity (Pythagorean Triples)
I have written two different algorithms to calculate Pythagorean Triples:

```<code>import java.util.*;

class Untitled {
  public static void main(String[] args) {

    int n = 20;

    System.out.println("--------------------");
    algorithmOne(n);
    System.out.println("--------------------\n");
    algorithmTwo(n);
    System.out.println("--------------------");
  }

  public static void algorithmOne(int n){

    long startTime = System.nanoTime();

    for (int i = 1 ; i <= n ; i++) {
      for (int j = 1 ; j <= n ; j++) {
        for (int k = 1; k <= n ; k++) {
          if (Math.pow(i,2) + Math.pow(j,2) == Math.pow(k,2)) {
            System.out.println(i + "," + j + "," + k);
          }
        }
      }
    }

    System.out.println("Run Time: " + (System.nanoTime() - startTime)/1000000 + " milliseconds");
  }

  public static void algorithmTwo(int n){

    long startTime = System.nanoTime();

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

    // O(n)
    for(int i = 1 ; ; i++) {
      if ((int)Math.sqrt(i) > n) {
        break;
      }
      if (Math.sqrt(i) == (int)Math.sqrt(i)) {
        squares.add(i);
      }
    }

    // O(n^3)
    for (int i = 0 ; i < squares.size() ; i++) {
      for (int j = 0 ; j < squares.size() ; j++) {
        for (int k = 0 ; k < squares.size() ; k++) {
          if (squares.get(i) + squares.get(j) == squares.get(k)) {
            System.out.println((int)Math.sqrt(squares.get(i)) + "," + (int)Math.sqrt(squares.get(j)) + "," + (int)Math.sqrt(squares.get(k)));
          }
        }
      }
    }

    System.out.println("Run Time: " + (System.nanoTime() - startTime)/1000000 + " milliseconds");

  }
}
</code>```

I believe both algorithms are O(n^3), however when I calculate the time they take to run, the second algorithm is a lot faster. using n=20, algorithm1 takes about 60 milliseconds and algorithms takes about 5 milliseconds. How can these two algorithms have the same time complexity, but one runs faster than the other? I understand that the second algorithm doesn't have to iterate over as many numbers in the triple for loop, but shouldn't that mean that the time complexity would be less?

答:
The big-O notation "hides the constant". Two algorithms, one that runs in 5n^3 milliseconds and another that runs in 5000000n^3 milliseconds would both have complexity O(n^3), but the second one would be million times slower. This is why big-O notation does not tell the entire story. For example there's a lot of different sorting algorithms that are O(N log N), yet some of them are faster than others, or faster than others on specific inputs, etc... There's more to performance than a basic introductory book to algorithms would tell you.

As far as your code goes, it seems that accessing a value within an array is faster than calculating Math.pow, therefore the version that precomputes the squares is faster overall. However, I guess that Math.pow in java is costlier than a simple integer multiplication. I would try replacing it with simple multiplication: i*i + j*j == k*k and see if there's any significant difference after that. Even if it's still slower than the 2nd algorithm, it's worth knowing that re-calculating some value may be faster than fetching it from memory in some circumstances.

Another unrelated thing I noticed in your code, is that you assume that the complexity of your square-calculating loop is O(n):

```<code>// O(n)
for(int i = 1 ; ; i++) {
  if ((int)Math.sqrt(i) > n) break;
  ...
}
</code>```

This isn't true though. You loop while sqrt(i) <= n, that is i <= n*n. Therefore the loop is executed n^2 times, giving a complexity of O(n^2) for that loop. The following loop does indeed have O(n) complexity:

```<code>// O(n)
for(int i = 1 ; i<=n; i++) {
   squares.add(i*i);
}
</code>```

It will run faster, but won't make much of a different due to the overall O(n^3) complexity of the entire algorithm.

Title: Time complexity (Pythagorean Triples)

Body:
I have written two different algorithms to calculate Pythagorean Triples:

import java.util.*;

class Untitled {
  public static void main(String[] args) {

    int n = 20;

    System.out.println("--------------------");
    algorithmOne(n);
    System.out.println("--------------------\n");
    algorithmTwo(n);
    System.out.println("--------------------");
  }

  public static void algorithmOne(int n){

    long startTime = System.nanoTime();

    for (int i = 1 ; i <= n ; i++) {
      for (int j = 1 ; j <= n ; j++) {
        for (int k = 1; k <= n ; k++) {
          if (Math.pow(i,2) + Math.pow(j,2) == Math.pow(k,2)) {
            System.out.println(i + "," + j + "," + k);
          }
        }
      }
    }

    System.out.println("Run Time: " + (System.nanoTime() - startTime)/1000000 + " milliseconds");
  }

  public static void algorithmTwo(int n){

    long startTime = System.nanoTime();

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

    // O(n)
    for(int i = 1 ; ; i++) {
      if ((int)Math.sqrt(i) > n) {
        break;
      }
      if (Math.sqrt(i) == (int)Math.sqrt(i)) {
        squares.add(i);
      }
    }

    // O(n^3)
    for (int i = 0 ; i < squares.size() ; i++) {
      for (int j = 0 ; j < squares.size() ; j++) {
        for (int k = 0 ; k < squares.size() ; k++) {
          if (squares.get(i) + squares.get(j) == squares.get(k)) {
            System.out.println((int)Math.sqrt(squares.get(i)) + "," + (int)Math.sqrt(squares.get(j)) + "," + (int)Math.sqrt(squares.get(k)));
          }
        }
      }
    }

    System.out.println("Run Time: " + (System.nanoTime() - startTime)/1000000 + " milliseconds");

  }
}

I believe both algorithms are O(n^3), however when I calculate the time they take to run, the second algorithm is a lot faster. using n=20, algorithm1 takes about 60 milliseconds and algorithms takes about 5 milliseconds. How can these two algorithms have the same time complexity, but one runs faster than the other? I understand that the second algorithm doesn't have to iterate over as many numbers in the triple for loop, but shouldn't that mean that the time complexity would be less?

Body:
The big-O notation "hides the constant". Two algorithms, one that runs in 5n^3 milliseconds and another that runs in 5000000n^3 milliseconds would both have complexity O(n^3), but the second one would be million times slower. This is why big-O notation does not tell the entire story. For example there's a lot of different sorting algorithms that are O(N log N), yet some of them are faster than others, or faster than others on specific inputs, etc... There's more to performance than a basic introductory book to algorithms would tell you.

As far as your code goes, it seems that accessing a value within an array is faster than calculating Math.pow, therefore the version that precomputes the squares is faster overall. However, I guess that Math.pow in java is costlier than a simple integer multiplication. I would try replacing it with simple multiplication: i*i + j*j == k*k and see if there's any significant difference after that. Even if it's still slower than the 2nd algorithm, it's worth knowing that re-calculating some value may be faster than fetching it from memory in some circumstances.

Another unrelated thing I noticed in your code, is that you assume that the complexity of your square-calculating loop is O(n):

// O(n)
for(int i = 1 ; ; i++) {
  if ((int)Math.sqrt(i) > n) break;
  ...
}

This isn't true though. You loop while sqrt(i) <= n, that is i <= n*n. Therefore the loop is executed n^2 times, giving a complexity of O(n^2) for that loop. The following loop does indeed have O(n) complexity:

// O(n)
for(int i = 1 ; i<=n; i++) {
   squares.add(i*i);
}

It will run faster, but won't make much of a different due to the overall O(n^3) complexity of the entire algorithm.


问:
service.foo is not a function Angular
my component isn't recognizing a function in a service

```<code>import { Injectable } from '@angular/core';
import { ToastController } from '@ionic/angular';

@Injectable({
  providedIn: 'root'
})
export class LocationService {

  private coordinates: any;
  constructor(
    private toastCtrl: ToastController
  ) { }

  set setCoords(coords: any) {
    this.coordinates = coords;
    this.toastCtrl.create({
      message: `Coordinates Assigned ${this.coordinates.latitude},${this.coordinates.longitude}`
    }).then(alertCtrl => {
      alertCtrl.present();
    });
  }
  get getCoords(): any {
    return this.coordinates;
  }
}

</code>```

Here is my component (app.component.ts) where I'm trying to access my function

```<code>  Geolocation.getCurrentPosition({ enableHighAccuracy: true, timeout: 5000 }).then(loc => {
        alert('Latitude: ' + loc.coords.latitude + 'Longitude: ' + loc.coords.longitude);
        console.log('Location: ', loc);
        this.locationService.setCoords(loc);
      }).catch(err => {
        alert(err);
        console.log('Error while getting location:', err);
      });
</code>```

But unfortunately get the following error, to which I've absolutely no clue why it's not detecting the function, although everything seems to be correct. I've tried to restart the app run it again, but nothing working.

```<code>Error while getting location: TypeError: this.locationService.setCoords is not a function
    at app.component.ts:56
    at ZoneDelegate.invoke (zone-evergreen.js:359)
    at Object.onInvoke (core.js:34201)
    at ZoneDelegate.invoke (zone-evergreen.js:358)
    at Zone.run (zone-evergreen.js:124)
    at zone-evergreen.js:855
    at ZoneDelegate.invokeTask (zone-evergreen.js:391)
    at Object.onInvokeTask (core.js:34182)
    at ZoneDelegate.invokeTask (zone-evergreen.js:390)
    at Zone.runTask (zone-evergreen.js:168)
</code>```

答: I got it wrong, its just a accessor and I was accessing it in a wrong way, i.e. the correct way was to access it without brackets .</p>

Title: service.foo is not a function Angular

Body:
my component isn't recognizing a function in a service

import { Injectable } from '@angular/core';
import { ToastController } from '@ionic/angular';

@Injectable({
  providedIn: 'root'
})
export class LocationService {

  private coordinates: any;
  constructor(
    private toastCtrl: ToastController
  ) { }

  set setCoords(coords: any) {
    this.coordinates = coords;
    this.toastCtrl.create({
      message: `Coordinates Assigned ${this.coordinates.latitude},${this.coordinates.longitude}`
    }).then(alertCtrl => {
      alertCtrl.present();
    });
  }
  get getCoords(): any {
    return this.coordinates;
  }
}

Here is my component (app.component.ts) where I'm trying to access my function

  Geolocation.getCurrentPosition({ enableHighAccuracy: true, timeout: 5000 }).then(loc => {
        alert('Latitude: ' + loc.coords.latitude + 'Longitude: ' + loc.coords.longitude);
        console.log('Location: ', loc);
        this.locationService.setCoords(loc);
      }).catch(err => {
        alert(err);
        console.log('Error while getting location:', err);
      });

But unfortunately get the following error, to which I've absolutely no clue why it's not detecting the function, although everything seems to be correct. I've tried to restart the app run it again, but nothing working.

Error while getting location: TypeError: this.locationService.setCoords is not a function
    at app.component.ts:56
    at ZoneDelegate.invoke (zone-evergreen.js:359)
    at Object.onInvoke (core.js:34201)
    at ZoneDelegate.invoke (zone-evergreen.js:358)
    at Zone.run (zone-evergreen.js:124)
    at zone-evergreen.js:855
    at ZoneDelegate.invokeTask (zone-evergreen.js:391)
    at Object.onInvokeTask (core.js:34182)
    at ZoneDelegate.invokeTask (zone-evergreen.js:390)
    at Zone.runTask (zone-evergreen.js:168)


问:
How can I replace a hash key with another key?
I have a condition that gets a hash.

```<code>  hash = {"_id"=>"4de7140772f8be03da000018", .....}
</code>```

Yet, I want to rename the key of that hash as follows.

```<code>  hash = {"id"=>"4de7140772f8be03da000018", ......}
</code>```

P.S. I don't know what keys are in the hash; they are random. Some keys are prefixed with an underscore that I would like to remove.

Body:
I have a condition that gets a hash.

  hash = {"_id"=>"4de7140772f8be03da000018", .....}

Yet, I want to rename the key of that hash as follows.

  hash = {"id"=>"4de7140772f8be03da000018", ......}

P.S. I don't know what keys are in the hash; they are random. Some keys are prefixed with an underscore that I would like to remove.

Body: hash.each {|k,v| hash.delete(k) && hash[k[1..-1]]=v if k[0,1] == '_'}

ContentLicense: CC BY-SA 3.0


问:
Is there any better way to send information to child view?
I have a view controller which has a child view. I want to convey information from the view to the child view. To do so, I did this :

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "visualize", sender: self)
    invoiceNumber = indexPath.row
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc = segue.destination as! PreviewViewController
    vc.invoiceNumber = invoiceNumber
}
</code>```

But the problem is that the value of invoiceNumber is not updated on the first iteration but on the second. I tried to see what the problem was and found that "invoiceNumber = indexPath.row" runs after "vc.invoiceNumber = invoiceNumber". Please help ! Thanks

Here is the code of printing :

```<code>import UIKit

class ViewController: UIViewController {
    var invoiceNumber: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(invoiceNumber)
    }
}
</code>```

Sorry I have mistaken :

```<code>    var customerData: [[customerInformation]] = []
    var itemsData: [[Item]] = []
    var totalData: [TotalInformation] = []

    var invoiceNumber = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.reloadData()
    }

    override func viewDidAppear(_ animated: Bool) {
        let tabBar = tabBarController as! baseTabBarController
        customerData = tabBar.customerData
        itemsData = tabBar.itemsData
        totalData = tabBar.totalData
        tableView.reloadData()

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return customerData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let invoiceCell = tableView.dequeueReusableCell(withIdentifier: "invoice", for: indexPath) as! invoiceTableViewCell
        invoiceCell.textLabel?.text = (customerData[indexPath.row][0]).input
        invoiceCell.detailTextLabel?.text = "Invoice n°" + String(indexPath.row)
        invoiceCell.totalLabel.text = (totalData[indexPath.row]).total
        return invoiceCell
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let tabBar = tabBarController as! baseTabBarController
            tabBar.customerData.remove(at: indexPath.row)
            //itemData.remove(at: indexPath.row)
            tabBar.totalData.remove(at: indexPath.row)
            customerData = tabBar.customerData
            itemsData = tabBar.itemsData
            totalData = tabBar.totalData
            tableView.deleteRows(at: [indexPath], with: .fade)

        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        invoiceNumber = indexPath.row
        print(invoiceNumber, "yes")
        performSegue(withIdentifier: "visualize", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! PreviewViewController
        vc.invoiceNumber = invoiceNumber
    }
}
</code>```

It is the "vc.invoiceNumber = invoiceNumber" which comes before the "invoiceNumber = indexPath.row" as I tried to change the value of invoiceNumber a variable in the view and print out the value in the child view and if showed its value first (I tested -1).

I added the Preview view controller which receives the invoiceNumber :

```<code>import UIKit
import WebKit

class PreviewViewController: UIViewController {

    @IBOutlet var webPreview: UIWebView!

    var invoiceComposer: InvoiceComposer!
    var HTMLContent: String!

    var invoiceNumber: Int = -1

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(invoiceNumber)
        createInvoiceAsHTML()
    }

    func createInvoiceAsHTML() {
        invoiceComposer = InvoiceComposer()
        if let tabBar = tabBarController as? baseTabBarController {
            if let invoiceHTML = invoiceComposer.renderInvoice(invoiceNumber: String(invoiceNumber), invoiceDate: "", recipientInfo: tabBar.customerData[invoiceNumber][0].input, items: tabBar.itemsData[invoiceNumber], totalAmount: tabBar.totalData[invoiceNumber].total) {

                   webPreview.loadHTMLString(invoiceHTML, baseURL: NSURL(string: invoiceComposer.pathToInvoiceHTMLTemplate!)! as URL)
                   HTMLContent = invoiceHTML
            }
        }
        else {
            print("tabBarController is not of type baseTabBarController or either nil ")
        }

    }

}
</code>```

答:
Change the order of execution, like this:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    invoiceNumber = indexPath.row
    performSegue(withIdentifier: "visualize", sender: self)
}
```

Body:
I have a view controller which has a child view. I want to convey information from the view to the child view. To do so, I did this :

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "visualize", sender: self)
    invoiceNumber = indexPath.row
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc = segue.destination as! PreviewViewController
    vc.invoiceNumber = invoiceNumber
}

But the problem is that the value of invoiceNumber is not updated on the first iteration but on the second. I tried to see what the problem was and found that "invoiceNumber = indexPath.row" runs after "vc.invoiceNumber = invoiceNumber". Please help ! Thanks

Here is the code of printing :

import UIKit

class ViewController: UIViewController {
    var invoiceNumber: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(invoiceNumber)
    }
}

Sorry I have mistaken :

    var customerData: [[customerInformation]] = []
    var itemsData: [[Item]] = []
    var totalData: [TotalInformation] = []

    var invoiceNumber = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.reloadData()
    }

    override func viewDidAppear(_ animated: Bool) {
        let tabBar = tabBarController as! baseTabBarController
        customerData = tabBar.customerData
        itemsData = tabBar.itemsData
        totalData = tabBar.totalData
        tableView.reloadData()

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return customerData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let invoiceCell = tableView.dequeueReusableCell(withIdentifier: "invoice", for: indexPath) as! invoiceTableViewCell
        invoiceCell.textLabel?.text = (customerData[indexPath.row][0]).input
        invoiceCell.detailTextLabel?.text = "Invoice n°" + String(indexPath.row)
        invoiceCell.totalLabel.text = (totalData[indexPath.row]).total
        return invoiceCell
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let tabBar = tabBarController as! baseTabBarController
            tabBar.customerData.remove(at: indexPath.row)
            //itemData.remove(at: indexPath.row)
            tabBar.totalData.remove(at: indexPath.row)
            customerData = tabBar.customerData
            itemsData = tabBar.itemsData
            totalData = tabBar.totalData
            tableView.deleteRows(at: [indexPath], with: .fade)

        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        invoiceNumber = indexPath.row
        print(invoiceNumber, "yes")
        performSegue(withIdentifier: "visualize", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! PreviewViewController
        vc.invoiceNumber = invoiceNumber
    }
}

It is the "vc.invoiceNumber = invoiceNumber" which comes before the "invoiceNumber = indexPath.row" as I tried to change the value of invoiceNumber a variable in the view and print out the value in the child view and if showed its value first (I tested -1).

I added the Preview view controller which receives the invoiceNumber :

import UIKit
import WebKit

class PreviewViewController: UIViewController {

    @IBOutlet var webPreview: UIWebView!

    var invoiceComposer: InvoiceComposer!
    var HTMLContent: String!

    var invoiceNumber: Int = -1

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(invoiceNumber)
        createInvoiceAsHTML()
    }

    func createInvoiceAsHTML() {
        invoiceComposer = InvoiceComposer()
        if let tabBar = tabBarController as? baseTabBarController {
            if let invoiceHTML = invoiceComposer.renderInvoice(invoiceNumber: String(invoiceNumber), invoiceDate: "", recipientInfo: tabBar.customerData[invoiceNumber][0].input, items: tabBar.itemsData[invoiceNumber], totalAmount: tabBar.totalData[invoiceNumber].total) {

                   webPreview.loadHTMLString(invoiceHTML, baseURL: NSURL(string: invoiceComposer.pathToInvoiceHTMLTemplate!)! as URL)
                   HTMLContent = invoiceHTML
            }
        }
        else {
            print("tabBarController is not of type baseTabBarController or either nil ")
        }

    }

}


问:
xy scatter plot with python-pptx not working
I am trying to make a simple python-pptx xy scatter chart with x and y series data but unsuccessful so far.

```<code>from pptx import Presentation
from pptx.util import Inches,Pt

from pptx.enum.chart import XL_CHART_TYPE
from pptx.chart.data import XySeriesData

prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
blank_slide_layout = prs.slide_layouts[6]

slide = prs.slides.add_slide(title_slide_layout)
slide2 = prs.slides.add_slide(blank_slide_layout)

title = slide.shapes.title
subtitle = slide.placeholders[1]

title.text = "Hello, World!"
subtitle.text = "python-pptx was here!"
chart_data = XySeriesData
chart_data.x_values=[0,1,2,3,4,5]
chart_data.y_values=[10,22,33,38,40,43]
x, y, cx, cy = Inches(1), Inches(2), Inches(8), Inches(3)
chart = slide2.shapes.add_chart(XL_CHART_TYPE.XY_SCATTER, x, y, cx, cy, chart_data).chart

prs.save('test1.pptx')
</code>```

The error i get is

File "C:\Users\adnan\Google Drive\Learning\Python\5g_tti_parser\untitled0.py", line 31, in
    chart = slide2.shapes.add_chart(XL_CHART_TYPE.XY_SCATTER, x, y, cx, cy, chart_data).chart

File "C:\ProgramData\Anaconda3\lib\site-packages\pptx\shapes\shapetree.py", line 250, in add_chart
    rId = self.part.add_chart_part(chart_type, chart_data)

File "C:\ProgramData\Anaconda3\lib\site-packages\pptx\parts\slide.py", line 174, in add_chart_part
    chart_part = ChartPart.new(chart_type, chart_data, self.package)

File "C:\ProgramData\Anaconda3\lib\site-packages\pptx\parts\chart.py", line 30, in new
    chart_blob = chart_data.xml_bytes(chart_type)

AttributeError: type object 'XySeriesData' has no attribute 'xml_bytes'

答:
I am working on this as well today - it looks like you skipped some steps.

Make sure you have the right imports, which include:

```<code>from pptx.chart.data import XySeriesData, XyChartData
</code>```

Change this line:

```<code>chart_data = XySeriesData
</code>```

to instantiate the class XyChartData:

```<code>chart_data = XyChartData()
</code>```

then you need to add a series (which creates the XySeries object), give it a name and a number format (I am using None)

```<code>chart_data.add_series('name_of_series', number_format= None)
</code>```

THEN

```<code>chart_data.x_values=[0,1,2,3,4,5]
chart_data.y_values=[10,22,33,38,40,43]
</code>```

I'm not fully sure if this will solve your problem, but I hope it helps. I was able to replace the data in a scatterplot this way today.

EDIT:

Setting the x_values and y_values on the chart_data object has been inconsistent and unreliable. In example below, set your numeric lists to variable names. I am using x_values_list and y_values_list for clarity.

New method:

Save your add_series object to a variable, and add x & y data points individually.

```<code>chart_data = XyChartData()
cd = chart_data.add_series('name_of_series', number_format= None)
    for x, y in list(zip(x_values_list, y_values_list)):
         cd.add_data_point(x, y, number_format=None)
</code>```

At this point, chart_data contains your series object and can be inserted into the chart shape, while cd represents the XySeries object. I think x_values and y_values are meant as accessors more than writers, perhaps? I could not set those values at the XySeries level successfully. I had many issues trying to set my lists to those attributes at the XyChartData level as well. This is functioning much better.

Body:
I am trying to make a simple python-pptx xy scatter chart with x and y series data but unsuccessful so far.

from pptx import Presentation
from pptx.util import Inches,Pt

from pptx.enum.chart import XL_CHART_TYPE
from pptx.chart.data import XySeriesData

prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
blank_slide_layout = prs.slide_layouts[6]

slide = prs.slides.add_slide(title_slide_layout)
slide2 = prs.slides.add_slide(blank_slide_layout)

title = slide.shapes.title
subtitle = slide.placeholders[1]

title.text = "Hello, World!"
subtitle.text = "python-pptx was here!"
chart_data = XySeriesData
chart_data.x_values=[0,1,2,3,4,5]
chart_data.y_values=[10,22,33,38,40,43]
x, y, cx, cy = Inches(1), Inches(2), Inches(8), Inches(3)
chart = slide2.shapes.add_chart(XL_CHART_TYPE.XY_SCATTER, x, y, cx, cy, chart_data).chart

prs.save('test1.pptx')

The error i get is

File "C:\Users\adnan\Google Drive\Learning\Python\5g_tti_parser\untitled0.py", line 31, in
    chart = slide2.shapes.add_chart(XL_CHART_TYPE.XY_SCATTER, x, y, cx, cy, chart_data).chart

File "C:\ProgramData\Anaconda3\lib\site-packages\pptx\shapes\shapetree.py", line 250, in add_chart
    rId = self.part.add_chart_part(chart_type, chart_data)

File "C:\ProgramData\Anaconda3\lib\site-packages\pptx\parts\slide.py", line 174, in add_chart_part
    chart_part = ChartPart.new(chart_type, chart_data, self.package)

File "C:\ProgramData\Anaconda3\lib\site-packages\pptx\parts\chart.py", line 30, in new
    chart_blob = chart_data.xml_bytes(chart_type)

AttributeError: type object 'XySeriesData' has no attribute 'xml_bytes'

Body:
I am working on this as well today - it looks like you skipped some steps.

Make sure you have the right imports, which include:

from pptx.chart.data import XySeriesData, XyChartData

Change this line:

chart_data = XySeriesData

to instantiate the class XyChartData:

chart_data = XyChartData()

then you need to add a series (which creates the XySeries object), give it a name and a number format (I am using None)

chart_data.add_series('name_of_series', number_format= None)

THEN

chart_data.x_values=[0,1,2,3,4,5]
chart_data.y_values=[10,22,33,38,40,43]

I'm not fully sure if this will solve your problem, but I hope it helps. I was able to replace the data in a scatterplot this way today.

EDIT:

Setting the x_values and y_values on the chart_data object has been inconsistent and unreliable. In example below, set your numeric lists to variable names. I am using x_values_list and y_values_list for clarity.

New method:

Save your add_series object to a variable, and add x & y data points individually.

chart_data = XyChartData()
cd = chart_data.add_series('name_of_series', number_format= None)
    for x, y in list(zip(x_values_list, y_values_list)):
         cd.add_data_point(x, y, number_format=None)

At this point, chart_data contains your series object and can be inserted into the chart shape, while cd represents the XySeries object. I think x_values and y_values are meant as accessors more than writers, perhaps? I could not set those values at the XySeries level successfully. I had many issues trying to set my lists to those attributes at the XyChartData level as well. This is functioning much better.


问:
Sum of 2-D Array
How to compare sum of each row in 2-D Array?

```<code>int arr[3][3];
2 2 3
5 8 9
4 1 2
</code>```

I want to compare sum of each row with each and every row of this 2-D array, to check if any two row exists having same sum.

答:
As suggested in the comments, you should probably look into using std::array or std::vector which makes certain things a lot easier.

Anyway, you could create a std::map with the sum as Key and a std::vector<size_t> as Value to store all the rows with that sum.

#include <cstddef>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <vector>

template<typename T, size_t Y, size_t X>
auto sum_rows(const T (&arr)[Y][X]) {

    // "res" stores the sums mapped to row numbers
    std::map<T, std::vector<size_t>> res;

    // accumulate each row
    for(size_t y = 0; y < Y; ++y) {
        // the result of accumulate is the key in the map
        // the row is pushed back into the vector that is stored for that key
        res[std::accumulate(std::begin(arr[y]), std::end(arr[y]), T{})].push_back(y);
    }

    return res;
}

int main() {
    int arr[3][3]{
        {2, 2, 3},
        {5, 8, 9},
        {4, 1, 2}
    };

    auto res = sum_rows(arr);

    // show the result
    for(const std::pair<int, std::vector<size_t>>& sumrows : res) {
        int sum = sumrows.first;
        const std::vector<size_t>& rows = sumrows.second;

        std::cout << "rows with sum " << sum << " (" << rows.size() << "):";
        for(size_t row : rows) std::cout << ' ' << row;
        std::cout << '\n';
    }
}
```

<p>Output:</p>

```rows with sum 7 (2): 0 2
rows with sum 22 (1): 1
```

Title: Sum of 2-D Array

Body:
How to compare sum of each row in 2-D Array?

int arr[3][3];
2 2 3
5 8 9
4 1 2

I want to compare sum of each row with each and every row of this 2-D array, to check if any two row exists having same sum.

Body:
As suggested in the comments, you should probably look into using std::array or std::vector which makes certain things a lot easier.

Anyway, you could create a std::map with the sum as Key and a std::vector<size_t> as Value to store all the rows with that sum.

#include <cstddef>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <vector>

template<typename T, size_t Y, size_t X>
auto sum_rows(const T (&arr)[Y][X]) {

    // "res" stores the sums mapped to row numbers
    std::map<T, std::vector<size_t>> res;

    // accumulate each row
    for(size_t y = 0; y < Y; ++y) {
        // the result of accumulate is the key in the map
        // the row is pushed back into the vector that is stored for that key
        res[std::accumulate(std::begin(arr[y]), std::end(arr[y]), T{})].push_back(y);
    }

    return res;
}

int main() {
    int arr[3][3]{
        {2, 2, 3},
        {5, 8, 9},
        {4, 1, 2}
    };

    auto res = sum_rows(arr);

    // show the result
    for(const std::pair<int, std::vector<size_t>>& sumrows : res) {
        int sum = sumrows.first;
        const std::vector<size_t>& rows = sumrows.second;

        std::cout << "rows with sum " << sum << " (" << rows.size() << "):";
        for(size_t row : rows) std::cout << ' ' << row;
        std::cout << '\n';
    }
}

Output:

rows with sum 7 (2): 0 2
rows with sum 22 (1): 1


问:
Cross platform listview swipe in xamarin forms
I am looking for a cross platform swipe on ListView to perform an action such as opening a menu or deleting an item.

Has anyone implemented such a scenario?  I would like to for instance delete an item when swiping on item to left.

I need to support all platforms: ios/droid/win

答:
You can use SwipeView and wrap it in a ListView.

```<code><ListView
ItemsSource="{Binding Items}"
SelectionMode="None"
CachingStrategy="RecycleElement"
RowHeight="110"
HeightRequest="1000"
BackgroundColor="White"
IsPullToRefreshEnabled="True"
Refreshing="OnRefresh">
<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell>
            <SwipeView>
                <SwipeView.GestureRecognizers>
                    <TapGestureRecognizer
                        Tapped="OnTapped"
                        NumberOfTapsRequired="1" />
                </SwipeView.GestureRecognizers>
                <SwipeView.RightItems>
                    <SwipeItems>
                        <SwipeItem
                            Text="Edit"
                            IconImageSource="edit_icon.png"
                            BackgroundColor="Green"
                            Invoked="OnEdit" />
                        <SwipeItem
                            Text="Delete"
                            IconImageSource="delete_icon.png"
                            BackgroundColor="Red"
                            Invoked="OnDelete" />
                    </SwipeItems>
                </SwipeView.RightItems>
                <SwipeView.Content>
                    :
                </SwipeView.Content>
            </SwipeView>
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>
</code>```

From: https://github.com/xamarin/Xamarin.Forms/issues/9089

Body:
You can use SwipeView and wrap it in a ListView.

<ListView
ItemsSource="{Binding Items}"
SelectionMode="None"
CachingStrategy="RecycleElement"
RowHeight="110"
HeightRequest="1000"
BackgroundColor="White"
IsPullToRefreshEnabled="True"
Refreshing="OnRefresh">
<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell>
            <SwipeView>
                <SwipeView.GestureRecognizers>
                    <TapGestureRecognizer
                        Tapped="OnTapped"
                        NumberOfTapsRequired="1" />
                </SwipeView.GestureRecognizers>
                <SwipeView.RightItems>
                    <SwipeItems>
                        <SwipeItem
                            Text="Edit"
                            IconImageSource="edit_icon.png"
                            BackgroundColor="Green"
                            Invoked="OnEdit" />
                        <SwipeItem
                            Text="Delete"
                            IconImageSource="delete_icon.png"
                            BackgroundColor="Red"
                            Invoked="OnDelete" />
                    </SwipeItems>
                </SwipeView.RightItems>
                <SwipeView.Content>
                    :
                </SwipeView.Content>
            </SwipeView>
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>

From: https://github.com/xamarin/Xamarin.Forms/issues/9089


答:
The error is easy to spot, you are using getters and setters:

```<code>export class LocationService {

  private coordinates: any;
  constructor(
    private toastCtrl: ToastController
  ) { }

  set setCoords(coords: any) {
    this.coordinates = coords;
    this.toastCtrl.create({
      message: `Coordinates Assigned ${this.coordinates.latitude},${this.coordinates.longitude}`
    }).then(alertCtrl => {
      alertCtrl.present();
    });
  }
  get getCoords(): any {
    return this.coordinates;
  }
}
</code>```

If you want it to be a function you should declare it without the get and set keyword in front of the functions

Title: service.foo is not a function Angular

Body:
The error is easy to spot, you are using getters and setters:

export class LocationService {

  private coordinates: any;
  constructor(
    private toastCtrl: ToastController
  ) { }

  set setCoords(coords: any) {
    this.coordinates = coords;
    this.toastCtrl.create({
      message: `Coordinates Assigned ${this.coordinates.latitude},${this.coordinates.longitude}`
    }).then(alertCtrl => {
      alertCtrl.present();
    });
  }
  get getCoords(): any {
    return this.coordinates;
  }
}

If you want it to be a function you should declare it without the get and set keyword in front of the functions


问:
Is Red5 production-ready?
I'm considering using Red5 instead of wowza and Flash Media Interactive Server. But it looks like a new project and it hasn't even reached full v1, so I'm worried about using it in a production environment.

Has anyone used it in a real production environment and would like to share the experience and document it with others?

答: As with any open source project, whether something is "production" ready or not depends on your readiness and enthusiasm. We use Red5 extensively in a video conferencing product - See www.kpoint.com

ContentLicense: CC BY-SA 2.5

Title: Is Red5 production-ready?