问:
Why can't I read the contents of a SameSite Lax cookie when opening a link from the Gmail iOS App?
My company's website (mercury.co) sends password reset links via email to users. We ran into some really weird behavior that we can only reproduce in the Gmail iOS app relating to the SameSite Lax attribute:

The user follows a link in their email to https://mercury.co/reset-password

The browser loads Javascript from that URL to set up the site

The client does a GET request, which returns a CSRF token in a cookie. This token has the SameSite Lax attribute set.

Expected behavior: The client can read the cookie with the CSRF token in it. Actual behavior: The client cannot read the cookie. We've determined this by doing an alert(document.cookie) and seeing the CSRF token is not there when same-site lax is set, but is there when the same-site attribute is not set.

This causes the next POST request to fail because it can't get the CSRF token to be sent to the server. Though, if you look at the cookies that are sent in the request, it includes the cookie that has the CSRF token in it.

My understanding is that the cookie should be readable, because it is not cross-site in this context. And it certainly should not be unreadable, and then sent to the server on the next request.

My understanding is that SameSite Lax cookies should not prevent the client from reading this cookie.

As a fix, we've determined we don't need the SameSite Lax attribute on this particular cookie. However, we'd still like to understand the underlying cause of this issue.

Some details our investigation so far:

We can only reproduce the issue in the iOS Gmail app. We can't reproduce the issue by creating our own UIWebview or WKWebview (I ran in the iOS simulator for iOS 12.2). We can't reproduce it on the two iPads we tested on (though those are maybe different iOS versions). I tested on my iPhone running iOS 12.2

Based on using this method: https://stackoverflow.com/a/18678703/1176156 our application is not embedded in an iframe or anything when run in Gmail. We also disallow wrapping our site in an iframe via header.

答: As it turns out, this must have been a bug in iOS 12.2, because I can no longer reproduce this behavior in iOS 12.3.1. I can't find an iOS changelog detailed enough to show this fix, though, and I didn't find anything relevant in the Webkit changelog.</p>


来源: stackexchange

问:
Pass an additional counter as parameter to a callback
I have a $("").load call to get data and dump it into several divs. Each div has a unique ID that I track with an index variable inside a For loop. I do several ajax calls inside this loop. In the call back function I want to use the value of this index again. However by the time the callback executes, the for loop is already finished the index variable always has the top limit value for the loop.

How can I pass the value to this index to the callback function?

EDIT:

```<code>for (var i=1;i<=daysNum;i++)
{

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + i);

    var tmd=(tomorrow.getMonth()+1)+'/'+(tomorrow.getDate())+'/'+tomorrow.getFullYear();
    var tmdurl=(tomorrow.getMonth()+1)+'%2F'+(tomorrow.getDate())+'%2F'+tomorrow.getFullYear();

    $("#events").append("<div><div id='event"+i+"'></div><div id='date"+i+"'>"+tmd+"</div></div>");
    $("#event"+i).load(seicalendarurl+"/calendar.aspx?CalendarDate="+tmdurl+"&CalendarPeriod=Day .ms-cal-tdayitem, .ms-cal-alldayevent"

        ,  function (data){
             if($("event"+i).html()=="")
                $("date"+i).html("");

           }
    );

}
</code>```

答:
I think the issue is with the load callback function.

You are not missing  the "#" before the event and date element selectors.

Try this version for the load callback:

```<code>function (data){
    if($("#event"+i).html()=="")
        $("#date"+i).html("");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a $("").load call to get data and dump it into several divs. Each div has a unique ID that I track with an index variable inside a For loop. I do several ajax calls inside this loop. In the call back function I want to use the value of this index again. However by the time the callback executes, the for loop is already finished the index variable always has the top limit value for the loop.

How can I pass the value to this index to the callback function?

EDIT:

for (var i=1;i<=daysNum;i++)
{

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + i);

    var tmd=(tomorrow.getMonth()+1)+'/'+(tomorrow.getDate())+'/'+tomorrow.getFullYear();
    var tmdurl=(tomorrow.getMonth()+1)+'%2F'+(tomorrow.getDate())+'%2F'+tomorrow.getFullYear();

    $("#events").append("

"+tmd+"

");
    $("#event"+i).load(seicalendarurl+"/calendar.aspx?CalendarDate="+tmdurl+"&CalendarPeriod=Day .ms-cal-tdayitem, .ms-cal-alldayevent"

        ,  function (data){
             if($("event"+i).html()=="")
                $("date"+i).html("");

           }
    );

}

Body:
I think the issue is with the load callback function.

You are not missing  the "#" before the event and date element selectors.

Try this version for the load callback:

function (data){
    if($("#event"+i).html()=="")
        $("#date"+i).html("");
}


问:
Check if positive value exist in dataframe
I have dataframe:

```<code>A B C D
1 0 0 2
0 1 0 0
0 0 0 0
</code>```

I need to select all values which are greater then 0 and put them in a list.
if row doesnt contain any positive value 0 should be written to list.

So, the output for given dataframe should look like this:

```<code> [1,2,1,0]
</code>```

How this can be resolved?

答:
In your case , first stack with your df, then we apply your condition , if the row contain the none 0 we select , if all 0 , then we keep it as zero

```<code>df.stack().groupby(level=0).apply(lambda x : x.head(1) if all(x==0) else x[x!=0]).tolist()
[1, 2, 1, 0]
</code>```

Or without apply

```<code>np.concatenate(df.mask(df==0).stack().groupby(level=0).apply(list).reindex(df.index,fill_value=[0]).values)
array([1., 2., 1., 0.])
</code>```

Shorten the process

```<code>np.concatenate(list(map(lambda x : [x[0]] if all(x==0) else x[x!=0],df.values)))
array([1, 2, 1, 0])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have dataframe:

A B C D
1 0 0 2
0 1 0 0
0 0 0 0

I need to select all values which are greater then 0 and put them in a list.
if row doesnt contain any positive value 0 should be written to list.

So, the output for given dataframe should look like this:

 [1,2,1,0]

How this can be resolved?

Body:
In your case , first stack with your df, then we apply your condition , if the row contain the none 0 we select , if all 0 , then we keep it as zero

df.stack().groupby(level=0).apply(lambda x : x.head(1) if all(x==0) else x[x!=0]).tolist()
[1, 2, 1, 0]

Or without apply

np.concatenate(df.mask(df==0).stack().groupby(level=0).apply(list).reindex(df.index,fill_value=[0]).values)
array([1., 2., 1., 0.])

Shorten the process

np.concatenate(list(map(lambda x : [x[0]] if all(x==0) else x[x!=0],df.values)))
array([1, 2, 1, 0])


问:
Update multiple rows with loop not working in Laravel
Hi I have simple problem in my project. I want to update data in db.
The sku codes sent with ajax. Like this A-1, A-2, A-3

I tried:

```<code>$sku2 = $request['sku'];
$sku = explode(',', $sku2);
foreach ($sku as $key => $value){
     $content = ProductNew::where('sku', $value)->update(['price' =>
     $price]);
}
</code>```

But it updated only first record (A-1)
Where is the problem?

This is full fuction

```<code>    public function setdiscount(Request $request)
    {
    $discount = Discount::where('id', $request['id'])->first();
    $d_price = $discount['price'];
    $d_type = $discount['type'];
    $price = 17;
    $sku2 = $request['sku'];
    $sku = explode(',', $sku2);
    foreach ($sku as $key => $value){
        ProductNew::whereIn('sku', $sku)->update(['price' => $price]);
    }

    }
</code>```

答:
You can try using wherein() along with update() to update multiple records:</p>

```<code>$sku2 = $request['sku'];
$sku = explode(',', $sku2);

$sku = array_map('trim', $sku);

ProductNew::whereIn('sku', $sku)->update(['price' => $price]);
</code>```

Body:
Hi I have simple problem in my project. I want to update data in db.
The sku codes sent with ajax. Like this A-1, A-2, A-3

I tried:

$sku2 = $request['sku'];
$sku = explode(',', $sku2);
foreach ($sku as $key => $value){
     $content = ProductNew::where('sku', $value)->update(['price' =>
     $price]);
}

But it updated only first record (A-1)
Where is the problem?

This is full fuction

    public function setdiscount(Request $request)
    {
    $discount = Discount::where('id', $request['id'])->first();
    $d_price = $discount['price'];
    $d_type = $discount['type'];
    $price = 17;
    $sku2 = $request['sku'];
    $sku = explode(',', $sku2);
    foreach ($sku as $key => $value){
        ProductNew::whereIn('sku', $sku)->update(['price' => $price]);
    }

    }

Body:
You can try using wherein() along with update() to update multiple records:

$sku2 = $request['sku'];
$sku = explode(',', $sku2);

$sku = array_map('trim', $sku);

ProductNew::whereIn('sku', $sku)->update(['price' => $price]);


问:
parseInt() - String to Integer and back in PHP
Im trying to reverse engineering some Javascript code and recode it in PHP.
There is a String which is "converted" with parseInt(String, 36) to an Integer.
I need a posibility to convert the integer back to the secret String in PHP, without knowing the secret string.

secretCode = "0vo8fz4kvy03";
decode = parseInt(secretCode, 36).toString();
console.log(decode); //= 115802171408044510```
</div>
</div>
</p>

<p>How i can do that in PHP?
<code>115802171408044510</code> back to <code>0vo8fz4kvy03</code></p>

<p>This interger contains some informations:</p>

```decode="115802171408044510";
storeID = decode.substr(0, 4); // 1158
posID = decode.substr(12, 2); // 04
orderID = decode.substr(14, 2); // 45
day = decode.substr(6, 2); // 17
month = decode.substr(4, 2); // 02
hour = decode.substr(8, 2); // 14
minutes = decode.substr(10, 2); // 08
```

I would like to edit this values above and convert this back to a "secretCode" String.
They are doing exactly this somehow server-side.

答:
You can try.

```<code>decode.toString(36)
</code>```

Body:
Im trying to reverse engineering some Javascript code and recode it in PHP.
There is a String which is "converted" with parseInt(String, 36) to an Integer.
I need a posibility to convert the integer back to the secret String in PHP, without knowing the secret string.

secretCode = "0vo8fz4kvy03";
decode = parseInt(secretCode, 36).toString();
console.log(decode); //= 115802171408044510

How i can do that in PHP?
115802171408044510 back to 0vo8fz4kvy03

This interger contains some informations:

decode="115802171408044510";
storeID = decode.substr(0, 4); // 1158
posID = decode.substr(12, 2); // 04
orderID = decode.substr(14, 2); // 45
day = decode.substr(6, 2); // 17
month = decode.substr(4, 2); // 02
hour = decode.substr(8, 2); // 14
minutes = decode.substr(10, 2); // 08

I would like to edit this values above and convert this back to a "secretCode" String.
They are doing exactly this somehow server-side.

Body:
You can try.

decode.toString(36)


问:
Can Python object instances have different logger levels at the same time?
I wanted different objects in my program to have different logging levels. Is that possible?

I made a base class as shown below containing methods to set the logging levels.

```<code>class Logging():
""" Utility class for common methods."""

logging_levels = ['DEBUG','INFO']#,'WARNING','ERROR'

@property
def verbosity(self):
    return self.__verbosity

@verbosity.setter
def verbosity(self,verbosity):
    """Method to set verbosity of logging on terminal. Different classes may have different levels of verbosity."""

    assert verbosity in self.logging_levels, '{} is not a valid logging level!'.format(verbosity)

    self.__verbosity = verbosity

    #Set logging level - {DEBUG,INFO,WARNING,ERROR}
    if verbosity == 'DEBUG':
        logging.getLogger().setLevel(logging.DEBUG)

    elif verbosity == 'INFO':
        logging.getLogger().setLevel(logging.INFO)

    elif verbosity == 'WARNING':
        logging.getLogger().setLevel(logging.INFO)

    print('{}:Logging level is set to:{}'.format(self.name,verbosity))

    return self.__verbosity
</code>```

My other two classes inherit from the 'Logging' class and I have following in their respective init methods:

```<code>self.verbosity = verbosity
</code>```

However, what I observed is that whenever an instance of either class is used to set the logging level, the logging level is set globally.
Is there any way to restrict logging levels to specific class instances?

Edited:
Using the suggestion from John Gordon, I was able to come up with a solution. Please see below.

答:
I was able to resolve it by making the following changes to my Logger class.

```<code>class Logging():
""" Utility class for common methods."""

logging_levels = ['DEBUG','INFO']#,'WARNING','ERROR'

def initialize_logger(self):
    """Initialize loggers for different classes."""

    self.logger = logging.getLogger(type(self).__name__)

@property
def verbosity(self):
    return self.__verbosity

@verbosity.setter
def verbosity(self,verbosity):
    """Method to set verbosity of logging on terminal. Different classes may have different levels of verbosity."""

    assert verbosity in self.logging_levels, '{} is not a valid logging level!'.format(verbosity)

    self.__verbosity = verbosity

    #Set logging level - {DEBUG,INFO,WARNING,ERROR}
    if verbosity == 'DEBUG':
        self.logger.setLevel(logging.DEBUG)

    elif verbosity == 'INFO':
        self.logger.setLevel(logging.INFO)

    elif verbosity == 'WARNING':
        self.logger.setLevel(logging.WARNING)

    self.logger.debug('{}:Logging level is set to:{}'.format(self.name,verbosity))

    return self.__verbosity
</code>```

I added the initialize_logger() method and called it in the init function of the classes I wanted to log from.

```<code>self.initialize_logger()
#Set logging level - {DEBUG,INFO,WARNING,ERROR}
self.verbosity = verbosity
</code>```

Then finally, I used the logger object I created with initialize_logger() instead of logging.debug().

```<code>self.logger.debug('My log message')
</code>```

Now I can control the logging level separately for all the classes.

Body:
I wanted different objects in my program to have different logging levels. Is that possible?

I made a base class as shown below containing methods to set the logging levels.

class Logging():
""" Utility class for common methods."""

logging_levels = ['DEBUG','INFO']#,'WARNING','ERROR'

@property
def verbosity(self):
    return self.__verbosity

@verbosity.setter
def verbosity(self,verbosity):
    """Method to set verbosity of logging on terminal. Different classes may have different levels of verbosity."""

    assert verbosity in self.logging_levels, '{} is not a valid logging level!'.format(verbosity)

    self.__verbosity = verbosity

    #Set logging level - {DEBUG,INFO,WARNING,ERROR}
    if verbosity == 'DEBUG':
        logging.getLogger().setLevel(logging.DEBUG)

    elif verbosity == 'INFO':
        logging.getLogger().setLevel(logging.INFO)

    elif verbosity == 'WARNING':
        logging.getLogger().setLevel(logging.INFO)

    print('{}:Logging level is set to:{}'.format(self.name,verbosity))

    return self.__verbosity

My other two classes inherit from the 'Logging' class and I have following in their respective init methods:

self.verbosity = verbosity

However, what I observed is that whenever an instance of either class is used to set the logging level, the logging level is set globally.
Is there any way to restrict logging levels to specific class instances?

Edited:
Using the suggestion from John Gordon, I was able to come up with a solution. Please see below.

Body:
I was able to resolve it by making the following changes to my Logger class.

class Logging():
""" Utility class for common methods."""

logging_levels = ['DEBUG','INFO']#,'WARNING','ERROR'

def initialize_logger(self):
    """Initialize loggers for different classes."""

    self.logger = logging.getLogger(type(self).__name__)

@property
def verbosity(self):
    return self.__verbosity

@verbosity.setter
def verbosity(self,verbosity):
    """Method to set verbosity of logging on terminal. Different classes may have different levels of verbosity."""

    assert verbosity in self.logging_levels, '{} is not a valid logging level!'.format(verbosity)

    self.__verbosity = verbosity

    #Set logging level - {DEBUG,INFO,WARNING,ERROR}
    if verbosity == 'DEBUG':
        self.logger.setLevel(logging.DEBUG)

    elif verbosity == 'INFO':
        self.logger.setLevel(logging.INFO)

    elif verbosity == 'WARNING':
        self.logger.setLevel(logging.WARNING)

    self.logger.debug('{}:Logging level is set to:{}'.format(self.name,verbosity))

    return self.__verbosity

I added the initialize_logger() method and called it in the init function of the classes I wanted to log from.

self.initialize_logger()
#Set logging level - {DEBUG,INFO,WARNING,ERROR}
self.verbosity = verbosity

Then finally, I used the logger object I created with initialize_logger() instead of logging.debug().

self.logger.debug('My log message')

Now I can control the logging level separately for all the classes.


问:
How to batch send existing Purchase Orders through a new PO Output Condition?
Our company has recently integrated with an existing supplier through EDI. The supplier has requested re-output of all existing PO's through EDI to sync their system.

We use tcode MN04 to establish the output condition, which works just fine for new POs. However, is anyone aware of a method to, in a batch, re-output the existing PO's through this new medium (EDI)?

答: You can use standard program SD70AV1A. It is intended especially for sales orders.


问:
UISegmentedControl works on iPhone but not iPad?
I use a UISegmentedControl, with 2 segments that spans the width of the screen.

This works as expected on iPhone. Tapping cat mode switches the highlight to cat mode, and the appropriate functions take place. However, on iPad, tapping Cat Mode does nothing. No highlight switch, no functions. If I start the highlight on Cat Mode, the same thing happens in reverse (all good on iPhone, Dog Mode can't be selected on iPad).

I use obviously one storyboard for both iPhone and iPad with Autolayout, and I'm not varying anything related to this segmented control for traits, so I have no clue what's going on. All other functions perform properly on iPhone and iPad.

Please let me know if I can provide additional info to help solve this question.

Thanks!

答: There was a Google Ad Banner blocking it. View debugger helped me see that. Thanks @matt for the suggestion to try it. </p>


问:
Get documents names in Firestore
When I get several documents from a collection, the result is only an array with each doc data.

```<code>firestore.collection("categories").valueChanges().subscribe(data => {
    console.log(data);
    // result will be: [{…}, {…}, {…}]
};
</code>```

How can I get the name of each doc?

The ideal result would look like this:

```<code>{"docname1": {…}, "docname2": {…}, "docname3": {…}}
</code>```

答:
```<code>// Print each document
db.collection("categories")
    .onSnapshot((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            console.log(doc.data()); // For data inside doc
            console.log(doc.id); // For doc name
        }
    }
</code>```

Title: Get documents names in Firestore

Body:
When I get several documents from a collection, the result is only an array with each doc data.

firestore.collection("categories").valueChanges().subscribe(data => {
    console.log(data);
    // result will be: [{…}, {…}, {…}]
};

How can I get the name of each doc?

The ideal result would look like this:

{"docname1": {…}, "docname2": {…}, "docname3": {…}}


问:
append the query with custom data modifications to add more
I have table where i am getting 10 records, out of those 10 records, one of the record has a value of 0 or -110 & 3, those two records have the same ID, so i want to remove those 3 rows from the query itself and then add the following condition just after those has been removed

```<code>AND DATEDIFF(day, ddate, GETDATE()) >= 21
</code>```

so consider my query has a sample data of like this

This is the query which derives the table data:

```<code>select id,name,counts,section,skid,ddate from mytable;

<table cellpadding="1" cellspacing="1">
<tr>
    <th>id</th>
    <th>name</th>
    <th>counts</th>
    <th>section</th>
    <th>skid</th>
</tr>
<tr>
    <td>1</td>
    <td>Jeremy</td>
    <td>0B4C96F0-AACE-5EC1-DA8B-A1F108804751</td>
    <td>-100</td>
    <td>84</td>
</tr>
<tr>
    <td>2</td>
    <td>Harrison</td>
    <td>986777D5-EAB3-5C72-A0B1-DE193A9D8102</td>
    <td>0</td>
    <td>84</td>
</tr>
<tr>
    <td>3</td>
    <td>Maia</td>
    <td>C401BA2E-086D-79EA-D230-2D1F55E3ECE9</td>
    <td>25</td>
    <td>84</td>
</tr>
<tr>
    <td>4</td>
    <td>Porter</td>
    <td>8C01AF11-F0E7-C843-0526-8D2549DB7DA7</td>
    <td>1669011652099</td>
    <td>47</td>
</tr>
<tr>
    <td>5</td>
    <td>Glenna</td>
    <td>B3299BC5-EA12-4F44-80E8-7331B79CF0D7</td>
    <td>1669030858599</td>
    <td>70</td>
</tr>
<tr>
    <td>6</td>
    <td>Nerea</td>
    <td>AF4EDD7C-A78F-2432-947E-A80B2B921713</td>
    <td>1647051538999</td>
    <td>44</td>
</tr>
<tr>
    <td>7</td>
    <td>Ulric</td>
    <td>3C630CD8-48F4-4D3E-5AFB-422F0664413B</td>
    <td>1674070698799</td>
    <td>47</td>
</tr>
<tr>
    <td>8</td>
    <td>Haley</td>
    <td>130BC961-B088-C5F9-106B-3C4EAF17359E</td>
    <td>1698091609199</td>
    <td>13</td>
</tr>
<tr>
    <td>9</td>
    <td>Dieter</td>
    <td>DD6DC447-B9A0-587D-D8CD-69ED71AE8967</td>
    <td>1600010948999</td>
    <td>10</td>
</tr>
<tr>
    <td>10</td>
    <td>Ariel</td>
    <td>DC6C1F2F-BB82-4E0B-A721-9970034BC07F</td>
    <td>1644031708599</td>
    <td>28</td>
</tr>
<tr>
    <td>11</td>
    <td>Nero</td>
    <td>542EEC9D-4D54-E6B0-16E7-14D3739DCD58</td>
    <td>1629091067899</td>
    <td>16</td>
</tr>
<tr>
    <td>12</td>
    <td>Brody</td>
    <td>4D3CCBF7-1559-544F-D3AF-C624EB16F62C</td>
    <td>1681060760299</td>
    <td>16</td>
</tr>
<tr>
    <td>13</td>
    <td>Eleanor</td>
    <td>201139AF-BC57-0929-E8C6-55F67979A3AD</td>
    <td>1679071473899</td>
    <td>93</td>
</tr>
<tr>
    <td>14</td>
    <td>Nathaniel</td>
    <td>9C545A83-0A9B-DCC8-C499-73101900E2CC</td>
    <td>1661082853199</td>
    <td>79</td>
</tr>
<tr>
    <td>15</td>
    <td>Erasmus</td>
    <td>6D8A578D-3D6D-57A0-E13A-CCF3E217967C</td>
    <td>1633021494299</td>
    <td>22</td>
</tr>
<tr>
    <td>16</td>
    <td>Ocean</td>
    <td>8777AC50-DF94-D5E6-9BA7-33D46C308E0B</td>
    <td>1646060491099</td>
    <td>84</td>
</tr>
<tr>
    <td>17</td>
    <td>Davis</td>
    <td>5513033D-4027-2F35-F041-9CAB1CFEDF5B</td>
    <td>1604042329999</td>
    <td>49</td>
</tr>
<tr>
    <td>18</td>
    <td>Dylan</td>
    <td>1632F874-F5FF-76BA-A5E4-71CF3A49F447</td>
    <td>1654112964999</td>
    <td>64</td>
</tr>
<tr>
    <td>19</td>
    <td>Sydney</td>
    <td>F405C793-9CD0-7522-3815-1AF5F6ED3EEE</td>
    <td>1651092172699</td>
    <td>36</td>
</tr>
<tr>
    <td>20</td>
    <td>Uriah</td>
    <td>9C689833-F56B-A2BF-83CA-8482A2DDAE73</td>
    <td>1612082112199</td>
    <td>5</td>
</tr>
<tr>
    <td>21</td>
    <td>Colt</td>
    <td>E04E8A54-0614-D4B0-DA1B-6F3793A2F9B9</td>
    <td>1620092569699</td>
    <td>17</td>
</tr>
<tr>
    <td>22</td>
    <td>Nichole</td>
    <td>344EA952-03B0-6B3F-9BD9-4A2A33B21969</td>
    <td>1625062523899</td>
    <td>19</td>
</tr>
<tr>
    <td>23</td>
    <td>Grant</td>
    <td>F4079717-1B11-A222-7896-75EBD5415199</td>
    <td>1616100287299</td>
    <td>22</td>
</tr>
<tr>
    <td>24</td>
    <td>Mark</td>
    <td>8C9B0252-EA63-C7FE-3E08-ED85746F05C6</td>
    <td>1652101578299</td>
    <td>78</td>
</tr>
<tr>
    <td>25</td>
    <td>Vernon</td>
    <td>77B6F222-6508-E34C-8B05-F92447FB295D</td>
    <td>1650042574699</td>
    <td>7</td>
</tr>
<tr>
    <td>26</td>
    <td>Hamish</td>
    <td>866DBCE3-754B-2CF7-29BB-CCEFBE3F51CE</td>
    <td>1691092777899</td>
    <td>3</td>
</tr>
<tr>
    <td>27</td>
    <td>Paloma</td>
    <td>A3AB2268-9F3E-59B6-570C-8CB3CFEFDC4F</td>
    <td>1695032198499</td>
    <td>39</td>
</tr>
<tr>
    <td>28</td>
    <td>Indigo</td>
    <td>751A36C1-3BA6-4696-21F4-9A86F429F26F</td>
    <td>1638101107199</td>
    <td>7</td>
</tr>
<tr>
    <td>29</td>
    <td>Caldwell</td>
    <td>00FB952F-2942-9AE0-F135-9544BCC231EF</td>
    <td>1666081161399</td>
    <td>62</td>
</tr>
<tr>
    <td>30</td>
    <td>Addison</td>
    <td>577752CB-B698-0F39-C088-38239FBC4175</td>
    <td>1666120504499</td>
    <td>35</td>
</tr>
<tr>
    <td>31</td>
    <td>Zeph</td>
    <td>E3D1BED8-E83E-705C-0B49-C944885EDDD9</td>
    <td>1613070119299</td>
    <td>26</td>
</tr>
<tr>
    <td>32</td>
    <td>Leah</td>
    <td>24A03760-1359-F74A-9993-400CA74989E0</td>
    <td>1671100721999</td>
    <td>69</td>
</tr>
<tr>
    <td>33</td>
    <td>Harlan</td>
    <td>DA71BC34-C887-5240-87F7-AFDB62FCEBEF</td>
    <td>1634061625699</td>
    <td>73</td>
</tr>
<tr>
    <td>34</td>
    <td>Barbara</td>
    <td>15566CAB-1612-9CE6-AA2C-689370B716B7</td>
    <td>1641120968899</td>
    <td>14</td>
</tr>
<tr>
    <td>35</td>
    <td>Arden</td>
    <td>CC14D9E6-1A42-91E7-51ED-EBB07D1893BB</td>
    <td>1631020829599</td>
    <td>81</td>
</tr>
<tr>
    <td>36</td>
    <td>Rylee</td>
    <td>6EAD8D4C-0772-890B-2777-11BF39118699</td>
    <td>1661100717699</td>
    <td>58</td>
</tr>
<tr>
    <td>37</td>
    <td>Keegan</td>
    <td>99C05F56-D2D5-BE91-9096-A0EC862978F7</td>
    <td>1678023087399</td>
    <td>84</td>
</tr>
<tr>
    <td>38</td>
    <td>Lee</td>
    <td>FD008FE6-9DEB-7C23-A1A5-B302F2BAB9D3</td>
    <td>1681032241999</td>
    <td>19</td>
</tr>
<tr>
    <td>39</td>
    <td>Mia</td>
    <td>9DDD3D31-1F83-1773-4EF1-6C8A227B0D13</td>
    <td>1620031462299</td>
    <td>97</td>
</tr>
<tr>
    <td>40</td>
    <td>Colt</td>
    <td>27699409-B83A-0136-2833-E021DF5BD4B4</td>
    <td>1650072467399</td>
    <td>63</td>
</tr>
<tr>
    <td>41</td>
    <td>Abdul</td>
    <td>80D98E0D-0594-7149-0771-48C53F763020</td>
    <td>1621111858399</td>
    <td>71</td>
</tr>
<tr>
    <td>42</td>
    <td>Jana</td>
    <td>F5D63E7A-8D87-765C-211A-125A722CD307</td>
    <td>1600100835399</td>
    <td>82</td>
</tr>
<tr>
    <td>43</td>
    <td>John</td>
    <td>C345760F-8C61-DF91-D65A-DFEC171CA098</td>
    <td>1641040266599</td>
    <td>72</td>
</tr>
<tr>
    <td>44</td>
    <td>Evangeline</td>
    <td>56E4C39A-5534-3752-72D6-A0DB1A9367BE</td>
    <td>1653060725799</td>
    <td>18</td>
</tr>
<tr>
    <td>45</td>
    <td>Keelie</td>
    <td>A5E9377C-B4D9-6FA3-0543-DE6038D793D1</td>
    <td>1676010796399</td>
    <td>58</td>
</tr>
<tr>
    <td>46</td>
    <td>Carson</td>
    <td>31E2BE9C-B2DE-54EF-FF99-000E047048FF</td>
    <td>1627122285599</td>
    <td>30</td>
</tr>
<tr>
    <td>47</td>
    <td>Kasper</td>
    <td>5B074C3A-A230-4608-EFBF-A8E9CD3FE266</td>
    <td>1650101362399</td>
    <td>90</td>
</tr>
<tr>
    <td>48</td>
    <td>Tate</td>
    <td>E99105AF-8DFE-EE94-9E58-8F982CAFBA55</td>
    <td>1659060933899</td>
    <td>14</td>
</tr>
<tr>
    <td>49</td>
    <td>Mechelle</td>
    <td>D77F0060-87A6-61AD-F178-C8D7B3845FC0</td>
    <td>1668111980499</td>
    <td>24</td>
</tr>
<tr>
    <td>50</td>
    <td>Pamela</td>
    <td>F8583251-6DE0-A1FA-2187-70597B4CD404</td>
    <td>1628121968099</td>
    <td>9</td>
</tr>
<tr>
    <td>51</td>
    <td>Fletcher</td>
    <td>57313BC1-BCCD-137E-33FF-BB067DB56638</td>
    <td>1692112615899</td>
    <td>8</td>
</tr>
<tr>
    <td>52</td>
    <td>Carla</td>
    <td>CE56A0A8-FD27-F461-5E51-EE5AB573DBD5</td>
    <td>1661032917899</td>
    <td>73</td>
</tr>
<tr>
    <td>53</td>
    <td>Basia</td>
    <td>9BD2CDC6-6B0A-C9D4-DE6E-A4BA28CD6427</td>
    <td>1687041589899</td>
    <td>59</td>
</tr>
<tr>
    <td>54</td>
    <td>Lesley</td>
    <td>CE21D00A-00F6-418C-C9E8-5B09CAD64B18</td>
    <td>1639050475699</td>
    <td>16</td>
</tr>
<tr>
    <td>55</td>
    <td>Jade</td>
    <td>132AE1C1-16E7-63AC-3D8A-B8C23E97813A</td>
    <td>1651082175399</td>
    <td>38</td>
</tr>
<tr>
    <td>56</td>
    <td>Autumn</td>
    <td>E2FA0C3E-B6F3-D40E-5FA6-0CA459C96278</td>
    <td>1690041526599</td>
    <td>84</td>
</tr>
<tr>
    <td>57</td>
    <td>Joan</td>
    <td>B6315225-A567-2DE6-F931-26FF2161D999</td>
    <td>1682022818699</td>
    <td>96</td>
</tr>
<tr>
    <td>58</td>
    <td>Marcia</td>
    <td>4CDB28E7-A449-27C3-3A78-4CDCF905AD07</td>
    <td>1641040720799</td>
    <td>88</td>
</tr>
<tr>
    <td>59</td>
    <td>Regan</td>
    <td>6D93AF43-13C8-0379-04C5-1C56A8930A5B</td>
    <td>1663052343799</td>
    <td>46</td>
</tr>
<tr>
    <td>60</td>
    <td>Christian</td>
    <td>818482C2-9912-BD5B-399B-BEEFE3DCE8D3</td>
    <td>1677020840699</td>
    <td>69</td>
</tr>
<tr>
    <td>61</td>
    <td>Wing</td>
    <td>7746878F-2BE8-7CFA-AD7D-4E9B0D77661F</td>
    <td>1670121897699</td>
    <td>65</td>
</tr>
<tr>
    <td>62</td>
    <td>Merritt</td>
    <td>79FE8FF1-42C4-3FA0-E3BC-51170948FC69</td>
    <td>1672010917299</td>
    <td>44</td>
</tr>
<tr>
    <td>63</td>
    <td>Kay</td>
    <td>D44BA900-07A0-24E8-9000-0D1FF173E5B7</td>
    <td>1677072899899</td>
    <td>53</td>
</tr>
<tr>
    <td>64</td>
    <td>Alfreda</td>
    <td>501006BC-AFE4-046C-20CA-41B4452A2F99</td>
    <td>1676022339299</td>
    <td>67</td>
</tr>
<tr>
    <td>65</td>
    <td>Barrett</td>
    <td>647ED1CB-7B40-81B9-05E3-19A0EEF00840</td>
    <td>1695071106999</td>
    <td>48</td>
</tr>
<tr>
    <td>66</td>
    <td>Edward</td>
    <td>CE31C4D2-391F-8CED-802D-36DD986A516D</td>
    <td>1668100834399</td>
    <td>3</td>
</tr>
<tr>
    <td>67</td>
    <td>Rudyard</td>
    <td>6CF06D57-3019-7B1D-3EA0-2DD297322D18</td>
    <td>1650072406099</td>
    <td>17</td>
</tr>
<tr>
    <td>68</td>
    <td>Rana</td>
    <td>487B8EF0-D757-353E-88BD-6AEB7E2A6892</td>
    <td>1649061924599</td>
    <td>71</td>
</tr>
<tr>
    <td>69</td>
    <td>Yuli</td>
    <td>040854F3-5D96-A14C-2D5B-F38E58752356</td>
    <td>1665022089299</td>
    <td>77</td>
</tr>
<tr>
    <td>70</td>
    <td>Debra</td>
    <td>E31EFCD4-CFC6-271B-5E94-764D0A317680</td>
    <td>1682021613899</td>
    <td>28</td>
</tr>
<tr>
    <td>71</td>
    <td>Eaton</td>
    <td>0B20B2EA-301E-24C6-B901-80CA984BDAC5</td>
    <td>1692123002399</td>
    <td>66</td>
</tr>
<tr>
    <td>72</td>
    <td>Acton</td>
    <td>F87766EE-273D-E8BC-88EB-4DB0ED6D07F1</td>
    <td>1688081955899</td>
    <td>41</td>
</tr>
<tr>
    <td>73</td>
    <td>Wallace</td>
    <td>02A2797C-E2E7-6E8B-2F54-14422B96EAC3</td>
    <td>1682010642899</td>
    <td>5</td>
</tr>
<tr>
    <td>74</td>
    <td>Valentine</td>
    <td>7EFC2906-5549-C5FB-EA40-75AC790531A1</td>
    <td>1642091417399</td>
    <td>11</td>
</tr>
<tr>
    <td>75</td>
    <td>Zane</td>
    <td>C10D8142-36D7-D358-513C-34079B93EED4</td>
    <td>1638121063899</td>
    <td>8</td>
</tr>
<tr>
    <td>76</td>
    <td>Addison</td>
    <td>A1426ED4-7ECF-C09A-0541-482DD835D7E8</td>
    <td>1657040512199</td>
    <td>41</td>
</tr>
<tr>
    <td>77</td>
    <td>Hedda</td>
    <td>FCF42864-0F47-55E8-ADC1-2878EB905976</td>
    <td>1679120807899</td>
    <td>68</td>
</tr>
<tr>
    <td>78</td>
    <td>Zeus</td>
    <td>89D8AD53-D477-1FE9-720E-28A54D9748CB</td>
    <td>1615032107099</td>
    <td>93</td>
</tr>
<tr>
    <td>79</td>
    <td>Shaeleigh</td>
    <td>2DF52B59-F914-2D5A-F1FA-C752AF13AC29</td>
    <td>1621010516399</td>
    <td>90</td>
</tr>
<tr>
    <td>80</td>
    <td>Peter</td>
    <td>791F363D-74BB-51B8-F05F-88E9A3E8D2D5</td>
    <td>1685060734699</td>
    <td>54</td>
</tr>
<tr>
    <td>81</td>
    <td>Chaney</td>
    <td>A843E306-7D2A-90EE-35B1-C6C99C73D5B8</td>
    <td>1651082857899</td>
    <td>98</td>
</tr>
<tr>
    <td>82</td>
    <td>Whitney</td>
    <td>10380818-AB30-501E-BFF3-8647EEC2CD3A</td>
    <td>1620072074699</td>
    <td>64</td>
</tr>
<tr>
    <td>83</td>
    <td>Rhiannon</td>
    <td>FBDBE676-2BDE-59BE-A3B5-6126C278274F</td>
    <td>1620071659699</td>
    <td>12</td>
</tr>
<tr>
    <td>84</td>
    <td>Risa</td>
    <td>CE7C1D86-A526-4AB6-BEC4-BF02880DE498</td>
    <td>1647092989299</td>
    <td>20</td>
</tr>
<tr>
    <td>85</td>
    <td>Hoyt</td>
    <td>C8D5DA43-42A4-9C9C-C954-7DDD0F577899</td>
    <td>1652022451199</td>
    <td>8</td>
</tr>
<tr>
    <td>86</td>
    <td>Cruz</td>
    <td>4AB62FBA-3F65-2F88-8D9D-7DF7A5159C74</td>
    <td>1603091524299</td>
    <td>56</td>
</tr>
<tr>
    <td>87</td>
    <td>Riley</td>
    <td>61E2C7FC-6435-F765-C376-9027981F823D</td>
    <td>1693092567199</td>
    <td>66</td>
</tr>
<tr>
    <td>88</td>
    <td>Magee</td>
    <td>13708277-A251-8C42-E8BD-C0218620F6E1</td>
    <td>1601051836499</td>
    <td>40</td>
</tr>
<tr>
    <td>89</td>
    <td>Mia</td>
    <td>2843F1B7-A70E-808C-7B8A-423925548D73</td>
    <td>1693061729799</td>
    <td>26</td>
</tr>
<tr>
    <td>90</td>
    <td>Solomon</td>
    <td>30828793-2CFF-C962-0ACC-5FC62AECE5F9</td>
    <td>1625060887299</td>
    <td>36</td>
</tr>
<tr>
    <td>91</td>
    <td>Josephine</td>
    <td>C43233D9-F4E9-EF31-9D77-2A913610CEC9</td>
    <td>1644101032099</td>
    <td>40</td>
</tr>
<tr>
    <td>92</td>
    <td>Odysseus</td>
    <td>4C4DD636-1403-2B4E-FD2B-36BAC8D7E450</td>
    <td>1626051308899</td>
    <td>28</td>
</tr>
<tr>
    <td>93</td>
    <td>Dana</td>
    <td>1FC26C48-5E15-1960-6041-7077670A9199</td>
    <td>1695061049499</td>
    <td>2</td>
</tr>
<tr>
    <td>94</td>
    <td>Eugenia</td>
    <td>B11F52CF-4168-C9BC-C5A0-E5F5DBA252B2</td>
    <td>1680102398699</td>
    <td>91</td>
</tr>
<tr>
    <td>95</td>
    <td>Brett</td>
    <td>4C51F8FC-1B90-B1B1-7A79-B34576FE6593</td>
    <td>1635110576499</td>
    <td>26</td>
</tr>
<tr>
    <td>96</td>
    <td>Quentin</td>
    <td>3B06D55B-2ACC-3926-42A8-80BD159C7062</td>
    <td>1628102018799</td>
    <td>53</td>
</tr>
<tr>
    <td>97</td>
    <td>Mira</td>
    <td>AF1BF61F-DA2D-7332-CCFF-D180420D5017</td>
    <td>1611031933599</td>
    <td>51</td>
</tr>
<tr>
    <td>98</td>
    <td>Adena</td>
    <td>FB963253-D1D3-F1F5-94B0-8E7598D9F03E</td>
    <td>1617051389799</td>
    <td>97</td>
</tr>
<tr>
    <td>99</td>
    <td>Nerea</td>
    <td>09320800-762C-3901-685D-B4DE1D9857CE</td>
    <td>1681032376299</td>
    <td>88</td>
</tr>
<tr>
    <td>100</td>
    <td>Vance</td>
    <td>DF056662-B997-9F8F-A3DB-3283C15B38E7</td>
    <td>1648120830099</td>
    <td>2</td>
</tr>
</table>
</code>```

This is the GIST of the Table

https://trycf.com/gist/26f59ea4fb3cae57cd76ad31c2f604da/lucee5?theme=monokai

my query is generating data like above

so within the query itself i want to remove those 3 rows which have a minus value, the same skid has one minus value, it will remove all its records

and add the above date condition i have to the query

how can i do all this in one sql condition, something using declare, i am not sure

答:
```<code>;with cteexclude
as
(
  select *
  from mytable c
  --Here you are excluding all SPID from selection
  --from MyTable that returns from the sub query
  --by this not in checking, you are getting only
  --records for SPID has all positive Section value
  where c.spid not in
  (
    --This part of query will return all spid
    --has at least 1 or more 0 or Negative value
    select distinct spid
    from mytable
    --For example Section calculation is as below
    --Then Do the calculation directly as shown below
    WHERE dateDiff(day,startdate,getDate()) <= 0
  )
)
--Now select all records from cteexclude
select * from cteexclude;
</code>```

Body:
I have table where i am getting 10 records, out of those 10 records, one of the record has a value of 0 or -110 & 3, those two records have the same ID, so i want to remove those 3 rows from the query itself and then add the following condition just after those has been removed

AND DATEDIFF(day, ddate, GETDATE()) >= 21

so consider my query has a sample data of like this

This is the query which derives the table data:

select id,name,counts,section,skid,ddate from mytable;

    id
    name
    counts
    section
    skid

    1
    Jeremy
    0B4C96F0-AACE-5EC1-DA8B-A1F108804751
    -100
    84

    2
    Harrison
    986777D5-EAB3-5C72-A0B1-DE193A9D8102
    0
    84

    3
    Maia
    C401BA2E-086D-79EA-D230-2D1F55E3ECE9
    25
    84

    4
    Porter
    8C01AF11-F0E7-C843-0526-8D2549DB7DA7
    1669011652099
    47

    5
    Glenna
    B3299BC5-EA12-4F44-80E8-7331B79CF0D7
    1669030858599
    70

    6
    Nerea
    AF4EDD7C-A78F-2432-947E-A80B2B921713
    1647051538999
    44

    7
    Ulric
    3C630CD8-48F4-4D3E-5AFB-422F0664413B
    1674070698799
    47

    8
    Haley
    130BC961-B088-C5F9-106B-3C4EAF17359E
    1698091609199
    13

    9
    Dieter
    DD6DC447-B9A0-587D-D8CD-69ED71AE8967
    1600010948999
    10

    10
    Ariel
    DC6C1F2F-BB82-4E0B-A721-9970034BC07F
    1644031708599
    28

    11
    Nero
    542EEC9D-4D54-E6B0-16E7-14D3739DCD58
    1629091067899
    16

    12
    Brody
    4D3CCBF7-1559-544F-D3AF-C624EB16F62C
    1681060760299
    16

    13
    Eleanor
    201139AF-BC57-0929-E8C6-55F67979A3AD
    1679071473899
    93

    14
    Nathaniel
    9C545A83-0A9B-DCC8-C499-73101900E2CC
    1661082853199
    79

    15
    Erasmus
    6D8A578D-3D6D-57A0-E13A-CCF3E217967C
    1633021494299
    22

    16
    Ocean
    8777AC50-DF94-D5E6-9BA7-33D46C308E0B
    1646060491099
    84

    17
    Davis
    5513033D-4027-2F35-F041-9CAB1CFEDF5B
    1604042329999
    49

    18
    Dylan
    1632F874-F5FF-76BA-A5E4-71CF3A49F447
    1654112964999
    64

    19
    Sydney
    F405C793-9CD0-7522-3815-1AF5F6ED3EEE
    1651092172699
    36

    20
    Uriah
    9C689833-F56B-A2BF-83CA-8482A2DDAE73
    1612082112199
    5

    21
    Colt
    E04E8A54-0614-D4B0-DA1B-6F3793A2F9B9
    1620092569699
    17

    22
    Nichole
    344EA952-03B0-6B3F-9BD9-4A2A33B21969
    1625062523899
    19

    23
    Grant
    F4079717-1B11-A222-7896-75EBD5415199
    1616100287299
    22

    24
    Mark
    8C9B0252-EA63-C7FE-3E08-ED85746F05C6
    1652101578299
    78

    25
    Vernon
    77B6F222-6508-E34C-8B05-F92447FB295D
    1650042574699
    7

    26
    Hamish
    866DBCE3-754B-2CF7-29BB-CCEFBE3F51CE
    1691092777899
    3

    27
    Paloma
    A3AB2268-9F3E-59B6-570C-8CB3CFEFDC4F
    1695032198499
    39

    28
    Indigo
    751A36C1-3BA6-4696-21F4-9A86F429F26F
    1638101107199
    7

    29
    Caldwell
    00FB952F-2942-9AE0-F135-9544BCC231EF
    1666081161399
    62

    30
    Addison
    577752CB-B698-0F39-C088-38239FBC4175
    1666120504499
    35

    31
    Zeph
    E3D1BED8-E83E-705C-0B49-C944885EDDD9
    1613070119299
    26

    32
    Leah
    24A03760-1359-F74A-9993-400CA74989E0
    1671100721999
    69

    33
    Harlan
    DA71BC34-C887-5240-87F7-AFDB62FCEBEF
    1634061625699
    73

    34
    Barbara
    15566CAB-1612-9CE6-AA2C-689370B716B7
    1641120968899
    14

    35
    Arden
    CC14D9E6-1A42-91E7-51ED-EBB07D1893BB
    1631020829599
    81

    36
    Rylee
    6EAD8D4C-0772-890B-2777-11BF39118699
    1661100717699
    58

    37
    Keegan
    99C05F56-D2D5-BE91-9096-A0EC862978F7
    1678023087399
    84

    38
    Lee
    FD008FE6-9DEB-7C23-A1A5-B302F2BAB9D3
    1681032241999
    19

    39
    Mia
    9DDD3D31-1F83-1773-4EF1-6C8A227B0D13
    1620031462299
    97

    40
    Colt
    27699409-B83A-0136-2833-E021DF5BD4B4
    1650072467399
    63

    41
    Abdul
    80D98E0D-0594-7149-0771-48C53F763020
    1621111858399
    71

    42
    Jana
    F5D63E7A-8D87-765C-211A-125A722CD307
    1600100835399
    82

    43
    John
    C345760F-8C61-DF91-D65A-DFEC171CA098
    1641040266599
    72

    44
    Evangeline
    56E4C39A-5534-3752-72D6-A0DB1A9367BE
    1653060725799
    18

    45
    Keelie
    A5E9377C-B4D9-6FA3-0543-DE6038D793D1
    1676010796399
    58

    46
    Carson
    31E2BE9C-B2DE-54EF-FF99-000E047048FF
    1627122285599
    30

    47
    Kasper
    5B074C3A-A230-4608-EFBF-A8E9CD3FE266
    1650101362399
    90

    48
    Tate
    E99105AF-8DFE-EE94-9E58-8F982CAFBA55
    1659060933899
    14

    49
    Mechelle
    D77F0060-87A6-61AD-F178-C8D7B3845FC0
    1668111980499
    24

    50
    Pamela
    F8583251-6DE0-A1FA-2187-70597B4CD404
    1628121968099
    9

    51
    Fletcher
    57313BC1-BCCD-137E-33FF-BB067DB56638
    1692112615899
    8

    52
    Carla
    CE56A0A8-FD27-F461-5E51-EE5AB573DBD5
    1661032917899
    73

    53
    Basia
    9BD2CDC6-6B0A-C9D4-DE6E-A4BA28CD6427
    1687041589899
    59

    54
    Lesley
    CE21D00A-00F6-418C-C9E8-5B09CAD64B18
    1639050475699
    16

    55
    Jade
    132AE1C1-16E7-63AC-3D8A-B8C23E97813A
    1651082175399
    38

    56
    Autumn
    E2FA0C3E-B6F3-D40E-5FA6-0CA459C96278
    1690041526599
    84

    57
    Joan
    B6315225-A567-2DE6-F931-26FF2161D999
    1682022818699
    96

    58
    Marcia
    4CDB28E7-A449-27C3-3A78-4CDCF905AD07
    1641040720799
    88

    59
    Regan
    6D93AF43-13C8-0379-04C5-1C56A8930A5B
    1663052343799
    46

    60
    Christian
    818482C2-9912-BD5B-399B-BEEFE3DCE8D3
    1677020840699
    69

    61
    Wing
    7746878F-2BE8-7CFA-AD7D-4E9B0D77661F
    1670121897699
    65

    62
    Merritt
    79FE8FF1-42C4-3FA0-E3BC-51170948FC69
    1672010917299
    44

    63
    Kay
    D44BA900-07A0-24E8-9000-0D1FF173E5B7
    1677072899899
    53

    64
    Alfreda
    501006BC-AFE4-046C-20CA-41B4452A2F99
    1676022339299
    67

    65
    Barrett
    647ED1CB-7B40-81B9-05E3-19A0EEF00840
    1695071106999
    48

    66
    Edward
    CE31C4D2-391F-8CED-802D-36DD986A516D
    1668100834399
    3

    67
    Rudyard
    6CF06D57-3019-7B1D-3EA0-2DD297322D18
    1650072406099
    17

    68
    Rana
    487B8EF0-D757-353E-88BD-6AEB7E2A6892
    1649061924599
    71

    69
    Yuli
    040854F3-5D96-A14C-2D5B-F38E58752356
    1665022089299
    77

    70
    Debra
    E31EFCD4-CFC6-271B-5E94-764D0A317680
    1682021613899
    28

    71
    Eaton
    0B20B2EA-301E-24C6-B901-80CA984BDAC5
    1692123002399
    66

    72
    Acton
    F87766EE-273D-E8BC-88EB-4DB0ED6D07F1
    1688081955899
    41

    73
    Wallace
    02A2797C-E2E7-6E8B-2F54-14422B96EAC3
    1682010642899
    5

    74
    Valentine
    7EFC2906-5549-C5FB-EA40-75AC790531A1
    1642091417399
    11

    75
    Zane
    C10D8142-36D7-D358-513C-34079B93EED4
    1638121063899
    8

    76
    Addison
    A1426ED4-7ECF-C09A-0541-482DD835D7E8
    1657040512199
    41

    77
    Hedda
    FCF42864-0F47-55E8-ADC1-2878EB905976
    1679120807899
    68

    78
    Zeus
    89D8AD53-D477-1FE9-720E-28A54D9748CB
    1615032107099
    93

    79
    Shaeleigh
    2DF52B59-F914-2D5A-F1FA-C752AF13AC29
    1621010516399
    90

    80
    Peter
    791F363D-74BB-51B8-F05F-88E9A3E8D2D5
    1685060734699
    54

    81
    Chaney
    A843E306-7D2A-90EE-35B1-C6C99C73D5B8
    1651082857899
    98

    82
    Whitney
    10380818-AB30-501E-BFF3-8647EEC2CD3A
    1620072074699
    64

    83
    Rhiannon
    FBDBE676-2BDE-59BE-A3B5-6126C278274F
    1620071659699
    12

    84
    Risa
    CE7C1D86-A526-4AB6-BEC4-BF02880DE498
    1647092989299
    20

    85
    Hoyt
    C8D5DA43-42A4-9C9C-C954-7DDD0F577899
    1652022451199
    8

    86
    Cruz
    4AB62FBA-3F65-2F88-8D9D-7DF7A5159C74
    1603091524299
    56

    87
    Riley
    61E2C7FC-6435-F765-C376-9027981F823D
    1693092567199
    66

    88
    Magee
    13708277-A251-8C42-E8BD-C0218620F6E1
    1601051836499
    40

    89
    Mia
    2843F1B7-A70E-808C-7B8A-423925548D73
    1693061729799
    26

    90
    Solomon
    30828793-2CFF-C962-0ACC-5FC62AECE5F9
    1625060887299
    36

    91
    Josephine
    C43233D9-F4E9-EF31-9D77-2A913610CEC9
    1644101032099
    40

    92
    Odysseus
    4C4DD636-1403-2B4E-FD2B-36BAC8D7E450
    1626051308899
    28

    93
    Dana
    1FC26C48-5E15-1960-6041-7077670A9199
    1695061049499
    2

    94
    Eugenia
    B11F52CF-4168-C9BC-C5A0-E5F5DBA252B2
    1680102398699
    91

    95
    Brett
    4C51F8FC-1B90-B1B1-7A79-B34576FE6593
    1635110576499
    26

    96
    Quentin
    3B06D55B-2ACC-3926-42A8-80BD159C7062
    1628102018799
    53

    97
    Mira
    AF1BF61F-DA2D-7332-CCFF-D180420D5017
    1611031933599
    51

    98
    Adena
    FB963253-D1D3-F1F5-94B0-8E7598D9F03E
    1617051389799
    97

    99
    Nerea
    09320800-762C-3901-685D-B4DE1D9857CE
    1681032376299
    88

    100
    Vance
    DF056662-B997-9F8F-A3DB-3283C15B38E7
    1648120830099
    2

This is the GIST of the Table

https://trycf.com/gist/26f59ea4fb3cae57cd76ad31c2f604da/lucee5?theme=monokai

my query is generating data like above

so within the query itself i want to remove those 3 rows which have a minus value, the same skid has one minus value, it will remove all its records

and add the above date condition i have to the query

how can i do all this in one sql condition, something using declare, i am not sure


问:
Problems Installing PostgreSQL 9.2
I've been trying to install the 64bit version of PostgreSQL 9.2 for Windows on my machine (Windows 7 64bit) and get this error:

The environment variable COMPSPEC does not seem to point to the cmd.exe or there is a trailing semi colon present.

I've installed it as Administrator.

I disabled the antivirus (Microsoft Security Essentials) and the firewall.

Running:

```<code>"%COMSPEC%" /C "echo test ok"
</code>```

returned test ok

I've checked my System Environment Variables for trailing semi colon and I couldn't find any.

I then installed the 32bit version and managed to get to the end of the install with a different error message stating: Problem running post-install step. Installation may not complete correctly Error reading the C:\Program Files (x86)\PostgreSQL\9.2\data\postgresql.conf but there is no postgresql.conf file in that directory. It did install the application and when I try to connect the server with the red X on it it says fail at the bottom and it won't connect after I type in my password.

How can I connect to this server connection?

答: If the installer exe is on a network share that mapped drive might actually not be accessible to the installer as it runs as administrator. This can often happen in some virtual machine arrangements such as running windows in a parallels VM. Copy the installer to a local drive first and you won't have a problem. </p>

Title: Problems Installing PostgreSQL 9.2

Body:
I've been trying to install the 64bit version of PostgreSQL 9.2 for Windows on my machine (Windows 7 64bit) and get this error:

The environment variable COMPSPEC does not seem to point to the cmd.exe or there is a trailing semi colon present.

I've installed it as Administrator.

I disabled the antivirus (Microsoft Security Essentials) and the firewall.

Running:

"%COMSPEC%" /C "echo test ok"

returned test ok

I've checked my System Environment Variables for trailing semi colon and I couldn't find any.

I then installed the 32bit version and managed to get to the end of the install with a different error message stating: Problem running post-install step. Installation may not complete correctly Error reading the C:\Program Files (x86)\PostgreSQL\9.2\data\postgresql.conf but there is no postgresql.conf file in that directory. It did install the application and when I try to connect the server with the red X on it it says fail at the bottom and it won't connect after I type in my password.

How can I connect to this server connection?


问:
JQuery select a variable by passing a text string of its name
I'd like to use a JQuery selector to return a variable by passing a text string of the variable name:

ex.

```<code>var test = "xxx";
</code>```

I'm thinking I could do something like this, but it won't work:

```<code>  alert($("#test"));
</code>```

Edit:  People are getting confused.  Think of it as a reflective way to get the contents of var test.  Preferrably with a JQuery selector, but I'll take any way one can come up with it..

答:
Maybe what you need is </p>

```<code>alert($("#" + test));
</code>```

Body:
I'd like to use a JQuery selector to return a variable by passing a text string of the variable name:

ex.

var test = "xxx";

I'm thinking I could do something like this, but it won't work:

  alert($("#test"));

Edit:  People are getting confused.  Think of it as a reflective way to get the contents of var test.  Preferrably with a JQuery selector, but I'll take any way one can come up with it..

Body:
Maybe what you need is

alert($("#" + test));


答:
Here is a simple loop you could use (looping through df.values gives us rows as arrays):

```<code>output = []

for ar in df.values:
    nonzeros = ar[ar > 0]
    # If nonzeros is not empty proceed and extend the output
    if nonzeros.size:
      output.extend(nonzeros)
    # If not add 0
    else:
      output.append(0)

print(output)
</code>```

returns:

```<code>[1, 2, 1, 0]
</code>```

Title: Check if positive value exist in dataframe

Body:
Here is a simple loop you could use (looping through df.values gives us rows as arrays):

output = []

for ar in df.values:
    nonzeros = ar[ar > 0]
    # If nonzeros is not empty proceed and extend the output
    if nonzeros.size:
      output.extend(nonzeros)
    # If not add 0
    else:
      output.append(0)

print(output)

returns:

[1, 2, 1, 0]


问:
Get the computed style and omit defaults
I'm trying to get the current runtime style of an element and filter out properties that have default values. For example, with markup like this:

```<code><style>
    .foo { background: red }
    span { font-size:30px }
</style>

<div style="color: blue">
    <span id="bar" class="foo">hello</span>
</div>
</code>```

I'd like the result to be:

```<code> background-color: red;
 color: blue;
 font-size: 30px;
</code>```

I tried window.getComputedStyle, but it returns a lot of stuff and I'm unsure how to filter out defaults. Any pointers will be appreciated.

答:
I have built what I believe to be a more modern, complete and efficient solution, based on mattsven's answer.

All you have to do is call the getUserStyles method with the node as a parameter, as such: Styles.getUserStyles(document.querySelector('#bar'))

Obviously, this snippet was not made with older browser support in mind, so some adjustments should be made if you are to use this on a public website.

class Styles {
    // Returns a dummy iframe with no styles or content
    // This allows us to get default styles from the browser for an element
    static getStylesIframe() {
        if (typeof window.blankIframe != 'undefined') {
            return window.blankIframe;
        }

        window.blankIframe = document.createElement('iframe');
        document.body.appendChild(window.blankIframe);

        return window.blankIframe;
    }

    // Turns a CSSStyleDeclaration into a regular object, as all values become "" after a node is removed
    static getStylesObject(node, parentWindow) {
        const styles = parentWindow.getComputedStyle(node);
        let stylesObject = {};

        for (let i = 0; i < styles.length; i++) {
            const property = styles[i];
            stylesObject[property] = styles[property];
        }

        return stylesObject;
    }

    // Returns a styles object with the browser's default styles for the provided node
    static getDefaultStyles(node) {
        const iframe = Styles.getStylesIframe();
        const iframeDocument = iframe.contentDocument;
        const targetElement = iframeDocument.createElement(node.tagName);

        iframeDocument.body.appendChild(targetElement);
        const defaultStyles = Styles.getStylesObject(targetElement, iframe.contentWindow);

        targetElement.remove();

        return defaultStyles;
    }

    // Returns a styles object with only the styles applied by the user's CSS that differ from the browser's default styles
    static getUserStyles(node) {
        const defaultStyles = Styles.getDefaultStyles(node);
        const styles = Styles.getStylesObject(node, window);
        let userStyles = {};

        for (let property in defaultStyles) {
            if (styles[property] != defaultStyles[property]) {
                userStyles[property] = styles[property];
            }
        }

        return userStyles;
    }
};
```

Body:
I'm trying to get the current runtime style of an element and filter out properties that have default values. For example, with markup like this:

    hello

I'd like the result to be:

 background-color: red;
 color: blue;
 font-size: 30px;

I tried window.getComputedStyle, but it returns a lot of stuff and I'm unsure how to filter out defaults. Any pointers will be appreciated.


问:
Fgets-How to prevent user from exceeding Maxsize?
I use fgets to get a name from the user and i put it in a char array.
If the user gives let's say beyond maxsize in fgets, then my program has a problem. I thought that if the user exceeds maxsize, NULL is returned. But that's not the case. How can i control this error?

Of course i can set maxsize at 200 and even more. But i think that's not a very good solution.

i have used fgets inside an if statement and if it's ==NULL, i print an error, but as i already told that won't work if the user exceeds maxsize.

```<code> fgets(name, 20, stdin);
</code>```

答:
Of course i can set maxsize at 200 and even more. But i think that's not a very good solution.

This approach is not so bad.

Creating some my_gets() that allows huge lines gives unlimited memory resource control over to user input - potential hacker exploit.  An huge line is more likely errant input or a nefarious code hack.

I'd go with @Constantine Georgiou and use a large, but sane upper limit.  Then detect such large lines as errant/hostile.

Note that text file lines have an environmental limit.  So proving huge buffers can be moot.

An implementation shall support text files with lines containing at least 254 characters, including the terminating new-line character. The value of the macro BUFSIZ shall be at least 256. C11 §7.21.2 7

```<code>#define MY_BUFSIZE ((BUFSIZE < 4096) ? BUFSIZE : 4096)

char name[MY_BUFSIZE + 2];
if (fgets(name, sizeof name, stdin)) {
  if (strlen(name) >= MY_BUFSIZE) Too_long_error();
</code>```

Note: Input unusually reads in a null character rendering     fgets() problematic.

Body:
I use fgets to get a name from the user and i put it in a char array.
If the user gives let's say beyond maxsize in fgets, then my program has a problem. I thought that if the user exceeds maxsize, NULL is returned. But that's not the case. How can i control this error?

Of course i can set maxsize at 200 and even more. But i think that's not a very good solution.

i have used fgets inside an if statement and if it's ==NULL, i print an error, but as i already told that won't work if the user exceeds maxsize.

 fgets(name, 20, stdin);

Body:
Of course i can set maxsize at 200 and even more. But i think that's not a very good solution.

This approach is not so bad.

Creating some my_gets() that allows huge lines gives unlimited memory resource control over to user input - potential hacker exploit.  An huge line is more likely errant input or a nefarious code hack.

I'd go with @Constantine Georgiou and use a large, but sane upper limit.  Then detect such large lines as errant/hostile.

Note that text file lines have an environmental limit.  So proving huge buffers can be moot.

An implementation shall support text files with lines containing at least 254 characters, including the terminating new-line character. The value of the macro BUFSIZ shall be at least 256. C11 §7.21.2 7

#define MY_BUFSIZE ((BUFSIZE < 4096) ? BUFSIZE : 4096)

char name[MY_BUFSIZE + 2];
if (fgets(name, sizeof name, stdin)) {
  if (strlen(name) >= MY_BUFSIZE) Too_long_error();

Note: Input unusually reads in a null character rendering     fgets() problematic.


问:
Add index to child elements within XML file Python
I´m a novice in python, so please help. I´d like to add an index to row and column elements in same way like page elements have index.

Within page 1 there are 4 rows, so the index would go from 0 to 3. Within page 1, row 0 there is only one column, so index would be only 0.
In page 1, row 2 there  are 3 columns, so index for columns would go from 0 to 2. The same for the other rows in other pages.

I've been beginning testing with Elementree but only the basics to print elements. Maybe someone could help me with this.

I have the following code for basic testings only but I don´t know how to proceed with this.

```<code>import xml.etree.ElementTree as ET
tree = ET.parse('smp.xml')
root = tree.getroot()

for text in root.iter('text'):
    print(text.attrib)

for text in root.iter('text'):
    print(text.text)
</code>```

The input XML is like this:

```<code><?xml version="1.0"?>
<doc>
    <page index="0"/>
    <page index="1">
        <row>
            <column>
                <text>fibrous drupe</text>
            </column>
        </row>
        <row>
            <column>
                <text>follicle</text>
            </column>
            <column>
                <text>legume</text>
            </column>
        </row>
        <row>
            <column>
                <text>loment</text>
            </column>
            <column>
                <text>nut</text>
            </column>
            <column>
                <text>samara</text>
            </column>
        </row>
        <row>
            <column>
                <text>schizocarp</text>
            </column>
        </row>
    </page>
    <page index="2">
        <row>
            <column>
                <text>cypsela</text>
            </column>
        </row>
    </page>
    <page index="3"/>
</doc>
</code>```

and I would like to convert it to this:

```<code><?xml version="1.0"?>
<doc>
    <page index="0"/>
    <page index="1">
        <row index="0">
            <column index="0">
                <text>fibrous drupe</text>
            </column>
        </row>
        <row index="1">
            <column index="0">
                <text>follicle</text>
            </column>
            <column index="1">
                <text>legume</text>
            </column>
        </row>
        <row index="2">
            <column index="0">
                <text>loment</text>
            </column>
            <column index="1">
                <text>nut</text>
            </column>
            <column index="2">
                <text>samara</text>
            </column>
        </row>
        <row index="3">
            <column index="0">
                <text>schizocarp</text>
            </column>
        </row>
    </page>
    <page index="2">
        <row index="0">
            <column index="0">
                <text>cypsela</text>
            </column>
        </row>
    </page>
    <page index="3"/>
</doc>
</code>```

I hope make sense. Thanks in advance.

答:
I'm new to python meself, so you have to finish this yourself:

```<code>import xml.etree.ElementTree as ET
tree = ET.parse('smp.xml')
root = tree.getroot()

for text in root:
    print(text.tag, text.attrib)
    for text2 in text:
        print(" ", text2.tag, text2.attrib)
        if (text2.tag=='row'):
           text2.set('index','42')

tree.write('output.xml')
</code>```

In 'output.xml' you will get:

```<code><doc>
    <page index="0" />
    <page index="1">
        <row index="42">
            <column>
                <text>fibrous drupe</text>
            </column>
        </row>
        <row index="42">
            <column>
                <text>follicle</text>
            </column>
            <column>
                <text>legume</text>
            </column>
        </row>
        <row index="42">
            <column>
               ….
</code>```

So, you need to change those '42' to the value you need them to be.

Body:
I´m a novice in python, so please help. I´d like to add an index to row and column elements in same way like page elements have index.

Within page 1 there are 4 rows, so the index would go from 0 to 3. Within page 1, row 0 there is only one column, so index would be only 0.
In page 1, row 2 there  are 3 columns, so index for columns would go from 0 to 2. The same for the other rows in other pages.

I've been beginning testing with Elementree but only the basics to print elements. Maybe someone could help me with this.

I have the following code for basic testings only but I don´t know how to proceed with this.

import xml.etree.ElementTree as ET
tree = ET.parse('smp.xml')
root = tree.getroot()

for text in root.iter('text'):
    print(text.attrib)

for text in root.iter('text'):
    print(text.text)

The input XML is like this:

<?xml version="1.0"?>
<doc>
    <page index="0"/>
    <page index="1">
        <row>
            <column>
                <text>fibrous drupe</text>
            </column>
        </row>
        <row>
            <column>
                <text>follicle</text>
            </column>
            <column>
                <text>legume</text>
            </column>
        </row>
        <row>
            <column>
                <text>loment</text>
            </column>
            <column>
                <text>nut</text>
            </column>
            <column>
                <text>samara</text>
            </column>
        </row>
        <row>
            <column>
                <text>schizocarp</text>
            </column>
        </row>
    </page>
    <page index="2">
        <row>
            <column>
                <text>cypsela</text>
            </column>
        </row>
    </page>
    <page index="3"/>
</doc>

and I would like to convert it to this:

<?xml version="1.0"?>
<doc>
    <page index="0"/>
    <page index="1">
        <row index="0">
            <column index="0">
                <text>fibrous drupe</text>
            </column>
        </row>
        <row index="1">
            <column index="0">
                <text>follicle</text>
            </column>
            <column index="1">
                <text>legume</text>
            </column>
        </row>
        <row index="2">
            <column index="0">
                <text>loment</text>
            </column>
            <column index="1">
                <text>nut</text>
            </column>
            <column index="2">
                <text>samara</text>
            </column>
        </row>
        <row index="3">
            <column index="0">
                <text>schizocarp</text>
            </column>
        </row>
    </page>
    <page index="2">
        <row index="0">
            <column index="0">
                <text>cypsela</text>
            </column>
        </row>
    </page>
    <page index="3"/>
</doc>

I hope make sense. Thanks in advance.

Body:
I'm new to python meself, so you have to finish this yourself:

import xml.etree.ElementTree as ET
tree = ET.parse('smp.xml')
root = tree.getroot()

for text in root:
    print(text.tag, text.attrib)
    for text2 in text:
        print(" ", text2.tag, text2.attrib)
        if (text2.tag=='row'):
           text2.set('index','42')

tree.write('output.xml')

In 'output.xml' you will get:

<doc>
    <page index="0" />
    <page index="1">
        <row index="42">
            <column>
                <text>fibrous drupe</text>
            </column>
        </row>
        <row index="42">
            <column>
                <text>follicle</text>
            </column>
            <column>
                <text>legume</text>
            </column>
        </row>
        <row index="42">
            <column>
               ….

So, you need to change those '42' to the value you need them to be.


问:
Implementation of Shortest Path Graph in Python Class

Hi! I am new to Python and I am struggling for many hours so far with some problem regarding Shortest Path Algorithm implementation in Python.

I am expected to solve some task about finding shortest paths (graph problem) among given persons, and at the end find a common person who connects all of them.

I've made something like this so far:

```<code>import itertools

class centralperson():

def initialization(self,N,data,a,b,c):
    self.data = data
    self.N = N
    self.a = a
    self.b = b
    self.c = c
    self.list_of_values = [self.a,self.b,self.c]
    self.list_of_paths = []
    self.common_person = []

def makeGraph(self):

    # Create dict with empty list for each key
    graph = {key: [] for key in range(self.N)}
    self.graph = graph

    for key in self.graph:
        for x in self.data:
            if key in x:

                x = x.copy()
                x.remove(key)
                self.graph[key].extend(x)

def find_path(self,start, end):
    path = []
    path = path + [start]
    if start == end:
        return path
    if start not in self.graph.keys():
        raise ValueError('No such key in graph!')
    for node in self.graph[start]:
        if node not in path:
            newpath = self.find_path(self.graph, node, end, path)
            if newpath: return newpath
    return self.list_of_paths.append(path)

def findPaths(self):

    for pair in itertools.combinations(self.list_of_values, r=5):
        self.find_path(*pair)

def commonperson(self):

    list_of_lens = {}
    commonalities = set(self.list_of_paths[0]) & set(self.list_of_paths[1]) & set(self.list_of_paths[2])
    for i in self.list_of_values:
        list_of_lens[i] = (len(self.graph[i]))

    if len(commonalities)>1 or len(commonalities)<1:
        for k,v in list_of_lens.items():
            if v==1 and self.graph[k][0] in commonalities:
                output = self.graph[k]
                self.common_person.append(output)
    else:
        output = list(commonalities)
        self.common_person.append(output)
    return

def printo(self):

    #return(self.common_person[0])
    return(self.list_of_paths,self.list_of_values)
</code>```

Description of each function and inputs:

N -> number of unique nodes

a,b,c -> some arbitrarily chosen nodes to find common one among them

initialization -> just initialize our global variables used in other methods, and store the list of outputs

makeGraph -> makes an Adjacency List out of an input.

find_path -> find path between two given nodes (backtracking recursion)

findPaths -> it was expected to call find_path here for every combination of A,B,C i.e A->B, A->C, B->C

commonperson -> expected to find common person from the output of list_of_paths list

printo -> print this common person

Generally It works (I'think) when I'am running each function separately. But, when I try to make a huge class of it, it doesn't work :(

I think the problem is with this recursive function find_path. It is supposed to find a path between two person given, and append the result path to the list with all paths. Yet, as I have 3 different persons, and find_path is a recursive function with only 2 parameters.

Hence, I need to find all paths that connects them (3 paths) and append it to a bigger list list_of_paths. I've created a def findPaths to make use of itertools.combinations and in for loop cal function find_path for every combination of start and end argument of this function, but it seems not to work...

Can you help me with this? Also I don't know how to run all the def functions at once, because honestly I wouldn't like to run all instances of the class separately... My desired version is to:

Provide Input to a class i.e : N,data,a,b,c where N is number of unique nodes, data is just list of list with networks assigned, and A,B,C are my persons.

Get Output: which is a common person for all this 3 persons, (I planned to store it in common_person list.

答:
The code inside you class should be indented, i.e.:

class centralperson:
    def __init__(self, ...):
        ...

    def makeGraph(self, ...):
        ...
```

<p>instead of </p>

<pre class="lang-py prettyprint-override"><code>class centralperson:
def __init__(self, ...):
    ...

def makeGraph(self, ...):
    ...
</code>```

Try googling for 'python class examples'. I hope this helps!

It might also be useful to experiment with simpler classes before working on this problem.

Body:
Hi! I am new to Python and I am struggling for many hours so far with some problem regarding Shortest Path Algorithm implementation in Python.

I am expected to solve some task about finding shortest paths (graph problem) among given persons, and at the end find a common person who connects all of them.

I've made something like this so far:

import itertools

class centralperson():

def initialization(self,N,data,a,b,c):
    self.data = data
    self.N = N
    self.a = a
    self.b = b
    self.c = c
    self.list_of_values = [self.a,self.b,self.c]
    self.list_of_paths = []
    self.common_person = []

def makeGraph(self):

    # Create dict with empty list for each key
    graph = {key: [] for key in range(self.N)}
    self.graph = graph

    for key in self.graph:
        for x in self.data:
            if key in x:

                x = x.copy()
                x.remove(key)
                self.graph[key].extend(x)

def find_path(self,start, end):
    path = []
    path = path + [start]
    if start == end:
        return path
    if start not in self.graph.keys():
        raise ValueError('No such key in graph!')
    for node in self.graph[start]:
        if node not in path:
            newpath = self.find_path(self.graph, node, end, path)
            if newpath: return newpath
    return self.list_of_paths.append(path)

def findPaths(self):

    for pair in itertools.combinations(self.list_of_values, r=5):
        self.find_path(*pair)

def commonperson(self):

    list_of_lens = {}
    commonalities = set(self.list_of_paths[0]) & set(self.list_of_paths[1]) & set(self.list_of_paths[2])
    for i in self.list_of_values:
        list_of_lens[i] = (len(self.graph[i]))

    if len(commonalities)>1 or len(commonalities)<1:
        for k,v in list_of_lens.items():
            if v==1 and self.graph[k][0] in commonalities:
                output = self.graph[k]
                self.common_person.append(output)
    else:
        output = list(commonalities)
        self.common_person.append(output)
    return

def printo(self):

    #return(self.common_person[0])
    return(self.list_of_paths,self.list_of_values)

Description of each function and inputs:

N -> number of unique nodes

a,b,c -> some arbitrarily chosen nodes to find common one among them

initialization -> just initialize our global variables used in other methods, and store the list of outputs

makeGraph -> makes an Adjacency List out of an input.

find_path -> find path between two given nodes (backtracking recursion)

findPaths -> it was expected to call find_path here for every combination of A,B,C i.e A->B, A->C, B->C

commonperson -> expected to find common person from the output of list_of_paths list

printo -> print this common person

Generally It works (I'think) when I'am running each function separately. But, when I try to make a huge class of it, it doesn't work :(

I think the problem is with this recursive function find_path. It is supposed to find a path between two person given, and append the result path to the list with all paths. Yet, as I have 3 different persons, and find_path is a recursive function with only 2 parameters.

Hence, I need to find all paths that connects them (3 paths) and append it to a bigger list list_of_paths. I've created a def findPaths to make use of itertools.combinations and in for loop cal function find_path for every combination of start and end argument of this function, but it seems not to work...

Can you help me with this? Also I don't know how to run all the def functions at once, because honestly I wouldn't like to run all instances of the class separately... My desired version is to:

Provide Input to a class i.e : N,data,a,b,c where N is number of unique nodes, data is just list of list with networks assigned, and A,B,C are my persons.

Get Output: which is a common person for all this 3 persons, (I planned to store it in common_person list.

Body:
The code inside you class should be indented, i.e.:

class centralperson:
    def __init__(self, ...):
        ...

    def makeGraph(self, ...):
        ...

instead of

class centralperson:
def __init__(self, ...):
    ...

def makeGraph(self, ...):
    ...

Try googling for 'python class examples'. I hope this helps!

It might also be useful to experiment with simpler classes before working on this problem.


问:
How do I add elements of a set and print their sum?
how do i add elements of the set and print their sum

i have done it by converting the set into list is their any other way without converting the set into a list

```<code>a1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
x = 0
sum = 0
while x != 10:
    z = list(a1)[x]
    sum += z
    x += 1
    print(sum)

a1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
x = 0
sum = 0
while x != 10:
    z = a1[x]
    sum += z
    x += 1
    print(sum)
</code>```

Traceback (most recent call last):   File
  "C:/Users/Usman/AppData/Local/Programs/Python/Python37/ddd.py", line
  5, in
      z=(a1[x]) TypeError: 'set' object is not subscriptable

I expect the result to be 55

答:
You can use the sum function.

```<code>a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print(sum(a))
</code>```

Body:
how do i add elements of the set and print their sum

i have done it by converting the set into list is their any other way without converting the set into a list

a1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
x = 0
sum = 0
while x != 10:
    z = list(a1)[x]
    sum += z
    x += 1
    print(sum)

a1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
x = 0
sum = 0
while x != 10:
    z = a1[x]
    sum += z
    x += 1
    print(sum)

Traceback (most recent call last):   File
  "C:/Users/Usman/AppData/Local/Programs/Python/Python37/ddd.py", line
  5, in
      z=(a1[x]) TypeError: 'set' object is not subscriptable

I expect the result to be 55

Body:
You can use the sum function.

a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print(sum(a))


问:
Using expression returning methods in EF
I have an expression returning method such as:

```<code>    public Expression<Func<User, bool>> GetUserPredicate(int userID)
    {
        return u => u.ID == userID;
    }
</code>```

(In the original code, this is a longer and more complex piece of logic that I want to reuse so that I extrcted it out into such a method.)

I can use it in queries for Users without a problem:

```<code>    var user = dbContext.Users
        .Where(GetUserPredicate(1))
        .Single();
</code>```

But I also want to use it when querying other entities like Posts:

```<code>    var post = dbContext.Posts
        .Where(p => p.ID == 1)
        .Where(p.User => GetUserPredicate(1))
        .Single();
</code>```

But this does not work. How can it be accomplished?

答:
Edit:

My solution uses the compiled function of the expression. Since EF only looks at the expression tree and translates it to Sql, it cannot process compiled functions because these are not expression trees (see comment by Filip Corades below).

If you are using my code for other things that can work with compiled functions, you shouldn't have any issues. For this question however it isn't the right answer.

Original answer:

You can add another method which uses the first one.

```<code>public Expression<Func<Post, bool>> GetPostUserPredicate(int userID)
{
    Expression<Func<User, bool>> expr = GetUserPredicate(userID);
    Func<User, bool> func = expr.Compile();
    return post => func(post.User);
}
</code>```

What this does is it compiles the function of the user-expression and uses it to make the expression fit for the post. You can call it like this (adjusted to your code):

```<code>var post = dbContext.Posts
        .Where(p => p.ID == 1)
        .Where(GetPostUserPredicate(1))
        .Single();
</code>```

You could also inline this instead of using an extra function but for me this is a bit too messy. I'll add it anyway:

```<code>var post = dbContext.Posts
    .Where(p => p.ID == 1)
    .Where(p => GetUserPredicate(1).Compile()(p.User))
    .Single();
</code>```

If there isn't something I'm missing about compiling expressions, this should work absolutely fine.

Hope this helps and let me know if it worked.

Body:
I have an expression returning method such as:

    public Expression<Func<User, bool>> GetUserPredicate(int userID)
    {
        return u => u.ID == userID;
    }

(In the original code, this is a longer and more complex piece of logic that I want to reuse so that I extrcted it out into such a method.)

I can use it in queries for Users without a problem:

    var user = dbContext.Users
        .Where(GetUserPredicate(1))
        .Single();

But I also want to use it when querying other entities like Posts:

    var post = dbContext.Posts
        .Where(p => p.ID == 1)
        .Where(p.User => GetUserPredicate(1))
        .Single();

But this does not work. How can it be accomplished?

Body:
Edit:

My solution uses the compiled function of the expression. Since EF only looks at the expression tree and translates it to Sql, it cannot process compiled functions because these are not expression trees (see comment by Filip Corades below).

If you are using my code for other things that can work with compiled functions, you shouldn't have any issues. For this question however it isn't the right answer.

Original answer:

You can add another method which uses the first one.

public Expression<Func<Post, bool>> GetPostUserPredicate(int userID)
{
    Expression<Func<User, bool>> expr = GetUserPredicate(userID);
    Func<User, bool> func = expr.Compile();
    return post => func(post.User);
}

What this does is it compiles the function of the user-expression and uses it to make the expression fit for the post. You can call it like this (adjusted to your code):

var post = dbContext.Posts
        .Where(p => p.ID == 1)
        .Where(GetPostUserPredicate(1))
        .Single();

You could also inline this instead of using an extra function but for me this is a bit too messy. I'll add it anyway:

var post = dbContext.Posts
    .Where(p => p.ID == 1)
    .Where(p => GetUserPredicate(1).Compile()(p.User))
    .Single();

If there isn't something I'm missing about compiling expressions, this should work absolutely fine.

Hope this helps and let me know if it worked.


问:
I wanna repeat function infinite but i couldn't
I wanna do some effect to my background so i tought i can add some shapes flying around but i do only 1 shape i cant loop or anything

i tried call function more than a one time but it doesnt help

```<code>function animasyon(a) {
    window.onload=function(){

        var id = setInterval(anim,5);

        $('body').append('<div class=shape></div>');
        $('body').append('<div class=shape></div>');

        var kutu = document.getElementsByClassName("shape");
        var pos = 0;
        var x = window.innerWidth;
        var y = window.innerHeight;
        var borderSize = Math.floor(Math.random() * 3 ) + 1;
        var ySize = Math.floor(Math.random() * y ) + 1;
        var Size = Math.floor(Math.random() * 30 ) + 5;
        var yon = Math.floor(Math.random() *2)+1;
        var dolu = Math.floor(Math.random() *2)+1;
        if (ySize > 50) { ySize-=20; }

            function anim(){

                if (pos == x) {
                    clearInterval(id);
                    document.getElementById("shape").remove();
                }else{
                    pos++;
                    kutu[a].style.position = "absolute";
                    kutu[a].style.border = "solid rgb(119,38,53) "+borderSize+"px";
                    kutu[a].style.left = pos+"px";
                    kutu[a].style.width = Size+"px";
                    kutu[a].style.height = Size+"px";

                    if (yon == 1) { ySize-=0.2; } else { ySize+=0.2; }
                    if (dolu==1) {kutu[a].style.background = "rgb(119,38,53)";}
                    if (kutu[a].offsetTop < 0 || kutu[a].offsetTop > y-30) {document.getElementById("shape").remove();}

                    kutu[a].style.top = ySize+"px";
                }
             }
    }

}

animasyon(0);
</code>```

答:
Try Calling 'anim' function in this way

```<code>setInterval(function(){anim()},5);
</code>```

Body:
I wanna do some effect to my background so i tought i can add some shapes flying around but i do only 1 shape i cant loop or anything

i tried call function more than a one time but it doesnt help

function animasyon(a) {
    window.onload=function(){

        var id = setInterval(anim,5);

        $('body').append('

');
        $('body').append('

');

        var kutu = document.getElementsByClassName("shape");
        var pos = 0;
        var x = window.innerWidth;
        var y = window.innerHeight;
        var borderSize = Math.floor(Math.random() * 3 ) + 1;
        var ySize = Math.floor(Math.random() * y ) + 1;
        var Size = Math.floor(Math.random() * 30 ) + 5;
        var yon = Math.floor(Math.random() *2)+1;
        var dolu = Math.floor(Math.random() *2)+1;
        if (ySize > 50) { ySize-=20; }

            function anim(){

                if (pos == x) {
                    clearInterval(id);
                    document.getElementById("shape").remove();
                }else{
                    pos++;
                    kutu[a].style.position = "absolute";
                    kutu[a].style.border = "solid rgb(119,38,53) "+borderSize+"px";
                    kutu[a].style.left = pos+"px";
                    kutu[a].style.width = Size+"px";
                    kutu[a].style.height = Size+"px";

                    if (yon == 1) { ySize-=0.2; } else { ySize+=0.2; }
                    if (dolu==1) {kutu[a].style.background = "rgb(119,38,53)";}
                    if (kutu[a].offsetTop < 0 || kutu[a].offsetTop > y-30) {document.getElementById("shape").remove();}

                    kutu[a].style.top = ySize+"px";
                }
             }
    }

}

animasyon(0);

Body:
Try Calling 'anim' function in this way

setInterval(function(){anim()},5);


问:
Image manipulation, theory, formulas and pseudo code
I'd like to know where read materials to learn how to manipulate image via code.
I just created a simple software to read any pixels from an image and i'm able to apply some simple code to modify it, for example i can create a gray scale image using this (pseudo)code:

```<code>foreach(pixel in image){
 red = pixel.r;
 green = pixel.g;
 blue = pixel.b;
 alpha = pixel.a;

 gray = (red + green + blue) / 3;

 pixel.r = gray;
 pixel.g = gray;
 pixel.b = gray;
}
</code>```

Do you know websites (or a books) where i can find any informations about image manipulation applied to software development ?

答: HIPR Image Processing Learning Resources</p>

Body:
I'd like to know where read materials to learn how to manipulate image via code.
I just created a simple software to read any pixels from an image and i'm able to apply some simple code to modify it, for example i can create a gray scale image using this (pseudo)code:

foreach(pixel in image){
 red = pixel.r;
 green = pixel.g;
 blue = pixel.b;
 alpha = pixel.a;

 gray = (red + green + blue) / 3;

 pixel.r = gray;
 pixel.g = gray;
 pixel.b = gray;
}

Do you know websites (or a books) where i can find any informations about image manipulation applied to software development ?


问:
NavLink interactions with boostrap classes
I am having trouble setting up my routing using 'react-router-dom'. The problem is if I use the NavLink class, the a tag is lost and bootstrap wont display the css behavior.

What i'd like to happen is figure out a way to get the classes working like a normal a tag. Even if I have the btn btn-outline-primary, having the NavLink will interfere with the css properties.

***edit: I found the problem. If I set all routes for testing purpose to="/", every link is going to be active. So, afterall, Bootstrap is working perfectly, just have to make sure to test it once all routes are set.

```<code><li className="nav-item">
  <NavLink to='/' className="btn btn-light mr-1" href="#">
    <i class="fas fa-user"></i> Perfíl
  </NavLink>
</li>
</code>```

答: try nesting the li in the Navlinks and also pass the bootstrap classes to the li and not the Navlink route. remove the href </p>

Body:
I am having trouble setting up my routing using 'react-router-dom'. The problem is if I use the NavLink class, the a tag is lost and bootstrap wont display the css behavior.

What i'd like to happen is figure out a way to get the classes working like a normal a tag. Even if I have the btn btn-outline-primary, having the NavLink will interfere with the css properties.

***edit: I found the problem. If I set all routes for testing purpose to="/", every link is going to be active. So, afterall, Bootstrap is working perfectly, just have to make sure to test it once all routes are set.

  <NavLink to='/' className="btn btn-light mr-1" href="#">
     Perfíl
  </NavLink>


答:
```<code>>>> a = set(range(1, 10+1)) # a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
>>> sum(a)
55
>>>
</code>```

set iterables are unordered, and therefore have no index. That explains the TypeError you are getting.

Title: How do I add elements of a set and print their sum?

Body:
>>> a = set(range(1, 10+1)) # a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
>>> sum(a)
55
>>>

set iterables are unordered, and therefore have no index. That explains the TypeError you are getting.


问:
Read from a file to a linked list C
I'm trying to read a txt file, and then save it to a linked list in C. I have tried a lot but I haven't found a solution.

This is what I have:

```<code>typedef struct contact{

    char name[50];
    char number[10];
    char bithday[15];
    struct contact *next;
}contact;

struct contact *head;
FILE *fp;
</code>```

This part saves the contacts that I've already have to a txt file.

```<code>void backup(){

    struct contact *ap;

    fp=fopen("save_contacts.txt", "w");

    if(fp==NULL){
        printf(" Error\n");
        system("pause");
        return 1;
    }
    for (ap=head;ap!=NULL;ap=ap->next){
        fprintf(fp,"%s ",ap->name);
        //fprintf(fp,", ");
        fprintf(fp,"%s ",ap->number);
        //fprintf(fp,", ");
        fprintf(fp,"%s ",ap->birthday);
        //fprintf(fp,", ");
        fprintf(fp,"; ");
    }
    fprintf(fp, "End");
}
</code>```

So my problem is with this part, it doesn't read the txt file.

```<code>void read() {
    struct contact *ap;
    int i;
    head=NULL;
    char aux[30];

    FILE *fp=fopen("save_contacts.txt","r");

    do{

        head=NULL;
        ap=(contact*)malloc(sizeof(contact));

        fscanf(fp,"%s ",&ap->name);
        fscanf(fp,"%s ",&ap->number);
        fscanf(fp,"%s ",&ap->birthday);
        fscanf(fp,"%s ",aux);

        if(strcmp(aux,";")==0){
            ap=ap->next;
        }
    }while(strcmp(aux,"End")!=0);

}
</code>```

答:
Doing

```<code>   ap=(contact*)malloc(sizeof(contact));

   fscanf(fp,"%s ",&ap->name);
   fscanf(fp,"%s ",&ap->number);
   fscanf(fp,"%s ",&ap->birthday);
   fscanf(fp,"%s ",aux);

   if(strcmp(aux,";")==0){
       ap=ap->next;
</code>```

ap->next is not set so the second turn ap has an undefined value so the behavior is undefined when you dereference it

Note your way to save with :

```<code> for (ap=head;ap!=NULL;ap=ap->next){
   ...
   fprintf(fp,"; ");
 }
 fprintf(fp, "End");
</code>```

is not compatible with your way to read where ';' is replaced by 'End' for the last element

You can do that (I suppose there is no ';' for the last element) :

```<code>int read() {
  FILE *fp=fopen("save_contacts.txt","r");

  if (fp == NULL) {
    fprintf(stderr, "cannot open 'save_contacts.txt'\n");
    head = NULL;
    return 0;
  }

  contact ** pp = &head;
  char aux[30];
  int result;

  for (;;) {
    *pp = malloc(sizeof(contact));

    if (fscanf(fp,"%49s %9s %14s %29s", (*pp)->name, (*pp)->number, (*pp)->birthday, aux) != 4) {
      fputs("invalid file, cannot read the 3 fields then ;/End\n", stderr);
      result = 0;
      free(*pp);
      break;
    }
    pp = &(*pp)->next;
    if (strcmp(aux,"End") == 0) {
      result = 1;
      break;
    }
    if (strcmp(aux, ";") != 0) {
      fputs("invalid file, expected ; or End\n", stderr);
      result = 0;
      break;
    }
  }

  *pp = NULL;
  fclose(fp);

  return result;
}
</code>```

returning 0 in case of a problem, else 1

Note I protect the read of the string to not write out of them and I check if the file is correct

For instance having the full program

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct contact{
  char name[50];
  char number[10];
  char birthday[15]; /* not bithday */
  struct contact *next;
}contact;

struct contact *head;

int read() {
  FILE *fp=fopen("save_contacts.txt","r");

  if (fp == NULL) {
    fprintf(stderr, "cannot open 'save_contacts.txt'\n");
    head = NULL;
    return 0;
  }

  contact ** pp = &head;
  char aux[30];
  int result;

  for (;;) {
    *pp = malloc(sizeof(contact));

    if (fscanf(fp,"%49s %9s %14s %29s", (*pp)->name, (*pp)->number, (*pp)->birthday, aux) != 4) {
      fputs("invalid file, cannot read the 3 fields then ;/End\n", stderr);
      result = 0;
      free(*pp);
      break;
    }
    pp = &(*pp)->next;
    if (strcmp(aux,"End") == 0) {
      result = 1;
      break;
    }
    if (strcmp(aux, ";") != 0) {
      fputs("invalid file, expected ; or End\n", stderr);
      result = 0;
      break;
    }
  }

  *pp = NULL;
  fclose(fp);

  return result;
}

int main()
{
  if (read()) {
    /* debug */
    for (contact * p = head; p != NULL; p = p->next)
      printf("%s %s %s\n", p->name, p->number, p->birthday);
  }

  /* free resources */
  while (head != NULL) {
    contact * p = head;

    head = head->next;
    free(p);
  }

  return 0;
}
</code>```

Compilation and execution:

```<code>pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall l.c
pi@raspberrypi:/tmp $ cat save_contacts.txt
bruno 007 19/02/1960 ;
you 001 01/01/2010 ;
bar 123 31/12/1999 End
pi@raspberrypi:/tmp $ ./a.out
bruno 007 19/02/1960
you 001 01/01/2010
bar 123 31/12/1999
pi@raspberrypi:/tmp $
</code>```

Execution under valgrind :

```<code>pi@raspberrypi:/tmp $ valgrind ./a.out
==2334== Memcheck, a memory error detector
==2334== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2334== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==2334== Command: ./a.out
==2334==
bruno 007 19/02/1960
you 001 01/01/2010
bar 123 31/12/1999
==2334==
==2334== HEAP SUMMARY:
==2334==     in use at exit: 0 bytes in 0 blocks
==2334==   total heap usage: 6 allocs, 6 frees, 5,712 bytes allocated
==2334==
==2334== All heap blocks were freed -- no leaks are possible
==2334==
==2334== For counts of detected and suppressed errors, rerun with: -v
==2334== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $
</code>```

Title: Read from a file to a linked list C

Body:
I'm trying to read a txt file, and then save it to a linked list in C. I have tried a lot but I haven't found a solution.

This is what I have:

typedef struct contact{

    char name[50];
    char number[10];
    char bithday[15];
    struct contact *next;
}contact;

struct contact *head;
FILE *fp;

This part saves the contacts that I've already have to a txt file.

void backup(){

    struct contact *ap;

    fp=fopen("save_contacts.txt", "w");

    if(fp==NULL){
        printf(" Error\n");
        system("pause");
        return 1;
    }
    for (ap=head;ap!=NULL;ap=ap->next){
        fprintf(fp,"%s ",ap->name);
        //fprintf(fp,", ");
        fprintf(fp,"%s ",ap->number);
        //fprintf(fp,", ");
        fprintf(fp,"%s ",ap->birthday);
        //fprintf(fp,", ");
        fprintf(fp,"; ");
    }
    fprintf(fp, "End");
}

So my problem is with this part, it doesn't read the txt file.

void read() {
    struct contact *ap;
    int i;
    head=NULL;
    char aux[30];

    FILE *fp=fopen("save_contacts.txt","r");

    do{

        head=NULL;
        ap=(contact*)malloc(sizeof(contact));

        fscanf(fp,"%s ",&ap->name);
        fscanf(fp,"%s ",&ap->number);
        fscanf(fp,"%s ",&ap->birthday);
        fscanf(fp,"%s ",aux);

        if(strcmp(aux,";")==0){
            ap=ap->next;
        }
    }while(strcmp(aux,"End")!=0);

}

Body:
Doing

   ap=(contact*)malloc(sizeof(contact));

   fscanf(fp,"%s ",&ap->name);
   fscanf(fp,"%s ",&ap->number);
   fscanf(fp,"%s ",&ap->birthday);
   fscanf(fp,"%s ",aux);

   if(strcmp(aux,";")==0){
       ap=ap->next;

ap->next is not set so the second turn ap has an undefined value so the behavior is undefined when you dereference it

Note your way to save with :

 for (ap=head;ap!=NULL;ap=ap->next){
   ...
   fprintf(fp,"; ");
 }
 fprintf(fp, "End");

is not compatible with your way to read where ';' is replaced by 'End' for the last element

You can do that (I suppose there is no ';' for the last element) :

int read() {
  FILE *fp=fopen("save_contacts.txt","r");

  if (fp == NULL) {
    fprintf(stderr, "cannot open 'save_contacts.txt'\n");
    head = NULL;
    return 0;
  }

  contact ** pp = &head;
  char aux[30];
  int result;

  for (;;) {
    *pp = malloc(sizeof(contact));

    if (fscanf(fp,"%49s %9s %14s %29s", (*pp)->name, (*pp)->number, (*pp)->birthday, aux) != 4) {
      fputs("invalid file, cannot read the 3 fields then ;/End\n", stderr);
      result = 0;
      free(*pp);
      break;
    }
    pp = &(*pp)->next;
    if (strcmp(aux,"End") == 0) {
      result = 1;
      break;
    }
    if (strcmp(aux, ";") != 0) {
      fputs("invalid file, expected ; or End\n", stderr);
      result = 0;
      break;
    }
  }

  *pp = NULL;
  fclose(fp);

  return result;
}

returning 0 in case of a problem, else 1

Note I protect the read of the string to not write out of them and I check if the file is correct

For instance having the full program

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct contact{
  char name[50];
  char number[10];
  char birthday[15]; /* not bithday */
  struct contact *next;
}contact;

struct contact *head;

int read() {
  FILE *fp=fopen("save_contacts.txt","r");

  if (fp == NULL) {
    fprintf(stderr, "cannot open 'save_contacts.txt'\n");
    head = NULL;
    return 0;
  }

  contact ** pp = &head;
  char aux[30];
  int result;

  for (;;) {
    *pp = malloc(sizeof(contact));

    if (fscanf(fp,"%49s %9s %14s %29s", (*pp)->name, (*pp)->number, (*pp)->birthday, aux) != 4) {
      fputs("invalid file, cannot read the 3 fields then ;/End\n", stderr);
      result = 0;
      free(*pp);
      break;
    }
    pp = &(*pp)->next;
    if (strcmp(aux,"End") == 0) {
      result = 1;
      break;
    }
    if (strcmp(aux, ";") != 0) {
      fputs("invalid file, expected ; or End\n", stderr);
      result = 0;
      break;
    }
  }

  *pp = NULL;
  fclose(fp);

  return result;
}

int main()
{
  if (read()) {
    /* debug */
    for (contact * p = head; p != NULL; p = p->next)
      printf("%s %s %s\n", p->name, p->number, p->birthday);
  }

  /* free resources */
  while (head != NULL) {
    contact * p = head;

    head = head->next;
    free(p);
  }

  return 0;
}

Compilation and execution:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall l.c
pi@raspberrypi:/tmp $ cat save_contacts.txt
bruno 007 19/02/1960 ;
you 001 01/01/2010 ;
bar 123 31/12/1999 End
pi@raspberrypi:/tmp $ ./a.out
bruno 007 19/02/1960
you 001 01/01/2010
bar 123 31/12/1999
pi@raspberrypi:/tmp $

Execution under valgrind :

pi@raspberrypi:/tmp $ valgrind ./a.out
==2334== Memcheck, a memory error detector
==2334== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2334== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==2334== Command: ./a.out
==2334==
bruno 007 19/02/1960
you 001 01/01/2010
bar 123 31/12/1999
==2334==
==2334== HEAP SUMMARY:
==2334==     in use at exit: 0 bytes in 0 blocks
==2334==   total heap usage: 6 allocs, 6 frees, 5,712 bytes allocated
==2334==
==2334== All heap blocks were freed -- no leaks are possible
==2334==
==2334== For counts of detected and suppressed errors, rerun with: -v
==2334== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $


问:
Should return empty list [] 200/204 or 404 in a Restful API design?
For example, there's a restful API GET http://luexu.com/users/{page} to list the users in Nth page. Suppose there're 20 users in each page. There're 100 users total in the database. GET http://luexu.com/users/5 returns the 80th to 100th users.

So how about query GET http://luexu.com/users/10? it's out of the total users. Which is a better design to return an empty list, empty array [] or 404?

200?

```<code>{
    "code": 200,
    "msg": "OK",
    "data": []
}
</code>```

or 204?

```<code>{
    "code": 204,
    "msg": "OK",
    "data": []
}
</code>```

or 404?

```<code>{
    "code": 404,
    "msg": "Not Found",
    "data": null
}
</code>```

答:
so how about code 204?

In HTTP, 204 No Content means something very specific -- that the message body is zero bytes long.

The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body.

So you shouldn't be thinking about it if you are sending, for example, a json encoded document.

If an empty list is an acceptable representation of the resource, then using 200 as the response code is fine.  For instance, consider this URI for stack overflow itself.

https://stackoverflow.com/questions/tagged/cqrs+or+domain-driven-design+or+event-sourcing?sort=newest&page=999&pagesize=15

As of 2019-06-01, there are many fewer than 999 pages of questions with these tags, but the server has no problem computing the correct representation for this page (including the information that the highest numbered page is 426).  Therefore, the semantics of 200 are perfectly suitable.

404 means that no representation for the resource was available.  All 4xx class response codes indicate an error with the request -- in this case, it suggests that the client made a mistake with the URI.  That could be a temporary condition (you shouldn't be asking about that resource right now).  So that could also be fine, if what you want to indicate is that the client has left the happy path of the domain protocol.

How to choose?  I start from this observation in the HTTP specification

the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.

So which is useful to the client?  A representation of the problem, or a representation of an empty collection?  This can be a challenging question when the same resources are being used for different things.

Body:
For example, there's a restful API GET http://luexu.com/users/{page} to list the users in Nth page. Suppose there're 20 users in each page. There're 100 users total in the database. GET http://luexu.com/users/5 returns the 80th to 100th users.

So how about query GET http://luexu.com/users/10? it's out of the total users. Which is a better design to return an empty list, empty array [] or 404?

200?

{
    "code": 200,
    "msg": "OK",
    "data": []
}

or 204?

{
    "code": 204,
    "msg": "OK",
    "data": []
}

or 404?

{
    "code": 404,
    "msg": "Not Found",
    "data": null
}