问:
Union intersected nested lists in python
I am looking for an efficient way to union intersected nested lists.
Ex:

```<code>input: [[1,2,3], [5,3,7],[8,9]]
output: [[1,2,3,5,7],[8,9]]
</code>```

Note: assume more than three nested lists

Current implementation:
Loop over each nested list --> loop over all lists --> if there is an intersection, union and delete old list -- do that until no intersection.

答:
So, I'm not sure how fast this is (let me think about it), but I think this works (I tested it on a few different inputs, including your example, and got correct results):

```<code>def merge_intersecting_elements(many_lists):
    # Let lst in claims.values()
    # claims[e] is lst iff e in lst.
    claims = {}

    for lst in many_lists:
        glob = lst[:]
        for e in lst:
            if e not in claims:
                claims[e] = glob  # We are the first to claim e.
                continue

            # Ignore self-intersection.
            if claims[e] is glob:
                continue

            # We found someone else that we intersect with.
            # Take over ALL their territory, not just e.
            glob.extend(claims[e])
            for e2 in claims[e]:
                claims[e2] = glob  # at some point, e2 = e

    deduper = {}
    for v in claims.values():
        deduper[id(v)] = v

    return list(deduper.values())
</code>```

So... One thing about this solution is that it maintains multiplicity. Based on your example, seems like you do not want that. Relatedly, it also seems that within each input sublist, each element is supposed to be unique, but you also didn't specify this.

In any case, I think it should be easy to adapt my suggested solution to maintain uniqueness, though it might affect performance. At the very least, you could uniquify each sublist at the end (which can be accelerated by sorting).

Update: I think you can speed up my solution by changing

```<code>for lst in many_lists
</code>```

to

```<code>for lst in sorted(many_lists, key=len, reverse=True)
</code>```

This would tend to reduce the total amount of time spent in the inner most loop, although I think it depends on exactly what data you feed in.

Here's the basic intuition why sorting by length in descending order would be helpful. Consider this degenerate example:

```<code>mother_lode = list(range(n))
[[0], [1], [2], [3], ... [n], mother_lode]
</code>```

If the first lst is mother_lode, then EVERYBODY collides with it and so we end up scanning a large list many times. But, if instead we consider mother_lode LAST, then we only rescan many small lists once. This adds up to n times less (total) rescanning time.

Body:
I am looking for an efficient way to union intersected nested lists.
Ex:

input: [[1,2,3], [5,3,7],[8,9]]
output: [[1,2,3,5,7],[8,9]]

Note: assume more than three nested lists

Current implementation:
Loop over each nested list --> loop over all lists --> if there is an intersection, union and delete old list -- do that until no intersection.

Body:
So, I'm not sure how fast this is (let me think about it), but I think this works (I tested it on a few different inputs, including your example, and got correct results):

def merge_intersecting_elements(many_lists):
    # Let lst in claims.values()
    # claims[e] is lst iff e in lst.
    claims = {}

    for lst in many_lists:
        glob = lst[:]
        for e in lst:
            if e not in claims:
                claims[e] = glob  # We are the first to claim e.
                continue

            # Ignore self-intersection.
            if claims[e] is glob:
                continue

            # We found someone else that we intersect with.
            # Take over ALL their territory, not just e.
            glob.extend(claims[e])
            for e2 in claims[e]:
                claims[e2] = glob  # at some point, e2 = e

    deduper = {}
    for v in claims.values():
        deduper[id(v)] = v

    return list(deduper.values())

So... One thing about this solution is that it maintains multiplicity. Based on your example, seems like you do not want that. Relatedly, it also seems that within each input sublist, each element is supposed to be unique, but you also didn't specify this.

In any case, I think it should be easy to adapt my suggested solution to maintain uniqueness, though it might affect performance. At the very least, you could uniquify each sublist at the end (which can be accelerated by sorting).

Update: I think you can speed up my solution by changing

for lst in many_lists

to

for lst in sorted(many_lists, key=len, reverse=True)

This would tend to reduce the total amount of time spent in the inner most loop, although I think it depends on exactly what data you feed in.

Here's the basic intuition why sorting by length in descending order would be helpful. Consider this degenerate example:

mother_lode = list(range(n))
[[0], [1], [2], [3], ... [n], mother_lode]

If the first lst is mother_lode, then EVERYBODY collides with it and so we end up scanning a large list many times. But, if instead we consider mother_lode LAST, then we only rescan many small lists once. This adds up to n times less (total) rescanning time.


来源: stackexchange

问:
Display tooltip on press in react hooks and hide after few seconds
I would like to display phonenumber as tooltipduring onPress(),the below code display the data always. How to make dispay during onPress and hide in 5 seconds.

```<code>    const [phoneTooltip, setPhoneTooltip] = useState({
        show: false,
        x: 0,
        y: 0,
        orientLeft: false
      });

  const displayPhoneToolTip = event => {
    if (!phoneTooltip) {
    setPhoneTooltip(true) // display tooltip
     }
   }

 <span className="phoneNumber_home">
    <img src="/images/phone_image.png" name="phoneNumberhomeicon" onPress={displayPhoneToolTip}/>
    <div key={phonenumber}>{phonenumber}</div>
 </span>
</code>```

答:
Your state is an object so you need to make checks using phoneTooltip.show and not just phoneTooltip.

Also make use of setTimeout to remove tooltip after your desired time

A quick demo is here using your code

Code snippet

const displayPhoneToolTip = (event) => {
  if (!phoneTooltip.show) {
    setPhoneTooltip((prev) => ({ ...prev, show: true })); // show tooltip
    setTimeout(() => {
      setPhoneTooltip((prev) => ({ ...prev, show: false })); // remove/hide tooltip
    }, 5000);
  }
};

```

ContentLicense: CC BY-SA 4.0

Body:
I would like to display phonenumber as tooltipduring onPress(),the below code display the data always. How to make dispay during onPress and hide in 5 seconds.

    const [phoneTooltip, setPhoneTooltip] = useState({
        show: false,
        x: 0,
        y: 0,
        orientLeft: false
      });

  const displayPhoneToolTip = event => {
    if (!phoneTooltip) {
    setPhoneTooltip(true) // display tooltip
     }
   }

{phonenumber}


问:
Having trouble with Bootstrap 4 dropdown menu
For some reason, my dropdown menu doesn't function in bootstrap4. I have jquery, bootstrap, and I'm not totally sure if popper was properly imported. Was wondering if anyone could point me as to if I did something wrong.</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title>Learning BootStrap</title>

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <script src="js/jquery.min.js"  ></script>

    <script src="js/bootstrap.min.js" ></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"> </script>

</head>

<body>

<p class="lead text-center">This is my website.</p>
<div class="dropdown">

<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Menu</button/>
    <div class="dropdown-menu">

        <a href="#" class="dropdown-item">first link</a>
        <a href="#" class="dropdown-item">second link</a>
        <a href="#" class="dropdown-item">third link</a>

</div>
</div>

</body>
</html>
</code>```

答:
The version you have downloaded is probably a minified version. I am saying this because it is referring something like js/bootstrap.min.js.

You have to include jquery and popper with the help of stackpath link they are not available in bootstrap Downloaded version. below is the code that you should be using in order to make that dropdown workable!

```<code><!DOCTYPE html>
<html>

<head>
  <title>Learning BootStrap</title>

<!-- ----------------------------Link you have to include before your css and js file -->

  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
    integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous">
  </script>

  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
    integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous">
  </script>

  <!-- ----------------------------Your File -->

  <link rel="stylesheet" href="css/bootstrap.min.css">
  <script src="js/bootstrap.min.js"></script>

</head>

<body>

  <p class="lead text-center">This is my website.</p>
  <div class="dropdown">

    <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Menu</button>
    <div class="dropdown-menu">

      <a href="#" class="dropdown-item">first link</a>
      <a href="#" class="dropdown-item">second link</a>
      <a href="#" class="dropdown-item">third link</a>

    </div>
  </div>

</body>

</html>
</code>```

Body:
For some reason, my dropdown menu doesn't function in bootstrap4. I have jquery, bootstrap, and I'm not totally sure if popper was properly imported. Was wondering if anyone could point me as to if I did something wrong.

<!DOCTYPE html>

    <title>Learning BootStrap</title>

    <link rel="stylesheet" href="css/bootstrap.min.css">

This is my website.

<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Menu</button/>

        first link
        second link
        third link

Body:
The version you have downloaded is probably a minified version. I am saying this because it is referring something like js/bootstrap.min.js.

You have to include jquery and popper with the help of stackpath link they are not available in bootstrap Downloaded version. below is the code that you should be using in order to make that dropdown workable!

<!DOCTYPE html>
<html>

<head>
  <title>Learning BootStrap</title>

<!-- ----------------------------Link you have to include before your css and js file -->

  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
    integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous">
  </script>

  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
    integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous">
  </script>

  <!-- ----------------------------Your File -->

  <link rel="stylesheet" href="css/bootstrap.min.css">
  <script src="js/bootstrap.min.js"></script>

</head>

<body>

  <p class="lead text-center">This is my website.</p>
  <div class="dropdown">

    <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Menu</button>
    <div class="dropdown-menu">

      <a href="#" class="dropdown-item">first link</a>
      <a href="#" class="dropdown-item">second link</a>
      <a href="#" class="dropdown-item">third link</a>

    </div>
  </div>

</body>

</html>


问:
Username hidden html + php
I have problem with html and php,so I created login page and all functions for login,but I want to put username in header (Like a facebook) and have problem.Username is hidden when I add php code.
Everything work perfect,here is my HTML code.
pocetna.html

```<code><?php
session_start();
?>
<html>
<head>
    <title>
        weekta RolePlay | Pocetna
    </title>
    <link rel="stylesheet" href="style/styless.css">
    <link href="https://fonts.googleapis.com/css2?family=Jost&display=swap" rel="stylesheet">
</head>
<body>
<header>
            <a class="logo" href="/" style="text-decoration: none;color: #1260a8;font-size: 30px;font-family: 'Jost', sans-serif;"><p>weekta</p></a>
            <nav>
                <ul class="nav__links">
                    <li><a href="#">Services</a></li>
                    <li><a href="#">Projects</a></li>
                    <li><a href="#">About</a></li>
                    <li><a href="#"><span><?php echo( $_SESSION['korisnickoime'] );?></span></a></li>
                </ul>
            </nav>
            <a class="cta" href="index.html">Login</a>

            <p class="menu cta">Menu</p>
        </header>
        <div id="mobile__menu" class="overlay">
            <a class="close">×</a>
            <div class="overlay__content">
                <a href="#">Services</a>
                <a href="#">Projects</a>
                <a href="#">About</a>
            </div>
        </div>
        <script type="text/javascript" src="mobile.js"></script>
</body>
</html>
</code>```

And here is login_process.php

```<code><?php

$mysql_host="localhost";
$mysql_user="root";
$mysql_password="";
$mysql_db="weekta";

$conn = mysqli_connect($mysql_host,$mysql_user,$mysql_password);
mysqli_select_db($conn, 'weekta');
session_start();
if(isset($_POST['korisnickoime'])){

    $username=$_POST['korisnickoime'];
    $password=$_POST['sifrajedan'];

    $sql="SELECT * FROM loginform where korisnickoime='".$username."'AND sifrajedan='".$password."' limit 1";

    $result = mysqli_query($conn,$sql);

    if(mysqli_num_rows($result)==1){
        header("Location:pocetna.html");
        echo " Dobodosao $username";
        exit();
    }
    else{
        echo " Pogresna lozinka.";
        exit();
    }
}
?>
</code>```

Can someone help me?Thanks.

答:
You are not setting $_SESSION['username'] after your user was found in the db.

Im not a PHP expert, but you need to do something like $_SESSION['username'] = 'xyz' i think. Besides that your select query is vunerable to sql injection.

https://www.php.net/manual/en/security.database.sql-injection.php

Title: Username hidden html + php

Body:
I have problem with html and php,so I created login page and all functions for login,but I want to put username in header (Like a facebook) and have problem.Username is hidden when I add php code.
Everything work perfect,here is my HTML code.
pocetna.html

<?php
session_start();
?>

    <title>
        weekta RolePlay | Pocetna
    </title>
    <link rel="stylesheet" href="style/styless.css">
    <link href="https://fonts.googleapis.com/css2?family=Jost&display=swap" rel="stylesheet">

weekta

Services

Projects

About

<?php echo( $_SESSION['korisnickoime'] );?>

            Login

Menu

            ×

                Services
                Projects
                About

And here is login_process.php

<?php

$mysql_host="localhost";
$mysql_user="root";
$mysql_password="";
$mysql_db="weekta";

$conn = mysqli_connect($mysql_host,$mysql_user,$mysql_password);
mysqli_select_db($conn, 'weekta');
session_start();
if(isset($_POST['korisnickoime'])){

    $username=$_POST['korisnickoime'];
    $password=$_POST['sifrajedan'];

    $sql="SELECT * FROM loginform where korisnickoime='".$username."'AND sifrajedan='".$password."' limit 1";

    $result = mysqli_query($conn,$sql);

    if(mysqli_num_rows($result)==1){
        header("Location:pocetna.html");
        echo " Dobodosao $username";
        exit();
    }
    else{
        echo " Pogresna lozinka.";
        exit();
    }
}
?>

Can someone help me?Thanks.


问:
POSTGRES: CREATE TABLE doesn't save
I'm connecting to a postgres database in Heroku and trying to create a table. I run the code below but no new table shows up in the database.

```<code>import psycopg2
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
create_table = (""" CREATE TABLE test_table (account_address__c varchar); """)
cur = conn.cursor()
cur.execute(create_table)
conn.close()
</code>```

Can you help?

Thank you!

答:
I forgot to add

```<code>conn.commit()
</code>```

.

```<code>cur = conn.cursor()
cur.execute(create_table)
conn.commit()
conn.close()
</code>```

Title: POSTGRES: CREATE TABLE doesn't save

Body:
I'm connecting to a postgres database in Heroku and trying to create a table. I run the code below but no new table shows up in the database.

import psycopg2
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
create_table = (""" CREATE TABLE test_table (account_address__c varchar); """)
cur = conn.cursor()
cur.execute(create_table)
conn.close()

Can you help?

Thank you!

Body:
I forgot to add

conn.commit()

.

cur = conn.cursor()
cur.execute(create_table)
conn.commit()
conn.close()


问:
Instead of updating record update command making new entries
At the time of running update command, it inserts it as a new entry and not updating the previous one. Username is the Foreign key in the insert table. Instead of updating record update command making new entries.

I have written a stored procedure to insert data:

```<code>CREATE PROCEDURE Login_insert
    @Name nvarchar(50),
    @Address varchar(50),
    @City varchar(50),
    @DateOfBirth datetime,
    @Username nvarchar(50)
AS
BEGIN
    INSERT INTO NewUser
    VALUES (@Name, @Address, @City, @DateOfBirth, @Username)
END
</code>```

and calling it from my C# code like this:

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    int count = 0;

    SqlCommand command;

    SqlConnection con = new SqlConnection("Data Source=DESKTOP-HKML31V\\SQLEXPRESS;Initial Catalog=DB;Integrated Security=True");
    con.Open();

    if (count > 0)
    {
        command = new SqlCommand("UPDATE NewUser SET Name = @Name, Address = @Address, City = @City, DateofBith = @DateofBirth WHERE Id = @Username", con);
    }
    else
    {
        command = new SqlCommand("Login_insert", con);
        command.CommandType = System.Data.CommandType.StoredProcedure;

        command.Parameters.AddWithValue("Name", TextBox1.Text);
        command.Parameters.AddWithValue("Address", TextBox2.Text);
        command.Parameters.AddWithValue("City", TextBox3.Text);
        command.Parameters.AddWithValue("DateofBirth", TextBox4.Text);
        command.Parameters.AddWithValue("Username", Label1.Text);
    }

    int rowsupdated = command.ExecuteNonQuery();
}
</code>```

答:
I would probably package the whole logic into the stored procedure: pass in all the values, and let the stored procedure check first if the record you're interested in exists - if so, update it - if not, insert a new record

```<code>CREATE PROCEDURE dbo.InsertOrUpdateUser
    @Name nvarchar(50),
    @Address varchar(50),
    @City varchar(50),
    @DateOfBirth datetime,
    @Username nvarchar(50)
AS
BEGIN
    -- check if the user already exists
    IF EXISTS (SELECT * FROM dbo.NewUser WHERE Id = @Username)
    BEGIN
        -- user does exist - update it
        UPDATE NewUser
        SET Name = @Name,
            Address = @Address,
            City = @City,
            DateofBith =  @DateofBirth
        WHERE Id = @Username
    END
    ELSE BEGIN
        -- user does not exist - insert a new entry
        INSERT INTO NewUser (Name, Address, City, DateOfBirth, Id)
        VALUES (@Name, @Address, @City, @DateOfBirth, @Username)
    END
END
</code>```

and then just call this stored procedure from your C# code:

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=DESKTOP-HKML31V\\SQLEXPRESS;Initial Catalog=DB;Integrated Security=True");

    SqlCommand cmdInsertOrUpdate = new SqlCommand("dbo.InsertOrUpdateUser", con);
    cmdInsertOrUpdate .CommandType = CommandType.StoredProcedure;

    cmdInsertOrUpdate.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value =  TextBox1.Text;
    cmdInsertOrUpdate.Parameters.Add("@Address", SqlDbType.NVarChar, 50).Value = TextBox2.Text;
    cmdInsertOrUpdate.Parameters.Add("@City", SqlDbType.NVarChar, 50).Value = TextBox3.Text;
    cmdInsertOrUpdate.Parameters.Add("@DateofBirth", SqlDbType.DateTime).Value = Convert.ToDateTime(TextBox4.Text);
    cmdInsertOrUpdate.Parameters.Add("@Username", SqlDbType.NVarChar, 50).Value = Label1.Text;

    con.Open();
    int rowsupdated = cmdInsertOrUpdate.ExecuteNonQuery();
    con.Close();
}
</code>```

Body:
At the time of running update command, it inserts it as a new entry and not updating the previous one. Username is the Foreign key in the insert table. Instead of updating record update command making new entries.

I have written a stored procedure to insert data:

CREATE PROCEDURE Login_insert
    @Name nvarchar(50),
    @Address varchar(50),
    @City varchar(50),
    @DateOfBirth datetime,
    @Username nvarchar(50)
AS
BEGIN
    INSERT INTO NewUser
    VALUES (@Name, @Address, @City, @DateOfBirth, @Username)
END

and calling it from my C# code like this:

protected void Button1_Click(object sender, EventArgs e)
{
    int count = 0;

    SqlCommand command;

    SqlConnection con = new SqlConnection("Data Source=DESKTOP-HKML31V\\SQLEXPRESS;Initial Catalog=DB;Integrated Security=True");
    con.Open();

    if (count > 0)
    {
        command = new SqlCommand("UPDATE NewUser SET Name = @Name, Address = @Address, City = @City, DateofBith = @DateofBirth WHERE Id = @Username", con);
    }
    else
    {
        command = new SqlCommand("Login_insert", con);
        command.CommandType = System.Data.CommandType.StoredProcedure;

        command.Parameters.AddWithValue("Name", TextBox1.Text);
        command.Parameters.AddWithValue("Address", TextBox2.Text);
        command.Parameters.AddWithValue("City", TextBox3.Text);
        command.Parameters.AddWithValue("DateofBirth", TextBox4.Text);
        command.Parameters.AddWithValue("Username", Label1.Text);
    }

    int rowsupdated = command.ExecuteNonQuery();
}

Body:
I would probably package the whole logic into the stored procedure: pass in all the values, and let the stored procedure check first if the record you're interested in exists - if so, update it - if not, insert a new record

CREATE PROCEDURE dbo.InsertOrUpdateUser
    @Name nvarchar(50),
    @Address varchar(50),
    @City varchar(50),
    @DateOfBirth datetime,
    @Username nvarchar(50)
AS
BEGIN
    -- check if the user already exists
    IF EXISTS (SELECT * FROM dbo.NewUser WHERE Id = @Username)
    BEGIN
        -- user does exist - update it
        UPDATE NewUser
        SET Name = @Name,
            Address = @Address,
            City = @City,
            DateofBith =  @DateofBirth
        WHERE Id = @Username
    END
    ELSE BEGIN
        -- user does not exist - insert a new entry
        INSERT INTO NewUser (Name, Address, City, DateOfBirth, Id)
        VALUES (@Name, @Address, @City, @DateOfBirth, @Username)
    END
END

and then just call this stored procedure from your C# code:

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=DESKTOP-HKML31V\\SQLEXPRESS;Initial Catalog=DB;Integrated Security=True");

    SqlCommand cmdInsertOrUpdate = new SqlCommand("dbo.InsertOrUpdateUser", con);
    cmdInsertOrUpdate .CommandType = CommandType.StoredProcedure;

    cmdInsertOrUpdate.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value =  TextBox1.Text;
    cmdInsertOrUpdate.Parameters.Add("@Address", SqlDbType.NVarChar, 50).Value = TextBox2.Text;
    cmdInsertOrUpdate.Parameters.Add("@City", SqlDbType.NVarChar, 50).Value = TextBox3.Text;
    cmdInsertOrUpdate.Parameters.Add("@DateofBirth", SqlDbType.DateTime).Value = Convert.ToDateTime(TextBox4.Text);
    cmdInsertOrUpdate.Parameters.Add("@Username", SqlDbType.NVarChar, 50).Value = Label1.Text;

    con.Open();
    int rowsupdated = cmdInsertOrUpdate.ExecuteNonQuery();
    con.Close();
}


问:
How to add button within text like ones on Twitter of Instagram app's hash tags

Buttons within text like Instagram or Twitter app's

On my iOS app, I need to embed buttons within text like Instagram or Twitter app's do for hash tags within a post.

Some detailed requirements are

buttons triggers iOS native action on "TOUCHN UP INSIDE"

buttons need to glow on "TOUCH DOWN" like UIButtons

buttons are NOT web links

.link AttribuedString did not work(this is what people say is the solution)

Using .link attribute for AttributedString was closest I got but it had some side effects.

It meets all my requirements but when I long tap the button, iOS show by its UIKit feature a link text over the UITextLabel and the link text is also can be dragged and I do not want those to happen.

Here is what I tried.  I basically added .link attributes and set keyword as URL that I could retried specific keyword on UITextView's delegate method "should interact with URL" and trigger some iOS native code.

```<code>public extension NSMutableAttributedString {

    func setKeywordAsLink(keyword: String, fontAttributeForKeyword font: UIFont) {
        guard let url = keyword.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return }

        self.addAttributes([ NSAttributedString.Key.font: font], range: NSString(string: self.string).range(of: keyword))
        self.addAttribute(.link, value: url, range: NSString(string: self.string).range(of: keyword))
    }
}

</code>```

答:
I don't have code off hand but I would not recommend the approach above. You should create a custom UIButton Class  and override the isHighlighted and isSelected functions. Here's a similar example of overriding the isHighlighted from an old project I have. You can add the UIButton as your normally would, just set it to the type of your custom Class (here it would be let button: UIButtonExample!) you can then add regular IBActions for TouchUpInside and TouchDown if you'd like.</p>

```<code>class UIButtonExample: UIButton {

    override func awakeFromNib() {
        super.awakeFromNib()

        //set up origin formatting here
        layer.borderWidth = 1.0
        layer.borderColor = .black
    }

    override var isHighlighted: Bool {
        didSet {
            if self.isHighlighted {
                //pressed on
                self.animatePress()
            } else {
                //unpressed
                self.animateHome()
            }
        }
    }

    func animatePress() {
        UIView.animate(withDuration: 0.15) {
            self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
        }
    }

    func animateHome() {
        UIView.animate(withDuration: 0.3) {
            self.transform = CGAffineTransform.identity
        }
    }

}
</code>```

Body:
Buttons within text like Instagram or Twitter app's

On my iOS app, I need to embed buttons within text like Instagram or Twitter app's do for hash tags within a post.

Some detailed requirements are

buttons triggers iOS native action on "TOUCHN UP INSIDE"

buttons need to glow on "TOUCH DOWN" like UIButtons

buttons are NOT web links

.link AttribuedString did not work(this is what people say is the solution)

Using .link attribute for AttributedString was closest I got but it had some side effects.

It meets all my requirements but when I long tap the button, iOS show by its UIKit feature a link text over the UITextLabel and the link text is also can be dragged and I do not want those to happen.

Here is what I tried.  I basically added .link attributes and set keyword as URL that I could retried specific keyword on UITextView's delegate method "should interact with URL" and trigger some iOS native code.

public extension NSMutableAttributedString {

    func setKeywordAsLink(keyword: String, fontAttributeForKeyword font: UIFont) {
        guard let url = keyword.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return }

        self.addAttributes([ NSAttributedString.Key.font: font], range: NSString(string: self.string).range(of: keyword))
        self.addAttribute(.link, value: url, range: NSString(string: self.string).range(of: keyword))
    }
}

Body:
I don't have code off hand but I would not recommend the approach above. You should create a custom UIButton Class  and override the isHighlighted and isSelected functions. Here's a similar example of overriding the isHighlighted from an old project I have. You can add the UIButton as your normally would, just set it to the type of your custom Class (here it would be let button: UIButtonExample!) you can then add regular IBActions for TouchUpInside and TouchDown if you'd like.

class UIButtonExample: UIButton {

    override func awakeFromNib() {
        super.awakeFromNib()

        //set up origin formatting here
        layer.borderWidth = 1.0
        layer.borderColor = .black
    }

    override var isHighlighted: Bool {
        didSet {
            if self.isHighlighted {
                //pressed on
                self.animatePress()
            } else {
                //unpressed
                self.animateHome()
            }
        }
    }

    func animatePress() {
        UIView.animate(withDuration: 0.15) {
            self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
        }
    }

    func animateHome() {
        UIView.animate(withDuration: 0.3) {
            self.transform = CGAffineTransform.identity
        }
    }

}


问:
Why does this beginner python program stop midway?
This is my first day learning python from a book called "Automate the Boring Stuff with Python".

On the "your first program" section the program is this

```<code># This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')  # ask for their name
myName = input("Mizu")
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')  # ask for their age
myAge = input('20')
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
</code>```

but the program only runs

```<code>Hello world!
What is your name?
Mizu
</code>```

but if i replace the input() functions with just values like myName = 'Mizu' , it prints the rest of the lines just fine.

What am i doing wrong here?

i used the default python editor and pycharm and both show no errors or anything.

答:
input means that it's waiting for you to write something.
Type something and press"Enter"

It isn't stopped.

Body:
This is my first day learning python from a book called "Automate the Boring Stuff with Python".

On the "your first program" section the program is this

# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')  # ask for their name
myName = input("Mizu")
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')  # ask for their age
myAge = input('20')
print('You will be ' + str(int(myAge) + 1) + ' in a year.')

but the program only runs

Hello world!
What is your name?
Mizu

but if i replace the input() functions with just values like myName = 'Mizu' , it prints the rest of the lines just fine.

What am i doing wrong here?

i used the default python editor and pycharm and both show no errors or anything.


问:
Cards in a split screen
I'm trying to build product cards into a split screen but they continue to stack on top of each other instead of side-by-side.

Does anyone have a solution ?

My code can be found below. I'm a newbie at coding, so ignore the some of the images and lack of experience. The purpose of this code is to create a uniform display of items being auction offed for charity.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stuf Auction</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat+Alternates&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="node_modules/font-awesome/css/font-awesome.min.css" />
    <link rel="stylesheet" href="stufcss.css">
</head>
<body>
<!-- left side -->
    <div class="split left">
        <div class="centered">
            <img src="images/stufgreen.png" alt="stuf logo">
            <h2></h2>
            <p></p>
        </div>
    </div>
<!-- right side -->
    <div class="split right">
        <div class="centered">
            <div class="container">
            <div class="row row-content">
                <div class="card">
                    <img src="images/jordanshoes.jpg" alt="Denim Jeans" style="width:100%">
                    <h1>Tailored Jeans</h1>
                    <p class="price">$19.99</p>
                    <p>Some text about the jeans. Super slim and comfy lorem ipsum lorem jeansum. Lorem jeamsun denim lorem jeansum.</p>
                    <p><button>Bid</button></p>
                </div>
                <div class="card">
                    <img src="images/jordanshoes.jpg" alt="Denim Jeans" style="width:100%">
                    <h1>Tailored Jeans</h1>
                    <p class="price">$19.99</p>
                    <p>Some text about the jeans. Super slim and comfy lorem ipsum lorem jeansum. Lorem jeamsun denim lorem jeansum.</p>
                    <p><button>Bid</button></p>
                </div>
            </div>
            </div>
        </div>
    </div>
<!-- footer -->
    <footer class="site footer">
        <div class="container">
            <div class="row">
                <div class="col-4 col-sm-2 offset-1">
                    <h5>Links</h5>
                    <ul class="list-unstyled">
                        <li><a href="#">Home</a></li>
                        <li><a href="aboutus.html">About</a></li>
                        <li><a href="contactus.html">Contact</a></li>
                    </ul>
                </div>
                <div class="col-6 col-sm-5 text-center">
                    <h5>Social</h5>
                    <a class="btn btn-social-icon btn-instagram" href="http://instagram.com/"><i
                            class="fa fa-instagram"></i></a>
                    <a class="btn btn-social-icon btn-facebook" href="http://facebook.com/"><i
                            class="fa fa-facebook"></i></a>
                    <a class="btn btn-social-icon btn-twitter" href="http://twitter.com/"><i class="fa fa-twitter"></i></a>
                    <a class="btn btn-social-icon btn-google" href="http://youtube.com/"><i class="fa fa-youtube"></i></a>
                </div>
                <div class="col-sm-4">
                    <a role="button" class="btn btn-link" href="tel:+12065551234"><i class="fa fa-phone"></i>
                        1-206-555-1234</a><br />
                    <a role="button" class="btn btn-link" href="mailto:campsites@nucamp.co"><i class="fa fa-envelope-o"></i>
                        campsites@nucamp.co</i>
                </div>
            </div>
        </div>
    </footer>

</body>

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
    integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
    crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
    integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
    crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
    integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
    crossorigin="anonymous"></script>
</html>
</code>```

答:
There's no class as split in bootstrap-4. If you want to split your screen you can use bootstrap-grids

```<code><div class="container">
  <div class="row">
    <div class="col-sm">
      One column
    </div>
    <div class="col-sm">
      One column
    </div>
  </div>
</div>
</code>```

more info

Title: Cards in a split screen

Body:
I'm trying to build product cards into a split screen but they continue to stack on top of each other instead of side-by-side.

Does anyone have a solution ?

My code can be found below. I'm a newbie at coding, so ignore the some of the images and lack of experience. The purpose of this code is to create a uniform display of items being auction offed for charity.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stuf Auction</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
        integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat+Alternates&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="node_modules/font-awesome/css/font-awesome.min.css" />
    <link rel="stylesheet" href="stufcss.css">

Tailored Jeans

$19.99

Some text about the jeans. Super slim and comfy lorem ipsum lorem jeansum. Lorem jeamsun denim lorem jeansum.

<button>Bid</button>

Tailored Jeans

$19.99

Some text about the jeans. Super slim and comfy lorem ipsum lorem jeansum. Lorem jeamsun denim lorem jeansum.

<button>Bid</button>

Links

Home

About

Contact

Social

                        1-206-555-1234

                        campsites@nucamp.co

Body:
There's no class as split in bootstrap-4. If you want to split your screen you can use bootstrap-grids

<div class="container">
  <div class="row">
    <div class="col-sm">
      One column
    </div>
    <div class="col-sm">
      One column
    </div>
  </div>
</div>

more info


问:
Plotting varImp in R
Im using the varImp function of the caret package and Im trying to plot the resulting dataframe that it creates. Here is the code:

```<code>RocImp2 <- varImp(svmFit, scale = FALSE)
</code>```

and Im using a simple plot to plot the chart:

```<code>plot(RocImp2)
</code>```

The results are supposed to look like this:

whereas mine looks like this:

Here is a copy of the dataframe:

disregard the names in the plot as they are from another example.

答:
here is a solution to plot the varImp in the case of a binary classification model.

model = glm(Survived~.,family="binomial", data=Titanic)

```<code>V = caret::varImp(model)

ggplot2::ggplot(V, aes(x=reorder(rownames(V),Overall), y=Overall)) +
geom_point( color="blue", size=4, alpha=0.6)+
geom_segment( aes(x=rownames(V), xend=rownames(V), y=0, yend=Overall),
color='skyblue') +
xlab('Variable')+
ylab('Overall Importance')+
theme_light() +
coord_flip()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Plotting varImp in R

Body:
Im using the varImp function of the caret package and Im trying to plot the resulting dataframe that it creates. Here is the code:

RocImp2 <- varImp(svmFit, scale = FALSE)

and Im using a simple plot to plot the chart:

plot(RocImp2)

The results are supposed to look like this:

whereas mine looks like this:

Here is a copy of the dataframe:

disregard the names in the plot as they are from another example.

Body:
here is a solution to plot the varImp in the case of a binary classification model.

model = glm(Survived~.,family="binomial", data=Titanic)

V = caret::varImp(model)

ggplot2::ggplot(V, aes(x=reorder(rownames(V),Overall), y=Overall)) +
geom_point( color="blue", size=4, alpha=0.6)+
geom_segment( aes(x=rownames(V), xend=rownames(V), y=0, yend=Overall),
color='skyblue') +
xlab('Variable')+
ylab('Overall Importance')+
theme_light() +
coord_flip()


问:
Unity object reference not set to an instance of an object unity
I have a "object reference not set to an instance of an object unity" errors even though I have an instance of object in project.

```<code>26: teslaGun = GameObject.Find("TeslaGun");
27: teslaGunController = teslaGun.GetComponent<TeslaGunController>();

35: arms = GameObject.Find("Arms").gameObject;

47: if (arms.activeSelf)
</code>```

答:
Try this</p>

```<code>teslaGun = GameObject.Find("Player/TeslaGun");
arms = GameObject.Find("Player/Arms");
</code>```

Body:
I have a "object reference not set to an instance of an object unity" errors even though I have an instance of object in project.

26: teslaGun = GameObject.Find("TeslaGun");
27: teslaGunController = teslaGun.GetComponent<TeslaGunController>();

35: arms = GameObject.Find("Arms").gameObject;

47: if (arms.activeSelf)

Body:
Try this

teslaGun = GameObject.Find("Player/TeslaGun");
arms = GameObject.Find("Player/Arms");


问:
Uncaught Reference Error when trying to pass a function through a button in JavaScript?
I'm trying to write a navigation bar at the top of my web app to change a parameter in backend, but when I call the function it always return an unexpected end of input or an uncaught reference error that says my function was not defined on click. Can someone please help me figure out what I'm doing wrong?

JS File:

```<code>let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(type);
}

let str = '<div class="topnav">';
for(let count = 0; count < typearray.length; count++){
    str = str +
    '<button onclick ="changeType("'+typearray[count]+'")" title = " '+ typearray[count] + '">' +typearray[count] +'</button>';
}
str = str + '</div>' +
'</div>';
console.log(str);

document.getElementById('navbar').innerHTML = str;
</code>```

HTML File(includes the rest of the program)

```<code><html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">
    <style>
      #map {
        height: 75%;
        width: 75%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <script src = getlocation.js></script>
    <!-- this implements the navbar-->
    <div id="navbar"></div>
    <script type = "module" src = navbar.js></script>
    <!-- this implements the map-->
    <div id="map"></div>
    <script src = index.js> </script>
    <!-- this implements the list-->
    <div id="list"></div>
    <script type = "module" src = rankedstores.js></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=000000000000000000
    &callback=initMap"></script>
  </body>
</html>
</code>```

答:
Just for understanding purpose:

The problem here is that a html attribute value has to be wrapped around single or double quotes. With your code, the quotes that wrap around the value of the button's onlick attribute end not there where you want because you start with double quotes but wrap the function with double quotes as well so the element at the end looks like this:

<button onclick="changeType(" supermarkets_and_groceries")"="" title=" supermarkets_and_groceries">supermarkets_and_groceries</button>

to fix this either use double and single quotes:

```<code>str = str +
"<button onclick='changeType(" + '"' + typearray[count] + '"' + ")' title = ' " + typearray[count] + "'>" + typearray[count] + "</button>";
</code>```

or use template literals (already mentioned by the other answers):

```<code>str = str + `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
</code>```

template literals explanation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Body:
I'm trying to write a navigation bar at the top of my web app to change a parameter in backend, but when I call the function it always return an unexpected end of input or an uncaught reference error that says my function was not defined on click. Can someone please help me figure out what I'm doing wrong?

JS File:

let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(type);
}

let str = '
';
for(let count = 0; count < typearray.length; count++){
    str = str +
    '<button onclick ="changeType("'+typearray[count]+'")" title = " '+ typearray[count] + '">' +typearray[count] +'</button>';
}
str = str + '
' +
'
';
console.log(str);

document.getElementById('navbar').innerHTML = str;

HTML File(includes the rest of the program)

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">

Body:
Just for understanding purpose:

The problem here is that a html attribute value has to be wrapped around single or double quotes. With your code, the quotes that wrap around the value of the button's onlick attribute end not there where you want because you start with double quotes but wrap the function with double quotes as well so the element at the end looks like this:

<button onclick="changeType(" supermarkets_and_groceries")"="" title=" supermarkets_and_groceries">supermarkets_and_groceries</button>

to fix this either use double and single quotes:

str = str +
"<button onclick='changeType(" + '"' + typearray[count] + '"' + ")' title = ' " + typearray[count] + "'>" + typearray[count] + "</button>";

or use template literals (already mentioned by the other answers):

str = str + `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;

template literals explanation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals


问:
Bidirectional data exchange between macOS Bundles (swift)
How can I pass data between macOS Bundles?

eg: MyApp.app sends data to a function or class initialiser in MyBundle.bundle, which performs its own logic on it. It could even return a value, which MyApp.app can then process further.

Fo example, a function in MyBundle (not nested in any other declaration):

```<code>    void initialise(unsigned int frameCount) {…} // not a class initialiser btw
</code>```

I have tried:

Declaring a class in MyBundle and then loading it in MyApp using Foundation.Bundle:

```<code>let class = (Bundle(url: url)!.classNamed("MyClass")! as! NSObject.Type).init()
// class is an instance of NSObject, but I can override the `init()` method
// (in MyBundle) to do whatever. I have not found a way to implement an
// initialiser with parameters, and it still be recognised here.
</code>```

Declaring a function in MyBundle and using CFBundleGetFunctionPointerForName to retrieve it.

```<code>var bundles = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault, bundleDirectory, bundleExtension)! as Array
var bundle1 = bundles.first! as! CFBundle

var untypedFunctionPointer = CFBundleGetFunctionPointerForName(bundle, "initialise" as CFString)!

let imp = unsafeBitCast(untypedFunctionPointer, to: IMP.self)

let function = unsafeBitCast(imp, to: (@convention(c)(CUnsignedInt) -> Void).self)
// If I specify parameters here, pass them in below, then try to use them in my objective c function, I get exc_bad_access.

function(CUnsignedInt(1.0)) // Will work only when not trying to access parameters in the original objective c function.

// Whatever @convention(c) function signature I use, the parameters are unusable in Objective C.
</code>```

The critical issue with both is that I am unable to pass data in as parameters. So a print statement will work but no ability to use arguments.

Edit: Accepted answer shows the correct method for calling function pointers. The crashes I talked about are a result of using types which are not being bridged to the C family of languages properly, so stick to NSNumber, NSString etc. from the Foundation library when in doubt.

答:
Based on your question Call Swift function from Bundle and comments in https://stackoverflow.com/a/56281093/5329717 I presume you're after dynamically invoking in Swift a function pointer or an objective-c method with UnsafeBufferPointer argument.

First of all UnsafeBufferPointer will make a copy so for interoping I recommend switching to OpaquePointer instead.

Assuming function to pointer case with signature void cFunction(void* arg):

```<code>let fakeIMP = unsafeBitCast(functionToPointerAddress, to: IMP.self)
unsafeBitCast(fakeIMP,to:(@convention(c)(OpaquePointer)->Void).self)(bufferArg)
</code>```

Assuming static objective-c method:

```<code>let receiverClass = NSClassFromString("SomeClass")
let selector: Selector = NSSelectorFromString("selectorArg:")
let methodIMP: IMP! = method_getImplementation(class_getClassMethod(receiverClass, selector))
unsafeBitCast(methodIMP,to:(@convention(c)(AnyClass?,Selector,OpaquePointer)->Any).self)(receiverClass,selector, bufferArg)
</code>```

For your provided C signature

```<code>void initialise(unsigned int frameCount);
</code>```

Try this:

```<code>let imp = unsafeBitCast(functionToPointerAddress, to: IMP.self)
unsafeBitCast(imp,to:(@convention(c)(Int)->Void).self)(1)
</code>```

Body:
How can I pass data between macOS Bundles?

eg: MyApp.app sends data to a function or class initialiser in MyBundle.bundle, which performs its own logic on it. It could even return a value, which MyApp.app can then process further.

Fo example, a function in MyBundle (not nested in any other declaration):

    void initialise(unsigned int frameCount) {…} // not a class initialiser btw

I have tried:

Declaring a class in MyBundle and then loading it in MyApp using Foundation.Bundle:

let class = (Bundle(url: url)!.classNamed("MyClass")! as! NSObject.Type).init()
// class is an instance of NSObject, but I can override the `init()` method
// (in MyBundle) to do whatever. I have not found a way to implement an
// initialiser with parameters, and it still be recognised here.

Declaring a function in MyBundle and using CFBundleGetFunctionPointerForName to retrieve it.

var bundles = CFBundleCreateBundlesFromDirectory(kCFAllocatorDefault, bundleDirectory, bundleExtension)! as Array
var bundle1 = bundles.first! as! CFBundle

var untypedFunctionPointer = CFBundleGetFunctionPointerForName(bundle, "initialise" as CFString)!

let imp = unsafeBitCast(untypedFunctionPointer, to: IMP.self)

let function = unsafeBitCast(imp, to: (@convention(c)(CUnsignedInt) -> Void).self)
// If I specify parameters here, pass them in below, then try to use them in my objective c function, I get exc_bad_access.

function(CUnsignedInt(1.0)) // Will work only when not trying to access parameters in the original objective c function.

// Whatever @convention(c) function signature I use, the parameters are unusable in Objective C.

The critical issue with both is that I am unable to pass data in as parameters. So a print statement will work but no ability to use arguments.

Edit: Accepted answer shows the correct method for calling function pointers. The crashes I talked about are a result of using types which are not being bridged to the C family of languages properly, so stick to NSNumber, NSString etc. from the Foundation library when in doubt.

Body:
Based on your question Call Swift function from Bundle and comments in https://stackoverflow.com/a/56281093/5329717 I presume you're after dynamically invoking in Swift a function pointer or an objective-c method with UnsafeBufferPointer argument.

First of all UnsafeBufferPointer will make a copy so for interoping I recommend switching to OpaquePointer instead.

Assuming function to pointer case with signature void cFunction(void* arg):

let fakeIMP = unsafeBitCast(functionToPointerAddress, to: IMP.self)
unsafeBitCast(fakeIMP,to:(@convention(c)(OpaquePointer)->Void).self)(bufferArg)

Assuming static objective-c method:

let receiverClass = NSClassFromString("SomeClass")
let selector: Selector = NSSelectorFromString("selectorArg:")
let methodIMP: IMP! = method_getImplementation(class_getClassMethod(receiverClass, selector))
unsafeBitCast(methodIMP,to:(@convention(c)(AnyClass?,Selector,OpaquePointer)->Any).self)(receiverClass,selector, bufferArg)

For your provided C signature

void initialise(unsigned int frameCount);

Try this:

let imp = unsafeBitCast(functionToPointerAddress, to: IMP.self)
unsafeBitCast(imp,to:(@convention(c)(Int)->Void).self)(1)


问:
Child component doesn't update correctly with state update in parent component
Simply i have a list item, that contain a list of names, clicking any list item change the color of that item, this is my logic:

```<code>const App = () => {

    const items = [
        {
            name: 'peter',
            id: 1
        },
        {
            name: 'Mark',
            id: 2
        },
        {
            name: 'john',
            id: 3
        }
    ]

    const [id, setId] = useState(null);
    const [names, setNames] = useState(items)

    const setClickedItemId = (id) => {
        setId(id)
    }

    const turnItemRed = () => {
        setNames(prev =>  prev.map(i => i.id === id ? {...i, color: 'red' } : i))

    }

    return (
        <div className="app">
            <ul className="items">
                {
                    names.map(i => {
                        return (
                            <Item
                               item={i}
                                setClickedItemId={setClickedItemId}
                                turnItemRed={turnItemRed}
                            />
                        )
                    })
                }
            </ul>
        </div>
    )
}

function Item({item, ...props}) {
    const { name, id} = item;
    const { setClickedItemId, turnItemRed } = props;
    return (
        <li
            className={`${item.color === 'red' ? 'red' : ''}`}
            onClick={() => {
                setClickedItemId(id);
                turnItemRed()

            }}
        >{name}</li>
    )
}

ReactDOM.render(<App />, document.getElementById('root'))

</code>```

This renders a list of items, i need two clicks to have an item turning into red, which means the child component doesn't catch the most recent version of state, but:

Just adding that line of code before the return statement in parent components,

```<code>const showingItems = names.map(i => i.id === id ? {...i, color: 'red'} : i)
</code>```

and then using that variable showingItems to render the list instead of state variable names make it right and don't know why

So, why the child components Items doesn't get the most recent version of the state while storing the state in a variable makes it work??

答:
```<code>import React,{useState} from 'react';
export default  () => {

    const items = [
        {
            name: 'peter',
            id: 1
        },
        {
            name: 'Mark',
            id: 2
        },
        {
            name: 'john',
            id: 3
        }
    ]

    const [id, setId] = useState(null);
    const [names, setNames] = useState(items)

    const setClickedItemId = (id) => {
        setId(id);
        turnItemRed(id);
    }

    const turnItemRed = (id) => {
        setNames(prev => prev.map(i => i.id === id ? { ...i, color: 'red' } : i))
    }
    return (
        <div className="app">
            <ul className="items">
                {
                    names.map(i => {
                        return (
                            <Item
                                item={i}
                                setClickedItemId={setClickedItemId}
                                turnItemRed={turnItemRed}
                            />
                        )
                    })
                }
            </ul>
        </div>
    )
}

function Item({ item, ...props }) {
    const { name, id } = item;
    const { setClickedItemId, turnItemRed } = props;
    return (
        <li
            style={{ color: item.color === 'red' ? 'red' : ''}}
            onClick={() => {
                setClickedItemId(id);
            }}
        >{name}</li>
    )
}
</code>```

Body:
Simply i have a list item, that contain a list of names, clicking any list item change the color of that item, this is my logic:

const App = () => {

    const items = [
        {
            name: 'peter',
            id: 1
        },
        {
            name: 'Mark',
            id: 2
        },
        {
            name: 'john',
            id: 3
        }
    ]

    const [id, setId] = useState(null);
    const [names, setNames] = useState(items)

    const setClickedItemId = (id) => {
        setId(id)
    }

    const turnItemRed = () => {
        setNames(prev =>  prev.map(i => i.id === id ? {...i, color: 'red' } : i))

    }

    return (

                {
                    names.map(i => {
                        return (
                            <Item
                               item={i}
                                setClickedItemId={setClickedItemId}
                                turnItemRed={turnItemRed}
                            />
                        )
                    })
                }

    )
}

function Item({item, ...props}) {
    const { name, id} = item;
    const { setClickedItemId, turnItemRed } = props;
    return (
        <li
            className={`${item.color === 'red' ? 'red' : ''}`}
            onClick={() => {
                setClickedItemId(id);
                turnItemRed()

            }}
        >{name}

    )
}

ReactDOM.render(<App />, document.getElementById('root'))

This renders a list of items, i need two clicks to have an item turning into red, which means the child component doesn't catch the most recent version of state, but:

Just adding that line of code before the return statement in parent components,

const showingItems = names.map(i => i.id === id ? {...i, color: 'red'} : i)

and then using that variable showingItems to render the list instead of state variable names make it right and don't know why

So, why the child components Items doesn't get the most recent version of the state while storing the state in a variable makes it work??


问:
Java XML Document XPath with Disable Escaping
Currently, I need to get the element of XML without escaping.

For example:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Message>
      <Header>H001</Header>
      <Body>
            <Item>ABC&ABC"</Item>
      </Body>
</Message>
</code>```

I need to get the value of "Item" element via XPath.
However, it is escaped automatically.

My Result = ABC&ABC"

Expected = ABC&ABC"

How can I get the expected value?

答:
Put content surrounded by CDATA.

Note: Charater data (CDATA) will tell the parser to send the text as regular text (no markup) without parsing.

For example :

abc.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Messages>
    <Message>
        <Header>H001</Header>
        <Body>
            <Item><![CDATA[ABC&&ABC&quot;]]></Item>
        </Body>
    </Message>
</Messages>
</code>```

Java code :

```<code>import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Test {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("abc.xml");
        Document doc = builder.parse(input);
        doc.getDocumentElement().normalize();
        NodeList list = doc.getElementsByTagName("Message");
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            NodeList children = node.getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
                node = children.item(j);
                System.out.println(node.getTextContent().trim());
            }
        }

    }

}
</code>```

Output :

```<code>H001

ABC&&ABC&quot;
</code>```

Body:
Currently, I need to get the element of XML without escaping.

For example:

<?xml version="1.0" encoding="UTF-8"?>
<Message>
      H001

            <Item>ABC&amp;ABC&quot;</Item>

</Message>

I need to get the value of "Item" element via XPath.
However, it is escaped automatically.

My Result = ABC&ABC"

Expected = ABC&amp;ABC&quot;

How can I get the expected value?

Body:
Put content surrounded by CDATA.

Note: Charater data (CDATA) will tell the parser to send the text as regular text (no markup) without parsing.

For example :

abc.xml

<?xml version="1.0" encoding="UTF-8"?>
<Messages>
    <Message>
        <Header>H001</Header>
        <Body>
            <Item><![CDATA[ABC&amp;&amp;ABC&amp;quot;]]></Item>
        </Body>
    </Message>
</Messages>

Java code :

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Test {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("abc.xml");
        Document doc = builder.parse(input);
        doc.getDocumentElement().normalize();
        NodeList list = doc.getElementsByTagName("Message");
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            NodeList children = node.getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
                node = children.item(j);
                System.out.println(node.getTextContent().trim());
            }
        }

    }

}

Output :

H001

ABC&amp;&amp;ABC&amp;quot;


问:
How to get the list elements using jquery?
I want to get the list elements using jquery. I tried but not getting the result.

The code is

I want a Chocolate Cookie

I want a Strawberry Icecream

I want a good

Chicken Sandwich and large fries

Veg Burger with cheese

```

I want to get the entire list text using its href element. If I give https://www.111.com, the jquery should return "I want a Chocolate Cookie"

If I give https://www.444.com, the jquery should return not only "Veg Burger with cheese", but also including its parent "I want a good Veg Burger with cheese"

It should automatically check for a parent list is present. Thanks in advance.

答:
$(document).ready(function() {

  $("#btn").click(function() {
  let url = $("#url").val();
    $("#result").text(`Looking for [${url}]`);

    let link = $(`a[href="${url}"]`);
    if (link.length>0) {
      let li = link.parents("li").last();

      $("#result").text(`${li.text()}`);
    } else {
      $("#result").text(`no item found for ${url}`);
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="paragraph">
  <ol>

    <li>I want a Chocolate<span style="color:rgb(80, 141, 36)"> Cookie</span></li>
    <li>I want a Strawberry<span style="color:rgb(80, 141, 36)"> Icecream</span></li>

    <li>I want a good
      <ol>
        <li>Chicken Sandwich<span style="color:rgb(80, 141, 36)"> and large fries</span></li>

        <li>Veg Burger<span style="color:rgb(80, 141, 36)"> with cheese</span></li>

      </ol>
    </li>
  </ol>
</div>

<input type="text" id="url" placeholder="Enter a url" value="https://www.111.com">
<button type="button" id="btn">Submit</button>
<div id="result"></div></code>```

Body:
I want to get the list elements using jquery. I tried but not getting the result.

The code is

I want a Chocolate Cookie

I want a Strawberry Icecream

I want a good

Chicken Sandwich and large fries

Veg Burger with cheese

I want to get the entire list text using its href element. If I give https://www.111.com, the jquery should return "I want a Chocolate Cookie"

If I give https://www.444.com, the jquery should return not only "Veg Burger with cheese", but also including its parent "I want a good Veg Burger with cheese"

It should automatically check for a parent list is present. Thanks in advance.

Body:
$(document).ready(function() {

  $("#btn").click(function() {
  let url = $("#url").val();
    $("#result").text(`Looking for [${url}]`);

    let link = $(`a[href="${url}"]`);
    if (link.length>0) {
      let li = link.parents("li").last();

      $("#result").text(`${li.text()}`);
    } else {
      $("#result").text(`no item found for ${url}`);
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="paragraph">
  <ol>

    <li>I want a <a href="https://www.111.com" target="_blank">Chocolate</a><span style="color:rgb(80, 141, 36)"> Cookie</span></li>
    <li>I want a <a href="https://www.222.com" target="_blank">Strawberry</a><span style="color:rgb(80, 141, 36)"> Icecream</span></li>

    <li>I want a good
      <ol>
        <li>Chicken <a href="https://www.333.com" target="_blank">Sandwich</a><span style="color:rgb(80, 141, 36)"> and large fries</span></li>

        <li>Veg <a href="https://www.444.com" target="_blank">Burger</a><span style="color:rgb(80, 141, 36)"> with cheese</span></li>

      </ol>
    </li>
  </ol>
</div>

<input type="text" id="url" placeholder="Enter a url" value="https://www.111.com">
<button type="button" id="btn">Submit</button>
<div id="result"></div>


问:
Angular is it possible to sort array alphabetically in ngFor?
I need to sort my ngFor alphabatically here is my code

```<code><div *ngFor="let main of data.mainCategories; let i = index" class="category-container">
  <ion-grid class="categories-card5" no-padding>
  <ion-row><ion-col class="ion-text-center">
  <ion-item lines="none" button="true" (click)="showSubCategory(i)" detail="false">
    <ion-thumbnail slot="start">
      <img *ngIf="main.image?.src" src="{{main.image.src}}">
    </ion-thumbnail>
    <ion-label>
      <h2 [innerHTML]="main.name"></h2>
      <h2 [innerHTML]="main.slug"></h2>
      <p [innerHTML]="main.description"></p>
    </ion-label>
    <ion-icon *ngIf="main.show" name="chevron-up-outline" mode="ios" color="medium"></ion-icon>
    <ion-icon *ngIf="!main.show" name="chevron-down-outline" mode="ios" color="medium"></ion-icon>
  </ion-item>
</ion-col>
</ion-row>
</ion-grid>
</div>
</code>```

In this i have main.slug i need to sort it by this example in main.slug which start alphabet is a it will show first like this

答:
One solution is to sort them within what you're looping from.

Sample:

const mainCategories = [
  { name: 'Category B', slug: 'B' },
  { name: 'Category A', slug: 'A' },
  { name: 'Category E', slug: 'E' },
  { name: 'Category C', slug: 'C' }
]

mainCategories.sort((a, b) => (a.slug > b.slug) ? 1 : -1)

console.log(mainCategories);```

Body:
I need to sort my ngFor alphabatically here is my code

  <ion-grid class="categories-card5" no-padding>
  <ion-row><ion-col class="ion-text-center">
  <ion-item lines="none" button="true" (click)="showSubCategory(i)" detail="false">
    <ion-thumbnail slot="start">

    </ion-thumbnail>
    <ion-label>

    </ion-label>
    <ion-icon *ngIf="main.show" name="chevron-up-outline" mode="ios" color="medium"></ion-icon>
    <ion-icon *ngIf="!main.show" name="chevron-down-outline" mode="ios" color="medium"></ion-icon>
  </ion-item>
</ion-col>
</ion-row>
</ion-grid>

In this i have main.slug i need to sort it by this example in main.slug which start alphabet is a it will show first like this


问:
Google Drive API v3 Change File Permissions and Get Publicly Shareable Link (Python)
I'm trying to use the Google Drive API v3 with Python 3 to automatically upload files, make them 'public' and get a shareable link that anybody, whether logged into a Google Account or not, can view and download (but not modify).

I'm close, but can't quite figure it out!  Observe my code.  It requires a text file named "testing.txt" to be in the same directory as the script:

```<code>from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

from apiclient.http import MediaFileUpload
from apiclient import errors

# https://developers.google.com/drive/api/v2/about-auth#requesting_full_drive_scope_during_app_development
SCOPES = 'https://www.googleapis.com/auth/drive' # https://stackoverflow.com/a/32309750

# https://developers.google.com/drive/api/v2/reference/permissions/update
def update_permission(service, file_id, permission_id, new_role, type):
  """Update a permission's role.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to update permission for.
    permission_id: ID of the permission to update.
    new_role: The value 'owner', 'writer' or 'reader'.

  Returns:
    The updated permission if successful, None otherwise.
  """
  try:
    # First retrieve the permission from the API.
    permission = service.permissions().get(fileId=file_id, permissionId=permission_id).execute()
    permission['role'] = new_role
    permission['type'] = type
    return service.permissions().update(fileId=file_id, permissionId=permission_id, body=permission).execute()
  except errors.HttpError as error:
    print('An error occurred:', error)
  return None

if __name__ == '__main__':
    # credential things
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    drive_service = build('drive', 'v3', http=creds.authorize(Http()))

    # create and upload file
    file_metadata = {'name': 'testing.txt'}
    media = MediaFileUpload('testing.txt',
                            mimetype='text/txt')
    file = drive_service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields='id, webViewLink, permissions').execute()

    # get information needed to update permissions
    file_id = file['id']
    permission_id = file['permissions'][0]['id']

    print(file_id)
    print(permission_id)

    # update permissions?  It doesn't work!
    update_permission(drive_service, file_id, permission_id, 'reader', 'anyone') # https://stackoverflow.com/a/11669565

    print(file.get('webViewLink'))
</code>```

When I run this code, I receive the following:

```<code>1quyzYHc0uCQIEt88gqd4h_jWtlBaoHHH
01486072639937946874
An error occurred: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/1quyzYHc0uCQIEt88gqd4h_jWtlBaoHHH/permissions/01486072639937946874?alt=json returned "The resource body includes fields which are not directly writable.">
https://drive.google.com/file/d/1quyzYHc0uCQIEt88gqd4h_jWtlBaoHHH/view?usp=drivesdk
</code>```

When I copy and paste the final link into another browser, it is not available, so clearly it did not succeed in changing the file permissions.  But I don't understand why it failed.  It mentions that The resource body includes fields which are not directly writable, but I don't know what this means.

Can somebody please help me understand what I'm doing wrong and what I need to change to fix it?  Thanks.

答:
The selected answer was not precise (nothing about type value and role) enough so I had to read the documentation a bit more, here is a working example, you just need to give the file_id:

def set_permission(service, file_id):
    print(file_id)
    try:
        permission = {'type': 'anyone',
                      'value': 'anyone',
                      'role': 'reader'}
        return service.permissions().create(fileId=file_id,body=permission).execute()
    except errors.HttpError as error:
        return print('Error while setting permission:', error)
```

Body:
I'm trying to use the Google Drive API v3 with Python 3 to automatically upload files, make them 'public' and get a shareable link that anybody, whether logged into a Google Account or not, can view and download (but not modify).

I'm close, but can't quite figure it out!  Observe my code.  It requires a text file named "testing.txt" to be in the same directory as the script:

from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

from apiclient.http import MediaFileUpload
from apiclient import errors

# https://developers.google.com/drive/api/v2/about-auth#requesting_full_drive_scope_during_app_development
SCOPES = 'https://www.googleapis.com/auth/drive' # https://stackoverflow.com/a/32309750

# https://developers.google.com/drive/api/v2/reference/permissions/update
def update_permission(service, file_id, permission_id, new_role, type):
  """Update a permission's role.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to update permission for.
    permission_id: ID of the permission to update.
    new_role: The value 'owner', 'writer' or 'reader'.

  Returns:
    The updated permission if successful, None otherwise.
  """
  try:
    # First retrieve the permission from the API.
    permission = service.permissions().get(fileId=file_id, permissionId=permission_id).execute()
    permission['role'] = new_role
    permission['type'] = type
    return service.permissions().update(fileId=file_id, permissionId=permission_id, body=permission).execute()
  except errors.HttpError as error:
    print('An error occurred:', error)
  return None

if __name__ == '__main__':
    # credential things
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    drive_service = build('drive', 'v3', http=creds.authorize(Http()))

    # create and upload file
    file_metadata = {'name': 'testing.txt'}
    media = MediaFileUpload('testing.txt',
                            mimetype='text/txt')
    file = drive_service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields='id, webViewLink, permissions').execute()

    # get information needed to update permissions
    file_id = file['id']
    permission_id = file['permissions'][0]['id']

    print(file_id)
    print(permission_id)

    # update permissions?  It doesn't work!
    update_permission(drive_service, file_id, permission_id, 'reader', 'anyone') # https://stackoverflow.com/a/11669565

    print(file.get('webViewLink'))

When I run this code, I receive the following:

1quyzYHc0uCQIEt88gqd4h_jWtlBaoHHH
01486072639937946874
An error occurred: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/1quyzYHc0uCQIEt88gqd4h_jWtlBaoHHH/permissions/01486072639937946874?alt=json returned "The resource body includes fields which are not directly writable.">
https://drive.google.com/file/d/1quyzYHc0uCQIEt88gqd4h_jWtlBaoHHH/view?usp=drivesdk

When I copy and paste the final link into another browser, it is not available, so clearly it did not succeed in changing the file permissions.  But I don't understand why it failed.  It mentions that The resource body includes fields which are not directly writable, but I don't know what this means.

Can somebody please help me understand what I'm doing wrong and what I need to change to fix it?  Thanks.


答:
you need to type some thing after the third line like
$Mizu"Mizu".
The Mizu shown on the run is just a reminder message to let know which input are you giving value.</p>

Title: Why does this beginner python program stop midway?

Body:
This is my first day learning python from a book called "Automate the Boring Stuff with Python".

On the "your first program" section the program is this

# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')  # ask for their name
myName = input("Mizu")
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')  # ask for their age
myAge = input('20')
print('You will be ' + str(int(myAge) + 1) + ' in a year.')

but the program only runs

Hello world!
What is your name?
Mizu

but if i replace the input() functions with just values like myName = 'Mizu' , it prints the rest of the lines just fine.

What am i doing wrong here?

i used the default python editor and pycharm and both show no errors or anything.


问:
Javascript alarm doesn't play the sound file
I am working on localhost at the moment, my laptop. I am the only user.

I made an online exam for a friend. He asked if I could make a bell ring or a message sound 5 minutes before the end of the exam, so the students don’t wait too long before pressing “Send” or they won't be able to send their answers.

I have this javascript. Someone told me it works for him. Look here:

```<code><script>
const d = new Date();

// if later than h, play the sound. It's past 11am here now!
// set the minutes later if this works
var h = d.getHours();
console.log({h});
if (h > 7) {
    // I put a hidden input on the page, with the value of the sound file
    // <input type="hidden" id="musicloc" size="55" value="mp3/fullstop.mp3" />
    var sound = document.getElementById("musicloc").value;
    playSound(sound);
}

// this should make an audio element and then play the sound
function playSound(soundFile) {
    var audioElement = document.createElement('audio');
    // maybe here the problem? What is 'src'?
    audioElement.setAttribute('src', soundFile);
    audioElement.play();

</script>
</code>```

But I get no sound.

In Firefox I did see this error  :

Autoplay is only allowed when approved by the user, the site is
  activated by the user, or media is muted.
  19BEsW13.html:259:18

```<code>NotAllowedError: The play method is not allowed by the user agent or the platform in the current context, possibly because the user
</code>```

denied permission.

I can't get Firefox to repeat this error message.

I can't open

console.log({h}) ReferenceError: h is not defined

Is this a Firefox settings problem? Can I change this?

Or play the sound some other way?

答:
As Pedroski pointed browser does not allow playing sound unless the user interacts with the page.

One way to fix this issue is to add a button which user needs to click to agree to ring reminder sound.

for example:

// javascript
let startBtn = document.getElementById("start")
startBtn.onclick = function (e) {
    e.preventDefault()
    let count = document.getElementById("count")
    let interval = window.setInterval(function () {
        count.textContent = --count.textContent;
        if (count.textContent == 0) {
            clearInterval(interval);
            let bell = document.getElementById("bell")
            bell.play()
        }
    }, 1000)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- html -->
<audio id="bell">
    <source
    src="http://filipcicspagerprogramming.weebly.com/uploads/1/0/5/4/10541783/05-dive-n.wav"
    />
    Your browser does not support the audio element.
</audio>
<p id="count" style="font-size: large;">5</p>
<button id="start">Remind After 5 Secs</button></code>```

Body:
I am working on localhost at the moment, my laptop. I am the only user.

I made an online exam for a friend. He asked if I could make a bell ring or a message sound 5 minutes before the end of the exam, so the students don’t wait too long before pressing “Send” or they won't be able to send their answers.

I have this javascript. Someone told me it works for him. Look here:

But I get no sound.

In Firefox I did see this error  :

Autoplay is only allowed when approved by the user, the site is
  activated by the user, or media is muted.
  19BEsW13.html:259:18

NotAllowedError: The play method is not allowed by the user agent or the platform in the current context, possibly because the user

denied permission.

I can't get Firefox to repeat this error message.

I can't open

console.log({h}) ReferenceError: h is not defined

Is this a Firefox settings problem? Can I change this?

Or play the sound some other way?

Body:
As Pedroski pointed browser does not allow playing sound unless the user interacts with the page.

One way to fix this issue is to add a button which user needs to click to agree to ring reminder sound.

for example:

// javascript
let startBtn = document.getElementById("start")
startBtn.onclick = function (e) {
    e.preventDefault()
    let count = document.getElementById("count")
    let interval = window.setInterval(function () {
        count.textContent = --count.textContent;
        if (count.textContent == 0) {
            clearInterval(interval);
            let bell = document.getElementById("bell")
            bell.play()
        }
    }, 1000)
}

<!-- html -->
<audio id="bell">
    <source
    src="http://filipcicspagerprogramming.weebly.com/uploads/1/0/5/4/10541783/05-dive-n.wav"
    />
    Your browser does not support the audio element.
</audio>
<p id="count" style="font-size: large;">5</p>
<button id="start">Remind After 5 Secs</button>


问:
Not able to configure mongodb in laravel framework
I am not able to integrate mongoDB is laravel project. Installation of 'jenssegers/mongodb' Package in the project fails. Following are the error prints.

Output of command composer require jenssegers/mongodb

```<code>./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install jenssegers/mongodb v3.6.3
    - Conclusion: don't install jenssegers/mongodb v3.6.2
    - Conclusion: don't install jenssegers/mongodb v3.6.1
    - Conclusion: remove laravel/framework v7.5.1
    - Installation request for jenssegers/mongodb ^3.6 -> satisfiable by jenssegers/mongodb[v3.6.0, v3.6.1, v3.6.2, v3.6.3].
    - Conclusion: don't install laravel/framework v7.5.1
    - jenssegers/mongodb v3.6.0 requires illuminate/events ^5.8|^6.0 -> satisfiable by illuminate/events[5.8.x-dev, 6.x-dev, v5.8.0, v5.8.11, v5.8.12, v5.8.14, v5.8.15, v5.8.17, v5.8.18, v5.8.19, v5.8.2, v5.8.20, v5.8.22, v5.8.24, v5.8.27, v5.8.28, v5.8.29, v5.8.3, v5.8.30, v5.8.31, v5.8.32, v5.8.33, v5.8.34, v5.8.35, v5.8.36, v5.8.4, v5.8.8, v5.8.9, v6.0.0, v6.0.1, v6.0.2, v6.0.3, v6.0.4, v6.1.0, v6.10.0, v6.11.0, v6.12.0, v6.13.0, v6.13.1, v6.14.0, v6.15.0, v6.15.1, v6.16.0, v6.17.0, v6.17.1, v6.18.0, v6.18.1, v6.18.2, v6.18.3, v6.18.4, v6.18.5, v6.2.0, v6.3.0, v6.4.1, v6.5.0, v6.5.1, v6.5.2, v6.6.0, v6.6.1, v6.6.2, v6.7.0, v6.8.0].
    - don't install illuminate/events 5.8.x-dev|don't install laravel/framework v7.5.1
    - don't install illuminate/events 6.x-dev|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.11|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.12|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.14|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.15|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.17|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.18|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.19|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.2|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.20|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.22|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.24|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.27|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.28|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.29|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.3|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.30|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.31|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.32|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.33|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.34|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.35|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.36|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.4|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.8|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.9|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.0.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.0.1|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.0.2|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.0.3|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.0.4|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.1.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.2.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.3.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.4.1|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.5.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.5.1|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.5.2|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.6.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.6.1|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.6.2|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.7.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.8.0|don't install laravel/framework v7.5.1
    - Installation request for laravel/framework (locked at v7.5.1, required as ^7.0) -> satisfiable by laravel/framework[v7.5.1].

Installation failed, reverting ./composer.json to its original content.
</code>```

Laravel framewok verion - php artisan --version -> Laravel Framework 7.5.1

MongoDB version -> 4.0.5

PHP version -> 7.4.3

PHP driver for mongodb is installed.

答:
Try - composer require jenssegers/mongodb dev-develop

As it might still be under development for laravel version 7

Body:
I am not able to integrate mongoDB is laravel project. Installation of 'jenssegers/mongodb' Package in the project fails. Following are the error prints.

Output of command composer require jenssegers/mongodb

./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install jenssegers/mongodb v3.6.3
    - Conclusion: don't install jenssegers/mongodb v3.6.2
    - Conclusion: don't install jenssegers/mongodb v3.6.1
    - Conclusion: remove laravel/framework v7.5.1
    - Installation request for jenssegers/mongodb ^3.6 -> satisfiable by jenssegers/mongodb[v3.6.0, v3.6.1, v3.6.2, v3.6.3].
    - Conclusion: don't install laravel/framework v7.5.1
    - jenssegers/mongodb v3.6.0 requires illuminate/events ^5.8|^6.0 -> satisfiable by illuminate/events[5.8.x-dev, 6.x-dev, v5.8.0, v5.8.11, v5.8.12, v5.8.14, v5.8.15, v5.8.17, v5.8.18, v5.8.19, v5.8.2, v5.8.20, v5.8.22, v5.8.24, v5.8.27, v5.8.28, v5.8.29, v5.8.3, v5.8.30, v5.8.31, v5.8.32, v5.8.33, v5.8.34, v5.8.35, v5.8.36, v5.8.4, v5.8.8, v5.8.9, v6.0.0, v6.0.1, v6.0.2, v6.0.3, v6.0.4, v6.1.0, v6.10.0, v6.11.0, v6.12.0, v6.13.0, v6.13.1, v6.14.0, v6.15.0, v6.15.1, v6.16.0, v6.17.0, v6.17.1, v6.18.0, v6.18.1, v6.18.2, v6.18.3, v6.18.4, v6.18.5, v6.2.0, v6.3.0, v6.4.1, v6.5.0, v6.5.1, v6.5.2, v6.6.0, v6.6.1, v6.6.2, v6.7.0, v6.8.0].
    - don't install illuminate/events 5.8.x-dev|don't install laravel/framework v7.5.1
    - don't install illuminate/events 6.x-dev|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.11|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.12|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.14|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.15|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.17|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.18|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.19|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.2|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.20|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.22|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.24|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.27|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.28|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.29|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.3|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.30|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.31|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.32|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.33|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.34|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.35|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.36|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.4|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.8|don't install laravel/framework v7.5.1
    - don't install illuminate/events v5.8.9|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.0.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.0.1|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.0.2|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.0.3|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.0.4|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.1.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.2.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.3.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.4.1|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.5.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.5.1|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.5.2|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.6.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.6.1|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.6.2|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.7.0|don't install laravel/framework v7.5.1
    - don't install illuminate/events v6.8.0|don't install laravel/framework v7.5.1
    - Installation request for laravel/framework (locked at v7.5.1, required as ^7.0) -> satisfiable by laravel/framework[v7.5.1].

Installation failed, reverting ./composer.json to its original content.

Laravel framewok verion - php artisan --version -> Laravel Framework 7.5.1

MongoDB version -> 4.0.5

PHP version -> 7.4.3

PHP driver for mongodb is installed.


问:
GCC inline assembly error: junk `(%ebp)+4' after expression
I'm trying to compile inline assembly (with -fasm-blocks) which works in MSVC, but GCC gives me the junk `(%ebp)+4' after expression error... Why won't it accept the syntax and how should I fix this?

```<code>uint64_t _tmp = 100;

_asm
{
     //_tmp value may be changed
     //...
     cmp dword ptr _tmp, 100 // Ok
     jnae temp
     cmp dword ptr _tmp + 4, 50 // It seems GCC doesn't want to accept _tmp + 4
     jnae temp
     //...
     temp:
};
</code>```

答:
You should change it to:</p>

```<code>cmp dword ptr [_tmp + 4], 50
</code>```

Body:
I'm trying to compile inline assembly (with -fasm-blocks) which works in MSVC, but GCC gives me the junk `(%ebp)+4' after expression error... Why won't it accept the syntax and how should I fix this?

uint64_t _tmp = 100;

_asm
{
     //_tmp value may be changed
     //...
     cmp dword ptr _tmp, 100 // Ok
     jnae temp
     cmp dword ptr _tmp + 4, 50 // It seems GCC doesn't want to accept _tmp + 4
     jnae temp
     //...
     temp:
};

Body:
You should change it to:

cmp dword ptr [_tmp + 4], 50


问:
Cannot resolve symbol 'HasRequired' Entity Framework Core
I'm trying to connect two tables by means of code in C# with Entity Framework Core.

The classes are:

```<code>public class roll
{
    [key]
    public int rollId { get; set; }

    public List<pieces> pieces { get; set; }
}

public class pieces
{
    [Key]
    public int pieceId { get; set; }
    public int quantity { get; set; }
    public decimal price { get; set; }
}
</code>```

In my DbContext, I have the following method:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<roll>()
                .HasRequired(m => m.quantity)
                .WithMany(m => m.pieces)
                .HasForeignKey(m => m.pieceId);

    base.OnModelCreating(modelBuilder);
}
</code>```

HasRequired turns red and gives this message:

EntityTypeBuilder does not contain a definition for HasRequired.

The project has added a reference to Microsoft.EntityFrameworkCore.Relational.
I have recompiled the solution, closed and opened visual studio and I cannot solve that HasRequired stops being red

What is wrong with my code?

答:
Entity Framework Core does not have HasRequired() - that's an old Entity Framework <=6 (.NET Framework) method.

EF Core instead uses HasOne(). You can see more on their official documentation here.

Body:
I'm trying to connect two tables by means of code in C# with Entity Framework Core.

The classes are:

public class roll
{
    [key]
    public int rollId { get; set; }

    public List<pieces> pieces { get; set; }
}

public class pieces
{
    [Key]
    public int pieceId { get; set; }
    public int quantity { get; set; }
    public decimal price { get; set; }
}

In my DbContext, I have the following method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<roll>()
                .HasRequired(m => m.quantity)
                .WithMany(m => m.pieces)
                .HasForeignKey(m => m.pieceId);

    base.OnModelCreating(modelBuilder);
}

HasRequired turns red and gives this message:

EntityTypeBuilder does not contain a definition for HasRequired.

The project has added a reference to Microsoft.EntityFrameworkCore.Relational.
I have recompiled the solution, closed and opened visual studio and I cannot solve that HasRequired stops being red

What is wrong with my code?


问:
Chrome is not rendering div, but MS Edge and development build is rendering as intended using React
The site is live at http://www.ipworld.ca/
but it should look like this:
from dev build viewed using chrome
I tried increasing the z-order through css, but no luck. Notice the elements are loaded, but are not shown in the live version.</p>

答:
I think the issue is with the transparency of the card.
Just make these changes in css.

```<code>.services-card {
    max-width: 66%;
    opacity: 1;
    margin: auto;
    background: rgba(255,255,255,0.8);
}
</code>```

The opacity will affect the visibility of the all the contents in the div.
In your case, you should change the background.

https://www.w3schools.com/cssref/func_rgba.asp

Body:
I think the issue is with the transparency of the card.
Just make these changes in css.

.services-card {
    max-width: 66%;
    opacity: 1;
    margin: auto;
    background: rgba(255,255,255,0.8);
}

The opacity will affect the visibility of the all the contents in the div.
In your case, you should change the background.

https://www.w3schools.com/cssref/func_rgba.asp


问:
Django CRM Need to invite agents by admins using email address
I have an uncompleted django CRM. I have 2 types of users:

Agents: can post and view data.

Admins: can view and edit data.

The thing is i need each admin to invite the users to CRM.

i need it to work as following:

Admins will have access to a form where they can write down the agents name and email, once theysubmit the form and an email will be sent to the agent.

The agent will receive an email with another form to set their username and password so they can login

do you have any idea what i should look for or how can i do that?

答:
Generate an activation key each time Admin adds a new user. Include that key in the URL you send to the agent for activating their account. When the agent clicks on the URL with the activation key, verify the key. If verification is successful, allow them to set their username and password, other redirect them an error page.

you can try following to generate Activation Key

```<code>salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
usernamesalt = agentEmail
if isinstance(usernamesalt, unicode):
usernamesalt = usernamesalt.encode('utf8')
activation_key = hashlib.sha1(salt+usernamesalt).hexdigest()
</code>```

Body:
Generate an activation key each time Admin adds a new user. Include that key in the URL you send to the agent for activating their account. When the agent clicks on the URL with the activation key, verify the key. If verification is successful, allow them to set their username and password, other redirect them an error page.

you can try following to generate Activation Key

salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
usernamesalt = agentEmail
if isinstance(usernamesalt, unicode):
usernamesalt = usernamesalt.encode('utf8')
activation_key = hashlib.sha1(salt+usernamesalt).hexdigest()