问:
Python Requests returns content of other random URL
So, I have a strange behavior when trying to scrape a webpage with python requests library. For some reason that I don't understand when I scrape the content of a webpage I get the data of another apparently random webpage. Here's an example:

```<code>import requests
from bs4 import BeautifulSoup

def scrape_webpage(url):
    """
    Function to scrape some data from given url
    """
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')

    data = {'event_title': soup.find('h1').text.lower()}
    data['event_date'] = soup.find('li', {'class': 'header'}).text.split()[1]

    return data

# Test URL
url = 'https://www.tapology.com/fightcenter/events/67412-ufc-on-espn-33'

# First try returns the correct info
first = scrape_webpage(url)
print(first)
# {'event_date': '05.16.2020', 'event_title': 'ufc fight night: overeem vs. harris'}

# A second try changing nothing returns wrong info
second = scrape_webpage(url)
print(second)
# {'event_date': '06.20.2020', 'event_title': 'efm 3'}

# A third try also fails to retrieve the correct data
third = scrape_webpage(url)
print(third)
# {'event_date': '10.05.2010', 'event_title': 'bystriy fight club 1'}
</code>```

And so this behavior repeats without apparent logic. Also worth to mention is that I'm using Google Colab to do this. If I try to scrape a list of urls only the first one gets the correct data (and only if it's the first try) and the rest returns data from a random url. So the questions is ¿how to fix this behavior?

答:
You should mimik a real browser, at least that can be done passing a User-Agent:

```<code>def scrape_webpage(url):
    #s = session()
    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4103.61 Safari/537.36"
    }
    """
    Function to scrape some data from given url
    """
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.content, 'html.parser')

    data = {'event_title': soup.find('h1').text.lower()}
    data['event_date'] = soup.find('li', {'class': 'header'}).text.split()[1]

    return data

# Test URL
url = 'https://www.tapology.com/fightcenter/events/67412-ufc-on-espn-33'

for x in range(10):
    # A second try changing nothing returns wrong info
    second = scrape_webpage(url)
    print(second)
</code>```

Output:

```<code>{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
</code>```

Body:
So, I have a strange behavior when trying to scrape a webpage with python requests library. For some reason that I don't understand when I scrape the content of a webpage I get the data of another apparently random webpage. Here's an example:

import requests
from bs4 import BeautifulSoup

def scrape_webpage(url):
    """
    Function to scrape some data from given url
    """
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')

    data = {'event_title': soup.find('h1').text.lower()}
    data['event_date'] = soup.find('li', {'class': 'header'}).text.split()[1]

    return data

# Test URL
url = 'https://www.tapology.com/fightcenter/events/67412-ufc-on-espn-33'

# First try returns the correct info
first = scrape_webpage(url)
print(first)
# {'event_date': '05.16.2020', 'event_title': 'ufc fight night: overeem vs. harris'}

# A second try changing nothing returns wrong info
second = scrape_webpage(url)
print(second)
# {'event_date': '06.20.2020', 'event_title': 'efm 3'}

# A third try also fails to retrieve the correct data
third = scrape_webpage(url)
print(third)
# {'event_date': '10.05.2010', 'event_title': 'bystriy fight club 1'}

And so this behavior repeats without apparent logic. Also worth to mention is that I'm using Google Colab to do this. If I try to scrape a list of urls only the first one gets the correct data (and only if it's the first try) and the rest returns data from a random url. So the questions is ¿how to fix this behavior?

Body:
You should mimik a real browser, at least that can be done passing a User-Agent:

def scrape_webpage(url):
    #s = session()
    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4103.61 Safari/537.36"
    }
    """
    Function to scrape some data from given url
    """
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.content, 'html.parser')

    data = {'event_title': soup.find('h1').text.lower()}
    data['event_date'] = soup.find('li', {'class': 'header'}).text.split()[1]

    return data

# Test URL
url = 'https://www.tapology.com/fightcenter/events/67412-ufc-on-espn-33'

for x in range(10):
    # A second try changing nothing returns wrong info
    second = scrape_webpage(url)
    print(second)

Output:

{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}
{'event_title': 'ufc fight night: overeem vs. harris', 'event_date': '05.16.2020'}


来源: stackexchange

问:
Is it possible in C++ to have a method in the superclass that when called by each subclass returns a shared_ptr to that subclass?
I want all children of a superclass to perform a similar action. So I figured I could have a method in the superclass to do so. The action requires sending a copy of (or shared_ptr to) itself as an argument to a method. But I do not know if such thing is possible or not, and if yes, how should it be done.

To clarify my question, please consider the following example. I want the printouts to be "Child" and "Parent". The current code prints out "Parent" and "Parent". Of course this is expected from this code as I am returning copying *this as a Parent type inside make_shared.

The question is if I could get the expected behavior. Please note that in the real case, there are many children, so implementing the function getPtr() in each is not that easy.

Thanks for your help.

```<code>class Parent
{
public:
  std::shared_ptr<Parent> getPtr() { return std::make_shared<Parent>(*this); } // I tried make_shared<decltype(*this)> also, but the code does not compile.

  virtual void printName() const { std::cout << "Parent\n"; }
};

class Child1 : public Parent {
  void printName() const override { std::cout << "Child\n"; }
};

int main() {
  Child1 c;
  auto cPtr = c.getPtr();
  cPtr->printName();       // I want this to print "Child", but it prints "Parent" (as expected)

  Parent p;
  auto pPtr = p.getPtr();
  pPtr->printName();
}
</code>```

答:
It is not entirely clear what you are doing, but you certainly want to derive your Parent from std::enable_shared_from_this.

This will give you a member function shared_from_this() (which is more or less what you want to achieve via getPtr()).

However, it must be stressed that your Parent objects must themselves be managed by std::shared_ptr. I.e., this will work only and only if

```<code>std::shared_ptr<Parent> p = std::make_shared<Parent>();
</code>```

Then you can use p->shared_from_this() to give you a shared pointer.

ContentLicense: CC BY-SA 4.0

Body:
I want all children of a superclass to perform a similar action. So I figured I could have a method in the superclass to do so. The action requires sending a copy of (or shared_ptr to) itself as an argument to a method. But I do not know if such thing is possible or not, and if yes, how should it be done.

To clarify my question, please consider the following example. I want the printouts to be "Child" and "Parent". The current code prints out "Parent" and "Parent". Of course this is expected from this code as I am returning copying *this as a Parent type inside make_shared.

The question is if I could get the expected behavior. Please note that in the real case, there are many children, so implementing the function getPtr() in each is not that easy.

Thanks for your help.

class Parent
{
public:
  std::shared_ptr<Parent> getPtr() { return std::make_shared<Parent>(*this); } // I tried make_shared<decltype(*this)> also, but the code does not compile.

  virtual void printName() const { std::cout << "Parent\n"; }
};

class Child1 : public Parent {
  void printName() const override { std::cout << "Child\n"; }
};

int main() {
  Child1 c;
  auto cPtr = c.getPtr();
  cPtr->printName();       // I want this to print "Child", but it prints "Parent" (as expected)

  Parent p;
  auto pPtr = p.getPtr();
  pPtr->printName();
}

Body:
It is not entirely clear what you are doing, but you certainly want to derive your Parent from std::enable_shared_from_this.

This will give you a member function shared_from_this() (which is more or less what you want to achieve via getPtr()).

However, it must be stressed that your Parent objects must themselves be managed by std::shared_ptr. I.e., this will work only and only if

std::shared_ptr<Parent> p = std::make_shared<Parent>();

Then you can use p->shared_from_this() to give you a shared pointer.


问:
Laravel collection paginate with where clause
I have a news table and i manage the read or unread flag. so I want to paginate both flags are separate without additional database queries.
My requirement is to get all the news and filter read or unread and paginate for a separate table view.
Once I try the following code but getting an error Method Illuminate\Database\Eloquent\Collection::paginate does not exist.

```<code>    $ns=News::all();
    $ns->where('read',1)->paginate(2);
    $ns->where('read',0)->paginate(2);
</code>```

I want to do that using only one DB Query.

答:
Can you Try below code

```<code>$readns = News::where('read',1)->paginate(2);
$unreadns = News::where('read',0)->paginate(2);
</code>```

You can use chunk() for it. Check this one laravel.com/docs/7.x/queries#chunking-results

Body:
I have a news table and i manage the read or unread flag. so I want to paginate both flags are separate without additional database queries.
My requirement is to get all the news and filter read or unread and paginate for a separate table view.
Once I try the following code but getting an error Method Illuminate\Database\Eloquent\Collection::paginate does not exist.

    $ns=News::all();
    $ns->where('read',1)->paginate(2);
    $ns->where('read',0)->paginate(2);

I want to do that using only one DB Query.

Body:
Can you Try below code

$readns = News::where('read',1)->paginate(2);
$unreadns = News::where('read',0)->paginate(2);

You can use chunk() for it. Check this one laravel.com/docs/7.x/queries#chunking-results


问:
How to give conditions in a scatter plot in matplotlib
Only the below condition should reflect in the scatter plot.How can i plot the condition?</p>

```<code>ipl.player[imdb.player< 0]

ax.scatter(data=ipl,x='player',y='budget')
</code>```

答:
Although your question is extremely confusing and unclear because you have two dataframes, IIUC, you want something like this</p>

```<code>ax.scatter(data=ipl[ipl.player< 0], x='player', y='budget')
</code>```

Body:
Only the below condition should reflect in the scatter plot.How can i plot the condition?

ipl.player[imdb.player< 0]

ax.scatter(data=ipl,x='player',y='budget')

Body:
Although your question is extremely confusing and unclear because you have two dataframes, IIUC, you want something like this

ax.scatter(data=ipl[ipl.player< 0], x='player', y='budget')


问:
Xamarin UI test - how to open navigation drawer
I am testing my android app using Xamarin UI Testing tool and I have written the following test: </p>

```<code>public void login()
    {
        app.Tap(x => x.Id("Activity.LoginActivity.RelativeLayout_email"));
        app.Tap(x => x.Id("EditText_email"));
        app.EnterText(x => x.Id("EditText_email"), "matt@matt.matt");
        app.Tap(x => x.Id("EditText_password"));
        app.EnterText(x => x.Id("EditText_password"), "matt123");
        app.PressEnter();
        app.Tap(x => x.Id("Button_login"));
        app.WaitForElement(x => x.Id("ImageView_OfferItem_photo"), timeout: TimeSpan.FromSeconds(120));
        app.SwipeLeftToRight();
        app.Tap(x => x.Id("ImageView_OfferItem_photo").Index(1));
    }
</code>```

<p>and at the end I want to open side navigation drawer but I am unable to do it, because I am using native menu icon, that has no id. I tried android.R.id.home, but it did not work, too.  </p>

答:
```<code>app.SwipeLeftToRight(0.99);
</code>```

You can  also swipe to open menu, like this :)

ContentLicense: CC BY-SA 3.0

Body:
I am testing my android app using Xamarin UI Testing tool and I have written the following test:

public void login()
    {
        app.Tap(x => x.Id("Activity.LoginActivity.RelativeLayout_email"));
        app.Tap(x => x.Id("EditText_email"));
        app.EnterText(x => x.Id("EditText_email"), "matt@matt.matt");
        app.Tap(x => x.Id("EditText_password"));
        app.EnterText(x => x.Id("EditText_password"), "matt123");
        app.PressEnter();
        app.Tap(x => x.Id("Button_login"));
        app.WaitForElement(x => x.Id("ImageView_OfferItem_photo"), timeout: TimeSpan.FromSeconds(120));
        app.SwipeLeftToRight();
        app.Tap(x => x.Id("ImageView_OfferItem_photo").Index(1));
    }

and at the end I want to open side navigation drawer but I am unable to do it, because I am using native menu icon, that has no id. I tried android.R.id.home, but it did not work, too.

Body:
app.SwipeLeftToRight(0.99);

You can  also swipe to open menu, like this :)


问:
Code condensing/efficiency
I'm writing a string replacing function to replace smiles with there actual image location but the code is going to be very big and messy because of all the nested ifs but i cant think of a more efficient way of writing the code.</p>

```<code>Public Function exchangeSmilies(ByVal postString As String) As String
    Dim ChangedString = postString
    ChangedString.ToLower()
    If ChangedString.Contains(":)") Then
        ChangedString = ChangedString.Replace(":)", GetSmilieMapPath("smile.gif"))
        If ChangedString.Contains(":p") Then
            ChangedString = ChangedString.Replace(":p", GetSmilieMapPath("toungue.gif"))
            If ChangedString.Contains(";)") Then
                ChangedString = ChangedString.Replace(";)", GetSmilieMapPath("wink.gif"))
                If ChangedString.Contains("<3") Then
                    ChangedString = ChangedString.Replace("<3", GetSmilieMapPath("heart.gif"))
                End If
            End If
        End If
    End If
    Return ChangedString
End Function

Public Function GetSmilieMapPath(ByVal SmilieImage As String) As String
    GetSmilieMapPath = "<img src=" & Chr(34) & "../Images/Smilies/" & SmilieImage & Chr(34) & ">"
    Return GetSmilieMapPath
End Function
</code>```

答:
Use a Dictionary instead.

Create a dictionary like the following at the class level:

```<code>Dim dictionary As New Dictionary(Of String, String)
dictionary.Add(":)", GetSmiliePath("smile.gif"))
dictionary.Add(":p", GetSmiliePath("tongue.gif"))
...
</code>```

In the exchangeSmilies function, you can loop through this dictionary to replace any occurrences:

```<code>...
For Each pair In dictionary
    If ChangedString.Contains(pair.Key) Then
        ChangedString = ChangedString.Replace(pair.Key, pair.Value)
    End If
Next
Return ChangedString
</code>```

Title: Code condensing/efficiency

Body:
I'm writing a string replacing function to replace smiles with there actual image location but the code is going to be very big and messy because of all the nested ifs but i cant think of a more efficient way of writing the code.

Public Function exchangeSmilies(ByVal postString As String) As String
    Dim ChangedString = postString
    ChangedString.ToLower()
    If ChangedString.Contains(":)") Then
        ChangedString = ChangedString.Replace(":)", GetSmilieMapPath("smile.gif"))
        If ChangedString.Contains(":p") Then
            ChangedString = ChangedString.Replace(":p", GetSmilieMapPath("toungue.gif"))
            If ChangedString.Contains(";)") Then
                ChangedString = ChangedString.Replace(";)", GetSmilieMapPath("wink.gif"))
                If ChangedString.Contains("<3") Then
                    ChangedString = ChangedString.Replace("<3", GetSmilieMapPath("heart.gif"))
                End If
            End If
        End If
    End If
    Return ChangedString
End Function

Public Function GetSmilieMapPath(ByVal SmilieImage As String) As String
    GetSmilieMapPath = ""
    Return GetSmilieMapPath
End Function

Body:
Use a Dictionary instead.

Create a dictionary like the following at the class level:

Dim dictionary As New Dictionary(Of String, String)
dictionary.Add(":)", GetSmiliePath("smile.gif"))
dictionary.Add(":p", GetSmiliePath("tongue.gif"))
...

In the exchangeSmilies function, you can loop through this dictionary to replace any occurrences:

...
For Each pair In dictionary
    If ChangedString.Contains(pair.Key) Then
        ChangedString = ChangedString.Replace(pair.Key, pair.Value)
    End If
Next
Return ChangedString


问:
Angular 8 - Multiple HTTP calls in a for loop
There is a list of unlimited cars in backend.
Each car has an id (unique id) and a name (car model name).

I have the list of car IDs, example:

const carIds = ['abc','xyz'];
```

<p>and I need to fetch respective car names for the above car Ids.
I tried the below code, but its not working at all, what is that I'm missing ?</p>

<pre class="lang-js prettyprint-override"><code>const carIds = ['abc','xyz']; // unique ids
const carsList = [];
for (const carId of carIds) {
  this.api.getCar(carId).pipe(
    map(response => {
      carsList.push({
        name: response.name,
        id: carId
      });
    })
  );
}
console.log(carsList); // When I run this, its printing nothing.
</code>```

Expected Output:

carsList = [{
 id: 'abc',
 name: 'benz'
},{
 id: 'xyz',
 name: 'mercede'
}]
```

Thanks in advance.

答:
You can use forkJoin to subscribe to many streams by once and get the result when all stream are complete, it is like a promise.all for rxjs.

const carIds = ['abc','xyz']; // unique ids
const httpCalls = carIds.map(id => this.api.getCar(id)) // array of streams
const carsList$ = forkJoin(httpCalls).pipe(
   map(results => results.map((r, index) => ({ id: carIds[index], name: r.name }));
);

carsList$.subscribe(console.log);
```

Body:
There is a list of unlimited cars in backend.
Each car has an id (unique id) and a name (car model name).

I have the list of car IDs, example:

const carIds = ['abc','xyz'];

and I need to fetch respective car names for the above car Ids.
I tried the below code, but its not working at all, what is that I'm missing ?

const carIds = ['abc','xyz']; // unique ids
const carsList = [];
for (const carId of carIds) {
  this.api.getCar(carId).pipe(
    map(response => {
      carsList.push({
        name: response.name,
        id: carId
      });
    })
  );
}
console.log(carsList); // When I run this, its printing nothing.

Expected Output:

carsList = [{
 id: 'abc',
 name: 'benz'
},{
 id: 'xyz',
 name: 'mercede'
}]

Thanks in advance.


问:
Create multiple folders in the working directory
I want to create 20 folders in the working directory. These should have random names containing the current minute, second and hour, plus a random number between 10000 and 50000.

For example, a valid name would be 05_06_20_11050.

To do that I have the below functions:

```<code>from random import randint, randrange
from datetime import datetime

def name_generator():
    td = datetime.today()
    e = td.strftime("%m_%d_%y")
    r = randint(51000, 100000)
    s = e + "_" + str(r)
    return s

import os

def directory_creator(name):
    os.mkdir(name)

import os, os.path

def create():
    pa = "C:/Users/Nuru/AppData/Local/Programs/Python/Python37-32/"
    n = directory_count()
    name = name_generator()
    t = os.path.join(pa, name)

    for i in range(n):
        if os.path.exists(t):
            pass
        else:
            directory_creator(name)
</code>```

All the functions work well, except for the create function: It only creates one folder. How do I fix this?

答:
Why don't you change the loop to:</p>

```<code>for i in range(n):

    name = name_generator()
    t = os.path.join(pa, name)

    if os.path.exists(t):
         pass
    else:
         directory_creator(t)
</code>```

Body:
I want to create 20 folders in the working directory. These should have random names containing the current minute, second and hour, plus a random number between 10000 and 50000.

For example, a valid name would be 05_06_20_11050.

To do that I have the below functions:

from random import randint, randrange
from datetime import datetime

def name_generator():
    td = datetime.today()
    e = td.strftime("%m_%d_%y")
    r = randint(51000, 100000)
    s = e + "_" + str(r)
    return s

import os

def directory_creator(name):
    os.mkdir(name)

import os, os.path

def create():
    pa = "C:/Users/Nuru/AppData/Local/Programs/Python/Python37-32/"
    n = directory_count()
    name = name_generator()
    t = os.path.join(pa, name)

    for i in range(n):
        if os.path.exists(t):
            pass
        else:
            directory_creator(name)

All the functions work well, except for the create function: It only creates one folder. How do I fix this?

Body:
Why don't you change the loop to:

for i in range(n):

    name = name_generator()
    t = os.path.join(pa, name)

    if os.path.exists(t):
         pass
    else:
         directory_creator(t)


问:
Discord bot get number of users in all channels
Im not good with javascript but i have been trying to get count number of users in all voice channels.
For example: if 2 users in 'voice channel 1' and 1 user in 'voice channel 2' I want to print number 3 in console which is all users in voice channels.

```<code>var Count;
for(Count in bot.users.array()){
   var User = bot.users.array()[Count];
   console.log(User.username);
}
</code>```

This code print all members(online/offline) name in console, But i don't know how to get number of only users in voice channels.

答:
If you don't want to use this inside an event but use in an embed,message etc; here is my solution. I used @slothiful 's solution but made a bit change.</p>

```<code>// I used my "message" property. You can change it with yours.
const voiceChannels = message.guild.channels.cache.filter(c => c.type === 'voice');
let count = 0;

for (const [id, voiceChannel] of voiceChannels) count += voiceChannel.members.size;

message.channel.send(count);
</code>```

Body:
Im not good with javascript but i have been trying to get count number of users in all voice channels.
For example: if 2 users in 'voice channel 1' and 1 user in 'voice channel 2' I want to print number 3 in console which is all users in voice channels.

var Count;
for(Count in bot.users.array()){
   var User = bot.users.array()[Count];
   console.log(User.username);
}

This code print all members(online/offline) name in console, But i don't know how to get number of only users in voice channels.

Body:
If you don't want to use this inside an event but use in an embed,message etc; here is my solution. I used @slothiful 's solution but made a bit change.

// I used my "message" property. You can change it with yours.
const voiceChannels = message.guild.channels.cache.filter(c => c.type === 'voice');
let count = 0;

for (const [id, voiceChannel] of voiceChannels) count += voiceChannel.members.size;

message.channel.send(count);


问:
Create Deepsecurity Global Rues through console
I want to create an Application Control Global Ruleset, however it seems to be the only kind of policy which cannot be created through the Management Console, only via the API access (which is not configured at the moment for my organisation).

Did I get something wrong, or is the creation not possible through the console?

答:
You are correct, creating Application Control Global Rulesets is handled through the API.

More information on this:

https://help.deepsecurity.trendmicro.com/application-control-rulesets.html

https://help.deepsecurity.trendmicro.com/application-control-rulesets-shared-global.html

https://automation.deepsecurity.trendmicro.com/article/dsaas/add-global-rules?platform=dsaas

As an aside, you mention that the API is not configured for your organization. Getting started with the API is very doable, and there's more info in the articles starting here: https://automation.deepsecurity.trendmicro.com/article/dsaas/first-steps-for-deep-security-developers?platform=dsaas

(I work for Trend Micro)


问:
.NET MVC application with Oracle database credentials changed
i have a .NET MVC web application using oracle database.  the application is in production and i have changed the credentials of the oracle db.  now i am not able to connect my application. anyone know where to change the oracle db password so that my .net application works</p>

答:
Hi typically the best practice is to place database credentials in a connection string variable the web.config

Do you see anything there?

Another option is to search (ctrl+f) for the old.password name.in in your entire.solition and see if old password found unless its hashed.

If those two options fail to turn up.anything try search for the database server and seeing if connection.open or a password string is near by


问:
mac os 10.6 server: crontab does not fire wget script
I am completely baffled by the behaviour of cron under Mac OS 10.6 Server. I am trying to run two scripts in a cronjob like this:

```<code>00 16 * * * /Users/myusername/script.sh
04 16 * * * /Users/myusername/crontest.sh
</code>```

While 'script.sh' contains a wget command:

```<code>#!/bin/sh
wget -r -l3 --no-parent -nc -A ".shtml" 'http://some.url/somethingelse/'
</code>```

'crontest.sh' contains just a test script:

```<code>echo "hi" >> /Users/myusername/crontest.txt
</code>```

Problem is, 'script.sh' does not fire, but 'crontest.sh' does. What could be the cause of the wget script not firing? Do the scripts require a specific encoding? Does cron write a log file somewhere?

(I tested the wget command by itself in the shell, where it works fine.)

答: Sorry for asking the obvious: Execute flag and permissions set the same on both scripts?</p>

Body:
I am completely baffled by the behaviour of cron under Mac OS 10.6 Server. I am trying to run two scripts in a cronjob like this:

00 16 * * * /Users/myusername/script.sh
04 16 * * * /Users/myusername/crontest.sh

While 'script.sh' contains a wget command:

#!/bin/sh
wget -r -l3 --no-parent -nc -A ".shtml" 'http://some.url/somethingelse/'

'crontest.sh' contains just a test script:

echo "hi" >> /Users/myusername/crontest.txt

Problem is, 'script.sh' does not fire, but 'crontest.sh' does. What could be the cause of the wget script not firing? Do the scripts require a specific encoding? Does cron write a log file somewhere?

(I tested the wget command by itself in the shell, where it works fine.)


问:
5/2 is 2 but I'm getting the one in index 3
I have a linked list 1-2-3-4-5-6. I need to get 4. I have a method that inserts all in the array and calculate the middle. if there are two, I'm printing the second one. in my head the method(I have on my text book) prints 3 but when I actually run it I get 4(as the text book indicates) </p>

```<code>public static void main(String[] args) {
    ListNode x = new ListNode(1);

    ListNode y = new ListNode(2,x);
    ListNode a = new ListNode(3, y);
    ListNode b = new ListNode(4, a);
    ListNode c = new ListNode(5, b);
    ListNode d = new ListNode(6, c);

    ListNode r= middleNode(d);
    System.out.println(r.val);

}
public static ListNode middleNode(ListNode head) {
    ListNode[] A = new ListNode[100];
    int t = 0;
    while (head.next != null) {
        A[t++] = head;
        head = head.next;
    }
    return A[5 / 2];

}
A[0] = 1
A[1] = 2
A[2] = 3
A[3] = 4
A[4] = 5
A[5] = 6

A[t] =5 t being 5
thus t/2 = 2. so should print 3.
</code>```

答: In the while loop you have reversed your nodes. So after reversing in the index 2 you have 4.</p>

Body:
I have a linked list 1-2-3-4-5-6. I need to get 4. I have a method that inserts all in the array and calculate the middle. if there are two, I'm printing the second one. in my head the method(I have on my text book) prints 3 but when I actually run it I get 4(as the text book indicates)

public static void main(String[] args) {
    ListNode x = new ListNode(1);

    ListNode y = new ListNode(2,x);
    ListNode a = new ListNode(3, y);
    ListNode b = new ListNode(4, a);
    ListNode c = new ListNode(5, b);
    ListNode d = new ListNode(6, c);

    ListNode r= middleNode(d);
    System.out.println(r.val);

}
public static ListNode middleNode(ListNode head) {
    ListNode[] A = new ListNode[100];
    int t = 0;
    while (head.next != null) {
        A[t++] = head;
        head = head.next;
    }
    return A[5 / 2];

}
A[0] = 1
A[1] = 2
A[2] = 3
A[3] = 4
A[4] = 5
A[5] = 6

A[t] =5 t being 5
thus t/2 = 2. so should print 3.


问:
How to iterate through multiple select options using forEach to get innerText values
How do you iterate, using forEach (or a similar modern browser method) to get the innerText value of each select option? This throws an error. Uncaught TypeError: intervals.forEach is not a function

```<code>let intervals = document.querySelector("#edit_amenity_hour_interval").options;
intervals.forEach(interval => {
    console.log(interval.innerText)
})
</code>```

答:
Use Array.from, because options returns collection, not array

```<code>let intervals = Array.from(document.querySelector("#edit_amenity_hour_interval").options)
</code>```

Body:
How do you iterate, using forEach (or a similar modern browser method) to get the innerText value of each select option? This throws an error. Uncaught TypeError: intervals.forEach is not a function

let intervals = document.querySelector("#edit_amenity_hour_interval").options;
intervals.forEach(interval => {
    console.log(interval.innerText)
})

Body:
Use Array.from, because options returns collection, not array

let intervals = Array.from(document.querySelector("#edit_amenity_hour_interval").options)


问:
Python_DF ordering and customdata in Plotly
I have issue with wrong reflection data in hovers in the code below. See code with comments for each block.

I have issue with wrong reflection data in hovers in the code below. See code with comments for each block.

```<code>import plotly.express as px
import pandas as pd
import plotly.graph_objects as go

rows=[['501-600','15','122.58333','45.36667','Name1'],
      ['till 500','4','12.5','27.5','Name2'],
      ['more 601','41','-115.53333','38.08','Name3'],
      ['till 500', '26', '65.5', '29.5','Name4'],
      ['501-600','35','12.58333','55.36667','Name5'],
      ['more 601','9','55.53333','-38.08','Name6'],
      ]

colmns=['bins','data','longitude','latitude','names']
#Df creation
df=pd.DataFrame(data=rows, columns=colmns)
#Ordering for labels in legend
order = ['till 500', '501-600', 'more 601']
df = df.set_index('bins')
df_ordered = df.T[order].T.reset_index()
df_ordered = df_ordered.astype({"data": int})
#Plotting viz
fig=px.scatter_geo(df_ordered,lon='longitude', lat='latitude',color='bins',
                   color_discrete_sequence=px.colors.qualitative.Set1,
                   hover_name="names",
                   size='data',opacity=0.7,text='data',
                   projection="equirectangular",size_max=35,
                   )
#Adding custom data for hovers
fig.update_traces(customdata=df_ordered)
fig.update_traces(hovertemplate="<b>Name: %{customdata[4]} </b><br><br>Bin: %{customdata[0]}<br>"
                                "Data: %{customdata[1]:.2f}<extra></extra>")
#Adding marker labels
fig.add_trace(go.Scattergeo(lon=df_ordered["longitude"],
              lat=df_ordered["latitude"],
              text=df_ordered["names"],
              textposition="middle left",
              mode='text',
              textfont=dict(size=12,color="black"),
              showlegend=False,
              texttemplate="       %{text}",
              hoverinfo='skip',
              ))
fig.show()
</code>```

So at the end I guess that this problems raise from ordering and maybe I need to remake smth in customdata lines, but can't understand how to fix it. Will appreciate for help in fixing it.

答:
I had quite hard time playing with the custom hovertemplate in this case (you can eventually see this doc) But I think that I could achieve the output your looking for without add an extra trace.

fig=px.scatter_geo(df_ordered,
                   lon='longitude',
                   lat='latitude',
                   color='bins',
                   color_discrete_sequence=px.colors.qualitative.Set1,
                   hover_name="names",
                   size='data',
                   opacity=0.7,
                   text='names',
                   projection="equirectangular",
                   size_max=35,
                   # by default every column go to hover
                   # you can eventually use formatting here
                   hover_data={"longitude": False,
                               "latitude": False,
                               "names": False,
                               "data": ":.2f"},
                   # if you don't want to change column names
                   # you can just change them here
                   labels={"bins": "Bin",
                           "data": "Data"}
                   )

fig.update_traces(mode="markers+text",
                  textposition="middle left",
                  textfont=dict(size=12,
                                color="black")
                  showlegend=False,
                 )

# Here I just change the `=` for `: ` in every trace
for data in fig.data:
    data.hovertemplate = data.hovertemplate.replace("=", ": ")

fig.show()
```

<p><strong>Update</strong> I just realized that there is a bug with <code>labels</code> used together with <code>hover_data</code> in particular if you use <code>labels</code> for some reasons the formatting "data": ":.2f" is not preserved. A possible workaround is the following</p>

<pre class="lang-py prettyprint-override"><code>fig = px.scatter_geo(df_ordered,
                     lon='longitude',
                     lat='latitude',
                     color='bins',
                     color_discrete_sequence=px.colors.qualitative.Set1,
                     hover_name="names",
                     size='data',
                     opacity=0.7,
                     text='names',
                     projection="equirectangular",
                     size_max=35,
                     # by default every column go to hover
                     # you can eventually use formatting here
                     hover_data={"longitude": False,
                                 "latitude": False,
                                 "names": False,
                                 "data": ":.2f"}
                    )

fig.update_traces(mode="markers+text",
                  textposition="middle left",
                  textfont=dict(size=12,
                                color="black"),
                  showlegend=False,
                 )

# it's pretty verbose but now the output should be
# exactly as you expect
for data in fig.data:
    template = data.hovertemplate
    template = template.replace("<b>", "<b>Name: ")\
                       .replace("bins=", "Bin: ")\
                       .replace("data=", "Data: ")
    data.hovertemplate = template

fig.show()
</code>```

Body:
I have issue with wrong reflection data in hovers in the code below. See code with comments for each block.

I have issue with wrong reflection data in hovers in the code below. See code with comments for each block.

import plotly.express as px
import pandas as pd
import plotly.graph_objects as go

rows=[['501-600','15','122.58333','45.36667','Name1'],
      ['till 500','4','12.5','27.5','Name2'],
      ['more 601','41','-115.53333','38.08','Name3'],
      ['till 500', '26', '65.5', '29.5','Name4'],
      ['501-600','35','12.58333','55.36667','Name5'],
      ['more 601','9','55.53333','-38.08','Name6'],
      ]

colmns=['bins','data','longitude','latitude','names']
#Df creation
df=pd.DataFrame(data=rows, columns=colmns)
#Ordering for labels in legend
order = ['till 500', '501-600', 'more 601']
df = df.set_index('bins')
df_ordered = df.T[order].T.reset_index()
df_ordered = df_ordered.astype({"data": int})
#Plotting viz
fig=px.scatter_geo(df_ordered,lon='longitude', lat='latitude',color='bins',
                   color_discrete_sequence=px.colors.qualitative.Set1,
                   hover_name="names",
                   size='data',opacity=0.7,text='data',
                   projection="equirectangular",size_max=35,
                   )
#Adding custom data for hovers
fig.update_traces(customdata=df_ordered)
fig.update_traces(hovertemplate="Name: %{customdata[4]}

Bin: %{customdata[0]}
"
                                "Data: %{customdata[1]:.2f}<extra></extra>")
#Adding marker labels
fig.add_trace(go.Scattergeo(lon=df_ordered["longitude"],
              lat=df_ordered["latitude"],
              text=df_ordered["names"],
              textposition="middle left",
              mode='text',
              textfont=dict(size=12,color="black"),
              showlegend=False,
              texttemplate="       %{text}",
              hoverinfo='skip',
              ))
fig.show()

So at the end I guess that this problems raise from ordering and maybe I need to remake smth in customdata lines, but can't understand how to fix it. Will appreciate for help in fixing it.

Body:
I had quite hard time playing with the custom hovertemplate in this case (you can eventually see this doc) But I think that I could achieve the output your looking for without add an extra trace.

fig=px.scatter_geo(df_ordered,
                   lon='longitude',
                   lat='latitude',
                   color='bins',
                   color_discrete_sequence=px.colors.qualitative.Set1,
                   hover_name="names",
                   size='data',
                   opacity=0.7,
                   text='names',
                   projection="equirectangular",
                   size_max=35,
                   # by default every column go to hover
                   # you can eventually use formatting here
                   hover_data={"longitude": False,
                               "latitude": False,
                               "names": False,
                               "data": ":.2f"},
                   # if you don't want to change column names
                   # you can just change them here
                   labels={"bins": "Bin",
                           "data": "Data"}
                   )

fig.update_traces(mode="markers+text",
                  textposition="middle left",
                  textfont=dict(size=12,
                                color="black")
                  showlegend=False,
                 )

# Here I just change the `=` for `: ` in every trace
for data in fig.data:
    data.hovertemplate = data.hovertemplate.replace("=", ": ")

fig.show()

Update I just realized that there is a bug with labels used together with hover_data in particular if you use labels for some reasons the formatting "data": ":.2f" is not preserved. A possible workaround is the following

fig = px.scatter_geo(df_ordered,
                     lon='longitude',
                     lat='latitude',
                     color='bins',
                     color_discrete_sequence=px.colors.qualitative.Set1,
                     hover_name="names",
                     size='data',
                     opacity=0.7,
                     text='names',
                     projection="equirectangular",
                     size_max=35,
                     # by default every column go to hover
                     # you can eventually use formatting here
                     hover_data={"longitude": False,
                                 "latitude": False,
                                 "names": False,
                                 "data": ":.2f"}
                    )

fig.update_traces(mode="markers+text",
                  textposition="middle left",
                  textfont=dict(size=12,
                                color="black"),
                  showlegend=False,
                 )

# it's pretty verbose but now the output should be
# exactly as you expect
for data in fig.data:
    template = data.hovertemplate
    template = template.replace("<b>", "<b>Name: ")\
                       .replace("bins=", "Bin: ")\
                       .replace("data=", "Data: ")
    data.hovertemplate = template

fig.show()


问:
Flutter - Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
Not sure on reason why I am getting error " Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f' ". Everything seems to be done correctly but still getting error</p>

```<code>Json link: https://androidapp.factory2homes.com/api/get-shipping-address-by-user-id/3
</code>```

```<code>class ShippingAddressPage extends StatefulWidget {
  @override
  _ShippingAddressPageState createState() => _ShippingAddressPageState();
}

class _ShippingAddressPageState extends State<ShippingAddressPage> {

  List<Shipping> _shippingAddressList = List<Shipping>();

 @override
 void initState() {
   super.initState();
   _getShippingAddressByUserId();
 }

 _getShippingAddressByUserId() async {
   SharedPreferences _prefs = await SharedPreferences.getInstance();
   int _userId = _prefs.getInt('userId');
   ShippingAddressService _shippingAddressService = ShippingAddressService();
   var result = await _shippingAddressService.getShippingAddressByUserId(_userId);
   var shipping = json.decode(result.body);
   shipping.forEach((shipping){
     var model = Shipping();
     model.id = shipping['id'];
     model.name = shipping['name'];
     model.address = shipping['address'];
     setState(() {
       _shippingAddressList.add(model);
     });
   });
 }
</code>```

```<code>E/flutter (26002): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
E/flutter (26002): #0      _ShippingAddressPageState._getShippingAddressByUserId (package:factory2homes/screens/shipping_address_page.dart:32:13)
E/flutter (26002): <asynchronous suspension>
E/flutter (26002): #1      _ShippingAddressPageState.initState (package:factory2homes/screens/shipping_address_page.dart:22:4)
</code>```

```<code>class ShippingAddressService{
  Repository _repository;

  ShippingAddressService(){
    _repository = Repository();
  }

  getShippingAddressByUserId(int userId) async {
    return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
  }

}
</code>```

答:
Does ShippingAddressService() have a constructor other than the default?  If so, please add it to your code sample. **

Your code:

```<code>  getShippingAddressByUserId(int userId) async {
    return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
  }
</code>```

I have on more than one occation had a simular issue.  My solution was to change the code to:

```<code>ShippingAddress getShippingAddressByUserId(int userId) async {

    ShippingAddress _shippingAddress = await _repository.httpGetById('get-shipping-address-by-user-id', userId);

    return _shippingAddress;
  }
</code>```

As always, YMMV.

Looking at your code further, my ShippingAddress might be your Shipping.

Body:
Not sure on reason why I am getting error " Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f' ". Everything seems to be done correctly but still getting error

Json link: https://androidapp.factory2homes.com/api/get-shipping-address-by-user-id/3

class ShippingAddressPage extends StatefulWidget {
  @override
  _ShippingAddressPageState createState() => _ShippingAddressPageState();
}

class _ShippingAddressPageState extends State<ShippingAddressPage> {

  List<Shipping> _shippingAddressList = List<Shipping>();

 @override
 void initState() {
   super.initState();
   _getShippingAddressByUserId();
 }

 _getShippingAddressByUserId() async {
   SharedPreferences _prefs = await SharedPreferences.getInstance();
   int _userId = _prefs.getInt('userId');
   ShippingAddressService _shippingAddressService = ShippingAddressService();
   var result = await _shippingAddressService.getShippingAddressByUserId(_userId);
   var shipping = json.decode(result.body);
   shipping.forEach((shipping){
     var model = Shipping();
     model.id = shipping['id'];
     model.name = shipping['name'];
     model.address = shipping['address'];
     setState(() {
       _shippingAddressList.add(model);
     });
   });
 }

E/flutter (26002): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
E/flutter (26002): #0      _ShippingAddressPageState._getShippingAddressByUserId (package:factory2homes/screens/shipping_address_page.dart:32:13)
E/flutter (26002): <asynchronous suspension>
E/flutter (26002): #1      _ShippingAddressPageState.initState (package:factory2homes/screens/shipping_address_page.dart:22:4)

class ShippingAddressService{
  Repository _repository;

  ShippingAddressService(){
    _repository = Repository();
  }

  getShippingAddressByUserId(int userId) async {
    return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
  }

}

Body:
Does ShippingAddressService() have a constructor other than the default?  If so, please add it to your code sample. **

Your code:

  getShippingAddressByUserId(int userId) async {
    return await _repository.httpGetById('get-shipping-address-by-user-id', userId);
  }

I have on more than one occation had a simular issue.  My solution was to change the code to:

ShippingAddress getShippingAddressByUserId(int userId) async {

    ShippingAddress _shippingAddress = await _repository.httpGetById('get-shipping-address-by-user-id', userId);

    return _shippingAddress;
  }

As always, YMMV.

Looking at your code further, my ShippingAddress might be your Shipping.


问:
How to check for cycles in a graph?
My code works fine but fails check50 test for skipping pairs when creating cycles. The logic I use to check for cycles is that before creating an edge from winner to loser I go back the edges from the winner and check if it ever reaches the loser. If it does, it means it'll create a cycle so the edge is skipped but It doesn't work. My logic could be wrong too, if so let me know. Here's my code-</p>

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

// Max number of candidates
#define MAX 9

// preferences[i][j] is number of voters who prefer i over j
int preferences[MAX][MAX];

// locked[i][j] means i is locked in over j
bool locked[MAX][MAX];

// Each pair has a winner, loser
typedef struct
{
    int winner;
    int loser;
}
pair;

// Array of candidates
string candidates[MAX];
pair pairs[MAX * (MAX - 1) / 2];

int pair_count;
int candidate_count;

// Function prototypes
bool vote(int rank, string name, int ranks[]);
void record_preferences(int ranks[]);
void add_pairs(void);
void sort_pairs(void);
void lock_pairs(void);
void print_winner(void);
bool check_cycle(int n, int m);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: tideman [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i] = argv[i + 1];
    }

    // Clear graph of locked in pairs
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            locked[i][j] = false;
        }
    }

    pair_count = 0;
    int voter_count = get_int("Number of voters: ");

    // Query for votes
    for (int i = 0; i < voter_count; i++)
    {
        // ranks[i] is voter's ith preference
        int ranks[candidate_count];

        // Query for each rank
        for (int j = 0; j < candidate_count; j++)
        {
            string name = get_string("Rank %i: ", j + 1);

            if (!vote(j, name, ranks))
            {
                printf("Invalid vote.\n");
                return 3;
            }
        }

        record_preferences(ranks);

        printf("\n");
    }

    add_pairs();
    sort_pairs();
    lock_pairs();
    print_winner();
    return 0;
}

// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(candidates[i], name) == 0)
        {
            ranks[rank] = i;
            return true;
        }
    }

    return false;
}

// Update preferences given one voter's ranks
void record_preferences(int ranks[])
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 1; j < candidate_count - i; j++)
        {
            preferences[ranks[i]][ranks[i + j]]++;
        }
    }

    return;
}

// Record pairs of candidates where one is preferred over the other
void add_pairs(void)
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            if (preferences[i][j] > preferences[j][i])
            {
                pairs[pair_count].winner = i;
                pairs[pair_count].loser = j;
                pair_count++;
            }
        }
    }

    return;
}

// Sort pairs in decreasing order by strength of victory
void sort_pairs(void)
{
    // TODO
    pair k;
    for (int i = 0; i < pair_count; i++)
    {
        for (int j = i + 1; j < pair_count; j++)
        {
            if (preferences[pairs[i].winner][pairs[i].loser] < preferences[pairs[j].winner][pairs[j].loser])
            {
                //memcpy
                k = pairs[i];
                pairs[i] = pairs[j];
                pairs[j] = k;
            }
        }
    }

    return;
}

// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
    // TODO
    for (int i = 0; i < pair_count; i++)
    {
        if (!check_cycle(pairs[i].winner, pairs[i].loser))
        {
            locked[pairs[i].winner][pairs[i].loser] = true;
        }
    }
    return;
}

// Print the winner of the election
void print_winner(void)
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        bool source = true;

        for (int j = 0; j < candidate_count; j++)
        {
            if (locked[j][i] == true)
            {
                source = false;
                break;
            }
        }

        if (source == true)
        {
            printf("%s\n", candidates[i]);
        }
    }

    return;
}

//checking for cycle
bool check_cycle(int n, int m)
{
    if (locked[m][n] == true)
    {
        return true;
    }

    for (int i = 0; i < candidate_count; i++)
    {
        if (locked[i][n] == true)
        {
            check_cycle(i, m);
        }
    }
    return false;
}
</code>```

答:
I don't think some of the previous answers gave the right answer.

For n candidates, there exists the ith candidate that no
arrow pointing to her or him if and only if the ith column of the
"locked" table is all false. In such a situation, no circle (a
circle with n nodes) can be drawn if the ith column must be a node.

However, this doesn't guarantee that there are no other smaller circles. If we make the "locked" table one-size smaller (i.e. remove
the nth candidate, now we will have a (n-1) *(n-1) "locked"
table. Like what we did in step(1), we can make sure that a circle of n-1 nodes is also impossible. By repeating this processing, no circle (any size) is possible.

We can check it by using recursion.

If you don't check whether a smaller circle is possible: you will have an error like this:

lock_pairs skips middle pair if it creates a cycle
      lock_pairs did not correctly lock all non-cyclical pairs

Here is the code:

```<code>bool is_circle (bool locked_array[MAX][MAX], int candi_count)
{
    //check the basic case
    //if there is only one node of course it doesn't form a circle
    if (candi_count == 1)
    {
        return false;
    }

    //recursively check whether the smaller locked_array with n-1 candidate form a circle
    //if the smaller one have a circle
    //this mean a middle pair create a circle if added into the "locked" table
    if (!is_circle(locked_array, candi_count - 1))
    {
        //if the one-size smaller "locked" table doesn't have a circle
        //check whether adding a new candidate forms a circle

        //if there is a column that is all false's after adding a new candidate
        //then it must not introduce a circle in this step
        for (int j = 0; j < candi_count; j++)
        {
            //a indicator variable for check whether a column has a true value;
            bool true_in_column = false;

            for (int i = 0; i < candi_count; i++)
            {
                if (locked_array[i][j] == true)
                {
                    true_in_column = true;
                }
            }

            //if there is a column doesn't have a true value then not circle is create at this step
            if (true_in_column == false)
            {
                return false;
            }
        }

        //if we cannot find such a column then the graph represented by current locked array
        //must have a circle
        return true;

    }

    //the smaller "locked" table forms a circle
    else
    {
        return true;
    }

}

</code>```

Title: How to check for cycles in a graph?

Body:
My code works fine but fails check50 test for skipping pairs when creating cycles. The logic I use to check for cycles is that before creating an edge from winner to loser I go back the edges from the winner and check if it ever reaches the loser. If it does, it means it'll create a cycle so the edge is skipped but It doesn't work. My logic could be wrong too, if so let me know. Here's my code-

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

// Max number of candidates
#define MAX 9

// preferences[i][j] is number of voters who prefer i over j
int preferences[MAX][MAX];

// locked[i][j] means i is locked in over j
bool locked[MAX][MAX];

// Each pair has a winner, loser
typedef struct
{
    int winner;
    int loser;
}
pair;

// Array of candidates
string candidates[MAX];
pair pairs[MAX * (MAX - 1) / 2];

int pair_count;
int candidate_count;

// Function prototypes
bool vote(int rank, string name, int ranks[]);
void record_preferences(int ranks[]);
void add_pairs(void);
void sort_pairs(void);
void lock_pairs(void);
void print_winner(void);
bool check_cycle(int n, int m);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: tideman [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i] = argv[i + 1];
    }

    // Clear graph of locked in pairs
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            locked[i][j] = false;
        }
    }

    pair_count = 0;
    int voter_count = get_int("Number of voters: ");

    // Query for votes
    for (int i = 0; i < voter_count; i++)
    {
        // ranks[i] is voter's ith preference
        int ranks[candidate_count];

        // Query for each rank
        for (int j = 0; j < candidate_count; j++)
        {
            string name = get_string("Rank %i: ", j + 1);

            if (!vote(j, name, ranks))
            {
                printf("Invalid vote.\n");
                return 3;
            }
        }

        record_preferences(ranks);

        printf("\n");
    }

    add_pairs();
    sort_pairs();
    lock_pairs();
    print_winner();
    return 0;
}

// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(candidates[i], name) == 0)
        {
            ranks[rank] = i;
            return true;
        }
    }

    return false;
}

// Update preferences given one voter's ranks
void record_preferences(int ranks[])
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 1; j < candidate_count - i; j++)
        {
            preferences[ranks[i]][ranks[i + j]]++;
        }
    }

    return;
}

// Record pairs of candidates where one is preferred over the other
void add_pairs(void)
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            if (preferences[i][j] > preferences[j][i])
            {
                pairs[pair_count].winner = i;
                pairs[pair_count].loser = j;
                pair_count++;
            }
        }
    }

    return;
}

// Sort pairs in decreasing order by strength of victory
void sort_pairs(void)
{
    // TODO
    pair k;
    for (int i = 0; i < pair_count; i++)
    {
        for (int j = i + 1; j < pair_count; j++)
        {
            if (preferences[pairs[i].winner][pairs[i].loser] < preferences[pairs[j].winner][pairs[j].loser])
            {
                //memcpy
                k = pairs[i];
                pairs[i] = pairs[j];
                pairs[j] = k;
            }
        }
    }

    return;
}

// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
    // TODO
    for (int i = 0; i < pair_count; i++)
    {
        if (!check_cycle(pairs[i].winner, pairs[i].loser))
        {
            locked[pairs[i].winner][pairs[i].loser] = true;
        }
    }
    return;
}

// Print the winner of the election
void print_winner(void)
{
    // TODO
    for (int i = 0; i < candidate_count; i++)
    {
        bool source = true;

        for (int j = 0; j < candidate_count; j++)
        {
            if (locked[j][i] == true)
            {
                source = false;
                break;
            }
        }

        if (source == true)
        {
            printf("%s\n", candidates[i]);
        }
    }

    return;
}

//checking for cycle
bool check_cycle(int n, int m)
{
    if (locked[m][n] == true)
    {
        return true;
    }

    for (int i = 0; i < candidate_count; i++)
    {
        if (locked[i][n] == true)
        {
            check_cycle(i, m);
        }
    }
    return false;
}

Body:
I don't think some of the previous answers gave the right answer.

For n candidates, there exists the ith candidate that no
arrow pointing to her or him if and only if the ith column of the
"locked" table is all false. In such a situation, no circle (a
circle with n nodes) can be drawn if the ith column must be a node.

However, this doesn't guarantee that there are no other smaller circles. If we make the "locked" table one-size smaller (i.e. remove
the nth candidate, now we will have a (n-1) *(n-1) "locked"
table. Like what we did in step(1), we can make sure that a circle of n-1 nodes is also impossible. By repeating this processing, no circle (any size) is possible.

We can check it by using recursion.

If you don't check whether a smaller circle is possible: you will have an error like this:

lock_pairs skips middle pair if it creates a cycle
      lock_pairs did not correctly lock all non-cyclical pairs

Here is the code:

bool is_circle (bool locked_array[MAX][MAX], int candi_count)
{
    //check the basic case
    //if there is only one node of course it doesn't form a circle
    if (candi_count == 1)
    {
        return false;
    }

    //recursively check whether the smaller locked_array with n-1 candidate form a circle
    //if the smaller one have a circle
    //this mean a middle pair create a circle if added into the "locked" table
    if (!is_circle(locked_array, candi_count - 1))
    {
        //if the one-size smaller "locked" table doesn't have a circle
        //check whether adding a new candidate forms a circle

        //if there is a column that is all false's after adding a new candidate
        //then it must not introduce a circle in this step
        for (int j = 0; j < candi_count; j++)
        {
            //a indicator variable for check whether a column has a true value;
            bool true_in_column = false;

            for (int i = 0; i < candi_count; i++)
            {
                if (locked_array[i][j] == true)
                {
                    true_in_column = true;
                }
            }

            //if there is a column doesn't have a true value then not circle is create at this step
            if (true_in_column == false)
            {
                return false;
            }
        }

        //if we cannot find such a column then the graph represented by current locked array
        //must have a circle
        return true;

    }

    //the smaller "locked" table forms a circle
    else
    {
        return true;
    }

}


问:
How to read logcat continuously and write into the internal storage file?
Reading logcat continuously and write into the internal storage for this i tried the below code.

```<code>public class LogCatTask extends AsyncTask<Void, String, Void> {
    public AtomicBoolean run = new AtomicBoolean(true);

    @Override
    protected Void doInBackground(Void... params) {
        try {

            //create text file in SDCard
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
            dir.mkdirs();
            File file = new File(dir, "logcat.txt");

            Runtime.getRuntime().exec("logcat -c");
            Process process = Runtime.getRuntime().exec("logcat -f "+file);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder log = new StringBuilder();
            String line = "";
            Log.e("log cat task...","while...run.get()."+run.get());
            while (run.get()) {
                line = bufferedReader.readLine();
                //Log.e("log cat task...","while...out.");
                if (line != null) {
                    Log.e("log cat task...","while....");
                    log.append(line);
                    //publishProgress(log.toString());

                    //to write logcat in text file
                    FileOutputStream fOut = new FileOutputStream(file);
                    OutputStreamWriter osw = new OutputStreamWriter(fOut);

                    // Write the string to the file
                    osw.write(log.toString());
                    osw.flush();
                    osw.close();
                }
                line = null;
                Thread.sleep(10);
                //Log.e("log cat task...","while...out.");
            }
            //Log.e("log cat task...","ouet....while....");
        }
        catch(Exception ex){

        }
        return null;
    }
}
</code>```

once the above code runs,it read the logcat and write into storage but upto some part of the log only it reads.it is not reading the continuos.How to read the logcat continuous?

答:
Here's a working code snippet

```<code>    try {
        Process process = Runtime.getRuntime().exec("logcat");
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

        StringBuilder log=new StringBuilder();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            // do what you want with the line you just read
            // you're in an infinite loop continuously reading the log,
            // you might want to add some mechanism to break out of it
        }
    }
    catch (IOException  e) {
        fail("failed to get log");
    }
</code>```

Your code is overly complicated and prone to race conditions.  For example, is the logcat -c guaranteed to complete before the logcat -f command. The -f command redirects output to a file, and your logic is also trying to write to that same file; that's very problematic. I've noticed that some of the logcat options such as "-T" doesn't work programmatically. Maybe the "-f" option also has problems.  If you only want to read the log file up to the current time use "logcat -d".

Body:
Reading logcat continuously and write into the internal storage for this i tried the below code.

public class LogCatTask extends AsyncTask<Void, String, Void> {
    public AtomicBoolean run = new AtomicBoolean(true);

    @Override
    protected Void doInBackground(Void... params) {
        try {

            //create text file in SDCard
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
            dir.mkdirs();
            File file = new File(dir, "logcat.txt");

            Runtime.getRuntime().exec("logcat -c");
            Process process = Runtime.getRuntime().exec("logcat -f "+file);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder log = new StringBuilder();
            String line = "";
            Log.e("log cat task...","while...run.get()."+run.get());
            while (run.get()) {
                line = bufferedReader.readLine();
                //Log.e("log cat task...","while...out.");
                if (line != null) {
                    Log.e("log cat task...","while....");
                    log.append(line);
                    //publishProgress(log.toString());

                    //to write logcat in text file
                    FileOutputStream fOut = new FileOutputStream(file);
                    OutputStreamWriter osw = new OutputStreamWriter(fOut);

                    // Write the string to the file
                    osw.write(log.toString());
                    osw.flush();
                    osw.close();
                }
                line = null;
                Thread.sleep(10);
                //Log.e("log cat task...","while...out.");
            }
            //Log.e("log cat task...","ouet....while....");
        }
        catch(Exception ex){

        }
        return null;
    }
}

once the above code runs,it read the logcat and write into storage but upto some part of the log only it reads.it is not reading the continuos.How to read the logcat continuous?

Body:
Here's a working code snippet

    try {
        Process process = Runtime.getRuntime().exec("logcat");
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

        StringBuilder log=new StringBuilder();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            // do what you want with the line you just read
            // you're in an infinite loop continuously reading the log,
            // you might want to add some mechanism to break out of it
        }
    }
    catch (IOException  e) {
        fail("failed to get log");
    }

Your code is overly complicated and prone to race conditions.  For example, is the logcat -c guaranteed to complete before the logcat -f command. The -f command redirects output to a file, and your logic is also trying to write to that same file; that's very problematic. I've noticed that some of the logcat options such as "-T" doesn't work programmatically. Maybe the "-f" option also has problems.  If you only want to read the log file up to the current time use "logcat -d".


问:
What is the best location to initialise the DynamoDB instance (Lambda + NodeJS)?
I have a lambda-layer with the code below:

```<code>class PersonModel {
    constructor(tableName, values) {
        // some implementation
    }

    async save() {
        // some implementation

        return docClient.put({
            TableName: this.tableName,
            Item: this.values
        }).promise();
    }
}
</code>```

Inside my lambdas implementation I instantiate the PersonModel to implement a kind of CRUD. It's something like that:

```<code>exports.handler = async (request) => {
    const person = new PersonModel('profile', { name: 'John' });
    person.save().then(d => {
        return {
            statusCode: 200,
            body: 'Person saved!'
        }
    }).catch(err => {
        return {
            statusCode: 500,
            body: 'Something went wrong!'
        }
    });
};
</code>```

My question:

Where is the best place to put the DocumentClient instance?

Here (at the js file level):

```<code>const docClient = new AWS.DynamoDB.DocumentClient();
class PersonModel {
    constructor(tableName, values) {
        // some implementation
    }
    // etc...
</code>```

Or here (inside the object implementation - it will create one instance for each lambda call):

```<code>class PersonModel {
    constructor(tableName, values) {
        // some implementation
        this.docClient = new AWS.DynamoDB.DocumentClient();
    }
    // etc...
</code>```

Or is it better in somewhere else?

答:
From the DynamoDB docs:

AWS service clients should be instantiated in the initialization code, not in the handler. This allows AWS Lambda to reuse existing connections, for the duration of the container's lifetime.

In general, you do not need to explicitly manage connections or implement connection pooling because AWS Lambda manages this for you.

Also note that some services like Amazon RDS have a limit on the maximum number of open connections, so that is something to keep in mind if you ever work with such a service. DynamoDB should not have any such limits.

Body:
I have a lambda-layer with the code below:

class PersonModel {
    constructor(tableName, values) {
        // some implementation
    }

    async save() {
        // some implementation

        return docClient.put({
            TableName: this.tableName,
            Item: this.values
        }).promise();
    }
}

Inside my lambdas implementation I instantiate the PersonModel to implement a kind of CRUD. It's something like that:

exports.handler = async (request) => {
    const person = new PersonModel('profile', { name: 'John' });
    person.save().then(d => {
        return {
            statusCode: 200,
            body: 'Person saved!'
        }
    }).catch(err => {
        return {
            statusCode: 500,
            body: 'Something went wrong!'
        }
    });
};

My question:

Where is the best place to put the DocumentClient instance?

Here (at the js file level):

const docClient = new AWS.DynamoDB.DocumentClient();
class PersonModel {
    constructor(tableName, values) {
        // some implementation
    }
    // etc...

Or here (inside the object implementation - it will create one instance for each lambda call):

class PersonModel {
    constructor(tableName, values) {
        // some implementation
        this.docClient = new AWS.DynamoDB.DocumentClient();
    }
    // etc...

Or is it better in somewhere else?


问:
how do make my background image work with @media screen and ()
my @media code is not responding to any of the code i put into it like if i were trying to change the background color or background image it won't respond i am trying to change the position of a logo to fit mobile

.logo-Home-desktop a {
  background-image: url("../images/logo.png");
  background-size: 300px;
  background-repeat: no-repeat;
  position: absolute;
  height: 300px;
  width: 350px;
  text-indent: -99999999px;
  left: 50px;
  background-size: 340px;
  display: block;
}

@media screen and(max-width: 600px) {
  .logo-Home-desktop a {
    height: 250px;
    width: 250px;
  }
}

/* fix logo here to center in moble not responsive to media code */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav>
    <ul class="navigation">
      <li>Home</li>
      <li>Locations</li>
      <li>Contacts</li>
      <li class="logo-Home-desktop">logo</li>
    </ul>
  </nav>

</header></code>```

答:
Your media query is formated wrong.

```<code>@media only screen and (max-width: 600px)
</code>```

Is the correct format.

Also, make sure to have:

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0">
</code>```

in your head tag.

Body:
my @media code is not responding to any of the code i put into it like if i were trying to change the background color or background image it won't respond i am trying to change the position of a logo to fit mobile

.logo-Home-desktop a {
  background-image: url("../images/logo.png");
  background-size: 300px;
  background-repeat: no-repeat;
  position: absolute;
  height: 300px;
  width: 350px;
  text-indent: -99999999px;
  left: 50px;
  background-size: 340px;
  display: block;
}

@media screen and(max-width: 600px) {
  .logo-Home-desktop a {
    height: 250px;
    width: 250px;
  }
}

/* fix logo here to center in moble not responsive to media code */

Home

Locations

Contacts

logo

Body:
Your media query is formated wrong.

@media only screen and (max-width: 600px)

Is the correct format.

Also, make sure to have:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

in your head tag.


问:
How would I go about using NODEJS and AWS to create an application that saves uploaded PDF's and allows another user to view them
I am currently a Computer Science student working on an independent project. However, I am lost on how to go about using some of the technologies I know to hopefully create an application.

I wanted to use NodeJS to create a website that allowed certain users to use the website to upload PDF's to an admin user. This admin user would be able to see all of the uploads in chronological order and load the PDF of any user. [The example I would give would be to have a teacher collecting HW from his/her students. Each student should only be able to upload his/her homework while the teacher should be able to view all homeworks.

How exactly would I go about storing and working with these PDF uploads? Is it common to just store PDF's in an AWS database? Furthermore, how would I go about allowing the host user to save and access these PDF's?

Sorry for asking such a general question, but I was wondering if anyone had any insight on the technology/frameworks/libraries that would be helpful about going about this. The technology for full-stack that I am most familiar with is using NodeJS and EJS Html Pages to save data.

答:
use aws-sdk library to upload the files to s3. You will probably need to use the stream apis

for viewing you can either track the metadata of the files in a db, or if its not needed you can list the s3 bucket and show all the files. For each files you can supply a download link

before you deploy you can test it locally. To deploy you can use heroku
Important things to note is the keep the aws credentials secured at all cost!


问:
log4net is logging all levels, instead of what I've configured it to do
I have the level set to "INFO" but I'm seeing DEBUG events in the log.

Config

<?xml version="1.0"?>

<configuration>
    <configSections>

    </configSections>

    <log4net>
        <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
            <level value="INFO"/>
            <file value="Logs\Log.txt" />
            <appendToFile value="true" />
            <rollingStyle value="Size" />
            <maxSizeRollBackups value="10" />
            <maximumFileSize value="10MB" />
            <staticLogFileName value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
            </layout>
        </appender>

        <root>
            <appender-ref ref="RollingFileAppender"/>
        </root>
    </log4net>
</configuration>
```

<h3>Code</h3>

```private ILog Log { get; set; }

static Program()
{
    XmlConfigurator.Configure();
    //...
    this.Log.Info("Started in RunOnce mode.");
}
```

答:
I typically declare/initialize my ILog with:

```<code>private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
</code>```

and then define the logger in the web config: (include full namespace of Program)

```<code><logger name="Program">
  <level value="Info"/>
  <appender-ref ref="RollingFileAppender"/>
</logger>
</code>```

Body:
I have the level set to "INFO" but I'm seeing DEBUG events in the log.

Config

<?xml version="1.0"?>

<configuration>
    <configSections>

    </configSections>

    <log4net>
        <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
            <level value="INFO"/>
            <file value="Logs\Log.txt" />
            <appendToFile value="true" />
            <rollingStyle value="Size" />
            <maxSizeRollBackups value="10" />
            <maximumFileSize value="10MB" />
            <staticLogFileName value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
            </layout>
        </appender>

        <root>
            <appender-ref ref="RollingFileAppender"/>
        </root>
    </log4net>
</configuration>

Code

private ILog Log { get; set; }

static Program()
{
    XmlConfigurator.Configure();
    //...
    this.Log.Info("Started in RunOnce mode.");
}

Body:
I typically declare/initialize my ILog with:

private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

and then define the logger in the web config: (include full namespace of Program)

<logger name="Program">
  <level value="Info"/>
  <appender-ref ref="RollingFileAppender"/>
</logger>


问:
How to dynamically add a pair of text input and textarea in Angular 8?
The following piece of html is from our angular page where a user is supposed to introduce a question and its respective answer (something like Q&A thing).

```<code> <mat-card>
           <button mat-stroked-button color="primary" style="margin-right: 20px;">
               Add a new Q & A pair
            </button>
            </mat-card>
            <div *ngFor="let qna of interview.qnas">
                <mat-card id="{{qna.id}}" style="margin-bottom: 25px;">
                    <mat-form-field>
                        <input matInput type="text" class="form-control" placeholder="Interview question" required [(ngModel)]="qna.question" name="question">
                    </mat-form-field>
                    <mat-form-field>
                        <textarea matInput rows="5" class="form-control" placeholder="Ideal answer from the talent" [(ngModel)]="qna.answer" name="answer"></textarea>
                    </mat-form-field>
                    <button mat-stroked-button color="warn">
                        Remove this
                    </button>
                </mat-card>
            </div>
</code>```

As you can see in the HTML, there are two buttons in there, the first button is supposed to let users add a new pair of  and  and the 2nd one is supposed to remove a pair. I can probably come up with a solution for removing the pair but I am not so sure how to implement adding a new Q&A pair on the fly when the user clicks on it. Also, please consider that we have two-way binding in place too.

答:
Try this : </p>

```<code> <mat-card>
           <button mat-stroked-button color="primary" style="margin-right: 20px;">
               Add a new Q & A pair
            </button>
            </mat-card>
            <div *ngFor="let qna of interview.qnas">
                <mat-card id="{{qna.id}}" style="margin-bottom: 25px;">
                    <mat-form-field>
                        <input matInput type="text" class="form-control" placeholder="Interview question" required value="{{qna.question}}" name="question">
                    </mat-form-field>
                    <mat-form-field>
                        <textarea matInput rows="5" class="form-control" placeholder="Ideal answer from the talent"  value="{{qna.answer}}" name="answer"></textarea>
                    </mat-form-field>
                    <button mat-stroked-button color="warn">
                        Remove this
                    </button>
                </mat-card>
            </div>
</code>```

Body:
The following piece of html is from our angular page where a user is supposed to introduce a question and its respective answer (something like Q&A thing).

 <mat-card>
           <button mat-stroked-button color="primary" style="margin-right: 20px;">
               Add a new Q & A pair
            </button>
            </mat-card>

                <mat-card id="{{qna.id}}" style="margin-bottom: 25px;">
                    <mat-form-field>
                        <input matInput type="text" class="form-control" placeholder="Interview question" required [(ngModel)]="qna.question" name="question">
                    </mat-form-field>
                    <mat-form-field>
                        <textarea matInput rows="5" class="form-control" placeholder="Ideal answer from the talent" [(ngModel)]="qna.answer" name="answer"></textarea>
                    </mat-form-field>
                    <button mat-stroked-button color="warn">
                        Remove this
                    </button>
                </mat-card>

As you can see in the HTML, there are two buttons in there, the first button is supposed to let users add a new pair of  and  and the 2nd one is supposed to remove a pair. I can probably come up with a solution for removing the pair but I am not so sure how to implement adding a new Q&A pair on the fly when the user clicks on it. Also, please consider that we have two-way binding in place too.

Body:
Try this :

 <mat-card>
           <button mat-stroked-button color="primary" style="margin-right: 20px;">
               Add a new Q & A pair
            </button>
            </mat-card>
            <div *ngFor="let qna of interview.qnas">
                <mat-card id="{{qna.id}}" style="margin-bottom: 25px;">
                    <mat-form-field>
                        <input matInput type="text" class="form-control" placeholder="Interview question" required value="{{qna.question}}" name="question">
                    </mat-form-field>
                    <mat-form-field>
                        <textarea matInput rows="5" class="form-control" placeholder="Ideal answer from the talent"  value="{{qna.answer}}" name="answer"></textarea>
                    </mat-form-field>
                    <button mat-stroked-button color="warn">
                        Remove this
                    </button>
                </mat-card>
            </div>


问:
What does it mean by a "pointer points to another memory location"?
I know that a pointer variable stores the memory address of another variable. But what does it mean by "Pointer points to another memory location"? What does it mean by "pointer points to..."?

答:
Fundamentally, a variable is an association between a name and a location in memory. It can be more complicated than that in other languages, and other information is usually associated with the variable (e.g. a type), but this is not relevant here.

A pointer variable is a variable (a name that references some area of memory), but what's in that area of memory? What's the pointer itself? Well, it's a memory address, a way of referencing another memory location. Rather than saying "the pointer has for value this other memory location", we say the pointer references or points to this other memory location.

We might have a name for that other memory location. That would make it a variable. As such, we also say the pointer references or points to this other variable.

In the following, we have a pointer p that points to variable i:

int i = 1000;
int *p = &i;
```

<p>We might have this memory:</p>

<pre class="lang-none prettyprint-override"><code>p at addr 0x1122       |      ⋮       |
i at addr 0x3344       +--------------+
                       |       0x3344 | 0x1122
                       +--------------+
                       |      ⋮       |
                       +--------------+
                       |         1000 | 0x3344
                       +--------------+
                       |      ⋮       |
</code>```

So what's the difference between the following two statements:

int *q = p;
int j = *p;
```

<p>In the first, we are copying the pointer itself, the memory address. </p>

<p>In the second, we are indirectly accessing <code>i</code>. We are telling C to <em>dereference</em> the pointer, which means to access that to which the pointer points. This is <code>i</code>.</p>

<p>We might have this memory:</p>

<pre class="lang-none prettyprint-override"><code>p at addr 0x1122       |      ⋮       |
i at addr 0x3344       +--------------+
q at addr 0x5566       |       0x3344 | 0x1122
j at addr 0x7788       +--------------+
                       |      ⋮       |
                       +--------------+
                       |         1000 | 0x3344
                       +--------------+
                       |      ⋮       |
                       +--------------+
                       |       0x3344 | 0x5566
                       +--------------+
                       |      ⋮       |
                       +--------------+
                       |         1000 | 0x7788
                       +--------------+
                       |      ⋮       |
</code>```

What happens to the others if you change one of *p, *q, i and j? I'll let you hypothesize and experiment :)

Body:
Fundamentally, a variable is an association between a name and a location in memory. It can be more complicated than that in other languages, and other information is usually associated with the variable (e.g. a type), but this is not relevant here.

A pointer variable is a variable (a name that references some area of memory), but what's in that area of memory? What's the pointer itself? Well, it's a memory address, a way of referencing another memory location. Rather than saying "the pointer has for value this other memory location", we say the pointer references or points to this other memory location.

We might have a name for that other memory location. That would make it a variable. As such, we also say the pointer references or points to this other variable.

In the following, we have a pointer p that points to variable i:

int i = 1000;
int *p = &i;

We might have this memory:

p at addr 0x1122       |      ⋮       |
i at addr 0x3344       +--------------+
                       |       0x3344 | 0x1122
                       +--------------+
                       |      ⋮       |
                       +--------------+
                       |         1000 | 0x3344
                       +--------------+
                       |      ⋮       |

So what's the difference between the following two statements:

int *q = p;
int j = *p;

In the first, we are copying the pointer itself, the memory address.

In the second, we are indirectly accessing i. We are telling C to dereference the pointer, which means to access that to which the pointer points. This is i.

We might have this memory:

p at addr 0x1122       |      ⋮       |
i at addr 0x3344       +--------------+
q at addr 0x5566       |       0x3344 | 0x1122
j at addr 0x7788       +--------------+
                       |      ⋮       |
                       +--------------+
                       |         1000 | 0x3344
                       +--------------+
                       |      ⋮       |
                       +--------------+
                       |       0x3344 | 0x5566
                       +--------------+
                       |      ⋮       |
                       +--------------+
                       |         1000 | 0x7788
                       +--------------+
                       |      ⋮       |

What happens to the others if you change one of *p, *q, i and j? I'll let you hypothesize and experiment :)


问:
How to speed up For loops in For loops in a batch file
I'm running the following in a batch file with an android device connected to pull some app data and its working however, I replete each code snip below for system apps and for 3rd party apps, and it's taking a long time due to what I think is the multiple FOR loops. </p>

<p>Can anyone recommend another way that would speed this up?  </p>

```<code>for /f "tokens=1 " %%a in ('adb.exe shell pm list users ^| grep.exe UserInfo ^| awk.exe -F "(UserInfo{)" "{print $2}" ^| awk.exe -F "(:)" "{print $1}"') do (
    echo User: %%a >> %FILENAME28%
    for /f "tokens=*" %%b in ('adb.exe shell pm list packages -3 --user %%a ^| awk.exe -F "(package:)" "{print $2}"') do (
        for /f "tokens=*" %%c in ('adb.exe shell dumpsys package %%b ^| grep.exe -m1 versionName ^| awk.exe -F "(versionName=)" "{print $2}"') do set vversionName=%%c
        for /f "tokens=*" %%d in ('adb.exe shell dumpsys package %%b ^| grep.exe -m1 installerPackageName ^| awk.exe -F "(installerPackageName=)" "{print $2}"') do set vversionStore=%%d
        for /f "tokens=*" %%e in ('adb.exe shell pm dump %%b ^| grep.exe codePath ^| awk.exe -F "(codePath=)" "{print $2}"') do set CodePath=%%e
        echo App: %%b    Version: !vversionName!    Installed Via: !vversionStore!    Install Path: !CodePath! >> %FILENAME28%
    )
)
</code>```

答:
With regards to my comment:

(for /f "tokens=1 " %%a in ('adb.exe shell pm list users ^| grep.exe UserInfo ^| awk.exe -F "(UserInfo{)" "{print $2}" ^| awk.exe -F "(:)" "{print $1}"') do (
    echo User: %%a
    for /f "tokens=*" %%b in ('adb.exe shell pm list packages -3 --user %%a ^| awk.exe -F "(package:)" "{print $2}"') do (
        for /f "tokens=*" %%c in ('adb.exe shell dumpsys package %%b ^| grep.exe -m1 versionName ^| awk.exe -F "(versionName=)" "{print $2}"') do set vversionName=%%c
        for /f "tokens=*" %%d in ('adb.exe shell dumpsys package %%b ^| grep.exe -m1 installerPackageName ^| awk.exe -F "(installerPackageName=)" "{print $2}"') do set vversionStore=%%d
        for /f "tokens=*" %%e in ('adb.exe shell pm dump %%b ^| grep.exe codePath ^| awk.exe -F "(codePath=)" "{print $2}"') do set CodePath=%%e
        echo App: %%b    Version: !vversionName!    Installed Via: !vversionStore!    Install Path: !CodePath!
    )
))>>"%FILENAME28%"
```

If filename28 is already doublequoted when defined, remove the doublequotes from the point of redirection.

Body:
I'm running the following in a batch file with an android device connected to pull some app data and its working however, I replete each code snip below for system apps and for 3rd party apps, and it's taking a long time due to what I think is the multiple FOR loops.

Can anyone recommend another way that would speed this up?

for /f "tokens=1 " %%a in ('adb.exe shell pm list users ^| grep.exe UserInfo ^| awk.exe -F "(UserInfo{)" "{print $2}" ^| awk.exe -F "(:)" "{print $1}"') do (
    echo User: %%a >> %FILENAME28%
    for /f "tokens=*" %%b in ('adb.exe shell pm list packages -3 --user %%a ^| awk.exe -F "(package:)" "{print $2}"') do (
        for /f "tokens=*" %%c in ('adb.exe shell dumpsys package %%b ^| grep.exe -m1 versionName ^| awk.exe -F "(versionName=)" "{print $2}"') do set vversionName=%%c
        for /f "tokens=*" %%d in ('adb.exe shell dumpsys package %%b ^| grep.exe -m1 installerPackageName ^| awk.exe -F "(installerPackageName=)" "{print $2}"') do set vversionStore=%%d
        for /f "tokens=*" %%e in ('adb.exe shell pm dump %%b ^| grep.exe codePath ^| awk.exe -F "(codePath=)" "{print $2}"') do set CodePath=%%e
        echo App: %%b    Version: !vversionName!    Installed Via: !vversionStore!    Install Path: !CodePath! >> %FILENAME28%
    )
)

Body:
With regards to my comment:

(for /f "tokens=1 " %%a in ('adb.exe shell pm list users ^| grep.exe UserInfo ^| awk.exe -F "(UserInfo{)" "{print $2}" ^| awk.exe -F "(:)" "{print $1}"') do (
    echo User: %%a
    for /f "tokens=*" %%b in ('adb.exe shell pm list packages -3 --user %%a ^| awk.exe -F "(package:)" "{print $2}"') do (
        for /f "tokens=*" %%c in ('adb.exe shell dumpsys package %%b ^| grep.exe -m1 versionName ^| awk.exe -F "(versionName=)" "{print $2}"') do set vversionName=%%c
        for /f "tokens=*" %%d in ('adb.exe shell dumpsys package %%b ^| grep.exe -m1 installerPackageName ^| awk.exe -F "(installerPackageName=)" "{print $2}"') do set vversionStore=%%d
        for /f "tokens=*" %%e in ('adb.exe shell pm dump %%b ^| grep.exe codePath ^| awk.exe -F "(codePath=)" "{print $2}"') do set CodePath=%%e
        echo App: %%b    Version: !vversionName!    Installed Via: !vversionStore!    Install Path: !CodePath!
    )
))>>"%FILENAME28%"

If filename28 is already doublequoted when defined, remove the doublequotes from the point of redirection.


问:
Patch Planner Tasks Details Error - Bad request with Base-64 string Error
I am trying to call https://graph.microsoft.com/v1.0/planner/tasks/{{taskId}}/details with this request:

```<code>{
    "checklist": {
        "552f6163-e7d3-4e31-9015-577b0e6cc997": {
            "@odata.type": "microsoft.graph.plannerChecklistItem",
            "title": "Update task details",
            "isChecked": false
        }
    }
}
</code>```

I have the if-match header set properly, with the etag from the tasks. I get the below 400 Bad Request response when I run the query:

```<code>{
    "error": {
        "code": "",
        "message": "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. ",
        "innerError": {
            "request-id": "c9781050-e409-4b88-9d7e-0a57dcec1f82",
            "date": "2020-05-29T21:26:17"
        }
    }
}
</code>```

I have tried random GUIDs, and base-64 encoded strings, to no avail. I also tried to download the Postman Environment, but I get the same error from there. Any help or guidance would be hugely appreciated.

Thanks for your time.
B.

答:
You are getting this error because the If-Match header has an invalid value. When viewed by tools, sometimes tools include escape characters, which needs to be adjusted when making queries manually through Graph Explorer or Postman. Correct If-Match header value looks like:

```<code>W/"Base64EncodedStuff"
</code>```

Aside from that issue, your query appears correct.

Body:
I am trying to call https://graph.microsoft.com/v1.0/planner/tasks/{{taskId}}/details with this request:

{
    "checklist": {
        "552f6163-e7d3-4e31-9015-577b0e6cc997": {
            "@odata.type": "microsoft.graph.plannerChecklistItem",
            "title": "Update task details",
            "isChecked": false
        }
    }
}

I have the if-match header set properly, with the etag from the tasks. I get the below 400 Bad Request response when I run the query:

{
    "error": {
        "code": "",
        "message": "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. ",
        "innerError": {
            "request-id": "c9781050-e409-4b88-9d7e-0a57dcec1f82",
            "date": "2020-05-29T21:26:17"
        }
    }
}

I have tried random GUIDs, and base-64 encoded strings, to no avail. I also tried to download the Postman Environment, but I get the same error from there. Any help or guidance would be hugely appreciated.

Thanks for your time.
B.

Body:
You are getting this error because the If-Match header has an invalid value. When viewed by tools, sometimes tools include escape characters, which needs to be adjusted when making queries manually through Graph Explorer or Postman. Correct If-Match header value looks like:

W/"Base64EncodedStuff"

Aside from that issue, your query appears correct.


问:
Best practice for storing external API secrets in server using AWS?
I built an application to integrate various financial services for my company. We access brittle, old legacy-esque external API's to pull purchases and things of nature. The server should update our transaction history every morning automatically through these API's. This information is very sensitive. I want to avoid storing secrets on the server or forcing the user to input credentials. I came up with an AWS-based solution. I'd like both advice on its implementation and suggestions on feasible alternatives.

I want to use Lambda or some other AWS service to both store the keys and retrieve the necessary information. The primary server can then either access the information through an API or be sent data from AWS. This secondary server should be as secure as possible, with no SSH or remote access except through Amazon's browser interface. I'd like to use certificates to retrieve the information from this cloud server at some point, if that's the implementation I end up going with.

答:
For secrets you'd want to be looking at Secrets Manager. The contents are natively encrypted via KMS so rest assured they'll be encrypted.

Any interaction is done via API, so it would be authenticated via IAM