问:
Github action No event triggers defined in `on`
I have created a pipeline and i want to trigger every time I push on any branch

There is my default.yml :

```<code>name: default

on:
  push:
    branches:
    - '*'

jobs:
  build:
    runs-on: macOS-latest

    steps:
    - uses: actions/checkout@v1
    - name: CocoaPod Install
      run: pod install
    - name: Force xcode version
      run: sudo xcode-select -switch /Applications/Xcode_11.2.1.app
    - name: Build
      run: ./pipelines.sh build
</code>```

When i push this on github, I have this error

No event triggers defined in on

答: I got this error from a commit where I have only edited the workflow yaml file but nothing else. It was triggered normally after editing and commiting other files.</p>

Body:
I have created a pipeline and i want to trigger every time I push on any branch

There is my default.yml :

name: default

on:
  push:
    branches:
    - '*'

jobs:
  build:
    runs-on: macOS-latest

    steps:
    - uses: actions/checkout@v1
    - name: CocoaPod Install
      run: pod install
    - name: Force xcode version
      run: sudo xcode-select -switch /Applications/Xcode_11.2.1.app
    - name: Build
      run: ./pipelines.sh build

When i push this on github, I have this error

No event triggers defined in on


来源: stackexchange

问:
Python xmltodict shows inconsistent behaviour in XML arrays
I seen some, IMHO, inconsistent behaviour in Python xmltodoct.parse function.

When an array has only 1 element, it returns an iterator with the child-elements

When an array has more than 1 element, it returns an iterator with the elements in OrderedDict

See the example below:

import xmltodict

if __name__ == "__main__":
    xml01 = """

                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>

    """

    xd = xmltodict.parse(xml01)
    print(xd)
    for x in xd['A']['C']:
        print(f"xml01: {x}")

    xml02 = """

                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>
                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>

    """

    xd = xmltodict.parse(xml02)
    for x in xd['A']['C']:
        print(f"xml02: {x}")
```
<p>The output is:</p>
<pre class="lang-sh prettyprint-override"><code>xml01: D
xml01: E
xml02: OrderedDict([('D', 'DDDD'), ('E', 'EEEE')])
xml02: OrderedDict([('D', 'DDDD'), ('E', 'EEEE')])
</code>```

I would expect that the output of the first iterator is:

xml01: OrderedDict([('D', 'DDDD'), ('E', 'EEEE')])
```

Now you need to do some type checking on the returned values of the iterator do know if there's one or more elements.
And with more elements you need to do a new loop.

I'm curious what Python experts are thinking of this and what their solution would be.

答:
You are right.

And if you are asking my opinion, then I think it should be changed such to have xml01 return a list with one child.

Though according to https://github.com/martinblech/xmltodict/issues/14, the devs are aware of this but will not fix it.

The accepted workaround is to add force_list as a parameter to the parse, thus forcing a list of OrderedDict for the child element.

In your case, this would look like this:

import xmltodict

if __name__ == "__main__":
    xml01 = """

                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>

    """

    xd = xmltodict.parse(xml01, force_list=set('C'))
    for x in xd['A']['C']:
        print(f"xml01: {x}")

    xml02 = """

                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>
                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>

    """

    xd = xmltodict.parse(xml02, force_list=set('C'))
    for x in xd['A']['C']:
        print(f"xml02: {x}")´

```

There is also a proposal to overwrite the dict_constructor to use defaultdict.

But you can browse this issue if that's the way you want to go with it.

ContentLicense: CC BY-SA 4.0

Body:
I seen some, IMHO, inconsistent behaviour in Python xmltodoct.parse function.

When an array has only 1 element, it returns an iterator with the child-elements

When an array has more than 1 element, it returns an iterator with the elements in OrderedDict

See the example below:

import xmltodict

if __name__ == "__main__":
    xml01 = """

                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>

    """

    xd = xmltodict.parse(xml01)
    print(xd)
    for x in xd['A']['C']:
        print(f"xml01: {x}")

    xml02 = """

                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>
                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>

    """

    xd = xmltodict.parse(xml02)
    for x in xd['A']['C']:
        print(f"xml02: {x}")

The output is:

xml01: D
xml01: E
xml02: OrderedDict([('D', 'DDDD'), ('E', 'EEEE')])
xml02: OrderedDict([('D', 'DDDD'), ('E', 'EEEE')])

I would expect that the output of the first iterator is:

xml01: OrderedDict([('D', 'DDDD'), ('E', 'EEEE')])

Now you need to do some type checking on the returned values of the iterator do know if there's one or more elements.
And with more elements you need to do a new loop.

I'm curious what Python experts are thinking of this and what their solution would be.

Body:
You are right.

And if you are asking my opinion, then I think it should be changed such to have xml01 return a list with one child.

Though according to https://github.com/martinblech/xmltodict/issues/14, the devs are aware of this but will not fix it.

The accepted workaround is to add force_list as a parameter to the parse, thus forcing a list of OrderedDict for the child element.

In your case, this would look like this:

import xmltodict

if __name__ == "__main__":
    xml01 = """
            <A>
                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>
            </A>
    """

    xd = xmltodict.parse(xml01, force_list=set('C'))
    for x in xd['A']['C']:
        print(f"xml01: {x}")

    xml02 = """
            <A>
                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>
                    <C>
                        <D>DDDD</D>
                        <E>EEEE</E>
                    </C>
            </A>
    """

    xd = xmltodict.parse(xml02, force_list=set('C'))
    for x in xd['A']['C']:
        print(f"xml02: {x}")´

There is also a proposal to overwrite the dict_constructor to use defaultdict.

But you can browse this issue if that's the way you want to go with it.


问:
Group array of string arrays with LINQ
I have array like this, values are string:

```<code>var arr1 = new [] { "H", "item1", "item2" };
var arr2 = new [] { "T", "thing1", "thing2" };
var arr3 = new [] { "T", "thing1", "thing2" };
var arr4 = new [] { "END", "something" };
var arr5 = new [] { "H", "item1", "item2" };
var arr6 = new [] { "T", "thing1", "thing2" };
var arr7 = new [] { "T", "thing1", "thing2" };
var arr8 = new [] { "END", "something" };

var allArrays = new [] { arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8 };
</code>```

I need to group this in to a new array of arrays, so that one array has arrays that start with H or T. The END records (not included in the results) are the delimiters between each section; each new array starts after an END array.

In the end I would like to have somethng like this:

```<code>[
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
]
</code>```

I know how I can do this with for each loop, but I'm looking for a cleaner way, possibly using linq. All suggestions are much valued, thank you!

答:
Here is a simple implementation.</p>
```<code>public static void Main(string[] args)
{
    var data = ConvertToArrayOfArray(arr1, arr2, arr3, arrr4, arr5, arr6, arr7, arr8);
}

private string[][] ConvertToArrayOfArray(params string[][] arrs)
{
    List<string[]> yoList = new List<string[]>();
    arrs.ToList().ForEach(x =>
    {
        if(!x[0] == "END") yoList.Add(x);
    });
    return yoList.ToArray();
}
</code>```

Title: Group array of string arrays with LINQ

Body:
I have array like this, values are string:

var arr1 = new [] { "H", "item1", "item2" };
var arr2 = new [] { "T", "thing1", "thing2" };
var arr3 = new [] { "T", "thing1", "thing2" };
var arr4 = new [] { "END", "something" };
var arr5 = new [] { "H", "item1", "item2" };
var arr6 = new [] { "T", "thing1", "thing2" };
var arr7 = new [] { "T", "thing1", "thing2" };
var arr8 = new [] { "END", "something" };

var allArrays = new [] { arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8 };

I need to group this in to a new array of arrays, so that one array has arrays that start with H or T. The END records (not included in the results) are the delimiters between each section; each new array starts after an END array.

In the end I would like to have somethng like this:

[
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
[ [H, item1, item2], [T, thing1, thing2], [T, thing1, thing2] ]
]

I know how I can do this with for each loop, but I'm looking for a cleaner way, possibly using linq. All suggestions are much valued, thank you!

Body:
Here is a simple implementation.

public static void Main(string[] args)
{
    var data = ConvertToArrayOfArray(arr1, arr2, arr3, arrr4, arr5, arr6, arr7, arr8);
}

private string[][] ConvertToArrayOfArray(params string[][] arrs)
{
    List<string[]> yoList = new List<string[]>();
    arrs.ToList().ForEach(x =>
    {
        if(!x[0] == "END") yoList.Add(x);
    });
    return yoList.ToArray();
}


问:
Hive TimeStamp Convertion from GreenPlum Code
Please help me to convert below Greenplum code to Hive supported one.

GP:

```<code>date_trunc('second', now())::timestamp without time zone load_time
</code>```

Expecting to convert similar operation and output in hive

答:
```<code>select timestamp(substr(current_timestamp,1,19)) as load_time
</code>```

Result:

```<code>2022-02-08 13:18:27.0
</code>```

substr() leaves only seconds, works as truncate.
and timestampt() - to convert from string to timestamp datatype.

Body:
Please help me to convert below Greenplum code to Hive supported one.

GP:

date_trunc('second', now())::timestamp without time zone load_time

Expecting to convert similar operation and output in hive

Body:
select timestamp(substr(current_timestamp,1,19)) as load_time

Result:

2022-02-08 13:18:27.0

substr() leaves only seconds, works as truncate.
and timestampt() - to convert from string to timestamp datatype.


问:
Perl backticks using bash
In Perl, the default shell to execute backticks is sh. I'd like to switch to use bash for its richer syntax. So far I found that the suggested solution is

```<code>`bash -c \"echo a b\"`
</code>```

The apparent drawback is that the escaped double quotes, which means I will have difficulty to use double quotes in my bash args. For example, if I wanted to run commands requiring double quotes in bash

```<code>echo "a'b"
</code>```

The above method will be very awkward.

Perl's system() call has a solution for this problem: to use ARRAY args,

```<code>system("bash", "-c", qq(echo "a'b"));
</code>```

This keeps my original bash command unmodified, and almost always.

I'd like to use ARRAY args in backticks too. Is it possible?

答:
You can change the shell used by perl :</p>
```<code>$ENV{PERL5SHELL} = "bash";
my $out = qx{echo "Hello ' world from bash \$BASH_VERSION"};
print($out);
</code>```

Title: Perl backticks using bash

Body:
In Perl, the default shell to execute backticks is sh. I'd like to switch to use bash for its richer syntax. So far I found that the suggested solution is

`bash -c \"echo a b\"`

The apparent drawback is that the escaped double quotes, which means I will have difficulty to use double quotes in my bash args. For example, if I wanted to run commands requiring double quotes in bash

echo "a'b"

The above method will be very awkward.

Perl's system() call has a solution for this problem: to use ARRAY args,

system("bash", "-c", qq(echo "a'b"));

This keeps my original bash command unmodified, and almost always.

I'd like to use ARRAY args in backticks too. Is it possible?

Body:
You can change the shell used by perl :

$ENV{PERL5SHELL} = "bash";
my $out = qx{echo "Hello ' world from bash \$BASH_VERSION"};
print($out);


问:
Is possible to check if the user/device still has my app installed?
I'm creating a Flutter+Firebase app for a dental franchise.

Every client will be asked to install the app before the treatment starts. When the treatment finishes, the system will send a notification to the device that will trigger a survey within the app, just to check the client overall satisfaction.

The problem is, if the client doesn't has the app installed anymore, it must not send any notification, because the client will be asked to answer the survey before leaving the clinic.

I thought about using Firebase Data Messaging to return an "OK" to the server, like a "PING-PONG" request, but it works only when the app is on background or foreground, not if it is terminated.

There's any other method to confirm if my app is still active/alive?

答:
There's any other method to confirm if my app is still active/alive?

From what I understand you want to know if your app is still installed - and for that the answer is Yes,

You can use FCM (Firebase cloud messaging).
when a server is sending a message to a specific device via FCM it uses the device firebase-token.

You can see the usage in this article.

if the device doesn't have your app installed you'll get a 'Not registered' response - such as -

```<code>{
"multicast_id": 123411681083894123,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
    {
        "error": "NotRegistered"
    }
]
</code>```

Body:
There's any other method to confirm if my app is still active/alive?

From what I understand you want to know if your app is still installed - and for that the answer is Yes,

You can use FCM (Firebase cloud messaging).
when a server is sending a message to a specific device via FCM it uses the device firebase-token.

You can see the usage in this article.

if the device doesn't have your app installed you'll get a 'Not registered' response - such as -

{
"multicast_id": 123411681083894123,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
    {
        "error": "NotRegistered"
    }
]


问:
Where Cache stored in asp.net
I'm using the Cache object to store the Datatable.
like as below

```<code>Cache["dt"]=dtsum;
</code>```

If I store like this where cahce will store either at client side or serverside.
Previoulsy I was storing in Viewstate. But I was thinking of Viewstate that store data in page itself. so I'm storing in Cache. which will be better option.
please suggest me.

答:
Cache stores the data at Server Side.

Upto.NET Framework 3.5 SP1, you had only one option that is it by default used to store in memory (In Proc).. With .NET 4, You have an option to store your cache outside as well using CacheProviders...

ContentLicense: CC BY-SA 3.0

Title: Where Cache stored in asp.net

Body:
I'm using the Cache object to store the Datatable.
like as below

Cache["dt"]=dtsum;

If I store like this where cahce will store either at client side or serverside.
Previoulsy I was storing in Viewstate. But I was thinking of Viewstate that store data in page itself. so I'm storing in Cache. which will be better option.
please suggest me.


问:
Algorithm Analysis Dependant quadratic
I want to ask for this question, what is the algorithm analysis for this?
outer loop will execute for n + 2 times
how we determine the inner loop? is it (n+1)/2</p>
```<code>for(int i = 0;i <= n;i++)
    for(int j = n;j>i;j--)
</code>```

答:
@Eran's answer works, but it's easier to figure this out without calculating exactly how many iterations there are of the inner loop.

For n/2 iterations of the outer loop (the ones for small i), the inner loop iterates at least n/2 times.  So in total you have at least (n/2)2 = n2/4 = O(n2).

We can also see that the outer loop iterates at most n times, and the inner loop at most n times for all of those, so in total you have at most n2 inner iterations, which is also O(2)

Title: Algorithm Analysis Dependant quadratic

Body:
I want to ask for this question, what is the algorithm analysis for this?
outer loop will execute for n + 2 times
how we determine the inner loop? is it (n+1)/2

for(int i = 0;i <= n;i++)
    for(int j = n;j>i;j--)


问:
Matching content between 2 CSVs and write the values
Each user has a domain1.com and domain2.com separate email address. I would like to compare email addresses within CSV1 & CSV2 and if the prefix name on their emails match, pull the value into CSV1.  This will later allow me to run other powershell commands on a source / target kind of scenario.

I have it somewhat, working below although the domain2_email column isn't matching the user row. It looks to be trying to import all of them into an array.

I have used Joe.Bloggs here to test if the IF is working, but ideally - I would like to have it search each entry in CSV1.

End Goal:

Search CSV2 with the name part of the primarySMTPAddress value and if match, put them into another column within CSV1.

CSV1 will have a user with domain1.com and domain2.com values within the row.

```<code># Pull in mailbox data
Get-EXOMailbox  -Filter {EmailAddresses -like *@domain1.com -and RecipientTypeDetails -notlike "SharedMailbox"} |  Export-Csv -Path './domain1export.csv'
Get-EXOMailbox  -Filter {EmailAddresses -like *@domain2.com -and RecipientTypeDetails -notlike "SharedMailbox"} |  Export-Csv -Path './domain2xexport.csv'

$outfile = './outfile.csv'
$finalOutfile = './finalOutfile.csv'

# Check if outfile.csv exists, if it does - delete.
if (test-path $outfile) {
    Remove-Item $outfile
    Write-Host "$outfile has been deleted"
}

$CSV1 = Import-Csv -Path './domain1export.csv'
$CSV2 = Import-Csv -Path './domain2export.csv'

$CVS1 | foreach {
    # Splits the name prefix from email
    $_ | Select-Object *,@{Name='Name_Prefix';Expression={$_.PrimarySmtpAddress.Split("@")[0] }} | Export-Csv -Path $outfile -Append -NoTypeInformation
}

$outfile2 = Import-Csv -Path $outfile
foreach ($item in $outfile2) {
    if ($outfile2.Name_Prefix -match "Joe.Bloggs") {
        $item | Select-Object *,@{Name='Domain2_email';Expression={$CSV2.PrimarySmtpAddress}} | Export-Csv -Path $finalOutfile -Append -NoTypeInformation
    }
}
</code>```

Data

CSV1

```<code>UserPrincipalName,Alias,DisplayName,EmailAddresses,PrimarySmtpAddress,RecipientType,RecipientTypeDetails
joe.bloggs@domain1.com,d1bloggsj,Domain1 Joe Bloggs,SIP:joe.blogggs@domain1.com SMTP:joe.blogggs@domain1.com,Joe.Bloggs@domain1.com,UserMailbox,UserMailbox
foo.bar@domain1.com,d1barf,Domain1 Foo Bar,SIP:foo.bar@domain1.com SMTP:foo.bar@domain1.com  ,foo.bar@domain1.com,UserMailbox,UserMailbox
</code>```

CSV2

```<code>UserPrincipalName,Alias,DisplayName,EmailAddresses,PrimarySmtpAddress,RecipientType,RecipientTypeDetails
joe.bloggs@domain2.com,d2bloggsj,Domain2 Joe Bloggs,SIP:joe.blogggs@domain2.com SMTP:joe.blogggs@domain2.com,Joe.Bloggs@domain2.com,UserMailbox,UserMailbox
foo.bar@domain2.com,d1barf,Domain2 Foo Bar,SIP:foo.bar@domain2.com SMTP:foo.bar@domain2.com  ,foo.bar@domain2.com,UserMailbox,UserMailbox

</code>```

答:
I would do it like this, first create a hash table using the Csv1 where the Keys are the mail prefix and the Values are the mail suffix and the, using a calculated property with Select-Object you can search for each line on Csv2 if the mail's prefix exists and obtain the corresponding Values (mail suffix):

Note, below code assumes that there are unique mail prefixes, if this was not the case, an if condition would need to be added to the first loop to avoid Key collision. I would also recommend you to use the MailAddress Class to parse your emails.

```<code>$map = @{}

foreach($line in $csv1) {
    $mail = [mailaddress]$line.PrimarySmtpAddress
    $map[$mail.User] = $mail
}

$csv2 | Select-Object *, @{
    Name = 'SecondaryDomain'
    Expression = { $map[([mailaddress]$_.PrimarySmtpAddress).User].Host }
}, @{
    Name = 'SecondarySmtpAddress'
    Expression = { $map[([mailaddress]$_.PrimarySmtpAddress).User].Address }
}

$result | Format-Table
</code>```

Body:
Each user has a domain1.com and domain2.com separate email address. I would like to compare email addresses within CSV1 & CSV2 and if the prefix name on their emails match, pull the value into CSV1.  This will later allow me to run other powershell commands on a source / target kind of scenario.

I have it somewhat, working below although the domain2_email column isn't matching the user row. It looks to be trying to import all of them into an array.

I have used Joe.Bloggs here to test if the IF is working, but ideally - I would like to have it search each entry in CSV1.

End Goal:

Search CSV2 with the name part of the primarySMTPAddress value and if match, put them into another column within CSV1.

CSV1 will have a user with domain1.com and domain2.com values within the row.

# Pull in mailbox data
Get-EXOMailbox  -Filter {EmailAddresses -like *@domain1.com -and RecipientTypeDetails -notlike "SharedMailbox"} |  Export-Csv -Path './domain1export.csv'
Get-EXOMailbox  -Filter {EmailAddresses -like *@domain2.com -and RecipientTypeDetails -notlike "SharedMailbox"} |  Export-Csv -Path './domain2xexport.csv'

$outfile = './outfile.csv'
$finalOutfile = './finalOutfile.csv'

# Check if outfile.csv exists, if it does - delete.
if (test-path $outfile) {
    Remove-Item $outfile
    Write-Host "$outfile has been deleted"
}

$CSV1 = Import-Csv -Path './domain1export.csv'
$CSV2 = Import-Csv -Path './domain2export.csv'

$CVS1 | foreach {
    # Splits the name prefix from email
    $_ | Select-Object *,@{Name='Name_Prefix';Expression={$_.PrimarySmtpAddress.Split("@")[0] }} | Export-Csv -Path $outfile -Append -NoTypeInformation
}

$outfile2 = Import-Csv -Path $outfile
foreach ($item in $outfile2) {
    if ($outfile2.Name_Prefix -match "Joe.Bloggs") {
        $item | Select-Object *,@{Name='Domain2_email';Expression={$CSV2.PrimarySmtpAddress}} | Export-Csv -Path $finalOutfile -Append -NoTypeInformation
    }
}

Data

CSV1

UserPrincipalName,Alias,DisplayName,EmailAddresses,PrimarySmtpAddress,RecipientType,RecipientTypeDetails
joe.bloggs@domain1.com,d1bloggsj,Domain1 Joe Bloggs,SIP:joe.blogggs@domain1.com SMTP:joe.blogggs@domain1.com,Joe.Bloggs@domain1.com,UserMailbox,UserMailbox
foo.bar@domain1.com,d1barf,Domain1 Foo Bar,SIP:foo.bar@domain1.com SMTP:foo.bar@domain1.com  ,foo.bar@domain1.com,UserMailbox,UserMailbox

CSV2

UserPrincipalName,Alias,DisplayName,EmailAddresses,PrimarySmtpAddress,RecipientType,RecipientTypeDetails
joe.bloggs@domain2.com,d2bloggsj,Domain2 Joe Bloggs,SIP:joe.blogggs@domain2.com SMTP:joe.blogggs@domain2.com,Joe.Bloggs@domain2.com,UserMailbox,UserMailbox
foo.bar@domain2.com,d1barf,Domain2 Foo Bar,SIP:foo.bar@domain2.com SMTP:foo.bar@domain2.com  ,foo.bar@domain2.com,UserMailbox,UserMailbox

Body:
I would do it like this, first create a hash table using the Csv1 where the Keys are the mail prefix and the Values are the mail suffix and the, using a calculated property with Select-Object you can search for each line on Csv2 if the mail's prefix exists and obtain the corresponding Values (mail suffix):

Note, below code assumes that there are unique mail prefixes, if this was not the case, an if condition would need to be added to the first loop to avoid Key collision. I would also recommend you to use the MailAddress Class to parse your emails.

$map = @{}

foreach($line in $csv1) {
    $mail = [mailaddress]$line.PrimarySmtpAddress
    $map[$mail.User] = $mail
}

$csv2 | Select-Object *, @{
    Name = 'SecondaryDomain'
    Expression = { $map[([mailaddress]$_.PrimarySmtpAddress).User].Host }
}, @{
    Name = 'SecondarySmtpAddress'
    Expression = { $map[([mailaddress]$_.PrimarySmtpAddress).User].Address }
}

$result | Format-Table


问:
Can't select or edit Textfield inside Tableview cell
I have a controller EditProfileController: UITableViewController and a cell EditProfileCell: UITableViewCell

```<code>extension EditProfileController {

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! EditProfileCell
        cell.delegate = self
        return cell
    }
}
</code>```

My EditProfileCell

This is my TextField:

```<code>class EditProfileCell: UITableViewCell {
    lazy var infoTextField: UITextField = {
        let tf = UITextField()
        tf.borderStyle = .none
        tf.font = UIFont.systemFont(ofSize: 14)
        tf.textAlignment = .left
        tf.textColor = .white
        tf.isUserInteractionEnabled = true

        return tf
    }()

}
</code>```

The Problem: I can edit the infos for the textfields using the simulator. But when I'm running the app on my iPhone, I'm not able to even select the Textfield, not even the keyboard shows up.

I've tested adding cell.infoTextField.becomeFirstResponder() on the extension, and it works, but this makes only the last textfield become editable.

What I'm doing wrong?

答:
You have to set contentView.isUserInteractionEnabled to false

```<code>extension EditProfileController {

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! EditProfileCell
        cell.delegate = self
        cell.contentView.isUserInteractionEnabled = false

        return cell
     }
}
</code>```

Body:
I have a controller EditProfileController: UITableViewController and a cell EditProfileCell: UITableViewCell

extension EditProfileController {

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! EditProfileCell
        cell.delegate = self
        return cell
    }
}

My EditProfileCell

This is my TextField:

class EditProfileCell: UITableViewCell {
    lazy var infoTextField: UITextField = {
        let tf = UITextField()
        tf.borderStyle = .none
        tf.font = UIFont.systemFont(ofSize: 14)
        tf.textAlignment = .left
        tf.textColor = .white
        tf.isUserInteractionEnabled = true

        return tf
    }()

}

The Problem: I can edit the infos for the textfields using the simulator. But when I'm running the app on my iPhone, I'm not able to even select the Textfield, not even the keyboard shows up.

I've tested adding cell.infoTextField.becomeFirstResponder() on the extension, and it works, but this makes only the last textfield become editable.

What I'm doing wrong?

Body:
You have to set contentView.isUserInteractionEnabled to false

extension EditProfileController {

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! EditProfileCell
        cell.delegate = self
        cell.contentView.isUserInteractionEnabled = false

        return cell
     }
}


问:
NS_ERROR_XPC_SECURITY_MANAGER_VETO Error In FF 30.0 Using Selenium IDE 2.5.0 To Populate Page
When running a selenium IDE script to autofill a form, I receive the following:

```<code>[error] There was an unexpected Alert! [Javascript Error :MY-SUPER-TOP-SECRET-URL line 37 Error: NS_ERROR_XPC_SECURITY_MANAGER_VETO: ]
</code>```

When I checked line 37, it is a tiny block of code setting a global bool, wrapped in a jQuery click() anon function.

```<code>  parent.jQuery(parent.document).click(function () {
     parent.sharedVars.enableGenderKey = false;
  });
</code>```

I am running jQuery 1.8.3.  Any tips? Interestingly, the form DOES fill successfully once, but on attempt 2 and above, it errors.

答:
We had this in a frameset environment where we were holding a reference to some previously loaded and now invalid and thrown away frame content (via some jQuery object) that had been refreshed already and thus was non-existing anymore.

Refreshing the jQuery frame object before accessing it fixed it.

Body:
When running a selenium IDE script to autofill a form, I receive the following:

[error] There was an unexpected Alert! [Javascript Error :MY-SUPER-TOP-SECRET-URL line 37 Error: NS_ERROR_XPC_SECURITY_MANAGER_VETO: ]

When I checked line 37, it is a tiny block of code setting a global bool, wrapped in a jQuery click() anon function.

  parent.jQuery(parent.document).click(function () {
     parent.sharedVars.enableGenderKey = false;
  });

I am running jQuery 1.8.3.  Any tips? Interestingly, the form DOES fill successfully once, but on attempt 2 and above, it errors.


问:
Design tips for a program to be run in 25 years
If creating an application (that does mostly data processing) that needs to be run now and maybe (maybe not) 10 or 25 years later, what design tips are out there for such applications?

The general rules apply: rely on open source software and proven platforms and failsafe data formats.

The language must be a high-level language for readability reasons (maybe the only option will be re-writing the application in 15 years by someone who has little knowledge of the original code).

I'd go for UNIX(Linux)+Python+YAML/JSON(/CSV/plaintext), any tips for this selection or an alternative toolset? Scheme/lisp has been around for ages and is really hard to screw up the language basics as well, given that everything would be self-contained.

EDIT: please don't forget tips about actual design and code, like 2038 year issue!

答:
Actually, the #1 requirement would be "use a popular language with an International Standards Organization formal spec".  This is far more important than any of the other things you mention.  ("Open Source"?  Please...  There are thousands of public domain programs from the 80s and 90s that it would be nigh-impossible to run today.)

For example, if you code rigidly to the C99 or C++98 or C++03 or even C++0x specification, the odds are roughly 99.9999% that a compiler will exist for your platform 10, 20, and 50 years from now that can handle your code with zero changes.  This is, arguably, the most useful thing about a formal spec for a popular language.

Coding rigidly to such a spec may not be easy, since many non-trivial programs (e.g. anything with a GUI) cannot be written 100% portably.

But that is still where I would start.  Implement as much as you can in 100% standard-compliant code, then isolate the rest (like the GUI) in platform-dependent modules.  Minimize the size of the latter, and you will minimize the work your successors have to perform.

Free 3rd-party tools -- whether something like Boost or something like Python -- are great answers to some questions, but not this one.


问:
Fatal error: Call to undefined function getsqlvaluestring()
Hey guys I get this error when I try to login with a default Dreamweaver Login Module, please help me - this is a though one, I'm just an html designer trying to make a simple login script for a small site I'm working one. It's be great if you can help

```<code>    <?php require_once('../Connections/dsfsdfsdfd.php'); ?>
    <?php
    // *** Validate request to login to this site.
    if (!isset($_SESSION)) {
    session_start();
    }
    $loginFormAction = $_SERVER['PHP_SELF'];
    if (isset($_GET['accesscheck'])) {
    $_SESSION['PrevUrl'] = $_GET['accesscheck'];
    }

    if (isset($_POST['username'])) {
    $loginUsername=$_POST['username'];
    $password=$_POST['password'];
    $MM_fldUserAuthorization = "access_level";
    $MM_redirectLoginSuccess = "index.php";
    $MM_redirecttoReferrer = true;
    mysql_select_db($database_promocenter, $promocenter);

    $LoginRS__query=sprintf("SELECT username, password, destination_page FROM
    users WHERE username=%s AND password=%s",
    GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "int"));

    $LoginRS = mysql_query($LoginRS__query, $promocenter) or die(mysql_error());
    $loginFoundUser = mysql_num_rows($LoginRS);
    if ($loginFoundUser) {

    $loginStrGroup = mysql_result($LoginRS,0,'access_level');

    if (PHP_VERSION >= 5.1) {session_regenerate_id(true);}
    else {session_regenerate_id();}
    //declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;

    if (isset($_SESSION['PrevUrl']) && true) {
    $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];
    }
    header("Location: " . $MM_redirectLoginSuccess );
    }
    else {
    header("Location: ". $MM_redirectLoginFailed );
    }
    }
    ?>
    <?php
    if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType,
    $theDefinedValue = "", $theNotDefinedValue = "")
    {
    if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
    }

    $theValue = function_exists("mysql_real_escape_string") ?
    mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

    switch ($theType) {
    case "text":
    $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
    break;
    case "long":
    case "int":
    $theValue = ($theValue != "") ? intval($theValue) : "NULL";
    break;
    case "double":
    $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
    break;
    case "date":
    $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
    break;
    case "defined":
    $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
    break;
    }
    return $theValue;
    }
    }

    mysql_select_db($database_promocenter, $promocenter);
    $query_rs_users_login = "SELECT * FROM users";
    $rs_users_login = mysql_query($query_rs_users_login, $promocenter)
    or die(mysql_error());
    $row_rs_users_login = mysql_fetch_assoc($rs_users_login);
    $totalRows_rs_users_login = mysql_num_rows($rs_users_login);
    ?>
</code>```

Sorry guys, the error is Fatal error: Call to undefined function getsqlvaluestring() in /u1/home/xxxxxx/public_html/newsletters/Resources/promocenter/admin/login.php on line 22 This is standard dreamweaver cs5 code.

Connecting to a database etc. I'm sure I have the file included right at the top of my code, please have a look there. I can also say that this code worked perfectly fine for a year and all of a sudden it gave me this error everytime I try to login. The normal front end still shows fields from the database. It's just the /admin/ login side that give the issue

答:
Below is some of Dreamweaver's standard code - it has solved the fatal error for me, as long as it is placed before the GetSQLValueString() is called.</p>
```<code><?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
?>
</code>```

Body:
Hey guys I get this error when I try to login with a default Dreamweaver Login Module, please help me - this is a though one, I'm just an html designer trying to make a simple login script for a small site I'm working one. It's be great if you can help

    <?php require_once('../Connections/dsfsdfsdfd.php'); ?>
    <?php
    // *** Validate request to login to this site.
    if (!isset($_SESSION)) {
    session_start();
    }
    $loginFormAction = $_SERVER['PHP_SELF'];
    if (isset($_GET['accesscheck'])) {
    $_SESSION['PrevUrl'] = $_GET['accesscheck'];
    }

    if (isset($_POST['username'])) {
    $loginUsername=$_POST['username'];
    $password=$_POST['password'];
    $MM_fldUserAuthorization = "access_level";
    $MM_redirectLoginSuccess = "index.php";
    $MM_redirecttoReferrer = true;
    mysql_select_db($database_promocenter, $promocenter);

    $LoginRS__query=sprintf("SELECT username, password, destination_page FROM
    users WHERE username=%s AND password=%s",
    GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "int"));

    $LoginRS = mysql_query($LoginRS__query, $promocenter) or die(mysql_error());
    $loginFoundUser = mysql_num_rows($LoginRS);
    if ($loginFoundUser) {

    $loginStrGroup = mysql_result($LoginRS,0,'access_level');

    if (PHP_VERSION >= 5.1) {session_regenerate_id(true);}
    else {session_regenerate_id();}
    //declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;

    if (isset($_SESSION['PrevUrl']) && true) {
    $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];
    }
    header("Location: " . $MM_redirectLoginSuccess );
    }
    else {
    header("Location: ". $MM_redirectLoginFailed );
    }
    }
    ?>
    <?php
    if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType,
    $theDefinedValue = "", $theNotDefinedValue = "")
    {
    if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
    }

    $theValue = function_exists("mysql_real_escape_string") ?
    mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

    switch ($theType) {
    case "text":
    $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
    break;
    case "long":
    case "int":
    $theValue = ($theValue != "") ? intval($theValue) : "NULL";
    break;
    case "double":
    $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
    break;
    case "date":
    $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
    break;
    case "defined":
    $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
    break;
    }
    return $theValue;
    }
    }

    mysql_select_db($database_promocenter, $promocenter);
    $query_rs_users_login = "SELECT * FROM users";
    $rs_users_login = mysql_query($query_rs_users_login, $promocenter)
    or die(mysql_error());
    $row_rs_users_login = mysql_fetch_assoc($rs_users_login);
    $totalRows_rs_users_login = mysql_num_rows($rs_users_login);
    ?>

Sorry guys, the error is Fatal error: Call to undefined function getsqlvaluestring() in /u1/home/xxxxxx/public_html/newsletters/Resources/promocenter/admin/login.php on line 22 This is standard dreamweaver cs5 code.

Connecting to a database etc. I'm sure I have the file included right at the top of my code, please have a look there. I can also say that this code worked perfectly fine for a year and all of a sudden it gave me this error everytime I try to login. The normal front end still shows fields from the database. It's just the /admin/ login side that give the issue

Body:
Below is some of Dreamweaver's standard code - it has solved the fatal error for me, as long as it is placed before the GetSQLValueString() is called.

<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
?>


问:
Laravel 8- Eloquent order table results in days array
I am trying to assemble a graph of tasks per user/day, but I can't find how to order it easily.

I make the following queries to collect the tasks;

```<code>$tasksLastMonth = Task::where('user_id', Auth::user()->id)
                        ->whereMonth('date', Carbon::now()->month)
                        ->with('client')->get();

$tasksLastWeek = Task::where('user_id', Auth::user()->id)
                        ->where('date', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
                        ->with('client')->get();
</code>```

On the other hand, I have two arrays with the days of the week and the month for the Xaxis of graph (are 2 graphs, one for week, and other for month)

```<code>$weekDays // [7,8,9,10,11,12,13]
$week // [1,2,3,4,.....,28]
</code>```

Now, I need two arrays of the same length as the days of the week and month, for the Y axis, containing the number of tasks for each day. For example, if on day 8 there are 5 tasks it would look something like this:

```<code>$tasksInWeek = [0,5,0,0,0,0,0];
</code>```

I also need other arrays for the number of clients for each day, but only the different ones. If one day there are 2 tasks for the same client, I only have to add 1 client that day.

I may be able to do it with just the query, but I can't find a way.

答:
This should work:

```<code>$groupedTasks = Task::where('user_id', Auth::user()->id)
            ->whereMonth('date', Carbon::now()->month)
            ->with('client')
            ->get()
            ->groupBy(function ($item) {
              return $item->date->format('Y-m-d');
            })
            ->map(function ($items, $date) {
              return $items->unique('user_id');
            });
</code>```

The idea here is to, first, group the elements by the date (instead of using an integer) and then, on each group just keep the distinct users.

You can duplicate almost the same logic to get the data for the weekly chart.

Body:
I am trying to assemble a graph of tasks per user/day, but I can't find how to order it easily.

I make the following queries to collect the tasks;

$tasksLastMonth = Task::where('user_id', Auth::user()->id)
                        ->whereMonth('date', Carbon::now()->month)
                        ->with('client')->get();

$tasksLastWeek = Task::where('user_id', Auth::user()->id)
                        ->where('date', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
                        ->with('client')->get();

On the other hand, I have two arrays with the days of the week and the month for the Xaxis of graph (are 2 graphs, one for week, and other for month)

$weekDays // [7,8,9,10,11,12,13]
$week // [1,2,3,4,.....,28]

Now, I need two arrays of the same length as the days of the week and month, for the Y axis, containing the number of tasks for each day. For example, if on day 8 there are 5 tasks it would look something like this:

$tasksInWeek = [0,5,0,0,0,0,0];

I also need other arrays for the number of clients for each day, but only the different ones. If one day there are 2 tasks for the same client, I only have to add 1 client that day.

I may be able to do it with just the query, but I can't find a way.

Body:
This should work:

$groupedTasks = Task::where('user_id', Auth::user()->id)
            ->whereMonth('date', Carbon::now()->month)
            ->with('client')
            ->get()
            ->groupBy(function ($item) {
              return $item->date->format('Y-m-d');
            })
            ->map(function ($items, $date) {
              return $items->unique('user_id');
            });

The idea here is to, first, group the elements by the date (instead of using an integer) and then, on each group just keep the distinct users.

You can duplicate almost the same logic to get the data for the weekly chart.


问:
Get the value of the selected item in a dropdownlist (DataSource)
I just created a dropdownlist and I'm trying to get the value of the selected item in particular the value isActive.
This DropDownList is built with a dataTable. How to get the value?

I based myself on the following document : https://learn.microsoft.com/fr-fr/dotnet/api/system.web.ui.webcontrols.dropdownlist?view=netframework-4.8

Thanks in advance.

```<code> if (!PostBack) {

    this.ddlList.DataSource = CreateDataSource(this.List);
    this.ddlList.DataTextField = "Name";
    this.ddlList.DataValueField = "value";
    this.ddlList.DataBind();
 }

 ICollection CreateDataSource(List<Vendor> vendorList)
    {
        DataTable dt = new DataTable();

        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Value", typeof(string)));
        dt.Columns.Add(new DataColumn("IsActive", typeof(bool)));

        foreach (var item in List)
        {
            dt.Rows.Add(CreateRow(item.DisplayName, item.Value, item.IsActive, dt));
        }
        DataView dv = new DataView(dt);
        return dv;
    }

    DataRow CreateRow(string Name, string Value, bool IsActive, DataTable dt)
    {
        DataRow dr = dt.NewRow();

        dr[0] = Name;
        dr[1] = Value;
        dr[2] = IsActive;

        return dr;
    }
</code>```

答:
```<code>var test = (DataView)this.ddlList.DataSource;
var test2 = test[i].Row["nameOfRow"]; //i is the index of the line

</code>```

Body:
I just created a dropdownlist and I'm trying to get the value of the selected item in particular the value isActive.
This DropDownList is built with a dataTable. How to get the value?

I based myself on the following document : https://learn.microsoft.com/fr-fr/dotnet/api/system.web.ui.webcontrols.dropdownlist?view=netframework-4.8

Thanks in advance.

 if (!PostBack) {

    this.ddlList.DataSource = CreateDataSource(this.List);
    this.ddlList.DataTextField = "Name";
    this.ddlList.DataValueField = "value";
    this.ddlList.DataBind();
 }

 ICollection CreateDataSource(List<Vendor> vendorList)
    {
        DataTable dt = new DataTable();

        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Value", typeof(string)));
        dt.Columns.Add(new DataColumn("IsActive", typeof(bool)));

        foreach (var item in List)
        {
            dt.Rows.Add(CreateRow(item.DisplayName, item.Value, item.IsActive, dt));
        }
        DataView dv = new DataView(dt);
        return dv;
    }

    DataRow CreateRow(string Name, string Value, bool IsActive, DataTable dt)
    {
        DataRow dr = dt.NewRow();

        dr[0] = Name;
        dr[1] = Value;
        dr[2] = IsActive;

        return dr;
    }


问:
How to make dictionary using two lists which contains multiple values for one key?
I want to make a dictionary out of the two lists "a" and "b" in which a contains the keys and b contains values but the problem is that there are multiple values for one key

```<code>a=['Eng','Eng','Eng','Science', 'Science' ,'Hindi','Maths','Maths']
b=['Noun','Pronoun','Tenses','Light','Sound','Algebra','Probability']
</code>```

expected output should be like

```<code>{'Eng':['Noun','Pronoun','Tenses'],'Science':['Light','Sound'],'Maths':['Algebra','Probability']}
</code>```

答:
You have an extra entry in a in your input. Removing the extra Hindi from a so that len(a) = len(b). You can use following small snippet -

```<code>d = {}
for i,j in zip(a,b):
    d.setdefault(i, []).append(j)

</code>```

output d -

```<code>{'Eng': ['Noun', 'Pronoun', 'Tenses'], 'Science': ['Light', 'Sound'], 'Maths': ['Algebra', 'Probability']}
</code>```

Body:
I want to make a dictionary out of the two lists "a" and "b" in which a contains the keys and b contains values but the problem is that there are multiple values for one key

a=['Eng','Eng','Eng','Science', 'Science' ,'Hindi','Maths','Maths']
b=['Noun','Pronoun','Tenses','Light','Sound','Algebra','Probability']

expected output should be like

{'Eng':['Noun','Pronoun','Tenses'],'Science':['Light','Sound'],'Maths':['Algebra','Probability']}

Body:
You have an extra entry in a in your input. Removing the extra Hindi from a so that len(a) = len(b). You can use following small snippet -

d = {}
for i,j in zip(a,b):
    d.setdefault(i, []).append(j)

output d -

{'Eng': ['Noun', 'Pronoun', 'Tenses'], 'Science': ['Light', 'Sound'], 'Maths': ['Algebra', 'Probability']}


问:
How to create a function in PHP
I'm trying to create a function called saveorder. This is my code so far:

```<code><?php
//function foo($arg_1, $arg_2, /* ..., */ $arg_n)
function saveorder($orderid,$txnid,$date,$amount)
{
    $a_str = array(
        "orderid"=>"175",
        "txnid"=>"RC456456456",
        "date"=>"54156456465",
        "amount"=>"109$"
    );

    $file = 'order.dat';

    $contents = implode("|", $a_str);

    $contents .= PHP_EOL . PHP_EOL;
    file_put_contents($file, $contents);
}
echo "function will return=".saveorder($orderid);
?>
</code>```

I think I'm doing it wrong because I never created my own function. Still, however, I want to create this function to save the order in the order.dat file. Can anyone please help me create this function? I'm trying very hard but I'm unable to create it.

答:
You didn't return anything.

Apart from that the function is okay:

```<code>function saveorder($orderid,$txnid,$date,$amount){
    $a_str = array(
        "orderid"=>$orderid,
        "txnid"=>$txnid,
        "date"=>$date,
        "amount"=>$amount
    );

    $file = 'order.dat';
    $contents = implode("|", $a_str);

    $contents .= PHP_EOL;
    file_put_contents($file, $contents, FILE_APPEND);
    return $contents;
}
echo "function will return=".saveorder("175","RC456456456","54156456465","109$");
</code>```

Title: How to create a function in PHP

Body:
I'm trying to create a function called saveorder. This is my code so far:

<?php
//function foo($arg_1, $arg_2, /* ..., */ $arg_n)
function saveorder($orderid,$txnid,$date,$amount)
{
    $a_str = array(
        "orderid"=>"175",
        "txnid"=>"RC456456456",
        "date"=>"54156456465",
        "amount"=>"109$"
    );

    $file = 'order.dat';

    $contents = implode("|", $a_str);

    $contents .= PHP_EOL . PHP_EOL;
    file_put_contents($file, $contents);
}
echo "function will return=".saveorder($orderid);
?>

I think I'm doing it wrong because I never created my own function. Still, however, I want to create this function to save the order in the order.dat file. Can anyone please help me create this function? I'm trying very hard but I'm unable to create it.

Body:
You didn't return anything.

Apart from that the function is okay:

function saveorder($orderid,$txnid,$date,$amount){
    $a_str = array(
        "orderid"=>$orderid,
        "txnid"=>$txnid,
        "date"=>$date,
        "amount"=>$amount
    );

    $file = 'order.dat';
    $contents = implode("|", $a_str);

    $contents .= PHP_EOL;
    file_put_contents($file, $contents, FILE_APPEND);
    return $contents;
}
echo "function will return=".saveorder("175","RC456456456","54156456465","109$");


问:
at grails.converters.XML.parse(XML.java:340) ~[grails-plugin-converters-3.0.17.jar:3.0.17]
I implement a end point in my grails controller and try to pass xml data with postman

```<code>request.withFormat {
                xml {
                    println("Inside Xml")
                    // render "The XML Title Is ${request.XML.userId}."
                    println("XML: " + request.XML) // exception in this line
                }
}

at grails.converters.XML.parse(XML.java:340) ~[grails-plugin-converters-3.0.17.jar:3.0.17]

Caused by: java.io.IOException: Stream closed
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at grails.converters.XML.parse(XML.java:337)
</code>```

I am using grails version 3.0.17

request.JSON is working fine but it throws error on request.XML

Below is the filters present on my controller

```<code>[pattern: '/demo/requests/**', filters: 'anonymousAuthenticationFilter,restTokenValidationFilter,restExceptionTranslationFilter,filterInvocationInterceptor'],
</code>```

答:
If you have something that is reading the body of the request before your request.withFormat method is invoked, that would explain the "Stream closed" error.

Common examples of that include a filter or interceptor in your app that is ready the body of the request before your controller action executes, and if the controller action accepts a command object, the body of the request has to be read before your code executes.

Body:
I implement a end point in my grails controller and try to pass xml data with postman

request.withFormat {
                xml {
                    println("Inside Xml")
                    // render "The XML Title Is ${request.XML.userId}."
                    println("XML: " + request.XML) // exception in this line
                }
}

at grails.converters.XML.parse(XML.java:340) ~[grails-plugin-converters-3.0.17.jar:3.0.17]

Caused by: java.io.IOException: Stream closed
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at grails.converters.XML.parse(XML.java:337)

I am using grails version 3.0.17

request.JSON is working fine but it throws error on request.XML

Below is the filters present on my controller

[pattern: '/demo/requests/**', filters: 'anonymousAuthenticationFilter,restTokenValidationFilter,restExceptionTranslationFilter,filterInvocationInterceptor'],


问:
Save configuration from class to class through save Button in a specific VC
I have a View Controller which has a UITextField and a button below it which i want to configure it when its pressed to save the data which are in the UITextField and store that data to the API class, Ill show some of the code and images below

Image of the Settings VC

So the default must be the URL that you are seeing but If the user decide to change that and press the button "Ruaj" then the URL needs to be updated in the APICaller class to, Ill show how the code is structured in the APICaller class where the URL needs to be updated

The code for the Settings class:

```<code>@IBOutlet weak var apiTextField: UITextField!
@IBOutlet weak var saveButton: UIButton!

@IBAction func theSaveButton(_ sender: Any) {

    let alert = UIAlertController(title: "", message: "The configurations are being saved...", preferredStyle: .alert)
    self.present(alert, animated: true, completion: nil)

    Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { _ in

        guard let tabBarController = self.storyboard?.instantiateViewController(withIdentifier: "qrCode") else {
            return
        }

        tabBarController.modalPresentationStyle = .custom
        self.present(tabBarController, animated: true, completion: nil)
    }
}
</code>```

The APICaller class:

```<code>class APICaller {

let token = "NjQzODM2N0NDNDM4GSH350NjA03536GSE3E="
static let shared = APICaller()
var baseURL = "http://411.42.111.234:3050/api/"    // the URL when save Button is pressed needs to update the baseURL here :)

func getVehicles(for id: String, completed: @escaping (Result<[Vehicles],OnTraErrors>) -> Void ){
    let endpoint = baseURL + "GetVehicles/?UserIdentificationValue=\(id)"
</code>```

I believe this might be very easy but for me as a new Swift wanabe Dev I am having difficulties like everyone who started out this journey but I am truly learning on daily basis through this amazing community!

答:
Don't have each view controller keep a separate copy of the URL.

I suggest you set up a model object (a struct) that holds your app state, and pass that around between your view controllers. Do a Google search on the UDF (Unidirectional Data Flow) design pattern.

Alternately you could set up a data container singleton that you ask for persistent state, but that has issues and is generally not recommended.

Body:
I have a View Controller which has a UITextField and a button below it which i want to configure it when its pressed to save the data which are in the UITextField and store that data to the API class, Ill show some of the code and images below

Image of the Settings VC

So the default must be the URL that you are seeing but If the user decide to change that and press the button "Ruaj" then the URL needs to be updated in the APICaller class to, Ill show how the code is structured in the APICaller class where the URL needs to be updated

The code for the Settings class:

@IBOutlet weak var apiTextField: UITextField!
@IBOutlet weak var saveButton: UIButton!

@IBAction func theSaveButton(_ sender: Any) {

    let alert = UIAlertController(title: "", message: "The configurations are being saved...", preferredStyle: .alert)
    self.present(alert, animated: true, completion: nil)

    Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { _ in

        guard let tabBarController = self.storyboard?.instantiateViewController(withIdentifier: "qrCode") else {
            return
        }

        tabBarController.modalPresentationStyle = .custom
        self.present(tabBarController, animated: true, completion: nil)
    }
}

The APICaller class:

class APICaller {

let token = "NjQzODM2N0NDNDM4GSH350NjA03536GSE3E="
static let shared = APICaller()
var baseURL = "http://411.42.111.234:3050/api/"    // the URL when save Button is pressed needs to update the baseURL here :)

func getVehicles(for id: String, completed: @escaping (Result<[Vehicles],OnTraErrors>) -> Void ){
    let endpoint = baseURL + "GetVehicles/?UserIdentificationValue=\(id)"

I believe this might be very easy but for me as a new Swift wanabe Dev I am having difficulties like everyone who started out this journey but I am truly learning on daily basis through this amazing community!


问:
How to load CSV file in Jupyter Notebook?
I'm new and studying machine learning. I stumble upon a tutorial I found online and I'd like to make the program work so I'll get a better understanding. However, I'm getting problems about loading the CSV File into the Jupyter Notebook.

I get this error:

```<code>File "<ipython-input-2-70e07fb5b537>", line 2
    student_data = pd.read_csv("C:\Users\xxxx\Desktop\student-intervention-
system\student-data.csv")
                          ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 2-3: truncated \UXXXXXXXX escape
</code>```

and here is the code:

I followed tutorials online regarding this error but none worked. Does anyone know how to fix it?

3rd attempt with r"path"

I've tried also "\" and utf-8 but none worked.

I'm using the latest version of Anaconda
Windows 7
Python 3.7

答:
To begin with, this has nothing to do with Jupyter. This is a pure Python problem!

In Python, as in most languages, a backslash is an special (escape) character in strings, for example "foo\"bar" is the string foo"bar without causing a syntax error. Also, "foo\nbar" is the strings foo and bar with a newline in between. There are many more escapes.

In your case, the meaning of \ in your path is literal, i.e. you actually want a backslash appearing in the string.

One option is to escape the backslash itself with another backslash: "foo\\bar" amounts to the string foo\bar. However, in your case, you have several of these, so for readability you might want to switch on "raw string mode", which disables (almost all) escapes:

```<code>r"foo\bar\baz\quux\etc"
</code>```

will produce

```<code>foo\bar\baz\quuz\etc
</code>```

As a matter of programming style, though, if you want your code to be portable, it is better to use os.path.join which knows the right path separator for your OS/platform:

```<code>In [1]: import os.path

In [2]: os.path.join("foo", "bar", "baz")
Out[2]: 'foo/bar/baz'
</code>```

on Windows, that would produce foo\bar\baz.

Body:
I'm new and studying machine learning. I stumble upon a tutorial I found online and I'd like to make the program work so I'll get a better understanding. However, I'm getting problems about loading the CSV File into the Jupyter Notebook.

I get this error:

File "<ipython-input-2-70e07fb5b537>", line 2
    student_data = pd.read_csv("C:\Users\xxxx\Desktop\student-intervention-
system\student-data.csv")
                          ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 2-3: truncated \UXXXXXXXX escape

and here is the code:

I followed tutorials online regarding this error but none worked. Does anyone know how to fix it?

3rd attempt with r"path"

I've tried also "\" and utf-8 but none worked.

I'm using the latest version of Anaconda
Windows 7
Python 3.7

Body:
To begin with, this has nothing to do with Jupyter. This is a pure Python problem!

In Python, as in most languages, a backslash is an special (escape) character in strings, for example "foo\"bar" is the string foo"bar without causing a syntax error. Also, "foo\nbar" is the strings foo and bar with a newline in between. There are many more escapes.

In your case, the meaning of \ in your path is literal, i.e. you actually want a backslash appearing in the string.

One option is to escape the backslash itself with another backslash: "foo\\bar" amounts to the string foo\bar. However, in your case, you have several of these, so for readability you might want to switch on "raw string mode", which disables (almost all) escapes:

r"foo\bar\baz\quux\etc"

will produce

foo\bar\baz\quuz\etc

As a matter of programming style, though, if you want your code to be portable, it is better to use os.path.join which knows the right path separator for your OS/platform:

In [1]: import os.path

In [2]: os.path.join("foo", "bar", "baz")
Out[2]: 'foo/bar/baz'

on Windows, that would produce foo\bar\baz.


问:
Go build: "Cannot find package" (even though GOPATH is set)
Even though I have GOPATH properly set, I still can't get "go build" or "go run" to find my own packages. What am I doing wrong?

```<code>$ echo $GOROOT
/usr/local/go

$ echo $GOPATH
/home/mitchell/go

$ cat ~/main.go
package main
import "foobar"
func main() { }

$ cat /home/mitchell/go/src/foobar.go
package foobar

$ go build main.go
main.go:3:8: import "foobar": cannot find package
</code>```

答:
I had a similar problem when building a docker file:

```<code>[1/3] STEP 9/9: RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -o manager main.go
api/v1alpha1/XXX.go:5:2: cannot find package "." in:
        /workspace/client/YYY/YYY.go
</code>```

This only appeared when building the Dockerfile, building locally worked fine.

The problem turned out to be a missing statement in my Dockerfile:

```<code>COPY client/ client/
</code>```

Body:
Even though I have GOPATH properly set, I still can't get "go build" or "go run" to find my own packages. What am I doing wrong?

$ echo $GOROOT
/usr/local/go

$ echo $GOPATH
/home/mitchell/go

$ cat ~/main.go
package main
import "foobar"
func main() { }

$ cat /home/mitchell/go/src/foobar.go
package foobar

$ go build main.go
main.go:3:8: import "foobar": cannot find package

Body:
I had a similar problem when building a docker file:

[1/3] STEP 9/9: RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -o manager main.go
api/v1alpha1/XXX.go:5:2: cannot find package "." in:
        /workspace/client/YYY/YYY.go

This only appeared when building the Dockerfile, building locally worked fine.

The problem turned out to be a missing statement in my Dockerfile:

COPY client/ client/


问:
round() mode ROUND_HALF_DOWN with PHP 5.2.17
I need to simulate ROUND_HALF_DOWN mode in PHP 5.2.17 - I cannot upgrade the server's PHP version. Any ideas how to achieve this?

The basic idea is that 1.895 becomes 1.89, not 1.90 like it usually does with round().

EDIT:
This function seems to do the trick:

```<code>function nav_round($v, $prec = 2) {
    // Seems to fix a bug with the ceil function
    $v = explode('.',$v);
    $v = implode('.',$v);
    // The actual calculation
    $v = $v * pow(10,$prec) - 0.5;
    $a = ceil($v) * pow(10,-$prec);
    return number_format( $a, 2, '.', '' );
}
</code>```

答:
You can cheat by simply converting to a string and back:

```<code>$num = 1.895;

$num = (string) $num;

if (substr($num, -1) == 5) $num = substr($num, 0, -1) . '4';

$num = round(floatval($num), 2);
</code>```

EDIT:

Here you have it in function form:

```<code>echo round_half_down(25.2568425, 6); // 25.256842

function round_half_down($num, $precision = 0)
{
    $num = (string) $num;
    $num = explode('.', $num);
    $num[1] = substr($num[1], 0, $precision + 1);
    $num = implode('.', $num);

    if (substr($num, -1) == 5)
        $num = substr($num, 0, -1) . '4';

    return round(floatval($num), $precision);
}
</code>```

Body:
I need to simulate ROUND_HALF_DOWN mode in PHP 5.2.17 - I cannot upgrade the server's PHP version. Any ideas how to achieve this?

The basic idea is that 1.895 becomes 1.89, not 1.90 like it usually does with round().

EDIT:
This function seems to do the trick:

function nav_round($v, $prec = 2) {
    // Seems to fix a bug with the ceil function
    $v = explode('.',$v);
    $v = implode('.',$v);
    // The actual calculation
    $v = $v * pow(10,$prec) - 0.5;
    $a = ceil($v) * pow(10,-$prec);
    return number_format( $a, 2, '.', '' );
}

Body:
You can cheat by simply converting to a string and back:

$num = 1.895;

$num = (string) $num;

if (substr($num, -1) == 5) $num = substr($num, 0, -1) . '4';

$num = round(floatval($num), 2);

EDIT:

Here you have it in function form:

echo round_half_down(25.2568425, 6); // 25.256842

function round_half_down($num, $precision = 0)
{
    $num = (string) $num;
    $num = explode('.', $num);
    $num[1] = substr($num[1], 0, $precision + 1);
    $num = implode('.', $num);

    if (substr($num, -1) == 5)
        $num = substr($num, 0, -1) . '4';

    return round(floatval($num), $precision);
}


问:
Can't set id on img Tag using puppeteer
I am trying to set id's to all  tags of a page, my loop runs its iterations completely but some of the  tags doesn't get the id's as can be seen in the below image:

Here is my code:

const browser = await puppeteer.launch({
    args: [
        '--no-sandbox',
    ],
  });
  const page = await browser.newPage();
  await page.setViewport({ width: 1440, height: 10000 })
  await page.goto(url, {
        waitUntil: 'networkidle2',
        timeout: 0,
  });

await page.evaluate(() => {
const images = document.getElementsByTagName('img') || []
    for (let i = 0; i < images.length; i++) {
        document.getElementsByTagName('img')[i].id = `${i}`
        document.getElementsByTagName('img')[i].src = document.getElementsByTagName('img')[i].getAttribute('src')?.startsWith('https') ?
        document.getElementsByTagName('img')[i].getAttribute('src')! :
        `https://leza.notion.site${document.getElementsByTagName('img')[i].getAttribute('src')}`
    }
})
```
<p>Am I missing anything? Any help would be highly appreciated!</p>
<p>I keep getting this warning log</p>
```PAGE LOG: %c NOTION%c WARNING %c background: black; color: white; background: black; color: orange font-weight: normal Reverting mutation of attribute src from "/image/https%3A%2F%2Fraw.githubusercontent.com%2Feirikmadland%2Fnotion-icons%2Fmaster%2Fv5%2Ficon3%2Ful-file-search-alt.svg?table=block&id=db9359ba-4fcd-4a24-9744-8514d7810939&userId=&cache=v2" -> "https://leza.notion.site/image/https%3A%2F%2Fraw.githubusercontent.com%2Feirikmadland%2Fnotion-icons%2Fmaster%2Fv5%2Ficon3%2Ful-file-search-alt.svg?table=block&id=db9359ba-4fcd-4a24-9744-8514d7810939&userId=&cache=v2" in component  JSHandle@object
```

答:
Instead of

await page.evaluate(() => {
    const images = document.getElementsByTagName('img') || []
```
<p>try using:</p>
<pre class="lang-js prettyprint-override"><code>await page.$eval('.img', (images) => { /* DO STUFF... */ });
</code>```

So the following code should work:

await page.$eval('.img', (images) => {
    for (let i = 0; i < images.length; i++) {
        const currentImage = images[i];
        const targetImageId = `${i}`;
        const currentImageSrc = currentImage.getAttribute('src');
        const targetImageSrc = currentImageSrc?.startsWith('https')
            ? currentImageSrc!
            : `https://leza.notion.site${currentImageSrc}`;

        currentImage.setAttribute("id", targetImageId);
        currentImage.setAttribute("src", targetImageSrc);
    }
});
```
<p>Note that your url will look something like the following, which are probably not correct URLs for the two 1st ones:</p>
<pre class="lang-html prettyprint-override"><code><img src="http://www.gravatar.com/avatar/8947787d4067fa6e66e485bfc72233e4?s=48&d=identicon&r=PG&f=1">
</code>```
```<code>https://leza.notion.sitehttp://www.gravatar.com/avatar/8947787d4067fa6e66e485bfc72233e4?s=48&d=identicon&r=PG&f=1
</code>```

or

```
```https://leza.notion.sitemyimage.png
```
<p>or</p>
<pre class="lang-html prettyprint-override"><code><img src="/image.png">
</code>```
```<code>https://leza.notion.sitemy/image.png
</code>```

Title: Can't set id on img Tag using puppeteer

Body:
I am trying to set id's to all  tags of a page, my loop runs its iterations completely but some of the  tags doesn't get the id's as can be seen in the below image:

Here is my code:

const browser = await puppeteer.launch({
    args: [
        '--no-sandbox',
    ],
  });
  const page = await browser.newPage();
  await page.setViewport({ width: 1440, height: 10000 })
  await page.goto(url, {
        waitUntil: 'networkidle2',
        timeout: 0,
  });

await page.evaluate(() => {
const images = document.getElementsByTagName('img') || []
    for (let i = 0; i < images.length; i++) {
        document.getElementsByTagName('img')[i].id = `${i}`
        document.getElementsByTagName('img')[i].src = document.getElementsByTagName('img')[i].getAttribute('src')?.startsWith('https') ?
        document.getElementsByTagName('img')[i].getAttribute('src')! :
        `https://leza.notion.site${document.getElementsByTagName('img')[i].getAttribute('src')}`
    }
})

Am I missing anything? Any help would be highly appreciated!

I keep getting this warning log

PAGE LOG: %c NOTION%c WARNING %c background: black; color: white; background: black; color: orange font-weight: normal Reverting mutation of attribute src from "/image/https%3A%2F%2Fraw.githubusercontent.com%2Feirikmadland%2Fnotion-icons%2Fmaster%2Fv5%2Ficon3%2Ful-file-search-alt.svg?table=block&id=db9359ba-4fcd-4a24-9744-8514d7810939&userId=&cache=v2" -> "https://leza.notion.site/image/https%3A%2F%2Fraw.githubusercontent.com%2Feirikmadland%2Fnotion-icons%2Fmaster%2Fv5%2Ficon3%2Ful-file-search-alt.svg?table=block&id=db9359ba-4fcd-4a24-9744-8514d7810939&userId=&cache=v2" in component  JSHandle@object

Body:
Instead of

await page.evaluate(() => {
    const images = document.getElementsByTagName('img') || []

try using:

await page.$eval('.img', (images) => { /* DO STUFF... */ });

So the following code should work:

await page.$eval('.img', (images) => {
    for (let i = 0; i < images.length; i++) {
        const currentImage = images[i];
        const targetImageId = `${i}`;
        const currentImageSrc = currentImage.getAttribute('src');
        const targetImageSrc = currentImageSrc?.startsWith('https')
            ? currentImageSrc!
            : `https://leza.notion.site${currentImageSrc}`;

        currentImage.setAttribute("id", targetImageId);
        currentImage.setAttribute("src", targetImageSrc);
    }
});

Note that your url will look something like the following, which are probably not correct URLs for the two 1st ones:

<img src="http://www.gravatar.com/avatar/8947787d4067fa6e66e485bfc72233e4?s=48&amp;d=identicon&amp;r=PG&amp;f=1">

https://leza.notion.sitehttp://www.gravatar.com/avatar/8947787d4067fa6e66e485bfc72233e4?s=48&d=identicon&r=PG&f=1

or

<img src="image.png">

https://leza.notion.sitemyimage.png

or

<img src="/image.png">

https://leza.notion.sitemy/image.png


问:
Pi4j to use java with raspberry Pi not working
I am honestly about to just give up, i've tried so many different possibilities, for multiple weeks now, almost a month, of multiple problems.

I am a new-ish programmer, especially with java, but i have a good understanding about java

I am able to create a maven project no problem, i have no problems with the structure of java itself, but i don't fully understand the pom.xml.

The file compiles just fine, but when i go to start it with java -jar (filename), i get the following output;

Exception in thread "main" java.lang.NoClassDefFoundError: com/pi4j/Pi4J
at com.pi.rasberri.Main.main(Main.java:16)
Caused by: java.lang.ClassNotFoundException: com.pi4j.Pi4J
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
... 1 more

Heres my pom that i have figuratively almost dismembered;

```<code>   (The long links)
<modelVersion>4.0.0</modelVersion>
<groupId>com.pi</groupId>
<artifactId>Rasberri</artifactId>
<version>3.6.1</version>
<packaging>jar</packaging>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>  <dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.32</version>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.32</version>
    </dependency>
    <dependency>
        <groupId>com.pi4j</groupId>
        <artifactId>pi4j-core</artifactId>
        <version>2.0</version>
    </dependency>
    <dependency>
    <groupId>com.pi4j</groupId>
    <artifactId>pi4j-plugin-raspberrypi</artifactId>
    <version>2.0</version>
</dependency>
<dependency>
    <groupId>com.pi4j</groupId>
    <artifactId>pi4j-plugin-pigpio</artifactId>
    <version>2.0</version>
</dependency>
</dependencies> <build>
  <plugins>
      <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2</version> </plugin>    <plugin>    <groupId>org.apache.maven.plugins</groupId>
</code>```

maven-jar-plugin    3.1.0

true
com.pi.rasberri.Main
lib/

true

true

com.pi.rasberri.Main
false
true

And my code, which is com.pi.rasberri.Main

```<code>    package com.pi.rasberri;

import com.pi4j.Pi4J;
import com.pi4j.io.gpio.digital.DigitalOutput;
import com.pi4j.io.gpio.digital.DigitalState;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {

    private static final int PIN_LED = 6;

    public static void main(String[] args) throws Exception{

       var pi4j = Pi4J.newAutoContext();
        int x = 0;

        var ledConfig = DigitalOutput.newConfigBuilder(pi4j)
           .id("led")
           .name("LED Flasher")
           .address(PIN_LED)
           .shutdown(DigitalState.LOW)
           .initial(DigitalState.LOW)
           .provider("pigpio-digital-output");

        var led = pi4j.create(ledConfig);

        while(x != 5){

            led.high();
            sleep(1000);
            led.low();
            sleep(500);
            x++;
        }
    }

    static void sleep(int z){

        try {
           Thread.sleep(z);
        }   catch (InterruptedException ex) {
           System.out.println("Thread.sleep went fucky wucky");
        }
    }
    }
</code>```

I would appreciate anything that can even direct me somewhere, because i am quite lost at this point, and of course, if i figure out the answer, i will let everyone know!
Thanks in advance

```<code>                       **UPDATE**
</code>```

Thank you, tgdavies, the article you linked
https://stackoverflow.com/a/574650/17644313 was the answer to that
specific problem!**

Just in case anyone else has the same chain of issues as me;

But with that being said, i ran directly into another error;

[main] INFO com.pi4j.Pi4J - New auto context
[main] INFO com.pi4j.Pi4J - New context builder
[main] INFO com.pi4j.platform.impl.DefaultRuntimePlatforms - adding platform to managed platform map [id=raspberrypi; name=RaspberryPi Platform; priority=5; class=com.pi4j.plugin.raspberrypi.platform.RaspberryPiPlatform]
Exception in thread "main" com.pi4j.provider.exception.ProviderNotFoundException: Pi4J provider [pigpio-digital-output] could not be found.  Please include this 'provider' JAR in the classpath.
at com.pi4j.provider.impl.DefaultRuntimeProviders.get(DefaultRuntimeProviders.java:238)
at com.pi4j.provider.impl.DefaultProviders.get(DefaultProviders.java:147)
at com.pi4j.provider.Providers.get(Providers.java:253)
at com.pi4j.context.Context.create(Context.java:316)
at com.pi4j.internal.IOCreator.create(IOCreator.java:58)
at com.pi4j.internal.IOCreator.create(IOCreator.java:96)
at com.pi4j.internal.IOCreator.create(IOCreator.java:176)
at com.pi.rasberri.Main.main(Main.java:27)

I cleaned the pom.xml a littlebit;

```<code><dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.32</version>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.32</version>
    <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.pi4j</groupId>
        <artifactId>pi4j-core</artifactId>
        <version>2.0</version>
    </dependency>
    <dependency>
    <groupId>com.pi4j</groupId>
    <artifactId>pi4j-plugin-raspberrypi</artifactId>
    <version>2.0</version>
</dependency>
<dependency>
    <groupId>com.pi4j</groupId>
    <artifactId>pi4j-plugin-pigpio</artifactId>
    <version>2.0</version>
</dependency>
</dependencies>

<build>
      <plugins>  <!--Package all libraries classes into one runnable jar -->
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
              <execution>
                <phase>package</phase>
                <goals>
                  <goal>single</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
                <archive>
                    <manifest>
                <mainClass>com.pi.rasberri.Main</mainClass>
                    </manifest>
                </archive>
              <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
              </descriptorRefs>
            </configuration>
        </plugin>
</plugins>
</build>
</project>
</code>```

At this point, i know of atleast 2 possibilities,

The code just needs to be run on the raspberry pi

I have entered the classpaths incorrectly

But i honestly dont really know as to where to start troubleshooting
I've tried a few things, one of which being to try another method of compiling the files,
but the other method just resulted in a even longer string of errors.

What should i try next?
Thanks in advance!
And thanks to anyone who has suggested troubleshooting steps thus far!

Oh, and the target is to hopefully just create a singular jar file to execute on the raspberry pi

update

I tried to run it on the Raspberri pi, and it resulted in the same error so it's not that

答:
I faced the same issue working with Raspberry P4, java 11 and pi4j v2. I solved it downloading pigpio library directly from the raspberry

```<code>sudo apt-get install pigpio
</code>```

After the library was installed, the jar worked perfecrly.
Remember also to run your program with sudo if you are not root user

Body:
I am honestly about to just give up, i've tried so many different possibilities, for multiple weeks now, almost a month, of multiple problems.

I am a new-ish programmer, especially with java, but i have a good understanding about java

I am able to create a maven project no problem, i have no problems with the structure of java itself, but i don't fully understand the pom.xml.

The file compiles just fine, but when i go to start it with java -jar (filename), i get the following output;

Exception in thread "main" java.lang.NoClassDefFoundError: com/pi4j/Pi4J
at com.pi.rasberri.Main.main(Main.java:16)
Caused by: java.lang.ClassNotFoundException: com.pi4j.Pi4J
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
... 1 more

Heres my pom that i have figuratively almost dismembered;

   (The long links)
<modelVersion>4.0.0</modelVersion>
<groupId>com.pi</groupId>
<artifactId>Rasberri</artifactId>
<version>3.6.1</version>
<packaging>jar</packaging>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
</properties>  <dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.32</version>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.32</version>
    </dependency>
    <dependency>
        <groupId>com.pi4j</groupId>
        <artifactId>pi4j-core</artifactId>
        <version>2.0</version>
    </dependency>
    <dependency>
    <groupId>com.pi4j</groupId>
    <artifactId>pi4j-plugin-raspberrypi</artifactId>
    <version>2.0</version>
</dependency>
<dependency>
    <groupId>com.pi4j</groupId>
    <artifactId>pi4j-plugin-pigpio</artifactId>
    <version>2.0</version>
</dependency>
</dependencies> <build>
  <plugins>
      <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2</version> </plugin>    <plugin>    <groupId>org.apache.maven.plugins</groupId>

maven-jar-plugin    3.1.0

true
com.pi.rasberri.Main
lib/

true

true

com.pi.rasberri.Main
false
true

And my code, which is com.pi.rasberri.Main

    package com.pi.rasberri;

import com.pi4j.Pi4J;
import com.pi4j.io.gpio.digital.DigitalOutput;
import com.pi4j.io.gpio.digital.DigitalState;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {

    private static final int PIN_LED = 6;

    public static void main(String[] args) throws Exception{

       var pi4j = Pi4J.newAutoContext();
        int x = 0;

        var ledConfig = DigitalOutput.newConfigBuilder(pi4j)
           .id("led")
           .name("LED Flasher")
           .address(PIN_LED)
           .shutdown(DigitalState.LOW)
           .initial(DigitalState.LOW)
           .provider("pigpio-digital-output");

        var led = pi4j.create(ledConfig);

        while(x != 5){

            led.high();
            sleep(1000);
            led.low();
            sleep(500);
            x++;
        }
    }

    static void sleep(int z){

        try {
           Thread.sleep(z);
        }   catch (InterruptedException ex) {
           System.out.println("Thread.sleep went fucky wucky");
        }
    }
    }

I would appreciate anything that can even direct me somewhere, because i am quite lost at this point, and of course, if i figure out the answer, i will let everyone know!
Thanks in advance

                       **UPDATE**

Thank you, tgdavies, the article you linked
https://stackoverflow.com/a/574650/17644313 was the answer to that
specific problem!**

Just in case anyone else has the same chain of issues as me;

But with that being said, i ran directly into another error;

[main] INFO com.pi4j.Pi4J - New auto context
[main] INFO com.pi4j.Pi4J - New context builder
[main] INFO com.pi4j.platform.impl.DefaultRuntimePlatforms - adding platform to managed platform map [id=raspberrypi; name=RaspberryPi Platform; priority=5; class=com.pi4j.plugin.raspberrypi.platform.RaspberryPiPlatform]
Exception in thread "main" com.pi4j.provider.exception.ProviderNotFoundException: Pi4J provider [pigpio-digital-output] could not be found.  Please include this 'provider' JAR in the classpath.
at com.pi4j.provider.impl.DefaultRuntimeProviders.get(DefaultRuntimeProviders.java:238)
at com.pi4j.provider.impl.DefaultProviders.get(DefaultProviders.java:147)
at com.pi4j.provider.Providers.get(Providers.java:253)
at com.pi4j.context.Context.create(Context.java:316)
at com.pi4j.internal.IOCreator.create(IOCreator.java:58)
at com.pi4j.internal.IOCreator.create(IOCreator.java:96)
at com.pi4j.internal.IOCreator.create(IOCreator.java:176)
at com.pi.rasberri.Main.main(Main.java:27)

I cleaned the pom.xml a littlebit;

<dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.32</version>
    </dependency>
    <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.32</version>
    <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.pi4j</groupId>
        <artifactId>pi4j-core</artifactId>
        <version>2.0</version>
    </dependency>
    <dependency>
    <groupId>com.pi4j</groupId>
    <artifactId>pi4j-plugin-raspberrypi</artifactId>
    <version>2.0</version>
</dependency>
<dependency>
    <groupId>com.pi4j</groupId>
    <artifactId>pi4j-plugin-pigpio</artifactId>
    <version>2.0</version>
</dependency>
</dependencies>

<build>
      <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
              <execution>
                <phase>package</phase>
                <goals>
                  <goal>single</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
                <archive>
                    <manifest>
                <mainClass>com.pi.rasberri.Main</mainClass>
                    </manifest>
                </archive>
              <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
              </descriptorRefs>
            </configuration>
        </plugin>
</plugins>
</build>
</project>

At this point, i know of atleast 2 possibilities,

The code just needs to be run on the raspberry pi

I have entered the classpaths incorrectly

But i honestly dont really know as to where to start troubleshooting
I've tried a few things, one of which being to try another method of compiling the files,
but the other method just resulted in a even longer string of errors.

What should i try next?
Thanks in advance!
And thanks to anyone who has suggested troubleshooting steps thus far!

Oh, and the target is to hopefully just create a singular jar file to execute on the raspberry pi

update

I tried to run it on the Raspberri pi, and it resulted in the same error so it's not that

Body:
I faced the same issue working with Raspberry P4, java 11 and pi4j v2. I solved it downloading pigpio library directly from the raspberry

sudo apt-get install pigpio

After the library was installed, the jar worked perfecrly.
Remember also to run your program with sudo if you are not root user


问:
Python Pandas: How can I drop rows using df.drop and df.loc?
Suppose I have the following dataframe:

```<code>import numpy as np
import pandas as pd

df = pd.DataFrame(
    {
        'user': ['Adam', 'Barry', 'Cindy', 'Dirk', 'Ella'],
        'income': [50000, 0, 100000, 30000, 0],
        'net worth': [250000, 1000000, 2000000, 50000, 0]
    }
)
</code>```

So far, I've been removing rows based on conditions using the following:

```<code>df2 = df[df.income != 0]
</code>```

And using multiple conditions like so:

```<code>df3 = df[(df['income'] != 0) & (df['net worth'] > 100000)]
</code>```

Question: Is this the preferred way to drop rows? If not, what is? Is it possible to do this via df.drop and df.loc? What would the syntax be?

答:
.loc creates a subset of the rows you want to keep rather than .drop filter rows you want to remove. drop need the row label (index name).

The equivalent of your last filter with drop is:

```<code>>>> df.drop(df[~((df['income'] != 0) & (df['net worth'] > 100000))].index)

    user  income  net worth
0   Adam   50000     250000
2  Cindy  100000    2000000

# OR a bit smart:
>>> df.drop(df[(df['income'] == 0) | (df['net worth'] <= 100000)].index)

    user  income  net worth
0   Adam   50000     250000
2  Cindy  100000    2000000
</code>```

Which syntax do you prefer?

Body:
Suppose I have the following dataframe:

import numpy as np
import pandas as pd

df = pd.DataFrame(
    {
        'user': ['Adam', 'Barry', 'Cindy', 'Dirk', 'Ella'],
        'income': [50000, 0, 100000, 30000, 0],
        'net worth': [250000, 1000000, 2000000, 50000, 0]
    }
)

So far, I've been removing rows based on conditions using the following:

df2 = df[df.income != 0]

And using multiple conditions like so:

df3 = df[(df['income'] != 0) & (df['net worth'] > 100000)]

Question: Is this the preferred way to drop rows? If not, what is? Is it possible to do this via df.drop and df.loc? What would the syntax be?

Body:
.loc creates a subset of the rows you want to keep rather than .drop filter rows you want to remove. drop need the row label (index name).

The equivalent of your last filter with drop is:

>>> df.drop(df[~((df['income'] != 0) & (df['net worth'] > 100000))].index)

    user  income  net worth
0   Adam   50000     250000
2  Cindy  100000    2000000

# OR a bit smart:
>>> df.drop(df[(df['income'] == 0) | (df['net worth'] <= 100000)].index)

    user  income  net worth
0   Adam   50000     250000
2  Cindy  100000    2000000

Which syntax do you prefer?


问:
Dynamically update options in selectfield depending on another Select Field's data of another Form
Is it possible? If yes, then how? Please, give an example, because I can't find it anywhere. (I found the example of dynamically update options depending on another select field's data but in the same form).</p>

答:
You can try this using JQuery:

 // Hide all options initially
    $('#selectChild option').attr('disabled',true);
    // When the user changes the Parent select (Animal Category)
    $(document).on('change', '#selectParent', function() {

      // Assign the value of the selected option to variable
      let category = $('#selectParent option:selected').val();

      // Run through each Child select (Animal Name) option and filter based on its data-* attribute value

      $('#selectChild option').filter(function() {
        if ($(this).data('category') != category) {
          $(this).attr('disabled',true);
        } else {
          $(this).attr('disabled',false);
        }
      })
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h5>
  Animal Category
</h5>
<select id="selectParent">
  <option value="">Please Select</option>
  <option value="mammal">Mammal</option>
  <option value="insect">Insect</option>

</select>
<br>
<hr>
<h5>
  Animal Name
</h5>
<select id="selectChild">
  <option> Please Select </option>
  <option value="dog" data-category="mammal">Dog</option>
  <option value="cat" data-category="mammal">Cat</option>
  <option value="horse" data-category="mammal">Horse</option>

  <option value="spider" data-category="insect">Spider</option>
  <option value="ant" data-category="insect">Ant</option>
  <option value="roach" data-category="insect">Roach</option>
</select></code>```

Body:
You can try this using JQuery:

 // Hide all options initially
    $('#selectChild option').attr('disabled',true);
    // When the user changes the Parent select (Animal Category)
    $(document).on('change', '#selectParent', function() {

      // Assign the value of the selected option to variable
      let category = $('#selectParent option:selected').val();

      // Run through each Child select (Animal Name) option and filter based on its data-* attribute value

      $('#selectChild option').filter(function() {
        if ($(this).data('category') != category) {
          $(this).attr('disabled',true);
        } else {
          $(this).attr('disabled',false);
        }
      })
    });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h5>
  Animal Category
</h5>
<select id="selectParent">
  <option value="">Please Select</option>
  <option value="mammal">Mammal</option>
  <option value="insect">Insect</option>

</select>
<br>
<hr>
<h5>
  Animal Name
</h5>
<select id="selectChild">
  <option> Please Select </option>
  <option value="dog" data-category="mammal">Dog</option>
  <option value="cat" data-category="mammal">Cat</option>
  <option value="horse" data-category="mammal">Horse</option>

  <option value="spider" data-category="insect">Spider</option>
  <option value="ant" data-category="insect">Ant</option>
  <option value="roach" data-category="insect">Roach</option>
</select>


问:
How to corrently use UIViews systemLayoutSizeFitting to get the height to show all subviews using a given width?
TD;DR

It seems that in some cases systemLayoutSizeFitting does not return the correct height to correctly show / position all subviews of a view. Am I using systemLayoutSizeFitting wrong or is there some other way to avoid this?

Long story:

The XIB file of a UIViewController does not only contain the main view but also a number of other views which are added to the view controllers view at runtime. All these additional views should get the same height when they are added to the view controllers view.

The views might look like this: A simple container view holding some subviews which are stacked on top of each other.

Since the height of the container view should be flexible, the vertical spacing between the bottom button and the lable above it, uses a grater-than constraint.

To give all views the same height, I tried to measure the necessary height of each view using systemLayoutSizeFitting:

```<code>@IBOutlet var pageViews: [UIView]!

override func viewDidLoad() {
    super.viewDidLoad()

    var maxHeight: CGFloat = 0
    for pageView in pageViews {
        // Add pageView somewhere on view and give it leading, trailing and top
        // constraint, but no height constraint yet.
        addToView(pageView)

        maxHeight = max(maxHeight, pageView.systemLayoutSizeFitting(CGSize(width: view.frame.width, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel).height)
    }

    for pageView in pageViews {
        // Give all pageViews the same height
        pageView.heightAnchor.constraint(equalToConstant: maxHeight).isActive = true
    }
}
</code>```

This does not work, when the label text becomes to long:

In the right example the height is not large enough and thus the button is squeezed. I can counter act this by raising the vertical compression resistance of the button, however in this case the other controls (e.g. the title label) is squeezed...

Why is this? Why does not systemLayoutSizeFitting return a height which is sufficent to show all controls without any squeezing?

答: If you want your view to resist to compression you should use the defaultHigh priority as a verticalFittingPriority instead of fittingSizeLevel.

Body:
TD;DR

It seems that in some cases systemLayoutSizeFitting does not return the correct height to correctly show / position all subviews of a view. Am I using systemLayoutSizeFitting wrong or is there some other way to avoid this?

Long story:

The XIB file of a UIViewController does not only contain the main view but also a number of other views which are added to the view controllers view at runtime. All these additional views should get the same height when they are added to the view controllers view.

The views might look like this: A simple container view holding some subviews which are stacked on top of each other.

Since the height of the container view should be flexible, the vertical spacing between the bottom button and the lable above it, uses a grater-than constraint.

To give all views the same height, I tried to measure the necessary height of each view using systemLayoutSizeFitting:

@IBOutlet var pageViews: [UIView]!

override func viewDidLoad() {
    super.viewDidLoad()

    var maxHeight: CGFloat = 0
    for pageView in pageViews {
        // Add pageView somewhere on view and give it leading, trailing and top
        // constraint, but no height constraint yet.
        addToView(pageView)

        maxHeight = max(maxHeight, pageView.systemLayoutSizeFitting(CGSize(width: view.frame.width, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel).height)
    }

    for pageView in pageViews {
        // Give all pageViews the same height
        pageView.heightAnchor.constraint(equalToConstant: maxHeight).isActive = true
    }
}

This does not work, when the label text becomes to long:

In the right example the height is not large enough and thus the button is squeezed. I can counter act this by raising the vertical compression resistance of the button, however in this case the other controls (e.g. the title label) is squeezed...

Why is this? Why does not systemLayoutSizeFitting return a height which is sufficent to show all controls without any squeezing?