问:
c# - cast generic class to its base non-generic class
I have following classes:

```<code>public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}
</code>```

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

```<code>    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }
</code>```

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

```<code>public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }
</code>```

答: You could move the WalkHierarchy method to the base class and make it virtual. The base class implementation would only process the current node. For the CustomerWithChildern<T> class, the override would do an actual walk.

OwnerDisplayName: Buthrakaur

ContentLicense: CC BY-SA 2.5

Body:
I have following classes:

public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }

LastEditorDisplayName: Buthrakaur

OwnerDisplayName: John Saunders


来源: stackexchange

问:
How to open mailto link in Chrome with Window.open without creating a new tab?
I am creating a Google Chrome extension and am trying to open a custom url scheme with (window.open) without having a new blank tab open up. For sake of argument lets try the 'mailto' url scheme.

My code:

```<code>window.open("mailto://Bob Lawblah", '_self');
</code>```

Unfortunately this open up a new blank tab as well as opening up the default mail program even though I specified '_self'. According to this I don't seem to be anything wrong.

Any ideas on how to not have an extra tab open when opening a 'mailto' link?

答: Since you're in a Chrome Extension context, you should be using chrome.tabs APIs. If you have an extra tab floating around, you can just close it via http://code.google.com/chrome/extensions/tabs.html#method-remove

ContentLicense: CC BY-SA 3.0

Body:
I am creating a Google Chrome extension and am trying to open a custom url scheme with (window.open) without having a new blank tab open up. For sake of argument lets try the 'mailto' url scheme.

My code:

window.open("mailto://Bob Lawblah", '_self');

Unfortunately this open up a new blank tab as well as opening up the default mail program even though I specified '_self'. According to this I don't seem to be anything wrong.

Any ideas on how to not have an extra tab open when opening a 'mailto' link?


问:
Incremental counter right before each

This should be easy, although I spent over 4 hours and nothing! I REALLY need to add a counter for
 tag, inside an specific DIV CLASS, to count lyric lines, and "echo" the corresponding number on each line right before the
. I understand that this can´t be done by css, like happens with
, because
 won´t allow before and after css conditionals. Will really appreciate the help.

Example:

Every time when I look in the mirror 1

All these lines on my face getting clearer 2

The past is gone 3

And it went by, like dusk to dawn 4

Isn't that the way? 5

Everybody's got their dues in life to pay 6

Yeah, I know nobody knows 7

Where it comes and where it goes 8

I know it's everybody's sin 9

You got to lose to know how to win 10

答:
In PHP, you can use explode function to extract all new lines as below

```<code>$arr=explode(PHP_EOL, $lyrics);

foreach($arr as $index=>$ele){
echo $ele.$index+1.'<br>';
}
</code>```

If you are getting another issues please fill free to comment.

ContentLicense: CC BY-SA 4.0

Title: Incremental counter right before each <br />

Body:
In PHP, you can use explode function to extract all new lines as below

$arr=explode(PHP_EOL, $lyrics);

foreach($arr as $index=>$ele){
echo $ele.$index+1.'<br>';
}

If you are getting another issues please fill free to comment.


问:
How to enable Multidex inside flutter which is added to existing android project as module
I have and android project, which I added flutter on it as module,
In my original android app, multidex is enabled, but this do not help me, when running the app in debug it's working normally, but when creating a release apk or even debug apk the FlutterFragment is appearing as white, like the engine did not attach.

Things I notice, 'flutter run --release' will ask me to support multidex, and will not run, updating the minSdkVersion to 21 and enabling multidex in .android/app/build.gradle then again 'flutter run --release' works perfect, but this have no effect on the host app because it's under .android which automatically build, and ignored by the host app.

Also I tried to search for how to update minSdkVersion to 21 instead of 16, but references lead to change in the .android which have no effect.

答:
Hey you can do two thing

Update your flutter SDK version by running command
flutter upgrade
The new version of flutter(2.10) multidex  support automatically.
simply pass the --multidex flag to flutter build appbundle or flutter build apk and your app will support multidex.

2.In your app folder inside android [project_folder]/app/build.gradle and add following lines.

```<code>defaultConfig {
...

multiDexEnabled true
</code>```

}

and

```<code>dependencies {
...

implementation 'com.android.support:multidex:1.0.3'
}
</code>```

Body:
Hey you can do two thing

Update your flutter SDK version by running command
flutter upgrade
The new version of flutter(2.10) multidex  support automatically.
simply pass the --multidex flag to flutter build appbundle or flutter build apk and your app will support multidex.

2.In your app folder inside android [project_folder]/app/build.gradle and add following lines.

defaultConfig {
...

multiDexEnabled true

}

and

dependencies {
...

implementation 'com.android.support:multidex:1.0.3'
}


问:
add a button below textarea in powerportals using jquery
I was wondering if there is away to add a button below a textarea using jquery. I have generated html like below in power portals page.

```<code><textarea rows="7" cols="20" maxlength="2000" id="description" class="textarea form-control "></textarea>
</code>```

I would like to add a button just below it. I am using the code below but it is not displaying the button at all.

```<code>$(document).ready(function () {
$("#description").append("<button type='button' id='btnSave' class='btn'
style='color:#fff;background-color:#36f;border-color:36f;'
onclick='savefunction'>Save</button><br><br>");
});
</code>```

答:
You cannot put html inside textarea, you can only put text inside it.
If you want to display a button within a text area, you can try appending the button on the parent of text area. and position the button accordingly.

$(document).ready(function () {
$("#textwrapper").append("<button onclick='savefunction' id='btnSave' type='button' style='color: #fff; background: #36f; border-color:#36f; display:block; margin-left:auto;'>Save</button>

");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}
.textarea-wrapper {
  position: relative;
  display:inline-block;
}</code>```

<textarea rows="7" cols="20" maxlength="2000" id="description" class="textarea form-control "></textarea>

```

Body:
I was wondering if there is away to add a button below a textarea using jquery. I have generated html like below in power portals page.

<textarea rows="7" cols="20" maxlength="2000" id="description" class="textarea form-control "></textarea>

I would like to add a button just below it. I am using the code below but it is not displaying the button at all.

$(document).ready(function () {
$("#description").append("<button type='button' id='btnSave' class='btn'
style='color:#fff;background-color:#36f;border-color:36f;'
onclick='savefunction'>Save</button>

");
});

Body:
You cannot put html inside textarea, you can only put text inside it.
If you want to display a button within a text area, you can try appending the button on the parent of text area. and position the button accordingly.

$(document).ready(function () {
$("#textwrapper").append("<button onclick='savefunction' id='btnSave' type='button' style='color: #fff; background: #36f; border-color:#36f; display:block; margin-left:auto;'>Save</button><br><br>");
});

* {
  box-sizing: border-box;
}
.textarea-wrapper {
  position: relative;
  display:inline-block;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="textwrapper" class="textarea-wrapper">
<textarea rows="7" cols="20" maxlength="2000" id="description" class="textarea form-control "></textarea>
</div>


问:
how to add font family into in main.dart flutter
I'm new to flutter and struggling to add font family in my code..already updated my pubspec.yamal with OpenSans fonts.. now how to add font family into this main. dart material app widget??

fontFamily: "OpenSans",

```<code>Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: theme.copyWith(
        colorScheme: theme.colorScheme.copyWith(primary: Color(0xff075e54),secondary: Color(0xff128C7E),

        ),
      ),
      home: Homescreen(key: null),
    );
  }
}
</code>```

答:
You can create a style file in your dart folder and use the font where ever you want like this way-text_styles.dart

```<code>class TextStyles {
  static TextStyle overline(
      {required BuildContext context, required Color color}) {
    return GoogleFonts.montserrat(
      textStyle: Theme.of(context).textTheme.overline?.copyWith(color: color),
    );
  }
}
</code>```

and use it as-

```<code>TextStyles.overline(context: context, color: theme.textColor).copyWith(fontWeight: FontWeight.w900),
</code>```

Note:if you use custom font you have to install the package from your pubspec.yaml.Example-

```<code>google_fonts:
</code>```

Body:
I'm new to flutter and struggling to add font family in my code..already updated my pubspec.yamal with OpenSans fonts.. now how to add font family into this main. dart material app widget??

fontFamily: "OpenSans",

Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: theme.copyWith(
        colorScheme: theme.colorScheme.copyWith(primary: Color(0xff075e54),secondary: Color(0xff128C7E),

        ),
      ),
      home: Homescreen(key: null),
    );
  }
}

Body:
You can create a style file in your dart folder and use the font where ever you want like this way-text_styles.dart

class TextStyles {
  static TextStyle overline(
      {required BuildContext context, required Color color}) {
    return GoogleFonts.montserrat(
      textStyle: Theme.of(context).textTheme.overline?.copyWith(color: color),
    );
  }
}

and use it as-

TextStyles.overline(context: context, color: theme.textColor).copyWith(fontWeight: FontWeight.w900),

Note:if you use custom font you have to install the package from your pubspec.yaml.Example-

google_fonts:


问:
How to Inspect an Element in Android Browser
I am trying to inspect an element in android browser but unable to find any software for that.
Can someone help  me in this?</p>

答:
It will look something like this:

Steps:

Go To Home Page > Press Three Dot Menu > Press Star icon (Add Bookmark)

Now Press Edit down below

Now Add the below code in URL section and change name of bookmark to Inspect Element or whatever you want.

Code:

javascript:(function () { var script = document.createElement('script'); script.src="//cdn.jsdelivr.net/npm/eruda"; document.body.appendChild(script); script.onload = function () { eruda.init() } })();
```

Now go back and open any site where you want to inspect, example: https://google.com > press the search bar at top > Search that Bookmark which you just saved > Press that bookmark

Now you will see a new floating button at below right corner

Just press that button and done

Note:

Don't forget to enable JavaScript and Pop-ups from Site Settings !

Body:
It will look something like this:

Steps:

Go To Home Page > Press Three Dot Menu > Press Star icon (Add Bookmark)

Now Press Edit down below

Now Add the below code in URL section and change name of bookmark to Inspect Element or whatever you want.

Code:

javascript:(function () { var script = document.createElement('script'); script.src="//cdn.jsdelivr.net/npm/eruda"; document.body.appendChild(script); script.onload = function () { eruda.init() } })();

Now go back and open any site where you want to inspect, example: https://google.com > press the search bar at top > Search that Bookmark which you just saved > Press that bookmark

Now you will see a new floating button at below right corner

Just press that button and done

Note:

Don't forget to enable JavaScript and Pop-ups from Site Settings !


问:
Android studio: How to artificially display a webpage?
I want to show the html file stored in localstorage when I access a webpage using chrome without being connected to the internet.

For example, if you try to access https://google.com without being connected to the Internet

```<code><p>google.com</p>
</code>```

I want the above html code to be displayed.

How can I perform the above tasks using android studio?

*(My native language is not English. Please forgive me if the sentence is awkward)

答:
Use this code inside activity</p>
```<code> WebView wv;
 wv = (WebView) findViewById(R.id.webView1);
 wv.loadUrl("file:///android_asset/aboutcertified.html");
</code>```

Body:
I want to show the html file stored in localstorage when I access a webpage using chrome without being connected to the internet.

For example, if you try to access https://google.com without being connected to the Internet

google.com

I want the above html code to be displayed.

How can I perform the above tasks using android studio?

*(My native language is not English. Please forgive me if the sentence is awkward)

Body:
Use this code inside activity

 WebView wv;
 wv = (WebView) findViewById(R.id.webView1);
 wv.loadUrl("file:///android_asset/aboutcertified.html");


问:
How to check if Email exists , throw error if so , and create user if no match with Sequelize and Express?
I am trying to check if the req.body.email already exists in the
db, then I would like to throw error, if not in the db , then try and create my user... But this is failing its only returning email is in system even if i change the email can anyone help me with this one please ?</p>
```<code>const User = require("../models/users");

const createSingleUser = async (req, res) => {
  // we need to make sure the provided email is not being used if it exists in the db
  // them we through an error if not then we create the user
  // step one lets search by the email provided
  const checkEmail = req.body.email;
  const found = await User.findOne({
    where: {
      email: checkEmail,
    },
  });
  // if found is not empty meaning a match was found
  if (found != "") {
    res.send("this email is already in system");
  } else {
    // create the user since its empty no match found
    try {
      const newUser = await User.create({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        dateOfBirth: req.body.dateOfBirth,
        email: req.body.email,
        phone: req.body.phone,
      });
      User.sync({ alter: true });
      res.send(await newUser);
    } catch (err) {
      res.send(err);
    }
  }
};

module.exports = createSingleUser;
</code>```

答:
You can use findOrCreate</p>
```<code>const createSingleUser = async (req, res) => {
  const { email } = req.body;
  const [user, created] = await User.findOrCreate({
    where: { email },
    defaults: { ...req.body }
  });

  if (!created) {
    res.send("this email is already in system");
  }
  return res.send(user);
};
</code>```

Body:
I am trying to check if the req.body.email already exists in the
db, then I would like to throw error, if not in the db , then try and create my user... But this is failing its only returning email is in system even if i change the email can anyone help me with this one please ?

const User = require("../models/users");

const createSingleUser = async (req, res) => {
  // we need to make sure the provided email is not being used if it exists in the db
  // them we through an error if not then we create the user
  // step one lets search by the email provided
  const checkEmail = req.body.email;
  const found = await User.findOne({
    where: {
      email: checkEmail,
    },
  });
  // if found is not empty meaning a match was found
  if (found != "") {
    res.send("this email is already in system");
  } else {
    // create the user since its empty no match found
    try {
      const newUser = await User.create({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        dateOfBirth: req.body.dateOfBirth,
        email: req.body.email,
        phone: req.body.phone,
      });
      User.sync({ alter: true });
      res.send(await newUser);
    } catch (err) {
      res.send(err);
    }
  }
};

module.exports = createSingleUser;

Body:
You can use findOrCreate

const createSingleUser = async (req, res) => {
  const { email } = req.body;
  const [user, created] = await User.findOrCreate({
    where: { email },
    defaults: { ...req.body }
  });

  if (!created) {
    res.send("this email is already in system");
  }
  return res.send(user);
};


答:
You can try this</p>
```<code>theme: theme.copyWith(
        colorScheme: theme.colorScheme.copyWith(primary: Color(0xff075e54),secondary: Color(0xff128C7E)),
        textTheme: theme.textTheme.apply(fontFamily: "OpenSans"),
),

</code>```

Title: how to add font family into in main.dart flutter

Body:
You can try this

theme: theme.copyWith(
        colorScheme: theme.colorScheme.copyWith(primary: Color(0xff075e54),secondary: Color(0xff128C7E)),
        textTheme: theme.textTheme.apply(fontFamily: "OpenSans"),
),


问: how to extract a link inside

答:
You can try extracting the json data, parse it to dictionary value and then navigate dictionary to get the data (json_data["/music/*-:id"]["musicData"]["playUrl"]["UrlList"][0])

```<code>import pycurl
from io import BytesIO
import certifi
from bs4 import BeautifulSoup
import re
import json

url = "https://vm.tiktok.com/ZML1t1vW7/"
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.CAINFO, certifi.where())
c.setopt(c.URL, url)
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(pycurl.SSL_VERIFYHOST, 0)
c.setopt(pycurl.HTTPHEADER, ["User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"])
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.FOLLOWLOCATION, True)
c.perform()
c.close()
body = buffer.getvalue()
response = body.decode('utf-8')
soup = BeautifulSoup(response, 'html.parser')
scripts = soup.findAll("script")

for s in scripts:
    s_str = str(s)
    res = re.search(r'<script>window.__INIT_PROPS__ = (.*)</script>', s_str)
    if res:
        json_data = json.loads(res.group(1))
        print(json_data["/music/*-:id"]["musicData"]["playUrl"]["UrlList"][0])
</code>```

Title: how to extract a link inside <script> tag

Body:
I'm trying to get a .mp3 file in a link from TikTok sounds
the problem is I can't extract it because it's inside <"script"> tag

I'm using pycurl instead of requests

all i need is to extract this from the response then extract the URL from UrlList"
"playUrl":{"Uri":"musically-maliva-obj/7038595527327419141.mp3","UrlList":["https://sf16-ies-music-va.tiktokcdn.com/obj/musically-maliva-obj/7038595527327419141.mp3"]}

import pycurl
from io import BytesIO
import certifi
from bs4 import BeautifulSoup

url = "https://vm.tiktok.com/ZML1t1vW7/"
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.CAINFO, certifi.where())
c.setopt(c.URL, url)
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(pycurl.SSL_VERIFYHOST, 0)
c.setopt(pycurl.HTTPHEADER, ["User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"])
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.FOLLOWLOCATION, True)
c.perform()
c.close()
body = buffer.getvalue()
response = body.decode('utf-8')
#response = response.split('"')
#response = response[1]
#response = response.split('.html?')
#response= response[0]
a = response.split("'")  # gives me a list and i don't know how to search in it
soup = BeautifulSoup(response, 'html.parser')  # cause response is a string
link = soup.find("script", id="sigi-persisted-data")  #i tried to use bs4 but i couldn't find a reasult
print(link)

Body:
You can try extracting the json data, parse it to dictionary value and then navigate dictionary to get the data (json_data["/music/*-:id"]["musicData"]["playUrl"]["UrlList"][0])

import pycurl
from io import BytesIO
import certifi
from bs4 import BeautifulSoup
import re
import json

url = "https://vm.tiktok.com/ZML1t1vW7/"
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.CAINFO, certifi.where())
c.setopt(c.URL, url)
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(pycurl.SSL_VERIFYHOST, 0)
c.setopt(pycurl.HTTPHEADER, ["User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"])
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.FOLLOWLOCATION, True)
c.perform()
c.close()
body = buffer.getvalue()
response = body.decode('utf-8')
soup = BeautifulSoup(response, 'html.parser')
scripts = soup.findAll("script")

for s in scripts:
    s_str = str(s)
    res = re.search(r'<script>window.__INIT_PROPS__ = (.*)</script>', s_str)
    if res:
        json_data = json.loads(res.group(1))
        print(json_data["/music/*-:id"]["musicData"]["playUrl"]["UrlList"][0])


问:
Calculate date & time difference between two cells (DD.MM.YYYY HH:MM:SS)

I am trying to find the difference in datetime between two cells from an imported data file.

I cannot seem to find the correct formula with the formatting.

DD.MM.YYYY HH:MM:SS

Is there anything I can do to help calculate without getting a #VALUE error? Attached below is a sample - the imported files often contain hundreds of entries.

答:
You can get Days, Months, Year, Hours and Minutes as difference between two dates. DD/MM/YYYY itself is a date format. You get can get datetime difference with:</p>
```<code>=DATEDIF(A2,B2,"y")&" years, "&DATEDIF(A2,B2,"ym")&" months, "&DATEDIF(A2,B2,"md")&" days, "&HOUR(B2-A2)&" hours, "&MINUTE(B2-A2)&" minutes and "&SECOND(B2-A2)&" seconds"
</code>```

Body:
You can get Days, Months, Year, Hours and Minutes as difference between two dates. DD/MM/YYYY itself is a date format. You get can get datetime difference with:

=DATEDIF(A2,B2,"y")&" years, "&DATEDIF(A2,B2,"ym")&" months, "&DATEDIF(A2,B2,"md")&" days, "&HOUR(B2-A2)&" hours, "&MINUTE(B2-A2)&" minutes and "&SECOND(B2-A2)&" seconds"


问:
How can I get current projectId inside Google Cloud Functions?
The question is simple. I need projectId in order to establish connection insde Google Cloud Function. I found the documentation where it said, that projectId is optional parameter and will be checked from GCLOUD_PROJECT, but on deployed function it didn't work.

So it is the question now how can I get the projectId env variable in order to pass it as argument for Datastore connection instance, or what should be done to not pass this id and establish connection with datastore inside Google Cloud Function?

Update 1

I found that I actually can get variable from process.env.GCLOUD_PROJECT, just like any other env.variable.
But, know is the last question, is it actually possible to use @google-cloud/datastore without any configuration object?

答:
The answer depends on which runtime you are using.
If your using  Python 3.7 and Go 1.11 you are in luck. Use

```<code>process.env.GCP_PROJECT
</code>```

If using any of the new runtimes, bad luck, either access the metadata server, or google suggests

Note: If your function/app requires one of the environment variables from
an older runtime, you can set the variable when deploying your
function. For example:

```<code>gcloud functions deploy envVarMemory \
--runtime nodejs10 \
--set-env-vars FUNCTION_MEMORY_MB=2Gi \
--memory 2Gi \
--trigger-http
</code>```

If using terraform:

resource "google_cloudfunctions_function" "my-function" {
  name        = "my-function"
  runtime     = "nodejs16"
  environment_variables = {
    GCP_PROJECT = var.project_id
  }
  #...
}
```

Body:
The answer depends on which runtime you are using.
If your using  Python 3.7 and Go 1.11 you are in luck. Use

process.env.GCP_PROJECT

If using any of the new runtimes, bad luck, either access the metadata server, or google suggests

Note: If your function/app requires one of the environment variables from
an older runtime, you can set the variable when deploying your
function. For example:

gcloud functions deploy envVarMemory \
--runtime nodejs10 \
--set-env-vars FUNCTION_MEMORY_MB=2Gi \
--memory 2Gi \
--trigger-http

If using terraform:

resource "google_cloudfunctions_function" "my-function" {
  name        = "my-function"
  runtime     = "nodejs16"
  environment_variables = {
    GCP_PROJECT = var.project_id
  }
  #...
}


问:
Mongoose update/insert value into array of objects
So I have this data stored in a mongodb database:

```<code>{
    _id: 'string',
    email: 'string',
    purchases: [
        { name: 'item 1', cost: 45, quantity: 3 },
        { name: 'item 2', cost: 62, quantity: 2 },
        { name: 'item 3', cost: 14, quantity: 7 },
    ]
}
</code>```

What I am trying to do is search for the user id (._id) and the item in the purchases array by the item name, so for item 1:

```<code>{ _id: req.body._id, purchases: { $elemMatch: { name: 'Item 1' }}}
</code>```

This query works fine. However the behavior I need is if the item exists, modify the quantity value to reset to one. If the item doesn't exist, i.e. its a new item, I want to insert a new item object.

I thought that .findOneAndReplace would work for this, so my code is:

```<code>    User.findOneAndReplace(
        { _id: req.body._id, purchases: { $elemMatch: { name: 'Item 1' }}},
        { $push: { purchases: { name: req.body.name, cost: req.body.cost, quantity: 1 }}},
        {
            upsert: true
        }
    ).then((result) => {
        res.status(200).json({
            message: 'Added score :D'
        })
    }).catch((error) => {
        res.status(400).json({
            message: 'Failed to add score...' + error
        })
    })
</code>```

but this obviously doesn't work. I can insert a new value into the purchases array but I cant update a current result if it exists.

答:
What you are doing is actually not a good way to handle documents.

A better way to handle your problem is to create a different model for purchases.

```<code>const purchases = mongoose.Schema({
      name: String,
      cost: Number,
      quantity: Number,
      user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
})
</code>```

Instead of adding purchases to the User model, you will create a new entry under purchases.

To update purchases, you can just update each purchase document directly.

If you want to retrieve all purchases for a user, you can simply

```<code> Purchases.find({ user: user._id })
</code>```

To see if item exist.

```<code> Purchases.find({ user: user._id, name: 'Item 1'});
</code>```

You can also find the purchases through the user model using $lookup.

```<code> Users.aggregate([
       {
          $match: { _id: user._id }
       },
       {
          $lookup: {
              from: 'purchases',
              localField: "_id",
              foreignField: "user",
              as: "purchases"
          }
       },
       {
          $project: {
               ....fields you want to return ....
          }
       }
 ])
</code>```

In the long run you will find this model of database more efficient and easier to up keep, and there's more pros than cons separating the documents into different collections.

Body:
So I have this data stored in a mongodb database:

{
    _id: 'string',
    email: 'string',
    purchases: [
        { name: 'item 1', cost: 45, quantity: 3 },
        { name: 'item 2', cost: 62, quantity: 2 },
        { name: 'item 3', cost: 14, quantity: 7 },
    ]
}

What I am trying to do is search for the user id (._id) and the item in the purchases array by the item name, so for item 1:

{ _id: req.body._id, purchases: { $elemMatch: { name: 'Item 1' }}}

This query works fine. However the behavior I need is if the item exists, modify the quantity value to reset to one. If the item doesn't exist, i.e. its a new item, I want to insert a new item object.

I thought that .findOneAndReplace would work for this, so my code is:

    User.findOneAndReplace(
        { _id: req.body._id, purchases: { $elemMatch: { name: 'Item 1' }}},
        { $push: { purchases: { name: req.body.name, cost: req.body.cost, quantity: 1 }}},
        {
            upsert: true
        }
    ).then((result) => {
        res.status(200).json({
            message: 'Added score :D'
        })
    }).catch((error) => {
        res.status(400).json({
            message: 'Failed to add score...' + error
        })
    })

but this obviously doesn't work. I can insert a new value into the purchases array but I cant update a current result if it exists.

Body:
What you are doing is actually not a good way to handle documents.

A better way to handle your problem is to create a different model for purchases.

const purchases = mongoose.Schema({
      name: String,
      cost: Number,
      quantity: Number,
      user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
})

Instead of adding purchases to the User model, you will create a new entry under purchases.

To update purchases, you can just update each purchase document directly.

If you want to retrieve all purchases for a user, you can simply

 Purchases.find({ user: user._id })

To see if item exist.

 Purchases.find({ user: user._id, name: 'Item 1'});

You can also find the purchases through the user model using $lookup.

 Users.aggregate([
       {
          $match: { _id: user._id }
       },
       {
          $lookup: {
              from: 'purchases',
              localField: "_id",
              foreignField: "user",
              as: "purchases"
          }
       },
       {
          $project: {
               ....fields you want to return ....
          }
       }
 ])

In the long run you will find this model of database more efficient and easier to up keep, and there's more pros than cons separating the documents into different collections.


问:
Rails 2.3.5 Mime::Type in environment.rb works for server but not console
To support a KML mime type I have this line in my environment.rb:

```<code>Mime::Type.register 'application/vnd.google-earth.kml+xml', :kml
</code>```

It seems to work just fine on the server. I can use .kml as a format in respond_to blocks and everything is OK. Without that line I cannot.

However, when I try to run the console now on the same environment I get an error on that line:

```<code>NameError: uninitialized constant Mime
</code>```

I did restart the server after modifying environment.rb.

I'm confused as to why the difference between the server and console and what I'm doing wrong with the config.

答: I discovered this works for both the server and console if it is added to  /initializers/mime_types.rb instead of environment.rb. I do not know why the console/server discrepancy existed but it seems this is the intended place anyway.</p>

Body:
To support a KML mime type I have this line in my environment.rb:

Mime::Type.register 'application/vnd.google-earth.kml+xml', :kml

It seems to work just fine on the server. I can use .kml as a format in respond_to blocks and everything is OK. Without that line I cannot.

However, when I try to run the console now on the same environment I get an error on that line:

NameError: uninitialized constant Mime

I did restart the server after modifying environment.rb.

I'm confused as to why the difference between the server and console and what I'm doing wrong with the config.


问:
Module '"@angular/fire/auth"' has no exported member 'AngularFireAuth'.ts(2305)
I am having this error with an import

import { AngularFireAuth } from "@angular/fire/auth"; Error-. Module '"@angular/fire/auth"' has no exported member 'AngularFireAuth'.ts(2305)
```
<p>And if import it from <code>@angular/fire/compat/auth</code> then getting bellow error in terminal:</p>
<pre class="lang-js prettyprint-override"><code>Time: 213ms

ERROR in node_modules/@firebase/firestore/dist/index.d.ts:26:28 - error TS1005: ']' expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                              ~~
node_modules/@firebase/firestore/dist/index.d.ts:26:47 - error TS1005: ';' expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                 ~
node_modules/@firebase/firestore/dist/index.d.ts:26:49 - error TS1109: Expression expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                   ~
node_modules/@firebase/firestore/dist/index.d.ts:26:50 - error TS1109: Expression expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                    ~
node_modules/@firebase/firestore/dist/index.d.ts:27:1 - error TS1128: Declaration or statement expected.

27 };
   ~

    ERROR in src/app/services/firebase.service.ts:2:10 - error TS2305: Module '"@angular/fire/compat"' has no exported member 'AngularFireAuth'.

    2 import { AngularFireAuth } from "@angular/fire/compat/";
               ~~~~~~~~~~~~~~~

Date: 2021-11-13T07:45:51.865Z - Hash: ff0e2da18163e6a524d5
5 unchanged chunks

Time: 330ms

ERROR in node_modules/@firebase/firestore/dist/index.d.ts:26:28 - error TS1005: ']' expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                              ~~
node_modules/@firebase/firestore/dist/index.d.ts:26:47 - error TS1005: ';' expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                 ~
node_modules/@firebase/firestore/dist/index.d.ts:26:49 - error TS1109: Expression expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                   ~
node_modules/@firebase/firestore/dist/index.d.ts:26:50 - error TS1109: Expression expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                    ~
node_modules/@firebase/firestore/dist/index.d.ts:27:1 - error TS1128: Declaration or statement expected.

27 };
   ~
node_modules/@angular/fire/compat/auth/auth.d.ts:13:55 - error TS1005: ',' expected.

13 export declare const USE_EMULATOR: InjectionToken<[url: string]>;
                                                         ~
node_modules/@angular/fire/compat/auth/auth.d.ts:13:63 - error TS1005: ',' expected.

13 export declare const USE_EMULATOR: InjectionToken<[url: string]>;
                                                                 ~
node_modules/@angular/fire/compat/auth/auth.d.ts:13:64 - error TS1134: Variable declaration expected.

13 export declare const USE_EMULATOR: InjectionToken<[url: string]>;
                                                                  ~
node_modules/@angular/fire/compat/auth/auth.d.ts:13:65 - error TS1109: Expression expected.

13 export declare const USE_EMULATOR: InjectionToken<[url: string]>;

</code>```

答:
Now I have following configuration in my project where I was facing the issue and Its working now.
package.json file>

```<code>       {
      "name": "something",
      "version": "0.0.0",
      "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "~9.1.13",
        "@angular/cdk": "^9.2.4",
        "@angular/common": "~9.1.13",
        "@angular/compiler": "~9.1.13",
        "@angular/core": "~9.1.13",
        "@angular/fire": "^6.1.5",
        "@angular/flex-layout": "^12.0.0-beta.35",
        "@angular/forms": "~9.1.13",
        "@angular/material": "^9.2.4",
        "@angular/platform-browser": "~9.1.13",
        "@angular/platform-browser-dynamic": "~9.1.13",
        "@angular/router": "~9.1.13",
        "@ngrx/effects": "^10.1.2",
        "@ngrx/store": "^10.1.2",
....
some other packages
....
        "@ngrx/store-devtools": "^10.1.2",
        "firebase": "^7.24.0",
        "hammerjs": "^2.0.8",
        "rxjs": "~6.5.4",
        "tslib": "^1.10.0",
        "zone.js": "~0.10.2"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~0.901.15",
        "@angular/cli": "~9.1.15",
        "@angular/compiler-cli": "~9.1.13",
        "@types/jasmine": "~3.5.0",
        "@types/jasminewd2": "~2.0.3",
        "@types/node": "^12.11.1",
        "codelyzer": "^5.1.2",
        "jasmine-core": "~3.5.0",
        "jasmine-spec-reporter": "~4.2.1",
        "karma": "~5.0.0",
        "karma-chrome-launcher": "~3.1.0",
        "karma-coverage-istanbul-reporter": "~2.1.0",
        "karma-jasmine": "~3.0.1",
        "karma-jasmine-html-reporter": "^1.4.2",
        "protractor": "~7.0.0",
        "ts-node": "~8.3.0",
        "tslint": "~6.1.0",
        "typescript": "~3.8.3"
      }
    }
</code>```

changing to "@angular/fire": "^6.1.5", and typescript version for project "typescript": "~3.8.3" and then deleting node_modules and fresh npm install worked for me.
Now I am able to import it without error as  import { AngularFireAuth } from '@angular/fire/auth';

Body:
I am having this error with an import

import { AngularFireAuth } from "@angular/fire/auth"; Error-. Module '"@angular/fire/auth"' has no exported member 'AngularFireAuth'.ts(2305)

And if import it from @angular/fire/compat/auth then getting bellow error in terminal:

Time: 213ms

ERROR in node_modules/@firebase/firestore/dist/index.d.ts:26:28 - error TS1005: ']' expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                              ~~
node_modules/@firebase/firestore/dist/index.d.ts:26:47 - error TS1005: ';' expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                 ~
node_modules/@firebase/firestore/dist/index.d.ts:26:49 - error TS1109: Expression expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                   ~
node_modules/@firebase/firestore/dist/index.d.ts:26:50 - error TS1109: Expression expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                    ~
node_modules/@firebase/firestore/dist/index.d.ts:27:1 - error TS1128: Declaration or statement expected.

27 };
   ~

    ERROR in src/app/services/firebase.service.ts:2:10 - error TS2305: Module '"@angular/fire/compat"' has no exported member 'AngularFireAuth'.

    2 import { AngularFireAuth } from "@angular/fire/compat/";
               ~~~~~~~~~~~~~~~

Date: 2021-11-13T07:45:51.865Z - Hash: ff0e2da18163e6a524d5
5 unchanged chunks

Time: 330ms

ERROR in node_modules/@firebase/firestore/dist/index.d.ts:26:28 - error TS1005: ']' expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                              ~~
node_modules/@firebase/firestore/dist/index.d.ts:26:47 - error TS1005: ';' expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                 ~
node_modules/@firebase/firestore/dist/index.d.ts:26:49 - error TS1109: Expression expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                   ~
node_modules/@firebase/firestore/dist/index.d.ts:26:50 - error TS1109: Expression expected.

26     [K in keyof T & string as `${Prefix}.${K}`]+?: T[K];
                                                    ~
node_modules/@firebase/firestore/dist/index.d.ts:27:1 - error TS1128: Declaration or statement expected.

27 };
   ~
node_modules/@angular/fire/compat/auth/auth.d.ts:13:55 - error TS1005: ',' expected.

13 export declare const USE_EMULATOR: InjectionToken<[url: string]>;
                                                         ~
node_modules/@angular/fire/compat/auth/auth.d.ts:13:63 - error TS1005: ',' expected.

13 export declare const USE_EMULATOR: InjectionToken<[url: string]>;
                                                                 ~
node_modules/@angular/fire/compat/auth/auth.d.ts:13:64 - error TS1134: Variable declaration expected.

13 export declare const USE_EMULATOR: InjectionToken<[url: string]>;
                                                                  ~
node_modules/@angular/fire/compat/auth/auth.d.ts:13:65 - error TS1109: Expression expected.

13 export declare const USE_EMULATOR: InjectionToken<[url: string]>;

Body:
Now I have following configuration in my project where I was facing the issue and Its working now.
package.json file>

       {
      "name": "something",
      "version": "0.0.0",
      "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "~9.1.13",
        "@angular/cdk": "^9.2.4",
        "@angular/common": "~9.1.13",
        "@angular/compiler": "~9.1.13",
        "@angular/core": "~9.1.13",
        "@angular/fire": "^6.1.5",
        "@angular/flex-layout": "^12.0.0-beta.35",
        "@angular/forms": "~9.1.13",
        "@angular/material": "^9.2.4",
        "@angular/platform-browser": "~9.1.13",
        "@angular/platform-browser-dynamic": "~9.1.13",
        "@angular/router": "~9.1.13",
        "@ngrx/effects": "^10.1.2",
        "@ngrx/store": "^10.1.2",
....
some other packages
....
        "@ngrx/store-devtools": "^10.1.2",
        "firebase": "^7.24.0",
        "hammerjs": "^2.0.8",
        "rxjs": "~6.5.4",
        "tslib": "^1.10.0",
        "zone.js": "~0.10.2"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~0.901.15",
        "@angular/cli": "~9.1.15",
        "@angular/compiler-cli": "~9.1.13",
        "@types/jasmine": "~3.5.0",
        "@types/jasminewd2": "~2.0.3",
        "@types/node": "^12.11.1",
        "codelyzer": "^5.1.2",
        "jasmine-core": "~3.5.0",
        "jasmine-spec-reporter": "~4.2.1",
        "karma": "~5.0.0",
        "karma-chrome-launcher": "~3.1.0",
        "karma-coverage-istanbul-reporter": "~2.1.0",
        "karma-jasmine": "~3.0.1",
        "karma-jasmine-html-reporter": "^1.4.2",
        "protractor": "~7.0.0",
        "ts-node": "~8.3.0",
        "tslint": "~6.1.0",
        "typescript": "~3.8.3"
      }
    }

changing to "@angular/fire": "^6.1.5", and typescript version for project "typescript": "~3.8.3" and then deleting node_modules and fresh npm install worked for me.
Now I am able to import it without error as  import { AngularFireAuth } from '@angular/fire/auth';


问:
N random samples from an array in bigquery
is it possible to get n random samples from an array

e.g. a table has two columns, id STRING, and values ARRAY(STRING)

the resulting array new_values ARRAY(STRING) for each id would be of length N and consist of random values from the original values array ( i.e. values picked at N random offsets in the array)

答:
Consider below approach</p>
```<code>select *, array(
    select value from (
      select value, offset
      from t.values as value with offset
      order by rand()
      limit 5 -- replace 5 with value of your N
    )
    order by offset
  ) new_values
from your_table t
</code>```

Body:
Consider below approach

select *, array(
    select value from (
      select value, offset
      from t.values as value with offset
      order by rand()
      limit 5 -- replace 5 with value of your N
    )
    order by offset
  ) new_values
from your_table t


问:
Error, "The timestamp service is not available." when using codesign on Mac OS X 10.8
I'm signing an app bundle using an Apple Developer ID certificate. I need to sign using the  the command line tool since our build is automated and runs from our toolchain. 90% of the time it works fine with this command:

```<code>ws5:bin nick$ codesign -fs "Developer ID Application: <my name here>" MyApp.app
ws5:bin nick$ spctl --assess MyApp.app
ws5:bin nick$
</code>```

Note: MyApp.app is not my real application name, and <my name here> is not the actual value.

So, maybe 1 in 10 times it intermittently fails with this error:

```<code>MyApp.app: The timestamp service is not available.
</code>```

I've verified the .app gets through the quarantine mechanism with spctl --assess and by zipping it and downloading the signed file. I know that Apple doesn't officially recommend using codesign for developer ID certificates (according to a WWDC video) but we need to use it for automation and because our app is a strange combination of gcc and Qt build output.

Is the best strategy around this error to just retry until it works again? That's all I can think to do.

答:
Each time you try to do code signing it will interact with time.apple.com server.
Sometime we find issue in connection with apple time server and code signing fails.

Two things we can do when we face this issue -

ping time.apple.com

this will help us to check time server is working properly without any glitch.

If above step won't work, last option is to reboot the machine.

This is the saver step and it always work because it restart the local apple time client.

If you don't want to restart the system, then you can find how to restart local apple time client.
OR

On one terminal - run ping time.apple.com and on 2nd terminal tab run codesign command continuously, this always works. And don't forget to run security unlock-keychain login.keychain before codesigning command.

Body:
I'm signing an app bundle using an Apple Developer ID certificate. I need to sign using the  the command line tool since our build is automated and runs from our toolchain. 90% of the time it works fine with this command:

ws5:bin nick$ codesign -fs "Developer ID Application: <my name here>" MyApp.app
ws5:bin nick$ spctl --assess MyApp.app
ws5:bin nick$

Note: MyApp.app is not my real application name, and <my name here> is not the actual value.

So, maybe 1 in 10 times it intermittently fails with this error:

MyApp.app: The timestamp service is not available.

I've verified the .app gets through the quarantine mechanism with spctl --assess and by zipping it and downloading the signed file. I know that Apple doesn't officially recommend using codesign for developer ID certificates (according to a WWDC video) but we need to use it for automation and because our app is a strange combination of gcc and Qt build output.

Is the best strategy around this error to just retry until it works again? That's all I can think to do.


问:
Type '({ articles }: Props) => JSX.Element' is not assignable to type 'NextPage<{}, {}>'
I'm just getting into React.js and Next.js after having used Vue.js before. I'm getting a strange typescript error, but weirdly it actually compiles despite VS Code complaining at me as though it wouldn't compile.

I'm trying to pass an array of Article into my home component as a prop.

Here the relevant code:

```<code>interface Article {
  userId: number;
  id: number;
  title: string;
  body: string;
}

interface Props {
  articles: Article | Article[];
}

const Home: NextPage = ({ articles }: Props) => {
  return (
    <div>
      {/* some stuff */}
    </div>
  );
};
</code>```

Home is underlined in red and when I hover over gives the error:

```<code>const Home: NextPage<{}, {}>
Type '({ articles }: Props) => JSX.Element' is not assignable to type 'NextPage<{}, {}>'.
  Type '({ articles }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
    Type '({ articles }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<{}>'.
      Types of parameters '__0' and 'props' are incompatible.
        Property 'articles' is missing in type '{ children?: ReactNode; }' but required in type 'Props'.
</code>```

Any help or insights as to what could be going on here would be greatly appreciated.

答:
you can write like this :

```<code>import React , {FC} from 'react';

interface Article {
  userId: number;
  id: number;
  title: string;
  body: string;
}

interface HomeProps {
  articles: Article[];
}

const Home : FC<HomeProps> = ({articles}) => {

console.log('articles: ', articles)

  return (
    <div>
      {/* some stuff */}
    </div>
  );
};

</code>```

and in the container :

```<code>
const myArticles = [
 {
   userId: 1,
   id: 1,
   title: 'my title',
   body: 'my body',
 }
]
...
return (
 <Home articles={myArticles}>
)
</code>```

Body:
I'm just getting into React.js and Next.js after having used Vue.js before. I'm getting a strange typescript error, but weirdly it actually compiles despite VS Code complaining at me as though it wouldn't compile.

I'm trying to pass an array of Article into my home component as a prop.

Here the relevant code:

interface Article {
  userId: number;
  id: number;
  title: string;
  body: string;
}

interface Props {
  articles: Article | Article[];
}

const Home: NextPage = ({ articles }: Props) => {
  return (

      {/* some stuff */}

  );
};

Home is underlined in red and when I hover over gives the error:

const Home: NextPage<{}, {}>
Type '({ articles }: Props) => JSX.Element' is not assignable to type 'NextPage<{}, {}>'.
  Type '({ articles }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
    Type '({ articles }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<{}>'.
      Types of parameters '__0' and 'props' are incompatible.
        Property 'articles' is missing in type '{ children?: ReactNode; }' but required in type 'Props'.

Any help or insights as to what could be going on here would be greatly appreciated.

Body:
you can write like this :

import React , {FC} from 'react';

interface Article {
  userId: number;
  id: number;
  title: string;
  body: string;
}

interface HomeProps {
  articles: Article[];
}

const Home : FC<HomeProps> = ({articles}) => {

console.log('articles: ', articles)

  return (
    <div>
      {/* some stuff */}
    </div>
  );
};

and in the container :

const myArticles = [
 {
   userId: 1,
   id: 1,
   title: 'my title',
   body: 'my body',
 }
]
...
return (
 <Home articles={myArticles}>
)


问:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
My Swift program is crashing with EXC_BAD_INSTRUCTION and one of the following similar errors. What does this error mean, and how do I fix it?

Fatal error: Unexpectedly found nil while unwrapping an Optional value

or

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

This post is intended to collect answers to "unexpectedly found nil" issues, so that they are not scattered and hard to find. Feel free to add your own answer or edit the existing wiki answer.

答: This is because you are trying to use a value which can possible be nil, but you decided you don't want to have to check it, but instead assume its set when you uses it and define it as !, there are different philosophies on use of variable set as force unwrap, some people are against there use at all, I personal think they are ok for things that will crash all the time and are simple to reason about, usually references to resource, like outlets to xib files, or uses of images with you app that are part of your assets, if these are not set up properly, you app is going to crash straight away, for a very obvious reason, you can get into difficult when the order of objects being created can be uncertain, and trying to reason solutions to this can be difficult, it usually means a bad design as even it you make them optional, calls to you optional variable may not ever be executed, some projects can demand use of force unwraps for security reasons, things like banking apps, because they want the app to crash rather then continue to work in an unplanned way.</p>


问:
Not Change URL in selenium chrome python
when I use get function in chrome selenium for first time it's ok but for second time get function doesn't look like update
example

```<code>from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("--start-maximized")  ## For Maximam Windows##
options.add_experimental_option("prefs",
{"profile.default_content_setting_values.notifications": 2})
options.add_argument("--disable-infobars")

def fun1():
  brows.get("https://www.facebook.com/")
  print(brows.current_url)
</code>```

when call fun2 the URL doesn't change

```<code>def fun2():
  brows.get("https://www.google.com/")
  print(brows.current_url)
</code>```

when run function output of print in both function is https://www.facebook.com/

can anyone say what's problem?

答:
I tried this

```<code>from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("--start-maximized")  ## For Maximam Windows##
options.add_experimental_option("prefs",
{"profile.default_content_setting_values.notifications": 2})
options.add_argument("--disable-infobars")

def fun1():
  driver.get("https://www.facebook.com/")
  print(driver.current_url)

def fun2():
  driver.get("https://www.google.com/")
  print(driver.current_url)

fun1()
fun2()
</code>```

Results :

Body:
when I use get function in chrome selenium for first time it's ok but for second time get function doesn't look like update
example

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("--start-maximized")  ## For Maximam Windows##
options.add_experimental_option("prefs",
{"profile.default_content_setting_values.notifications": 2})
options.add_argument("--disable-infobars")

def fun1():
  brows.get("https://www.facebook.com/")
  print(brows.current_url)

when call fun2 the URL doesn't change

def fun2():
  brows.get("https://www.google.com/")
  print(brows.current_url)

when run function output of print in both function is https://www.facebook.com/

can anyone say what's problem?

Body:
I tried this

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("--start-maximized")  ## For Maximam Windows##
options.add_experimental_option("prefs",
{"profile.default_content_setting_values.notifications": 2})
options.add_argument("--disable-infobars")

def fun1():
  driver.get("https://www.facebook.com/")
  print(driver.current_url)

def fun2():
  driver.get("https://www.google.com/")
  print(driver.current_url)

fun1()
fun2()

Results :


问:
jQuery Animate Question
I have a very basic function which I am using jQuery to slide some content either out (from left to right) or back in (from right to left). The code below works, however, what I am trying to do now is include the "+" at the end of my "overDiv", and make it so that it will always show.

To paint a more lucid picture, right now if you paste that code into your editor and include google's jQuery, you will see that clicking the "+" eliminates the "overDiv" block completely. However, what I want to do is place the "+" at the end of the "overDiv" block so that when the text 'disappears' off of the page, the + will always remain. Hopefully that makes some sense?

Thanks in advance.

```<code><body>

<script language="javascript" type="text/javascript">
$(function() {
    // when we click on the a-href id 'togglen', we move the overDiv to the left.
$('#togglen').click(function() {
    // simple animation
    $('#overDiv').animate({
      left: parseInt($('#overDiv').css('left'),10) == 0 ? -$('#overDiv').outerWidth() : 0
    });
  }); //
});

</script>
<div><a href="#" id="togglen">+</a></div>
<div style="background-color:#CCC; width:180px;  position:absolute; left:0; overflow:hidden; float:left;" id="overDiv">Lorem ipsum.</div>
</code>```

答:
See here: http://jsfiddle.net/yVReu/

You need to also position your "+" element.

Title: jQuery Animate Question

Body:
I have a very basic function which I am using jQuery to slide some content either out (from left to right) or back in (from right to left). The code below works, however, what I am trying to do now is include the "+" at the end of my "overDiv", and make it so that it will always show.

To paint a more lucid picture, right now if you paste that code into your editor and include google's jQuery, you will see that clicking the "+" eliminates the "overDiv" block completely. However, what I want to do is place the "+" at the end of the "overDiv" block so that when the text 'disappears' off of the page, the + will always remain. Hopefully that makes some sense?

Thanks in advance.

+

Lorem ipsum.


问:
How to install xclip on Centos 8?
I recently started using Centos 8 on my Workstation and there is no xsel or xclip

Is there something wrong or is it on purpose, that xclip is not available?

Here is the output of dnf repolist, maybe I'm missing some must-have repo?

```<code>repo id                                                                             repo name                                                                                status
AppStream                                                                           CentOS-8 - AppStream                                                                                5.089
Atom                                                                                Atom Editor                                                                                142
BaseOS                                                                              CentOS-8 - Base                                                                                2.843
amdgpu-pro-local                                                                    AMD amdgpu Pro local repository                                                                                70
docker-ce-stable                                                                    Docker CE Stable - x86_64                                                                                57
*epel                                                                               Extra Packages for Enterprise Linux 8 - x86_64                                                                          3.643
extras                                                                              CentOS-8 - Extras                                                                                3
virtualbox                                                                          Oracle Linux / RHEL / CentOS-8 / x86_64 - VirtualBox                                                                        4

</code>```

Title: How to install xclip on Centos 8?

Body:
I recently started using Centos 8 on my Workstation and there is no xsel or xclip

Is there something wrong or is it on purpose, that xclip is not available?

Here is the output of dnf repolist, maybe I'm missing some must-have repo?

repo id                                                                             repo name                                                                                status
AppStream                                                                           CentOS-8 - AppStream                                                                                5.089
Atom                                                                                Atom Editor                                                                                142
BaseOS                                                                              CentOS-8 - Base                                                                                2.843
amdgpu-pro-local                                                                    AMD amdgpu Pro local repository                                                                                70
docker-ce-stable                                                                    Docker CE Stable - x86_64                                                                                57
*epel                                                                               Extra Packages for Enterprise Linux 8 - x86_64                                                                          3.643
extras                                                                              CentOS-8 - Extras                                                                                3
virtualbox                                                                          Oracle Linux / RHEL / CentOS-8 / x86_64 - VirtualBox                                                                        4

Body:
First Enable EPEL (Extra Packages for Enterprise Linux) repo on CentOS 8 to install extra packages such xclip.

Step 1: Install epel repo

# yum install epel-release.noarch
             or
# dnf install epel-release

Step 2: Install xclip from the EPEL repo

# dnf install xclip
Last metadata expiration check: 0:06:09 ago on Mon 07 Feb 2022 10:39:39 AM IST.
Dependencies resolved.
=============================================================================================================================================================
 Package                             Architecture                         Version                                   Repository                          Size
=============================================================================================================================================================
Installing:
 xclip                               x86_64                               0.13-8.el8                                epel                                35 k

Transaction Summary
=============================================================================================================================================================
Install  1 Package


问:
pyspark extracting a string using python
Spark dataframe which has column emailID  : ram.shyam.78uy@testing.com. i would like to extract the string between "." and "@"  i.e 78uy and store it in column.
tried

```<code>split_for_alias = split(rs_csv['emailID'],'[.]')
rs_csv_alias= rs_csv.withColumn('alias',split_for_alias.getItem(size(split_for_alias) -2))
</code>```

Its adding 78uy@testing as alias. Another column can be added and chop off the extra values. But is it possible to do in single statement.

答:
Extract the alphanumeric immediately to the left of special character . and immediately followed by special character @

DataFrame

```<code>data= [
      (1,"am.shyam.78uy@testing.com"),
      (2, "j.k.kilo@jom.com")
    ]

df=spark.createDataFrame(data, ("id",'emailID'))

df.show()

+---+--------------------+
| id|             emailID|
+---+--------------------+
|  1|am.shyam.78uy@tes...|
|  2|    j.k.kilo@jom.com|
+---+--------------------+
</code>```

Code

```<code>df.withColumn('name', regexp_extract('emailID', '(?<=\.)(\w+)(?=\@)',1)).show()
</code>```

outcome

```<code>+---+--------------------+----+
| id|             emailID|name|
+---+--------------------+----+
|  1|am.shyam.78uy@tes...|78uy|
|  2|    j.k.kilo@jom.com|kilo|
+---+--------------------+----+
</code>```

Body:
Spark dataframe which has column emailID  : ram.shyam.78uy@testing.com. i would like to extract the string between "." and "@"  i.e 78uy and store it in column.
tried

split_for_alias = split(rs_csv['emailID'],'[.]')
rs_csv_alias= rs_csv.withColumn('alias',split_for_alias.getItem(size(split_for_alias) -2))

Its adding 78uy@testing as alias. Another column can be added and chop off the extra values. But is it possible to do in single statement.

Body:
Extract the alphanumeric immediately to the left of special character . and immediately followed by special character @

DataFrame

data= [
      (1,"am.shyam.78uy@testing.com"),
      (2, "j.k.kilo@jom.com")
    ]

df=spark.createDataFrame(data, ("id",'emailID'))

df.show()

+---+--------------------+
| id|             emailID|
+---+--------------------+
|  1|am.shyam.78uy@tes...|
|  2|    j.k.kilo@jom.com|
+---+--------------------+

Code

df.withColumn('name', regexp_extract('emailID', '(?<=\.)(\w+)(?=\@)',1)).show()

outcome

+---+--------------------+----+
| id|             emailID|name|
+---+--------------------+----+
|  1|am.shyam.78uy@tes...|78uy|
|  2|    j.k.kilo@jom.com|kilo|
+---+--------------------+----+


问:
how to add font family into in main.dart flutter
I'm new to flutter and struggling to add font family in my code..already updated my pubspec.yamal with OpenSans fonts.. now how to add font family into this main. dart material app widget??

fontFamily: "OpenSans",

```<code>Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: theme.copyWith(
        colorScheme: theme.colorScheme.copyWith(primary: Color(0xff075e54),secondary: Color(0xff128C7E),

        ),
      ),
      home: Homescreen(key: null),
    );
  }
}
</code>```

答:
Create a simple file for the theme like the one I created theme_util.dart and use it as follows.

```<code>return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: appTheme,
      home: Homescreen(key: null),
 );
</code>```

theme_util.dart

```<code>ThemeData appTheme = ThemeData(
  backgroundColor: appColor.white,
  scaffoldBackgroundColor: appColor.white,
  appBarTheme: AppBarTheme(
      color: appColor.white,
      brightness: Brightness.light,
      textTheme: TextTheme().copyWith(headline6: titleStyle),
      iconTheme: IconThemeData(color: appColor.primaryColor)),
  fontFamily: 'Opensans',
  primaryColor: appColor.primaryColor,
  primaryColorDark: appColor.primaryDarkColor,
  primaryColorLight: appColor.primaryLight,
  accentColor: appColor.accentColor,
  brightness: Brightness.light,
  //primarySwatch: appColor.blue,
  visualDensity: VisualDensity.adaptivePlatformDensity,
  buttonTheme: ButtonThemeData(buttonColor: appColor.primaryColor),
);
</code>```

Body:
I'm new to flutter and struggling to add font family in my code..already updated my pubspec.yamal with OpenSans fonts.. now how to add font family into this main. dart material app widget??

fontFamily: "OpenSans",

Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: theme.copyWith(
        colorScheme: theme.colorScheme.copyWith(primary: Color(0xff075e54),secondary: Color(0xff128C7E),

        ),
      ),
      home: Homescreen(key: null),
    );
  }
}

Body:
Create a simple file for the theme like the one I created theme_util.dart and use it as follows.

return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: appTheme,
      home: Homescreen(key: null),
 );

theme_util.dart

ThemeData appTheme = ThemeData(
  backgroundColor: appColor.white,
  scaffoldBackgroundColor: appColor.white,
  appBarTheme: AppBarTheme(
      color: appColor.white,
      brightness: Brightness.light,
      textTheme: TextTheme().copyWith(headline6: titleStyle),
      iconTheme: IconThemeData(color: appColor.primaryColor)),
  fontFamily: 'Opensans',
  primaryColor: appColor.primaryColor,
  primaryColorDark: appColor.primaryDarkColor,
  primaryColorLight: appColor.primaryLight,
  accentColor: appColor.accentColor,
  brightness: Brightness.light,
  //primarySwatch: appColor.blue,
  visualDensity: VisualDensity.adaptivePlatformDensity,
  buttonTheme: ButtonThemeData(buttonColor: appColor.primaryColor),
);


问:
How can I initialize an std::array of a class without a default constructor?
Let's say I have a class without a default constructor called Foo.

If I were using an std::vector, I could do this:

```<code>std::vector<Foo> vec(100, Foo(5));
</code>```

This would create a vector of 100 elements, each with value Foo(5).

How do I do the same with std::array<Foo, 100>?

I obviously do not want to list out Foo(5) explicitly 100 times in an initializer list. And yet I cannot wait till after the array is constructed to initialize it, since the lack of default constructor will produce a compiler error.

Bonus points for a solution that allows me to avoid the copy constructor as well, by supplying explicit constructor arguments similar to "placement new" or emplace functions.

答:
std::array is just a thin wrapper around a fixed array. It has no repeat-insert logic, like std::vector does. Since Foo does not have a default constructor, the only way to initialize an instance of std::array<Foo, N> is to use aggregate initialization with N number of values specified (sorry, I know you don't want to to do this), eg:

```<code>std::array<Foo, 100> arr{5, 5, 5, ...}; // N times...
</code>```

Otherwise, you will have to create a byte array of sufficient size and then use placement-new in a loop, eg:

```<code>std::aligned_storage_t<sizeof(Foo), alignof(Foo)> arr[100];
for(int i = 0; i < 100; ++i) {
   new (&arr[i]) Foo(5);
}
...
// use static_cast<Foo*>(&arr[index]) to access each object as needed...
...
for(int i = 0; i < 100; ++i) {
    // when using placement-new, you must call each object's destructor explicitly...
    static_cast<Foo*>(&arr[i])->~Foo();
}

</code>```

Body:
Let's say I have a class without a default constructor called Foo.

If I were using an std::vector, I could do this:

std::vector<Foo> vec(100, Foo(5));

This would create a vector of 100 elements, each with value Foo(5).

How do I do the same with std::array<Foo, 100>?

I obviously do not want to list out Foo(5) explicitly 100 times in an initializer list. And yet I cannot wait till after the array is constructed to initialize it, since the lack of default constructor will produce a compiler error.

Bonus points for a solution that allows me to avoid the copy constructor as well, by supplying explicit constructor arguments similar to "placement new" or emplace functions.

Body:
std::array is just a thin wrapper around a fixed array. It has no repeat-insert logic, like std::vector does. Since Foo does not have a default constructor, the only way to initialize an instance of std::array<Foo, N> is to use aggregate initialization with N number of values specified (sorry, I know you don't want to to do this), eg:

std::array<Foo, 100> arr{5, 5, 5, ...}; // N times...

Otherwise, you will have to create a byte array of sufficient size and then use placement-new in a loop, eg:

std::aligned_storage_t<sizeof(Foo), alignof(Foo)> arr[100];
for(int i = 0; i < 100; ++i) {
   new (&arr[i]) Foo(5);
}
...
// use static_cast<Foo*>(&arr[index]) to access each object as needed...
...
for(int i = 0; i < 100; ++i) {
    // when using placement-new, you must call each object's destructor explicitly...
    static_cast<Foo*>(&arr[i])->~Foo();
}


问:
Javascript Image onError not working when updating image src on hover
I have created a table that contains a list of Magic the Gathering cards. When the user hovers over the card name it displays the cards image. These images are stored in a AWS S3 buckets.

There is a cost involved to loading those images from the S3 bucket so rather than loading 20-50 images when the page loads, what I have done is saved the Image URL in a custom attribute - url - for the image element and then when the user hovers over the card name it replaces src with url. The works as expected when the card image exists in the S3 bucket.

However this seems to have broken the onError attribute so now when there is not an image in the S3 bucket for a particular card the broken card symbol appear rather than the placeholder image.

function hover(e) { let url = e.nextSibling.firstChild.getAttribute('url'); e.nextSibling.firstChild.setAttribute('src', url); e.nextSibling.classList.remove("hidden"); }
function unhover(e) { e.nextSibling.classList.add("hidden");
```
<pre class="lang-html prettyprint-override"><code><span onmouseover="hover(this);" onmouseout="unhover(this);" class="group cursor-pointer font-semibold hover:text-primary">
  Card Name
</span>
<span id="large" class="hidden">
  <img id="large-image" class="..." src="" url=".../card_image.jpg" height="500" onError="this.onerror=null;this.src=\'/static/img/placeholder.png\';">
</span>
</code>```

How do I get the placeholder image to work when there is not image found in the S3 bucket?

答:
An  element with an src="" attribute will fire the error event when appended to the document, simply don't set this attribute in your HTML to avoid your error handler firing before it's needed.

```

Body:
I have created a table that contains a list of Magic the Gathering cards. When the user hovers over the card name it displays the cards image. These images are stored in a AWS S3 buckets.

There is a cost involved to loading those images from the S3 bucket so rather than loading 20-50 images when the page loads, what I have done is saved the Image URL in a custom attribute - url - for the image element and then when the user hovers over the card name it replaces src with url. The works as expected when the card image exists in the S3 bucket.

However this seems to have broken the onError attribute so now when there is not an image in the S3 bucket for a particular card the broken card symbol appear rather than the placeholder image.

function hover(e) { let url = e.nextSibling.firstChild.getAttribute('url'); e.nextSibling.firstChild.setAttribute('src', url); e.nextSibling.classList.remove("hidden"); }
function unhover(e) { e.nextSibling.classList.add("hidden");

  Card Name

How do I get the placeholder image to work when there is not image found in the S3 bucket?

Body:
An <img> element with an src="" attribute will fire the error event when appended to the document, simply don't set this attribute in your HTML to avoid your error handler firing before it's needed.

<img onerror="alert('fired')" src="">
<img onerror="alert('will not fire')">


答:
With copy constructor, something along these lines:

```<code>template <typename T, size_t... Is>
std::array<T, sizeof...(Is)> MakeArrayHelper(
    const T& val, std::index_sequence<Is...>) {
  return {(static_cast<void>(Is), val) ...};
}

template <typename T, size_t N>
std::array<T, N> MakeArray(const T& val) {
  return MakeArrayHelper<T>(val, std::make_index_sequence<N>{});
}

std::array<Foo, 100> arr = MakeArray<Foo, 100>(Foo(5));
</code>```

Actually, this can be done without copy constructor after all. This solution relies heavily on C++17's mandatory copy elision.

```<code>template <typename T, size_t... Is, typename... Args>
std::array<T, sizeof...(Is)> MakeArrayHelper(
    std::index_sequence<Is...>, Args&&... args) {
  return {(static_cast<void>(Is), T{std::forward<Args>(args)...}) ...};
}

template <typename T, size_t N, typename... Args>
std::array<T, N> MakeArray(Args&&... args) {
  return MakeArrayHelper<T>(std::make_index_sequence<N>{},
                            std::forward<Args>(args)...);
}
</code>```

Demo

Title: How can I initialize an std::array of a class without a default constructor?

Body:
With copy constructor, something along these lines:

template <typename T, size_t... Is>
std::array<T, sizeof...(Is)> MakeArrayHelper(
    const T& val, std::index_sequence<Is...>) {
  return {(static_cast<void>(Is), val) ...};
}

template <typename T, size_t N>
std::array<T, N> MakeArray(const T& val) {
  return MakeArrayHelper<T>(val, std::make_index_sequence<N>{});
}

std::array<Foo, 100> arr = MakeArray<Foo, 100>(Foo(5));

Actually, this can be done without copy constructor after all. This solution relies heavily on C++17's mandatory copy elision.

template <typename T, size_t... Is, typename... Args>
std::array<T, sizeof...(Is)> MakeArrayHelper(
    std::index_sequence<Is...>, Args&&... args) {
  return {(static_cast<void>(Is), T{std::forward<Args>(args)...}) ...};
}

template <typename T, size_t N, typename... Args>
std::array<T, N> MakeArray(Args&&... args) {
  return MakeArrayHelper<T>(std::make_index_sequence<N>{},
                            std::forward<Args>(args)...);
}

Demo


问:
How to return a value from Firebase to a react component?
I am trying to read a value from RealtimeDatabase on Firebase and render it in an element, but it keeps returning undefined. I have the following code:

```<code>const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        return snapshot.val().name;
    })
}

const StudentName = (studentId) => ( <p>{getStudentName(studentId)}</p> )
</code>```

I know it's nothing wrong with the database itself or the value I'm finding, because if I do:

```<code>const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        console.log(snapshot.val().name);
        return "Test";
    })
}
</code>```

I still see a correct name from my database outputted to console as expected, yet "Test" is not returned to the element. However, if I do it like this:

```<code>const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        console.log(snapshot.val().name);
    })
    return "Test";
}
</code>```

then "Test" is returned to the
 element and displayed. I'm very confused, as I don't understand how my console.log() can be reached inside the function but a 'return' statement right after it will not return.

New to React and Firebase, please help! Thank you.

EDIT: I'm sure it's self-explanatory, but you can assume a simple database in the form:

```<code>{ "students": [
    "0": { "name": "David" },
    "1": { "name": "Sally" } ]}
</code>```

If 'studentId' is 0 then 'console.log(snapshot.val().name)' successfully outputs 'David', but 'David' will not return to the
 element.

答:
I'm not sure where you are consuming getStudentName, but your current code makes attaches a real-time listener to that database location. Each time the data at that location updates, your callback function gets invoked. Because of that, returning a value from such a function doesn't make much sense.

If you instead meant to fetch the name from the database just once, you can use the once() method, which returns a Promise containing the value you are looking for.

As another small optimization, if you only need the student's name, consider fetching /students/{studentId}/name instead.

```<code>const getStudentName = (studentId) => {
    return firebase.database()
      .ref("students")
      .child(studentId)
      .child("name")
      .once("value")
      .then(nameSnapshot => nameSnapshot.val());
}
</code>```

With the above code, getStudentName(studentId) now returns a Promise<string | null>, where null would be returned when that student doesn't exist.

```<code>getStudentName(studentId)
  .then(studentName => { /* ... do something ... */ })
  .catch(err => { /* ... handle errors ... */ })
</code>```

If instead you were filling a <Student> component, continuing to use the on snapshot listener may be the better choice:

```<code>const Student = (props) => {
  const [studentInfo, setStudentInfo] = useState({ status: "loading", data: null, error: null });

  useEffect(() => {
    // build reference
    const studentDataRef = firebase.database()
      .ref("students")
      .child(props.studentId)
      .child("name");

    // attach listener
    const listener = studentDataRef.on(
      'value',
      (snapshot) => {
        setStudentInfo({
          status: "ready",
          data: snapshot.val(),
          error: null
        });
      },
      (error) => {
        setStudentInfo({
          status: "error",
          data: null,
          error
        });
      }
    );

    // detach listener in unsubscribe callback
    return () => studentDataRef.off(listener);
  }, [props.studentId]); // <- run above code whenever props.studentId changes

  // handle the different states while the data is loading
  switch (studentInfo.status) {
    case "loading":
      return null; // hides component, could also show a placeholder/spinner
    case "error":
      return (
        <div class="error">
          Failed to retrieve data: {studentInfo.error.message}
        </div>
      );
  }

  // render data using studentInfo.data
  return (
    <div id={"student-" + props.studentId}>
      <img src={studentInfo.data.image} />
      <span>{studentInfo.data.name}</span>
    </div>
  );
}
</code>```

Because of how often you might end up using that above useState/useEffect combo, you could rewrite it into your own useDatabaseData hook.

Body:
I am trying to read a value from RealtimeDatabase on Firebase and render it in an element, but it keeps returning undefined. I have the following code:

const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        return snapshot.val().name;
    })
}

const StudentName = (studentId) => (
{getStudentName(studentId)}
 )

I know it's nothing wrong with the database itself or the value I'm finding, because if I do:

const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        console.log(snapshot.val().name);
        return "Test";
    })
}

I still see a correct name from my database outputted to console as expected, yet "Test" is not returned to the element. However, if I do it like this:

const getStudentName = (studentId) => {
    firebase.database().ref('students').child(studentId).on("value", (snapshot) => {
        console.log(snapshot.val().name);
    })
    return "Test";
}

then "Test" is returned to the
 element and displayed. I'm very confused, as I don't understand how my console.log() can be reached inside the function but a 'return' statement right after it will not return.

New to React and Firebase, please help! Thank you.

EDIT: I'm sure it's self-explanatory, but you can assume a simple database in the form:

{ "students": [
    "0": { "name": "David" },
    "1": { "name": "Sally" } ]}

If 'studentId' is 0 then 'console.log(snapshot.val().name)' successfully outputs 'David', but 'David' will not return to the
 element.

Body:
I'm not sure where you are consuming getStudentName, but your current code makes attaches a real-time listener to that database location. Each time the data at that location updates, your callback function gets invoked. Because of that, returning a value from such a function doesn't make much sense.

If you instead meant to fetch the name from the database just once, you can use the once() method, which returns a Promise containing the value you are looking for.

As another small optimization, if you only need the student's name, consider fetching /students/{studentId}/name instead.

const getStudentName = (studentId) => {
    return firebase.database()
      .ref("students")
      .child(studentId)
      .child("name")
      .once("value")
      .then(nameSnapshot => nameSnapshot.val());
}

With the above code, getStudentName(studentId) now returns a Promise<string | null>, where null would be returned when that student doesn't exist.

getStudentName(studentId)
  .then(studentName => { /* ... do something ... */ })
  .catch(err => { /* ... handle errors ... */ })

If instead you were filling a <Student> component, continuing to use the on snapshot listener may be the better choice:

const Student = (props) => {
  const [studentInfo, setStudentInfo] = useState({ status: "loading", data: null, error: null });

  useEffect(() => {
    // build reference
    const studentDataRef = firebase.database()
      .ref("students")
      .child(props.studentId)
      .child("name");

    // attach listener
    const listener = studentDataRef.on(
      'value',
      (snapshot) => {
        setStudentInfo({
          status: "ready",
          data: snapshot.val(),
          error: null
        });
      },
      (error) => {
        setStudentInfo({
          status: "error",
          data: null,
          error
        });
      }
    );

    // detach listener in unsubscribe callback
    return () => studentDataRef.off(listener);
  }, [props.studentId]); // <- run above code whenever props.studentId changes

  // handle the different states while the data is loading
  switch (studentInfo.status) {
    case "loading":
      return null; // hides component, could also show a placeholder/spinner
    case "error":
      return (
        <div class="error">
          Failed to retrieve data: {studentInfo.error.message}
        </div>
      );
  }

  // render data using studentInfo.data
  return (
    <div id={"student-" + props.studentId}>
      <img src={studentInfo.data.image} />
      <span>{studentInfo.data.name}</span>
    </div>
  );
}

Because of how often you might end up using that above useState/useEffect combo, you could rewrite it into your own useDatabaseData hook.


问:
Must coroutine return type be copy- or move-constructible if it is passed in co_await
In the following code example, the lambda coroutine g performs co_await f, where f is coroutine return type with deleted copy- and move- constructors:

```<code>#include <coroutine>

class task {
public:
    class task_promise {
    public:
        task get_return_object() { return task{handle_type::from_promise(*this)}; }
        auto initial_suspend() { return std::suspend_always{}; }
        auto final_suspend() noexcept { return std::suspend_never{}; }
        void return_void() {}
        void unhandled_exception() {}
    };
    using handle_type = std::coroutine_handle<task_promise>;
    handle_type handle;

    auto await_ready() { return false; }
    auto await_suspend(handle_type) { return handle; }
    void await_resume() { handle.resume(); }

    using promise_type = task_promise;
    task(handle_type h) : handle(h) {}
    task(const task&) = delete;
    task& operator=(const task&) = delete;
    task(task&&) = delete;
    task& operator=(task&&) = delete;
};

int main() {
    task f = []() -> task { co_return; }();
    task g = [&f]() -> task { co_await f; }();
    g.handle.resume();
}
</code>```

The code is accepted in MSVC, but not in GCC.

GCC 11.2 complains on the missing move-constructor:

```<code>error: use of deleted function 'task::task(task&&)'
</code>```

and GCC trunk - on the missing copy-constructor:

```<code>error: use of deleted function 'task::task(const task&)'
</code>```

Demo: https://gcc.godbolt.org/z/1c7fajqn8

Which compiler is right here?

P.S. There is a related question Why must the return type of a coroutine be move-constructible? but

the issue there was fixed in GCC 10.2, while the example from this question is still valid in GCC 11 and trunk;

this question asks about co_await requirements, while the other does not mention co_await at all;

the other question is about move-constructor only, while here the latest GCC demands copy-constructor.

答:
It is a compiler bug. Specifically,

If o would be a prvalue, the temporary materialization conversion (7.3.4) is applied -- co_await 7.6.2.3

Which basically means it should be constructed in place using RVO.

Body:
In the following code example, the lambda coroutine g performs co_await f, where f is coroutine return type with deleted copy- and move- constructors:

#include <coroutine>

class task {
public:
    class task_promise {
    public:
        task get_return_object() { return task{handle_type::from_promise(*this)}; }
        auto initial_suspend() { return std::suspend_always{}; }
        auto final_suspend() noexcept { return std::suspend_never{}; }
        void return_void() {}
        void unhandled_exception() {}
    };
    using handle_type = std::coroutine_handle<task_promise>;
    handle_type handle;

    auto await_ready() { return false; }
    auto await_suspend(handle_type) { return handle; }
    void await_resume() { handle.resume(); }

    using promise_type = task_promise;
    task(handle_type h) : handle(h) {}
    task(const task&) = delete;
    task& operator=(const task&) = delete;
    task(task&&) = delete;
    task& operator=(task&&) = delete;
};

int main() {
    task f = []() -> task { co_return; }();
    task g = [&f]() -> task { co_await f; }();
    g.handle.resume();
}

The code is accepted in MSVC, but not in GCC.

GCC 11.2 complains on the missing move-constructor:

error: use of deleted function 'task::task(task&&)'

and GCC trunk - on the missing copy-constructor:

error: use of deleted function 'task::task(const task&)'

Demo: https://gcc.godbolt.org/z/1c7fajqn8

Which compiler is right here?

P.S. There is a related question Why must the return type of a coroutine be move-constructible? but

the issue there was fixed in GCC 10.2, while the example from this question is still valid in GCC 11 and trunk;

this question asks about co_await requirements, while the other does not mention co_await at all;

the other question is about move-constructor only, while here the latest GCC demands copy-constructor.


问:
Incremental counter right before each

This should be easy, although I spent over 4 hours and nothing! I REALLY need to add a counter for
 tag, inside an specific DIV CLASS, to count lyric lines, and "echo" the corresponding number on each line right before the
. I understand that this can´t be done by css, like happens with
, because
 won´t allow before and after css conditionals. Will really appreciate the help.

Example:

Every time when I look in the mirror 1

All these lines on my face getting clearer 2

The past is gone 3

And it went by, like dusk to dawn 4

Isn't that the way? 5

Everybody's got their dues in life to pay 6

Yeah, I know nobody knows 7

Where it comes and where it goes 8

I know it's everybody's sin 9

You got to lose to know how to win 10

答:
If each line is a
 you can do that to replace each

var listElements = document.getElementsByTagName('br')

for(var i = 1; i <= listElements.length; i++){
var line = listElements[i-1].parentElement.innerHTML

    listElements[i-1].parentElement.innerHTML = line.replace('<br', i+'<br')
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Every time when I look in the mirror <br /> </p>
    <p>All these lines on my face getting clearer <br /></p>
    <p>The past is gone <br /></p>
    <p>And it went by, like dusk to dawn <br /></p>
    <p>Isn't that the way? <br /></p>
    <p>Everybody's got their dues in life to pay <br /></p>
    <p>Yeah, I know nobody knows <br /></p>
    <p>Where it comes and where it goes <br /></p>
    <p>I know it's everybody's sin <br /></p>
    <p>You got to lose to know how to win <br /></p></code>```

Body:
If each line is a <p> you can do that to replace each <br>

var listElements = document.getElementsByTagName('br')

for(var i = 1; i <= listElements.length; i++){
var line = listElements[i-1].parentElement.innerHTML

    listElements[i-1].parentElement.innerHTML = line.replace('<br', i+'<br')
}

<p>Every time when I look in the mirror <br /> </p>
    <p>All these lines on my face getting clearer <br /></p>
    <p>The past is gone <br /></p>
    <p>And it went by, like dusk to dawn <br /></p>
    <p>Isn't that the way? <br /></p>
    <p>Everybody's got their dues in life to pay <br /></p>
    <p>Yeah, I know nobody knows <br /></p>
    <p>Where it comes and where it goes <br /></p>
    <p>I know it's everybody's sin <br /></p>
    <p>You got to lose to know how to win <br /></p>


问:
React Router with optional path parameter
I want to declare a path with an optional path parameter, hence when I add it the page to do something extra (e.g. fill some data):

http://localhost/app/path/to/page <= render the page
  http://localhost/app/path/to/page/pathParam <= render the page with
  some data according to the pathParam

In my react router I have the following paths, in order to support the two options (this is a simplified example):

```<code><Router history={history}>
   <Route path="/path" component={IndexPage}>
      <Route path="to/page" component={MyPage}/>
      <Route path="to/page/:pathParam" component={MyPage}/>
   </Route>
</Router>
</code>```

My question is, can we declare it in one route? If I add only the second row then the route without the parameter is not found.

EDIT#1:

The solution mentioned here about the following syntax did not work for me, is it a proper one? Does it exist in the documentation?

```<code><Route path="/product/:productName/?:urlID?" handler={SomeHandler} />
</code>```

My react-router version is: 1.0.3

答:
As Sayak pointed out, optional parameters have been removed from React Router V6. The easiest solution I have found was to just make two routes. One for the url without the param and one with:

<Route path="/product/:productName/" handler={SomeHandler} />
<Route path="/product/:productName/:urlID" handler={SomeHandler} />
```

Body:
I want to declare a path with an optional path parameter, hence when I add it the page to do something extra (e.g. fill some data):

http://localhost/app/path/to/page <= render the page
  http://localhost/app/path/to/page/pathParam <= render the page with
  some data according to the pathParam

In my react router I have the following paths, in order to support the two options (this is a simplified example):

<Router history={history}>
   <Route path="/path" component={IndexPage}>
      <Route path="to/page" component={MyPage}/>
      <Route path="to/page/:pathParam" component={MyPage}/>
   </Route>
</Router>

My question is, can we declare it in one route? If I add only the second row then the route without the parameter is not found.

EDIT#1:

The solution mentioned here about the following syntax did not work for me, is it a proper one? Does it exist in the documentation?

<Route path="/product/:productName/?:urlID?" handler={SomeHandler} />

My react-router version is: 1.0.3


问:
Can exception be perfectly replaced by if.. else?
I'm new to programming and I have a conceptual question.

That is, can "exception" be perfectly replaced by "if.. else" ?

I know "exception" is to handling some exceptional conditions that might cause error or crash.

But we also use "if.. else" to ensure the correctness of value of variables, don't we?

Or "exception" can really be replaced by "if.. else", but using "exception" has other benefits(like convenience?)

Thank you, and sorry for my poor English.

答:
Most of your questions relate to Python, so here is an answer based on that fact.

In Python, it is idiomatic (or "pythonic") to use try-except blocks. We call this "EAFP": Easier to ask for forgiveness than permission.

In C, where there were no exceptions, it was usual to "LBYL": Look before you leap, resulting in lots of if (...) statements.

So, while you can LBYL, you should follow the idioms of the language in which you are programming: using exceptions for handling exceptional cases and if-statements for conditionals.