问:
How to exit from Javascript processing after DWR-based validation
I'm relatively new to Javascript and new to Ajax and DWR - I suspect this is a Javascript question rather than Ajax/DWR, but here goes:

I'm writing Javascript that uses DWR to call a remote Java method to validate some data entered in the browser. If the validation fails (the Java method returns an error message (non-empty string), I want to show an error message to the user and do no more Javascript processing. If the validation succeeds (empty string returned by the Java method) I want to continue in my Javascript to process the user's input.

What I'm finding is that on a validation error, the error message is shown, but the Javascript processing does not stop, it continues as if the validation succeeded. So my question is how do I end the Javascript processing when the validation fails ('A:' in the code below).

This is a mix of Javascript and pseudocode but it should illustrate what I'm doing.

Thanks for any help,

Steve

```<code>MyRemoteService.validateData(myData, {
    callback:function(str) {
        if (str) {
        // A: show an error message
            return;
        }
    }
    });

// pseudocode - this is what I want to happen:

if (validation error)
    //    don't do anything else
}

// Data was valid  - continue to do stuff
</code>```

答:
As far i can understand your post,

You want to execute some java script code, only after you get the result from backend either if its success or error message!(Am i right or missing something)

If thats the case, write your javascript code with in the dwr call back function. So, they will get called only after the result comes from the back end.

Body:
I'm relatively new to Javascript and new to Ajax and DWR - I suspect this is a Javascript question rather than Ajax/DWR, but here goes:

I'm writing Javascript that uses DWR to call a remote Java method to validate some data entered in the browser. If the validation fails (the Java method returns an error message (non-empty string), I want to show an error message to the user and do no more Javascript processing. If the validation succeeds (empty string returned by the Java method) I want to continue in my Javascript to process the user's input.

What I'm finding is that on a validation error, the error message is shown, but the Javascript processing does not stop, it continues as if the validation succeeded. So my question is how do I end the Javascript processing when the validation fails ('A:' in the code below).

This is a mix of Javascript and pseudocode but it should illustrate what I'm doing.

Thanks for any help,

Steve

MyRemoteService.validateData(myData, {
    callback:function(str) {
        if (str) {
        // A: show an error message
            return;
        }
    }
    });

// pseudocode - this is what I want to happen:

if (validation error)
    //    don't do anything else
}

// Data was valid  - continue to do stuff


来源: stackexchange

问:
how to configure Spring Integration to read from Redis with multithread?
I'm setting up a Spring Integration configuration to read from redis with multithread but when I run my application, Spring only creates one thread.

I am creating an int-redis:queue-inbound-channel-adapter with an executor-task with pool-size= 500 and queue-capacity=0.

<redis:queue-inbound-channel-adapter
            id="fromRedis" channel="privateAggregationExecutorChannel" queue="${instance}_private"
            receive-timeout="1000" recovery-interval="3000" expect-message="false" error-channel="distributionErrors"
            auto-startup="false" task-executor="robotTaskExecutor"/>

<task:executor
            id="robotTaskExecutor"
            pool-size="500"
            queue-capacity="0"
            keep-alive="50"
            rejection-policy="CALLER_RUNS" />

<int:service-activator input-channel="privateAggregationExecutorChannel" ref="aggregationExecutor" method="run" />
```

I don't know what I'm doing wrong or if there is something that I'm missing. I appreciate your help.

答:
That's correct. The RedisQueueMessageDrivenEndpoint is really single-threaded component:

```<code>@Override
protected void doStart() {
    if (!this.active) {
        this.active = true;
        this.restart();
    }
}

private void restart() {
    this.taskExecutor.execute(new ListenerTask());
}
</code>```

As you see only one ListenerTask is scheduled from this channel adapters.

To make it multi-threaded, it is better to have an ExecutorChannel to send messages from this channel adapter. This way even if  RedisQueueMessageDrivenEndpoint is a single-threaded one, you're still going to have a multi-threaded processing.

We just realized that it is going to be a bit complicated to introduce a concurrency into this component when we can workaround other simple way.

Another approach is to have several <redis:queue-inbound-channel-adapter> definitions for the same queue and same channel to send.

ContentLicense: CC BY-SA 4.0

Body:
I'm setting up a Spring Integration configuration to read from redis with multithread but when I run my application, Spring only creates one thread.

I am creating an int-redis:queue-inbound-channel-adapter with an executor-task with pool-size= 500 and queue-capacity=0.

<redis:queue-inbound-channel-adapter
            id="fromRedis" channel="privateAggregationExecutorChannel" queue="${instance}_private"
            receive-timeout="1000" recovery-interval="3000" expect-message="false" error-channel="distributionErrors"
            auto-startup="false" task-executor="robotTaskExecutor"/>

<task:executor
            id="robotTaskExecutor"
            pool-size="500"
            queue-capacity="0"
            keep-alive="50"
            rejection-policy="CALLER_RUNS" />

<int:service-activator input-channel="privateAggregationExecutorChannel" ref="aggregationExecutor" method="run" />

I don't know what I'm doing wrong or if there is something that I'm missing. I appreciate your help.

Body:
That's correct. The RedisQueueMessageDrivenEndpoint is really single-threaded component:

@Override
protected void doStart() {
    if (!this.active) {
        this.active = true;
        this.restart();
    }
}

private void restart() {
    this.taskExecutor.execute(new ListenerTask());
}

As you see only one ListenerTask is scheduled from this channel adapters.

To make it multi-threaded, it is better to have an ExecutorChannel to send messages from this channel adapter. This way even if  RedisQueueMessageDrivenEndpoint is a single-threaded one, you're still going to have a multi-threaded processing.

We just realized that it is going to be a bit complicated to introduce a concurrency into this component when we can workaround other simple way.

Another approach is to have several <redis:queue-inbound-channel-adapter> definitions for the same queue and same channel to send.


问:
Looking for a better statement to use rather than an if statement with sql query
I am running a query and need it to pick from one field and score the user according to race and gender.

I tried the if statement to look for the query and select the correct score but it either picks the first if statement and doesn't check the rest even if the query is different when the approve button is clicked.

```<code>//Approve Button Rating
                if(isset($_POST['approveBtn'])){
          $query ="UPDATE bbee SET status=1 WHERE id='$id' AND race='Black'";

                        if(mysqli_query($connection,$query))
                        {?>
                            <div class="successmsg alert alert-autocloseable-success">
                            <a href="#" class="close" data-dismiss="alert">×</a>
                            <p align="center">
                                You are a level 1 B-BBEE Contributor
                            </p>
                            </div>
                        <?php
                        }else{
                        ?>
                            <div class="errormsg alert alert-autocloseable-danger">
                                <a href="#" class="close" data-dismiss="alert">×</a>
                                <p align="center">
                                    An error occured, Could not disapprove business
                                </p>
                            </div>
                        <?php
                        }
                }

                if(isset($_POST['approveBtn'])){
                    $query ="UPDATE bbee SET status=2 WHERE id='$id' AND race='White'";

                    if(mysqli_query($connection,$query))
                    {?>
                        <div class="successmsg alert alert-autocloseable-success">
                        <a href="#" class="close" data-dismiss="alert">×</a>
                        <p align="center">
                            You are a level 2 B-BBEE Contributor
                        </p>
                        </div>
                    <?php
                    }else{
                    ?>
                        <div class="errormsg alert alert-autocloseable-danger">
                            <a href="#" class="close" data-dismiss="alert">×</a>
                            <p align="center">
                                An error occured, Could not disapprove business
                            </p>
                        </div>
                    <?php
                    }
            }
</code>```

I am looking for a better statement to use because even this statement runs both results and doesn't show one result.

答:
You do know that your code is written in a way that BOTH the queries get executed in case

if(isset($_POST['approveBtn']))

is true, do you ? I'm not sure this really was what you wanted...

As someone has already said, UPDATE queries are successful even when they don't update any record (you should check affected rows), but beware of inserting the $id in the query as you're doing in your code as that may be open to SQL injections.

Body:
I am running a query and need it to pick from one field and score the user according to race and gender.

I tried the if statement to look for the query and select the correct score but it either picks the first if statement and doesn't check the rest even if the query is different when the approve button is clicked.

//Approve Button Rating
                if(isset($_POST['approveBtn'])){
          $query ="UPDATE bbee SET status=1 WHERE id='$id' AND race='Black'";

                        if(mysqli_query($connection,$query))
                        {?>

                            ×

                                You are a level 1 B-BBEE Contributor

                        <?php
                        }else{
                        ?>

                                ×

                                    An error occured, Could not disapprove business

                        <?php
                        }
                }

                if(isset($_POST['approveBtn'])){
                    $query ="UPDATE bbee SET status=2 WHERE id='$id' AND race='White'";

                    if(mysqli_query($connection,$query))
                    {?>

                        ×

                            You are a level 2 B-BBEE Contributor

                    <?php
                    }else{
                    ?>

                            ×

                                An error occured, Could not disapprove business

                    <?php
                    }
            }

I am looking for a better statement to use because even this statement runs both results and doesn't show one result.


问:
logging.basicConfig in Python won't work if calling logging.info() before declaring
Based on this answer, Easier way to enable verbose logging

Let's take this Python script.

```<code>import argparse
import logging

def main():
    import argparse
    import logging

    parser = argparse.ArgumentParser(
        description='A test script for http://stackoverflow.com/q/14097061/78845'
    )
    parser.add_argument("-v", "--verbose", help="increase output verbosity",
                        action="store_true")

    args = parser.parse_args()
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    logging.info('Shown in debug and info mode')
    logging.debug('Only shown in debug mode')

if __name__ == "__main__":
    logging.info('Starting script!')
    main()
</code>```

Running this script from terminal as python -m verbose -v won't print anything.

If you comment the line logging.info('Starting script!') from the file as in

```<code>if __name__ == "__main__":
    #logging.info('Starting script!')
    main()
</code>```

then logging works as expected.

It looks like an attempt to call a logging.info() before basicConfig is defined will fully disable any logging.

Is it a bug in logging or a common gotcha and why does this happen?

I am on Python 3.6.7.

答:
From the logging documentation: (Emphasis mine)

```<code> logging.basicConfig(**kwargs)
</code>```

Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root
  logger.

The functions debug(), info(), warning(), error() and
  critical() will call basicConfig() automatically if no handlers are
  defined for the root logger.

This function does nothing if the root logger already has handlers configured for it.

So basically your first call to logging.info made some automatic configuration. Your later configuration attempt silently failed because of the automatic configuration that already happend.

Body:
Based on this answer, Easier way to enable verbose logging

Let's take this Python script.

import argparse
import logging

def main():
    import argparse
    import logging

    parser = argparse.ArgumentParser(
        description='A test script for http://stackoverflow.com/q/14097061/78845'
    )
    parser.add_argument("-v", "--verbose", help="increase output verbosity",
                        action="store_true")

    args = parser.parse_args()
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    logging.info('Shown in debug and info mode')
    logging.debug('Only shown in debug mode')

if __name__ == "__main__":
    logging.info('Starting script!')
    main()

Running this script from terminal as python -m verbose -v won't print anything.

If you comment the line logging.info('Starting script!') from the file as in

if __name__ == "__main__":
    #logging.info('Starting script!')
    main()

then logging works as expected.

It looks like an attempt to call a logging.info() before basicConfig is defined will fully disable any logging.

Is it a bug in logging or a common gotcha and why does this happen?

I am on Python 3.6.7.

Body:
From the logging documentation: (Emphasis mine)

 logging.basicConfig(**kwargs)

Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root
  logger.

The functions debug(), info(), warning(), error() and
  critical() will call basicConfig() automatically if no handlers are
  defined for the root logger.

This function does nothing if the root logger already has handlers configured for it.

So basically your first call to logging.info made some automatic configuration. Your later configuration attempt silently failed because of the automatic configuration that already happend.


问:
I need to split a value in the variable
I need to split the path defined in below code in following a manner that </p>

```<code>k[0] = /dev/mapper/centos-root
k[1] = 52403200
k[2] = 14460252 an so on.
</code>```

<p>What have I tried?
I tried using the split function but it currently takes k[0] = /
also, I tried passing it into a list where the whole context comes as one value </p>

```<code>command = ("df -P | egrep '([20][0-9]|100)%' |  awk '{print}'|sed -e 's/ / : /g'")
command_execute = (stdin, stdout, stderr) = ssh.exec_command(command)
read_contents = stdout.read().decode("utf-8")
read_contents
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'
k=read_contents[0]
k
'/'
k=read_contents[1]
k
'd'
k.split(" ")
['d']
m =k.split(":")
m
['d']
s = [read_contents]
s
['/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n']
s[0]
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'
s[1]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: list index out of range
s[0]
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'

k[0] = /dev/mapper/centos-root
k[1] = 52403200
k[2] = 14460252 an so on.
</code>```

答:
Another option is to use filter function to select by the expected numbers length.

read_contents = '/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 3794...: 2948 :  :  :  :  :  : 28% : /\n'
k = list(filter(lambda x: len(x)>5, read_contents.split(':')))
```

<p>Ouput:</p>

<pre class="lang-py prettyprint-override"><code>print(k)
['/dev/mapper/centos-root ', ' 52403200 ', ' 14460252 ', ' 3794...', ' 2948 ']
</code>```

Title: I need to split a value in the variable

Body:
I need to split the path defined in below code in following a manner that

k[0] = /dev/mapper/centos-root
k[1] = 52403200
k[2] = 14460252 an so on.

What have I tried?
I tried using the split function but it currently takes k[0] = /
also, I tried passing it into a list where the whole context comes as one value

command = ("df -P | egrep '([20][0-9]|100)%' |  awk '{print}'|sed -e 's/ / : /g'")
command_execute = (stdin, stdout, stderr) = ssh.exec_command(command)
read_contents = stdout.read().decode("utf-8")
read_contents
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'
k=read_contents[0]
k
'/'
k=read_contents[1]
k
'd'
k.split(" ")
['d']
m =k.split(":")
m
['d']
s = [read_contents]
s
['/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n']
s[0]
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'
s[1]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: list index out of range
s[0]
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'

k[0] = /dev/mapper/centos-root
k[1] = 52403200
k[2] = 14460252 an so on.

Body:
Another option is to use filter function to select by the expected numbers length.

read_contents = '/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 3794...: 2948 :  :  :  :  :  : 28% : /\n'
k = list(filter(lambda x: len(x)>5, read_contents.split(':')))

Ouput:

print(k)
['/dev/mapper/centos-root ', ' 52403200 ', ' 14460252 ', ' 3794...', ' 2948 ']


答:
You could do it something like the below :</p>

```<code>INSERT INTO Child
(
   Id
   ,De
   ,Fr
   ,En
)
OUTPUT Inserted.Id INTO #Temp
SELECT Id
       ,De
       ,Fr
       ,En
FROM @Values --If you are using a table type to insert into the Child table as a set based approach

;WITH CTE
AS
(
  SELECT ROW_NUMBER() OVER(ORDER BY Id) AS Rnk
  ,Id
  FROM #Temp

)
,CTE1 AS
(
  SELECT ROW_NUMBER() OVER(ORDER BY Id) AS Rnk
  ,*
  FROM Parent
)

UPDATE cte1
SET TranslationId = cte.Id
FROM CTE1 cte1
JOIN CTE cte ON cte.Rnk = cte1.Rnk
</code>```

Title: Insert on a child table and update FK on parent

Body:
I have a parent table with the following structure and data:

---------------------------------------------
|  Id | TranslationId |                Name |
---------------------------------------------
|   1 |          NULL |          Image1.jpg |
|   2 |          NULL |          Image7.jpg |
|   3 |          NULL |    Picture_Test.png |
---------------------------------------------

And the empty child table which holds the translated images:

-------------------------------------------------------------------------
|  Id |                  De |                  Fr |                  En |
-------------------------------------------------------------------------
|     |                     |                     |                     |
-------------------------------------------------------------------------

Now I'm looking for a single query statement or at least few queries which I can run without any further programming. Doing this job with scripting or programming would be easy but I have often situations where I need this kind of insert / update. And developing each time a small console app is not feasible.

At the end the two tables should look like this:

---------------------------------------------
|  Id | TranslationId |                Name |
---------------------------------------------
|   1 |            28 |                NULL |
|   2 |            29 |                NULL |
|   3 |            30 |                NULL |
---------------------------------------------

-------------------------------------------------------------------------
|  Id |                  De |                  Fr |                  En |
-------------------------------------------------------------------------
|  28 |          Image1.jpg |                NULL |               NULL  |
|  29 |          Image7.jpg |                NULL |               NULL  |
|  30 |    Picture_Test.png |                NULL |               NULL  |
-------------------------------------------------------------------------

Thank you for any advice.

Body:
You could do it something like the below :

INSERT INTO Child
(
   Id
   ,De
   ,Fr
   ,En
)
OUTPUT Inserted.Id INTO #Temp
SELECT Id
       ,De
       ,Fr
       ,En
FROM @Values --If you are using a table type to insert into the Child table as a set based approach

;WITH CTE
AS
(
  SELECT ROW_NUMBER() OVER(ORDER BY Id) AS Rnk
  ,Id
  FROM #Temp

)
,CTE1 AS
(
  SELECT ROW_NUMBER() OVER(ORDER BY Id) AS Rnk
  ,*
  FROM Parent
)

UPDATE cte1
SET TranslationId = cte.Id
FROM CTE1 cte1
JOIN CTE cte ON cte.Rnk = cte1.Rnk


问:
How does closing a socket affects other's side read
For example we have a server-client application. If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?</p>

答:
"If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?"

Yes. The client will get the data that was sent before the FIN packet that closes the socket.


问:
A line graph for non-numeric data
I have a dataset with mostly non numeric forms. I would love to create a visualization for them but I am having an error message.

My data set looks like this

```<code> |plant_name|Customer_name|Job site|Delivery.Date|DeliveryQuantity|
 |SN13|John|Sweden|01.01.2019|6|
 |SN14|Ruth|France|01.04.2018|4|
 |SN15|Jane|Serbia|01.01.2019|2|
 |SN11|Rome|Denmark|01.04.2018|10|
 |SN14|John|Sweden|03.04.2018|5|
 |SN15|John|Sweden|04.09.2019|7|
 |
</code>```

I need to create a lineplot to show how many times John made a purchase using Delivery Date as my timeline (x-axis)

```<code>import  pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
pd.set_option("display.max_rows", 5)

hr_data = pd.read_excel("D:\data\Days_Calculation.xlsx", parse_dates = True)

x = hr_data['DeliveryDate']
y = hr_data ['Customer_name']

sns.lineplot(x,y)

Error: No numeric types to aggregate
</code>```

My expected result show be a line graph like this

John's marker will present on the timeline (Delivery Date) on "01.01.2019", "03.04.2018" and "04.09.2019"

Another instance
To plot string vs float for example Total number of quantity (DeliveryQuantity) vs Customer Name .How can one approach this

how do one format the axes distance of a plot  (not label)

答:
Generally speaking you have to aggregate something when working with categorical data. Whether you will be counting names in a column or adding number of orders, or ranking some categories this is still numeric data.

```<code>plot_data = hr_data.pivot_table(index='DeliveryDate', columns='Customer_name', values='DeliveryQuantity', aggfunc='sum')

plt.xticks(LISTOFVALUESFORXRANGE)
plot_data.plot(legend=False)
</code>```

Title: A line graph for non-numeric data

Body:
I have a dataset with mostly non numeric forms. I would love to create a visualization for them but I am having an error message.

My data set looks like this

 |plant_name|Customer_name|Job site|Delivery.Date|DeliveryQuantity|
 |SN13|John|Sweden|01.01.2019|6|
 |SN14|Ruth|France|01.04.2018|4|
 |SN15|Jane|Serbia|01.01.2019|2|
 |SN11|Rome|Denmark|01.04.2018|10|
 |SN14|John|Sweden|03.04.2018|5|
 |SN15|John|Sweden|04.09.2019|7|
 |

I need to create a lineplot to show how many times John made a purchase using Delivery Date as my timeline (x-axis)

import  pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
pd.set_option("display.max_rows", 5)

hr_data = pd.read_excel("D:\data\Days_Calculation.xlsx", parse_dates = True)

x = hr_data['DeliveryDate']
y = hr_data ['Customer_name']

sns.lineplot(x,y)

Error: No numeric types to aggregate

My expected result show be a line graph like this

John's marker will present on the timeline (Delivery Date) on "01.01.2019", "03.04.2018" and "04.09.2019"

Another instance
To plot string vs float for example Total number of quantity (DeliveryQuantity) vs Customer Name .How can one approach this

how do one format the axes distance of a plot  (not label)

Body:
Generally speaking you have to aggregate something when working with categorical data. Whether you will be counting names in a column or adding number of orders, or ranking some categories this is still numeric data.

plot_data = hr_data.pivot_table(index='DeliveryDate', columns='Customer_name', values='DeliveryQuantity', aggfunc='sum')

plt.xticks(LISTOFVALUESFORXRANGE)
plot_data.plot(legend=False)


问:
Scraping data from web canvas with python
Anyone knows how to scrape data from a web canvas?
I would like to scrape all values from the blue/orange line graph, that's the photo:

I have tried nothing, i've just can't find anything about it.
To make that graph open, you should click at the curve line plus button at the top, right after IBOV and then place at the search "RSI Estocástico"

答: Tradingview has a good public api, but maybe not for RSI indicator. If it has no, you need to fetch the chart data with the API, and you could calculate RSI by you own.</p>


问:
Why does my If/Else loop break out of my For loop?
I'm doing a supposedly simple python challenge a friend gave me involving an elevator and the logic behind its movements. Everything was going well and good until I got to the point where I had to write how to determine if the elevator could move hit a called floor en route to its next queued floor.

def floorCompare(currentFloor,destinationFloor,calledFloor):
    if calledFloor > currentFloor and calledFloor < destinationFloor:
        return(True)
    elif calledFloor < currentFloor and calledFloor > destinationFloor:
        return(True)
    else:
        return(False)

floor = "1"
doors = "closed"
queue = []
def elevator(): # function defines how the elevator should move
    print("The Elevator is on floor: 1. The doors are "+doors+".")
    for x in range(int(input("How many floors need to be visited? "))):
        callFloor = int(input("Floor to call the elevator to: "))
        queue.append(callFloor)
        if callFloor > 10 or callFloor < 1:
            raise Exception(str(callFloor)+" is not a valid floor.")
    if queue[0] == 1:
        del queue[0]
        print("The elevator has arrived on floor 1, and the doors are open.")
    print("The queue of floors to visit is...",queue)
    for x in queue:
        print("The elevator's doors are closed and it's moving to floor:",x)
        floor = str(x)
        print("...")
        print()
        print("The elevator has arrived on floor "+floor+", and the doors are open.")
        queue.remove(x)
        addFloor = int(input("Floor to call the elevator to: "))
        if addFloor > 10 or addFloor < 1:
            raise Exception(str(addFloor)+" is not a valid floor.")
        print(queue)
        if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
            print("The elevator can hit this stop en route to its next one.")
        else:
            print("The elevator must hit this stop separately.")
    print("Continuing Queue")

elevator()
```

<p>So in the For loop, there is a nested If/Else loop, which I would assume would be iterated along with the rest of the code in the for loop. However, when I run the code, upon reaching the If/Else loop, it breaks out of the For loop and continues on its merry way, disregarding any further iterations that need to be done in the array. What's going on here?</p>

<p>When I run the code with a basic trial set of floors, here's what I get as output.</p>

```The Elevator is on floor: 1. The doors are closed.
How many floors need to be visited? 4
Floor to call the elevator to: 3
Floor to call the elevator to: 6
Floor to call the elevator to: 9
Floor to call the elevator to: 10
The queue of floors to visit is... [3, 6, 9, 10]
The elevator's doors are closed and it's moving to floor: 3
...

The elevator has arrived on floor 3, and the doors are open.
Floor to call the elevator to: 7
[6, 9, 10]
The elevator must hit this stop seperately.
The elevator's doors are closed and it's moving to floor: 9
...

The elevator has arrived on floor 9, and the doors are open.
Floor to call the elevator to: 3
[6, 10]
The elevator must hit this stop separately.

Process finished with exit code 0
```

答:
I think your problem lies in the use of a for loop in conjunction with the queue.remove() function. It seems like the for x in queue: operator runs into problems when you edit the list while it runs. I would recommend using while queue: instead and setting x to the first element.

```<code>    while queue:
        x = queue[0]
        print("The elevator's doors are closed and it's moving to floor:",x)
        floor = str(x)
        print("...")
        print()
        print("The elevator has arrived on floor "+floor+", and the doors are open.")
        queue.remove(x)
        addFloor = int(input("Floor to call the elevator to: "))
        if addFloor > 10 or addFloor < 1:
            raise Exception(str(addFloor)+" is not a valid floor.")
        print(queue)
        if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
            print("The elevator can hit this stop en route to its next one.")
        else:
            print("The elevator must hit this stop separately.")
</code>```

Body:
I'm doing a supposedly simple python challenge a friend gave me involving an elevator and the logic behind its movements. Everything was going well and good until I got to the point where I had to write how to determine if the elevator could move hit a called floor en route to its next queued floor.

def floorCompare(currentFloor,destinationFloor,calledFloor):
    if calledFloor > currentFloor and calledFloor < destinationFloor:
        return(True)
    elif calledFloor < currentFloor and calledFloor > destinationFloor:
        return(True)
    else:
        return(False)

floor = "1"
doors = "closed"
queue = []
def elevator(): # function defines how the elevator should move
    print("The Elevator is on floor: 1. The doors are "+doors+".")
    for x in range(int(input("How many floors need to be visited? "))):
        callFloor = int(input("Floor to call the elevator to: "))
        queue.append(callFloor)
        if callFloor > 10 or callFloor < 1:
            raise Exception(str(callFloor)+" is not a valid floor.")
    if queue[0] == 1:
        del queue[0]
        print("The elevator has arrived on floor 1, and the doors are open.")
    print("The queue of floors to visit is...",queue)
    for x in queue:
        print("The elevator's doors are closed and it's moving to floor:",x)
        floor = str(x)
        print("...")
        print()
        print("The elevator has arrived on floor "+floor+", and the doors are open.")
        queue.remove(x)
        addFloor = int(input("Floor to call the elevator to: "))
        if addFloor > 10 or addFloor < 1:
            raise Exception(str(addFloor)+" is not a valid floor.")
        print(queue)
        if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
            print("The elevator can hit this stop en route to its next one.")
        else:
            print("The elevator must hit this stop separately.")
    print("Continuing Queue")

elevator()

So in the For loop, there is a nested If/Else loop, which I would assume would be iterated along with the rest of the code in the for loop. However, when I run the code, upon reaching the If/Else loop, it breaks out of the For loop and continues on its merry way, disregarding any further iterations that need to be done in the array. What's going on here?

When I run the code with a basic trial set of floors, here's what I get as output.

The Elevator is on floor: 1. The doors are closed.
How many floors need to be visited? 4
Floor to call the elevator to: 3
Floor to call the elevator to: 6
Floor to call the elevator to: 9
Floor to call the elevator to: 10
The queue of floors to visit is... [3, 6, 9, 10]
The elevator's doors are closed and it's moving to floor: 3
...

The elevator has arrived on floor 3, and the doors are open.
Floor to call the elevator to: 7
[6, 9, 10]
The elevator must hit this stop seperately.
The elevator's doors are closed and it's moving to floor: 9
...

The elevator has arrived on floor 9, and the doors are open.
Floor to call the elevator to: 3
[6, 10]
The elevator must hit this stop separately.

Process finished with exit code 0

Body:
I think your problem lies in the use of a for loop in conjunction with the queue.remove() function. It seems like the for x in queue: operator runs into problems when you edit the list while it runs. I would recommend using while queue: instead and setting x to the first element.

    while queue:
        x = queue[0]
        print("The elevator's doors are closed and it's moving to floor:",x)
        floor = str(x)
        print("...")
        print()
        print("The elevator has arrived on floor "+floor+", and the doors are open.")
        queue.remove(x)
        addFloor = int(input("Floor to call the elevator to: "))
        if addFloor > 10 or addFloor < 1:
            raise Exception(str(addFloor)+" is not a valid floor.")
        print(queue)
        if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
            print("The elevator can hit this stop en route to its next one.")
        else:
            print("The elevator must hit this stop separately.")


问:
How to group arrays in array by first element object key
Got an array of arrays like this:

```<code>    let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        {"key":1, "other":11},
        {"key":1, "other":23}
      ],
      [
        {"key":1, "other":22}
      ]
    ]
</code>```

I need to get this arr but with grouped arrays with the same "key" value of the first element so it will be look like:

```<code>  let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        [
          {"key":1, "other":11},
          {"key":1, "other":23}
        ],
        [
          {"key":1, "other":22}
        ]
      ],

    ]
</code>```

I tried to use reduce function, but the result was totally different.

```<code>let final = []
  for (let i=0; i<arr.length; i++) {

    let arr1 = i==0?arr:arr.slice(i)

    let final1 = arr1.reduce((acc,x)=> {

      acc = acc[0].key==x[0].key?acc.concat(x):acc
      return acc
    })
    arr1.length>1&&final.push(final1)
  }
</code>```

In this code the problem is that it compares arr[1] with arr[2], arr[3] and then again arr[2] with arr[3] and groups it(even though arr[1].key and arr[2].key and arr[3].key are the same) Can you give some tips or give the final function to do this?

答:
```<code>let arr = [
      [
        {"key":2},
        {"key":2}
      ],
      [
        {"key":3}
      ],
      [
        {"key":1},
        {"key":1}
      ],
      [
        {"key":1}
      ]
    ]
var myMap = new Map();
for (i = 0; i < arr.length; i++) {
    if(!myMap.has(arr[i][0]['key'])){
        myMap.set(arr[i][0]['key'],i)
    }else if(myMap.get(arr[i][0]['key'])===undefined){

        myMap.set(arr[i][0]['key'],i)
    }else{
        myMap.set(arr[i][0]['key'],myMap.get(arr[i][0]['key'])+','+i)
    }
}
var out =[];
for(var v of myMap.values()){
    var s = String(v).split(",");
    var fi = s[0]
    var subarray =[]
    for(var i in s){
        subarray.push(arr[s[i]])
    }
    out[fi] = subarray;
}
</code>```

You will find your response in out array. Hope that it works for you

Body:
Got an array of arrays like this:

    let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        {"key":1, "other":11},
        {"key":1, "other":23}
      ],
      [
        {"key":1, "other":22}
      ]
    ]

I need to get this arr but with grouped arrays with the same "key" value of the first element so it will be look like:

  let arr = [
      [
        {"key":2, "other":123},
        {"key":2, "other":222}
      ],
      [
        {"key":3, "other":0}
      ],
      [
        [
          {"key":1, "other":11},
          {"key":1, "other":23}
        ],
        [
          {"key":1, "other":22}
        ]
      ],

    ]

I tried to use reduce function, but the result was totally different.

let final = []
  for (let i=0; i<arr.length; i++) {

    let arr1 = i==0?arr:arr.slice(i)

    let final1 = arr1.reduce((acc,x)=> {

      acc = acc[0].key==x[0].key?acc.concat(x):acc
      return acc
    })
    arr1.length>1&&final.push(final1)
  }

In this code the problem is that it compares arr[1] with arr[2], arr[3] and then again arr[2] with arr[3] and groups it(even though arr[1].key and arr[2].key and arr[3].key are the same) Can you give some tips or give the final function to do this?

Body:
let arr = [
      [
        {"key":2},
        {"key":2}
      ],
      [
        {"key":3}
      ],
      [
        {"key":1},
        {"key":1}
      ],
      [
        {"key":1}
      ]
    ]
var myMap = new Map();
for (i = 0; i < arr.length; i++) {
    if(!myMap.has(arr[i][0]['key'])){
        myMap.set(arr[i][0]['key'],i)
    }else if(myMap.get(arr[i][0]['key'])===undefined){

        myMap.set(arr[i][0]['key'],i)
    }else{
        myMap.set(arr[i][0]['key'],myMap.get(arr[i][0]['key'])+','+i)
    }
}
var out =[];
for(var v of myMap.values()){
    var s = String(v).split(",");
    var fi = s[0]
    var subarray =[]
    for(var i in s){
        subarray.push(arr[s[i]])
    }
    out[fi] = subarray;
}

You will find your response in out array. Hope that it works for you


问:
Data not being displayed in one of two FlatLists in the same component
I have a component with two TextInputs. Under each TextInput, there is a FlatList which gets rendered when the user types in some characters (the actual rendering happens in ListItem, a module from react-native elements). For the first FlatList, everything works fine - it is rendered as expected. The problem is with the second FlatList - I cannot get it to render. See this gif to understand what I mean: https://gph.is/g/E1G1jnx

I've tried using the "extraData" prop as advised in One of two FlatLists not rendering items in same component , but it didn't fix the issue.

I know that the problem doesn not come from onChangeAddress(address) being an async function. I used a static dataset and still it wouldn't render.

```<code>import { StyleSheet, Text, TextInput, View, FlatList, ImageBackground, Image } from 'react-native';
import { ListItem, Button } from 'react-native-elements';

 class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            jobInputValue: '',
            addressInputValue: '',
            showJobsDropdown: false,
            showAddressesDropdown: false,
            jobsList: this.props.jobTitles.results,
            addressPredictions: []
     };
  }

async onChangeAddress(address) {
//fetch the data from the API
//filteredAddresses stores the data from the API
if (filteredAddresses.length > 0) {
            this.setState({
               addressPredictions: filteredAddresses,
               showAddressesDropdown: true
            })
        }
    }

}

  render() {
    return (
    <ImageBackground style={styles.bkgImage} source={require('../assets/homepage_background.jpg')}>
        <TextInput
            style={styles.jobTextInput}
            value={this.state.jobInputValue}
            placeholder='Ce job cauți?'
            onChangeText={(jobInputValue) => this.setState({jobInputValue}, this.checkJobsDropdown(jobInputValue))}/>
                <FlatList
                data={this.state.jobsList}
                style={this.state.showJobsDropdown ? styles.jobsDropdownStyle : styles.dropdownHiddenStyle}
                renderItem={({ item }) => (
                    <ListItem
                        title={item}
                        containerStyle={{paddingBottom: -4}}
                        titleProps={{ style: styles.dropdownItemStyle}}
                        onPress={() => this.setState({jobInputValue: item}, this.hideJobsDropdown())}
                    />
                )}
                keyExtractor={item => item}
            />

        <TextInput
            style={styles.addressTextInput}
            value={this.state.addressInputValue}
            placeholder='La ce adresă locuiești?'
            onChangeText={addressInputValue => this.onChangeAddress(addressInputValue)}
            />
//the issue is with the FlatList below
            <FlatList
                data={this.state.addressPredictions}
                extraData={this.state}
                style={this.state.showAddressesDropdown ? styles.addressDropdownStyle : styles.dropdownHiddenStyle}
                renderItem={({ addressItem, index }) => (
                    <ListItem
                        title={addressItem}
                        containerStyle={{paddingBottom: -4}}
                        titleProps={{style: styles.dropdownItemStyle}}
                        onPress={() => this.setState({addressInputValue: addressItem}, this.hideAddressesDropdown())}
                    />
                )}
                keyExtractor={(addressItem, index) => index.toString()}
            />
        <Button
            title="CAUTĂ"
            type="outline"
            underlayColor={colors.red}
            titleStyle={styles.buttonTitleStyle}
            color={colors.red}
            style={styles.buttonStyle}
            onPress={this.printState}
            />

    </ImageBackground>
    );
  }
</code>```

Any help will be greatly appreciated!

答:
The problem is in the destructuring of the data for rendering the items of your second flatlist:

```<code>renderItem={({ addressItem, index }) => (
                <ListItem
                    title={addressItem}
                    containerStyle={{paddingBottom: -4}}
                    titleProps={{style: styles.dropdownItemStyle}}
                    onPress={() => this.setState({addressInputValue: addressItem}, this.hideAddressesDropdown())}
                />
            )}
</code>```

({ addressItem, index }) <- there's no addressItem available here. You have to replace that with item, as Flatlist offers an object with the { item: Object, index: Number, separators: object } structure as the param to your renderList callback.

Body:
I have a component with two TextInputs. Under each TextInput, there is a FlatList which gets rendered when the user types in some characters (the actual rendering happens in ListItem, a module from react-native elements). For the first FlatList, everything works fine - it is rendered as expected. The problem is with the second FlatList - I cannot get it to render. See this gif to understand what I mean: https://gph.is/g/E1G1jnx

I've tried using the "extraData" prop as advised in One of two FlatLists not rendering items in same component , but it didn't fix the issue.

I know that the problem doesn not come from onChangeAddress(address) being an async function. I used a static dataset and still it wouldn't render.

import { StyleSheet, Text, TextInput, View, FlatList, ImageBackground, Image } from 'react-native';
import { ListItem, Button } from 'react-native-elements';

 class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            jobInputValue: '',
            addressInputValue: '',
            showJobsDropdown: false,
            showAddressesDropdown: false,
            jobsList: this.props.jobTitles.results,
            addressPredictions: []
     };
  }

async onChangeAddress(address) {
//fetch the data from the API
//filteredAddresses stores the data from the API
if (filteredAddresses.length > 0) {
            this.setState({
               addressPredictions: filteredAddresses,
               showAddressesDropdown: true
            })
        }
    }

}

  render() {
    return (
    <ImageBackground style={styles.bkgImage} source={require('../assets/homepage_background.jpg')}>
        <TextInput
            style={styles.jobTextInput}
            value={this.state.jobInputValue}
            placeholder='Ce job cauți?'
            onChangeText={(jobInputValue) => this.setState({jobInputValue}, this.checkJobsDropdown(jobInputValue))}/>
                <FlatList
                data={this.state.jobsList}
                style={this.state.showJobsDropdown ? styles.jobsDropdownStyle : styles.dropdownHiddenStyle}
                renderItem={({ item }) => (
                    <ListItem
                        title={item}
                        containerStyle={{paddingBottom: -4}}
                        titleProps={{ style: styles.dropdownItemStyle}}
                        onPress={() => this.setState({jobInputValue: item}, this.hideJobsDropdown())}
                    />
                )}
                keyExtractor={item => item}
            />

        <TextInput
            style={styles.addressTextInput}
            value={this.state.addressInputValue}
            placeholder='La ce adresă locuiești?'
            onChangeText={addressInputValue => this.onChangeAddress(addressInputValue)}
            />
//the issue is with the FlatList below
            <FlatList
                data={this.state.addressPredictions}
                extraData={this.state}
                style={this.state.showAddressesDropdown ? styles.addressDropdownStyle : styles.dropdownHiddenStyle}
                renderItem={({ addressItem, index }) => (
                    <ListItem
                        title={addressItem}
                        containerStyle={{paddingBottom: -4}}
                        titleProps={{style: styles.dropdownItemStyle}}
                        onPress={() => this.setState({addressInputValue: addressItem}, this.hideAddressesDropdown())}
                    />
                )}
                keyExtractor={(addressItem, index) => index.toString()}
            />
        <Button
            title="CAUTĂ"
            type="outline"
            underlayColor={colors.red}
            titleStyle={styles.buttonTitleStyle}
            color={colors.red}
            style={styles.buttonStyle}
            onPress={this.printState}
            />

    </ImageBackground>
    );
  }

Any help will be greatly appreciated!

Body:
The problem is in the destructuring of the data for rendering the items of your second flatlist:

renderItem={({ addressItem, index }) => (
                <ListItem
                    title={addressItem}
                    containerStyle={{paddingBottom: -4}}
                    titleProps={{style: styles.dropdownItemStyle}}
                    onPress={() => this.setState({addressInputValue: addressItem}, this.hideAddressesDropdown())}
                />
            )}

({ addressItem, index }) <- there's no addressItem available here. You have to replace that with item, as Flatlist offers an object with the { item: Object, index: Number, separators: object } structure as the param to your renderList callback.


问:
Javascript Redirect Based On Radio Selection
I have devised this script to redirect to the specific page based on the radio selection but it keeps going to the old link that was setup. Are there any recommendations you can suggest to get this working?

```<code>            <div class="col-12" style="margin-top">
            <label><strong>What Is Your Business Currently Generating?</strong></label>
            <div class="d-flex m-t--20">
                <div class="p--relative check">
                    <input type="radio" id="o5kradio" name="income" value="o5k" checked required/>
                    <label for="diy">Over $5k Per Month</label>
                </div>
                <div class="p--relative check">
                    <input type="radio" id="u5kradio" name="income" value="u5k" required/>
                    <label for="hands-on">Under $5k Per Month</label>
                </div>
            </div>
        </div>

        <script>
        var o5kradio = document.getElementById("o5kradio"),
        u5kradio = document.getElementById("u5kradio"),
        submitButton = document.getElementById("SubmitButton");

         submitButton.addEventListener("click", function () {
         if (o5kradio.checked) {
         alert('o5k');
         window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/";
         } else {
         alert('u5k');
         window.location = "https://vincedelmonte7figuremastermind.com/sit-in/schedule-now-2/";
    }
    }, false);
    </script>

        <!--ERROR/SUCCESS MESSAGE-->
        <div class="message js-message"></div>
        <button type="submit" value="submit" id="SubmitButton" class="btn txt--shadow-smaller">Click TO SUBMIT APPLICATION</button>
    </form>
</code>```

Sends users here no matter the selection: https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/

答:
Here is one approach to achieve page redirects based on radio button selection:

const incomeRadioButtons = document.querySelectorAll('[name="income"]');

incomeRadioButtons.forEach((radioButton) => {

  radioButton.onchange = function(){

    window.location.href = window.location.href + radioButton.dataset.url;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.default {
display: none;
}</code>```

<form>

What Is Your Business Currently Generating?

<input type="radio" id="default" name="income" value="default" checked required />Default
<input type="radio" id="o5kradio" name="income" value="o5k" data-url="/o5k/" required  />
Over $5k Per Month
<input type="radio" id="u5kradio" name="income" value="u5k" data-url="/u5k/" required/>
Under $5k Per Month
</form>```

Body:
I have devised this script to redirect to the specific page based on the radio selection but it keeps going to the old link that was setup. Are there any recommendations you can suggest to get this working?

            What Is Your Business Currently Generating?

                    <input type="radio" id="o5kradio" name="income" value="o5k" checked required/>
                    Over $5k Per Month

                    <input type="radio" id="u5kradio" name="income" value="u5k" required/>
                    Under $5k Per Month

        <button type="submit" value="submit" id="SubmitButton" class="btn txt--shadow-smaller">Click TO SUBMIT APPLICATION</button>
    </form>

Sends users here no matter the selection: https://vincedelmonte7figuremastermind.com/sit-in/schedule-now/

Body:
Here is one approach to achieve page redirects based on radio button selection:

const incomeRadioButtons = document.querySelectorAll('[name="income"]');

incomeRadioButtons.forEach((radioButton) => {

  radioButton.onchange = function(){

    window.location.href = window.location.href + radioButton.dataset.url;
  }
});

.default {
display: none;
}

<form>
<h2>What Is Your Business Currently Generating?</h2>

<label class="default"><input type="radio" id="default" name="income" value="default" checked required />Default</label>
<label><input type="radio" id="o5kradio" name="income" value="o5k" data-url="/o5k/" required  />
Over $5k Per Month</label>
<label><input type="radio" id="u5kradio" name="income" value="u5k" data-url="/u5k/" required/>
Under $5k Per Month</label>
</form>


问:
Azure Availability sets vs. Availibility Zones
Azure offers two different availability solutions:

1. Availability Sets

A group with two or more virtual machines in the same Data Center is called Availability Set, this ensures that at least one of the
  virtual machines hosted on Azure will be available if something
  happens. This configuration offers 99.95% SLA.

2. Availability Zones

... Virtual Machines are in different physical locations within an Azure Region. ... Availability zones offer 99.99% SLA.

Not all services support Availability Zones.

My Question

So Availability Zones seem to be the superior solution: Higher SLA at the same price. Are there any reasons why I should choose Availability Sets if Availability Zones are supported?

答:
Azure Availability sets are used to place your VMs in the different Fault Domains and Update domains but in the same Data Center. Hence 99.95 % SLA.

When it comes to Azure Availability Zones, each region is logically divided into 3 Zones and your VMs will be placed in different Fault Domain and Update Domain in different Zones providing more resiliency. Hence 99.99 % SLA.

There are two types - Zonal and Zone redundant.

If you want to decide on which Zone your resource has to be deployed, then choose Zonal service
If you want Azure to manage the Zones, then choose Zonal Redundant service


问:
pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"
I am very new to Python and trying to > pip install linkchecker on Windows 7. Some notes:

pip install is failing no matter the package. For example, > pip install scrapy also results in the SSL error.

Vanilla install of Python 3.4.1 included pip 1.5.6. The first thing I tried to do was install linkchecker. Python 2.7 was already installed, it came with ArcGIS. python and pip were not available from the command line until I installed 3.4.1.

> pip search linkchecker works. Perhaps that is because pip search does not verify the site's SSL certificate.

I am in a company network but we do not go through a proxy to reach the Internet.

Each company computer (including mine) has a Trusted Root Certificate Authority that is used for various reasons including enabling monitoring TLS traffic to https://google.com. Not sure if that has anything to do with it.

Here are the contents of my pip.log after running pip install linkchecker:

Downloading/unpacking linkchecker
  Getting page https://pypi.python.org/simple/linkchecker/
  Could not fetch URL https://pypi.python.org/simple/linkchecker/: connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)
  Will skip URL https://pypi.python.org/simple/linkchecker/ when looking for download links for linkchecker
  Getting page https://pypi.python.org/simple/
  Could not fetch URL https://pypi.python.org/simple/: connection error: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/ (Caused by <class 'http.client.CannotSendRequest'>: Request-sent)
  Will skip URL https://pypi.python.org/simple/ when looking for download links for linkchecker
  Cannot fetch index base URL https://pypi.python.org/simple/
  URLs to search for versions for linkchecker:
  * https://pypi.python.org/simple/linkchecker/
  Getting page https://pypi.python.org/simple/linkchecker/
  Could not fetch URL https://pypi.python.org/simple/linkchecker/: connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)
  Will skip URL https://pypi.python.org/simple/linkchecker/ when looking for download links for linkchecker
  Could not find any downloads that satisfy the requirement linkchecker
Cleaning up...
  Removing temporary dir C:\Users\jcook\AppData\Local\Temp\pip_build_jcook...
No distributions at all found for linkchecker
Exception information:
Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\pip\basecommand.py", line 122, in main
    status = self.run(options, args)
  File "C:\Python34\lib\site-packages\pip\commands\install.py", line 278, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "C:\Python34\lib\site-packages\pip\req.py", line 1177, in prepare_files
    url = finder.find_requirement(req_to_install, upgrade=self.upgrade)
  File "C:\Python34\lib\site-packages\pip\index.py", line 277, in find_requirement
    raise DistributionNotFound('No distributions at all found for %s' % req)
pip.exceptions.DistributionNotFound: No distributions at all found for linkchecker
```

答:
I faced a similar issue. The solution that worked for me
1) uninstall python 2.7
2) delete python27 folder
3) reinstall the latest python</p>


问:
Does Dapper support custom types on stored procedure parameters?
If I have a custom type (in my case, a Date class), is it possible to have Dapper automatically handle the type conversions when setting up stored procedure parameters? At the moment, I have to do this:

```<code>public void Execute(Date value)
{
    var parameters = new DynamicParameters();
    parameters.Add("MyDate", Date.ToDateTime(), DbType.Date);
    Execute("dbo.InsertDate", parameters, CommandType.StoredProcedure);
}
</code>```

Do I really have to convert it to a more recognised system type? I was hoping that Dapper's TypeHandler code would work, but it seems to be ignoring it, so I am assuming that it is only for handling projections when retrieving data, not for parameterising commands.

This is using Dapper 1.60.0 on .NET Framework 4.7.2

答:
Yes, Dapper does support the custom handling of types on stored procedure parameters. Here is a working example for the conversion of a custom Date class:

```<code>// only required once per app-domain, unless SqlMapper.ResetTypeHandlers() is called
SqlMapper.AddTypeHandler(typeof(Date), new DateHandler());

DynamicParameters parameters = new DynamicParameters();
parameters.Add("MyDate", new Date() { MyDate = DateTime.Today });

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    connection.Execute(
        sql: "dbo.InsertDate",
        param: parameters,
        commandType: CommandType.StoredProcedure);
}
</code>```

Here is the class to handle the conversion given to SqlMapper.AddTypeHandler. For setting a stored procedure parameter, it's SetValue that's relevant.

```<code>public class DateHandler : ITypeHandler
{
    public object Parse(Type destinationType, object value)
    {
        return new Date() { MyDate = (DateTime)value };
    }

    public void SetValue(IDbDataParameter parameter, object value)
    {
        parameter.DbType = DbType.Date;
        parameter.Value = ((Date)value).MyDate;
    }
}
</code>```

And for completeness, this is the custom class that needs custom handling.

```<code>public class Date
{
    public DateTime MyDate { get; set; }
}
</code>```

Body:
If I have a custom type (in my case, a Date class), is it possible to have Dapper automatically handle the type conversions when setting up stored procedure parameters? At the moment, I have to do this:

public void Execute(Date value)
{
    var parameters = new DynamicParameters();
    parameters.Add("MyDate", Date.ToDateTime(), DbType.Date);
    Execute("dbo.InsertDate", parameters, CommandType.StoredProcedure);
}

Do I really have to convert it to a more recognised system type? I was hoping that Dapper's TypeHandler code would work, but it seems to be ignoring it, so I am assuming that it is only for handling projections when retrieving data, not for parameterising commands.

This is using Dapper 1.60.0 on .NET Framework 4.7.2

Body:
Yes, Dapper does support the custom handling of types on stored procedure parameters. Here is a working example for the conversion of a custom Date class:

// only required once per app-domain, unless SqlMapper.ResetTypeHandlers() is called
SqlMapper.AddTypeHandler(typeof(Date), new DateHandler());

DynamicParameters parameters = new DynamicParameters();
parameters.Add("MyDate", new Date() { MyDate = DateTime.Today });

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    connection.Execute(
        sql: "dbo.InsertDate",
        param: parameters,
        commandType: CommandType.StoredProcedure);
}

Here is the class to handle the conversion given to SqlMapper.AddTypeHandler. For setting a stored procedure parameter, it's SetValue that's relevant.

public class DateHandler : ITypeHandler
{
    public object Parse(Type destinationType, object value)
    {
        return new Date() { MyDate = (DateTime)value };
    }

    public void SetValue(IDbDataParameter parameter, object value)
    {
        parameter.DbType = DbType.Date;
        parameter.Value = ((Date)value).MyDate;
    }
}

And for completeness, this is the custom class that needs custom handling.

public class Date
{
    public DateTime MyDate { get; set; }
}


问:
Error linking libboost_system in Visual C++
I have a problem using boost.asio. I use Windows XP and Visual Studio 2005

I followed these steps:

I downloaded the latest version (http://sourceforge.net/projects/boost/files/boost/1.46.1/) of W: \boost_1_46_1

I set the environment variable INCLUDE : W:\boost_1_46_1

In the properties of my project (VS->tools->Options project&solutions->vcc++directories) I added $(INCLUDE)

I added in my file. h this:

I get the following error:

LINK : fatal error LNK1104: cannot open file 'libboost_system-vc80-mt-gd-1_46_1.lib

答:
The boost::asio library needs to be built. ( Many other boost 'libraries are headers only and do not need to be built ).  Building it yourself is a small challenge.  Better to use the pre-built binary installer which is here

Once you have the built libraries, one way or another, you have to tell the linker where they are.  However, you do not need to specify each individual library by name, just specify the folder that contains them.  The easiest way to do this IMHO is to create an environment variable called BOOSTROOT which you you set equal to the folder where you installed boost.  Then you tell the linker to look for libraries in $(BOOSTROOT)/lib

ContentLicense: CC BY-SA 3.0


问:
Cost for retrieving user data using Firebase Admin Auth
I came across the following cloud function which gets all users data. What would it cost me transaction wise?</p>

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

const auth = admin.auth();

/**
 * Gets all the users (1000 MAX) from Firebase auth.
 *
 * @param {Object} req Express Request Object.
 * @param {Object} res Express Response Object
 */
const getAllUsers = (req, res) => {
  const maxResults = 1; // optional arg.

  auth.listUsers(maxResults).then((userRecords) => {
    userRecords.users.forEach((user) => console.log(user.toJSON()));
    res.end('Retrieved users list successfully.');
  }).catch((error) => console.log(error));
};

module.exports = {
  api: functions.https.onRequest(getAllUsers),
};
</code>```

答:
As far as I am concerned, there is absolutely no cost connected to this.
This is probably also the reason for the limit of 1000 users.

Firebase Authentication does not  store a lot of data and is not meant to be used as a "database". Hence, it would not make sense to bill "user" reads.
You could also just sit there all day and refresh the Users tab in the Firebase Console and it would also not cost you anything.

You will probably get rate limited if you try to fetch users too often.

For any other concerns, you should contact Firebase support.

Body:
I came across the following cloud function which gets all users data. What would it cost me transaction wise?

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

const auth = admin.auth();

/**
 * Gets all the users (1000 MAX) from Firebase auth.
 *
 * @param {Object} req Express Request Object.
 * @param {Object} res Express Response Object
 */
const getAllUsers = (req, res) => {
  const maxResults = 1; // optional arg.

  auth.listUsers(maxResults).then((userRecords) => {
    userRecords.users.forEach((user) => console.log(user.toJSON()));
    res.end('Retrieved users list successfully.');
  }).catch((error) => console.log(error));
};

module.exports = {
  api: functions.https.onRequest(getAllUsers),
};


问:
How to correctly join tables in Spring Boot
I have a User, and the user has Expenses. In expenses table I want to have the expense id, the user who made the expense and the amount of expense. In the user table I want user id, his username, his current balance and list of all expenses he's made.

I want to join those 2, but I don't know how to correctly reference user, therefore user form Expense class is always null.

First, I send post request to create a user:

```<code>{
    "username":"abcd",
    "balance":"100"
}
</code>```

then I want to create an expense, but here I'm not sure how to correctly send a User:

```<code>{
    "username":"abcd",
    "id":"1",
    "balance":"100",
    "amount":"20"
}
</code>```

and this doesn't work, then I tried like this:

```<code>{
    "User":{
    "username":"abcd",
    "id":"1",
    "balance":"100"
    },
    "amount":"20"
}
</code>```

and that didn't work either.

This is the User class:

```<code>@Entity
@Table(name = "Users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @NotBlank(message = "Username is mandatory")
    private String username;
    private Double balance = 0.0;

    @OneToMany(mappedBy = "user")
    private List<Expense> expenses;
    ...
</code>```

I removed getters and setters from here.

Here is the Expense class:

```<code>@Entity
@Table(name = "Expenses")
public class Expense {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    private Double amount;
    ...
</code>```

For saving the expense I use .save() from JpaRepository<Expense, Long> and for retrieveing everyting I use .findAll().

The result is always the same: get for all expenses gives

```<code>{
        "id": 1,
        "user": null,
        "amount": 20
}
</code>```

and get for all users gives

```<code>{
        "id": 1,
        "username": "abcd",
        "balance": 100,
        "expenses": []
}
</code>```

Now I'm not sure whether I'm sending the requests the wrong way or joining the tables the wrong way or both.

EDIT: here is ExpenseController:

```<code>@RestController
public class ExpenseController {

    @Autowired
    IExpenseService expenseService;

    @GetMapping("/expenses")
    public List<Expense> findExpenses() {
        return expenseService.findAll();
    }

    @PostMapping("/expenses")
    public void createNewExpense(@RequestBody Expense expense) {
        expenseService.createNewExpense(expense);
    }
}
</code>```

createNewUser(...) from ExpenseService

```<code>@Override
    public void createNewExpense(Expense expense) {
        repository.save(expense);
    }
</code>```

and ExpenseRepository:

```<code>@Repository
public interface ExpenseRepository extends JpaRepository<Expense, Long> {
}
</code>```

UserController:

```<code>@RestController
public class UserController {

    @Autowired
    IUserService userService;

    @GetMapping("/users")
    public List<User> findUsers() {
        return userService.findAll();
    }

    @GetMapping("/users/{id}")
    public User findUserById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @PostMapping("/users")
    public ResponseEntity<Object> createUser(@RequestBody User user) {

        if (userService.checkIfUsernameIsTaken(user)) {

            Map<String, Object> response = new HashMap<>();
            response.put("status", HttpStatus.NOT_ACCEPTABLE);
            response.put("errors", "Username is already taken");
            response.put("timestamp", new Date());

            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        } else {
            userService.createNewUser(user);
            User currentUser = userService.findById(userService.findByUsername(user.getUsername()));
            Map<String, Object> response = new HashMap<>();
            response.put("id", currentUser.getId());
            response.put("username", currentUser.getUsername());
            response.put("balance", currentUser.getBalance());
            response.put("expenses", currentUser.getExpenses());
            return new ResponseEntity<>(response, HttpStatus.OK);
        }
    }

    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }

    @PutMapping("/users/{id}/{balance}")
    public void updateBalance(@PathVariable Long id, @PathVariable Double balance) {
        userService.updateBalance(id, balance);
    }
}
</code>```

the rest of the User model is the same as the Expense model.

答:
Try to send post request with this payload (field 'user' begins with a small letter), and i think the 'id' field in user object should be enough

```<code>  {
   "user":{
     "username":"abcd",
     "id":"1",
     "balance":"100"
    },
    "amount":"20"
  }
</code>```

EDIT: Also you need to add @JsonIgnoreProperties("expenses") to your Expense entity to prevent jackson from recursive reading json

```<code>@Entity
@Table(name = "Expenses")
public class Expense {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @JsonIgnoreProperties("expenses")
  @ManyToOne
  @JoinColumn(name = "user_id")
  private User user;

  private Double amount;
.....
</code>```

Body:
I have a User, and the user has Expenses. In expenses table I want to have the expense id, the user who made the expense and the amount of expense. In the user table I want user id, his username, his current balance and list of all expenses he's made.

I want to join those 2, but I don't know how to correctly reference user, therefore user form Expense class is always null.

First, I send post request to create a user:

{
    "username":"abcd",
    "balance":"100"
}

then I want to create an expense, but here I'm not sure how to correctly send a User:

{
    "username":"abcd",
    "id":"1",
    "balance":"100",
    "amount":"20"
}

and this doesn't work, then I tried like this:

{
    "User":{
    "username":"abcd",
    "id":"1",
    "balance":"100"
    },
    "amount":"20"
}

and that didn't work either.

This is the User class:

@Entity
@Table(name = "Users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @NotBlank(message = "Username is mandatory")
    private String username;
    private Double balance = 0.0;

    @OneToMany(mappedBy = "user")
    private List<Expense> expenses;
    ...

I removed getters and setters from here.

Here is the Expense class:

@Entity
@Table(name = "Expenses")
public class Expense {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    private Double amount;
    ...

For saving the expense I use .save() from JpaRepository<Expense, Long> and for retrieveing everyting I use .findAll().

The result is always the same: get for all expenses gives

{
        "id": 1,
        "user": null,
        "amount": 20
}

and get for all users gives

{
        "id": 1,
        "username": "abcd",
        "balance": 100,
        "expenses": []
}

Now I'm not sure whether I'm sending the requests the wrong way or joining the tables the wrong way or both.

EDIT: here is ExpenseController:

@RestController
public class ExpenseController {

    @Autowired
    IExpenseService expenseService;

    @GetMapping("/expenses")
    public List<Expense> findExpenses() {
        return expenseService.findAll();
    }

    @PostMapping("/expenses")
    public void createNewExpense(@RequestBody Expense expense) {
        expenseService.createNewExpense(expense);
    }
}

createNewUser(...) from ExpenseService

@Override
    public void createNewExpense(Expense expense) {
        repository.save(expense);
    }

and ExpenseRepository:

@Repository
public interface ExpenseRepository extends JpaRepository<Expense, Long> {
}

UserController:

@RestController
public class UserController {

    @Autowired
    IUserService userService;

    @GetMapping("/users")
    public List<User> findUsers() {
        return userService.findAll();
    }

    @GetMapping("/users/{id}")
    public User findUserById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @PostMapping("/users")
    public ResponseEntity<Object> createUser(@RequestBody User user) {

        if (userService.checkIfUsernameIsTaken(user)) {

            Map<String, Object> response = new HashMap<>();
            response.put("status", HttpStatus.NOT_ACCEPTABLE);
            response.put("errors", "Username is already taken");
            response.put("timestamp", new Date());

            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        } else {
            userService.createNewUser(user);
            User currentUser = userService.findById(userService.findByUsername(user.getUsername()));
            Map<String, Object> response = new HashMap<>();
            response.put("id", currentUser.getId());
            response.put("username", currentUser.getUsername());
            response.put("balance", currentUser.getBalance());
            response.put("expenses", currentUser.getExpenses());
            return new ResponseEntity<>(response, HttpStatus.OK);
        }
    }

    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }

    @PutMapping("/users/{id}/{balance}")
    public void updateBalance(@PathVariable Long id, @PathVariable Double balance) {
        userService.updateBalance(id, balance);
    }
}

the rest of the User model is the same as the Expense model.

Body:
Try to send post request with this payload (field 'user' begins with a small letter), and i think the 'id' field in user object should be enough

  {
   "user":{
     "username":"abcd",
     "id":"1",
     "balance":"100"
    },
    "amount":"20"
  }

EDIT: Also you need to add @JsonIgnoreProperties("expenses") to your Expense entity to prevent jackson from recursive reading json

@Entity
@Table(name = "Expenses")
public class Expense {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @JsonIgnoreProperties("expenses")
  @ManyToOne
  @JoinColumn(name = "user_id")
  private User user;

  private Double amount;
.....


问:
Bootstrap3 - Glyphicons are not displayed in Chrome, only
Strangely, none of Bootstrap3 glyphicons are displaying in Chrome v31(displays a small square). But, works fine in FF v26, Opera v18, Safari v5.1 and IE v10. Also, works fine in Android 4.x - Chrome and FF.

Tested with simple code:

Please help. Thanks much in advance!

Environment: Windows 8.0

答:
Ensure that you have the fonts folder in your project besides the js, css and others.

If the fonts folder is in the project and the path in the bootstrap.min.css file is like this ../fonts/glyphicons ie the fonts folder not in the css folder, Then everything will work just fine. Thank you.


问:
Why replace the challenge by webauthn?
The following strings are different for server-generated and client-generated challenges:

+ -> -

/ -> _

= -> (empty space)

Why do we need to do substitution to solve this?

Source code used for reference.

webauthn.io

https://webauthn.io/dist/js/webauthn.js

Jxck/jxck.io

https://github.com/Jxck/jxck.io/blob/master/labs.jxck.io/webauthentication/fido-u2f/static/js/base64.mjs

答:
It looks like it the difference between the plain Base64 encoding and Base64 URL, and padding vs. no padding options (trailing =s). The latter is safe to use in URLs, contrary to the former. See also https://en.wikipedia.org/wiki/Base64#URL_applications

Webauthn requires using Base64 URL encoding while some functions (such as javascript's atob or btoa) the plain Base64 encoding scheme, hence the need to convert from one to another.

Title: Why replace the challenge by webauthn?


问:
include the GUI from another process in my qt application
Would you be kind to answer these questios ?

Is there an alternative to FindWindow, but which is cross-platform ?

How can I include the GUI from another process in my qt application ?

Thanks.

答:
Simple answer is: if it had been possible, it would have already been implemented by Qt team.
Please note that identifying processes in various OSes is different, so is identifying "foreign" windows.</p>


问:
Informix connection string error
I'm trying to connecto to informix server. I've downloaded the latest CLient SDK with the server driver package, where are the .net DLL's When I'm using this connection string:

Database=mydb;Server=myip:someport;User
  ID=myuser;Password=mypass

I get "ERROR [08001] [IBM] SQL30081N

But when I try to add something else like protocol or the conn string from https://www.connectionstrings.com/informix/

It says that I have invalid argument exception.

I've tried to read through the stack overflow archive nothing helps, any ideas? My sdk version is: clientsdk.4.10.FC5DE.WIN

答:
Answer for @mabiyan this is what the connection string should look like. I'm posting the answer for better readability

  <connectionStrings>
<add name="InformixDB" connectionString="Host=your_server_addres; Service=port; Server=server_name; User Id=user; Password=pass;Database=db_name;Client_Locale=your_locale;Protocol=onsoctcp;" />
```

The locale part gave me my db admin, and also thinks like port, server name and db name. Hope that helps.

Title: Informix connection string error

Body:
Answer for @mabiyan this is what the connection string should look like. I'm posting the answer for better readability

  <connectionStrings>
<add name="InformixDB" connectionString="Host=your_server_addres; Service=port; Server=server_name; User Id=user; Password=pass;Database=db_name;Client_Locale=your_locale;Protocol=onsoctcp;" />

The locale part gave me my db admin, and also thinks like port, server name and db name. Hope that helps.


问:
Angular5: Hide ag-gird rows based on condition
I have the below response from the service, when ever the flag is true I have to hide the whole row (total 20 columns I have) else show it. How can I achieve this in ag-grid?

```<code>data = {
    name: "A",
    flag: true
   },
   {
    name: "B",
    flag: false
   },
   {
    name: "C",
    flag: false
   }
</code>```

I did try the useExternalFilter like below and then I got stuck as to how to use this useExternalFilter further. Can any one please guide me through.

```<code>this.filterOptions = {
  useExternalFilter: true
};

this.gridOptions = {
  filterOptions:  this.filterOptions
 };
</code>```

答:
Even though we can use api.setRowData(newData) to explicitly update/remove your data, this method essentially hard resets your entire grid. According to the documentation, this results in the following:

the grid discards all previous selections and filters, and completely
  overwrites the old data with the new. This was the first way the grid
  worked and is the most 'brute force' way.

As such, I would recommend you to use transaction.remove instead. According to the documentation, you can either supply the rowNodeId to remove the rows, or we can remove the rows by using the rows based on object reference.

This method is preferred, as

The grid keeps all active sorting, grouping and filtering, including
  updating to reflect the changes in the data should the sorting,
  grouping or filtering be impacted.

First, we can get the list of objects that need to be removed. Then, we use api.updateRowData(transaction) to carry out the transaction to update the row data such that those rows will be removed.

```<code>const removeData = this.data.filter(item => item.flag);
this.gridApi.updateRowData({ remove: removeData });
</code>```

I have created a working demo to illustrate the above behaviour.

Body:
I have the below response from the service, when ever the flag is true I have to hide the whole row (total 20 columns I have) else show it. How can I achieve this in ag-grid?

data = {
    name: "A",
    flag: true
   },
   {
    name: "B",
    flag: false
   },
   {
    name: "C",
    flag: false
   }

I did try the useExternalFilter like below and then I got stuck as to how to use this useExternalFilter further. Can any one please guide me through.

this.filterOptions = {
  useExternalFilter: true
};

this.gridOptions = {
  filterOptions:  this.filterOptions
 };

Body:
Even though we can use api.setRowData(newData) to explicitly update/remove your data, this method essentially hard resets your entire grid. According to the documentation, this results in the following:

the grid discards all previous selections and filters, and completely
  overwrites the old data with the new. This was the first way the grid
  worked and is the most 'brute force' way.

As such, I would recommend you to use transaction.remove instead. According to the documentation, you can either supply the rowNodeId to remove the rows, or we can remove the rows by using the rows based on object reference.

This method is preferred, as

The grid keeps all active sorting, grouping and filtering, including
  updating to reflect the changes in the data should the sorting,
  grouping or filtering be impacted.

First, we can get the list of objects that need to be removed. Then, we use api.updateRowData(transaction) to carry out the transaction to update the row data such that those rows will be removed.

const removeData = this.data.filter(item => item.flag);
this.gridApi.updateRowData({ remove: removeData });

I have created a working demo to illustrate the above behaviour.


答:
The reason for it to skip floor 6, is because of removing the data from the list, which is being iterated.

```<code>l=[3,6,9,10,14]
for i in l:
    print(i)
</code>```

Output:
3
6
9
10
14

```<code>for i in l:
    print(i)
    l.remove(i)
</code>```

output:
3
9
14

Title: Why does my If/Else loop break out of my For loop?

Body:
The reason for it to skip floor 6, is because of removing the data from the list, which is being iterated.

l=[3,6,9,10,14]
for i in l:
    print(i)

Output:
3
6
9
10
14

for i in l:
    print(i)
    l.remove(i)

output:
3
9
14


答:
The reason for the early exit is because you are modifying the list while looping on it. To have a simple example:

```<code>l = [3,6,9,10]

for x in l:
    print(x)
    l.remove(x)
</code>```

The output is

```<code>3
9
</code>```

However, there are many other problems with your current code. Some I could catch are:

You aren't adding the newly called floors inside the for loop.

The floorCompare method is being called with queue[0] as the destination, while that isn't the final one. As you can see, 7 was not considered en route since you compared 3 and 6. You should have compared 3 and 10, the farthest one.

Also note that queue is not initially sorted, and the intermediate calls will also not be in order. So you need to keep that in mind while using it.

Body:
I'm doing a supposedly simple python challenge a friend gave me involving an elevator and the logic behind its movements. Everything was going well and good until I got to the point where I had to write how to determine if the elevator could move hit a called floor en route to its next queued floor.

def floorCompare(currentFloor,destinationFloor,calledFloor):
    if calledFloor > currentFloor and calledFloor < destinationFloor:
        return(True)
    elif calledFloor < currentFloor and calledFloor > destinationFloor:
        return(True)
    else:
        return(False)

floor = "1"
doors = "closed"
queue = []
def elevator(): # function defines how the elevator should move
    print("The Elevator is on floor: 1. The doors are "+doors+".")
    for x in range(int(input("How many floors need to be visited? "))):
        callFloor = int(input("Floor to call the elevator to: "))
        queue.append(callFloor)
        if callFloor > 10 or callFloor < 1:
            raise Exception(str(callFloor)+" is not a valid floor.")
    if queue[0] == 1:
        del queue[0]
        print("The elevator has arrived on floor 1, and the doors are open.")
    print("The queue of floors to visit is...",queue)
    for x in queue:
        print("The elevator's doors are closed and it's moving to floor:",x)
        floor = str(x)
        print("...")
        print()
        print("The elevator has arrived on floor "+floor+", and the doors are open.")
        queue.remove(x)
        addFloor = int(input("Floor to call the elevator to: "))
        if addFloor > 10 or addFloor < 1:
            raise Exception(str(addFloor)+" is not a valid floor.")
        print(queue)
        if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
            print("The elevator can hit this stop en route to its next one.")
        else:
            print("The elevator must hit this stop separately.")
    print("Continuing Queue")

elevator()

So in the For loop, there is a nested If/Else loop, which I would assume would be iterated along with the rest of the code in the for loop. However, when I run the code, upon reaching the If/Else loop, it breaks out of the For loop and continues on its merry way, disregarding any further iterations that need to be done in the array. What's going on here?

When I run the code with a basic trial set of floors, here's what I get as output.

The Elevator is on floor: 1. The doors are closed.
How many floors need to be visited? 4
Floor to call the elevator to: 3
Floor to call the elevator to: 6
Floor to call the elevator to: 9
Floor to call the elevator to: 10
The queue of floors to visit is... [3, 6, 9, 10]
The elevator's doors are closed and it's moving to floor: 3
...

The elevator has arrived on floor 3, and the doors are open.
Floor to call the elevator to: 7
[6, 9, 10]
The elevator must hit this stop seperately.
The elevator's doors are closed and it's moving to floor: 9
...

The elevator has arrived on floor 9, and the doors are open.
Floor to call the elevator to: 3
[6, 10]
The elevator must hit this stop separately.

Process finished with exit code 0

Body:
The reason for the early exit is because you are modifying the list while looping on it. To have a simple example:

l = [3,6,9,10]

for x in l:
    print(x)
    l.remove(x)

The output is

3
9

However, there are many other problems with your current code. Some I could catch are:

You aren't adding the newly called floors inside the for loop.

The floorCompare method is being called with queue[0] as the destination, while that isn't the final one. As you can see, 7 was not considered en route since you compared 3 and 6. You should have compared 3 and 10, the farthest one.

Also note that queue is not initially sorted, and the intermediate calls will also not be in order. So you need to keep that in mind while using it.


Title: Converting array of lists to array of dictionary

Body:
I have data as follows

{"array": [[1288.1639933233453], [1255.1777295971826],
[1250.1075681742996], [1283.9962801780075], [1297.4411412000093]]}

I want to convert above data as follows

[{"value": 1288.1639933233453},
{"value": 1255.1777295971826},
{"value": 1250.1075681742996},
{"value": 1283.9962801780075},
{"value": 1297.4411412000093}]

Body:
You can do this:

values = {"array": [[1288.1639933233453], [1255.1777295971826],
[1250.1075681742996], [1283.9962801780075], [1297.4411412000093]]}

values = [{"value: i[0]} for i in values["array"]]


问:
How to "close" database when the query happens?
```<code>$database->count = "SELECT * FROM table WHERE item_id = 1"

if($database->count == 1)
{
   $database->update = "UPDATE users SET money = money - 1000";
   $database->delete = "DELETE table WHERE item_id = 1";
}
</code>```

Let's say I have this code (I've just created it) in index.php page. Can at the same time "SELECT * FROM table WHERE item_id = 1" query happen so two people would get count 1 and -1000 money? If yes, how can I avoid that?

Thank you.

答:
If you're worried about two queries running at the same time being responsible for unbalanced state in your DB, you should be using transactions : http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-transactions.html

Transactions are helpful in keeping the state of your data correct.

Body:
$database->count = "SELECT * FROM table WHERE item_id = 1"

if($database->count == 1)
{
   $database->update = "UPDATE users SET money = money - 1000";
   $database->delete = "DELETE table WHERE item_id = 1";
}

Let's say I have this code (I've just created it) in index.php page. Can at the same time "SELECT * FROM table WHERE item_id = 1" query happen so two people would get count 1 and -1000 money? If yes, how can I avoid that?

Thank you.


答: Firebase Authentication is for the most part a free product. The only paid part is phone number verification, which you're not using in this code. There's no cost associated with listing users using the Admin SDK.</p>

Title: Cost for retrieving user data using Firebase Admin Auth