问:
Running a combn function on different columns of a dataframe, one row at a time
I have the following data frame :

```<code># A tibble: 3 x 4
  index number_1 number_2 number_3
  <int> <chr>    <chr>    <chr>
1     1 32       16       29
2     2 13       50       47
3     3 37       19       18
</code>```

I would like to run a combn function with an parameter of 2 to every line of that tibble between the 3 columns number; that would yield a result along the lines of :

```<code># A tibble: 3 x 2
  index combn
  <dbl> <chr>
1     1 32,16
2     1 32,29
3     1 16,29
4     2 13,50
.............
</code>```

I have thought of something like

```<code>theTibble %>%
               (
               select(., number_1 : nulber_3) %>% lapply(FUN = combn,2)
               ) %>% View
</code>```

but to no avail.

I would like a pipe friendly solution.
What a possible solution would be?

Thank you for your help

答:
You can get the data in long format, for each index apply combn function selecting 2 values at a time, paste them into comma-separated string (toString) and unnest.

```<code>library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = -index) %>%
  group_by(index) %>%
  summarise(combn = list(combn(value, 2, toString))) %>%
  unnest(combn)

#  index combn
#  <int> <chr>
#1     1 32, 16
#2     1 32, 29
#3     1 16, 29
#4     2 13, 50
#5     2 13, 47
#6     2 50, 47
#7     3 37, 19
#8     3 37, 18
#9     3 19, 18
</code>```

Body:
I have the following data frame :

# A tibble: 3 x 4
  index number_1 number_2 number_3
  <int> <chr>    <chr>    <chr>
1     1 32       16       29
2     2 13       50       47
3     3 37       19       18

I would like to run a combn function with an parameter of 2 to every line of that tibble between the 3 columns number; that would yield a result along the lines of :

# A tibble: 3 x 2
  index combn
  <dbl> <chr>
1     1 32,16
2     1 32,29
3     1 16,29
4     2 13,50
.............

I have thought of something like

theTibble %>%
               (
               select(., number_1 : nulber_3) %>% lapply(FUN = combn,2)
               ) %>% View

but to no avail.

I would like a pipe friendly solution.
What a possible solution would be?

Thank you for your help

Body:
You can get the data in long format, for each index apply combn function selecting 2 values at a time, paste them into comma-separated string (toString) and unnest.

library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = -index) %>%
  group_by(index) %>%
  summarise(combn = list(combn(value, 2, toString))) %>%
  unnest(combn)

#  index combn
#  <int> <chr>
#1     1 32, 16
#2     1 32, 29
#3     1 16, 29
#4     2 13, 50
#5     2 13, 47
#6     2 50, 47
#7     3 37, 19
#8     3 37, 18
#9     3 19, 18


来源: stackexchange

问:
How can I prevent my VB application to crash
I hope that you can help me with my problem.

I get this error:

System.Net.WebException:

  The remote server returned an error: (401) Unauthorized.

when I click on button_2. I want to prevent the application from crashing using, show a MessageBox error or something similar.

Can anyone help?

```<code>Private Sub Guna2Button1_Click(sender As Object, e As EventArgs) Handles Guna2Button1.Click
    Dim api As String
    api = Guna2TextBox1.Text
    Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("link")
    Dim wc As New WebClient
    Dim data As String
    Dim response As System.Net.HttpWebResponse
    Try
        response = request.GetResponse()
    Catch ex As System.Net.WebException
        MsgBox("Bad API")
    End Try
    MsgBox("Good API")

        data = wc.DownloadString("link")
        Dim IPV4Regex = New Regex("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
        Dim ipstr As String = ("")
        Dim total As String = ("")
        Dim myJObject = JObject.Parse(data)

        For Each match In myJObject("matches")
            Dim ip = match("http")("host")
            If IPV4Regex.Match(ip).Success Then
                ipstr = ip
                total = total + ipstr & vbCrLf
                Guna2TextBox2.Text = total
                Label4.Visible = True
            End If
        Next
End Sub
</code>```

答:
Try this </p>

```<code>Dim response As System.Net.HttpWebResponse

            Try
                response = request.GetResponse()
            'Put other lines here...
            Catch ex As System.Net.WebException
                msgbox("Something bad happened")
            End Try
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I hope that you can help me with my problem.

I get this error:

System.Net.WebException:

  The remote server returned an error: (401) Unauthorized.

when I click on button_2. I want to prevent the application from crashing using, show a MessageBox error or something similar.

Can anyone help?

Private Sub Guna2Button1_Click(sender As Object, e As EventArgs) Handles Guna2Button1.Click
    Dim api As String
    api = Guna2TextBox1.Text
    Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("link")
    Dim wc As New WebClient
    Dim data As String
    Dim response As System.Net.HttpWebResponse
    Try
        response = request.GetResponse()
    Catch ex As System.Net.WebException
        MsgBox("Bad API")
    End Try
    MsgBox("Good API")

        data = wc.DownloadString("link")
        Dim IPV4Regex = New Regex("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
        Dim ipstr As String = ("")
        Dim total As String = ("")
        Dim myJObject = JObject.Parse(data)

        For Each match In myJObject("matches")
            Dim ip = match("http")("host")
            If IPV4Regex.Match(ip).Success Then
                ipstr = ip
                total = total + ipstr & vbCrLf
                Guna2TextBox2.Text = total
                Label4.Visible = True
            End If
        Next
End Sub

Body:
Try this

Dim response As System.Net.HttpWebResponse

            Try
                response = request.GetResponse()
            'Put other lines here...
            Catch ex As System.Net.WebException
                msgbox("Something bad happened")
            End Try


问:
Xpath - Retrieveing Text value when condition contains a tag
I have section of a table and I am trying to get the value "Distributor 10"

```<code><table class="d">
    <tr>
        <td class="ah">supplier<td>
        <td class="ad">
            <a href="/S/3/143.html">Supplier 10</a>
        </td>
    </tr>
    <tr>
        <td class="ah">distributor```

            Distributor 10

```

<p>If I am within Chrome Developer, I get this value by using the following xpath string</p>

```//tr/td[text()="distributor]/following-sibling::td[@class="ad"]/a/text()
```

<p>But when I code this in python - it returns an empty list... From what I can see its is because of the <code>``` tag next to "distributor"
When I amend the above mentioned xpath to look for "supplier" instead of distributor it works perfectly well

any suggestions would be welcome

答:
Assuming you're using lxml you can use one of the following XPath to get this working :

```<code>//tr[contains(.,"distributor")]//a/text()

//a[parent::td[@class="ad"] and starts-with(@href,"/D")]/text()
</code>```

Piece of code :

```<code>from lxml import etree
from io import StringIO
html = '''<table class="d">
    <tr>
        <td class="ah">supplier<td>
        <td class="ad">
            <a href="/S/3/143.html">Supplier 10</a>
        </td>
    </tr>
    <tr>
        <td class="ah">distributor```

            Distributor 10

'''

parser = etree.HTMLParser()
tree   = etree.parse(StringIO(html), parser)

data = tree.xpath('//tr[contains(.,"distributor")]//a/text()')
print (data)
```

Output : ['Distributor 10']

Alternative : use lxml html cleaner class ("remove_tags") to remove the pre element from your page.

References :

https://lxml.de/api/lxml.html.clean.Cleaner-class.html

https://lxml.de/lxmlhtml.html#cleaning-up-html

Body:
I have section of a table and I am trying to get the value "Distributor 10"

        supplier

            Supplier 10

        distributor

            Distributor 10

If I am within Chrome Developer, I get this value by using the following xpath string

//tr/td[text()="distributor]/following-sibling::td[@class="ad"]/a/text()

But when I code this in python - it returns an empty list... From what I can see its is because of the
 tag next to "distributor"
When I amend the above mentioned xpath to look for "supplier" instead of distributor it works perfectly well

any suggestions would be welcome

Body:
Assuming you're using lxml you can use one of the following XPath to get this working :

//tr[contains(.,"distributor")]//a/text()

//a[parent::td[@class="ad"] and starts-with(@href,"/D")]/text()

Piece of code :

from lxml import etree
from io import StringIO
html = '''<table class="d">
    <tr>
        <td class="ah">supplier<td>
        <td class="ad">
            <a href="/S/3/143.html">Supplier 10</a>
        </td>
    </tr>
    <tr>
        <td class="ah">distributor<pre><td>
        <td class="ad">
            <a href="/D/3/143.html">Distributor 10</a>
        </td>
    </tr>
</table>'''

parser = etree.HTMLParser()
tree   = etree.parse(StringIO(html), parser)

data = tree.xpath('//tr[contains(.,"distributor")]//a/text()')
print (data)

Output : ['Distributor 10']

Alternative : use lxml html cleaner class ("remove_tags") to remove the pre element from your page.

References :

https://lxml.de/api/lxml.html.clean.Cleaner-class.html

https://lxml.de/lxmlhtml.html#cleaning-up-html


问:
How do I use variables from different methods
This is a grocery store problem that asks the user for what they are buying, how much of it and the price. The final price would then be calculated for each item (I have yet to do that for item 2 and 3)

I want to know how to use quantity1 and price1 from my getInfo() method into my calc() method.

The error code I get is :

```<code>   assignment_2.java:62: error: cannot find symbol
          double total1 = quantity1 * price1;
                          ^
      symbol:   variable quantity1
      location: class assignment_2
    assignment_2.java:62: error: cannot find symbol
          double total1 = quantity1 * price1;
                                      ^
      symbol:   variable price1
      location: class assignment_2
</code>```

My code :

```<code>import java.util.Scanner;
public class assignment_2
{
   public static void main(String[] args)
   {
      // Call methods here
      getInfo();
      calc();
   }

   public static void getInfo()
   {
      Scanner input = new Scanner(System.in);

      > Here I'm asking the user for the name of item 1
      // Item 1
      System.out.println("Name of item 1: ");
      String item1 = input.nextLine();

      > Here I'm asking the user for the quantity of item 1
      System.out.println("Quantity of item 1: ");
      int quantity1 = input.nextInt();

      > Here I'm asking the user for the price of item 1
      System.out.println("Price of item 1: ");
      double price1 = input.nextDouble();

      // Item 2
      Scanner input2 = new Scanner(System.in);

      System.out.println("Name of item 2: ");
      String item2 = input2.nextLine();

      System.out.println("Quantity of item 2: ");
      int quantity2 = input2.nextInt();

      System.out.println("Price of item 2: ");
      double price2 = input2.nextDouble();

      // Item 3
      Scanner input3 = new Scanner(System.in);

      System.out.println("Name of item 3: ");
      String item3 = input3.nextLine();

      System.out.println("Quantity of item 3: ");
      int quantity3 = input3.nextInt();

      System.out.println("Price of item 3: ");
      double price3 = input3.nextDouble();

      // Calculations
      // double total1 = quantity1 * price1;
      // System.out.println("Item 1 total: " + total1);

      // double total2 = quantity2 * price2;
      // System.out.println("Item 2 total: " + total2);

      // double total3 = quantity3 * price3;
      // System.out.println("Item 3 total: " + total3);
   }
   public static void calc()
   {
      double total1 = quantity1 * price1;
      System.out.println("Item 1 total: " + total1);
   }
}
</code>```

答:
Pass the param into your method

public static void getInfo() {
      // Item 3
      Scanner input3 = new Scanner(System.in);
      System.out.println("Name of item 3: ");
      String item3 = input3.nextLine();

      System.out.println("Quantity of item 3: ");
      int quantity3 = input3.nextInt();

      System.out.println("Price of item 3: ");
      double price3 = input3.nextDouble();
      double total = calc(quantity, price3);
}
public static double calc(int quantity, double price)
   {
      double total = quantity * price;
      System.out.println("Item 1 total: " + total1);
      return total
   }

```

Body:
This is a grocery store problem that asks the user for what they are buying, how much of it and the price. The final price would then be calculated for each item (I have yet to do that for item 2 and 3)

I want to know how to use quantity1 and price1 from my getInfo() method into my calc() method.

The error code I get is :

   assignment_2.java:62: error: cannot find symbol
          double total1 = quantity1 * price1;
                          ^
      symbol:   variable quantity1
      location: class assignment_2
    assignment_2.java:62: error: cannot find symbol
          double total1 = quantity1 * price1;
                                      ^
      symbol:   variable price1
      location: class assignment_2

My code :

import java.util.Scanner;
public class assignment_2
{
   public static void main(String[] args)
   {
      // Call methods here
      getInfo();
      calc();
   }

   public static void getInfo()
   {
      Scanner input = new Scanner(System.in);

      > Here I'm asking the user for the name of item 1
      // Item 1
      System.out.println("Name of item 1: ");
      String item1 = input.nextLine();

      > Here I'm asking the user for the quantity of item 1
      System.out.println("Quantity of item 1: ");
      int quantity1 = input.nextInt();

      > Here I'm asking the user for the price of item 1
      System.out.println("Price of item 1: ");
      double price1 = input.nextDouble();

      // Item 2
      Scanner input2 = new Scanner(System.in);

      System.out.println("Name of item 2: ");
      String item2 = input2.nextLine();

      System.out.println("Quantity of item 2: ");
      int quantity2 = input2.nextInt();

      System.out.println("Price of item 2: ");
      double price2 = input2.nextDouble();

      // Item 3
      Scanner input3 = new Scanner(System.in);

      System.out.println("Name of item 3: ");
      String item3 = input3.nextLine();

      System.out.println("Quantity of item 3: ");
      int quantity3 = input3.nextInt();

      System.out.println("Price of item 3: ");
      double price3 = input3.nextDouble();

      // Calculations
      // double total1 = quantity1 * price1;
      // System.out.println("Item 1 total: " + total1);

      // double total2 = quantity2 * price2;
      // System.out.println("Item 2 total: " + total2);

      // double total3 = quantity3 * price3;
      // System.out.println("Item 3 total: " + total3);
   }
   public static void calc()
   {
      double total1 = quantity1 * price1;
      System.out.println("Item 1 total: " + total1);
   }
}


问:
Make input invisible through css?
I have a form where depending on the website's brand one of two input fields should be visible at one given spot.

I figured I just put both input fields in the same container and then through my stylesheet set one of them to display:none;
This does hide the field, but it still makes it take up space.
I also tried setting the height and width to 0 or setting visibility to hidden or collapse but none of those worked.

Untill now all the branding things could be done with css style sheets so I would like to keep it that way.
The solution should at least be supported in IE6 & up, Firefox 2 & up and Chrome (latest).

答:
You can do this if you want to isolate the css code from other input:

```<code>input[type="checkbox"] {
    display: none;
}
</code>```

You can also further isolate it from the same type by indicating another class.

ContentLicense: CC BY-SA 2.5

Title: Make input invisible through css?

Body:
You can do this if you want to isolate the css code from other input:

input[type="checkbox"] {
    display: none;
}

You can also further isolate it from the same type by indicating another class.


问:
How to create shadow or elevation on TabBar?

I tried different options but unable to add the shadow like in the image:

```<code>TabBar(
        indicatorColor: Colors.transparent,
        indicatorSize: TabBarIndicatorSize.tab,
        unselectedLabelColor: inActiveColor,
        // Using BoxDecoration there is PADDING issue in Tabs
         indicator: BoxDecoration(
           borderRadius: BorderRadius.circular(50),
           color: hexToColor(primaryColorDark),
           boxShadow: [
             BoxShadow(
               color: Colors.grey.withOpacity(0.5),
               spreadRadius: 10,
               blurRadius: 10,
               offset: Offset(0, 10), // changes position of shadow
             ),
           ],
         ),
        tabs: <Tab>[
          Tab(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.create,
                  size: 20,
                ),
                Text('   ' + 'Form'),
              ],
            ),
          ),
          Tab(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.remove_red_eye,
                  size: 20,
                ),
                Text('   ' + 'Preview'),
              ],
            ),
          ),
        ],
      ),
</code>```

答:
try this not bad

```<code>@override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: SafeArea(
        child: Scaffold(
            appBar: PreferredSize(
              preferredSize: Size(MediaQuery.of(context).size.width, 500),
              child: Container(
                color: Colors.white,
                padding: const EdgeInsets.all(16),
                child: Row(
                  children: <Widget>[
                    Icon(Icons.arrow_back_ios,size: 30,),
                    SizedBox(
                      width: 16,
                    ),
                    Expanded(
                      child: TabBar(
                        indicatorColor: Colors.transparent,
                        indicatorSize: TabBarIndicatorSize.tab,
                        unselectedLabelColor: Colors.grey[400],
                        // Using BoxDecoration there is PADDING issue in Tabs
                        indicator: BoxDecoration(
                          borderRadius: BorderRadius.circular(50),
                          color: Colors.blueAccent,
                          boxShadow: [
                            BoxShadow(
                              color: Colors.deepPurple
                                  .withOpacity(0.3)
                                  .withBlue(150),
                              blurRadius: 25,
                              offset:
                                  Offset(0, 20), // changes position of shadow
                            ),
                          ],
                        ),
                        tabs: <Tab>[
                          Tab(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Icon(
                                  Icons.create,
                                  size: 20,
                                ),
                                Text('   ' + 'Form'),
                              ],
                            ),
                          ),
                          Tab(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Icon(
                                  Icons.remove_red_eye,
                                  size: 20,
                                ),
                                Text('   ' + 'Preview'),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            body: Container()),
      ),
    );
  }
</code>```

Body:
I tried different options but unable to add the shadow like in the image:

TabBar(
        indicatorColor: Colors.transparent,
        indicatorSize: TabBarIndicatorSize.tab,
        unselectedLabelColor: inActiveColor,
        // Using BoxDecoration there is PADDING issue in Tabs
         indicator: BoxDecoration(
           borderRadius: BorderRadius.circular(50),
           color: hexToColor(primaryColorDark),
           boxShadow: [
             BoxShadow(
               color: Colors.grey.withOpacity(0.5),
               spreadRadius: 10,
               blurRadius: 10,
               offset: Offset(0, 10), // changes position of shadow
             ),
           ],
         ),
        tabs: <Tab>[
          Tab(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.create,
                  size: 20,
                ),
                Text('   ' + 'Form'),
              ],
            ),
          ),
          Tab(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.remove_red_eye,
                  size: 20,
                ),
                Text('   ' + 'Preview'),
              ],
            ),
          ),
        ],
      ),

Body:
try this not bad

@override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: SafeArea(
        child: Scaffold(
            appBar: PreferredSize(
              preferredSize: Size(MediaQuery.of(context).size.width, 500),
              child: Container(
                color: Colors.white,
                padding: const EdgeInsets.all(16),
                child: Row(
                  children: <Widget>[
                    Icon(Icons.arrow_back_ios,size: 30,),
                    SizedBox(
                      width: 16,
                    ),
                    Expanded(
                      child: TabBar(
                        indicatorColor: Colors.transparent,
                        indicatorSize: TabBarIndicatorSize.tab,
                        unselectedLabelColor: Colors.grey[400],
                        // Using BoxDecoration there is PADDING issue in Tabs
                        indicator: BoxDecoration(
                          borderRadius: BorderRadius.circular(50),
                          color: Colors.blueAccent,
                          boxShadow: [
                            BoxShadow(
                              color: Colors.deepPurple
                                  .withOpacity(0.3)
                                  .withBlue(150),
                              blurRadius: 25,
                              offset:
                                  Offset(0, 20), // changes position of shadow
                            ),
                          ],
                        ),
                        tabs: <Tab>[
                          Tab(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Icon(
                                  Icons.create,
                                  size: 20,
                                ),
                                Text('   ' + 'Form'),
                              ],
                            ),
                          ),
                          Tab(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Icon(
                                  Icons.remove_red_eye,
                                  size: 20,
                                ),
                                Text('   ' + 'Preview'),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            body: Container()),
      ),
    );
  }


问:
How to drop a class (table) in Back4app Dashboard
I'm new to parse and back4app. While I'm trying to delete a class (table) in the dashboard, I can't find any menu item that allows me to do it. Can anybody point me to the right direction?

Also related, is it possible to change a column's name after it is added, and is it possible to bulk update rows for certain fields, all within the dashboard?

答: Well, actually I just found part of the answer. The "Delete this class" menu item is in the top right Edit menu, as shown in this screenshot:


问:
How to check if value is a positive number using Chai?
I'm trying to figure out how to check if a value is a positive number (bigger than zero) by using Chai. What I tried:

```<code>expect(5).that.is.a('number');
</code>```

But it also works for -5 and 0. I also tried to change to integer but js does not have this type. How can I check it?

答:
You can use above(val) to check if a number is above a value.

This will make sure that the value is both a number and that it's above whatever value you want. In this case, since you want it to be a positive value, we'll use above(0).

If you want to also check if it's a whole number, you can use expect(val % 1).to.equal(0) as shown in Chai Unittesting - expect(42).to.be.an('integer')

chai.expect(5).to.be.above(0)

try {
  chai.expect(-5).to.be.above(0)
} catch (error) {
  console.log(error.message);
}
try {
  chai.expect(0).to.be.above(0)
} catch (error) {
  console.log(error.message);
}

try {
  chai.expect('5').to.be.above(0)
} catch (error) {
  console.log(error.message);
}

try {
  let val = 2.5;
  chai.expect(val).to.be.above(0);
  chai.expect(val % 1,'to be a whole number').to.equal(0)
} catch (error) {
  console.log(error.message);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script></code>```

Body:
I'm trying to figure out how to check if a value is a positive number (bigger than zero) by using Chai. What I tried:

expect(5).that.is.a('number');

But it also works for -5 and 0. I also tried to change to integer but js does not have this type. How can I check it?

Body:
You can use above(val) to check if a number is above a value.

This will make sure that the value is both a number and that it's above whatever value you want. In this case, since you want it to be a positive value, we'll use above(0).

If you want to also check if it's a whole number, you can use expect(val % 1).to.equal(0) as shown in Chai Unittesting - expect(42).to.be.an('integer')

chai.expect(5).to.be.above(0)

try {
  chai.expect(-5).to.be.above(0)
} catch (error) {
  console.log(error.message);
}
try {
  chai.expect(0).to.be.above(0)
} catch (error) {
  console.log(error.message);
}

try {
  chai.expect('5').to.be.above(0)
} catch (error) {
  console.log(error.message);
}

try {
  let val = 2.5;
  chai.expect(val).to.be.above(0);
  chai.expect(val % 1,'to be a whole number').to.equal(0)
} catch (error) {
  console.log(error.message);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script>


问:
awk, if else conditional when record contains a value
I'm having trouble getting an awk if/else conditional to properly trigger when the record contains a value. Running this in zsh on Mac OS Catalina.

This script (issue is on second to last line)...

```<code>echo "abcdefgh" >  ./temp
echo "abc\"\(\"h" >> ./temp
echo "abcdefgh" >> ./temp
echo "abcde\(h" >> ./temp

val='"\("'
key="NEW_NEW"
file="./temp"

echo $val
echo $key
echo $file

echo ""
echo "###############"
echo ""

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    ($0 ~ /old/){ s=index($0,old); print substr($0,1,s-1) new substr($0,s+len) }{ print $0 }
' $val $key $file
</code>```

outputs:

```<code>"\("
NEW_NEW
./temp

###############

abcdefgh
abc"\("h
abcdefgh
abcde\(h
</code>```

I want to fix the script so that it changes the "\(" to NEW_NEW but skips the parenthesis without the quotes...

```<code>"\("
NEW_NEW
./temp

###############

abcdefgh
abcNEW_NEWh
abcdefgh
abcde\(h
</code>```

EDIT

This is an abbreviated version of the real script that I'm working on. The answer will need to include the variable expansions that the sample above has, in order for me to use the command in the larger script. The ARGV format in use is preserving special characters, so the main question I have is why the conditional isn’t triggered as expected.

答:
($0 ~ /old/) means "do a regexp comparison between the current record ($0) and the literal regexp old" so it matches when $0 contains the 3 characters o, l, d in that order. You probably were trying to do a regexp comparison against the contents of the variable named old which would be $0 ~ old (see How do I use shell variables in an awk script?) but you don't actually want that, you want a string comparison which would be index($0,old) as shown in your previous question (https://stackoverflow.com/a/62096075/1745001) but which you have now for some reason moved out of the condition part of your condition { action } awk statement and put it as the first part of the action instead. So don't do that.

The other major problem with your script is you're removing the quotes from around your shell variables so they're being interpreted by the shell and undergoing globbing, file name expansion, etc. before awk even gets to see them (see https://mywiki.wooledge.org/Quotes). So don't do that either.

Fixing just the parts I mentioned:

```<code>$ cat tst.sh
echo "abcdefgh" >  ./temp
echo "abc\"\(\"h" >> ./temp
echo "abcdefgh" >> ./temp
echo "abcde\(h" >> ./temp

val='"\("'
key="NEW_NEW"
file="./temp"

echo "$val"
echo "$key"
echo "$file"

echo ""
echo "###############"
echo ""

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$val" "$key" "$file"
</code>```

.

```<code>$ ./tst.sh
"\("
NEW_NEW
./temp

###############

abcdefgh
abcNEW_NEWh
abcdefgh
abcde\(h
</code>```

Body:
I'm having trouble getting an awk if/else conditional to properly trigger when the record contains a value. Running this in zsh on Mac OS Catalina.

This script (issue is on second to last line)...

echo "abcdefgh" >  ./temp
echo "abc\"\(\"h" >> ./temp
echo "abcdefgh" >> ./temp
echo "abcde\(h" >> ./temp

val='"\("'
key="NEW_NEW"
file="./temp"

echo $val
echo $key
echo $file

echo ""
echo "###############"
echo ""

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    ($0 ~ /old/){ s=index($0,old); print substr($0,1,s-1) new substr($0,s+len) }{ print $0 }
' $val $key $file

outputs:

"\("
NEW_NEW
./temp

###############

abcdefgh
abc"\("h
abcdefgh
abcde\(h

I want to fix the script so that it changes the "\(" to NEW_NEW but skips the parenthesis without the quotes...

"\("
NEW_NEW
./temp

###############

abcdefgh
abcNEW_NEWh
abcdefgh
abcde\(h

EDIT

This is an abbreviated version of the real script that I'm working on. The answer will need to include the variable expansions that the sample above has, in order for me to use the command in the larger script. The ARGV format in use is preserving special characters, so the main question I have is why the conditional isn’t triggered as expected.

Body:
($0 ~ /old/) means "do a regexp comparison between the current record ($0) and the literal regexp old" so it matches when $0 contains the 3 characters o, l, d in that order. You probably were trying to do a regexp comparison against the contents of the variable named old which would be $0 ~ old (see How do I use shell variables in an awk script?) but you don't actually want that, you want a string comparison which would be index($0,old) as shown in your previous question (https://stackoverflow.com/a/62096075/1745001) but which you have now for some reason moved out of the condition part of your condition { action } awk statement and put it as the first part of the action instead. So don't do that.

The other major problem with your script is you're removing the quotes from around your shell variables so they're being interpreted by the shell and undergoing globbing, file name expansion, etc. before awk even gets to see them (see https://mywiki.wooledge.org/Quotes). So don't do that either.

Fixing just the parts I mentioned:

$ cat tst.sh
echo "abcdefgh" >  ./temp
echo "abc\"\(\"h" >> ./temp
echo "abcdefgh" >> ./temp
echo "abcde\(h" >> ./temp

val='"\("'
key="NEW_NEW"
file="./temp"

echo "$val"
echo "$key"
echo "$file"

echo ""
echo "###############"
echo ""

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
    s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
    { print }
' "$val" "$key" "$file"

.

$ ./tst.sh
"\("
NEW_NEW
./temp

###############

abcdefgh
abcNEW_NEWh
abcdefgh
abcde\(h


问:
iOS, how to get subarray from an array using subarraywithRange
I am having problem with using subArrayWithRange.

Basically, what I want to do is make subarray of 50 elements or less from mainArray
for example if mainArray has 70 elements I want a sortedArray to have an array of first 50 elements in first index and another array of 20 elements in the last index of sortedArray

Hope I am clear what I want to do get.

anyway, my code is

```<code>for (int i=0; i<=ceilLoopCount; i++) {
    [sortedArray insertObject:[testArray subarrayWithRange:NSMakeRange(0,50)] atIndex:i];
}
</code>```

and the problem I am having is I only get the same 50 elements in all the array

Please help,
Pondd

答:
```<code>NSUInteger size = 50;

for (NSUInteger i = 0; i * size < [testArray count]; i++) {
  NSUInteger start = i * size;
  NSRange range = NSMakeRange(start, MIN([testArray count] - start, size));
  [sortedArray addObject:[testArray subarrayWithRange:range]];
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having problem with using subArrayWithRange.

Basically, what I want to do is make subarray of 50 elements or less from mainArray
for example if mainArray has 70 elements I want a sortedArray to have an array of first 50 elements in first index and another array of 20 elements in the last index of sortedArray

Hope I am clear what I want to do get.

anyway, my code is

for (int i=0; i<=ceilLoopCount; i++) {
    [sortedArray insertObject:[testArray subarrayWithRange:NSMakeRange(0,50)] atIndex:i];
}

and the problem I am having is I only get the same 50 elements in all the array

Please help,
Pondd


问:
Extend Express Request object using Typescript
I’m trying to add a property to express request object from a middleware using typescript. However I can’t figure out how to add extra properties to the object. I’d prefer to not use bracket notation if possible.

I’m looking for a solution that would allow me to write something similar to this (if possible):

```<code>app.use((req, res, next) => {
    req.property = setProperty();
    next();
});
</code>```

答:
To help anyone who is just looking for something else to try here is what worked for me in late May of 2020 when trying to extend ExpressJS' Request. I had to have tried more than a dozen things before getting this to work:

Flip the order of what everyone is recommending in the "typeRoots" of your tsconfig.json (and don't forget to drop the src pathing if you have a rootDir setting in tsconfig such as "./src"). Example:

"typeRoots": [
      "./node_modules/@types",
      "./your-custom-types-dir"
]
```

<ul>
<li>Example of custom extension ('./your-custom-types-dir/express/index.d.ts"). I had to use inline import and default exports to use classes as a type in my experience so that is shown too:</li>
</ul>

<pre class="lang-js prettyprint-override"><code>declare global {
  namespace Express {
    interface Request {
      customBasicProperty: string,
      customClassProperty: import("../path/to/CustomClass").default;
    }
  }
}
</code>```

Update your nodemon.json file to add the "--files" command to ts-node, example:

{
  "restartable": "rs",
  "ignore": [".git", "node_modules/**/node_modules"],
  "verbose": true,
  "exec": "ts-node --files",
  "watch": ["src/"],
  "env": {
    "NODE_ENV": "development"
  },
  "ext": "js,json,ts"
}
```

Body:
I’m trying to add a property to express request object from a middleware using typescript. However I can’t figure out how to add extra properties to the object. I’d prefer to not use bracket notation if possible.

I’m looking for a solution that would allow me to write something similar to this (if possible):

app.use((req, res, next) => {
    req.property = setProperty();
    next();
});

Body:
To help anyone who is just looking for something else to try here is what worked for me in late May of 2020 when trying to extend ExpressJS' Request. I had to have tried more than a dozen things before getting this to work:

Flip the order of what everyone is recommending in the "typeRoots" of your tsconfig.json (and don't forget to drop the src pathing if you have a rootDir setting in tsconfig such as "./src"). Example:

"typeRoots": [
      "./node_modules/@types",
      "./your-custom-types-dir"
]

Example of custom extension ('./your-custom-types-dir/express/index.d.ts"). I had to use inline import and default exports to use classes as a type in my experience so that is shown too:

declare global {
  namespace Express {
    interface Request {
      customBasicProperty: string,
      customClassProperty: import("../path/to/CustomClass").default;
    }
  }
}

Update your nodemon.json file to add the "--files" command to ts-node, example:

{
  "restartable": "rs",
  "ignore": [".git", "node_modules/**/node_modules"],
  "verbose": true,
  "exec": "ts-node --files",
  "watch": ["src/"],
  "env": {
    "NODE_ENV": "development"
  },
  "ext": "js,json,ts"
}


问:
How can I make my conditionals working in this JavaScript piece of code?
I'm writing some JavaScript code as part of my homework to create a password generator app and I have decided to put all the questions that I should ask from the user inside a function. One of the criteria to generate a password is to choose the number of characters between 8 and 128. I wanted to be sure that the user enters the correct number otherwise the function restarts and won't let the user see the rest of the confirm boxes until he enters the desired number so I wrote it like this:

```<code>function askQuestions() {
  let numOfChracaters = +prompt("Choose the number of characters for your password (between 8 and 128)");
  console.log(numOfChracaters);
  if (numOfChracaters >= 8 || numOfChracaters <= 128) {
    let hasUppercase = confirm("Do you want your password to include uppercase letters?");
    let hasLowercase = confirm("Do you want your password to include lowercase letters?");
    let hasNumber = confirm("Do you want your password to include numbers?");
    let hasSpecialCharacters = confirm("Do you want your password to include special characters?");

    let prefrencesArray = [numOfChracaters, hasUppercase, hasLowercase, hasNumber, hasSpecialCharacters];
    return prefrencesArray;
  } else {
    askQuestions();
  }
}
</code>```

But for some reason it doesn't work and still allows user to enter whatever number they want. Any ideas what did I do wrong here?

答:
replace conditional
 numOfChracaters >= 8 || numOfChracaters <= 128

 to
 numOfChracaters >= 8 && numOfChracaters <= 128

Body:
I'm writing some JavaScript code as part of my homework to create a password generator app and I have decided to put all the questions that I should ask from the user inside a function. One of the criteria to generate a password is to choose the number of characters between 8 and 128. I wanted to be sure that the user enters the correct number otherwise the function restarts and won't let the user see the rest of the confirm boxes until he enters the desired number so I wrote it like this:

function askQuestions() {
  let numOfChracaters = +prompt("Choose the number of characters for your password (between 8 and 128)");
  console.log(numOfChracaters);
  if (numOfChracaters >= 8 || numOfChracaters <= 128) {
    let hasUppercase = confirm("Do you want your password to include uppercase letters?");
    let hasLowercase = confirm("Do you want your password to include lowercase letters?");
    let hasNumber = confirm("Do you want your password to include numbers?");
    let hasSpecialCharacters = confirm("Do you want your password to include special characters?");

    let prefrencesArray = [numOfChracaters, hasUppercase, hasLowercase, hasNumber, hasSpecialCharacters];
    return prefrencesArray;
  } else {
    askQuestions();
  }
}

But for some reason it doesn't work and still allows user to enter whatever number they want. Any ideas what did I do wrong here?


答:
You can use an infinite loop to run till the requirements are met</p>

```<code>let numOfChracaters = 0;
while(numOfChracaters < 8) {
  numOfChracaters = +prompt("Choose the number of characters for your password (between 8 and 128)");
}
</code>```

Title: How can I make my conditionals working in this JavaScript piece of code?

Body:
You can use an infinite loop to run till the requirements are met

let numOfChracaters = 0;
while(numOfChracaters < 8) {
  numOfChracaters = +prompt("Choose the number of characters for your password (between 8 and 128)");
}


问:
How to transfer a complex C struct to C from Go
I am writing gobinding for a private project

there is a typedef struct like this.

```<code>typedef struct {
skynet_risk_t risk;
.....
const void *unknown[13];
} skynet_result_t;
</code>```

when I try passing this struct into a func
skynet_status_t skynet_classify(
......,
skynet_result_t *result);

I write like this

```<code>result := C.skynet_result_t{}
status = C.skynet_classify(
    ...
    &result,
)
</code>```

I got this
cannot use _cgo2 (type *_Ctype_char) as type unsafe.Pointer in argument to _Cfunc_skynet_classify

but when I write a func like this

void print_skynet_result(skynet_result_t *result){
    // do nothing
}
```

<p>and I call it in same way.</p>

```result := C.skynet_result_t{}
C.print_skynet_result(&result)
```

compile through and everything is ok.
what's the trouble I encountered

I don't know why cgo say it is a (type *_Ctype_char)

答:
the compiler always said

```<code>./skynet.go:266:14: cannot use _cgo2 (type *_Ctype_char) as type unsafe.Pointer in argument to _Cfunc_skynet_classify
</code>```

the line is error …… I never thought about this.

the origin func define like this.

```<code>skynet_status_t skynet_classify(skynet_request_t *req,
skynet_classify_type_t type,
const void *data,
size_t length,
skynet_result_t *result);
</code>```

and I define a wrapper like this one.

```<code>func (s *skynetRequest) Classify(t uint32, data []byte) (*skynetResult, error) {
    var result skynetResult
    // var temp = C.pass_skynet_result_t((*C.skynet_result_t)(&result))
    var status = C.skynet_classify(
        (*C.skynet_request_t)(s),
        (C.uint)(t),
        unsafe.Pointer(&data[0]),
        C.ulong(len(data)),
        (*C.skynet_result_t)(&result),
    )
    if status != 0 {
        return &result, errors.New("classify error")
    }
    return &result, nil
}
</code>```

@user2089648 reminded me, this may not cause by result parameter, but may cause by other parameter，then I find the const void *data should be transfer like this
unsafe.Pointer(&data[0])，wrapper works well.

Body:
I am writing gobinding for a private project

there is a typedef struct like this.

typedef struct {
skynet_risk_t risk;
.....
const void *unknown[13];
} skynet_result_t;

when I try passing this struct into a func
skynet_status_t skynet_classify(
......,
skynet_result_t *result);

I write like this

result := C.skynet_result_t{}
status = C.skynet_classify(
    ...
    &result,
)

I got this
cannot use _cgo2 (type *_Ctype_char) as type unsafe.Pointer in argument to _Cfunc_skynet_classify

but when I write a func like this

void print_skynet_result(skynet_result_t *result){
    // do nothing
}

and I call it in same way.

result := C.skynet_result_t{}
C.print_skynet_result(&result)

compile through and everything is ok.
what's the trouble I encountered

I don't know why cgo say it is a (type *_Ctype_char)

Body:
the compiler always said

./skynet.go:266:14: cannot use _cgo2 (type *_Ctype_char) as type unsafe.Pointer in argument to _Cfunc_skynet_classify

the line is error …… I never thought about this.

the origin func define like this.

skynet_status_t skynet_classify(skynet_request_t *req,
skynet_classify_type_t type,
const void *data,
size_t length,
skynet_result_t *result);

and I define a wrapper like this one.

func (s *skynetRequest) Classify(t uint32, data []byte) (*skynetResult, error) {
    var result skynetResult
    // var temp = C.pass_skynet_result_t((*C.skynet_result_t)(&result))
    var status = C.skynet_classify(
        (*C.skynet_request_t)(s),
        (C.uint)(t),
        unsafe.Pointer(&data[0]),
        C.ulong(len(data)),
        (*C.skynet_result_t)(&result),
    )
    if status != 0 {
        return &result, errors.New("classify error")
    }
    return &result, nil
}

@user2089648 reminded me, this may not cause by result parameter, but may cause by other parameter，then I find the const void *data should be transfer like this
unsafe.Pointer(&data[0])，wrapper works well.


答:
You have made a funny mistake. Every number is either >= 8 OR <= 128.

What you're looking for is && operator, because both sides need to be true at the same time.


问:
jQuery e ColorBox
Hello ppl I'm having a little problem in integrating colorbox , then is this , I have a code that loads the data into a list, after the data loaded I can just click on the title to edit, the edit form to be loaded by this plugin colorbox till here all right , after closing the colorbox it reloads the data again, and if you try to edit another item he 's not let this error :

```<code>     $.colorbox is not a function
[Parar Neste Erro] onClosed: function () {
</code>```

My current code is this :

```<code>$("a[href*='#tabsDadosSoftware']").click(function () {
    CarregarDadosSoftware();
});

function CarregarDadosSoftware() {
    $.ajax({
        url: 'ajax/Software.php',
        cache: false,
        data: "acc=Visualizar&idpc=<?php echo (int)$_GET["id"]; ?>",
        type: 'GET',
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        beforeSend: function () {
            $('div#ListagemSoftware > div.Informacoes .load').show();
            $('div#ListagemSoftware > div.Informacoes > ul').html("");
        },
        success: function (result) {
            $('div#ListagemSoftware > div.Informacoes .load').hide();
            $('div#ListagemSoftware > div.Informacoes > ul').html(result)
        }
    });
}
$("div#ListagemSoftware > div.Informacoes > ul > li > .titulo").live('click', function () {
        var IDSoftware = $(this).parent().attr("id");
    $.colorbox({
        href: "ajax/Software.php?acc=Editar&idpc=<?php echo (int)$_GET["id"]; ?>&id="+IDSoftware,
        onClosed: function () {
                                CarregarDadosSoftware();
        }
    });
});
</code>```

And now leave a video on youtube with the demonstration of error

http://www.youtube.com/watch?v=AXOG5nec8_M

Greetings

答:
My bet would be that either this:
url: 'ajax/Software.php',

Or this:
href: "ajax/Software.php?acc=Editar&idpc=&id="+IDSoftware

Is opening a file that contains a script block pointing to jQuery.  Since you are using ajax (instead of sandboxing it with an iframe), the recently loaded version of jQuery replaces your original document's version of jQuery.  That first version of jQuery was extended with the colorbox plugin, when it is replaced, $.colorbox is lost.

Since you already have jQuery in your original document, you don't need another copy in the markup you are loading through ajax.

Title: jQuery e ColorBox

Body:
Hello ppl I'm having a little problem in integrating colorbox , then is this , I have a code that loads the data into a list, after the data loaded I can just click on the title to edit, the edit form to be loaded by this plugin colorbox till here all right , after closing the colorbox it reloads the data again, and if you try to edit another item he 's not let this error :

     $.colorbox is not a function
[Parar Neste Erro] onClosed: function () {

My current code is this :

$("a[href*='#tabsDadosSoftware']").click(function () {
    CarregarDadosSoftware();
});

function CarregarDadosSoftware() {
    $.ajax({
        url: 'ajax/Software.php',
        cache: false,
        data: "acc=Visualizar&idpc=<?php echo (int)$_GET["id"]; ?>",
        type: 'GET',
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        beforeSend: function () {
            $('div#ListagemSoftware > div.Informacoes .load').show();
            $('div#ListagemSoftware > div.Informacoes > ul').html("");
        },
        success: function (result) {
            $('div#ListagemSoftware > div.Informacoes .load').hide();
            $('div#ListagemSoftware > div.Informacoes > ul').html(result)
        }
    });
}
$("div#ListagemSoftware > div.Informacoes > ul > li > .titulo").live('click', function () {
        var IDSoftware = $(this).parent().attr("id");
    $.colorbox({
        href: "ajax/Software.php?acc=Editar&idpc=<?php echo (int)$_GET["id"]; ?>&id="+IDSoftware,
        onClosed: function () {
                                CarregarDadosSoftware();
        }
    });
});

And now leave a video on youtube with the demonstration of error

http://www.youtube.com/watch?v=AXOG5nec8_M

Greetings


问:
Failed to load resource: the server responded with a status of 400 (Bad Request): on Angular + NodeJS
I have an Angular and NodeJS application with Express (v4.17.1). I expose a REST API like this:

```<code>app.get('/myRestApi', function (req, res)
{
  console.log('here you are ... ');
  res.end('success!\n');
});
</code>```

and the body of this API contains these parameters:

```<code>{"name":"Joe",
 "surname":"Soap",
 "coordinate":"ASNDNFNS;SDFGSDFGSDF;ASFRTGERG;SERFQEAWE"}
</code>```

The issue is that when I receive the coordinate field larger than a certain amount (so a lot of these ASFRTGERG;SERFQEAWE) I get the error on the browser (regardless the browser):

```<code>The server responded with a status of 400 (Bad Request).
</code>```

As I do not get the console.log('here you are ... '); log I suppose NodeJS discards it returning 400. I'm pretty sure NodeJS returns this as on the browser I get:

```<code>HTTP/1.1 400 Bad Request
Access-Control-Allow-Origin: *
Content-Length: 0
Connection: keep-alive
X-Powered-By: Express
Strict-Transport-Security: max-age=31536000
</code>```

****UPDATE****

I've set the DEBUG level on NodeJS and the request never get to the backend so the problem is in the Angular side I believe. At one point on the Angular side I do this:

```<code>window.location.href = this.url;   //this.url = /myRestApi
</code>```

which navigates to the /myRestApi URL. I believe that window.location.href mechanism got a problem here as one field of the body of this request (see above) is too big then it crashes? ... or something that cause 400.

Suggestions?

答:
I've found the issue and the problem was that the HTTP GET sent to the backend was too big. After a deeper analysis, I've seen that the cookie made a huge difference in my case.

I've fixed it by increasing the max HTTP header size:

```<code>node --max-http-header-size 21000 application.js
</code>```

Body:
I have an Angular and NodeJS application with Express (v4.17.1). I expose a REST API like this:

app.get('/myRestApi', function (req, res)
{
  console.log('here you are ... ');
  res.end('success!\n');
});

and the body of this API contains these parameters:

{"name":"Joe",
 "surname":"Soap",
 "coordinate":"ASNDNFNS;SDFGSDFGSDF;ASFRTGERG;SERFQEAWE"}

The issue is that when I receive the coordinate field larger than a certain amount (so a lot of these ASFRTGERG;SERFQEAWE) I get the error on the browser (regardless the browser):

The server responded with a status of 400 (Bad Request).

As I do not get the console.log('here you are ... '); log I suppose NodeJS discards it returning 400. I'm pretty sure NodeJS returns this as on the browser I get:

HTTP/1.1 400 Bad Request
Access-Control-Allow-Origin: *
Content-Length: 0
Connection: keep-alive
X-Powered-By: Express
Strict-Transport-Security: max-age=31536000

****UPDATE****

I've set the DEBUG level on NodeJS and the request never get to the backend so the problem is in the Angular side I believe. At one point on the Angular side I do this:

window.location.href = this.url;   //this.url = /myRestApi

which navigates to the /myRestApi URL. I believe that window.location.href mechanism got a problem here as one field of the body of this request (see above) is too big then it crashes? ... or something that cause 400.

Suggestions?

Body:
I've found the issue and the problem was that the HTTP GET sent to the backend was too big. After a deeper analysis, I've seen that the cookie made a huge difference in my case.

I've fixed it by increasing the max HTTP header size:

node --max-http-header-size 21000 application.js


问:
How to initialize a two-dimensional array in Python?
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this:

```<code>def initialize_twodlist(foo):
    twod_list = []
    new = []
    for i in range (0, 10):
        for j in range (0, 10):
            new.append(foo)
        twod_list.append(new)
        new = []
</code>```

It gives the desired result, but feels like a workaround. Is there an easier/shorter/more elegant way to do this?

答:
Another way is to use a dictionary to hold a two-dimensional array.

```<code>twoD = {}
twoD[0,0] = 0
print(twoD[0,0]) # ===> prints 0
</code>```

This just can hold any 1D, 2D values and to initialize this to 0 or any other int value, use collections.

```<code>import collections
twoD = collections.defaultdict(int)
print(twoD[0,0]) # ==> prints 0
twoD[1,1] = 1
print(twoD[1,1]) # ==> prints 1
</code>```

Body:
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this:

def initialize_twodlist(foo):
    twod_list = []
    new = []
    for i in range (0, 10):
        for j in range (0, 10):
            new.append(foo)
        twod_list.append(new)
        new = []

It gives the desired result, but feels like a workaround. Is there an easier/shorter/more elegant way to do this?

Body:
Another way is to use a dictionary to hold a two-dimensional array.

twoD = {}
twoD[0,0] = 0
print(twoD[0,0]) # ===> prints 0

This just can hold any 1D, 2D values and to initialize this to 0 or any other int value, use collections.

import collections
twoD = collections.defaultdict(int)
print(twoD[0,0]) # ==> prints 0
twoD[1,1] = 1
print(twoD[1,1]) # ==> prints 1


问:
Get an image to display when hovering over an div
I have a div tag that looks like this:

EXCPERIENCES

Websites, Ecommerce, Mobile Apps &
Installations

```

<p>I want the image (ski) to display when i hover over </p>

<pre class="lang-html prettyprint-override"><code><div id="left">
</code>```

and when I don't have
the mouse over the "left" div the image should disappear.

This div called "left" is an childbox in a bigger parent box called "middle", when I hover the "left" div the picture should be visible over the entire "middle" which is the parent.

I have tried different solutions bust most of them is for a  or an  tag.

I can explain better if necessary and I don't need to show css, I'm only looking for a solution on how to do it, I'm familiar with JS.

to summarize I want a picture to be invisible until hovering over the box/div called "left" I don't want the picture to show only when
  hovering the text, and when hovering the "left" the picture should be
  shown and displayed, the rest I can figure out myself.

答:
```<code><!DOCTYPE html>
<html>
    <div id="left">
       <p class="h1">EXPERIENCES</p>

       <p class="describe">Websites, Ecommerce, Mobile Apps & <br />Installations</p>

       <img id="img1"src="ski.jpg" alt="ski">
    </div>

<script>
    document.getElementById("left").onmouseover = function() {showImage()};
    document.getElementById("left").onmouseout = function() {hideImage()};

    function showImage() {
      document.getElementById("img1").setAttribute("style", "visibility: hidden");
    }

    function hideImage() {
      document.getElementById("img1").setAttribute("style", "visibility: visible");
    }
</script>

</html>
</code>```

This code should work, also I fixed your spelling mistake regarding the word "experiences". Enjoy bud :)

Body:
I have a div tag that looks like this:

EXCPERIENCES

Websites, Ecommerce, Mobile Apps &
Installations

I want the image (ski) to display when i hover over

and when I don't have
the mouse over the "left" div the image should disappear.

This div called "left" is an childbox in a bigger parent box called "middle", when I hover the "left" div the picture should be visible over the entire "middle" which is the parent.

I have tried different solutions bust most of them is for a  or an  tag.

I can explain better if necessary and I don't need to show css, I'm only looking for a solution on how to do it, I'm familiar with JS.

to summarize I want a picture to be invisible until hovering over the box/div called "left" I don't want the picture to show only when
  hovering the text, and when hovering the "left" the picture should be
  shown and displayed, the rest I can figure out myself.

Body:
<!DOCTYPE html>
<html>
    <div id="left">
       <p class="h1">EXPERIENCES</p>

       <p class="describe">Websites, Ecommerce, Mobile Apps & <br />Installations</p>

       <img id="img1"src="ski.jpg" alt="ski">
    </div>

<script>
    document.getElementById("left").onmouseover = function() {showImage()};
    document.getElementById("left").onmouseout = function() {hideImage()};

    function showImage() {
      document.getElementById("img1").setAttribute("style", "visibility: hidden");
    }

    function hideImage() {
      document.getElementById("img1").setAttribute("style", "visibility: visible");
    }
</script>

</html>

This code should work, also I fixed your spelling mistake regarding the word "experiences". Enjoy bud :)


问:
PokeAPI - Fetching Pokemon Data
I have just started to learn React and I am trying to build a PokeDex using the PokeAPI, but I am having an extremely hard time understanding how to fetch data from the API. I want to fetch the first 384 Pokemon related information. I have written this code below in componentDidMount() to extract the complete data in my main App class component, and push it to an array called pokemonArray which I will set to my state.

```<code>let pokemonArray = [];
/* First API fetch call to return names and URL's of first 384 Pokemon after promise is resolved.*/
fetch('https://pokeapi.co/api/v2/pokemon/?limit=384')
  .then(response => response.json())
  .then(data => {
    let results = data.results;
    let promisesArray = results.map(result => {
      return fetch(result.url).then(response => response.json()).then(data => pokemonArray.push(data));
    })
    return Promise.all(promisesArray)
  }).then(this.setState({ pokemon: pokemonArray }, () => console.log('Main Pokemon State: ', this.state.pokemon)));

}
</code>```

In my render method I want to pass this newly set state as a prop to a component called PokeList like so

```<code><PokeList pokemon={this.state.pokemon} />
</code>```

Once I pass it on and I try to render it out in my PokeList component like so

```<code>export const PokeList = ({ pokemon }) => {
    console.log(pokemon);

    return (
        <div className="pokecard-container">
            <h1>{pokemon[0].id}</h1>
        </div>
    );
}
</code>```

I get an error that says TypeError: Cannot read property '0' of null. The React Developer tools shows the state being populated with the retrieved values as well as the props being set as well, but it seems to consider it null. Could anyone please help out with this, it's been so frustrating to see this error out

答:
There are two issues with your code. First, here's a modified working version:

fetch('https://pokeapi.co/api/v2/pokemon/?limit=2')
  .then(response => response.json())
  .then(data => {
    let results = data.results;
    let promisesArray = results.map(result => {
      return fetch(result.url).then(response => response.json());
    })
    return Promise.all(promisesArray);
  }).then((data) => this.setState({ pokemon: data }, () => console.log('Main Pokemon State: ', this.state.pokemon)));
```

<p>And the explanation:</p>

<p><strong>Issue 1:</strong></p>

<p>Original code:</p>

<pre class="lang-js prettyprint-override"><code>let promisesArray = results.map(result => {
  return fetch(result.url).then(response => response.json()).then(data => pokemonArray.push(data));
})
return Promise.all(promisesArray)
</code>```

The last then() callback returns the results of pokemonArray.push(data). Array.push returns the length of the array, so return Promise.all(promisesArray) returns an array of array lengths.

Change it to:

let promisesArray = results.map(result => {
  return fetch(result.url).then(response => response.json()); // Returns the data
})
return Promise.all(promisesArray)
```

<p><strong>Issue 2:</strong></p>

<p>Original code:</p>

<pre class="lang-js prettyprint-override"><code>then(this.setState({ pokemon: pokemonArray }, () => console.log('Main Pokemon State: ', this.state.pokemon)));
</code>```

You must supply a callback function to then():

.then((data) => this.setState({ pokemon: data }, () => console.log('Main Pokemon State: ', this.state.pokemon)));
```

<p>You must also remember to initialize the state when your component is created:</p>

<pre class="lang-js prettyprint-override"><code>constructor(props) {
  super(props);

  this.state = {
    pokemon: [],
  };
}
</code>```

Thus, when you render PokeList (<PokeList pokemon={this.state.pokemon} />), it will always receive an array, though it will be empty until the data is fetched.

Title: PokeAPI - Fetching Pokemon Data

Body:
I have just started to learn React and I am trying to build a PokeDex using the PokeAPI, but I am having an extremely hard time understanding how to fetch data from the API. I want to fetch the first 384 Pokemon related information. I have written this code below in componentDidMount() to extract the complete data in my main App class component, and push it to an array called pokemonArray which I will set to my state.

let pokemonArray = [];
/* First API fetch call to return names and URL's of first 384 Pokemon after promise is resolved.*/
fetch('https://pokeapi.co/api/v2/pokemon/?limit=384')
  .then(response => response.json())
  .then(data => {
    let results = data.results;
    let promisesArray = results.map(result => {
      return fetch(result.url).then(response => response.json()).then(data => pokemonArray.push(data));
    })
    return Promise.all(promisesArray)
  }).then(this.setState({ pokemon: pokemonArray }, () => console.log('Main Pokemon State: ', this.state.pokemon)));

}

In my render method I want to pass this newly set state as a prop to a component called PokeList like so

<PokeList pokemon={this.state.pokemon} />

Once I pass it on and I try to render it out in my PokeList component like so

export const PokeList = ({ pokemon }) => {
    console.log(pokemon);

    return (

{pokemon[0].id}

    );
}

I get an error that says TypeError: Cannot read property '0' of null. The React Developer tools shows the state being populated with the retrieved values as well as the props being set as well, but it seems to consider it null. Could anyone please help out with this, it's been so frustrating to see this error out

Body:
There are two issues with your code. First, here's a modified working version:

fetch('https://pokeapi.co/api/v2/pokemon/?limit=2')
  .then(response => response.json())
  .then(data => {
    let results = data.results;
    let promisesArray = results.map(result => {
      return fetch(result.url).then(response => response.json());
    })
    return Promise.all(promisesArray);
  }).then((data) => this.setState({ pokemon: data }, () => console.log('Main Pokemon State: ', this.state.pokemon)));

And the explanation:

Issue 1:

Original code:

let promisesArray = results.map(result => {
  return fetch(result.url).then(response => response.json()).then(data => pokemonArray.push(data));
})
return Promise.all(promisesArray)

The last then() callback returns the results of pokemonArray.push(data). Array.push returns the length of the array, so return Promise.all(promisesArray) returns an array of array lengths.

Change it to:

let promisesArray = results.map(result => {
  return fetch(result.url).then(response => response.json()); // Returns the data
})
return Promise.all(promisesArray)

Issue 2:

Original code:

then(this.setState({ pokemon: pokemonArray }, () => console.log('Main Pokemon State: ', this.state.pokemon)));

You must supply a callback function to then():

.then((data) => this.setState({ pokemon: data }, () => console.log('Main Pokemon State: ', this.state.pokemon)));

You must also remember to initialize the state when your component is created:

constructor(props) {
  super(props);

  this.state = {
    pokemon: [],
  };
}

Thus, when you render PokeList (<PokeList pokemon={this.state.pokemon} />), it will always receive an array, though it will be empty until the data is fetched.


问:
Why does nn.CrossEntropyLoss throw "TypeError: iteration over a 0-d tensor" when I verify inputs to be non-0-dimensional?
I am using PyTorch version 1.5.0.
When I pass an input torch tensor of size [8,21,400,400] with a target of size [8,400,400], the program raises a TypeError: iteration over a 0-d tensor. However, the dimensions of the arguments are 4 and 3 respectively.

What could be causing this error?

The traceback points to torch\tensor.py's iter function.

```<code>Traceback (most recent call last):
  File "train.py", line 108, in <module>
    loss, accuracy = lossLayer(pred2, targetBatch)
  File "C:\Users\PC\anaconda3\lib\site-packages\torch\tensor.py", line 462, in __iter__
    raise TypeError('iteration over a 0-d tensor')
TypeError: iteration over a 0-d tensor
</code>```

答: You get the error because nn.CrossEntropyLoss just returns one torch.Tensor, not a pair (it doesn't return accuracy). And this tensor is 0-dimensional, i.e. one number (unless you don't override reduction argument to 'none' to get per-element loss). So when you try to assign its value to two variables loss, accuracy python tries to iterate over this tensor variable, hence the error message. Simply use loss = lossLayer(pred2, targetBatch).

Body:
I am using PyTorch version 1.5.0.
When I pass an input torch tensor of size [8,21,400,400] with a target of size [8,400,400], the program raises a TypeError: iteration over a 0-d tensor. However, the dimensions of the arguments are 4 and 3 respectively.

What could be causing this error?

The traceback points to torch\tensor.py's iter function.

Traceback (most recent call last):
  File "train.py", line 108, in <module>
    loss, accuracy = lossLayer(pred2, targetBatch)
  File "C:\Users\PC\anaconda3\lib\site-packages\torch\tensor.py", line 462, in __iter__
    raise TypeError('iteration over a 0-d tensor')
TypeError: iteration over a 0-d tensor


问:
Why does this golang pointer address not change when replaced in goroutine?
It's my understanding that when I create an object with the foo := &bar{} I'm allocating new memory for that object. Why then, when I attempt to replace *foo in a goroutine does it not get a new pointer address?

package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
)

type pointerToObjects struct {
    objs *objects
}
type objects struct {
    sliceOfObject []*object
}
type object struct {
    number  int
    boolean bool
}

func main() {
    p := &pointerToObjects{objs: newObjects()}
    mu := &sync.Mutex{}

    for _, o := range p.objs.sliceOfObject {
        o.setBool(true)
    }
    // goroutine 1
    go func() {
        ticker := time.NewTicker(time.Second)
        defer ticker.Stop()
        for range ticker.C {
            mu.Lock()
            fmt.Printf("objects pointer: %v\n", &p.objs)
            for i, o := range p.objs.sliceOfObject {
                fmt.Printf("i: %d p: %v n: %d b: %t\n", i, &o, o.number, o.boolean)
            }
            fmt.Print("---\n")
            mu.Unlock()
        }
    }()
    // goroutine 2
    go func() {
        ticker := time.NewTicker(time.Second * 2)
        defer ticker.Stop()
        for range ticker.C {
            newObjects := &objects{sliceOfObject: newSliceOfObject()}
            mu.Lock()
            p.objs = newObjects
            mu.Unlock()
            fmt.Printf("replaced: %v <-- %v \n", &p.objs, &newObjects)
        }
    }()

    // let the goroutines run for 10 seconds
    time.Sleep(time.Second * 10)
}
func newObjects() *objects {
    objs := &objects{}
    objs.sliceOfObject = newSliceOfObject()
    return objs
}

func newSliceOfObject() []*object {
    var sliceObjs []*object
    for i := 0; i < 3; i++ {
        sliceObjs = append(sliceObjs, newObject())
    }
    return sliceObjs
}
func newObject() *object {
    return &object{number: rand.Int()}
}

func (obj *object) setBool(b bool) {
    obj.boolean = b
}

```
<p>playground link</p>
<p>actual:</p>
```objects pointer: 0xc00000e030
i: 0 p: 0xc00009a010 n: 5577006791947779410 b: true
i: 1 p: 0xc00009a010 n: 8674665223082153551 b: true
i: 2 p: 0xc00009a010 n: 6129484611666145821 b: true
---
replaced: 0xc00000e030 <-- 0xc00000e040
objects pointer: 0xc00000e030
i: 0 p: 0xc00000e050 n: 4037200794235010051 b: false
i: 1 p: 0xc00000e050 n: 3916589616287113937 b: false
i: 2 p: 0xc00000e050 n: 6334824724549167320 b: false
```
<p>expected:</p>
```objects pointer: 0xc00000e030
i: 0 p: 0xc00009a010 n: 5577006791947779410 b: true
i: 1 p: 0xc00009a010 n: 8674665223082153551 b: true
i: 2 p: 0xc00009a010 n: 6129484611666145821 b: true
---
replaced: 0xc00000e030 <-- 0xc00000e040
objects pointer: 0xc00000e040
i: 0 p: 0xc00000e050 n: 4037200794235010051 b: false
i: 1 p: 0xc00000e050 n: 3916589616287113937 b: false
i: 2 p: 0xc00000e050 n: 6334824724549167320 b: false
```

when run, the values update as I would expect, but the pointer in p to objects remains unchanged. I would expect it to be updated when I call *p.objs = *newObjects

is this a trick of the compiler? How can I get "objects pointer" to update to the new location? do I need to use more explicit pointers to pointers?

EDIT: fixed race condition and tried to assigned with p.objs = newObjects without success.

答:
With the exception of the printed output, the program works as you expect.

To print the value of a variable, use the variable in the fmt.Printf argument list. Do not pass the address of the variable.  The value of a variable and the address of a variable are different things.

To best view pointers, print pointers with the %p verb instead of %v.

Here's one example. Change

```<code>        fmt.Printf("replaced: %v <-- %v \n", &p.objs, &newObjects)
</code>```

to

```<code>        fmt.Printf("replaced: %p <-- %p \n", p.objs, newObjects)
</code>```

The issue unrelated to the use of goroutines as mentioned in the title.

Body:
It's my understanding that when I create an object with the foo := &bar{} I'm allocating new memory for that object. Why then, when I attempt to replace *foo in a goroutine does it not get a new pointer address?

package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
)

type pointerToObjects struct {
    objs *objects
}
type objects struct {
    sliceOfObject []*object
}
type object struct {
    number  int
    boolean bool
}

func main() {
    p := &pointerToObjects{objs: newObjects()}
    mu := &sync.Mutex{}

    for _, o := range p.objs.sliceOfObject {
        o.setBool(true)
    }
    // goroutine 1
    go func() {
        ticker := time.NewTicker(time.Second)
        defer ticker.Stop()
        for range ticker.C {
            mu.Lock()
            fmt.Printf("objects pointer: %v\n", &p.objs)
            for i, o := range p.objs.sliceOfObject {
                fmt.Printf("i: %d p: %v n: %d b: %t\n", i, &o, o.number, o.boolean)
            }
            fmt.Print("---\n")
            mu.Unlock()
        }
    }()
    // goroutine 2
    go func() {
        ticker := time.NewTicker(time.Second * 2)
        defer ticker.Stop()
        for range ticker.C {
            newObjects := &objects{sliceOfObject: newSliceOfObject()}
            mu.Lock()
            p.objs = newObjects
            mu.Unlock()
            fmt.Printf("replaced: %v <-- %v \n", &p.objs, &newObjects)
        }
    }()

    // let the goroutines run for 10 seconds
    time.Sleep(time.Second * 10)
}
func newObjects() *objects {
    objs := &objects{}
    objs.sliceOfObject = newSliceOfObject()
    return objs
}

func newSliceOfObject() []*object {
    var sliceObjs []*object
    for i := 0; i < 3; i++ {
        sliceObjs = append(sliceObjs, newObject())
    }
    return sliceObjs
}
func newObject() *object {
    return &object{number: rand.Int()}
}

func (obj *object) setBool(b bool) {
    obj.boolean = b
}

playground link

actual:

objects pointer: 0xc00000e030
i: 0 p: 0xc00009a010 n: 5577006791947779410 b: true
i: 1 p: 0xc00009a010 n: 8674665223082153551 b: true
i: 2 p: 0xc00009a010 n: 6129484611666145821 b: true
---
replaced: 0xc00000e030 <-- 0xc00000e040
objects pointer: 0xc00000e030
i: 0 p: 0xc00000e050 n: 4037200794235010051 b: false
i: 1 p: 0xc00000e050 n: 3916589616287113937 b: false
i: 2 p: 0xc00000e050 n: 6334824724549167320 b: false

expected:

objects pointer: 0xc00000e030
i: 0 p: 0xc00009a010 n: 5577006791947779410 b: true
i: 1 p: 0xc00009a010 n: 8674665223082153551 b: true
i: 2 p: 0xc00009a010 n: 6129484611666145821 b: true
---
replaced: 0xc00000e030 <-- 0xc00000e040
objects pointer: 0xc00000e040
i: 0 p: 0xc00000e050 n: 4037200794235010051 b: false
i: 1 p: 0xc00000e050 n: 3916589616287113937 b: false
i: 2 p: 0xc00000e050 n: 6334824724549167320 b: false

when run, the values update as I would expect, but the pointer in p to objects remains unchanged. I would expect it to be updated when I call *p.objs = *newObjects

is this a trick of the compiler? How can I get "objects pointer" to update to the new location? do I need to use more explicit pointers to pointers?

EDIT: fixed race condition and tried to assigned with p.objs = newObjects without success.

Body:
With the exception of the printed output, the program works as you expect.

To print the value of a variable, use the variable in the fmt.Printf argument list. Do not pass the address of the variable.  The value of a variable and the address of a variable are different things.

To best view pointers, print pointers with the %p verb instead of %v.

Here's one example. Change

        fmt.Printf("replaced: %v <-- %v \n", &p.objs, &newObjects)

to

        fmt.Printf("replaced: %p <-- %p \n", p.objs, newObjects)

The issue unrelated to the use of goroutines as mentioned in the title.


问:
Unable to import torch (ImportError: libcudart.so.10.0)
I'm currently working on a Nvidia Jetson Nano and I'm not very familiar with Linux. I am trying to run a python file which imports a package called torch. I have installed it alongside with  torchvision while following the instructions from NVIDIA here.

When I run pip list on my terminal, I am able to see torch listed as one of the packages installed. However, I am unable to run the python file due to the error seen below. When I try to run it on python shell, the same error pops up.
FYI: Previously it had issues as the system was using python 2 by default but I have already fixed the path by switching to python 3 by editing the .bashrc file.

```<code>>>> import torch
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jiayi/.local/lib/python3.6/site-packages/torch/__init__.py", line 81, in <module>
    from torch._C import *
ImportError: libcudart.so.10.0: cannot open shared object file: No such file or directory
</code>```

I have tried uninstalling and installing via pip but to no avail. When I try to install the pytorch package (following the instructions from a github repo here), an error occurs as seen below and it is due to the same issue. It is able to detect that the torch package is installed but there seems to be an internal issue.

```<code>Requirement already satisfied: torch==1.4.0 from file:///home/jiayi/jetson-inference/build/torch-1.4.0-cp36-cp36m-linux_aarch64.whl in /home/jiayi/.local/lib/python3.6/site-packages (1.4.0)
[jetson-inference]  cloning torchvision...
[sudo] password for jiayi:
Cloning into 'torchvision-36'...
remote: Enumerating objects: 71, done.
remote: Counting objects: 100% (71/71), done.
remote: Compressing objects: 100% (56/56), done.
remote: Total 8219 (delta 37), reused 29 (delta 15), pack-reused 8148
Receiving objects: 100% (8219/8219), 10.22 MiB | 3.60 MiB/s, done.
Resolving deltas: 100% (5631/5631), done.
[jetson-inference]  building torchvision for Python 3.6...
Traceback (most recent call last):
  File "setup.py", line 14, in <module>
    import torch
  File "/home/jiayi/.local/lib/python3.6/site-packages/torch/__init__.py", line 81, in <module>
    from torch._C import *
ImportError: libcudart.so.10.0: cannot open shared object file: No such file or directory

[jetson-inference]  installation complete, exiting with status code 0
[jetson-inference]  to run this tool again, use the following commands:

    $ cd <jetson-inference>/build
    $ ./install-pytorch.sh
</code>```

答: I meet the exact same problem. The problem seems to be cuda 10.2. Downgrading to 10.0 does not help either. Probably the solution is to manually install everything from Jetpack and making sure that the cuda version to be installed is 10.0.</p>

Body:
I'm currently working on a Nvidia Jetson Nano and I'm not very familiar with Linux. I am trying to run a python file which imports a package called torch. I have installed it alongside with  torchvision while following the instructions from NVIDIA here.

When I run pip list on my terminal, I am able to see torch listed as one of the packages installed. However, I am unable to run the python file due to the error seen below. When I try to run it on python shell, the same error pops up.
FYI: Previously it had issues as the system was using python 2 by default but I have already fixed the path by switching to python 3 by editing the .bashrc file.

>>> import torch
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jiayi/.local/lib/python3.6/site-packages/torch/__init__.py", line 81, in <module>
    from torch._C import *
ImportError: libcudart.so.10.0: cannot open shared object file: No such file or directory

I have tried uninstalling and installing via pip but to no avail. When I try to install the pytorch package (following the instructions from a github repo here), an error occurs as seen below and it is due to the same issue. It is able to detect that the torch package is installed but there seems to be an internal issue.

Requirement already satisfied: torch==1.4.0 from file:///home/jiayi/jetson-inference/build/torch-1.4.0-cp36-cp36m-linux_aarch64.whl in /home/jiayi/.local/lib/python3.6/site-packages (1.4.0)
[jetson-inference]  cloning torchvision...
[sudo] password for jiayi:
Cloning into 'torchvision-36'...
remote: Enumerating objects: 71, done.
remote: Counting objects: 100% (71/71), done.
remote: Compressing objects: 100% (56/56), done.
remote: Total 8219 (delta 37), reused 29 (delta 15), pack-reused 8148
Receiving objects: 100% (8219/8219), 10.22 MiB | 3.60 MiB/s, done.
Resolving deltas: 100% (5631/5631), done.
[jetson-inference]  building torchvision for Python 3.6...
Traceback (most recent call last):
  File "setup.py", line 14, in <module>
    import torch
  File "/home/jiayi/.local/lib/python3.6/site-packages/torch/__init__.py", line 81, in <module>
    from torch._C import *
ImportError: libcudart.so.10.0: cannot open shared object file: No such file or directory

[jetson-inference]  installation complete, exiting with status code 0
[jetson-inference]  to run this tool again, use the following commands:

    $ cd <jetson-inference>/build
    $ ./install-pytorch.sh


问:
Using constants defined in header file
I'm trying to translate a X11/OpenGL demo into Java and I'm not sure how to use the constants OpenGL defines.  The only method I can think of is digging into the OpenGL headers and copying the constants to my program but is that the proper way to do it?  I imagine that there is no guarantee that those constants will be the same in a different environment.</p>

答: If you use a library like LWJGL it defines those constants for you and you don't have to worry about their actual values. </p>

Title: Using constants defined in header file


答:
You can utilize css :hover for this. Pure css solution:</p>

```<code>#img1 {
 display: none;
}

#left:hover #img1 {
 display: block;
}
</code>```

Title: Get an image to display when hovering over an div

Body:
You can utilize css :hover for this. Pure css solution:

#img1 {
 display: none;
}

#left:hover #img1 {
 display: block;
}


答:
Here is my suggestion to rewrite your fetching code :

```<code>class App extends Component{
 state = {
   pokemonArray : []
 }
 componentDidMount = () =>{
   fetch('https://pokeapi.co/api/v2/pokemon/?limit=384')
   .then(response => response.json())
   .then(data => {
      let results = data.results;
      this.setState({ pokemonArray : [...results]})
     console.log("Here are my pokemons",   this.state.pokemonArray)
     })

 }
...
}
</code>```

I'm using spread operator to copy the received data to the pokemonArray. You could pass then your array to the component as a prop.
Hope this helps you.

Title: PokeAPI - Fetching Pokemon Data

Body:
Here is my suggestion to rewrite your fetching code :

class App extends Component{
 state = {
   pokemonArray : []
 }
 componentDidMount = () =>{
   fetch('https://pokeapi.co/api/v2/pokemon/?limit=384')
   .then(response => response.json())
   .then(data => {
      let results = data.results;
      this.setState({ pokemonArray : [...results]})
     console.log("Here are my pokemons",   this.state.pokemonArray)
     })

 }
...
}

I'm using spread operator to copy the received data to the pokemonArray. You could pass then your array to the component as a prop.
Hope this helps you.


问:
CS50 pset4 filter reflection
```<code>#include "helpers.h"
#include <math.h>
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
    for ( int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width ; w++)
        {
           int i = image[h][w].rgbtBlue + image[h][w].rgbtGreen + image[h][w].rgbtRed ;
           float j = i/3 ;
           int n = round(j) ;

           image[h][w].rgbtBlue = n ;
           image[h][w].rgbtGreen = n ;
           image[h][w].rgbtRed = n ;
        }
    }
    return;
}

// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    for ( int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width ; w++)
        {
            float sr = .393 * image[h][w].rgbtRed + .769 * image[h][w].rgbtGreen + .189 * image[h][w].rgbtBlue ;
            float sg = .349 * image[h][w].rgbtRed + .686 * image[h][w].rgbtGreen + .168 * image[h][w].rgbtBlue ;
            float sb = .272 * image[h][w].rgbtRed + .534 * image[h][w].rgbtGreen + .131 * image[h][w].rgbtBlue ;

            int SR = round(sr);
            int SG = round(sg);
            int SB = round(sb);

            if ( SR>255)
            {
                SR = 255 ;
            }
            if (SG>255)
            {
                SG = 255 ;
            }
            if (SB>255)
            {
                 SB = 255 ;
            }

            image[h][w].rgbtBlue = SB ;
            image[h][w].rgbtGreen = SG ;
            image[h][w].rgbtRed = SR ;
        }
    }
    return;
}

// Reflect image horizontally
void swap (int *a , int *b) ;

void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    for (int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width/2 ; w++)
        {
            for (int p=width-1 ; p>=round(width/2) ; p--)
            {
                int blue = image[h][w].rgbtBlue ;
                int B = image[h][p].rgbtBlue ;
                swap(&blue , &B);

                int g = image[h][w].rgbtGreen ;
                int G = image[h][p].rgbtGreen ;
                swap(&g , &G);

                int r = image[h][w].rgbtRed ;
                int R = image[h][p].rgbtRed ;
                swap(&r , &R );

            }
        }
    }
    return;
}
void swap (int *a , int *b)
    {
        int tmp = *a ;
            *a = *b ;
            *b = tmp ;
    }

// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
    return;
}
</code>```

I have written this code for helper.c. It compiles ok and works for grayscale and sepia but fails to reflect the image.

I am stuck in it . Please tell me where have i made the mistake.

答:
```<code>// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{

    int tmp[3];
    for (int h = 0; h < height; h++)
    {
        for (int w = 0; w < width / 2; w++)
        {
            // Place the first pixel in a temporary variable
            tmp[0] = image[h][w].rgbtRed;
            tmp[1] = image[h][w].rgbtGreen;
            tmp[2] = image[h][w].rgbtBlue;
            // Place the opposite pixel one into the first pixel
            image[h][w].rgbtRed = image[h][width - w - 1].rgbtRed;
            image[h][w].rgbtGreen = image[h][width - w - 1].rgbtGreen;
            image[h][w].rgbtBlue = image[h][width - w - 1].rgbtBlue;
            // From the temporary variable extract the first pixel and place it into
            the opposite pixel
            image[h][width - w - 1].rgbtRed = tmp[0];
            image[h][width - w - 1].rgbtGreen = tmp[1];
            image[h][width - w - 1].rgbtBlue = tmp[2];
        }
    }
   return;
}
</code>```

Title: CS50 pset4 filter reflection

Body:
#include "helpers.h"
#include <math.h>
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
    for ( int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width ; w++)
        {
           int i = image[h][w].rgbtBlue + image[h][w].rgbtGreen + image[h][w].rgbtRed ;
           float j = i/3 ;
           int n = round(j) ;

           image[h][w].rgbtBlue = n ;
           image[h][w].rgbtGreen = n ;
           image[h][w].rgbtRed = n ;
        }
    }
    return;
}

// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    for ( int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width ; w++)
        {
            float sr = .393 * image[h][w].rgbtRed + .769 * image[h][w].rgbtGreen + .189 * image[h][w].rgbtBlue ;
            float sg = .349 * image[h][w].rgbtRed + .686 * image[h][w].rgbtGreen + .168 * image[h][w].rgbtBlue ;
            float sb = .272 * image[h][w].rgbtRed + .534 * image[h][w].rgbtGreen + .131 * image[h][w].rgbtBlue ;

            int SR = round(sr);
            int SG = round(sg);
            int SB = round(sb);

            if ( SR>255)
            {
                SR = 255 ;
            }
            if (SG>255)
            {
                SG = 255 ;
            }
            if (SB>255)
            {
                 SB = 255 ;
            }

            image[h][w].rgbtBlue = SB ;
            image[h][w].rgbtGreen = SG ;
            image[h][w].rgbtRed = SR ;
        }
    }
    return;
}

// Reflect image horizontally
void swap (int *a , int *b) ;

void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    for (int h=0 ; h<height ; h++)
    {
        for (int w=0 ; w<width/2 ; w++)
        {
            for (int p=width-1 ; p>=round(width/2) ; p--)
            {
                int blue = image[h][w].rgbtBlue ;
                int B = image[h][p].rgbtBlue ;
                swap(&blue , &B);

                int g = image[h][w].rgbtGreen ;
                int G = image[h][p].rgbtGreen ;
                swap(&g , &G);

                int r = image[h][w].rgbtRed ;
                int R = image[h][p].rgbtRed ;
                swap(&r , &R );

            }
        }
    }
    return;
}
void swap (int *a , int *b)
    {
        int tmp = *a ;
            *a = *b ;
            *b = tmp ;
    }

// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
    return;
}

I have written this code for helper.c. It compiles ok and works for grayscale and sepia but fails to reflect the image.

I am stuck in it . Please tell me where have i made the mistake.


问:
React component looks like it has a static shared state within its instances

Expected component behaviour:
- Load animation as defined by 'if' condition
- Then after 1000ms, the setTimeout function will change the state, thus rendering the 'else' part of the conditional

Additional Details
The component loads in fine, however, when I have another instance of the component created, both on alerts fire at the same time, and the this.render.state is set to true. This prevents the animation from loading as part of the conditional statement, since state.render is true... even though it should be false... Shouldn't each instance of this component display the default conditional behaviour?

Name.js Component

```<code>
export class Name extends Component {
  state = {
    render: false,
  };

  componentDidMount() {
    //alert('Test')
    setTimeout(
      function () {
        //Start the timer
        this.setState({ render: true }); //After 1 second, set render to true
      }.bind(this),
      1000
    );
  }

  render() {
    if (this.state.render === false) {
      return (
        <div className={styles.LContainer}>
          <div className={styles.ldsRing}>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
          </div>
        </div>
      );
    } else {
      console.log(this.state.render)
      return (
        <div className={styles.Container}>
          <img
            className={styles.imageO}
            src={require("./Apple_logo_white.svg")}
          />
          <div className={styles.textArea}>
            <h1 className={styles.title}>{this.props.title}</h1>
            <h2 className={styles.subtitle}>
            {this.props.sub}
          </h2>
          <Input name="name" handleChange = {this.props.handleChange} />
          <ScreenButton  goDirection={this.props.backScreen}  direction="back"/>
          <ScreenButton  goDirection={this.props.nextScreen}  direction="next"/>
          </div>
        </div>
      );
    }
  }
}
</code>```

I'm also using a switch statement to render these components, could that have anything to do with it?

```<code>render() {
    //Pulling information down from state:
    const { step, name, interest, location } = this.state;
    const values = { step, name, interest, location };

    switch (step) {
      case 1:
        return (
          <Welcome
            nextScreen={this.nextScreen}
            handleChange={this.handleChange}
            values={values}
          />
        );

      case 2:
        console.log(this.state.step);
        //return <h1>GOLS</h1>
        return (
            <React.Fragment>
          <Name
            nextScreen={this.nextScreen}
            backScreen={this.backScreen}
            handleChange={this.handleChange}
            values={values}
            sub="Example text"
            title="Example text"
          />
          </React.Fragment>
        );

      case 3:
        console.log(this.state.step);
        return (
          <React.Fragment>
            <Name
              nextScreen={this.nextScreen}
              backScreen={this.backScreen}
              handleChange={this.handleChange}
              values={values}
              sub="Example text"
              title="Example text"
            />
          </React.Fragment>
        );

    }
  }

  [1]: https://i.stack.imgur.com/U0v38.gif
</code>```

答:
Good news! I figured out the solution when my <Input/> components started to behave similarly.

The problem was that each component (both <Name /> and <Input/>were behaving similarly to their first rendered instance, almost as if they were sharing state.

The fix was simple... assign a key value for each component instance.

Like this:
<Name key="Unique Key Value">

Body:
Expected component behaviour:
- Load animation as defined by 'if' condition
- Then after 1000ms, the setTimeout function will change the state, thus rendering the 'else' part of the conditional

Additional Details
The component loads in fine, however, when I have another instance of the component created, both on alerts fire at the same time, and the this.render.state is set to true. This prevents the animation from loading as part of the conditional statement, since state.render is true... even though it should be false... Shouldn't each instance of this component display the default conditional behaviour?

Name.js Component

export class Name extends Component {
  state = {
    render: false,
  };

  componentDidMount() {
    //alert('Test')
    setTimeout(
      function () {
        //Start the timer
        this.setState({ render: true }); //After 1 second, set render to true
      }.bind(this),
      1000
    );
  }

  render() {
    if (this.state.render === false) {
      return (

      );
    } else {
      console.log(this.state.render)
      return (

{this.props.title}

            {this.props.sub}

          <Input name="name" handleChange = {this.props.handleChange} />
          <ScreenButton  goDirection={this.props.backScreen}  direction="back"/>
          <ScreenButton  goDirection={this.props.nextScreen}  direction="next"/>

      );
    }
  }
}

I'm also using a switch statement to render these components, could that have anything to do with it?

render() {
    //Pulling information down from state:
    const { step, name, interest, location } = this.state;
    const values = { step, name, interest, location };

    switch (step) {
      case 1:
        return (
          <Welcome
            nextScreen={this.nextScreen}
            handleChange={this.handleChange}
            values={values}
          />
        );

      case 2:
        console.log(this.state.step);
        //return
GOLS

        return (
            <React.Fragment>
          <Name
            nextScreen={this.nextScreen}
            backScreen={this.backScreen}
            handleChange={this.handleChange}
            values={values}
            sub="Example text"
            title="Example text"
          />
          </React.Fragment>
        );

      case 3:
        console.log(this.state.step);
        return (
          <React.Fragment>
            <Name
              nextScreen={this.nextScreen}
              backScreen={this.backScreen}
              handleChange={this.handleChange}
              values={values}
              sub="Example text"
              title="Example text"
            />
          </React.Fragment>
        );

    }
  }

  [1]: https://i.stack.imgur.com/U0v38.gif


问:
Get text string between first and 2nd comma
Let's say I have this text within a specific H1 called ".prop-address h1":

```<code><h1>31620 NE 129th St, Duvall, WA 98019</h1>
</code>```

How do I get the text "Duvall" (text between first & second comma) with Jquery/JS so I can use it for whatever purposes? I've looked up a bunch of stuff but can't seem to make it work. Thanks in advance!

答:
Like this

$( document ).ready(function() {
   $('#result').text($('#test').text().split(',')[1])
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 id='test'>31620 NE 129th St, Duvall, WA 98019</h1>
<div id="result"></div></code>```

Body:
Let's say I have this text within a specific H1 called ".prop-address h1":

31620 NE 129th St, Duvall, WA 98019

How do I get the text "Duvall" (text between first & second comma) with Jquery/JS so I can use it for whatever purposes? I've looked up a bunch of stuff but can't seem to make it work. Thanks in advance!

Body:
Like this

$( document ).ready(function() {
   $('#result').text($('#test').text().split(',')[1])
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 id='test'>31620 NE 129th St, Duvall, WA 98019</h1>
<div id="result"></div>