问:
How can i fetch the element inside 2 {{}} in c #
```<code>var options = new RestClientOptions(Endpoint)
var client = new RestClient(options);
vsr request = new RestRequest();
var response = await client.GetAsync(request);
var requestContent = response.Content;
var parsed = JsonConvert.DeserializeObject(responseContent);
</code>```

the value in parsed is :

```<code>{{
"value1" : "input1",
"value2" : null,
"value3" : {"valuex" : 4,
"valuey" : 5,
"valuez" : 6}
"value4" : 17
}}
</code>```

the value in requestContent :

```<code>"{
\"value1\" : \"input1\",
\"value2\" : null,
\"value3\" : {\"valuex\" : 4,
\"valuey\" : 5,
\"valuez\" : 6}
\"value4\" : 17
}"
</code>```

I'm new to c#, all I want is to parse the data inside valuez which is 6 in this case, I tried so many things on request content like trying like deserializing and trying to parse the parsed value where I debugged and tried to access its child by putting . after parsed similar to what we'd do in javascript for example but nothing seems to be working.

答:
You provided invalid JSON:

{
    "value1": "input1",
    "value2": null,
    "value3": {
        "valuex": 4,
        "valuey": 5,
        "valuez": 6
    }         // <---- missing comma here.
    "value4": 17
}
```
<p>If unsure, you can always confirm if it's valid using a tool like JSONLint (remember to remove escape characters, which can be done using regex (online tool like regex101))</p>
<p>given you have a valid json (so just add the comma):</p>
<pre class="lang-cs prettyprint-override"><code>var r = JsonConvert.DeserializeObject<Dictionary<string,dynamic>>(yourInputString);
</code>```

... or as others mentioned, you can create a custom model. The easy way to do that is using another tool, i.e. Json2csharp. You can also refer to this article

Body:
var options = new RestClientOptions(Endpoint)
var client = new RestClient(options);
vsr request = new RestRequest();
var response = await client.GetAsync(request);
var requestContent = response.Content;
var parsed = JsonConvert.DeserializeObject(responseContent);

the value in parsed is :

{{
"value1" : "input1",
"value2" : null,
"value3" : {"valuex" : 4,
"valuey" : 5,
"valuez" : 6}
"value4" : 17
}}

the value in requestContent :

"{
\"value1\" : \"input1\",
\"value2\" : null,
\"value3\" : {\"valuex\" : 4,
\"valuey\" : 5,
\"valuez\" : 6}
\"value4\" : 17
}"

I'm new to c#, all I want is to parse the data inside valuez which is 6 in this case, I tried so many things on request content like trying like deserializing and trying to parse the parsed value where I debugged and tried to access its child by putting . after parsed similar to what we'd do in javascript for example but nothing seems to be working.

Body:
You provided invalid JSON:

{
    "value1": "input1",
    "value2": null,
    "value3": {
        "valuex": 4,
        "valuey": 5,
        "valuez": 6
    }         // <---- missing comma here.
    "value4": 17
}

If unsure, you can always confirm if it's valid using a tool like JSONLint (remember to remove escape characters, which can be done using regex (online tool like regex101))

given you have a valid json (so just add the comma):

var r = JsonConvert.DeserializeObject<Dictionary<string,dynamic>>(yourInputString);

... or as others mentioned, you can create a custom model. The easy way to do that is using another tool, i.e. Json2csharp. You can also refer to this article


来源: stackexchange

问:
How to join same table on multiple columns?
What would be the best way to JOIN a table based on whether join column is NULL or not.

I need to JOIN table #main with table #sub.

For example:

if ID column in table #main is NULL then join on column LocationID = #sub.LocationID

if ID and LocationID columns in table #main is NULLs then join on column UserID = #sub.UserID

```<code>create table #main (ID int, locationID varchar(50), UserID varchar(50))
insert into #main values (1,'Loc1',NULL),
                         (2,NULL,'User1'),
                         (NULL,'Loc1','User1'),
                         (4,'Loc1',NULL),
                         (5,NULL,'User1'),
                         (NULL,'Loc1','User1')
--select * from #main

select *
from #main m
-- if m.ID is not null then join on m.ID
-- OR if m.ID is null then join on m.locationID = s.LocationID
-- OR if m.ID is null and m.LocationID is null then join on  m.UserID = s.UserID
    left join #sub s ON  m.ID = s.ID OR m.locationID = s.LocationID OR m.UserID = s.UserID
</code>```

Thank you

答:
I'm not sure whether you want join or left join (you referred to both in your question), so modify the code below as fits your needs:

```<code>select  ...
from    #main  m
join    #sub   s  on m.id = s.id
                     or (m.id is null and and m.locationId = s.locationId)
                     or (m.id is null and m.locationId is null and m.userId = s.userId)
</code>```

I have used a feature of null here to shorten the syntax: null is not equal to anything. It's not even equal to null. So when doing the join on the m.id column, it might seem like you have to do this:

```<code>on m.id is not null and m.id = s.id
</code>```

But if m.id is null, then it will never equal s.id, because null is not equal to anything. And so you can just do

```<code>on m.id = s.id
</code>```

Because that condition can only be met when m.id is not null. I have used a similar dirty trick for the locationId join condition.

However, joins containing or conditions are often very slow, and it is sometimes helpful to explain to SQL Server that this same problem can be phrased in terms of union operations where the joins contain no or operations, only and operations:

```<code>select    ...
from      #main  m
join      #sub   s on m.id = s.id
union all
select    ...
from      #main  m
join      #sub   s on m.id is null
                      and m.locationId = s.locationId
union all
select    ...
from      #main  m
join      #sub   s on m.id is null
                      and m.locationId is null
                      and m.userId = s.userId

</code>```

ContentLicense: CC BY-SA 4.0

Body:
What would be the best way to JOIN a table based on whether join column is NULL or not.

I need to JOIN table #main with table #sub.

For example:

if ID column in table #main is NULL then join on column LocationID = #sub.LocationID

if ID and LocationID columns in table #main is NULLs then join on column UserID = #sub.UserID

create table #main (ID int, locationID varchar(50), UserID varchar(50))
insert into #main values (1,'Loc1',NULL),
                         (2,NULL,'User1'),
                         (NULL,'Loc1','User1'),
                         (4,'Loc1',NULL),
                         (5,NULL,'User1'),
                         (NULL,'Loc1','User1')
--select * from #main

select *
from #main m
-- if m.ID is not null then join on m.ID
-- OR if m.ID is null then join on m.locationID = s.LocationID
-- OR if m.ID is null and m.LocationID is null then join on  m.UserID = s.UserID
    left join #sub s ON  m.ID = s.ID OR m.locationID = s.LocationID OR m.UserID = s.UserID

Thank you

Body:
I'm not sure whether you want join or left join (you referred to both in your question), so modify the code below as fits your needs:

select  ...
from    #main  m
join    #sub   s  on m.id = s.id
                     or (m.id is null and and m.locationId = s.locationId)
                     or (m.id is null and m.locationId is null and m.userId = s.userId)

I have used a feature of null here to shorten the syntax: null is not equal to anything. It's not even equal to null. So when doing the join on the m.id column, it might seem like you have to do this:

on m.id is not null and m.id = s.id

But if m.id is null, then it will never equal s.id, because null is not equal to anything. And so you can just do

on m.id = s.id

Because that condition can only be met when m.id is not null. I have used a similar dirty trick for the locationId join condition.

However, joins containing or conditions are often very slow, and it is sometimes helpful to explain to SQL Server that this same problem can be phrased in terms of union operations where the joins contain no or operations, only and operations:

select    ...
from      #main  m
join      #sub   s on m.id = s.id
union all
select    ...
from      #main  m
join      #sub   s on m.id is null
                      and m.locationId = s.locationId
union all
select    ...
from      #main  m
join      #sub   s on m.id is null
                      and m.locationId is null
                      and m.userId = s.userId


问:
Matching files using python program
I have to two files as follows

```<code>File1
ids
CID5265
CID7263
CID9289
....

File 2
ids
CID7363  3.5e-06 -3837
CID5265  4.5      -938
CID9289  8.9      -9873
....
</code>```

I want  compare file1 with file2  to match any ids in file1 is present in file2 if yes  i should print whole line as follows

```<code>CIDS9289  8.9  -9873
....
</code>```

to acheive this wrote python script as follows

```<code>infile = open("file1","r")

searchtxt = open("file2.txt","r")

for line in infile.readlines():

    if searchtxt in line:

       print line
</code>```

but i gives following error

```<code>Traceback (most recent call last):
  File "finding_words.py", line 7, in <module>
    if searchtxt in line:
TypeError: 'in <string>' requires string as left operand, not file
</code>```

I know im doing very simple mistake but not able to figure it out can anybody tell how to solve this..

THanks in advance

NI

答:
```<code># Usage: foo.py ID_FILE DATA_FILE

ids = set()
with open(sys.argv[1]) as id_file:
    ids = set(line.strip() for line in id_file)

with open(sys.argv[2]) as data_file:
    for line in data_file:
        if line.split()[0] in ids:
            print line,
</code>```

ContentLicense: CC BY-SA 3.0

Title: Matching files using python program

Body:
I have to two files as follows

File1
ids
CID5265
CID7263
CID9289
....

File 2
ids
CID7363  3.5e-06 -3837
CID5265  4.5      -938
CID9289  8.9      -9873
....

I want  compare file1 with file2  to match any ids in file1 is present in file2 if yes  i should print whole line as follows

CIDS9289  8.9  -9873
....

to acheive this wrote python script as follows

infile = open("file1","r")

searchtxt = open("file2.txt","r")

for line in infile.readlines():

    if searchtxt in line:

       print line

but i gives following error

Traceback (most recent call last):
  File "finding_words.py", line 7, in <module>
    if searchtxt in line:
TypeError: 'in <string>' requires string as left operand, not file

I know im doing very simple mistake but not able to figure it out can anybody tell how to solve this..

THanks in advance

NI


答:
Have a query for each condition and union the results, something like</p>
```<code>select *
from #main m
left join #sub s on s.locationId = m.LocationId
where m.Id is null and m.locationId is not null
union all
select *
from #main m
left join #sub s on s.UserId - m.UserId
where m.Id is null and m.locationId is null
</code>```

Title: How to join same table on multiple columns?

Body:
Have a query for each condition and union the results, something like

select *
from #main m
left join #sub s on s.locationId = m.LocationId
where m.Id is null and m.locationId is not null
union all
select *
from #main m
left join #sub s on s.UserId - m.UserId
where m.Id is null and m.locationId is null


问:
C++ How am I able to access this strings s.size index?
```<code>void run_case() {
    int N, K;
    cin >> N >> K;
    string S;
    cin >> S;
    cout << S[6] << '\n';
    int goodness = 0;
    for (int i = 0; i <= N/2-1; i++)
    {
        cout << i << ' ' << S[i] << ' ' << N - i << ' ' << S[N-i] << '\n';
        if (S[i] != S[N - i]) goodness++;
    }
    cout << goodness << '\n';
}
</code>```

So I entered this input:

1

6 1

CABABC

S's size is 6 why am I able to print it out and do all this stuff when S[6] doesn't exist..? S[5] is the last char can anyone explain why this is happening? I mean I know that C style strings have an extra char to signal that it's over but what's going on here?

答:
std::string::operator[ s.size() ] has changed in C++11. Before:

If pos == size(), the behavior is undefined.

If pos == size(), a reference to the character with value CharT() (the null character) is returned.

Where 1) refers to the non-const overload and 2) to the const overload. Since C++11:

If pos == size(), a reference to the character with value CharT() (the null character) is returned.
For the first (non-const) version, the behavior is undefined if this character is modified to any value other than CharT().

When the size of the string is 6 then S[6] is completely fine. You just are not allowed to assign anything to it other than \0.

However, as mentioned in a comment, when your first input is 1 then S == "1" and accessing any index other than 0 or 1 is out-of-bounds. Attempting to access an out-of-bounds index is undefined behavior. Anything can happen. In the worst case the code might appear to work fine. It is important to understand that undefined behavior is typically not caught by compiler errors (though often compilers can warn about it).

Body:
void run_case() {
    int N, K;
    cin >> N >> K;
    string S;
    cin >> S;
    cout << S[6] << '\n';
    int goodness = 0;
    for (int i = 0; i <= N/2-1; i++)
    {
        cout << i << ' ' << S[i] << ' ' << N - i << ' ' << S[N-i] << '\n';
        if (S[i] != S[N - i]) goodness++;
    }
    cout << goodness << '\n';
}

So I entered this input:

1

6 1

CABABC

S's size is 6 why am I able to print it out and do all this stuff when S[6] doesn't exist..? S[5] is the last char can anyone explain why this is happening? I mean I know that C style strings have an extra char to signal that it's over but what's going on here?


问:
How can we get the current selected item from the Dropdown Search Package in Flutter
I am using this package
https://pub.dev/packages/dropdown_search

I have a dropdown inside a form I made, when a user selects an item, I would like to get the value of the selection and assign it to a variable. I've read some docs but they are quite hard to understand in regards to getting the value out. As far as I understood, the SelectedItem property is only to set a starting selection. How can I get the selected item from the dropdown?

 DropdownSearch<String>(
                  mode: Mode.MENU,
                  showSearchBox: false,
                  showSelectedItems: true,
                  items: const [
                    'Item 1',
                    'Item 2',
                    'Item 3',
                  ],
                  dropdownSearchDecoration: InputDecoration(
                    labelText: 'Items',
                  ),
                ),
```

In my above code, I'm not understanding how I should get the selected item, I am uploading the selected item to Firestore.

答:
There is an onChanged property for DropDownSearch. You can use it to get the selected item.
Eg:</p>
```<code>    DropdownSearch<UserModel>(
      label: "Name",
      onFind: (String filter) => getData(filter),
      itemAsString: (UserModel u) => u.userAsStringById(),
      onChanged: (UserModel data) {     <----- THIS ONE
         //Do something with this data
         },
    )
</code>```

Body:
I am using this package
https://pub.dev/packages/dropdown_search

I have a dropdown inside a form I made, when a user selects an item, I would like to get the value of the selection and assign it to a variable. I've read some docs but they are quite hard to understand in regards to getting the value out. As far as I understood, the SelectedItem property is only to set a starting selection. How can I get the selected item from the dropdown?

 DropdownSearch<String>(
                  mode: Mode.MENU,
                  showSearchBox: false,
                  showSelectedItems: true,
                  items: const [
                    'Item 1',
                    'Item 2',
                    'Item 3',
                  ],
                  dropdownSearchDecoration: InputDecoration(
                    labelText: 'Items',
                  ),
                ),

In my above code, I'm not understanding how I should get the selected item, I am uploading the selected item to Firestore.

Body:
There is an onChanged property for DropDownSearch. You can use it to get the selected item.
Eg:

    DropdownSearch<UserModel>(
      label: "Name",
      onFind: (String filter) => getData(filter),
      itemAsString: (UserModel u) => u.userAsStringById(),
      onChanged: (UserModel data) {     <----- THIS ONE
         //Do something with this data
         },
    )


问:
Firebase Realtime DB: How to setup rule to only write to DB if value being passed to be written is not already stored in DB
I am looking for syntax to setup a rule in my Firebase Realtime DB to confirm that the value being passed from my app does not already exist in that particular location before writing another duplicate entry. I am passing an "ExponentPushToken" value for push notifications. This happens anonymously. That is, the write is happening without any user authentication, the DB is simply storing a list of "ExponentPushToken" like so:

```<code>{
  "users" : {
    "push_token" : {
      "auto-generated key" : "ExponentPushToken-value"
    }
  }
}
</code>```

I attempted to use the following, but it still will allow the "duplicate" value to be written. I am wondering if this has anything to do with random 'auto-generated key' that is generated for each instance a value written to the DB, or if i am not thinking through this properly.

```<code>{
  "rules": {
    ".read": "false",
    ".write": "true && newData.val() !== data.child('push_token').val()",
  }
}
</code>```

For context, each ExponentPushToken is a unique value for a given device that is used to open my app. The ExponentPushToken is a unique ID that is assigned to that device indefinitely and won't change ever in any case that particular device is accessing the app. The ExponentPushToken is assigned to the device indefinitely, and is written to the DB. Each time the app is opened, there is a push/set command to write that token to the DB within my app's code. I would like to setup a rule for Firebase Realtime DB to confirm the value being passed from the app to the DB does NOT get written if that value already exists. I am stuck and am finding myself having to manually parse the db to remove duplicate value to keep the DB clean and not send more than one Push Notification to app users.

Any help or direction you can provide would be greatly appreciated!

Thanks!

答:
This cannot be done using firebase security rules, as they cannot search for values (that wouldn't scale). The query to check for existing values in a particular location in the database would have to be done in the app that is performing the push/writing of the value into the database.

The app would need to query the database for values and have a condition in place to prevent the writing of duplicate values.

An example of working code that can be implemented within the app can be found here that accomplishes the desired outcome for this specific ask/desired outcome.

Expo and Firebase Realtime DB - Read values and confirm a particular value does not exist before writing to database

Body:
I am looking for syntax to setup a rule in my Firebase Realtime DB to confirm that the value being passed from my app does not already exist in that particular location before writing another duplicate entry. I am passing an "ExponentPushToken" value for push notifications. This happens anonymously. That is, the write is happening without any user authentication, the DB is simply storing a list of "ExponentPushToken" like so:

{
  "users" : {
    "push_token" : {
      "auto-generated key" : "ExponentPushToken-value"
    }
  }
}

I attempted to use the following, but it still will allow the "duplicate" value to be written. I am wondering if this has anything to do with random 'auto-generated key' that is generated for each instance a value written to the DB, or if i am not thinking through this properly.

{
  "rules": {
    ".read": "false",
    ".write": "true && newData.val() !== data.child('push_token').val()",
  }
}

For context, each ExponentPushToken is a unique value for a given device that is used to open my app. The ExponentPushToken is a unique ID that is assigned to that device indefinitely and won't change ever in any case that particular device is accessing the app. The ExponentPushToken is assigned to the device indefinitely, and is written to the DB. Each time the app is opened, there is a push/set command to write that token to the DB within my app's code. I would like to setup a rule for Firebase Realtime DB to confirm the value being passed from the app to the DB does NOT get written if that value already exists. I am stuck and am finding myself having to manually parse the db to remove duplicate value to keep the DB clean and not send more than one Push Notification to app users.

Any help or direction you can provide would be greatly appreciated!

Thanks!


问:
How to convert R formula to text?
I have trouble working with formula as with text. What I'm trying to do is to concatenate the formula to the title of the graph. However, when I try to work with the formula as with text, I fail:

```<code>model <- lm(celkem ~ rok + mesic)
formula(model)
# celkem ~ rok + mesic
</code>```

This is fine. Now I want to build string like "my text celkem ~ rok + mesic" - this is where the problem comes:

```<code>paste("my text", formula(model))
# [1] "my text ~"           "my text celkem"      "my text rok + mesic"

paste("my text", as.character(formula(model)))
# [1] "my text ~"           "my text celkem"      "my text rok + mesic"

paste("my text", toString(formula(model)))
# [1] "my text ~, celkem, rok + mesic"
</code>```

Now I see there is a sprint function in package gtools, but I think this is such a basic thing that it deserves a solution within the default environment!!

答:
Was optimizing some functions today. A few approaches that have not been mentioned so far.

f <- Y ~ 1 + a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u
bench::mark(
  expression = as.character(as.expression(f)),
  deparse = deparse(f, width.cutoff = 500L),
  deparse1 = deparse1(f),
  tools = formula.tools:::as.character.formula(f),
  stringi = stringi::stri_c(f),
  I = as.character(I(f)),
  as = as(f, "character"),
  txt = gettext(f),
  txtf = gettextf(f),
  sub = sub("", "", f),
  chr = as.character(f),
  str = substring(f, 1L),
  paste = paste0(f),
)[c(1, 3, 5, 7)]

#> # A tibble: 13 x 3
#>    expression   median mem_alloc
#>    <bch:expr> <bch:tm> <bch:byt>
#>  1 expression   15.4us        0B
#>  2 deparse        31us        0B
#>  3 deparse1       34us        0B
#>  4 tools        58.7us    1.74MB
#>  5 stringi        67us    3.09KB
#>  6 I            64.1us        0B
#>  7 as          100.5us  521.61KB
#>  8 txt          83.4us        0B
#>  9 txtf         85.8us    3.12KB
#> 10 sub          64.6us        0B
#> 11 chr            60us        0B
#> 12 str          62.8us        0B
#> 13 paste        63.5us        0B
```

Title: How to convert R formula to text?

Body:
I have trouble working with formula as with text. What I'm trying to do is to concatenate the formula to the title of the graph. However, when I try to work with the formula as with text, I fail:

model <- lm(celkem ~ rok + mesic)
formula(model)
# celkem ~ rok + mesic

This is fine. Now I want to build string like "my text celkem ~ rok + mesic" - this is where the problem comes:

paste("my text", formula(model))
# [1] "my text ~"           "my text celkem"      "my text rok + mesic"

paste("my text", as.character(formula(model)))
# [1] "my text ~"           "my text celkem"      "my text rok + mesic"

paste("my text", toString(formula(model)))
# [1] "my text ~, celkem, rok + mesic"

Now I see there is a sprint function in package gtools, but I think this is such a basic thing that it deserves a solution within the default environment!!


问:
Android Check Application Status
I have a question about Android application status. I want to know that am I able to check whether application is alive or dead, visible or on background. I need to make a decision according to application status in my broadcast receiver.

Thanks in advance..

答: Within Android, it is standard practise to track 'changes' to the various states. You can read more about this here. Within the specific lifecycle related methods, you can perform specific actions as deemed appropriate.</p>

Title: Android Check Application Status


问:
Find value in collection
I'm trying to figure out the following challenge:

Write a script in a programming language of your choice (I'm going with vanilla JS) that uses a loop and a conditional statement to find the value of the number of dogs in the following collection of key-value pairs. Depending on what language you’re using, it is acceptable to think of this variable as either a dictionary or an array of key-value pairs. Please only use logic that is native to the language without any external libraries:

```<code>KennelCapacity = {cats: 7, hamsters: 12, birds: 21, dogs: 3, chickens: 1}
</code>```

I'm trying to set up a for loop with an if/else statement, but I'm honestly not sure how to piece it together for a proper answer. How should I do this?

答:
So, this question is very strange, because in JavaScript you could just do KennelCapacity.dogs and get the number of the dogs.

But this is not the question, so the following would be a possible solution:

const KennelCapacity = {
  cats: 7,
  hamsters: 12,
  birds: 21,
  dogs: 3,
  chickens: 1
};

let numberOfDogs;

// this gets [key, value] (here [animal, number]) of each key-value pair in the object
for (let [animal, number] of Object.entries(KennelCapacity)) {
  if (animal == "dogs") {
    numberOfDogs = number;
    break;
  }
}

console.log(numberOfDogs);```

This code runs through your Object and gets each value-pair. (See Object.entries() at MDN).

With the Javascript notation [key, value] you can split the given array in the key and value or in my example code animal and value.

In the if statement is checked if the key is "dogs". If that is true, numberOfDogs is set to the number of dogs, that is stored as value in your object and the for loop is broken.

I hope, this helps you. If you have more questions, you are welcome to ask.

Title: Find value in collection

Body:
I'm trying to figure out the following challenge:

Write a script in a programming language of your choice (I'm going with vanilla JS) that uses a loop and a conditional statement to find the value of the number of dogs in the following collection of key-value pairs. Depending on what language you’re using, it is acceptable to think of this variable as either a dictionary or an array of key-value pairs. Please only use logic that is native to the language without any external libraries:

KennelCapacity = {cats: 7, hamsters: 12, birds: 21, dogs: 3, chickens: 1}

I'm trying to set up a for loop with an if/else statement, but I'm honestly not sure how to piece it together for a proper answer. How should I do this?

Body:
So, this question is very strange, because in JavaScript you could just do KennelCapacity.dogs and get the number of the dogs.

But this is not the question, so the following would be a possible solution:

const KennelCapacity = {
  cats: 7,
  hamsters: 12,
  birds: 21,
  dogs: 3,
  chickens: 1
};

let numberOfDogs;

// this gets [key, value] (here [animal, number]) of each key-value pair in the object
for (let [animal, number] of Object.entries(KennelCapacity)) {
  if (animal == "dogs") {
    numberOfDogs = number;
    break;
  }
}

console.log(numberOfDogs);

This code runs through your Object and gets each value-pair. (See Object.entries() at MDN).

With the Javascript notation [key, value] you can split the given array in the key and value or in my example code animal and value.

In the if statement is checked if the key is "dogs". If that is true, numberOfDogs is set to the number of dogs, that is stored as value in your object and the for loop is broken.

I hope, this helps you. If you have more questions, you are welcome to ask.


问:
How can I update the data that received from firebase
My function that receives data =>

```<code> Future<Object?> GetTotal() async {
      FirebaseDatabase database = FirebaseDatabase.instance;

      DatabaseReference ref = FirebaseDatabase.instance.ref("Total");

      DatabaseEvent event = await ref.once();

      return event.snapshot.value;
    }
</code>```

And it's where I use it =>

```<code>FutureBuilder(
                      future: GetTotal(),
                      builder: (context, snapshot) {
                        if (snapshot.hasError) {
                          print(snapshot.error);
                        }
                        if (snapshot.hasData) {
                          var data1 = snapshot.data!.toString();
                          var data2 = double.parse(data1);
                          String data3 = data2.toStringAsFixed(2);
                          return Text(
                            "Total Amount \n\n\n" + "${data3} TL",
                            textAlign: TextAlign.center,
                            style: TextStyle(fontSize: 24),
                          );
                        } else {
                          return CircularProgressIndicator();
                        }
                      }),
</code>```

It only fetches the data when the app is opened. But I want it to fetch the data every minute or every 10 minute how can I make it?

I think the problem is in GetTotal() function ref.once() but what can I use instead of ref.once()

答:
The solution here is to use a StreamBuilder. Every change in your "Total" node, will fire a new event, this will update the data that is shown by the StreamBuilder.</p>
```<code>DatabaseReference ref = FirebaseDatabase.instance.ref("Totals");

StreamBuilder(
        stream: ref.onValue
        builder: (ctx, snapshot) {
          if (chatSnapshot.connectionState == ConnectionState.waiting) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          // do something with the snapshot
          print(snapshot.snapshot.value); // this will show what is in the data you got
          return Container(child: Text("your data"));
        });
</code>```

Body:
My function that receives data =>

 Future<Object?> GetTotal() async {
      FirebaseDatabase database = FirebaseDatabase.instance;

      DatabaseReference ref = FirebaseDatabase.instance.ref("Total");

      DatabaseEvent event = await ref.once();

      return event.snapshot.value;
    }

And it's where I use it =>

FutureBuilder(
                      future: GetTotal(),
                      builder: (context, snapshot) {
                        if (snapshot.hasError) {
                          print(snapshot.error);
                        }
                        if (snapshot.hasData) {
                          var data1 = snapshot.data!.toString();
                          var data2 = double.parse(data1);
                          String data3 = data2.toStringAsFixed(2);
                          return Text(
                            "Total Amount \n\n\n" + "${data3} TL",
                            textAlign: TextAlign.center,
                            style: TextStyle(fontSize: 24),
                          );
                        } else {
                          return CircularProgressIndicator();
                        }
                      }),

It only fetches the data when the app is opened. But I want it to fetch the data every minute or every 10 minute how can I make it?

I think the problem is in GetTotal() function ref.once() but what can I use instead of ref.once()

Body:
The solution here is to use a StreamBuilder. Every change in your "Total" node, will fire a new event, this will update the data that is shown by the StreamBuilder.

DatabaseReference ref = FirebaseDatabase.instance.ref("Totals");

StreamBuilder(
        stream: ref.onValue
        builder: (ctx, snapshot) {
          if (chatSnapshot.connectionState == ConnectionState.waiting) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          // do something with the snapshot
          print(snapshot.snapshot.value); // this will show what is in the data you got
          return Container(child: Text("your data"));
        });


问:
Find total unique counter based on unique id and date - MongoDB
I'm trying to count all and unique events on daily based based on the following data shape:

```<code>{
    username: "jack",
    events: [
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "01234567-0ebb-4238-8bf7-01234567"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-30T10:26:11.214Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     },
    {
       eventType: "party",
       createdAt: "2022-01-30T10:16:11.214Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     }
       ]

    }
</code>```

I'm trying to count events (all and unique ones based on visitorId) on date (daily).
This is what I have so far (thanks to @R2D2's guide on the approach):

```<code> Event.aggregate([
  { $match: { username: 'jack' } },

  { $unwind: "$events" },

  {
    $project: {
      total: {
        $cond: [
          {
            $eq: ["$events.eventType", "party"],
          },
          1,
          0,
        ],
      },

    unique: { // where I'm stuck. I need to count unique events based on visitorId on current date.
        $cond: [
          {
            $eq: ["$events.eventType", "party"],
          },
          1,
          0,
        ],
      },

      date: "$events.createdAt",
    },
  },

  {
    $group: {
      _id: {
        $dateToString: { format: "%Y-%m-%d", date: "$date" },
      },

      total: {
        $sum: "$total",
      },

      uniqueTotal: {
        $sum: "$unique",
      },
    },
  },
  {
    $project: {
      date: "$_id",
      total: 1,
      uniqueTotal: 1,
    },
  },
  {
    $group: {
      _id: "0",
      dateAndEventFrequency: {
        $push: "$$ROOT",
      },
    },
  },
  {
    $project: {
      _id: 0,
      dateAndEventFrequency: 1,
    },
  },
]);
</code>```

I tried using $addToSet but it's not used with $project (it works with $group).
Any new approach is welcome based on the data shape and the desired result I'm expecting. I used $project because I was already using it.

Basically what I'm hoping to get in the end:

```<code>dateAndEventFrequency: [
    {
    _id: "2022-01-23",
    uniqueTotal: 2,
    total: 3,
    date: "2022-01-23",
    },
   {
    _id: "2022-01-30",
    uniqueTotal: 1,
    total: 2,
    date: "2022-01-30",
    },
]
</code>```

Any help or guidance is appreciated. Thanks!

答:
first group by date and visitorId together and then do another group just by date

you can test it here mongo playground

```<code>db.collection.aggregate([
  {
    $match: {
      username: "jack"
    }
  },
  {
    "$unwind": "$events"
  },
  {
    "$group": {
      "_id": {
        date: {
          "$dateToString": {
            format: "%Y-%m-%d",
            date: "$events.createdAt"
          }
        },
        "visitorId": "$events.visitorInfo.visitorId",

      },
      "count": {
        "$count": {}
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.date",
      "uniqueTotal": {
        "$count": {}
      },
      total: {
        "$sum": "$count"
      }
    }
  }
])
</code>```

Body:
I'm trying to count all and unique events on daily based based on the following data shape:

{
    username: "jack",
    events: [
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "87654321-0ebb-4238-8bf7-87654321"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-23T10:26:11.214Z",
       visitorInfo: {
            visitorId: "01234567-0ebb-4238-8bf7-01234567"
           }
     },
     {
       eventType: "party",
       createdAt: "2022-01-30T10:26:11.214Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     },
    {
       eventType: "party",
       createdAt: "2022-01-30T10:16:11.214Z",
       visitorInfo: {
            visitorId: "12345678-0ebb-4238-8bf7-12345678"
           }
     }
       ]

    }

I'm trying to count events (all and unique ones based on visitorId) on date (daily).
This is what I have so far (thanks to @R2D2's guide on the approach):

 Event.aggregate([
  { $match: { username: 'jack' } },

  { $unwind: "$events" },

  {
    $project: {
      total: {
        $cond: [
          {
            $eq: ["$events.eventType", "party"],
          },
          1,
          0,
        ],
      },

    unique: { // where I'm stuck. I need to count unique events based on visitorId on current date.
        $cond: [
          {
            $eq: ["$events.eventType", "party"],
          },
          1,
          0,
        ],
      },

      date: "$events.createdAt",
    },
  },

  {
    $group: {
      _id: {
        $dateToString: { format: "%Y-%m-%d", date: "$date" },
      },

      total: {
        $sum: "$total",
      },

      uniqueTotal: {
        $sum: "$unique",
      },
    },
  },
  {
    $project: {
      date: "$_id",
      total: 1,
      uniqueTotal: 1,
    },
  },
  {
    $group: {
      _id: "0",
      dateAndEventFrequency: {
        $push: "$$ROOT",
      },
    },
  },
  {
    $project: {
      _id: 0,
      dateAndEventFrequency: 1,
    },
  },
]);

I tried using $addToSet but it's not used with $project (it works with $group).
Any new approach is welcome based on the data shape and the desired result I'm expecting. I used $project because I was already using it.

Basically what I'm hoping to get in the end:

dateAndEventFrequency: [
    {
    _id: "2022-01-23",
    uniqueTotal: 2,
    total: 3,
    date: "2022-01-23",
    },
   {
    _id: "2022-01-30",
    uniqueTotal: 1,
    total: 2,
    date: "2022-01-30",
    },
]

Any help or guidance is appreciated. Thanks!

Body:
first group by date and visitorId together and then do another group just by date

you can test it here mongo playground

db.collection.aggregate([
  {
    $match: {
      username: "jack"
    }
  },
  {
    "$unwind": "$events"
  },
  {
    "$group": {
      "_id": {
        date: {
          "$dateToString": {
            format: "%Y-%m-%d",
            date: "$events.createdAt"
          }
        },
        "visitorId": "$events.visitorInfo.visitorId",

      },
      "count": {
        "$count": {}
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.date",
      "uniqueTotal": {
        "$count": {}
      },
      total: {
        "$sum": "$count"
      }
    }
  }
])


问:
UIPageViewController transition bugged if animation starts in the meanwhile
I have a strange behaviour in my app using a UIPageViewController.
The layout of my app is a PageViewController (camera roll like) with a ads banner on bottom.

The banner's container starts as hidden and, when the ad gets loaded, i set the isHidden=false with an animation.

My problem is that when the banner gets into the screen it breaks the UIPageViewController transition if in progress as shown in this video:

I made a new project that reproduces the error very easy with a few lines, you can checkout it in GITHUB: You just need to spam the "Next" button until the banner gets loaded. It also can be reproduced by swipping the PageViewController but is harder to reproduce.

The full example code is:

```<code>class TestViewController: UIViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource {
    @IBOutlet weak var constraintAdviewHeight: NSLayoutConstraint!
    weak var pageViewController : UIPageViewController?

    @IBOutlet weak var containerAdView: UIView!
    @IBOutlet weak var adView: UIView!
    @IBOutlet weak var containerPager: UIView!

    var currentIndex = 0;
    var clickEnabled = true

    override func viewDidLoad() {
        super.viewDidLoad()
        let pageVC = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        pageViewController = pageVC
        pageVC.delegate = self
        pageVC.dataSource = self
        addChildViewController(pageVC)
        pageVC.didMove(toParentViewController: self)
        containerPager.addSubview(pageVC.view)
        pageVC.view.translatesAutoresizingMaskIntoConstraints = true
        pageVC.view.frame = containerPager.bounds
        pushViewControllerForCurrentIndex()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.containerAdView.isHidden = true

        DispatchQueue.main.asyncAfter(deadline: .now()+4) {
            self.simulateBannerLoad()
        }

    }

    @IBAction func buttonClicked(_ sender: Any) {
        guard clickEnabled else {return}
        currentIndex -= 1;
        pushViewControllerForCurrentIndex()

    }

    @IBAction func button2Clicked(_ sender: Any) {
        guard clickEnabled else {return}
        currentIndex += 1;
        pushViewControllerForCurrentIndex()
    }

    private func simulateBannerLoad(){
        constraintAdviewHeight.constant = 50
        pageViewController?.view.setNeedsLayout()
        UIView.animate(withDuration: 0.3,
                       delay: 0, options: .allowUserInteraction, animations: {
                        self.containerAdView.isHidden = false
                        self.view.layoutIfNeeded()
                        self.pageViewController?.view.layoutIfNeeded()
        })

    }

    //MARK: data source

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        return getViewControllerForIndex(currentIndex+1)
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        return getViewControllerForIndex(currentIndex-1)
    }

    func getViewControllerForIndex(_ index:Int) -> UIViewController? {
        guard (index>=0) else {return nil}
        let vc :UIViewController = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(withIdentifier: "pageTest")
        vc.view.backgroundColor = (index % 2 == 0) ? .red : .green
        return vc
    }

    func pushViewControllerForCurrentIndex() {
        guard let vc = getViewControllerForIndex(currentIndex) else {return}
        print("settingViewControllers start")
        clickEnabled = false
        pageViewController?.setViewControllers([vc], direction: .forward, animated: true, completion: { finished in
            print("setViewControllers finished")
            self.clickEnabled = true
        })
    }
}
</code>```

Note: Another unwanted effect is that the last completion block when the bug occurs does not get called, so it leaves the buttons disabled:

```<code>    func pushViewControllerForCurrentIndex() {
        guard let vc = getViewControllerForIndex(currentIndex) else {return}
        print("settingViewControllers start")
        clickEnabled = false
        pageViewController?.setViewControllers([vc], direction: .forward, animated: true, completion: { finished in
            print("setViewControllers finished")
            self.clickEnabled = true
        })
    }
</code>```

Note2: The banner load event is something I can't control manually. Due to the library used for displaying ads its a callback in the main thread that can happen in any moment. In the sample proyect this is simulated with a DispatchQueue.main.asyncAfter: call

How can I fix that? Thanks

答:
For us, it was due to a device rotation causing a layout pass at the same time as an animation to a new view controller. We could not figure out how to stop the layout pass in this situation.

This worked for us:

```<code>let pageController = UIPageViewController()

func updatePageController() {
    pageController.setViewControllers(newViewControllers, direction: .forward, animated: true, completion: {[weak self] _ in
        // There is a bug with UIPageViewController where a layout pass during an animation
        // to a new view controller can cause the UIPageViewController to display the old and new view controller
        // In our case, we can compare the view controller `children` count against the the `viewControllers` count
        // In other cases, we may need to examine `children` more closely against `viewControllers` to see if there discrepancies.
        // Since this is on the animation callback we need to dispatch to the main thread to work around another bug: https://stackoverflow.com/a/24749239/2191796
        DispatchQueue.main.async { [weak self] in
            guard let self = self else {return}

            if self.pageController.children.count != self.pageController.viewControllers?.count {
                self.pageController.setViewControllers(self.pageController.viewControllers, direction: .forward, animated: false, completion: nil)
            }
        }
    })
}
</code>```

Body:
I have a strange behaviour in my app using a UIPageViewController.
The layout of my app is a PageViewController (camera roll like) with a ads banner on bottom.

The banner's container starts as hidden and, when the ad gets loaded, i set the isHidden=false with an animation.

My problem is that when the banner gets into the screen it breaks the UIPageViewController transition if in progress as shown in this video:

I made a new project that reproduces the error very easy with a few lines, you can checkout it in GITHUB: You just need to spam the "Next" button until the banner gets loaded. It also can be reproduced by swipping the PageViewController but is harder to reproduce.

The full example code is:

class TestViewController: UIViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource {
    @IBOutlet weak var constraintAdviewHeight: NSLayoutConstraint!
    weak var pageViewController : UIPageViewController?

    @IBOutlet weak var containerAdView: UIView!
    @IBOutlet weak var adView: UIView!
    @IBOutlet weak var containerPager: UIView!

    var currentIndex = 0;
    var clickEnabled = true

    override func viewDidLoad() {
        super.viewDidLoad()
        let pageVC = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        pageViewController = pageVC
        pageVC.delegate = self
        pageVC.dataSource = self
        addChildViewController(pageVC)
        pageVC.didMove(toParentViewController: self)
        containerPager.addSubview(pageVC.view)
        pageVC.view.translatesAutoresizingMaskIntoConstraints = true
        pageVC.view.frame = containerPager.bounds
        pushViewControllerForCurrentIndex()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.containerAdView.isHidden = true

        DispatchQueue.main.asyncAfter(deadline: .now()+4) {
            self.simulateBannerLoad()
        }

    }

    @IBAction func buttonClicked(_ sender: Any) {
        guard clickEnabled else {return}
        currentIndex -= 1;
        pushViewControllerForCurrentIndex()

    }

    @IBAction func button2Clicked(_ sender: Any) {
        guard clickEnabled else {return}
        currentIndex += 1;
        pushViewControllerForCurrentIndex()
    }

    private func simulateBannerLoad(){
        constraintAdviewHeight.constant = 50
        pageViewController?.view.setNeedsLayout()
        UIView.animate(withDuration: 0.3,
                       delay: 0, options: .allowUserInteraction, animations: {
                        self.containerAdView.isHidden = false
                        self.view.layoutIfNeeded()
                        self.pageViewController?.view.layoutIfNeeded()
        })

    }

    //MARK: data source

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        return getViewControllerForIndex(currentIndex+1)
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        return getViewControllerForIndex(currentIndex-1)
    }

    func getViewControllerForIndex(_ index:Int) -> UIViewController? {
        guard (index>=0) else {return nil}
        let vc :UIViewController = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(withIdentifier: "pageTest")
        vc.view.backgroundColor = (index % 2 == 0) ? .red : .green
        return vc
    }

    func pushViewControllerForCurrentIndex() {
        guard let vc = getViewControllerForIndex(currentIndex) else {return}
        print("settingViewControllers start")
        clickEnabled = false
        pageViewController?.setViewControllers([vc], direction: .forward, animated: true, completion: { finished in
            print("setViewControllers finished")
            self.clickEnabled = true
        })
    }
}

Note: Another unwanted effect is that the last completion block when the bug occurs does not get called, so it leaves the buttons disabled:

    func pushViewControllerForCurrentIndex() {
        guard let vc = getViewControllerForIndex(currentIndex) else {return}
        print("settingViewControllers start")
        clickEnabled = false
        pageViewController?.setViewControllers([vc], direction: .forward, animated: true, completion: { finished in
            print("setViewControllers finished")
            self.clickEnabled = true
        })
    }

Note2: The banner load event is something I can't control manually. Due to the library used for displaying ads its a callback in the main thread that can happen in any moment. In the sample proyect this is simulated with a DispatchQueue.main.asyncAfter: call

How can I fix that? Thanks

Body:
For us, it was due to a device rotation causing a layout pass at the same time as an animation to a new view controller. We could not figure out how to stop the layout pass in this situation.

This worked for us:

let pageController = UIPageViewController()

func updatePageController() {
    pageController.setViewControllers(newViewControllers, direction: .forward, animated: true, completion: {[weak self] _ in
        // There is a bug with UIPageViewController where a layout pass during an animation
        // to a new view controller can cause the UIPageViewController to display the old and new view controller
        // In our case, we can compare the view controller `children` count against the the `viewControllers` count
        // In other cases, we may need to examine `children` more closely against `viewControllers` to see if there discrepancies.
        // Since this is on the animation callback we need to dispatch to the main thread to work around another bug: https://stackoverflow.com/a/24749239/2191796
        DispatchQueue.main.async { [weak self] in
            guard let self = self else {return}

            if self.pageController.children.count != self.pageController.viewControllers?.count {
                self.pageController.setViewControllers(self.pageController.viewControllers, direction: .forward, animated: false, completion: nil)
            }
        }
    })
}


问:
ASP .NET anonymous users not getting stored in database
I'm trying to setup anonymous users in MVC. For some reason it wont store the users in the database. I have added the following in the web.config

```<code><anonymousIdentification enabled="true" />
</code>```

It successfully creates the .ASPXANONYMOUS cookie when i visit the site but doesn't create the user in the database. Is this something i have to do manually?

答: It will be stored if you will try to save some data like for example something in this user's profile.</p>

OwnerDisplayName: Alex

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to setup anonymous users in MVC. For some reason it wont store the users in the database. I have added the following in the web.config

<anonymousIdentification enabled="true" />

It successfully creates the .ASPXANONYMOUS cookie when i visit the site but doesn't create the user in the database. Is this something i have to do manually?

OwnerDisplayName: Koistya Navin .NET


问:
select * only return one value
I want select multiple (all) values from table Account.

```<code>string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();
</code>```

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

答:
Using where id = 2 and id = 3 would return zero results as as id=2 and id=3 are mutually exclusive. where id = 2 or id = 3 could work.

```<code>while (reader.Read()) { /*Do stuff with current row*/ }
</code>```

could work for iterating through the results

Title: select * only return one value

Body:
I want select multiple (all) values from table Account.

string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

Body:
Using where id = 2 and id = 3 would return zero results as as id=2 and id=3 are mutually exclusive. where id = 2 or id = 3 could work.

while (reader.Read()) { /*Do stuff with current row*/ }

could work for iterating through the results


问:
Configure vs code for Selenium 4 - error while installing dotnet 6 sdk using PowerShell
I was following the steps here:

https://www.fleekitsolutions.com/use-selenium-c-visual-studio-code/

To use Selenium 4 with vs code. Then this led me to the following instructions here:

https://learn.microsoft.com/en-us/dotnet/core/install/windows?tabs=net60#install-with-powershell-automation

to install .NET 6 SDK using PowerShell script, and I got the error below:

dotnet-install.ps1: Exception calling "ExtractToFile" with "3"
argument(s): "The archive entry was compressed using an unsupported
compression method.

See the snapshot below.

My intention was to get the latest version of "Visual C++ Redistributable for Visual Studio" which led me to the above instructions to install dotnet 6 sdk.

Note the I am using elevated admin PowerShell console for this purpose.

I also got a similar error when I was trying to install the latest version of Selenium PowerShell Module using PowerShell. When I installed version 3.0.1 of Selenium-PowerShell module, it was successful.

Edit:
After installing .NET SDK 6 from MS Build Tools, I completed the steps to configure vscode for Selenium 4, and now I am getting this error:

```<code>PS> dotnet restore
</code>```

C:\Projects\Selenium\demoProject\FirstTest\FirstTest.csproj : error
NU1100: Unable to resolve 'Selenium.WebDriver (>= 4.1.0)' for
'net6.0'.

Other things I tried:

I tried the following config in .csproj and nothing worked:

<TargetFramework>net48</TargetFramework>

<TargetFramework>net5.0</TargetFramework>

<TargetFramework>net6.0</TargetFramework>

Note that the sample Hello World Program of dotnet new console is working fine with all the TargetFramework I used above. The error occurs when I add Selenium.WebDriver to the project using NuGet package manager extension.

After I add the Selenium WebDriver, I get popup requesting to restore, and OmniSharp server will restart, and then a similar error shows up in the output:

```<code>[warn]: OmniSharp.MSBuild.ProjectManager
        Failed to load project file 'c:\Projects\Selenium\demoProject\FirsProj\FirsProj.csproj'.
c:\Projects\Selenium\demoProject\FirsProj\FirsProj.csproj
c:\Projects\Selenium\demoProject\FirsProj\FirsProj.csproj(0,0): Error: Unable to resolve 'Selenium.WebDriver (>= 4.1.0)' for '.NETFramework,Version=v4.8'.
c:\Projects\Selenium\demoProject\FirsProj\FirsProj.csproj(0,0): Error: Unable to resolve 'Selenium.WebDriver (>= 4.1.0)' for '.NETFramework,Version=v4.8/win7-x86'.

[info]: OmniSharp.MSBuild.ProjectManager
        Update project: FirsProj
[warn]: OmniSharp.MSBuild.PackageDependencyChecker
        FirsProj: Did not find 'Selenium.WebDriver' in lock file.
</code>```

I appreciate your help.

答:
I solved the problems with the following:

Using MS Build Tools, I downloaded the needed .NET SDKs. I selected only the needed items. I didn't download Visual Studio.

I did try to download using older version such as using Visual Studio Build Tools 2019 but not sure exactly since I was trying a ton of steps...

There is an issue that the config section of NuGet is empty. Add the following part to %appdata%\NuGet\nuget.config:

```<code><configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <add key="nuget.org" value="https://www.nuget.org/api/v2/" />
  </packageSources>
...
</code>```

See this answer for details.

And, the error disappeared with both .NET 5 and .NET 6.

This is unfair, why it was so hard to find the solution?

Body:
I was following the steps here:

https://www.fleekitsolutions.com/use-selenium-c-visual-studio-code/

To use Selenium 4 with vs code. Then this led me to the following instructions here:

https://learn.microsoft.com/en-us/dotnet/core/install/windows?tabs=net60#install-with-powershell-automation

to install .NET 6 SDK using PowerShell script, and I got the error below:

dotnet-install.ps1: Exception calling "ExtractToFile" with "3"
argument(s): "The archive entry was compressed using an unsupported
compression method.

See the snapshot below.

My intention was to get the latest version of "Visual C++ Redistributable for Visual Studio" which led me to the above instructions to install dotnet 6 sdk.

Note the I am using elevated admin PowerShell console for this purpose.

I also got a similar error when I was trying to install the latest version of Selenium PowerShell Module using PowerShell. When I installed version 3.0.1 of Selenium-PowerShell module, it was successful.

Edit:
After installing .NET SDK 6 from MS Build Tools, I completed the steps to configure vscode for Selenium 4, and now I am getting this error:

PS> dotnet restore

C:\Projects\Selenium\demoProject\FirstTest\FirstTest.csproj : error
NU1100: Unable to resolve 'Selenium.WebDriver (>= 4.1.0)' for
'net6.0'.

Other things I tried:

I tried the following config in .csproj and nothing worked:

<TargetFramework>net48</TargetFramework>

<TargetFramework>net5.0</TargetFramework>

<TargetFramework>net6.0</TargetFramework>

Note that the sample Hello World Program of dotnet new console is working fine with all the TargetFramework I used above. The error occurs when I add Selenium.WebDriver to the project using NuGet package manager extension.

After I add the Selenium WebDriver, I get popup requesting to restore, and OmniSharp server will restart, and then a similar error shows up in the output:

[warn]: OmniSharp.MSBuild.ProjectManager
        Failed to load project file 'c:\Projects\Selenium\demoProject\FirsProj\FirsProj.csproj'.
c:\Projects\Selenium\demoProject\FirsProj\FirsProj.csproj
c:\Projects\Selenium\demoProject\FirsProj\FirsProj.csproj(0,0): Error: Unable to resolve 'Selenium.WebDriver (>= 4.1.0)' for '.NETFramework,Version=v4.8'.
c:\Projects\Selenium\demoProject\FirsProj\FirsProj.csproj(0,0): Error: Unable to resolve 'Selenium.WebDriver (>= 4.1.0)' for '.NETFramework,Version=v4.8/win7-x86'.

[info]: OmniSharp.MSBuild.ProjectManager
        Update project: FirsProj
[warn]: OmniSharp.MSBuild.PackageDependencyChecker
        FirsProj: Did not find 'Selenium.WebDriver' in lock file.

I appreciate your help.

Body:
I solved the problems with the following:

Using MS Build Tools, I downloaded the needed .NET SDKs. I selected only the needed items. I didn't download Visual Studio.

I did try to download using older version such as using Visual Studio Build Tools 2019 but not sure exactly since I was trying a ton of steps...

There is an issue that the config section of NuGet is empty. Add the following part to %appdata%\NuGet\nuget.config:

<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <add key="nuget.org" value="https://www.nuget.org/api/v2/" />
  </packageSources>
...

See this answer for details.

And, the error disappeared with both .NET 5 and .NET 6.

This is unfair, why it was so hard to find the solution?


问:
How can I do a ternary operator inside a map with the mapping for the true condition but without the mapping for the false
I'm trying to return a table with data mapped from an api. When a condition is true I want the data to be mapped and returned but when it's false I want a message to be returned.

Here's my code :

```<code>{ability?.pokemon?.map((ap) =>
  ap.is_hidden === false ? (
    <tr key={ap.pokemon.name} className='ability_container_table_body_row'>
      (multiple td tag)
    </tr>
  ) : (
    <tr>
      <td>No pokémon has this ability</td>
    </tr>
  )
)}
</code>```

The problem is that I need to map the ability.pokemon because otherwise it will only return the data for the first object of the array.

The above code is returning multiple message (one for every pokemon that doesn' check the condition) and I want it to be rendered only once.

Edit : I'm using React JS

答:
```<code>let items = []
const allHidden = ability?.pokemon?.every(ap => ap.is_hidden)
if (allHidden) {
  // No pokemon has this ability
  items = <tr><td>No pokemon has this ability</td><tr>
} else {
 // ... map all visible ones here
 items = ability?.pokemon?.map(ap => !ap.is_hidden && (
    <tr key={ap.pokemon.name} className='ability_container_table_body_row'>
      (multiple td tag)
    </tr>
  ))}
}
return <table>{items}</table> // return or assign items: just an example
</code>```

Check if every pokemon is hidden. If true, then display your "No pokemon", if not, map the visible ones.

The every method checks if all mapped matches the condition.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

https://jsfiddle.net/04fz683g/1/

Body:
I'm trying to return a table with data mapped from an api. When a condition is true I want the data to be mapped and returned but when it's false I want a message to be returned.

Here's my code :

{ability?.pokemon?.map((ap) =>
  ap.is_hidden === false ? (

      (multiple td tag)

  ) : (

      No pokémon has this ability

  )
)}

The problem is that I need to map the ability.pokemon because otherwise it will only return the data for the first object of the array.

The above code is returning multiple message (one for every pokemon that doesn' check the condition) and I want it to be rendered only once.

Edit : I'm using React JS

Body:
let items = []
const allHidden = ability?.pokemon?.every(ap => ap.is_hidden)
if (allHidden) {
  // No pokemon has this ability
  items = <tr><td>No pokemon has this ability</td><tr>
} else {
 // ... map all visible ones here
 items = ability?.pokemon?.map(ap => !ap.is_hidden && (
    <tr key={ap.pokemon.name} className='ability_container_table_body_row'>
      (multiple td tag)
    </tr>
  ))}
}
return <table>{items}</table> // return or assign items: just an example

Check if every pokemon is hidden. If true, then display your "No pokemon", if not, map the visible ones.

The every method checks if all mapped matches the condition.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

https://jsfiddle.net/04fz683g/1/


问:
Connecting an IBOutlet to a view within a scrollview within a tab view crashes app. Any ideas?
I used the tabview setup to create an app that has several tabs. One tab has a UIScrollView on it which loads 12 different views into 12 pages. I tried adding a button and imageview to one of the views and now it crashes. I've pored over every single question on here I can find, and have tried every suggested solution, but to no avail. The error that I get is the famous "this class is not key value coding-compliant for the key foo" error. As with everyone else who had this problem, if I disconnect the outlet, it works fine. I've checked and rechecked the class for the nib and it points to the right place.

So I'm not even sure where to go next.

I could post some code, but I don't even know what code would be helpful to post. I'm hoping someone just says, "Um yeah, you can't have a scroll view with multiple views in it and expect to have functionality on each page." That would be helpful!

Page2.h:

```<code>#import <UIKit/UIKit.h>
</code>```

@interface Page2 : UIViewController {

```<code>IBOutlet UIImageView *infoImage;
</code>```

}

@property (retain, nonatomic) UIImageView *infoImage;

(IBAction) showInfo:(id)sender;

@end

Page2.m:

```<code>- (IBAction)showInfo:(id)sender {

// do something please!
</code>```

}

Then in the nib file I CTRL-dragged from "touch-up inside" on my button to the Files Owner and chose "showInfo" ... and I CTRL-dragged from Files Owner down to my UIImageView and chose infoImage.

CRASH

I am not cool enough to insert an image: http://i.stack.imgur.com/KjWhk.png

答:
I have sent you the email and attached your project. Hope its working at your end now.

Happy Coding!

Body:
I used the tabview setup to create an app that has several tabs. One tab has a UIScrollView on it which loads 12 different views into 12 pages. I tried adding a button and imageview to one of the views and now it crashes. I've pored over every single question on here I can find, and have tried every suggested solution, but to no avail. The error that I get is the famous "this class is not key value coding-compliant for the key foo" error. As with everyone else who had this problem, if I disconnect the outlet, it works fine. I've checked and rechecked the class for the nib and it points to the right place.

So I'm not even sure where to go next.

I could post some code, but I don't even know what code would be helpful to post. I'm hoping someone just says, "Um yeah, you can't have a scroll view with multiple views in it and expect to have functionality on each page." That would be helpful!

Page2.h:

#import <UIKit/UIKit.h>

@interface Page2 : UIViewController {

IBOutlet UIImageView *infoImage;

}

@property (retain, nonatomic) UIImageView *infoImage;

(IBAction) showInfo:(id)sender;

@end

Page2.m:

- (IBAction)showInfo:(id)sender {

// do something please!

}

Then in the nib file I CTRL-dragged from "touch-up inside" on my button to the Files Owner and chose "showInfo" ... and I CTRL-dragged from Files Owner down to my UIImageView and chose infoImage.

CRASH

I am not cool enough to insert an image: http://i.stack.imgur.com/KjWhk.png


问:
I'm trying to find a group of objects with similar names in SQL ORACLE but i'm getting an error that i can't solve
I don't know what's wrong.

Both this queries return the following error:

SQL Error [936] [42000]: ORA-00936: missing expression

Queries:

```<code>SELECT * FROM ALL_OBJECTS WHERE owner = 'hatemalifeDatabase' AND OBJECT_TYPE = 'SEQUENCE' AND OBJECT_NAME = 'Object name changed for security reasons'

SELECT * FROM ALL_OBJECTS WHERE owner = 'WATDATABASE' AND OBJECT_TYPE = 'SEQUENCE' AND OBJECT_NAME LIKE = '%SECURITYREASONS%'
</code>```

This querie is working normally and i modified her to find the alike objects.

```<code>SELECT * FROM ALL_OBJECTS WHERE owner = 'IhateAliens' AND OBJECT_TYPE = 'SEQUENCEm' AND OBJECT_NAME = 'qwkrhqwkrqwkrqwr'
</code>```

答:
do not use '=' with a 'like' condition

Like condition

Body:
I don't know what's wrong.

Both this queries return the following error:

SQL Error [936] [42000]: ORA-00936: missing expression

Queries:

SELECT * FROM ALL_OBJECTS WHERE owner = 'hatemalifeDatabase' AND OBJECT_TYPE = 'SEQUENCE' AND OBJECT_NAME = 'Object name changed for security reasons'

SELECT * FROM ALL_OBJECTS WHERE owner = 'WATDATABASE' AND OBJECT_TYPE = 'SEQUENCE' AND OBJECT_NAME LIKE = '%SECURITYREASONS%'

This querie is working normally and i modified her to find the alike objects.

SELECT * FROM ALL_OBJECTS WHERE owner = 'IhateAliens' AND OBJECT_TYPE = 'SEQUENCEm' AND OBJECT_NAME = 'qwkrhqwkrqwkrqwr'


问:
I want to find values greater than/less than a specific value In Google Sheets and replace them with a another value
I have a have a data set in Google Sheets consisting of numbers between 1 and 100. I want to replace all numbers greater than 10, with 10 (or any other number I choose). Is there a way to do this?

答:
Suppose your original numbers are in A2:A. Place the following formula in B2 of an otherwise empty range B2:B...

=ArrayFormula(IF(A2:A="",, IF(A2:A<10, A2:A, 10)))

For some other maximum number, just change the two instances of 10 in the formula to that other number.


问:
What's my GitHub appliance's REST API endpoint?
I want to use Groovy, HttpBuilder and REST API to access our company's onsidte GitHub appliance.
The GitHub developer's site: https://developer.github.com/v3/, shows this URL: https://api.github.com. So if my company's GitHub URL is: http://github.mycompany.com, what is my REST API endpoint URL? e.g. if I want to list all users, what's the correct URL?

When I access this URL: https://github.mycompany.com/api/v3, it gives me an error:

github.mycompany.com refused to connect.
ERR_CONNECTION_REFUSED

答:
if you need https://github.com/google/shaka-player it would be
https://api.github.com/repos/google/shaka-player

more info at https://api.github.com/

```<code>  "current_user_url": "https://api.github.com/user",

  "current_user_authorizations_html_url": https://github.com/settings/connections/applications{/client_id}",

  "authorizations_url": "https://api.github.com/authorizations",

  "code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}",

  "commit_search_url": "https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}",

  "emails_url": "https://api.github.com/user/emails",

  "emojis_url": "https://api.github.com/emojis",

  "events_url": "https://api.github.com/events",

  "feeds_url": "https://api.github.com/feeds",

  "followers_url": "https://api.github.com/user/followers",

  "following_url": "https://api.github.com/user/following{/target}",

  "gists_url": "https://api.github.com/gists{/gist_id}",

  "hub_url": "https://api.github.com/hub",

  "issue_search_url": "https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}",

  "issues_url": "https://api.github.com/issues",

  "keys_url": "https://api.github.com/user/keys",

  "label_search_url": "https://api.github.com/search/labels?q={query}&repository_id={repository_id}{&page,per_page}",

  "notifications_url": "https://api.github.com/notifications",

  "organization_url": "https://api.github.com/orgs/{org}",

  "organization_repositories_url": "https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}",

  "organization_teams_url": "https://api.github.com/orgs/{org}/teams",

  "public_gists_url": "https://api.github.com/gists/public",

  "rate_limit_url": "https://api.github.com/rate_limit",

  "repository_url": "https://api.github.com/repos/{owner}/{repo}",

  "repository_search_url": "https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}",

  "current_user_repositories_url": "https://api.github.com/user/repos{?type,page,per_page,sort}",

  "starred_url": "https://api.github.com/user/starred{/owner}{/repo}",

  "starred_gists_url": "https://api.github.com/gists/starred",

  "topic_search_url": "https://api.github.com/search/topics?q={query}{&page,per_page}",

  "user_url": "https://api.github.com/users/{user}",

  "user_organizations_url": "https://api.github.com/user/orgs",

  "user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}",

  "user_search_url": "https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"
</code>```

Body:
if you need https://github.com/google/shaka-player it would be
https://api.github.com/repos/google/shaka-player

more info at https://api.github.com/

  "current_user_url": "https://api.github.com/user",

  "current_user_authorizations_html_url": https://github.com/settings/connections/applications{/client_id}",

  "authorizations_url": "https://api.github.com/authorizations",

  "code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}",

  "commit_search_url": "https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}",

  "emails_url": "https://api.github.com/user/emails",

  "emojis_url": "https://api.github.com/emojis",

  "events_url": "https://api.github.com/events",

  "feeds_url": "https://api.github.com/feeds",

  "followers_url": "https://api.github.com/user/followers",

  "following_url": "https://api.github.com/user/following{/target}",

  "gists_url": "https://api.github.com/gists{/gist_id}",

  "hub_url": "https://api.github.com/hub",

  "issue_search_url": "https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}",

  "issues_url": "https://api.github.com/issues",

  "keys_url": "https://api.github.com/user/keys",

  "label_search_url": "https://api.github.com/search/labels?q={query}&repository_id={repository_id}{&page,per_page}",

  "notifications_url": "https://api.github.com/notifications",

  "organization_url": "https://api.github.com/orgs/{org}",

  "organization_repositories_url": "https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}",

  "organization_teams_url": "https://api.github.com/orgs/{org}/teams",

  "public_gists_url": "https://api.github.com/gists/public",

  "rate_limit_url": "https://api.github.com/rate_limit",

  "repository_url": "https://api.github.com/repos/{owner}/{repo}",

  "repository_search_url": "https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}",

  "current_user_repositories_url": "https://api.github.com/user/repos{?type,page,per_page,sort}",

  "starred_url": "https://api.github.com/user/starred{/owner}{/repo}",

  "starred_gists_url": "https://api.github.com/gists/starred",

  "topic_search_url": "https://api.github.com/search/topics?q={query}{&page,per_page}",

  "user_url": "https://api.github.com/users/{user}",

  "user_organizations_url": "https://api.github.com/user/orgs",

  "user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}",

  "user_search_url": "https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"


问:
Loop through folders that have changes in a PR
In a github workflow (.yaml) script, I'm wondering how to loop through any folders that have changes as part of a particular PR.

For instance, suppose I have this structure:

```<code>Dir1\File1.txt
Dir2\File2.txt
Dir3\File3.txt
Dir4\File4.txt
</code>```

If a PR has changes to File2.txt and File4.txt, I want a workflow that will loop thru and do something in folders: Dir2 and Dir4.

I know of a way to do this for specific folders, but I don't want to have to specify all of the folders that exist in my source, i.e. this works for a list of specified directories:

```<code>   - name: myJob
        run: |
          myDirectories=("Dir1" "Dir2" "Dir3" "Dir4")

          for i in "${myDirectories[@]}"
          do
            if git diff --name-only --diff-filter=ACMRT ${{ github.event.pull_request.base.sha }} ${{ github.sha }} | grep -c "^$i/"; then
              ...do something...
            fi
          done
</code>```

Thank you.

答:
Easiest solution will be to use this action: https://github.com/tj-actions/changed-files/

You can do things like:

```<code>- name: Get specific changed files
        id: changed-files-specific
        uses: tj-actions/changed-files@v14.5
        with:
          files: |
            Dir*\*

- name: Run step if any of the listed files above change
        if: steps.changed-files-specific.outputs.any_changed == 'true'
        run: |
          for file in ${{ steps.changed-files-specific.outputs. all_changed_files }}; do
            echo "$file was modified"
          done

</code>```

Body:
In a github workflow (.yaml) script, I'm wondering how to loop through any folders that have changes as part of a particular PR.

For instance, suppose I have this structure:

Dir1\File1.txt
Dir2\File2.txt
Dir3\File3.txt
Dir4\File4.txt

If a PR has changes to File2.txt and File4.txt, I want a workflow that will loop thru and do something in folders: Dir2 and Dir4.

I know of a way to do this for specific folders, but I don't want to have to specify all of the folders that exist in my source, i.e. this works for a list of specified directories:

   - name: myJob
        run: |
          myDirectories=("Dir1" "Dir2" "Dir3" "Dir4")

          for i in "${myDirectories[@]}"
          do
            if git diff --name-only --diff-filter=ACMRT ${{ github.event.pull_request.base.sha }} ${{ github.sha }} | grep -c "^$i/"; then
              ...do something...
            fi
          done

Thank you.

Body:
Easiest solution will be to use this action: https://github.com/tj-actions/changed-files/

You can do things like:

- name: Get specific changed files
        id: changed-files-specific
        uses: tj-actions/changed-files@v14.5
        with:
          files: |
            Dir*\*

- name: Run step if any of the listed files above change
        if: steps.changed-files-specific.outputs.any_changed == 'true'
        run: |
          for file in ${{ steps.changed-files-specific.outputs. all_changed_files }}; do
            echo "$file was modified"
          done


问:
ReferenceError: Path is not defined: EJS
The app runs for shop and admin routes but doesn't work for error route.Error routes was also in MVC format but i tested it without the architecture also.

Below is the snippet of app.js from root directory.

```<code>const path = require('path');

const express = require('express');
const bodyParser = require('body-parser');

const errorController = require('./controllers/error');

const app = express();

app.set('view engine', 'ejs');
app.set('views', 'views');

const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/admin', adminRoutes);
app.use(shopRoutes);

app.use((req, res, next) => {
  res.status(404).render('404', { pageTitle: 'Page Not Found' });
});

app.listen(3000);
</code>```

And the 404 EJS code is

```<code><%- include('includes/head.ejs') %>
</head>

<body>
    <%- include('includes/navigation.ejs') %>
    <h1>Page Not Found!</h1>

<%- include('includes/end.ejs') %>
</code>```

And, Navigation.ejs is

```<code><header class="main-header">
    <nav class="main-header__nav">
        <ul class="main-header__item-list">
            <li class="main-header__item">
                <a class="<%= path === '/' ? 'active' : '' %>" href="/">Shop</a>
            </li>
            <li class="main-header__item">
                <a class="<%= path === '/admin/add-product' ? 'active' : '' %>" href="/admin/add-product">Add Product</a>
            </li>
        </ul>
    </nav>
</header>
</code>```

It shows the following error:

```<code>ReferenceError: C:\Users\Najus\Desktop\New folder\views\404.ejs:5
    3|
    4| <body>
 >> 5|     <%- include('includes/navigation.ejs') %>
    6|     <h1>Page Not Found!</h1>
    7|
    8| <%- include('includes/end.ejs') %>

C:\Users\Najus\Desktop\New folder\views\includes\navigation.ejs:6
    4|         <ul class="main-header__item-list">
    5|             <li class="main-header__item">
 >> 6|                 <a class="<%= path === '/' ? 'active' : '' %>" href="/">Shop</a>
    7|             </li>
    8|             <li class="main-header__item">
    9|                 <a class="<%= path === '/admin/add-product' ? 'active' : '' %>" href="/admin/add-product">Add Product</a>

path is not defined
    at eval (eval at compile (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:618:12), <anonymous>:11:26)
    at returnedFn (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:653:17)
    at include (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:651:39)
    at eval (eval at compile (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:618:12), <anonymous>:12:17)
    at returnedFn (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:653:17)
    at tryHandleCache (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:251:36)
    at View.exports.renderFile [as engine] (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:482:10)
    at View.render (C:\Users\Najus\Desktop\New folder\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\Users\Najus\Desktop\New folder\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\Users\Najus\Desktop\New folder\node_modules\express\lib\application.js:592:3)
</code>```

I have tried back and forth various ways looking up the internet and couldn't find the way to tweak the code.

答:
ejs uses relative path, so include the layout folder as part of the path i.e

<%- include('layouts/includes/navigation.ejs') %>

Body:
The app runs for shop and admin routes but doesn't work for error route.Error routes was also in MVC format but i tested it without the architecture also.

Below is the snippet of app.js from root directory.

const path = require('path');

const express = require('express');
const bodyParser = require('body-parser');

const errorController = require('./controllers/error');

const app = express();

app.set('view engine', 'ejs');
app.set('views', 'views');

const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/admin', adminRoutes);
app.use(shopRoutes);

app.use((req, res, next) => {
  res.status(404).render('404', { pageTitle: 'Page Not Found' });
});

app.listen(3000);

And the 404 EJS code is

<%- include('includes/head.ejs') %>

    <%- include('includes/navigation.ejs') %>

Page Not Found!

<%- include('includes/end.ejs') %>

And, Navigation.ejs is

                <a class="<%= path === '/' ? 'active' : '' %>" href="/">Shop

                <a class="<%= path === '/admin/add-product' ? 'active' : '' %>" href="/admin/add-product">Add Product

It shows the following error:

ReferenceError: C:\Users\Najus\Desktop\New folder\views\404.ejs:5
    3|
    4|
 >> 5|     <%- include('includes/navigation.ejs') %>
    6|
Page Not Found!

    7|
    8| <%- include('includes/end.ejs') %>

C:\Users\Najus\Desktop\New folder\views\includes\navigation.ejs:6
    4|

    5|

 >> 6|                 <a class="<%= path === '/' ? 'active' : '' %>" href="/">Shop
    7|

    8|

    9|                 <a class="<%= path === '/admin/add-product' ? 'active' : '' %>" href="/admin/add-product">Add Product

path is not defined
    at eval (eval at compile (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:618:12), <anonymous>:11:26)
    at returnedFn (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:653:17)
    at include (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:651:39)
    at eval (eval at compile (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:618:12), <anonymous>:12:17)
    at returnedFn (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:653:17)
    at tryHandleCache (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:251:36)
    at View.exports.renderFile [as engine] (C:\Users\Najus\Desktop\New folder\node_modules\ejs\lib\ejs.js:482:10)
    at View.render (C:\Users\Najus\Desktop\New folder\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\Users\Najus\Desktop\New folder\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\Users\Najus\Desktop\New folder\node_modules\express\lib\application.js:592:3)

I have tried back and forth various ways looking up the internet and couldn't find the way to tweak the code.


问:
Assist me in creating a hamburger menu for responsive website
I created a responsive hamburger menu for my website, however, there is a button tag in the navbar that is causing an issue.

It seems to be great on a desktop view, however, the button is missing from the hamburger menu on a mobile device.

If I put the button tag under the ul, the desktop view is disrupted.

Despite the fact that it is unfinished, please assist with this issue.

I'm including an image to give you an idea of what I'm looking for.

@import url("https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300&family=Prata&display=swap");
* {
  margin: 0%;
  padding: 0%;
  font-family: "Inter", "Prata", serif;
}

body {
  background: black;
  color: white;
}

.navbar-section {
  margin: 2rem 6rem;
}

.nav-logo,
.nav-links,
.nav-button {
  font-family: "prata", sans-serif;
}

.nav-logo {
  align-self: center;
}

.nav-logo {
  text-decoration: none;
  font-family: "prata", sans-serif;
  font-size: 18px;
  font-weight: 100;
}

.navbar {
  display: flex;
  justify-content: space-between;
}

.navbar a {
  text-decoration: none;
  color: rgb(190, 190, 190);
  align-self: center;
  font-size: 18px;
}

.nav-links {
  display: flex;
  justify-content: space-between;
  flex-grow: 0.2;
  align-self: center;
}

.nav-links li {
  list-style-type: none;
}

.nav-button {
  background-color: rgb(255, 219, 74);
  color: black;
  border-style: none;
  font-size: 18px;
  padding: 10px 20px;
  font-family: "prata", sans-serif;
}

/* responsive menu */

@media(max-width: 700px) {
  #icon {
    display: block;
  }
  nav ul {
    display: flex;
    flex-direction: column;
    position: fixed;
    width: 100%;
    height: 100vh;
    background-color: #2f3640;
    top: 80px;
    left: 0;
    text-align: center;
  }
  .nav-links li {
    display: block;
    margin: 50px 0;
    line-height: 30px;
  }
  .nav-links a {
    font-size: 20px;
  }
  a.active,
  a:hover {
    color: #3498db;
  }
  .nav-links i {
    font-size: 32px;
    padding-left: 60px;
  }
  nav ul {
    margin-right: 20px;
  }
  nav a {
    font-size: 17px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar-section">
  <nav class="navbar">
    <!-- Navbar Logo  -->
    Johnathan Specter

    <!-- Navbar Links  -->
    <ul class="nav-links">
      <li>Articles</li>
      <li>Chats</li>
      <li>Awards</li>
      <li>About</li>
    </ul>
    <!-- Navbar Button  -->
    <button class="nav-button">Get in touch</button>
  </nav>
</div></code>```

答:
Try to use @media css rule for different screen widths.
https://www.w3schools.com/cssref/css3_pr_mediaquery.asp

Many ways to approach it.

The trick sometimes is to make 2 menus.
One shown on pc and one for mobile.

You could also use JS if youre familiar with it.

codepen is a good place to try out examples.

Body:
I created a responsive hamburger menu for my website, however, there is a button tag in the navbar that is causing an issue.

It seems to be great on a desktop view, however, the button is missing from the hamburger menu on a mobile device.

If I put the button tag under the ul, the desktop view is disrupted.

Despite the fact that it is unfinished, please assist with this issue.

I'm including an image to give you an idea of what I'm looking for.

@import url("https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300&family=Prata&display=swap");
* {
  margin: 0%;
  padding: 0%;
  font-family: "Inter", "Prata", serif;
}

body {
  background: black;
  color: white;
}

.navbar-section {
  margin: 2rem 6rem;
}

.nav-logo,
.nav-links,
.nav-button {
  font-family: "prata", sans-serif;
}

.nav-logo {
  align-self: center;
}

.nav-logo {
  text-decoration: none;
  font-family: "prata", sans-serif;
  font-size: 18px;
  font-weight: 100;
}

.navbar {
  display: flex;
  justify-content: space-between;
}

.navbar a {
  text-decoration: none;
  color: rgb(190, 190, 190);
  align-self: center;
  font-size: 18px;
}

.nav-links {
  display: flex;
  justify-content: space-between;
  flex-grow: 0.2;
  align-self: center;
}

.nav-links li {
  list-style-type: none;
}

.nav-button {
  background-color: rgb(255, 219, 74);
  color: black;
  border-style: none;
  font-size: 18px;
  padding: 10px 20px;
  font-family: "prata", sans-serif;
}

/* responsive menu */

@media(max-width: 700px) {
  #icon {
    display: block;
  }
  nav ul {
    display: flex;
    flex-direction: column;
    position: fixed;
    width: 100%;
    height: 100vh;
    background-color: #2f3640;
    top: 80px;
    left: 0;
    text-align: center;
  }
  .nav-links li {
    display: block;
    margin: 50px 0;
    line-height: 30px;
  }
  .nav-links a {
    font-size: 20px;
  }
  a.active,
  a:hover {
    color: #3498db;
  }
  .nav-links i {
    font-size: 32px;
    padding-left: 60px;
  }
  nav ul {
    margin-right: 20px;
  }
  nav a {
    font-size: 17px;
  }
}

    Johnathan Specter

Articles

Chats

Awards

About

    <button class="nav-button">Get in touch</button>


问:
XNA/C# 2D Coordinate Scaling in World Matrix to 3D View Matrix?
This is my Transform. I got it from an example of a simple 2D camera.

```<code>    public Matrix Transform(GraphicsDevice graphicsDevice)
    {
        float ViewportWidth = graphicsDevice.Viewport.Width;
        float ViewportHeight = graphicsDevice.Viewport.Height;

        matrixTransform =
          Matrix.CreateTranslation(new Vector3(-cameraPosition.X, -cameraPosition.Y, 0)) *
              Matrix.CreateRotationZ(Rotation) *
              Matrix.CreateScale(new Vector3(Zoom, Zoom, 0)) *
              Matrix.CreateTranslation(
                    new Vector3(ViewportWidth * 0.5f, ViewportHeight * 0.5f, 0));
        return matrixTransform;
    }
</code>```

If I understand it correctly, it allows for a roll(rotation), sprite scale change on zoom, and translation between world and camera for simple up, down, left, right controls. However, it does not alter the Z depth.

But what I need is for the game world to zoom, not just the sprites drawn. And I assume in order to do this I need to change the Z distance between the camera and the world matrix.

I am VERY NEW to programming and have only a simple understanding of matrix in general. I have even less understanding as to how XNA uses them in the draw method. And so far I feel like pulling my hair out from a fruitless search for answers... I just need the world coordinates to scale on zoom, so that before my mouse at a pre-zoom X.60 Y.60 will be at X.600 Y.600 post-zoom (ie: zoom level 0.1). But my mouse has not moved, only the world got bigger in view (or shrank).

答:
I seem to have figured out how to get the coordinates to scale...

I was assuming that the current mouse status would reflect the world matrix its clicked on, but apparently it never actually does this. It is always linked to the view matrix. (The screen itself) and that value needs to scale along with the world matrix (in the transform).

So as the transform is effected by Zoom in the Matrix.CreateScale(new Vector3(Zoom, Zoom, 0)) so too does the mouseState X & Y coordinates need to be scaled by it to virtually mirror the world matrix.

```<code>    //Offsets any cam location by a zoom scaled window bounds
    Vector2 CamCenterOffset
    {
        get { return new Vector2((game.Window.ClientBounds.Height / Zoom)
             * 0.5f, (game.Window.ClientBounds.Width / Zoom) * 0.5f);
        }
    }

    //Scales the mouse.X and mouse.Y by the same Zoom as everything.
    Vector2 MouseCursorInWorld
    {
        get
        {
            currMouseState = Mouse.GetState();
            return cameraPosition + new Vector2(currMouseState.X / Zoom,
                currMouseState.Y / Zoom);
        }
    }
</code>```

Body:
This is my Transform. I got it from an example of a simple 2D camera.

    public Matrix Transform(GraphicsDevice graphicsDevice)
    {
        float ViewportWidth = graphicsDevice.Viewport.Width;
        float ViewportHeight = graphicsDevice.Viewport.Height;

        matrixTransform =
          Matrix.CreateTranslation(new Vector3(-cameraPosition.X, -cameraPosition.Y, 0)) *
              Matrix.CreateRotationZ(Rotation) *
              Matrix.CreateScale(new Vector3(Zoom, Zoom, 0)) *
              Matrix.CreateTranslation(
                    new Vector3(ViewportWidth * 0.5f, ViewportHeight * 0.5f, 0));
        return matrixTransform;
    }

If I understand it correctly, it allows for a roll(rotation), sprite scale change on zoom, and translation between world and camera for simple up, down, left, right controls. However, it does not alter the Z depth.

But what I need is for the game world to zoom, not just the sprites drawn. And I assume in order to do this I need to change the Z distance between the camera and the world matrix.

I am VERY NEW to programming and have only a simple understanding of matrix in general. I have even less understanding as to how XNA uses them in the draw method. And so far I feel like pulling my hair out from a fruitless search for answers... I just need the world coordinates to scale on zoom, so that before my mouse at a pre-zoom X.60 Y.60 will be at X.600 Y.600 post-zoom (ie: zoom level 0.1). But my mouse has not moved, only the world got bigger in view (or shrank).

Body:
I seem to have figured out how to get the coordinates to scale...

I was assuming that the current mouse status would reflect the world matrix its clicked on, but apparently it never actually does this. It is always linked to the view matrix. (The screen itself) and that value needs to scale along with the world matrix (in the transform).

So as the transform is effected by Zoom in the Matrix.CreateScale(new Vector3(Zoom, Zoom, 0)) so too does the mouseState X & Y coordinates need to be scaled by it to virtually mirror the world matrix.

    //Offsets any cam location by a zoom scaled window bounds
    Vector2 CamCenterOffset
    {
        get { return new Vector2((game.Window.ClientBounds.Height / Zoom)
             * 0.5f, (game.Window.ClientBounds.Width / Zoom) * 0.5f);
        }
    }

    //Scales the mouse.X and mouse.Y by the same Zoom as everything.
    Vector2 MouseCursorInWorld
    {
        get
        {
            currMouseState = Mouse.GetState();
            return cameraPosition + new Vector2(currMouseState.X / Zoom,
                currMouseState.Y / Zoom);
        }
    }