问:
recursion compilation error in Standard ML
I am making a function that recurses over a string and replaces each instance of a user-specified character. However, I get a compilation error of :

```<code>Error: operator and operand do not agree [tycon mismatch]
  operator domain: string * string
  operand:         char * 'Z
</code>```

I would like to know what this error means for my program and what I could be doing wrong. I'm new to SML and have been trying to research this for some time now. Thanks.

This is my code:

```<code>fun remCharR(expr, letter) =
    if String.sub(expr, 0) = letter
    then remCharR(String.substring(expr, 0, 1), letter)
    else String.sub(expr, 0) ^ remCharR(String.substring(expr, 0, 1), letter);
</code>```

答: ^ operator needs two string operands and the first operator in String.sub(expr, 0) ^ remCharR(String.substring(expr, 0, 1), letter) is of type char.  To fix this error, change String.sub(expr, 0) to String.substring(expr, 0, 1).

Body:
I am making a function that recurses over a string and replaces each instance of a user-specified character. However, I get a compilation error of :

Error: operator and operand do not agree [tycon mismatch]
  operator domain: string * string
  operand:         char * 'Z

I would like to know what this error means for my program and what I could be doing wrong. I'm new to SML and have been trying to research this for some time now. Thanks.

This is my code:

fun remCharR(expr, letter) =
    if String.sub(expr, 0) = letter
    then remCharR(String.substring(expr, 0, 1), letter)
    else String.sub(expr, 0) ^ remCharR(String.substring(expr, 0, 1), letter);


来源: stackexchange

问:
Why can't a struct be passed as value as template non-type parameter?
Non-type template parameters are obviously ones that aren't types, for example:

```<code>template<int x>
void foo() { cout << x; }
</code>```

There are other options than int in that case, and I'd like to refer to this great answer.

Now, there's one thing that bugs me: structs. Consider:

```<code>struct Triple { int x, y, z; };

Triple t { 1, 2, 3 };

template<Triple const& t>
class Foo { };
</code>```

Now, using normal nontype reference semantics, we can write:

```<code>Foo<t> f;
</code>```

What's worth noting here is that t can't be constexpr or even const, because that implies internal linkage, which basically means that the line won't compile. We can bypass that by declaring t as const extern. That itself might be a bit weird, but the one that really made me wonder was why this isn't possible:

```<code>Foo<Triple { 1, 2, 3 }> f;
</code>```

We get a really decent error from compiler:

error: Triple{1, 2, 3} is not a valid template argument for type const Triple& because it is not an lvalue.

We can't specify Triple in template by value, because that's disallowed. However, I fail to understand the real problem with that small line of code. What's the reasoning behind not allowing using structs as value parameters. If I can use three ints, why not a struct of three ints? If it has only trivial special members, it shouldn't be really different in handling than just three variables.

答:
Updated answer for c++20 users:

C++20 adds support for class literal (class with constexpr constructor) non-type template parameters, which would allow the example in the original question to work, provided the template parameter is accepted by value:

template<Triple t> // Note: accepts t by value
class Foo { };

// Works with unnamed instantiation of Triple.
Foo<Triple { 1, 2, 3 }> f1 {};

// Also works if provided from a constexpr variable.
constexpr Triple t { 1, 2, 3 };
Foo<t> f2 {};
```
<p>Further, all template parameter instances of <code>Triple { 1, 2, 3 }</code> throughout the program will refer to the <em><strong>same</strong></em> static storage duration object:</p>
<pre class="lang-cpp prettyprint-override"><code>template<Triple t1, Triple t2>
void Func() {
    assert(&t1 == &t2); // Passes.
}

constexpr Triple t { 1, 2, 3 };

int main()
{
    Func<t, Triple {1, 2, 3}>();
}
</code>```

From cppreference:

An identifier that names a non-type template parameter of class type T denotes a static storage duration object of type const T, called a template parameter object, whose value is that of the corresponding template argument after it has been converted to the type of the template parameter. All such template parameters in the program of the same type with the same value denote the same template parameter object.

Note that there are quite a few restrictions on the class literal types allowable by template parameters. For more detail, checkout this blog post I wrote explaining the usage and restrictions of literal class NTTPs: Literal Classes as Non-type Template Parameters in C++20.

ContentLicense: CC BY-SA 3.0

Body:
Non-type template parameters are obviously ones that aren't types, for example:

template<int x>
void foo() { cout << x; }

There are other options than int in that case, and I'd like to refer to this great answer.

Now, there's one thing that bugs me: structs. Consider:

struct Triple { int x, y, z; };

Triple t { 1, 2, 3 };

template<Triple const& t>
class Foo { };

Now, using normal nontype reference semantics, we can write:

Foo<t> f;

What's worth noting here is that t can't be constexpr or even const, because that implies internal linkage, which basically means that the line won't compile. We can bypass that by declaring t as const extern. That itself might be a bit weird, but the one that really made me wonder was why this isn't possible:

Foo<Triple { 1, 2, 3 }> f;

We get a really decent error from compiler:

error: Triple{1, 2, 3} is not a valid template argument for type const Triple& because it is not an lvalue.

We can't specify Triple in template by value, because that's disallowed. However, I fail to understand the real problem with that small line of code. What's the reasoning behind not allowing using structs as value parameters. If I can use three ints, why not a struct of three ints? If it has only trivial special members, it shouldn't be really different in handling than just three variables.

Body:
Updated answer for c++20 users:

C++20 adds support for class literal (class with constexpr constructor) non-type template parameters, which would allow the example in the original question to work, provided the template parameter is accepted by value:

template<Triple t> // Note: accepts t by value
class Foo { };

// Works with unnamed instantiation of Triple.
Foo<Triple { 1, 2, 3 }> f1 {};

// Also works if provided from a constexpr variable.
constexpr Triple t { 1, 2, 3 };
Foo<t> f2 {};

Further, all template parameter instances of Triple { 1, 2, 3 } throughout the program will refer to the same static storage duration object:

template<Triple t1, Triple t2>
void Func() {
    assert(&t1 == &t2); // Passes.
}

constexpr Triple t { 1, 2, 3 };

int main()
{
    Func<t, Triple {1, 2, 3}>();
}

From cppreference:

An identifier that names a non-type template parameter of class type T denotes a static storage duration object of type const T, called a template parameter object, whose value is that of the corresponding template argument after it has been converted to the type of the template parameter. All such template parameters in the program of the same type with the same value denote the same template parameter object.

Note that there are quite a few restrictions on the class literal types allowable by template parameters. For more detail, checkout this blog post I wrote explaining the usage and restrictions of literal class NTTPs: Literal Classes as Non-type Template Parameters in C++20.

ContentLicense: CC BY-SA 4.0


问:
List combinations and number of times they repeat in SQL
I'm not sure even exactly how to describe this issue, generally I have a small table (in SQL Server 2019) with 2 columns, not a lot of data, it looks like this

```<code>MechanicID       CarID
----------------------
1                   2
1                   3
2                   1
2                   3
4                   1
4                   2
4                   3
</code>```

Now the idea is to (using SELECT preferably, maybe a stored procedure if SELECT is impossible?) check how many times does a certain combination of cars happen.

Basically it lists combinations of cars which were serviced together and the number of mechanics that serviced those combinations. Only those combinations that are existent should appear.

The result should be:

```<code>Car combination        Number of occurrences
---------------------------------------------
1&2                    1
1&3                    2
2&3                    2
</code>```

So mechanic 1 has serviced cars 2&3, this combo has also been serviced by mechanic 4, so the number of occurrences is 2.

Help will be highly appreciated

答:
Use a self join and aggregation:</p>

```<code>select t1.carid, t2.carid, count(*)
from t t1 join
     t t2
     on t1.MechanicID = t2.MechanicID and
        t1.carid < t2.carid
group by t1.carid, t2.carid
</code>```

Body:
I'm not sure even exactly how to describe this issue, generally I have a small table (in SQL Server 2019) with 2 columns, not a lot of data, it looks like this

MechanicID       CarID
----------------------
1                   2
1                   3
2                   1
2                   3
4                   1
4                   2
4                   3

Now the idea is to (using SELECT preferably, maybe a stored procedure if SELECT is impossible?) check how many times does a certain combination of cars happen.

Basically it lists combinations of cars which were serviced together and the number of mechanics that serviced those combinations. Only those combinations that are existent should appear.

The result should be:

Car combination        Number of occurrences
---------------------------------------------
1&2                    1
1&3                    2
2&3                    2

So mechanic 1 has serviced cars 2&3, this combo has also been serviced by mechanic 4, so the number of occurrences is 2.

Help will be highly appreciated

Body:
Use a self join and aggregation:

select t1.carid, t2.carid, count(*)
from t t1 join
     t t2
     on t1.MechanicID = t2.MechanicID and
        t1.carid < t2.carid
group by t1.carid, t2.carid


问:
How to select until sum a column reaches a value?
i need to select records from a mysql table until sum a column reaches a goal value,
lets assume my table is that

```<code>CREATE TABLE Table1
    (
     id int auto_increment primary key,
     Date DateTime,
     type int,
     MyAmountCol int
    );

INSERT INTO Table1
(Date, type, MyAmountCol)
VALUES
('2013-02-01 00:00:00','85482','1'),
('2013-02-01 00:00:00','47228','2'),
('2013-02-02 00:00:00','12026','4'),
('2013-02-03 00:00:00','78927','6'),
('2013-02-04 00:00:00','85662','2'),
('2013-03-05 00:00:00','47978','1'),
('2013-08-07 00:00:00','8582','1');
</code>```

and this is the sql query i am trying .

```<code>SELECT
  O.Id,
  O.Type,
  O.MyAmountCol,
  (SELECT
     sum(MyAmountCol) FROM Table1
   WHERE Id <= O.Id) 'RunningTotal'
FROM Table1 O
HAVING RunningTotal <=8
</code>```

http://sqlfiddle.com/#!9/ec160/5

but doesn't work as needed,Any help would be greatly appreciated.

答:
DO it like this:</p>

```<code>;with cte as
(
select *,
sum(MyAmountCol) over(order by id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as RunningTotal from Table1
)
select * from cte where RunningTotal <= 8
</code>```

Body:
i need to select records from a mysql table until sum a column reaches a goal value,
lets assume my table is that

CREATE TABLE Table1
    (
     id int auto_increment primary key,
     Date DateTime,
     type int,
     MyAmountCol int
    );

INSERT INTO Table1
(Date, type, MyAmountCol)
VALUES
('2013-02-01 00:00:00','85482','1'),
('2013-02-01 00:00:00','47228','2'),
('2013-02-02 00:00:00','12026','4'),
('2013-02-03 00:00:00','78927','6'),
('2013-02-04 00:00:00','85662','2'),
('2013-03-05 00:00:00','47978','1'),
('2013-08-07 00:00:00','8582','1');

and this is the sql query i am trying .

SELECT
  O.Id,
  O.Type,
  O.MyAmountCol,
  (SELECT
     sum(MyAmountCol) FROM Table1
   WHERE Id <= O.Id) 'RunningTotal'
FROM Table1 O
HAVING RunningTotal <=8

http://sqlfiddle.com/#!9/ec160/5

but doesn't work as needed,Any help would be greatly appreciated.

Body:
DO it like this:

;with cte as
(
select *,
sum(MyAmountCol) over(order by id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as RunningTotal from Table1
)
select * from cte where RunningTotal <= 8


问:
Pick property from other type and select from union at same time
If i have this type for example:

type Stuff = {
    variants: 'primary' | 'secondary' | 'tertiary'
}
```

<p>And i want a second type with a key of <code>variants</code> but with a subset of the union above, lets say for this example only <code>primary</code> and <code>secondary</code>.</p>

<p>My understanding is you can do it like this:</p>

<pre class="lang-js prettyprint-override"><code>type StuffThree = {
    variants: Extract<Stuff['variants'], 'primary' | 'secondary'>
}
</code>```

This works, however, i would rather not have to state the key variants again, is this possible?.

I have tried the below but it doesn't seem to work

type StuffTwo = Pick<Extract<Stuff, 'variants'>, 'primary'>
```

Here's my attempt in the TS playground:

答:
You create a generic type that has this property variants and then use it with different types for the values.</p>

```<code>type VariantsObject<K> = {
    variants: K
}

type RestrictedVariants = 'primary' | 'secondary'
type AllVariants = RestrictedVariants | 'tertiary';

type Stuff1 = VariantsObject<AllVariants>

type Stuff2 = VariantsObject<RestrictedVariants>

</code>```

Body:
If i have this type for example:

type Stuff = {
    variants: 'primary' | 'secondary' | 'tertiary'
}

And i want a second type with a key of variants but with a subset of the union above, lets say for this example only primary and secondary.

My understanding is you can do it like this:

type StuffThree = {
    variants: Extract<Stuff['variants'], 'primary' | 'secondary'>
}

This works, however, i would rather not have to state the key variants again, is this possible?.

I have tried the below but it doesn't seem to work

type StuffTwo = Pick<Extract<Stuff, 'variants'>, 'primary'>

Here's my attempt in the TS playground:

Body:
You create a generic type that has this property variants and then use it with different types for the values.

type VariantsObject<K> = {
    variants: K
}

type RestrictedVariants = 'primary' | 'secondary'
type AllVariants = RestrictedVariants | 'tertiary';

type Stuff1 = VariantsObject<AllVariants>

type Stuff2 = VariantsObject<RestrictedVariants>


问:
How can I create a virtual environment with virtualenv for Python 3.7 without having to install Python 3.7 on my computer (Ubuntu 16.04.6 LTS x64)?
How can I create a virtual environment with virtualenv for Python 3.7 without having to install Python 3.7 on my computer (Ubuntu 16.04.6 LTS x64)?

```<code>virtualenv -p python3.7 /mnt/ilcompn0d1/user/dernonco/pyenv/codetest
</code>```

yields:

```<code>The executable python3.7 (from --python=python3.7) does not exist
</code>```

but I would prefer not to have to install Python 3.7 on my computer.

答:
You don't need to install Python 3.7 system-wide, but you do need to install it somewhere if you want to use it in a virtualenv. Easy options include via pyenv or pythonz.

If you install pyenv, install Python 3.7 via pyenv install 3.7, then create your virtualenv. Or use a higher-level tool like Pipenv, which can manage virtualenvs for you and install them via pyenv automatically:

Install pyenv

Install pipenv, e.g. with pip install --user pipenv

In a project directory, create  new virtualenv using pipenv:

```<code>pipenv install --python 3.7
</code>```

Python 3.7 will automatically be installed for your user via pyenv.

Alternatively, pew can do much the same thing via pythonz:

Install pew with the optional pythonz integration:

```<code>pip install --user pew[pythonz]
</code>```

Create a new virtualenv:

```<code>pew new -p $(pythonz locate 3.7) some-name
</code>```

Both of these solutions assume that you have the Python user directory added to your $PATH. On my system that's ~/.local/bin/. Use import site; print(site.USER_BASE) to double-check on your machine.

Body:
How can I create a virtual environment with virtualenv for Python 3.7 without having to install Python 3.7 on my computer (Ubuntu 16.04.6 LTS x64)?

virtualenv -p python3.7 /mnt/ilcompn0d1/user/dernonco/pyenv/codetest

yields:

The executable python3.7 (from --python=python3.7) does not exist

but I would prefer not to have to install Python 3.7 on my computer.

Body:
You don't need to install Python 3.7 system-wide, but you do need to install it somewhere if you want to use it in a virtualenv. Easy options include via pyenv or pythonz.

If you install pyenv, install Python 3.7 via pyenv install 3.7, then create your virtualenv. Or use a higher-level tool like Pipenv, which can manage virtualenvs for you and install them via pyenv automatically:

Install pyenv

Install pipenv, e.g. with pip install --user pipenv

In a project directory, create  new virtualenv using pipenv:

pipenv install --python 3.7

Python 3.7 will automatically be installed for your user via pyenv.

Alternatively, pew can do much the same thing via pythonz:

Install pew with the optional pythonz integration:

pip install --user pew[pythonz]

Create a new virtualenv:

pew new -p $(pythonz locate 3.7) some-name

Both of these solutions assume that you have the Python user directory added to your $PATH. On my system that's ~/.local/bin/. Use import site; print(site.USER_BASE) to double-check on your machine.


答:
In MySQL 8+ and the more recent versions of MySQL, you can use window functions:

```<code>select t1.*
from (select t1.*,
             sum(t1.amount) over (order by t1.id) as running_amount
      from table1 t1
     ) t1
where running_amount <= 8
</code>```

If you want the first that reaches or exceeds 8, then:

```<code>where running_amount - amount < 8
</code>```

In older versions, you can do this with a correlated subquery or variables:

```<code>select t1.*
from (select t1.*,
             (select sum(tt1.amount)
              from table1 tt1
              where tt1.id <= t1.id
             ) as running_amount
      from table1 t1
     ) t1
where running_amount <= 8;
</code>```

I prefer the subquery to the having clause, but that is just a preference.

Title: How to select until sum a column reaches a value?

Body:
In MySQL 8+ and the more recent versions of MySQL, you can use window functions:

select t1.*
from (select t1.*,
             sum(t1.amount) over (order by t1.id) as running_amount
      from table1 t1
     ) t1
where running_amount <= 8

If you want the first that reaches or exceeds 8, then:

where running_amount - amount < 8

In older versions, you can do this with a correlated subquery or variables:

select t1.*
from (select t1.*,
             (select sum(tt1.amount)
              from table1 tt1
              where tt1.id <= t1.id
             ) as running_amount
      from table1 t1
     ) t1
where running_amount <= 8;

I prefer the subquery to the having clause, but that is just a preference.


问:
Average UDP packet loss and packet re-ordering
I'd like to garner fellow SO'ers experience with regards to the issue of UDP packet loss (or drop-out).

Initially my understanding is that given direct point to point connections where the NICs are connected via a crossover cable and ample buffer on the NICs and timely processing of said buffers, that there 'should' be no packet loss or packet ordering issues. I believe this is also the case given one good/high-end switch in between the points.

Excluding the above scenario, what is the expected average UDP packet loss over a LAN

What scenarios cause UDP packet ordering issues?

答:
No idea on the UDP packetloss on average LANs. I assume reasonably low on modern switched networks, otherwise your LAN or endpoints are too highly loaded. :)

The re-ordering is probably easiest to achieve when routes are brought up and down; say, one of the switches in your organization is under enough load that re-organizing the tree makes sense and traffic is sent through different switches. More likely is your ISP's peers coming and going, or reaching traffic limits, and the priority of packets through them changes -- old packets were in flight on the heavy-loaded network, new packets are in flight on the lighter-loaded network, and they arrive out of order.


问:
how do I display the correct output when no positve numbers are entered
I'm new to coding. Assignment is to calculate the average of all the positive numbers input and exit when a zero is input. If no positive numbers are input display a message average not possible.  </p>

<p>The following is what I have so far. I am stuck on the part about printing out the message "cannot calculate the average" when only a zero or negative numbers are input. </p>

```<code>public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int numbers = 0;
    int sumOfNumbers = 0;
    double averagePositive = 0;
    while (true) {
        System.out.println("Give a number: ");
        int number = Integer.valueOf(scanner.nextLine());
        if (number == 0)
            break;

        if (number > 0)
            sumOfNumbers = number + sumOfNumbers;

        if (number > 0)
            numbers = numbers + 1;

        if (number > 0)
            averagePositive = (double)sumOfNumbers / (double)numbers;
    }
    System.out.println(averagePositive);
}
</code>```

答:
Try it as follows...</p>

```<code>public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Give a number: ");
    int num=input.nextInt();
    int tot=0; //total
    int count=0; // counting the positive numbers
    if(num>0){
         while(num!=0){
             tot+=num;
             count++;
             System.out.print("Give a number: ");
             num=input.nextInt();
             if(num<0){
              System.out.print("Not possible");
              return;
              }
         }
         double avg =(double)tot/n;
         System.out.print("Average: "+avg);

    }else{
         System.out.println("Cannot calculate the average.");
    }

}
</code>```

Body:
I'm new to coding. Assignment is to calculate the average of all the positive numbers input and exit when a zero is input. If no positive numbers are input display a message average not possible.

The following is what I have so far. I am stuck on the part about printing out the message "cannot calculate the average" when only a zero or negative numbers are input.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int numbers = 0;
    int sumOfNumbers = 0;
    double averagePositive = 0;
    while (true) {
        System.out.println("Give a number: ");
        int number = Integer.valueOf(scanner.nextLine());
        if (number == 0)
            break;

        if (number > 0)
            sumOfNumbers = number + sumOfNumbers;

        if (number > 0)
            numbers = numbers + 1;

        if (number > 0)
            averagePositive = (double)sumOfNumbers / (double)numbers;
    }
    System.out.println(averagePositive);
}

Body:
Try it as follows...

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Give a number: ");
    int num=input.nextInt();
    int tot=0; //total
    int count=0; // counting the positive numbers
    if(num>0){
         while(num!=0){
             tot+=num;
             count++;
             System.out.print("Give a number: ");
             num=input.nextInt();
             if(num<0){
              System.out.print("Not possible");
              return;
              }
         }
         double avg =(double)tot/n;
         System.out.print("Average: "+avg);

    }else{
         System.out.println("Cannot calculate the average.");
    }

}


问:
IGRAPH Python - How to find source code of modularity?
Ok, so IGRAPH is open source. That means I should be able to find the source code where they compute the modularity of a partition. But I've been searching in their site and the best I could find is some comments explaining how they did it, but no code (https://igraph.org/python/doc/igraph-pysrc.html#GraphBase.modularity line 820). Am I blind or their implementation isn't avaliable on their site?</p>

答:
The GraphBase class is not defined in the Python code, but in a C extension wrapping the igraph library.

You can find the implementation of the modularity method in igraph/src/community.c, e.g. on GitHub:

https://github.com/igraph/igraph/blob/98969b233d1d97a2dc271fac0036394d2abdaa3c/src/community.c#L907


问:
TimeZone name / abbreviation from offset
I'm starting with a GMT offset in seconds, and I want the name of the corresponding time zone. I'm saying:

```<code>let offset = -28800
let tz = TimeZone(secondsFromGMT: offset)
let tzname = tz?.localizedName(for: .standard, locale: Locale.current)
</code>```

I've tried many ways of getting tzname but all I ever get is GMT-05:00. That's not what I want. I'm hoping for something like "Eastern Standard Time" or "EST". Is there a way to get it?

I do not want to pass through some sort of reverse geocoding. I expect the system simply to hand me the answer. Other responses to this sort of question on Stack Overflow seem to indicate that that's what it ought to do, but it isn't doing it.

答:
You cannot use the seconds offset from GMT, alone, to uniquely determine the timezone abbreviation. There is not a one-to-one correspondence between offsets and timezones.

This probably isn't going to be satisfying, but you can get a list of matching timezones by iterating through the knownTimeZoneIdentifiers and find a list of matching time zones:

```<code>let abbreviationsAndIdentifiers = TimeZone.knownTimeZoneIdentifiers
    .compactMap { TimeZone(identifier: $0) }
    .filter { $0.secondsFromGMT() == -28800 }
</code>```

From there, you can use map to grab either abbreviation(for:), identifier or localizedName(for:locale:) to get PST, America/Los_Angeles or Pacific Standard Time for -28800, respectively. Obviously, the above may return a variety of different matches depending on the offset and time of year.

A few caveats for future readers:

Timezone abbreviations are not unique. See https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations and you’ll see the same three letter abbreviation mapping to completely different time zones. E.g. CST can mean “Central Standard Time” (in North America), “Cuba Standard Time” or “China Standard Time”.

Be wary about the fact that an offset from GMT of -28800 will result in different timezones depending upon the time of the year. E.g. -28800 will return one set of timezone matches in January and another set in July because of daylight savings. Consider using secondsFromGMT(for:), specifying the date, instead, to remove any ambiguity.

Body:
I'm starting with a GMT offset in seconds, and I want the name of the corresponding time zone. I'm saying:

let offset = -28800
let tz = TimeZone(secondsFromGMT: offset)
let tzname = tz?.localizedName(for: .standard, locale: Locale.current)

I've tried many ways of getting tzname but all I ever get is GMT-05:00. That's not what I want. I'm hoping for something like "Eastern Standard Time" or "EST". Is there a way to get it?

I do not want to pass through some sort of reverse geocoding. I expect the system simply to hand me the answer. Other responses to this sort of question on Stack Overflow seem to indicate that that's what it ought to do, but it isn't doing it.

Body:
You cannot use the seconds offset from GMT, alone, to uniquely determine the timezone abbreviation. There is not a one-to-one correspondence between offsets and timezones.

This probably isn't going to be satisfying, but you can get a list of matching timezones by iterating through the knownTimeZoneIdentifiers and find a list of matching time zones:

let abbreviationsAndIdentifiers = TimeZone.knownTimeZoneIdentifiers
    .compactMap { TimeZone(identifier: $0) }
    .filter { $0.secondsFromGMT() == -28800 }

From there, you can use map to grab either abbreviation(for:), identifier or localizedName(for:locale:) to get PST, America/Los_Angeles or Pacific Standard Time for -28800, respectively. Obviously, the above may return a variety of different matches depending on the offset and time of year.

A few caveats for future readers:

Timezone abbreviations are not unique. See https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations and you’ll see the same three letter abbreviation mapping to completely different time zones. E.g. CST can mean “Central Standard Time” (in North America), “Cuba Standard Time” or “China Standard Time”.

Be wary about the fact that an offset from GMT of -28800 will result in different timezones depending upon the time of the year. E.g. -28800 will return one set of timezone matches in January and another set in July because of daylight savings. Consider using secondsFromGMT(for:), specifying the date, instead, to remove any ambiguity.


问:
Eliminating forced downcasts
I am using swiftlint as a way to code better, and for the most part I have been able to muddle my way through up to the following code which includes a forced downcast:

```<code>let questionToAdd = MultipleChoiceQuestion(question: dictionary["Question"] as! String,
            correctAnswer: dictionary["CorrectAnswer"] as! String,
            answers: dictionary["Answers"] as! [String])
           questions.append(questionToAdd)
</code>```

I have been unable to remove the forced unwrapping.  Any suggestions would be greatly appreciated.  I have tried used the ELSE { return } but that isn't working either, could be the way I had it structured..nonetheless any help or point me in the right direction would be appreciated.

答:
The alternative to forced cast is an optional cast using as?. Typically you'd unwrap the results of those casts and then use the values, like this:

guard let question = dictionary["Question"] as? String,
    let answer = dictionary["CorrectAnswer"] as? String,
    let answers = dictionary["Answers"] as? [String] else { return }

questions.append(MultipleChoiceQuestion(question: question, answer: answer, answers: answers))
```

However, since it looks like you're decoding something like JSON, a better choice would be to implement Decodable for your MultipleChoiceQuestion type do this transform for you.

Title: Eliminating forced downcasts

Body:
I am using swiftlint as a way to code better, and for the most part I have been able to muddle my way through up to the following code which includes a forced downcast:

let questionToAdd = MultipleChoiceQuestion(question: dictionary["Question"] as! String,
            correctAnswer: dictionary["CorrectAnswer"] as! String,
            answers: dictionary["Answers"] as! [String])
           questions.append(questionToAdd)

I have been unable to remove the forced unwrapping.  Any suggestions would be greatly appreciated.  I have tried used the ELSE { return } but that isn't working either, could be the way I had it structured..nonetheless any help or point me in the right direction would be appreciated.

Body:
The alternative to forced cast is an optional cast using as?. Typically you'd unwrap the results of those casts and then use the values, like this:

guard let question = dictionary["Question"] as? String,
    let answer = dictionary["CorrectAnswer"] as? String,
    let answers = dictionary["Answers"] as? [String] else { return }

questions.append(MultipleChoiceQuestion(question: question, answer: answer, answers: answers))

However, since it looks like you're decoding something like JSON, a better choice would be to implement Decodable for your MultipleChoiceQuestion type do this transform for you.


问:
Dequeing reusable Cell crash in tableView
I'm having some troubles adding new cells on table view.

The strange thing is that I run once the function works perfectly without problems, if I do it for a second time it crash with this error.

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

Here my code:

```<code>override func viewWillAppear(_ animated: Bool) {
    if prodottoDaAggiungere != nil {
        prodotti.append(prodottoDaAggiungere!)
        let indexPath = IndexPath(row: prodotti.count-1, section: 1)
        tableView.insertRows(at: [indexPath], with: .fade) // ?
        prodottoDaAggiungere = nil
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row < prodotti.count && indexPath.section == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ProdottoTableViewCell", for: indexPath) as! ProdottoTableViewCell // Crash :|
        let indexRow = indexPath.row // Fix
        cell.title.text = "\(prodotti[indexRow].prodotto.nome!) - \(prodotti[indexRow].prodotto.marca!)"
        cell.subtitle.text = "\(prodotti[indexRow].prodotto.formati[prodotti[indexRow].formato].dimensione) \(prodotti[indexRow].prodotto.unitàMisura!) - \(prodotti[indexRow].prodotto.formati[prodotti[indexRow].formato].prezzo) €"
        cell.number.text = Int(cell.stepper.value).description // 1
        cell.stepper.addTarget(self, action: #selector(stepperChanged), for: .valueChanged)
        return cell
    }

    return super.tableView(tableView, cellForRowAt: indexPath)
}
</code>```

Using breakpoint I founded app crash on the dequeueReusableCell but I cannot understand why, someone could tell me why this code crash?

Here my tableView numberOfRowsInSection func:

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    if section == 0 {
        return 1
    } else if section == 1 {
        return 1+prodotti.count
    } else {
        return 0
    }
}
</code>```

Really thanks
AP

答:
I've got the solution for you:

https://stackoverflow.com/a/49157374/8737121

Really thanks to:
Shan Ye

Body:
I'm having some troubles adding new cells on table view.

The strange thing is that I run once the function works perfectly without problems, if I do it for a second time it crash with this error.

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

Here my code:

override func viewWillAppear(_ animated: Bool) {
    if prodottoDaAggiungere != nil {
        prodotti.append(prodottoDaAggiungere!)
        let indexPath = IndexPath(row: prodotti.count-1, section: 1)
        tableView.insertRows(at: [indexPath], with: .fade) // ?
        prodottoDaAggiungere = nil
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row < prodotti.count && indexPath.section == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ProdottoTableViewCell", for: indexPath) as! ProdottoTableViewCell // Crash :|
        let indexRow = indexPath.row // Fix
        cell.title.text = "\(prodotti[indexRow].prodotto.nome!) - \(prodotti[indexRow].prodotto.marca!)"
        cell.subtitle.text = "\(prodotti[indexRow].prodotto.formati[prodotti[indexRow].formato].dimensione) \(prodotti[indexRow].prodotto.unitàMisura!) - \(prodotti[indexRow].prodotto.formati[prodotti[indexRow].formato].prezzo) €"
        cell.number.text = Int(cell.stepper.value).description // 1
        cell.stepper.addTarget(self, action: #selector(stepperChanged), for: .valueChanged)
        return cell
    }

    return super.tableView(tableView, cellForRowAt: indexPath)
}

Using breakpoint I founded app crash on the dequeueReusableCell but I cannot understand why, someone could tell me why this code crash?

Here my tableView numberOfRowsInSection func:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    if section == 0 {
        return 1
    } else if section == 1 {
        return 1+prodotti.count
    } else {
        return 0
    }
}

Really thanks
AP


问:
Add a date column to a temporary table in SQL
I am working with a temporary table in Netezza that contains the columns id, gender, start_date, and end_date. I am trying to add a new column to this table that contains a default date of 2019-01-01 for all rows. The table to which I want to add this column is a local temp table, so ALTER TABLE does not work ("Error: Operation not allowed on a temp table"). To get around this, I created a new temp table with an appropriately-named empty column, but now I find I cannot use UPDATE/SET to populate it with my date ("Error: Value too large for column"). What is the best way to alter my temp table to include a new column with my date in it? If possible, I would like to just directly modify the old temp table rather than creating a new one. Note: I do not have the necessary administrator privileges in the database I'm working in to just create a permanent table to ALTER instead.

The code that successfully created a new temp table with an empty column is:

```<code>DROP TABLE new_temp_table IF EXISTS;
GO
SELECT id, gender, start_date, end_date, NULL default_date
INTO TEMP TABLE new_temp_table
FROM old_temp_table;
GO
</code>```

The code that does not work to replace the NULL values in the new column is:

```<code>UPDATE new_temp_table
SET default_date = '2019-01-01';
GO
</code>```

答:
Cast NULL as the type you want:

```<code>SELECT id, gender, start_date, end_date,
       CAST(NULL as DATE) as default_date
INTO TEMP TABLE new_temp_table
FROM old_temp_table;
</code>```

Netezza doesn't know what the type is, so it makes a guess.  And that guess is unlikely to be a date (I think it is an int).

Body:
I am working with a temporary table in Netezza that contains the columns id, gender, start_date, and end_date. I am trying to add a new column to this table that contains a default date of 2019-01-01 for all rows. The table to which I want to add this column is a local temp table, so ALTER TABLE does not work ("Error: Operation not allowed on a temp table"). To get around this, I created a new temp table with an appropriately-named empty column, but now I find I cannot use UPDATE/SET to populate it with my date ("Error: Value too large for column"). What is the best way to alter my temp table to include a new column with my date in it? If possible, I would like to just directly modify the old temp table rather than creating a new one. Note: I do not have the necessary administrator privileges in the database I'm working in to just create a permanent table to ALTER instead.

The code that successfully created a new temp table with an empty column is:

DROP TABLE new_temp_table IF EXISTS;
GO
SELECT id, gender, start_date, end_date, NULL default_date
INTO TEMP TABLE new_temp_table
FROM old_temp_table;
GO

The code that does not work to replace the NULL values in the new column is:

UPDATE new_temp_table
SET default_date = '2019-01-01';
GO

Body:
Cast NULL as the type you want:

SELECT id, gender, start_date, end_date,
       CAST(NULL as DATE) as default_date
INTO TEMP TABLE new_temp_table
FROM old_temp_table;

Netezza doesn't know what the type is, so it makes a guess.  And that guess is unlikely to be a date (I think it is an int).


问:
How to find the inverse for the inverse sampling method in R
Generally for the inverse sampling method, we have a density and we would like to sample from it. A first step is to find the the cumulative density function for the density. Then to find it's inverse, and finally to find the inverse function for a randomly sampled value from the uniform distribution.

For example, I have this function y= ((3/2)/(1+x)^2) so the cdf equals (3x)/2(x+1) and the inverse of the cdf is ((3/2)*u)/(1-(3/2)*u)

To do this in R, I wrote

```<code> f<-function(x){
 y= ((3/2)/(1+x)^2)
 return(y)
}

cdf <- function(x){
  integrate(f, -Inf, x)$value
}

invcdf <- function(q){
  uniroot(function(x){cdf(x) - q}, range(x))$root
}
U <- runif(1e6)
X <- invcdf(U)
</code>```

I have two problem! First: the code returns the function and not the samples.
The second: is there another simple way to do this work? for example to find the cdf and inverse in more simple ways?

I would like to add that I am not looking for efficiency of the code. I am just interested of a code that could be written by a beginner.

答:
You could try a numerical approach to inverse sampling. As per your request, this is more about transparency of method than efficiency.

This function will numerically integrate a given function over the given range (though it will trim infinite values)

```<code>cdf <- function(f, lower_bound, upper_bound)
{
  if(lower_bound < -10000) lower_bound <- -10000          # Trim large negatives
  if(upper_bound > 10000) upper_bound <- 10000            # Trim large positive
  x <- seq(lower_bound, upper_bound, length.out = 100001) # Finely divide x axis
  delta <- mean(diff(x))                                  # Get delta x (i.e. dx)
  mid_x <- (x[-1] + x[-length(x)])/2                      # Get the mid point of each slice
  result <- cumsum(delta * f(mid_x))                      # sum f(x) dx
  result <- result / max(result)                          # normalize
  list(x = mid_x, cdf = result)                           # return both x and f(x) in list
}
</code>```

And to get the inverse, we find the closest value in the cdf of a random number drawn from the uniform distribution between 0 and 1. We then see which value of x corresponds to that value of the cdf. We want to be able to do this for n samples at a time so we use sapply:

```<code>inverse_sample <- function(f, n = 1, lower_bound = -1000, upper_bound = 1000)
{
  CDF <- cdf(f, lower_bound, upper_bound)
  samples <- runif(n)
  sapply(samples, function(s) CDF$x[which.min(abs(s - CDF$cdf))])
}
</code>```

We can test it by drawing histograms of the results. We'll start with the normal distribution's density function (dnorm in R), drawing 1000 samples and plotting their distribution:

```<code>hist(inv_sample(dnorm, 1000))
</code>```

And we can do the same for the exponential distribution, this time setting the limits of integration between 0 and 100:

```<code>hist(inv_sample(dexp, 1000, 0, 100))
</code>```

And finally we can do the same with your own example:

f <- function(x) 3/2/(1 + x)^2

hist(inv_sample(f, 1000, 0, 10))
```

Body:
Generally for the inverse sampling method, we have a density and we would like to sample from it. A first step is to find the the cumulative density function for the density. Then to find it's inverse, and finally to find the inverse function for a randomly sampled value from the uniform distribution.

For example, I have this function y= ((3/2)/(1+x)^2) so the cdf equals (3x)/2(x+1) and the inverse of the cdf is ((3/2)*u)/(1-(3/2)*u)

To do this in R, I wrote

 f<-function(x){
 y= ((3/2)/(1+x)^2)
 return(y)
}

cdf <- function(x){
  integrate(f, -Inf, x)$value
}

invcdf <- function(q){
  uniroot(function(x){cdf(x) - q}, range(x))$root
}
U <- runif(1e6)
X <- invcdf(U)

I have two problem! First: the code returns the function and not the samples.
The second: is there another simple way to do this work? for example to find the cdf and inverse in more simple ways?

I would like to add that I am not looking for efficiency of the code. I am just interested of a code that could be written by a beginner.

Body:
You could try a numerical approach to inverse sampling. As per your request, this is more about transparency of method than efficiency.

This function will numerically integrate a given function over the given range (though it will trim infinite values)

cdf <- function(f, lower_bound, upper_bound)
{
  if(lower_bound < -10000) lower_bound <- -10000          # Trim large negatives
  if(upper_bound > 10000) upper_bound <- 10000            # Trim large positive
  x <- seq(lower_bound, upper_bound, length.out = 100001) # Finely divide x axis
  delta <- mean(diff(x))                                  # Get delta x (i.e. dx)
  mid_x <- (x[-1] + x[-length(x)])/2                      # Get the mid point of each slice
  result <- cumsum(delta * f(mid_x))                      # sum f(x) dx
  result <- result / max(result)                          # normalize
  list(x = mid_x, cdf = result)                           # return both x and f(x) in list
}

And to get the inverse, we find the closest value in the cdf of a random number drawn from the uniform distribution between 0 and 1. We then see which value of x corresponds to that value of the cdf. We want to be able to do this for n samples at a time so we use sapply:

inverse_sample <- function(f, n = 1, lower_bound = -1000, upper_bound = 1000)
{
  CDF <- cdf(f, lower_bound, upper_bound)
  samples <- runif(n)
  sapply(samples, function(s) CDF$x[which.min(abs(s - CDF$cdf))])
}

We can test it by drawing histograms of the results. We'll start with the normal distribution's density function (dnorm in R), drawing 1000 samples and plotting their distribution:

hist(inv_sample(dnorm, 1000))

And we can do the same for the exponential distribution, this time setting the limits of integration between 0 and 100:

hist(inv_sample(dexp, 1000, 0, 100))

And finally we can do the same with your own example:

f <- function(x) 3/2/(1 + x)^2

hist(inv_sample(f, 1000, 0, 10))


问:
Query Single Document Based on Single Field Firestore
I have recently been working with React and Firebase to create a project where I would need to find specific documents in my collection based on their fields.

Currently, the only way to do this is by the following:

```<code>let ref = myFirebase.firestore().collection("Users");
let refQuery = ref.where('Token', '==', userUID);
</code>```

This will give me the result I am looking for but in my rules I would have to allow my user to allow list or allow read for the collection Users. To my understanding, this will be a potential hazard because I'm allowing the user to go through all the users in my collection. Instead, I want to be able to keep my rules to only allow get so only the user can retrieve his own information but it won't work with my query code above.

Is there anyway I can change my React query code to be able to put my rules to only allow get for my user in my Users collection?

Here is a snippet from my rules that I want to implement:

```<code>match /Users/{UsersDoc} {
    allow create: if request.auth.uid != null;
    allow update, delete, get: if request.auth.uid == resource.data.Token;
}
</code>```

答:
allow get only works for individual document gets, and not for queries.

What you have now is actually exactly what you want, except you just want to apply it to read access:

```<code>allow update, delete, read: if request.auth.uid == resource.data.Token;
</code>```

This does not allow the user to "go through all the users", as you're suggesting.  It forces the user to only query Users with the filter on Token that you require.  Any other query that doesn't filter correctly on Token will be rejected.  This is something that you should be able to test pretty easily.

Body:
I have recently been working with React and Firebase to create a project where I would need to find specific documents in my collection based on their fields.

Currently, the only way to do this is by the following:

let ref = myFirebase.firestore().collection("Users");
let refQuery = ref.where('Token', '==', userUID);

This will give me the result I am looking for but in my rules I would have to allow my user to allow list or allow read for the collection Users. To my understanding, this will be a potential hazard because I'm allowing the user to go through all the users in my collection. Instead, I want to be able to keep my rules to only allow get so only the user can retrieve his own information but it won't work with my query code above.

Is there anyway I can change my React query code to be able to put my rules to only allow get for my user in my Users collection?

Here is a snippet from my rules that I want to implement:

match /Users/{UsersDoc} {
    allow create: if request.auth.uid != null;
    allow update, delete, get: if request.auth.uid == resource.data.Token;
}

Body:
allow get only works for individual document gets, and not for queries.

What you have now is actually exactly what you want, except you just want to apply it to read access:

allow update, delete, read: if request.auth.uid == resource.data.Token;

This does not allow the user to "go through all the users", as you're suggesting.  It forces the user to only query Users with the filter on Token that you require.  Any other query that doesn't filter correctly on Token will be rejected.  This is something that you should be able to test pretty easily.


问:
How to edit an specific word from a I/O File Java
So I'm trying to modify a line from my textFile but when i put the new values and print the result, it prints in a whole new line at the bottom as if it were the last line instead of replacing the line i want to replace.</p>

```<code> try {

                 LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
                 PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
                 boolean finder = false;

                 String oldContent = "";

                 while((target = readers.readLine()) != null)
                 {
                     if(target.contains(CL.getID()))
                     {
                         finder = true;
                         target = readers.readLine() + 1;
                         System.out.println("Escriba el Nuevo presupuesto");
                         CL.setPresupuesto(reader.next());
                         output.write("Presupuesto: " + CL.getID() + "$");

                         System.out.println("Nuevo Presupuesto");

                         output.close();
                         readers.close();
                         break;
                     }

                 }

                 if(finder == false)
                 {
                     System.out.println("ID no encontrado!!");
                 }

             }catch(IOException ex) {

             }
</code>```

答: I don't think there's any such way to delete a specific line in the original file. What you can try to do is create a new file without that specific line. This would create a new file but  serve the purpose.</p>

Body:
So I'm trying to modify a line from my textFile but when i put the new values and print the result, it prints in a whole new line at the bottom as if it were the last line instead of replacing the line i want to replace.

 try {

                 LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
                 PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
                 boolean finder = false;

                 String oldContent = "";

                 while((target = readers.readLine()) != null)
                 {
                     if(target.contains(CL.getID()))
                     {
                         finder = true;
                         target = readers.readLine() + 1;
                         System.out.println("Escriba el Nuevo presupuesto");
                         CL.setPresupuesto(reader.next());
                         output.write("Presupuesto: " + CL.getID() + "$");

                         System.out.println("Nuevo Presupuesto");

                         output.close();
                         readers.close();
                         break;
                     }

                 }

                 if(finder == false)
                 {
                     System.out.println("ID no encontrado!!");
                 }

             }catch(IOException ex) {

             }


问:
Cannot Read an item from a DynamoDB Table using the DynamoDB Node SDK docClient
I am new to DynamoDB docClient for Node. I am trying to do a simple read an item call but it throws this error

```<code>The provided key element does not match the schema
</code>```

The link that I am following
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html#GettingStarted.NodeJs.03.02

Here is my code

```<code>const id = req.params; //value is 83166ce1-b36b-4074-b586-e2468346eb03
const docClient = new AWS.DynamoDB.DocumentClient();

const params = {
  TableName: 'users',
  Key: {
    'id': id,
  }
};

docClient.get(params, function(err, data) {
  if (err) {
    console.log(err);
    res.status(500).send("Error fetching user item from DB");
  } else {
    res.status(200).json(data.promoCredits);
  }
});
</code>```

Here is my table configuration
Table Configuration

My Items

Items in Table

I have tried to google but I cannot find an answer to this. Currently I am returning all my users and manually filtering but that is not the optimal solution. Please help.

Hitting my request like this

```<code>http://localhost:8081/api/user/getPromoCredits/83166ce1-b36b-4074-b586-e2468346eb03
</code>```

my endpoint config is

```<code>app.get('/api/user/getPromoCredits/:id', user.getUserPromoCredits);
</code>```

Thank you

答:
It was an issue where I was not deconstructing my id, and id was of type Object. Based on the two comments above, thank you so much for your help...

Updated to

```<code>const { id } = req.params;
</code>```

Body:
I am new to DynamoDB docClient for Node. I am trying to do a simple read an item call but it throws this error

The provided key element does not match the schema

The link that I am following
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html#GettingStarted.NodeJs.03.02

Here is my code

const id = req.params; //value is 83166ce1-b36b-4074-b586-e2468346eb03
const docClient = new AWS.DynamoDB.DocumentClient();

const params = {
  TableName: 'users',
  Key: {
    'id': id,
  }
};

docClient.get(params, function(err, data) {
  if (err) {
    console.log(err);
    res.status(500).send("Error fetching user item from DB");
  } else {
    res.status(200).json(data.promoCredits);
  }
});

Here is my table configuration
Table Configuration

My Items

Items in Table

I have tried to google but I cannot find an answer to this. Currently I am returning all my users and manually filtering but that is not the optimal solution. Please help.

Hitting my request like this

http://localhost:8081/api/user/getPromoCredits/83166ce1-b36b-4074-b586-e2468346eb03

my endpoint config is

app.get('/api/user/getPromoCredits/:id', user.getUserPromoCredits);

Thank you

Body:
It was an issue where I was not deconstructing my id, and id was of type Object. Based on the two comments above, thank you so much for your help...

Updated to

const { id } = req.params;


问:
Parameter in Controller is giving null value exception in asp.net mvc
I am making a text-box with drop down for auto-completing suggestion using jquery and ajax but the error I have found through debugging is that when the debug point comes to the given code it successfully moves to return statement and when comes second time on the same statement it gives an exception that "Keyword is null" (Keyword is the alphabet entered by the user in the textbox)

```<code>var result = (from a in objGameList where
a.GameName.ToLower().StartsWith(keyword.ToLower())
select new { a.GameName });
</code>```

Here is the code:

Index.cs

```<code><script type="text/javascript">
    $(document).ready(function () {
        $("#GameName").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { keyword: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.GameName, value: item.GameName };
                        }))
                    },
                    error: function () {
                        alert('something went wrong !');
                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <div class="form-group">
            <div>
                @Html.EditorFor(model => model.GameName, new { htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>
    </div>
}
```
```
<p><strong>Controller.cs</strong></p>
```[HttpPost]
    public JsonResult Index(string keyword)
    {
        //This can be replaced with database call.

        List<Games> objGameList = new List<Games>(){
            new Games {Id=1,GameName="Cricket" },
            new Games {Id=2,GameName="Football" },
            new Games {Id=3,GameName="Chesh" },
            new Games {Id=4,GameName="VallyBall" },
        };

        var result = (from a in objGameList
                        where a.GameName.ToLower().StartsWith(keyword.ToLower())
                        select new { a.GameName });

        return Json(result);
    }
```

Thanks in advance.

答:
```<code>dataType: "json",
data: { keyword: request.term },
</code>```

You are sending data as JSON like this. That means that there is a single object being sent to the server with a keyword property.

When sending JSON objects to the server, you should always create a custom complex object in order for ASP.NET Core to deserialize it properly:

```<code>public class AutoCompleteViewModel
{
    public string Keyword { get; set; }
}
</code>```

```<code>[HttpPost]
public JsonResult Index(AutoCompleteViewModel model)
{
    // work with model.Keyword instead
}
</code>```

Body:
I am making a text-box with drop down for auto-completing suggestion using jquery and ajax but the error I have found through debugging is that when the debug point comes to the given code it successfully moves to return statement and when comes second time on the same statement it gives an exception that "Keyword is null" (Keyword is the alphabet entered by the user in the textbox)

var result = (from a in objGameList where
a.GameName.ToLower().StartsWith(keyword.ToLower())
select new { a.GameName });

Here is the code:

Index.cs

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

                @Html.EditorFor(model => model.GameName, new { htmlAttributes = new { @class = "form-control" } })

}
```

Controller.cs

[HttpPost]
    public JsonResult Index(string keyword)
    {
        //This can be replaced with database call.

        List<Games> objGameList = new List<Games>(){
            new Games {Id=1,GameName="Cricket" },
            new Games {Id=2,GameName="Football" },
            new Games {Id=3,GameName="Chesh" },
            new Games {Id=4,GameName="VallyBall" },
        };

        var result = (from a in objGameList
                        where a.GameName.ToLower().StartsWith(keyword.ToLower())
                        select new { a.GameName });

        return Json(result);
    }

Thanks in advance.

Body:
dataType: "json",
data: { keyword: request.term },

You are sending data as JSON like this. That means that there is a single object being sent to the server with a keyword property.

When sending JSON objects to the server, you should always create a custom complex object in order for ASP.NET Core to deserialize it properly:

public class AutoCompleteViewModel
{
    public string Keyword { get; set; }
}

[HttpPost]
public JsonResult Index(AutoCompleteViewModel model)
{
    // work with model.Keyword instead
}


问:
Dockerized MongoDB Failing to connect on Heroku from NodeJs Container
i have a node web service and I'm a bit new to docker, so please bear with me.  Below is my docker-compose file.  I have run this image locally and it works fine, but when trying to deploy it to Heroku I get the following error:

```<code>{ MongoError: failed to connect to server [mongo:27017] on first connect [MongoError: getaddrinfo ENOTFOUND mongo mongo:27017]
</code>```

I've found where I'm supposed to set the environment flags in Heroku, so I managed to check that and its fine.  But it still can't find mongo:27017

What could I be doing wrong?

```<code>version: "3"
services:
  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - ./data:/data/charecters
    ports:
      - "27017:27017"
    environment:
      - MONGO_INITDB_ROOT_USERNAME=admin
      - MONGO_INITDB_ROOT_PASSWORD=password
  mongo-seed:
    build: ./mongo-seed
    links:
      - mongo
    volumes:
      - ./mongo-seed:/mongo-seed
    command:
      - /mongo-seed/script.sh
  app:
    container_name: app
    restart: always
    build: .
    ports:
      - "3000:3000"
    links:
      - mongo
    environment:
      - DB_SERVERS=mongo:27017
</code>```

答:
```<code>links:
      - mongo

is depreciated try

depends_on:
     - mongo

also, check that

mongo:
    container_name: mongo, is properly referenced in DB setup

change command:
  - /mongo-seed/script.sh

try command:
   - 'node your-app-file'
</code>```

Body:
i have a node web service and I'm a bit new to docker, so please bear with me.  Below is my docker-compose file.  I have run this image locally and it works fine, but when trying to deploy it to Heroku I get the following error:

{ MongoError: failed to connect to server [mongo:27017] on first connect [MongoError: getaddrinfo ENOTFOUND mongo mongo:27017]

I've found where I'm supposed to set the environment flags in Heroku, so I managed to check that and its fine.  But it still can't find mongo:27017

What could I be doing wrong?

version: "3"
services:
  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - ./data:/data/charecters
    ports:
      - "27017:27017"
    environment:
      - MONGO_INITDB_ROOT_USERNAME=admin
      - MONGO_INITDB_ROOT_PASSWORD=password
  mongo-seed:
    build: ./mongo-seed
    links:
      - mongo
    volumes:
      - ./mongo-seed:/mongo-seed
    command:
      - /mongo-seed/script.sh
  app:
    container_name: app
    restart: always
    build: .
    ports:
      - "3000:3000"
    links:
      - mongo
    environment:
      - DB_SERVERS=mongo:27017


问:
How to force a link to use specific route (MVC routing)
I have these two routes:

```<code>routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "Default2", // Route name
            "{controller}/{action}/{OrderId}/{CustomerID}", // URL with parameters
            new { controller = "NorthwindOrders", action = "Index", OrderId = UrlParameter.Optional, CustomerID = UrlParameter.Optional } // Parameter defaults
        );
</code>```

and want to create link that uses the second route.

How can I do this?

答:
As well you should use definition of routes in different order.
the order should be more specific first to less

also in your action links i would add routing parameters

Body:
I have these two routes:

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "Default2", // Route name
            "{controller}/{action}/{OrderId}/{CustomerID}", // URL with parameters
            new { controller = "NorthwindOrders", action = "Index", OrderId = UrlParameter.Optional, CustomerID = UrlParameter.Optional } // Parameter defaults
        );

and want to create link that uses the second route.

How can I do this?


问:
ngrams analysis in tidytext in R
I am trying to do ngram analysis for in tidytext, I have a corpus of 770 speeches. However the function unnest_tokens in tidytext takes data frame as input. when i checked with the example (jane austin books) each line of the book is stored as row in a data frame. i am not able to convert the corpus into a dataframe, neither for one speech at a time nor for all the corpus at once.

What is the way i can run ngrams (n=2,3, etc) analysis on tidytext using unnest tokens on my corpus. Can someone please suggest?

Thanks

答:
You say that you have a "corpus" of 770 speeches. Do you mean you have a character vector? If so, you can tokenize your text in this way:

library(tidyverse)
library(tidytext)

speech_vec <- c("I am giving a speech!",
                "My second speech is even better.",
                "Unfortunately, this speech is terrible!",
                "For my final speech, I will wow you all.")

speech_df <- tibble(text = speech_vec) %>%
  mutate(speech = row_number())

tidy_speeches <- speech_df %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2)

tidy_speeches
#> # A tibble: 21 x 2
#>    speech bigram
#>     <int> <chr>
#>  1      1 i am
#>  2      1 am giving
#>  3      1 giving a
#>  4      1 a speech
#>  5      2 my second
#>  6      2 second speech
#>  7      2 speech is
#>  8      2 is even
#>  9      2 even better
#> 10      3 unfortunately this
#> # … with 11 more rows
```

Created on 2020-02-15 by the reprex package (v0.3.0)

If instead, you mean that you have a DocumentTermMatrix from the tm package, check out this chapter for details on how to convert to a tidy data structure.

Title: ngrams analysis in tidytext in R

Body:
You say that you have a "corpus" of 770 speeches. Do you mean you have a character vector? If so, you can tokenize your text in this way:

library(tidyverse)
library(tidytext)

speech_vec <- c("I am giving a speech!",
                "My second speech is even better.",
                "Unfortunately, this speech is terrible!",
                "For my final speech, I will wow you all.")

speech_df <- tibble(text = speech_vec) %>%
  mutate(speech = row_number())

tidy_speeches <- speech_df %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2)

tidy_speeches
#> # A tibble: 21 x 2
#>    speech bigram
#>     <int> <chr>
#>  1      1 i am
#>  2      1 am giving
#>  3      1 giving a
#>  4      1 a speech
#>  5      2 my second
#>  6      2 second speech
#>  7      2 speech is
#>  8      2 is even
#>  9      2 even better
#> 10      3 unfortunately this
#> # … with 11 more rows

Created on 2020-02-15 by the reprex package (v0.3.0)

If instead, you mean that you have a DocumentTermMatrix from the tm package, check out this chapter for details on how to convert to a tidy data structure.


问:
QWebengineView: open local file with id
I am using Qt WebEngine 5.14 on Manjaro Linux.

I want to open local html file with id, but the following code is not working. It says file is not found.

Here is code:

```<code>#include <QApplication>
#include <QWebEngineView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWebEngineView view;

    //open remote html with id is working
    //view.load(QUrl("https://cges30901.github.io/test/hash/test#p3"));

    //open local file is working
    //view.load(QUrl::fromLocalFile(a.applicationDirPath()+"/test.html"));

    //open local file with id is not working
    view.load(QUrl::fromLocalFile(a.applicationDirPath()+"/test.html#p3"));

    view.show();
    return a.exec();
}
</code>```

This is test.html:

```<code><!--?xml version='1.0' encoding='utf-8'?-->
<!DOCTYPE html>

<html lang="zh-hant" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<title>test</title>
</head>
<body>
<p id="p1">This is paragraph 1</p>
<p id="p2">This is paragraph 2</p>
<p id="p3">This is paragraph 3</p>
<p id="p4">This is paragraph 4</p>
<p id="p5">This is paragraph 5</p>
<p id="p6">This is paragraph 6</p>
<p id="p7">This is paragraph 7</p>
<p id="p8">This is paragraph 8</p>
<p id="p9">This is paragraph 9</p>
<p id="p10">This is paragraph 10</p>
<p id="p11">This is paragraph 11</p>
<p id="p12">This is paragraph 12</p>
<p id="p13">This is paragraph 13</p>
<p id="p14">This is paragraph 14</p>
<p id="p15">This is paragraph 15</p>
<p id="p16">This is paragraph 16</p>
<p id="p17">This is paragraph 17</p>
<p id="p18">This is paragraph 18</p>
<p id="p19">This is paragraph 19</p>
</body>
</html>
</code>```

Can someone teach me how to open local html file with id?

答:
Problem

You are trying to create an url from a local file with the path .../test.html#p3. Calling QUrl::fromLocalFile results in an url like file:///<path>/test.html%23p3 which fails to load.

Solution

First convert the local path into a URL. Add the fragment to the resulting URL and display it:

```<code>QUrl url = QUrl::fromLocalFile(a.applicationDirPath() + "/test.html");
url.setFragment("p3");
view.load(url);
</code>```

Then it works as intended.

Title: QWebengineView: open local file with id

Body:
I am using Qt WebEngine 5.14 on Manjaro Linux.

I want to open local html file with id, but the following code is not working. It says file is not found.

Here is code:

#include <QApplication>
#include <QWebEngineView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWebEngineView view;

    //open remote html with id is working
    //view.load(QUrl("https://cges30901.github.io/test/hash/test#p3"));

    //open local file is working
    //view.load(QUrl::fromLocalFile(a.applicationDirPath()+"/test.html"));

    //open local file with id is not working
    view.load(QUrl::fromLocalFile(a.applicationDirPath()+"/test.html#p3"));

    view.show();
    return a.exec();
}

This is test.html:

<!DOCTYPE html>

<meta charset="utf-8"/>
<title>test</title>

This is paragraph 1

This is paragraph 2

This is paragraph 3

This is paragraph 4

This is paragraph 5

This is paragraph 6

This is paragraph 7

This is paragraph 8

This is paragraph 9

This is paragraph 10

This is paragraph 11

This is paragraph 12

This is paragraph 13

This is paragraph 14

This is paragraph 15

This is paragraph 16

This is paragraph 17

This is paragraph 18

This is paragraph 19

Can someone teach me how to open local html file with id?

Body:
Problem

You are trying to create an url from a local file with the path .../test.html#p3. Calling QUrl::fromLocalFile results in an url like file:///<path>/test.html%23p3 which fails to load.

Solution

First convert the local path into a URL. Add the fragment to the resulting URL and display it:

QUrl url = QUrl::fromLocalFile(a.applicationDirPath() + "/test.html");
url.setFragment("p3");
view.load(url);

Then it works as intended.


问:
Alert after page load
This is my script :

```<code><%
    if (TempData["Resultat"] != null){
%>
<script type="text/javascript">
    alert('<%: TempData["Resultat"]%>');
</script>
<%
    }
%>
</code>```

In this case pop-up is shown before page loaded, but i want that's appear after page is fully loaded.
in Html it's looks like this :

```<code><body onload="happycode() ;">
</code>```

but i can't use it in MVC i got one master page for all my web application

答:
Another option is to use the defer attribute on the script, but it's only appropriate for external scripts with a src attribute:

```<code><script src = "exampleJsFile.js" defer> </script>
</code>```

Title: Alert after page load

Body:
This is my script :

<%
    if (TempData["Resultat"] != null){
%>

<%
    }
%>

In this case pop-up is shown before page loaded, but i want that's appear after page is fully loaded.
in Html it's looks like this :

but i can't use it in MVC i got one master page for all my web application

Body:
Another option is to use the defer attribute on the script, but it's only appropriate for external scripts with a src attribute:

<script src = "exampleJsFile.js" defer> </script>


问:
Fetch API call for each item in a Jinja2 for loop
I'm currently stuck on a personal project where Im making Fetch API calls to get the audio src for a list of html audio tags.

The fetch call is triggered by an onclick event on the track. Though regardless of what track i click on, fetch calls /play_track/1/ and appends the audio player to only the first track. Any way to remedy this?

As you can see my index.html is basically just jinja2:

```<code>{% extends 'base.html' %}

{% block content %}

    {% for track in tracks %}
        {% include '_post.html' %}
    {% endfor %}

{% endblock content %}
</code>```

Heres _post.html with the Fetch call: (Currently using an onclick event to call but will switch to onpageload)

```<code><div class="card mb-3">
    <div class="row no-gutters">
        <div class="col-xl-4 col-lg-5 col-md-5 col-sm-5">
            <img width="500px" height="500px" class="img-thumbnail thumb" src="{{ track.thumbnail }}" class="card-img" alt="{{ track.title }}">
        </div>
        <div class="col-xl-8 col-lg-7 col-md-6 col-sm-7">
            <div id="card-body" class="card-body">
                <h5 class="card-title h5-title">{{ track.title }}</h5>
                <p class="card-text p-artist">{{ track.artist }}</p>
                <p class="card-text p-uploaded-at"><small class="text-muted">Uploaded on {{ track.created_at.strftime('%b %m, %Y') }}</small></p>
                <p onclick="fetchURL(event)" id="track-id">{{ track.id }}</p>

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

    <script>

        function fetchURL(event) {

            tid = document.getElementById('track-id');
            track_id = tid.innerHTML;

            fetch(`${window.origin}/play_track/${track_id}`)
                .then((response) => {
                    console.log(response.status);
                    return response.json();
                })
                .then(function(data) {
                    console.log(data.message.url);
                    createAudioPlayer(data);
                });
        }

        function createAudioPlayer(data) {

            let cardBody = document.getElementById('card-body');

            let audio = document.createElement('audio');
            audio.controls = true;

            let source = document.createElement('source');
            source.type = "audio/mpeg";
            source.src = data.message.url

            cardBody.append(audio);
            audio.prepend(source);
        };

    </script>
</div>
</code>```

And here is the backend code: (Which im pretty sure if i tweak I can avoid Fetch all-together but thats another issue)

```<code>@bp.route('/play_track/<track_id>/')
def play_track(track_id):

    track = Track.query.filter_by(id=track_id).first()

    res = requests.get(track.audio)
    if not res.status_code == 200:
        return f'Status code: {res.status_code}'

    json_res = json.loads(res.text)
    mpeg_audio_url = json_res['url']

    msg_dict = {
        'url': mpeg_audio_url
    }

    res = make_response(jsonify({'message': msg_dict}))
    return res
</code>```

To summarize: Fetch call not understanding Jinja2 for loop. Whether i click on track 1, 10, or 46, etc, It calls /play_track/1/ and appends the audio tag to the first track.

Thanks!

答:
```<code>        function fetchURL(event) {
            tid = event.target;
            track_id = tid.innerHTML;

            fetch(`${window.origin}/play_track/${track_id}`)
                .then((response) => {
                    console.log(response.status);
                    return response.json();
                })
                .then(function(data) {
                    console.log(data.message.url);
                    createAudioPlayer(data, event);
                });
        }
</code>```

The problem was the first line. you weren't getting the current event target.

Ids are must be unique thus every time you loop through the track you create an element with the same id. Change track-id from id to class.

```<code><p onclick="fetchURL(event)" class="track-id">{{ track.id }}</p>
</code>```

Also since you were using document.getElementById() it would return the first occurrence of that id. That is the reason, it was returning track 1 constantly.
Another thing, there is no point in having it loop the javascript over and over since the new ones would just override the old ones.

Fixed createAudioPlayer(), make sure to pass the event object into it. I already did it for you, so just copy the new fetchURL function.

```<code>        function createAudioPlayer(data, event) {

            let cardBody = event.target.parentElement;

            let audio = document.createElement('audio');
            audio.controls = true;

            let source = document.createElement('source');
            source.type = "audio/mpeg";
            source.src = data.message.url

            cardBody.append(audio);
            audio.prepend(source);
        };
</code>```

Body:
I'm currently stuck on a personal project where Im making Fetch API calls to get the audio src for a list of html audio tags.

The fetch call is triggered by an onclick event on the track. Though regardless of what track i click on, fetch calls /play_track/1/ and appends the audio player to only the first track. Any way to remedy this?

As you can see my index.html is basically just jinja2:

{% extends 'base.html' %}

{% block content %}

    {% for track in tracks %}
        {% include '_post.html' %}
    {% endfor %}

{% endblock content %}

Heres _post.html with the Fetch call: (Currently using an onclick event to call but will switch to onpageload)

{{ track.title }}

{{ track.artist }}

Uploaded on {{ track.created_at.strftime('%b %m, %Y') }}

{{ track.id }}

And here is the backend code: (Which im pretty sure if i tweak I can avoid Fetch all-together but thats another issue)

@bp.route('/play_track/<track_id>/')
def play_track(track_id):

    track = Track.query.filter_by(id=track_id).first()

    res = requests.get(track.audio)
    if not res.status_code == 200:
        return f'Status code: {res.status_code}'

    json_res = json.loads(res.text)
    mpeg_audio_url = json_res['url']

    msg_dict = {
        'url': mpeg_audio_url
    }

    res = make_response(jsonify({'message': msg_dict}))
    return res

To summarize: Fetch call not understanding Jinja2 for loop. Whether i click on track 1, 10, or 46, etc, It calls /play_track/1/ and appends the audio tag to the first track.

Thanks!

Body:
        function fetchURL(event) {
            tid = event.target;
            track_id = tid.innerHTML;

            fetch(`${window.origin}/play_track/${track_id}`)
                .then((response) => {
                    console.log(response.status);
                    return response.json();
                })
                .then(function(data) {
                    console.log(data.message.url);
                    createAudioPlayer(data, event);
                });
        }

The problem was the first line. you weren't getting the current event target.

Ids are must be unique thus every time you loop through the track you create an element with the same id. Change track-id from id to class.

<p onclick="fetchURL(event)" class="track-id">{{ track.id }}</p>

Also since you were using document.getElementById() it would return the first occurrence of that id. That is the reason, it was returning track 1 constantly.
Another thing, there is no point in having it loop the javascript over and over since the new ones would just override the old ones.

Fixed createAudioPlayer(), make sure to pass the event object into it. I already did it for you, so just copy the new fetchURL function.

        function createAudioPlayer(data, event) {

            let cardBody = event.target.parentElement;

            let audio = document.createElement('audio');
            audio.controls = true;

            let source = document.createElement('source');
            source.type = "audio/mpeg";
            source.src = data.message.url

            cardBody.append(audio);
            audio.prepend(source);
        };


问:
JS statement question: replacementory for 'return' in 'for loop' to get all values from 'for loop'
Because of return itself, numInOrder + " : " + nameInOrder; gives only one value, "1 : a" on console.

But I want

"1 : a

2 : b

3 : c

4 : d

5 : e

6 : f"

on console.log.

Plus, I do not want consol.log(numInOrder + " : " + nameInOrder); instead of return numInOrder + " : " + nameInOrder;, because consol.log(numInOrder + " : " + nameInOrder); print

"1 : a

2 : b

3 : c

4 : d

5 : e

6 : f

undefined"

To prevent printing undefined at the end of the numInOrder + " : " + nameInOrder;, how can I improve this code?

list = ['a','b','c','d','e','f'];

function x() {
  for (var i=0; i<list.length; i++){
    var numInOrder = i+1;
    var nameInOrder = list[i];

    return numInOrder + " : " + nameInOrder;
  }
}

console.log(x());```

答:
Map to an array of strings you want, then join that array by \n and return it:

list = ['a','b','c','d','e','f'];
const x = () => list
  .map((char, i) => char + ' : ' + (i + 1))
  .join('\n');

console.log(x());```
</div>
</div>
</p>

<p>Or, to change your original code, less concisely, but with the same logic:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>list = ['a', 'b', 'c', 'd', 'e', 'f'];

function x() {
  const arr = [];
  for (var i = 0; i < list.length; i++) {
    var numInOrder = i + 1;
    var nameInOrder = list[i];

    arr.push(numInOrder + " : " + nameInOrder);
  }
  return arr.join('\n');
}

console.log(x());</code>```

Body:
Map to an array of strings you want, then join that array by \n and return it:

list = ['a','b','c','d','e','f'];
const x = () => list
  .map((char, i) => char + ' : ' + (i + 1))
  .join('\n');

console.log(x());

Or, to change your original code, less concisely, but with the same logic:

list = ['a', 'b', 'c', 'd', 'e', 'f'];

function x() {
  const arr = [];
  for (var i = 0; i < list.length; i++) {
    var numInOrder = i + 1;
    var nameInOrder = list[i];

    arr.push(numInOrder + " : " + nameInOrder);
  }
  return arr.join('\n');
}

console.log(x());


问:
set pages main html tag in c#
I am writing a .net c# website which is available in multiple languages. How can I set the following main html tag in code behind of a page:

```<code><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
</code>```

Is this possible?

答:
Sure, just add an id and runat=server to your HTML tag in your page:

```<code><html id="html" runat="server" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
</code>```

Then in your code behind you can set whatever you'd like:

```<code>    html.Attributes["xml:lang"] = "somethingelse";
    html.Attributes["lang"] = "somethingelse";
</code>```

Title: set pages main html tag in c#

Body:
I am writing a .net c# website which is available in multiple languages. How can I set the following main html tag in code behind of a page:

Is this possible?

Body:
Sure, just add an id and runat=server to your HTML tag in your page:

<html id="html" runat="server" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

Then in your code behind you can set whatever you'd like:

    html.Attributes["xml:lang"] = "somethingelse";
    html.Attributes["lang"] = "somethingelse";


问:
Executing code after nested completion handlers
I am writing a Safari app extension and want to fetch the URL for the active page in my view controller.

This means nested completion handlers to fetch the window, to fetch the tab, to fetch the page, to access its properties.  Annoying but simple enough.  It looks like this:

```<code>func doStuffWithURL() {

    var url: URL?

    SFSafariApplication.getActiveWindow { (window) in
        window?.getActiveTab { (tab) in
            tab?.getActivePage { (page) in
                page?.getPropertiesWithCompletionHandler { (properties) in
                    url = properties?.url
                }
            }
        }
    }

    // NOW DO STUFF WITH THE URL
    NSLog("The URL is \(String(describing: url))")

}
</code>```

The obvious problem is it does not work.  Being completion handlers they will not be executed until the end of the function.  The variable url will be nil, and the stuff will be done before any attempt is made to get the URL.

One way around this is to use a DispatchQueue.  It works, but the code is truly ugly:

```<code>func doStuffWithURL() {

    var url: URL?

    let group = DispatchGroup()
    group.enter()
    SFSafariApplication.getActiveWindow { (window) in
        if let window = window {
            group.enter()
            window.getActiveTab { (tab) in
                if let tab = tab {
                    group.enter()
                    tab.getActivePage { (page) in
                        if let page = page {
                            group.enter()
                            page.getPropertiesWithCompletionHandler { (properties) in
                                url = properties?.url
                                group.leave()
                            }
                        }
                        group.leave()
                    }
                }
                group.leave()
            }
        }
        group.leave()
    }

    // NOW DO STUFF WITH THE URL
    group.notify(queue: .main) {
        NSLog("The URL is \(String(describing: url))")
    }

}
</code>```

The if blocks are needed to know we are not dealing with a nil value.  We need to be certain a completion handler will return, and therefore a .leave() call before we can call a .enter() to end up back at zero.

I cannot even bury all that ugliness away in some kind of getURLForPage() function or extension (adding some kind of SFSafariApplication.getPageProperties would be my preference) as obviously you cannot return from a function from within a .notify block.

Although I tried creating a function using queue.wait and a different DispatchQueue as described in the following answer to be able to use return…

https://stackoverflow.com/a/42484670/2081620

…not unsurprisingly to me it causes deadlock, as the .wait is still executing on the main queue.

Is there a better way of achieving this?  The "stuff to do," incidentally, is to update the UI at a user request so needs to be on the main queue.

Edit: For the avoidance of doubt, this is not an iOS question.  Whilst similar principles apply, Safari app extensions are a feature of Safari for macOS only.

答:
Thanks to Larme's suggestions in the comments, I have come up with a solution that hides the ugliness, is reusable, and keep the code clean and standard.

The nested completion handlers can be replaced by an extension to the SFSafariApplication class so that only one is required in the main body of the code.

```<code>extension SFSafariApplication {

    static func getActivePageProperties(_ completionHandler: @escaping (SFSafariPageProperties?) -> Void) {

        self.getActiveWindow { (window) in
            guard let window = window else { return completionHandler(nil) }
            window.getActiveTab { (tab) in
                guard let tab = tab else { return completionHandler(nil) }
                tab.getActivePage { (page) in
                    guard let page = page else { return completionHandler(nil) }
                    page.getPropertiesWithCompletionHandler { (properties) in
                        return completionHandler(properties)
                    }
                }
            }
         }

    }

}
</code>```

Then in the code it can be used as:

```<code>func doStuffWithURL() {

    SFSafariApplication.getActivePageProperties { (properties) in
        if let url = properties?.url {
            // NOW DO STUFF WITH THE URL
            NSLog("URL is \(url))")
        } else {
            // NOW DO STUFF WHERE THERE IS NO URL
            NSLog("URL ERROR")
        }
    }

}
</code>```

Body:
I am writing a Safari app extension and want to fetch the URL for the active page in my view controller.

This means nested completion handlers to fetch the window, to fetch the tab, to fetch the page, to access its properties.  Annoying but simple enough.  It looks like this:

func doStuffWithURL() {

    var url: URL?

    SFSafariApplication.getActiveWindow { (window) in
        window?.getActiveTab { (tab) in
            tab?.getActivePage { (page) in
                page?.getPropertiesWithCompletionHandler { (properties) in
                    url = properties?.url
                }
            }
        }
    }

    // NOW DO STUFF WITH THE URL
    NSLog("The URL is \(String(describing: url))")

}

The obvious problem is it does not work.  Being completion handlers they will not be executed until the end of the function.  The variable url will be nil, and the stuff will be done before any attempt is made to get the URL.

One way around this is to use a DispatchQueue.  It works, but the code is truly ugly:

func doStuffWithURL() {

    var url: URL?

    let group = DispatchGroup()
    group.enter()
    SFSafariApplication.getActiveWindow { (window) in
        if let window = window {
            group.enter()
            window.getActiveTab { (tab) in
                if let tab = tab {
                    group.enter()
                    tab.getActivePage { (page) in
                        if let page = page {
                            group.enter()
                            page.getPropertiesWithCompletionHandler { (properties) in
                                url = properties?.url
                                group.leave()
                            }
                        }
                        group.leave()
                    }
                }
                group.leave()
            }
        }
        group.leave()
    }

    // NOW DO STUFF WITH THE URL
    group.notify(queue: .main) {
        NSLog("The URL is \(String(describing: url))")
    }

}

The if blocks are needed to know we are not dealing with a nil value.  We need to be certain a completion handler will return, and therefore a .leave() call before we can call a .enter() to end up back at zero.

I cannot even bury all that ugliness away in some kind of getURLForPage() function or extension (adding some kind of SFSafariApplication.getPageProperties would be my preference) as obviously you cannot return from a function from within a .notify block.

Although I tried creating a function using queue.wait and a different DispatchQueue as described in the following answer to be able to use return…

https://stackoverflow.com/a/42484670/2081620

…not unsurprisingly to me it causes deadlock, as the .wait is still executing on the main queue.

Is there a better way of achieving this?  The "stuff to do," incidentally, is to update the UI at a user request so needs to be on the main queue.

Edit: For the avoidance of doubt, this is not an iOS question.  Whilst similar principles apply, Safari app extensions are a feature of Safari for macOS only.

Body:
Thanks to Larme's suggestions in the comments, I have come up with a solution that hides the ugliness, is reusable, and keep the code clean and standard.

The nested completion handlers can be replaced by an extension to the SFSafariApplication class so that only one is required in the main body of the code.

extension SFSafariApplication {

    static func getActivePageProperties(_ completionHandler: @escaping (SFSafariPageProperties?) -> Void) {

        self.getActiveWindow { (window) in
            guard let window = window else { return completionHandler(nil) }
            window.getActiveTab { (tab) in
                guard let tab = tab else { return completionHandler(nil) }
                tab.getActivePage { (page) in
                    guard let page = page else { return completionHandler(nil) }
                    page.getPropertiesWithCompletionHandler { (properties) in
                        return completionHandler(properties)
                    }
                }
            }
         }

    }

}

Then in the code it can be used as:

func doStuffWithURL() {

    SFSafariApplication.getActivePageProperties { (properties) in
        if let url = properties?.url {
            // NOW DO STUFF WITH THE URL
            NSLog("URL is \(url))")
        } else {
            // NOW DO STUFF WHERE THERE IS NO URL
            NSLog("URL ERROR")
        }
    }

}