问:
How to remove
 tag but keep everything within the same paragraph
It's my first time posting so hopefully I'm able to make this as clear as possible.

For an assignment I have to use BeautifulSoup to crawl a made-up webpage and extract all the titles and abstracts from each publication page. In general I've been able to do this by finding the abstract paragraph on each page and just appending that to an empty list. However, one of the pages has broken the abstract into several small chunks separated by
.

This is annoying because instead of considering it as one abstract, it is considered as 5 different ones, so it affects all the following publications and the title-abstracts don't match up.

I've tried extracting the
 with the following code:

#text from abstract
abstracttext = []

for url in final_list:
    page = requests.get(url)
    soup = BeautifulSoup(page.content, "html.parser")
#    print(soup.prettify())

    necessarytext = soup.find("p")

    for e in soup.find_all('br'):
        e.extract()

#    print(necessarytext)

    for text in necessarytext:
        abstracttext.append(text)

#print(abstracttext)```

If I look at 'necessarytext' now it appears the problem is solved as all the sentences are within the same paragraph. However once I go ahead and append everything to the empty list, the sentences are again separated out as if they were different paragraphs and throw everything off.

Does anybody have any ideas why this might be? Is there any way of removing the
 but ensuring everything stays within the same paragraph, or is there a general-purpose way of concatenating all these sentences together? Sorry if I've been a bit unclear and I appreciate any help you can send my way.

EDIT: The 'url' in the code comes from a previous web-scraping I did. The publications are grouped by topic so I was able to go through each of the topics and extract the publication pages from there. All the unique URLs were added to a list called 'final_list' and so this for loop is supposed to go through each of these publication pages to extract the abstract. Hope that is clearer.

答:
To remove the
s from the
 you could use extract() or decompose():

```<code>...
necessarytext = soup.find("p")

for x in necessarytext:
    if x.name == 'br':
        x.extract()
        ##or
        ##x.decompose()

abstracttext.append(necessarytext)
...
</code>```

Note Cause it was not that clear - if you do not need the
 at all just call abstracttext.append(soup.find("p").text) this will give plain text of
 without

Example

```<code>import requests
from bs4 import BeautifulSoup

abstracttext = []

html='''<p>a <br/> b <br/> c</p>'''
soup = BeautifulSoup(html, "html.parser")
necessarytext = soup.find("p")
for x in necessarytext:
    if x.name == 'br':
        x.decompose()

abstracttext.append(necessarytext)

print(abstracttext)
</code>```

Output

```<code>[<p>a  b  c</p>]
</code>```

Title: How to remove <br> tag but keep everything within the same paragraph

Body:
It's my first time posting so hopefully I'm able to make this as clear as possible.

For an assignment I have to use BeautifulSoup to crawl a made-up webpage and extract all the titles and abstracts from each publication page. In general I've been able to do this by finding the abstract paragraph on each page and just appending that to an empty list. However, one of the pages has broken the abstract into several small chunks separated by
.

This is annoying because instead of considering it as one abstract, it is considered as 5 different ones, so it affects all the following publications and the title-abstracts don't match up.

I've tried extracting the
 with the following code:

#text from abstract
abstracttext = []

for url in final_list:
    page = requests.get(url)
    soup = BeautifulSoup(page.content, "html.parser")
#    print(soup.prettify())

    necessarytext = soup.find("p")

    for e in soup.find_all('br'):
        e.extract()

#    print(necessarytext)

    for text in necessarytext:
        abstracttext.append(text)

#print(abstracttext)

If I look at 'necessarytext' now it appears the problem is solved as all the sentences are within the same paragraph. However once I go ahead and append everything to the empty list, the sentences are again separated out as if they were different paragraphs and throw everything off.

Does anybody have any ideas why this might be? Is there any way of removing the
 but ensuring everything stays within the same paragraph, or is there a general-purpose way of concatenating all these sentences together? Sorry if I've been a bit unclear and I appreciate any help you can send my way.

EDIT: The 'url' in the code comes from a previous web-scraping I did. The publications are grouped by topic so I was able to go through each of the topics and extract the publication pages from there. All the unique URLs were added to a list called 'final_list' and so this for loop is supposed to go through each of these publication pages to extract the abstract. Hope that is clearer.

Body:
To remove the <br>s from the <p> you could use extract() or decompose():

...
necessarytext = soup.find("p")

for x in necessarytext:
    if x.name == 'br':
        x.extract()
        ##or
        ##x.decompose()

abstracttext.append(necessarytext)
...

Note Cause it was not that clear - if you do not need the <p> at all just call abstracttext.append(soup.find("p").text) this will give plain text of <p> without <br/>

Example

import requests
from bs4 import BeautifulSoup

abstracttext = []

html='''<p>a <br/> b <br/> c</p>'''
soup = BeautifulSoup(html, "html.parser")
necessarytext = soup.find("p")
for x in necessarytext:
    if x.name == 'br':
        x.decompose()

abstracttext.append(necessarytext)

print(abstracttext)

Output

[<p>a  b  c</p>]


来源: stackexchange

问:
onResume() not called when using ViewPager2 and Fragment
I have Main_Activity inside of it a ViewPager2 which contains 3 Fragment. So I'm trying to use onResume() on the MainActivity to check if the user is connected to the internet. If he's connected i will display an Ad view. but the onResume() called only the first time, and when the user change the fragment onResume() doesn't called.
I think the reason why is because of the MainActivity lost its foucs. So is there anyway.

Main_Activity.xml

```<code><com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@id/guideline_v2"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:background="@color/black_action_bar"
        app:tabTextColor="@color/gris"
        app:tabGravity="fill"
        app:tabMode="fixed"
        app:tabMaxWidth="0dp"
        app:tabSelectedTextColor="@color/green_org"
        app:tabIndicatorColor="@color/green_org"
        app:tabTextAppearance="@style/customfontstyle"
        >
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="IMAGES" />
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="VIDEOS" />
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SAVED" />

    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/guideline_v2"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_height="0dp"/>
</code>```

MainActivity.java

```<code>FragmentManager fragmentManager = getSupportFragmentManager();
    pagerAdapter = new PagerAdapter(fragmentManager,getLifecycle());
    pagerAdapter.addFragment(new ImagesFragment());
    pagerAdapter.addFragment(new VideosFragment());
    pagerAdapter.addFragment(new SavedFragment());
    viewPager.setAdapter(pagerAdapter);

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            tabLayout.selectTab(tabLayout.getTabAt(position));
        }
    });
</code>```

答:
The Fragment and Activity have different onResume methods.

So with the default Fragment lifecycle when you swipe left and right the onResume of ImagesFragment, VideosFragment and SavedFragment get called not the onResume method of MainActivity

Update based on comment

It sounds like you are doing the Internet check in the wrong place, it should probably not be in the MainActivity onResume method as there is no guarantee that this is called when you move out of cell range or turn on or off mobile data or wifi.

It sounds like the Internet connectivity check should be in a Broadcaster Receiver that is listens for network connectivity state changes. Quick scan of StackOverflow shows this as how to do that https://stackoverflow.com/a/26114247/2373819

ContentLicense: CC BY-SA 4.0

Body:
I have Main_Activity inside of it a ViewPager2 which contains 3 Fragment. So I'm trying to use onResume() on the MainActivity to check if the user is connected to the internet. If he's connected i will display an Ad view. but the onResume() called only the first time, and when the user change the fragment onResume() doesn't called.
I think the reason why is because of the MainActivity lost its foucs. So is there anyway.

Main_Activity.xml

<com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@id/guideline_v2"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:background="@color/black_action_bar"
        app:tabTextColor="@color/gris"
        app:tabGravity="fill"
        app:tabMode="fixed"
        app:tabMaxWidth="0dp"
        app:tabSelectedTextColor="@color/green_org"
        app:tabIndicatorColor="@color/green_org"
        app:tabTextAppearance="@style/customfontstyle"
        >
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="IMAGES" />
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="VIDEOS" />
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SAVED" />

    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/guideline_v2"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_height="0dp"/>

MainActivity.java

FragmentManager fragmentManager = getSupportFragmentManager();
    pagerAdapter = new PagerAdapter(fragmentManager,getLifecycle());
    pagerAdapter.addFragment(new ImagesFragment());
    pagerAdapter.addFragment(new VideosFragment());
    pagerAdapter.addFragment(new SavedFragment());
    viewPager.setAdapter(pagerAdapter);

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            tabLayout.selectTab(tabLayout.getTabAt(position));
        }
    });


问:
Power BI REST API - Error: connect: exceeded the limit of 5 sockets
Hello dear PBI REST API experts, I would appreciate any support on the following issue.
Trying to send data from MongoDB Atlas to Power BI Push Dataset through Rest API.
However I met the following issue, when I'm making more than 5 post http requests to PBI Rest API it says <code>'Error: connect: exceeded the limit of 5 sockets'. </code>
I found the following link on this website, however seems like solution was not found there: Close socket connection in request.js</p>
```<code>function postDataToPowerBi(result) {
...
              collection.findOne({"_id": item._id}).then(itemDoc => {
                postOne(itemDoc, access_token);
              });
...
  }
</code>```
```<code>
  function postOne(itemDoc, access_token){

      var postData = JSON.stringify({
          "rows": [
            {
              "Name": itemDoc.Name,
              "name.1": itemDoc.name
            }
          ]
      });

      // request option
      var options = {
        host: 'api.powerbi.com' ,
        port: 443,
        method: 'POST',
        path: '/v1.0/myorg/groups/' + group_id + '/datasets/' + dataset_id + '/tables/' + table_name + '/rows',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + access_token,
          // 'Content-Length': postData.length,
          'Connection': 'Close'
        }
      };
      // request object
      var req = https.request(options, function (res) {
        var result = '';
        res.on('data', function (chunk) {
          result += chunk;
        });
        res.on('end', function () {
          console.log(res.statusCode);

        });
        res.on('error', function (err) {
          console.log(err);
        });
      });

      // req error
      req.on('error', function (err) {
        console.log(err);
      });

      req.on('close', function () {
        console.log("request closed");
      });

      //send request witht the postData form
      req.write(postData);
      req.end();
  }
</code>```

答:
Found explanation for the question posted. Power BI has 5 max pending POST rows requests per dataset for push datasets. More information here: https://learn.microsoft.com/en-us/power-bi/developer/embedded/push-datasets-limitations Hence the only and much better approach is to post rows in bulk instead of line by line. Example below:

```<code>function postBulk(docs, access_token, firstRun){

      if(firstRun){
        deleteRows(access_token);
      }

      var postData = '{"rows": ' + JSON.stringify(docs) + '}';

      // console.log(postData);

      // request option
      var options = {
        host: 'api.powerbi.com' ,
        port: 443,
        method: 'POST',
        path: '/v1.0/myorg/groups/' + group_id + '/datasets/' + dataset_id + '/tables/' + table_name + '/rows',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + access_token,
          // 'Content-Length': postData.length,
          // 'Connection': 'Close'
        }
      };
      // request object
      var req = https.request(options, function (res) {
        var result = '';
        res.on('data', function (chunk) {
          result += chunk;
        });
        res.on('end', function () {
          console.log("postBulk: " + res.statusMessage);

        });
        res.on('error', function (err) {
          console.log("postBulk: " + err);
        });
      });

      // req error
      req.on('error', function (err) {
        console.log("postBulk: " + err);
      });

      // req.on('close', function () {
      //   console.log("request closed");
      // });

      //send request witht the postData form
      req.write(postData);
      req.end();
  }
</code>```

Body:
Hello dear PBI REST API experts, I would appreciate any support on the following issue.
Trying to send data from MongoDB Atlas to Power BI Push Dataset through Rest API.
However I met the following issue, when I'm making more than 5 post http requests to PBI Rest API it says 'Error: connect: exceeded the limit of 5 sockets'.
I found the following link on this website, however seems like solution was not found there: Close socket connection in request.js

function postDataToPowerBi(result) {
...
              collection.findOne({"_id": item._id}).then(itemDoc => {
                postOne(itemDoc, access_token);
              });
...
  }

  function postOne(itemDoc, access_token){

      var postData = JSON.stringify({
          "rows": [
            {
              "Name": itemDoc.Name,
              "name.1": itemDoc.name
            }
          ]
      });

      // request option
      var options = {
        host: 'api.powerbi.com' ,
        port: 443,
        method: 'POST',
        path: '/v1.0/myorg/groups/' + group_id + '/datasets/' + dataset_id + '/tables/' + table_name + '/rows',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + access_token,
          // 'Content-Length': postData.length,
          'Connection': 'Close'
        }
      };
      // request object
      var req = https.request(options, function (res) {
        var result = '';
        res.on('data', function (chunk) {
          result += chunk;
        });
        res.on('end', function () {
          console.log(res.statusCode);

        });
        res.on('error', function (err) {
          console.log(err);
        });
      });

      // req error
      req.on('error', function (err) {
        console.log(err);
      });

      req.on('close', function () {
        console.log("request closed");
      });

      //send request witht the postData form
      req.write(postData);
      req.end();
  }

Body:
Found explanation for the question posted. Power BI has 5 max pending POST rows requests per dataset for push datasets. More information here: https://learn.microsoft.com/en-us/power-bi/developer/embedded/push-datasets-limitations Hence the only and much better approach is to post rows in bulk instead of line by line. Example below:

function postBulk(docs, access_token, firstRun){

      if(firstRun){
        deleteRows(access_token);
      }

      var postData = '{"rows": ' + JSON.stringify(docs) + '}';

      // console.log(postData);

      // request option
      var options = {
        host: 'api.powerbi.com' ,
        port: 443,
        method: 'POST',
        path: '/v1.0/myorg/groups/' + group_id + '/datasets/' + dataset_id + '/tables/' + table_name + '/rows',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + access_token,
          // 'Content-Length': postData.length,
          // 'Connection': 'Close'
        }
      };
      // request object
      var req = https.request(options, function (res) {
        var result = '';
        res.on('data', function (chunk) {
          result += chunk;
        });
        res.on('end', function () {
          console.log("postBulk: " + res.statusMessage);

        });
        res.on('error', function (err) {
          console.log("postBulk: " + err);
        });
      });

      // req error
      req.on('error', function (err) {
        console.log("postBulk: " + err);
      });

      // req.on('close', function () {
      //   console.log("request closed");
      // });

      //send request witht the postData form
      req.write(postData);
      req.end();
  }


问:
I had a problem with javascript alert fuunction
I am having 3 kind of swf players and if any one of player is playing all others should pause.

1 st one - audioPlayer - autoplay = true;
2 nd one - audioPlayer - autoplay = false;
3 rd one - audioPlayer - autoplay = false;

If 2nd and 3rd paused or ended then 1st one should continue if it was not paused.

This is my java script code.

```<code>function videoPlaying(val){
    tmp = val;
}
function sendTojs(value){
        if(value == "end" || value == "pause"){
         thisMovie("movie0").sndToAS("pause");
         alert("done");
    }
    for(i=0; i<=7; i++){
         var mov="movie"+i;
        if(tmp!=mov){
                thisMovie(mov).sndToAS("resume");
            }
         }
        }
</code>```

here sndToAS is my actionscript function and tmp will have the strings "resume", "pause" and "end". I have used externalInterface.callBack in AS3.

actionscript3.0

within callback function

```<code>if(val == "pause")
{
    videoPlay();
}
</code>```

My problem:
   if I use the alert function within sendTojs then the condition is working else not. Why?

答:
Perhaps you have a situation where the display is not being updated until the script pauses (in this case for an alert). Try using setTimeout().

```<code>if(tmp2=="end")
 {
    thisMovie("movie0").sndToAS("pause"),
    setTimeout(function() {},1);
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having 3 kind of swf players and if any one of player is playing all others should pause.

1 st one - audioPlayer - autoplay = true;
2 nd one - audioPlayer - autoplay = false;
3 rd one - audioPlayer - autoplay = false;

If 2nd and 3rd paused or ended then 1st one should continue if it was not paused.

This is my java script code.

function videoPlaying(val){
    tmp = val;
}
function sendTojs(value){
        if(value == "end" || value == "pause"){
         thisMovie("movie0").sndToAS("pause");
         alert("done");
    }
    for(i=0; i<=7; i++){
         var mov="movie"+i;
        if(tmp!=mov){
                thisMovie(mov).sndToAS("resume");
            }
         }
        }

here sndToAS is my actionscript function and tmp will have the strings "resume", "pause" and "end". I have used externalInterface.callBack in AS3.

actionscript3.0

within callback function

if(val == "pause")
{
    videoPlay();
}

My problem:
   if I use the alert function within sendTojs then the condition is working else not. Why?

Body:
Perhaps you have a situation where the display is not being updated until the script pauses (in this case for an alert). Try using setTimeout().

if(tmp2=="end")
 {
    thisMovie("movie0").sndToAS("pause"),
    setTimeout(function() {},1);
 }


问:
Stepper using Variables from Binding Structs Crashes View?
I am passing an object between views using @Binding from the previous view. The struct is designed as such:

```<code>struct Topping: Identifiable {
    let name: String
    let price: Double
    var amount: Int
    let id = UUID()
}
// Ex. Topping(name: "Cheese", price: 3.00, amount: 0)

struct ToppingList: Identifiable {
    let name: String
    var list: [Topping]
    var id: String {
        name+"menu\(menu.indices)"
    }
}
// Ex. ToppingList(name: "Cheeses", menu: [Topping(...), Topping(...)])

struct MenuItem: Identifiable {
    let name: String
    let description: String
    let size: [String]
    let image: String
    let price: [Double]
    var toppings: [ToppingList]
    var id: String {
        "_"+name
    }
}
// Ex. MenuItem(...toppings: [Topping(name: "Cheese", price: 3.00, amount: 0), Topping(name: "Pepperoni", price: 3.00, amount: 0)])
</code>```

I pass the list of toppings to the view, and with a stepper hope to increment or decrement the amount of toppings (per unique topping). The problem that arises is when this happens, the view crashes to my home page.

The code for the views is separated into 2 - one for displaying the rows of steppers in a form, and the child view - for the individual rows.

```<code>// This view is the main view,
struct ToppingCategoryView: View {

@Binding var menuItem: MenuItem
// Pretend this is the MenuItem passed:
// MenuItem(...toppings: ToppingList(name: "Cheeses", list: [Topping(name: "Mozza", price: 3.00, amount: 0), Topping(name: "Parmesan", price: 3.00, amount: 0)]))

var body: some View {
    VStack {
        Form {
            ForEach($menuItem.toppings) { $menu in
                Section (menu.name){
                    ExtraToppingsView(toppingsList: $menu.list)
                }
            }
        }
    }
}
</code>```

The following view is where the stepper and @Binding variable is. I wish to increase the amount of toppings. Doing so, dismisses the view, but still increases the variable. If I load the view again, it displays correctly. Not sure why the view is dismissed. No error messages or warnings I could reproduce or find.

```<code>struct ExtraToppingsView: View {

@Binding var toppingsList: [Topping]

var body: some View {
    VStack {
        ForEach($toppingsList) { $topping in
            Stepper {
                Text("\(topping.amount)")
            } onIncrement: {
                topping.amount += 1
                if topping.amount >= 4 { topping.amount = 3 }
            } onDecrement: {
                topping.amount -= 1
                if topping.amount <= -1 { topping.amount = 0 }
            }
        }
    }
}
</code>```

}

答:
I figured out what the issue is, it seems to be some kind of bug or something else I am not aware of.

It relates to using NESTED navigation links.

To fix this, I simply add .isDetailLink(False) to EVERY NavigationLink in the project. This fixed the issue.

Body:
I am passing an object between views using @Binding from the previous view. The struct is designed as such:

struct Topping: Identifiable {
    let name: String
    let price: Double
    var amount: Int
    let id = UUID()
}
// Ex. Topping(name: "Cheese", price: 3.00, amount: 0)

struct ToppingList: Identifiable {
    let name: String
    var list: [Topping]
    var id: String {
        name+"menu\(menu.indices)"
    }
}
// Ex. ToppingList(name: "Cheeses", menu: [Topping(...), Topping(...)])

struct MenuItem: Identifiable {
    let name: String
    let description: String
    let size: [String]
    let image: String
    let price: [Double]
    var toppings: [ToppingList]
    var id: String {
        "_"+name
    }
}
// Ex. MenuItem(...toppings: [Topping(name: "Cheese", price: 3.00, amount: 0), Topping(name: "Pepperoni", price: 3.00, amount: 0)])

I pass the list of toppings to the view, and with a stepper hope to increment or decrement the amount of toppings (per unique topping). The problem that arises is when this happens, the view crashes to my home page.

The code for the views is separated into 2 - one for displaying the rows of steppers in a form, and the child view - for the individual rows.

// This view is the main view,
struct ToppingCategoryView: View {

@Binding var menuItem: MenuItem
// Pretend this is the MenuItem passed:
// MenuItem(...toppings: ToppingList(name: "Cheeses", list: [Topping(name: "Mozza", price: 3.00, amount: 0), Topping(name: "Parmesan", price: 3.00, amount: 0)]))

var body: some View {
    VStack {
        Form {
            ForEach($menuItem.toppings) { $menu in
                Section (menu.name){
                    ExtraToppingsView(toppingsList: $menu.list)
                }
            }
        }
    }
}

The following view is where the stepper and @Binding variable is. I wish to increase the amount of toppings. Doing so, dismisses the view, but still increases the variable. If I load the view again, it displays correctly. Not sure why the view is dismissed. No error messages or warnings I could reproduce or find.

struct ExtraToppingsView: View {

@Binding var toppingsList: [Topping]

var body: some View {
    VStack {
        ForEach($toppingsList) { $topping in
            Stepper {
                Text("\(topping.amount)")
            } onIncrement: {
                topping.amount += 1
                if topping.amount >= 4 { topping.amount = 3 }
            } onDecrement: {
                topping.amount -= 1
                if topping.amount <= -1 { topping.amount = 0 }
            }
        }
    }
}

}


问:
Search - Appscript - targetRange column start is not at the column I ask for
I am still learning a lot about Apps Script and needed to make a sheet for my work.
At the moment I am busy on a Search function.
The only problem is that the results that I want to get, do not go to that column.
Only to a column way further.

```<code>function Search() {
  var sourcesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Source");
  //USER INPUT
  sourceRowStart = 2; //Row to start getting formulas from
  sourceColumnStart = 13; //Column to start getting formulas from
  numberOfSourceColumnsToGet = 9; //Number of columns to get formulas from
  targetRowStart = 4; //Row to start copying formulas to
  targetRange = 1; //Column to start copying formulas to
  //END OF USER INPUT
  activeSheet = SpreadsheetApp.getActiveSheet();
  sourceRange = activeSheet.getRange(sourceRowStart, sourceColumnStart, activeSheet.getLastRow(), numberOfSourceColumnsToGet);
  sourceFormulas = sourceRange.getFormulas();//Get only formulas from the source rang
  targetRange = activeSheet.getRange(targetRowStart, targetRange, sourceFormulas.length, sourceFormulas[0].length);
  targetRange.setFormulas(sourceFormulas);//Copy the formulas to the target range
}
</code>```

Following is the link of a test-sheet for this question:

https://docs.google.com/spreadsheets/d/1b5Xa1z6xdeqyFbAVtxwc-U76iDteC1Sn46Ll_v9WGPU/edit#gid=713972882

Thankyou in advance to whoever could help me out!

答:
Not sure if it causes the error in this case, but anyway. You have the line:

```<code>targetRange = 1; //Column to start copying formulas to
</code>```

And then:

```<code>targetRange = activeSheet.getRange(targetRowStart, targetRange, sourceFormulas.length, sourceFormulas[0].length);
</code>```

You're using the same variable targetRange for different purposes. It's not a good practice. It can get you glitches sometimes.

And to be honest, from yours spreadsheet and the code I failed to understand how the desired result should look like. Is the activeSheet supposed to be 'Database' sheet or 'Source' sheet, or something else? Etc.

Body:
I am still learning a lot about Apps Script and needed to make a sheet for my work.
At the moment I am busy on a Search function.
The only problem is that the results that I want to get, do not go to that column.
Only to a column way further.

function Search() {
  var sourcesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Source");
  //USER INPUT
  sourceRowStart = 2; //Row to start getting formulas from
  sourceColumnStart = 13; //Column to start getting formulas from
  numberOfSourceColumnsToGet = 9; //Number of columns to get formulas from
  targetRowStart = 4; //Row to start copying formulas to
  targetRange = 1; //Column to start copying formulas to
  //END OF USER INPUT
  activeSheet = SpreadsheetApp.getActiveSheet();
  sourceRange = activeSheet.getRange(sourceRowStart, sourceColumnStart, activeSheet.getLastRow(), numberOfSourceColumnsToGet);
  sourceFormulas = sourceRange.getFormulas();//Get only formulas from the source rang
  targetRange = activeSheet.getRange(targetRowStart, targetRange, sourceFormulas.length, sourceFormulas[0].length);
  targetRange.setFormulas(sourceFormulas);//Copy the formulas to the target range
}

Following is the link of a test-sheet for this question:

https://docs.google.com/spreadsheets/d/1b5Xa1z6xdeqyFbAVtxwc-U76iDteC1Sn46Ll_v9WGPU/edit#gid=713972882

Thankyou in advance to whoever could help me out!

Body:
Not sure if it causes the error in this case, but anyway. You have the line:

targetRange = 1; //Column to start copying formulas to

And then:

targetRange = activeSheet.getRange(targetRowStart, targetRange, sourceFormulas.length, sourceFormulas[0].length);

You're using the same variable targetRange for different purposes. It's not a good practice. It can get you glitches sometimes.

And to be honest, from yours spreadsheet and the code I failed to understand how the desired result should look like. Is the activeSheet supposed to be 'Database' sheet or 'Source' sheet, or something else? Etc.


问:
React Js Get Data with Fetch limit return
I am new to React and was following a tutorial this React tutorial to get data with fetch. Why when I append it with a limit in the query it still returns 10 results?</p>
```<code>
    import React from 'react'

export default function UsersData() {
    return (
        <div>

        </div>
    )
}
import React, { useState, useEffect } from 'react'

export default function UsersData() {
  const [Users, fetchUsers] = useState([])

  const getData = () => {
    fetch('https://jsonplaceholder.typicode.com/posts?_limit=8')
      .then((res) => res.json())
      .then((res) => {
        console.log(res)
        fetchUsers(res)
      })
  }

  useEffect(() => {
    getData()
  }, [])

  return (
    <>
      <h2>React Fetch API Example</h2>
      <ul>
        {Users.map((item, i) => {
          return <li key={i}>{item.name}</li>
        })}
      </ul>
    </>
  )
}```

</code>```

答:
```<code>    var params = {
       method: 'GET',
       headers: {
          "cache-control": 'no-cache',
          pragma: 'no-cache',
         }
       };

fetch("https://jsonplaceholder.typicode.com/posts?_limit=8", params)
  .then(res => res.json())
  .then(res => {
      console.log(res)
  })
</code>```

can you try like this ?

Body:
I am new to React and was following a tutorial this React tutorial to get data with fetch. Why when I append it with a limit in the query it still returns 10 results?

    import React from 'react'

export default function UsersData() {
    return (

    )
}
import React, { useState, useEffect } from 'react'

export default function UsersData() {
  const [Users, fetchUsers] = useState([])

  const getData = () => {
    fetch('https://jsonplaceholder.typicode.com/posts?_limit=8')
      .then((res) => res.json())
      .then((res) => {
        console.log(res)
        fetchUsers(res)
      })
  }

  useEffect(() => {
    getData()
  }, [])

  return (
    <>

React Fetch API Example

        {Users.map((item, i) => {
          return
{item.name}

        })}

    </>
  )
}```

Body:
    var params = {
       method: 'GET',
       headers: {
          "cache-control": 'no-cache',
          pragma: 'no-cache',
         }
       };

fetch("https://jsonplaceholder.typicode.com/posts?_limit=8", params)
  .then(res => res.json())
  .then(res => {
      console.log(res)
  })

can you try like this ?


问:
Problem with Update in Every Refresh, localStorage, useState, useEffect
I am trying to prevent my app to go into useEffect hook and implement what is inside within a 5 second period regardless of the situation the page is refreshed or not.

My code still only fires up the useEffect hook only on page refresh. It does not really care whether 5 seconds passed it fires up in every page refresh and then does not do anything for an eternity unless you refresh the page again. It acts like a useEffect hook with empty dependency array.

How can I achieve useEffect hook to run every 5 seconds regardless the page is refreshed or not? Here is my snippet.

```<code>  const localVisitTime = localStorage.getItem('localVisitTime');
  const currentTime = new Date().getTime();
  const timeDifference = currentTime - localVisitTime;

  const [ visitTime, setVisitTime ] = useState(localVisitTime);

  if (localVisitTime && timeDifference <= 5000) {
    // Do nothing, wait!
  } else {
    localStorage.setItem('localVisitTime', new Date().getTime());
    setVisitTime(localVisitTime);
  }

  useEffect(() => {

    const fetchData = async () => {
      console.log('Data fetched!');
    }

    fetchData();
  }, [visitTime]);
</code>```

答:
The reason it is not firing multiple times is the check for time difference happence only once, you should use a set interval which checks every second if the time is valid and tries to set the time difference in a state, but i think its not necessary.

I believe you want to maintain this 5 seconds firing even between page refreshes but if its not critical, you can always start again when the page refreshes. I think you should  use the set interval and not worry about refreshes like this.

```<code>const fetchData = async () => {
  console.log("Data fetched!");
};

useEffect(() => {
  fetchData();
  const interval = setInterval(() => {
    fetchData();
  }, 5000);
  return () => clearInterval(interval);
}, []);
</code>```

This way, the fetch data will run every 5 seconds, and will run on every refresh

Body:
I am trying to prevent my app to go into useEffect hook and implement what is inside within a 5 second period regardless of the situation the page is refreshed or not.

My code still only fires up the useEffect hook only on page refresh. It does not really care whether 5 seconds passed it fires up in every page refresh and then does not do anything for an eternity unless you refresh the page again. It acts like a useEffect hook with empty dependency array.

How can I achieve useEffect hook to run every 5 seconds regardless the page is refreshed or not? Here is my snippet.

  const localVisitTime = localStorage.getItem('localVisitTime');
  const currentTime = new Date().getTime();
  const timeDifference = currentTime - localVisitTime;

  const [ visitTime, setVisitTime ] = useState(localVisitTime);

  if (localVisitTime && timeDifference <= 5000) {
    // Do nothing, wait!
  } else {
    localStorage.setItem('localVisitTime', new Date().getTime());
    setVisitTime(localVisitTime);
  }

  useEffect(() => {

    const fetchData = async () => {
      console.log('Data fetched!');
    }

    fetchData();
  }, [visitTime]);

Body:
The reason it is not firing multiple times is the check for time difference happence only once, you should use a set interval which checks every second if the time is valid and tries to set the time difference in a state, but i think its not necessary.

I believe you want to maintain this 5 seconds firing even between page refreshes but if its not critical, you can always start again when the page refreshes. I think you should  use the set interval and not worry about refreshes like this.

const fetchData = async () => {
  console.log("Data fetched!");
};

useEffect(() => {
  fetchData();
  const interval = setInterval(() => {
    fetchData();
  }, 5000);
  return () => clearInterval(interval);
}, []);

This way, the fetch data will run every 5 seconds, and will run on every refresh


问:
R: Return a vector using %in% operator
I have a vector with delimiters and I want to generate a vector of the same length with boolean values based on whether or not one of the delimited values contains what I am after. I cannot find a way to do this neatly in vector-based logic. As an example:

```<code>x <- c('a', 'a; b', 'ab; c', 'b; c', 'c; a', 'c')
</code>```

Using some magic asking whether 'a' %in% x, I want to get the vector:

```<code>TRUE, TRUE, FALSE, FALSE, TRUE, FALSE
</code>```

I initially tried the following:

```<code>'a' %in% trimws(strsplit(x, ';'))
</code>```

But this unexpectedly collapses the entire list and returns TRUE, rather than a vector, since one of the elements in x is 'a'. Is there a way to get the vector I am looking for without rewriting the code into a for-loop?

答:
If you would like to use %in%, here is a base R option

```<code>> mapply(`%in%`, list("a"), strsplit(x, ";\\s+"))
[1]  TRUE  TRUE FALSE FALSE  TRUE FALSE
</code>```

A more efficient way might be using grepl like below

```<code>> grepl("\\ba\\b",x)
[1]  TRUE  TRUE FALSE FALSE  TRUE FALSE
</code>```

Title: R: Return a vector using %in% operator

Body:
I have a vector with delimiters and I want to generate a vector of the same length with boolean values based on whether or not one of the delimited values contains what I am after. I cannot find a way to do this neatly in vector-based logic. As an example:

x <- c('a', 'a; b', 'ab; c', 'b; c', 'c; a', 'c')

Using some magic asking whether 'a' %in% x, I want to get the vector:

TRUE, TRUE, FALSE, FALSE, TRUE, FALSE

I initially tried the following:

'a' %in% trimws(strsplit(x, ';'))

But this unexpectedly collapses the entire list and returns TRUE, rather than a vector, since one of the elements in x is 'a'. Is there a way to get the vector I am looking for without rewriting the code into a for-loop?

Body:
If you would like to use %in%, here is a base R option

> mapply(`%in%`, list("a"), strsplit(x, ";\\s+"))
[1]  TRUE  TRUE FALSE FALSE  TRUE FALSE

A more efficient way might be using grepl like below

> grepl("\\ba\\b",x)
[1]  TRUE  TRUE FALSE FALSE  TRUE FALSE


问:
CheckedChanged event for Dynamically generated Checkbox column in DataGrid(Asp.Net)
I have a datagrid (Asp.Net) with dynamically generated checkbox column..I am not able to generate the checkedChanged event for the checkbox..

Here is my code:

public class ItemTemplate : ITemplate
{
    //Instantiates the checkbox
    void ITemplate.InstantiateIn(Control container)
    {
        CheckBox box = new CheckBox();

        box.CheckedChanged += new EventHandler(this.OnCheckChanged);
        box.AutoPostBack = true;
        box.EnableViewState = true;
        box.Text = text;
        box.ID = id;
        container.Controls.Add(box);
    }

```<code>public event EventHandler CheckedChanged;

private void OnCheckChanged(object sender, EventArgs e)
{
    if (CheckedChanged != null)
    {
        CheckedChanged(sender, e);
    }
}
</code>```

}

and Here is the event

private void OnCheckChanged(object sender, EventArgs e)
{

}

Thanks In advance

答:
When do you add your custom column? If it is on load, then it is too late. Load it on init. I.e. following works with your code:</p>

```<code>protected void Page_Init(object sender, EventArgs e)
{
    ItemTemplate myTemplate = new ItemTemplate();
    myTemplate.CheckedChanged += new EventHandler(myTemplate_CheckedChanged);

    TemplateField col = new TemplateField();
    col.ItemTemplate = myTemplate;
    col.ItemStyle.Wrap = false;

    grid.Columns.Add(col);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a datagrid (Asp.Net) with dynamically generated checkbox column..I am not able to generate the checkedChanged event for the checkbox..

Here is my code:

public class ItemTemplate : ITemplate
{
    //Instantiates the checkbox
    void ITemplate.InstantiateIn(Control container)
    {
        CheckBox box = new CheckBox();

        box.CheckedChanged += new EventHandler(this.OnCheckChanged);
        box.AutoPostBack = true;
        box.EnableViewState = true;
        box.Text = text;
        box.ID = id;
        container.Controls.Add(box);
    }

public event EventHandler CheckedChanged;

private void OnCheckChanged(object sender, EventArgs e)
{
    if (CheckedChanged != null)
    {
        CheckedChanged(sender, e);
    }
}

}

and Here is the event

private void OnCheckChanged(object sender, EventArgs e)
{

}

Thanks In advance

Body:
When do you add your custom column? If it is on load, then it is too late. Load it on init. I.e. following works with your code:

protected void Page_Init(object sender, EventArgs e)
{
    ItemTemplate myTemplate = new ItemTemplate();
    myTemplate.CheckedChanged += new EventHandler(myTemplate_CheckedChanged);

    TemplateField col = new TemplateField();
    col.ItemTemplate = myTemplate;
    col.ItemStyle.Wrap = false;

    grid.Columns.Add(col);
}

OwnerDisplayName: Ruslan


问:
ASP.NET MVC 3 Route parameter problem
I have a desktop system that calls a PHP script (script.php) and I send a parameter called by "x" to this script (ex: script.php?x=123), but now the PHP scripts are being rewritten in ASP.NET/MVC, but I can't change the desktop system, then I've created a route like this:

```<code>routes.MapRoute("ScriptPHP",
    "myscript/script.php",
    new { controller = "MyController", action = "MyAction", x = UrlParameter.Optional }
);
</code>```

The problem is: MyAction receives a parameter named "id" (MyAction(int id)), and this route works only if I call "script.php?id=123".

How do I send the parameter "x" and this route convert "x" to "id" parameter name? It's possible?

NOTE: I can't change the action parameters.

答: Take a look here. You can probably extend it to alias query params.</p>

Title: ASP.NET MVC 3 Route parameter problem

Body:
I have a desktop system that calls a PHP script (script.php) and I send a parameter called by "x" to this script (ex: script.php?x=123), but now the PHP scripts are being rewritten in ASP.NET/MVC, but I can't change the desktop system, then I've created a route like this:

routes.MapRoute("ScriptPHP",
    "myscript/script.php",
    new { controller = "MyController", action = "MyAction", x = UrlParameter.Optional }
);

The problem is: MyAction receives a parameter named "id" (MyAction(int id)), and this route works only if I call "script.php?id=123".

How do I send the parameter "x" and this route convert "x" to "id" parameter name? It's possible?

NOTE: I can't change the action parameters.


问:
With pandas, how to create a table of average ocurrences, using more than one column?
Say I have a df that looks like this:

```<code>    name  day  var_A   var_B
0   Pete  Wed      4       5
1   Luck  Thu      1      10
2   Pete  Sun     10      10
</code>```

And I want to sum var_A and var_B for every name/person and then get the average of this sum by the number of ocurrences of that name/person.

Let's take Pete for example. Sum his variables (in this case, (4+10) + (5+10) = 29), and divide this sum by the ocurrences of Pete in the df (29/2 = 14,5). And the "day" column would be eliminated, there would be only one column for the name and another for the average.
Would look like this:

```<code>>>> df.method().method()

        name   avg
    0   Pete  14.5
    1   Luck  11.0
</code>```

I've been trying to do this using groupby and other methods, but I eventually got stuck.
Any help would be appreciated.

答:
pandas' groupby is a lazy expression, and as such it is reusable:

# create group
group = df.drop(columns="day").groupby("name")

# compute output
 group.sum().sum(1) / group.size()

name
Luck    11.0
Pete    14.5
dtype: float64
```

Body:
Say I have a df that looks like this:

    name  day  var_A   var_B
0   Pete  Wed      4       5
1   Luck  Thu      1      10
2   Pete  Sun     10      10

And I want to sum var_A and var_B for every name/person and then get the average of this sum by the number of ocurrences of that name/person.

Let's take Pete for example. Sum his variables (in this case, (4+10) + (5+10) = 29), and divide this sum by the ocurrences of Pete in the df (29/2 = 14,5). And the "day" column would be eliminated, there would be only one column for the name and another for the average.
Would look like this:

>>> df.method().method()

        name   avg
    0   Pete  14.5
    1   Luck  11.0

I've been trying to do this using groupby and other methods, but I eventually got stuck.
Any help would be appreciated.


问:
How to apply HostOptions.ShutdownTimeout when configuring .NET Core Generic Host?
I am using the .NET Core Generic Host (not Web Host) to build a Console app that needs a rather lengthy graceful shutdown.  From the source code in

aspnet/Hosting/src/Microsoft.Extensions.Hosting/HostOptions

it seems pretty clear that the ShutdownTimeout option can be used to change the shutdown timeout in the cancellation token that is provided as a parameter to ShutdownAsync.  By default it is 5 seconds.

However, I can't figure out where and how to write the code to specify this option in the HostBuilder configuration code that you typically put in the Program.cs file.

Can someone post some code that shows how to do this?

答:
A relevant answer for ASP.NET Core 6+:

Solution 1:

var builder = WebApplication.CreateBuilder(args);
//...
builder.WebHost.UseShutdownTimeout(TimeSpan.FromSeconds(30));
//...
var app = builder.Build();

```
<h3>Solution 2:</h3>
<pre class="lang-cs prettyprint-override"><code>var builder = WebApplication.CreateBuilder(args);
//...
builder.Services.Configure<HostOptions>(
     opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(30));
//...
var app = builder.Build();
</code>```

Solution 3:

var builder = WebApplication.CreateBuilder(args);
//...
builder.Services.PostConfigureAll<HostOptions>(opts =>
    opts.ShutdownTimeout = TimeSpan.FromSeconds(30));
//...
var app = builder.Build();
```

Solution 3 will be applied after all others.

Body:
A relevant answer for ASP.NET Core 6+:

Solution 1:

var builder = WebApplication.CreateBuilder(args);
//...
builder.WebHost.UseShutdownTimeout(TimeSpan.FromSeconds(30));
//...
var app = builder.Build();

Solution 2:

var builder = WebApplication.CreateBuilder(args);
//...
builder.Services.Configure<HostOptions>(
     opts => opts.ShutdownTimeout = TimeSpan.FromSeconds(30));
//...
var app = builder.Build();

Solution 3:

var builder = WebApplication.CreateBuilder(args);
//...
builder.Services.PostConfigureAll<HostOptions>(opts =>
    opts.ShutdownTimeout = TimeSpan.FromSeconds(30));
//...
var app = builder.Build();

Solution 3 will be applied after all others.


问:
Error while starting chromedriver from java application on raspberry pi
I want to run my java standalone jar on my raspberry pi (Model 3B+). It depends on seleneium, so it needs chromedriver. I have installed java 14 and also chromedrivers version 95.0.4638.78-rpt6 via

```<code>sudo apt-get install chromium-chromedriver
</code>```

now I have installed:

```<code>dpkg -l | grep chromium
ii  chromium-browser                     95.0.4638.78-rpt6                armhf        Chromium web browser, open-source version of
ii  chromium-browser-l10n                95.0.4638.78-rpt6                all          chromium-browser language packages
ii  chromium-chromedriver                95.0.4638.78-rpt6                armhf        WebDriver driver for the Chromium Browser
ii  chromium-codecs-ffmpeg-extra         95.0.4638.78-rpt6                armhf        Extra ffmpeg codecs for the Chromium Browser
ii  rpi-chromium-mods                    20220111
</code>```

When I start my application now, I get this log:

```<code>WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.bouncycastle.jcajce.provider.drbg.DRBG                                                     (file:/home/pi/StreamCrawler.jar) to constructor sun.security.provider.Sun()
WARNING: Please consider reporting this to the maintainers of org.bouncycastle.j                                                    cajce.provider.drbg.DRBG
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflect                                                    ive access operations
WARNING: All illegal access operations will be denied in a future release
/usr/bin/chromedriver: 5: Syntax error: word unexpected (expecting ")")
Feb 06, 2022 6:39:21 PM org.openqa.selenium.os.OsProcess checkForError
SEVERE: org.apache.commons.exec.ExecuteException: Process exited with an error: 2 (Exit value: 2)
Exception in thread "Thread-1" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: 'unknown', revision: 'e82be7d358', time: '2018-11-14T08:24:01'
System info: host: 'raspberrypi', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'arm', os.version: '5.10.92-v7+', java.version: '14'
Driver info: driver.version: ChromeDriver
        at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:202)
        at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:188)
        at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:147)
        at crawler.RequestCrawler.getPlaylistURL(RequestCrawler.java:48)
        at crawler.StreamCrawler.crawl(StreamCrawler.java:29)
        at crawler.StateChecker.run(StateChecker.java:37)
        at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:11309/status] to be available after 20017 ms
        at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
        at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:197)
        ... 11 more
Caused by: java.util.concurrent.TimeoutException
        at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:204)
        at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156)
        at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
        ... 12 more
</code>```

On my windows machine it runs fine. But on windows I am using chromedriver 98, not 95. Now I am not sure what to do as next step.

Option A is an update of the chromedrivers to 98 on my raspberry. But when I am checking out https://archive.raspberrypi.org/debian/pool/main/c/chromium-browser/, there is no 98. In https://chromedriver.storage.googleapis.com/index.html?path=98.0.4758.80/ I can find a 98 Linux version but how to install that file without extension?

Option B is a java application which runs with chromedrivers 95. Currently I use this selenium version:

```<code>   <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.141.59</version>
    </dependency>
</code>```

Would it run if I use an older version? And which version do I need?

Is there maybe an other better option? Thanks for help!

答:
Within the Raspberrypi chromium-browser archive the latest version seems chromium-browser v95.

So with the combination of:

selenium=3.141.59

chromium-browser=95.0.4638.78

chromedriver=95.0.4638.69

would be definately good to go.

Body:
I want to run my java standalone jar on my raspberry pi (Model 3B+). It depends on seleneium, so it needs chromedriver. I have installed java 14 and also chromedrivers version 95.0.4638.78-rpt6 via

sudo apt-get install chromium-chromedriver

now I have installed:

dpkg -l | grep chromium
ii  chromium-browser                     95.0.4638.78-rpt6                armhf        Chromium web browser, open-source version of
ii  chromium-browser-l10n                95.0.4638.78-rpt6                all          chromium-browser language packages
ii  chromium-chromedriver                95.0.4638.78-rpt6                armhf        WebDriver driver for the Chromium Browser
ii  chromium-codecs-ffmpeg-extra         95.0.4638.78-rpt6                armhf        Extra ffmpeg codecs for the Chromium Browser
ii  rpi-chromium-mods                    20220111

When I start my application now, I get this log:

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.bouncycastle.jcajce.provider.drbg.DRBG                                                     (file:/home/pi/StreamCrawler.jar) to constructor sun.security.provider.Sun()
WARNING: Please consider reporting this to the maintainers of org.bouncycastle.j                                                    cajce.provider.drbg.DRBG
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflect                                                    ive access operations
WARNING: All illegal access operations will be denied in a future release
/usr/bin/chromedriver: 5: Syntax error: word unexpected (expecting ")")
Feb 06, 2022 6:39:21 PM org.openqa.selenium.os.OsProcess checkForError
SEVERE: org.apache.commons.exec.ExecuteException: Process exited with an error: 2 (Exit value: 2)
Exception in thread "Thread-1" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: 'unknown', revision: 'e82be7d358', time: '2018-11-14T08:24:01'
System info: host: 'raspberrypi', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'arm', os.version: '5.10.92-v7+', java.version: '14'
Driver info: driver.version: ChromeDriver
        at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:202)
        at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:188)
        at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:147)
        at crawler.RequestCrawler.getPlaylistURL(RequestCrawler.java:48)
        at crawler.StreamCrawler.crawl(StreamCrawler.java:29)
        at crawler.StateChecker.run(StateChecker.java:37)
        at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:11309/status] to be available after 20017 ms
        at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
        at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:197)
        ... 11 more
Caused by: java.util.concurrent.TimeoutException
        at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:204)
        at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156)
        at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
        ... 12 more

On my windows machine it runs fine. But on windows I am using chromedriver 98, not 95. Now I am not sure what to do as next step.

Option A is an update of the chromedrivers to 98 on my raspberry. But when I am checking out https://archive.raspberrypi.org/debian/pool/main/c/chromium-browser/, there is no 98. In https://chromedriver.storage.googleapis.com/index.html?path=98.0.4758.80/ I can find a 98 Linux version but how to install that file without extension?

Option B is a java application which runs with chromedrivers 95. Currently I use this selenium version:

   <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.141.59</version>
    </dependency>

Would it run if I use an older version? And which version do I need?

Is there maybe an other better option? Thanks for help!


问:
How to create an np.array from another np.array if the element of a third np.array of the same index is zero?
Suppose I have

a = np.array([0, 1, 3, 0])
b = np.array([[4,5],[7,8],[9,5],[8,2]])
```
<p>How can I create a third array</p>
```c = [[4,5],[8,2]]
```

with a list comprehension?

答: c = np.array([b[i] for i in range(len(b)) if a[i] == 0])

Body:
Suppose I have

a = np.array([0, 1, 3, 0])
b = np.array([[4,5],[7,8],[9,5],[8,2]])

How can I create a third array

c = [[4,5],[8,2]]

with a list comprehension?


问:
Add blank option to top of select and make it the selected option in IE
HTML:

```<code><select id="dropdown">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
</code>```

jQuery:

```<code>$("#dropdown").prepend("<option value='' selected='selected'></option>");
</code>```

When I run this in FireFox or Chrome, the drop down has the newly inserted blank option selected. When I run it in IE8, it still has Volvo selected. Any ideas?

http://jsfiddle.net/YFu2h/

答:
Change it to this, and it'll work:

```<code>$("#theSelectId").prepend("<option value=''></option>").val('');
</code>```

http://jsfiddle.net/YFu2h/1/

It seems that IE only evaluates the selected attribute when it first encounters the select.

Body:
HTML:

<select id="dropdown">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

jQuery:

$("#dropdown").prepend("<option value='' selected='selected'></option>");

When I run this in FireFox or Chrome, the drop down has the newly inserted blank option selected. When I run it in IE8, it still has Volvo selected. Any ideas?

http://jsfiddle.net/YFu2h/

Body:
Change it to this, and it'll work:

$("#theSelectId").prepend("<option value=''></option>").val('');

http://jsfiddle.net/YFu2h/1/

It seems that IE only evaluates the selected attribute when it first encounters the select.


问:
How to package my python project to be runnable from command line?
I've coded my python project and have succeeded in publishing it to test pypi. However, now I can't figure out how to correctly configure it as a console script. Upon running my_project on the command line, I get the following stack trace:

```<code>Traceback (most recent call last):
  File "/home/thatcoolcoder/.local/bin/my_project", line 5, in <module>
    from my_project.__main__ import main
ModuleNotFoundError: No module named 'my_project'
</code>```

Clearly, it's created a script to run but the script is then failing to import my actual code.

Folder structure:

```<code>pyproject.toml
setup.cfg
my_project
├── __init__.py (empty)
├── __main__.py
</code>```

Relevant sections of setup.cfg:

```<code>[metadata]
name = my-project
version = 1.0.5

...

[options]
package_dir =
    = my_project
packages = find:

...

[options.packages.find]
where = my_project

[options.entry_points]
console_scripts =
    my_project = my_project.__main__:main
</code>```

pyproject.toml (probably not relevant)

```<code>[build-system]
requires = [
    "setuptools>=42",
    "wheel"
]
</code>```

__main__.py:

```<code>from my_project import foo

def main():
    foo.bar()

if __name__ == '__main__':
    main()
</code>```

To build and upload, I'm running the following: (python is python 3.10)

```<code>python -m build
python -m twine upload --repository testpypi dist/*
</code>```

Then to install and run:

```<code>pip install -i https://test.pypi.org/pypi/ --extra-index-url https://pypi.org/simple my-project --upgrade

my_project
</code>```

How can I make this console script work?

Also, this current method of setting console_scripts only allows it to be run as my_project; is it possible to also make it work by python -m my_project? Or perhaps this will work once my main issue is fixed.

答:
I finally got back to this problem today and it appears that I was using an incorrect source layout, which caused the pip module installation to not work. I switched to a directory structure like this one:

```<code>├── src
│   └── mypackage
│       ├── __init__.py
│       └── mod1.py
├── setup.py
└── setup.cfg
</code>```

and modified the relevant parts of my setup.cfg:

```<code>[options]
package_dir=
    =src
packages=find:

[options.packages.find]
where=src
</code>```

Then I can run it like python -m mypackage. This also made the console scripts work. It works on Linux but I presume it also works on other systems.

Body:
I've coded my python project and have succeeded in publishing it to test pypi. However, now I can't figure out how to correctly configure it as a console script. Upon running my_project on the command line, I get the following stack trace:

Traceback (most recent call last):
  File "/home/thatcoolcoder/.local/bin/my_project", line 5, in <module>
    from my_project.__main__ import main
ModuleNotFoundError: No module named 'my_project'

Clearly, it's created a script to run but the script is then failing to import my actual code.

Folder structure:

pyproject.toml
setup.cfg
my_project
├── __init__.py (empty)
├── __main__.py

Relevant sections of setup.cfg:

[metadata]
name = my-project
version = 1.0.5

...

[options]
package_dir =
    = my_project
packages = find:

...

[options.packages.find]
where = my_project

[options.entry_points]
console_scripts =
    my_project = my_project.__main__:main

pyproject.toml (probably not relevant)

[build-system]
requires = [
    "setuptools>=42",
    "wheel"
]

__main__.py:

from my_project import foo

def main():
    foo.bar()

if __name__ == '__main__':
    main()

To build and upload, I'm running the following: (python is python 3.10)

python -m build
python -m twine upload --repository testpypi dist/*

Then to install and run:

pip install -i https://test.pypi.org/pypi/ --extra-index-url https://pypi.org/simple my-project --upgrade

my_project

How can I make this console script work?

Also, this current method of setting console_scripts only allows it to be run as my_project; is it possible to also make it work by python -m my_project? Or perhaps this will work once my main issue is fixed.

Body:
I finally got back to this problem today and it appears that I was using an incorrect source layout, which caused the pip module installation to not work. I switched to a directory structure like this one:

├── src
│   └── mypackage
│       ├── __init__.py
│       └── mod1.py
├── setup.py
└── setup.cfg

and modified the relevant parts of my setup.cfg:

[options]
package_dir=
    =src
packages=find:

[options.packages.find]
where=src

Then I can run it like python -m mypackage. This also made the console scripts work. It works on Linux but I presume it also works on other systems.


问:
Histogram of string in C
I need to find how many times letters appear in string. But I need to ignore the difference between lowercase and uppercase letters.

```<code>#include <stdio.h>
#include <string.h>
void stringHistogram(char *s) {
  int i, len = 0, counts[256] = {0};
  len = strlen(s);
  for (i = 0; i < len; i++) {
    counts[(s[i])]++;
  }
  for (i = 65; i < 123; i++) {
      if(i>=91&&i<=96)continue;
    if (counts[i] > 0)
       printf("%c occurs %d times.\n", i, counts[i]);
  }
}
int main() {
  char s[] = "!!!!!PrOgraMMing -------iN C Is easy....";
  stringHistogram(s);

  return 0;
}
</code>```

For example in this string "I" appears once and "i" appears twice. I want to add these two numbers and print number of them as one character. Program output should be "I appears 3 times."
Could you help me modify these code?

答:
here is another solution:

```<code>#include <stdio.h>
#include <string.h>
#include <ctype.h>

void stringHistogram(char *s) {

  size_t len = 0;
  size_t counts[256] = {0};

  len = strlen(s);

  for (size_t ii = 0; ii < len; ++ii) {
    size_t idx = (size_t)s[ii];
    if((idx > 64) && (idx < 91)){
      idx += 32;
    }
    counts[idx]++;
  }

  for (size_t ii = 0; ii < 255; ++ii) {
    if(0 != isprint((char)ii)){
      if (counts[ii] > 0){
        printf("%lu [%c] occurs %lu times.\n", ii, (char)ii, counts[ii]);
      }
    }
  }
  return;
}

int main() {
  char s[] = "!!!!!PrOgraMMing -------iN C Is easy....";
  stringHistogram(s);

  return 0;
}
</code>```

first like 0___________, I handled upper/lower case while counting, also I used size_t over int (it's an unsigned type)

My output is

```<code>32 [ ] occurs 4 times.
33 [!] occurs 5 times.
45 [-] occurs 7 times.
46 [.] occurs 4 times.
97 [a] occurs 2 times.
99 [c] occurs 1 times.
101 [e] occurs 1 times.
103 [g] occurs 2 times.
105 [i] occurs 3 times.
109 [m] occurs 2 times.
110 [n] occurs 2 times.
111 [o] occurs 1 times.
112 [p] occurs 1 times.
114 [r] occurs 2 times.
115 [s] occurs 2 times.
121 [y] occurs 1 times.
</code>```

Title: Histogram of string in C

Body:
I need to find how many times letters appear in string. But I need to ignore the difference between lowercase and uppercase letters.

#include <stdio.h>
#include <string.h>
void stringHistogram(char *s) {
  int i, len = 0, counts[256] = {0};
  len = strlen(s);
  for (i = 0; i < len; i++) {
    counts[(s[i])]++;
  }
  for (i = 65; i < 123; i++) {
      if(i>=91&&i<=96)continue;
    if (counts[i] > 0)
       printf("%c occurs %d times.\n", i, counts[i]);
  }
}
int main() {
  char s[] = "!!!!!PrOgraMMing -------iN C Is easy....";
  stringHistogram(s);

  return 0;
}

For example in this string "I" appears once and "i" appears twice. I want to add these two numbers and print number of them as one character. Program output should be "I appears 3 times."
Could you help me modify these code?

Body:
here is another solution:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void stringHistogram(char *s) {

  size_t len = 0;
  size_t counts[256] = {0};

  len = strlen(s);

  for (size_t ii = 0; ii < len; ++ii) {
    size_t idx = (size_t)s[ii];
    if((idx > 64) && (idx < 91)){
      idx += 32;
    }
    counts[idx]++;
  }

  for (size_t ii = 0; ii < 255; ++ii) {
    if(0 != isprint((char)ii)){
      if (counts[ii] > 0){
        printf("%lu [%c] occurs %lu times.\n", ii, (char)ii, counts[ii]);
      }
    }
  }
  return;
}

int main() {
  char s[] = "!!!!!PrOgraMMing -------iN C Is easy....";
  stringHistogram(s);

  return 0;
}

first like 0___________, I handled upper/lower case while counting, also I used size_t over int (it's an unsigned type)

My output is

32 [ ] occurs 4 times.
33 [!] occurs 5 times.
45 [-] occurs 7 times.
46 [.] occurs 4 times.
97 [a] occurs 2 times.
99 [c] occurs 1 times.
101 [e] occurs 1 times.
103 [g] occurs 2 times.
105 [i] occurs 3 times.
109 [m] occurs 2 times.
110 [n] occurs 2 times.
111 [o] occurs 1 times.
112 [p] occurs 1 times.
114 [r] occurs 2 times.
115 [s] occurs 2 times.
121 [y] occurs 1 times.


问:
Figuring out correct numpy transpose for 3*3*3 array
Suppose I have a 3*3*3 array x. I would like to find out an array y, such that such that y[0,1,2] = x[1,2,0], or more generally, y[a,b,c]= x[b,c,a]. I can try numpy.transpose

```<code>import numpy as np
x = np.arange(27).reshape((3,3,3))
y = np.transpose(x, [2,0,1])
print(x[0,1,2],x[1,2,0])
print(y[0,1,2])
</code>```

The output is

```<code>5 15
15
</code>```

The result 15,15 is what I expected (the first 15 is the reference value from x[1,2,0]; the second is from y[0,1,2]) . However, I found the transpose [2,0,1] by drawing in a paper.

```<code>B C A
A B C
</code>```

by inspection, the transpose should be [2,0,1], the last entry in the upper row goes to 1st in the lower row; the middle goes last; the first go middle. Is there any automatic and hopefully efficient way to do it (like any standard function in numpy/sympy)?

Given the input y[a,b,c]= x[b,c,a], output [2,0,1]?

答:
I find easier to explore tranpose with a example with shape like (2,3,4), each axis is different.

But sticking with your (3,3,3)

```<code>In [23]: x = np.arange(27).reshape(3,3,3)
In [24]: x
Out[24]:
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])
In [25]: x[0,1,2]
Out[25]: 5
</code>```

Your sample transpose:

```<code>In [26]: y = x.transpose(2,0,1)
In [27]: y
Out[27]:
array([[[ 0,  3,  6],
        [ 9, 12, 15],
        [18, 21, 24]],

       [[ 1,  4,  7],
        [10, 13, 16],
        [19, 22, 25]],

       [[ 2,  5,  8],
        [11, 14, 17],
        [20, 23, 26]]])
</code>```

We get the same 5 with

```<code>In [28]: y[2,0,1]
Out[28]: 5
</code>```

We could get that (2,0,1) by applying the same transposing values:

```<code>In [31]: idx = np.array((0,1,2))   # use an array for ease of indexing
In [32]: idx[[2,0,1]]
Out[32]: array([2, 0, 1])
</code>```

The way I think about the trapose (2,0,1), we are moving the last axis, 2, to the front, and preserving the order of the other 2.

With differing dimensions, it's easier to visualize the change:

```<code>In [33]: z=np.arange(2*3*4).reshape(2,3,4)
In [34]: z
Out[34]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
In [35]: z.transpose(2,0,1)
Out[35]:
array([[[ 0,  4,  8],
        [12, 16, 20]],

       [[ 1,  5,  9],
        [13, 17, 21]],

       [[ 2,  6, 10],
        [14, 18, 22]],

       [[ 3,  7, 11],
        [15, 19, 23]]])
In [36]: _.shape
Out[36]: (4, 2, 3)
</code>```

np.swapaxes is another compiled function for making these changes.  np.rollaxis is another, though it's python code that ends up calling transpose.

I haven't tried to follow all of your reasoning, though I think you want a kind reverse of the transpose numbers, one where you specify the result order, and want how to get them.

Body:
Suppose I have a 3*3*3 array x. I would like to find out an array y, such that such that y[0,1,2] = x[1,2,0], or more generally, y[a,b,c]= x[b,c,a]. I can try numpy.transpose

import numpy as np
x = np.arange(27).reshape((3,3,3))
y = np.transpose(x, [2,0,1])
print(x[0,1,2],x[1,2,0])
print(y[0,1,2])

The output is

5 15
15

The result 15,15 is what I expected (the first 15 is the reference value from x[1,2,0]; the second is from y[0,1,2]) . However, I found the transpose [2,0,1] by drawing in a paper.

B C A
A B C

by inspection, the transpose should be [2,0,1], the last entry in the upper row goes to 1st in the lower row; the middle goes last; the first go middle. Is there any automatic and hopefully efficient way to do it (like any standard function in numpy/sympy)?

Given the input y[a,b,c]= x[b,c,a], output [2,0,1]?

Body:
I find easier to explore tranpose with a example with shape like (2,3,4), each axis is different.

But sticking with your (3,3,3)

In [23]: x = np.arange(27).reshape(3,3,3)
In [24]: x
Out[24]:
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])
In [25]: x[0,1,2]
Out[25]: 5

Your sample transpose:

In [26]: y = x.transpose(2,0,1)
In [27]: y
Out[27]:
array([[[ 0,  3,  6],
        [ 9, 12, 15],
        [18, 21, 24]],

       [[ 1,  4,  7],
        [10, 13, 16],
        [19, 22, 25]],

       [[ 2,  5,  8],
        [11, 14, 17],
        [20, 23, 26]]])

We get the same 5 with

In [28]: y[2,0,1]
Out[28]: 5

We could get that (2,0,1) by applying the same transposing values:

In [31]: idx = np.array((0,1,2))   # use an array for ease of indexing
In [32]: idx[[2,0,1]]
Out[32]: array([2, 0, 1])

The way I think about the trapose (2,0,1), we are moving the last axis, 2, to the front, and preserving the order of the other 2.

With differing dimensions, it's easier to visualize the change:

In [33]: z=np.arange(2*3*4).reshape(2,3,4)
In [34]: z
Out[34]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
In [35]: z.transpose(2,0,1)
Out[35]:
array([[[ 0,  4,  8],
        [12, 16, 20]],

       [[ 1,  5,  9],
        [13, 17, 21]],

       [[ 2,  6, 10],
        [14, 18, 22]],

       [[ 3,  7, 11],
        [15, 19, 23]]])
In [36]: _.shape
Out[36]: (4, 2, 3)

np.swapaxes is another compiled function for making these changes.  np.rollaxis is another, though it's python code that ends up calling transpose.

I haven't tried to follow all of your reasoning, though I think you want a kind reverse of the transpose numbers, one where you specify the result order, and want how to get them.


问:
Auto Generate Reference if HTML field left blank using MYSQL count of foreign key
I have a input field in a basic html form which the user can either add their own reference number, or they can leave this input blank.  However I want it so that if the user leaves the field blank that the sql will generate a reference number based on a count of a foreign key in my mysql table.

```<code>INSERT INTO my_table (`reference`,)
VALUES (CASE {$inputValue}
            WHEN '' THEN sum(case when `fk` CONTAINS {$inputFK} then 1 else 0 end)
            ELSE {$inputValue}
        END)
</code>```

When I've run the above code I get '#1111 - Invalid use of group function'

Is there a better way of doing this, or is there a way of fixing the above code?

答:
Like the commants already explained , you need some selects to run this query

```<code>CREATE TABLE my_table (reference int, colum1 varchar(50) , fk varchar(50))
</code>```

```<code>INSERT INTO my_table (reference)
SELECT CASE `colum1`
            WHEN '' THEN (SELECT  sum( `fk` = 'test' ) FROM my_table)
            ELSE 1
        END
        FROM my_table
</code>```

```<code>SELECT * FROM  my_table
</code>```
```
reference | colum1 | fk
--------: | :----- | :-
```

db<>fiddle here

Body:
I have a input field in a basic html form which the user can either add their own reference number, or they can leave this input blank.  However I want it so that if the user leaves the field blank that the sql will generate a reference number based on a count of a foreign key in my mysql table.

INSERT INTO my_table (`reference`,)
VALUES (CASE {$inputValue}
            WHEN '' THEN sum(case when `fk` CONTAINS {$inputFK} then 1 else 0 end)
            ELSE {$inputValue}
        END)

When I've run the above code I get '#1111 - Invalid use of group function'

Is there a better way of doing this, or is there a way of fixing the above code?

Body:
Like the commants already explained , you need some selects to run this query

CREATE TABLE my_table (reference int, colum1 varchar(50) , fk varchar(50))

INSERT INTO my_table (reference)
SELECT CASE `colum1`
            WHEN '' THEN (SELECT  sum( `fk` = 'test' ) FROM my_table)
            ELSE 1
        END
        FROM my_table

SELECT * FROM  my_table

reference | colum1 | fk
--------: | :----- | :-

db<>fiddle here


问:
Recursive behavior
Why does the following executes such that the print statement is called as often as it recursed but the count variable, count, when x == 1 is never reached.

```<code>def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1 # when x == 1

  count_bits(int(n/2), count)
  print("counter")

  return count

</code>```

why is it necessary to recurse with the return statement?  Because if the recursive call is above the return statement the code
returns the wrong output but with the recursive call called with
return keyword, everything works well.  Typically, the print statement
prints 'counter' as often as it recursed showing that the recursive call
works.

On the other hand, if "return" follows after the recursive call, it returns the count from the base condition, correctly.

```<code>def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1

  return count_bits(int(n/2), count)
</code>```

答:
You have to return recursion result, as reccurent function meaning is to count current step you have to get result of previous step

```<code>F_k = F_k-1 * a + b  # simple example
</code>```

Means that you have to get result of F_k-1 from F_k and count current result using it.

Title: Recursive behavior

Body:
Why does the following executes such that the print statement is called as often as it recursed but the count variable, count, when x == 1 is never reached.

def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1 # when x == 1

  count_bits(int(n/2), count)
  print("counter")

  return count

why is it necessary to recurse with the return statement?  Because if the recursive call is above the return statement the code
returns the wrong output but with the recursive call called with
return keyword, everything works well.  Typically, the print statement
prints 'counter' as often as it recursed showing that the recursive call
works.

On the other hand, if "return" follows after the recursive call, it returns the count from the base condition, correctly.

def count_bits(n, count = 0):
  x = n % 2
  if n == 1:
    return count + 1

  if n < 1:
    return count

  if x == 1:
    count += 1

  return count_bits(int(n/2), count)

Body:
You have to return recursion result, as reccurent function meaning is to count current step you have to get result of previous step

F_k = F_k-1 * a + b  # simple example

Means that you have to get result of F_k-1 from F_k and count current result using it.


问:
Need help: localized a bug but still can't quash it
The program below is a substantial simplification of one that worked but in spite of hours of effort I can't identify why the following bug occurs:
Everything works as expected except that when the line "if behavior[2,0] > t then goright(brain,stimulus) end" is executed, the line "stimulus.each {|n| stimulus[n,0]=0 }" does NOT reset all of the elements of the stimulus vector to 0 as it does otherwise.  Instead the "1" placed there by the previous trip through the "for c in (0..$Choices)" remains thereby generating double behaviors (both a left and right turn) when only one is expected.  I've commented out everything that I believe is irrelevant yet it still happens.</p>
```<code>class Matrix
  def []=(i, j, x)
    @rows[i][j] = x
  end
end #code to allow putting individual elements in matrix at i,j
brain=  Matrix[ [90,0,0,0,0,0,0,0,0,0,0],
                [0,90,0,10,10,10,10,0,0,0,0],
                [0,0,90,10,10,10,10,0,0,0,0] ]
longmem=Matrix[ [90,0,0,0,0,0,0,0,0,0,0],
                [0,90,0,10,10,10,10,0,0,0,0],
                [0,0,90,10,10,10,10,0,0,0,0] ]
stimulus=Matrix.column_vector([0,0,0,0,0,0,0,0,0,0,0])
behavior=Matrix.column_vector([0,0,0])
t=89 # t=threshold
# decay_rate=2
$Stimmax=10
$Behavmax=2
$Choices=2
# begin defining behavioral methods
def learn(ix, brain, stimulus)
    psp=20
    for j in (8..$Stimmax)
    if brain[ix,j] > 0 then brain[ix,j]+= 20 end #modified hunting for bug
    end # for j
end # learn
#def positive_fixer(brain,stimulus,longmem,energy)
#   reinf=0.9
#   for i in (0..$Behavmax)
#   for j in (7..$Stimmax)
#      if longmem[i,j]>0 then longmem[i,j]+=(reinf*(brain[i,j]-longmem[i,j])).round end
#    end
#    end
#    learn(0, brain, stimulus)
#end #positive fixer comment out in bug hunt
def goleft(brain,stimulus)
    puts "              Left Turn"
    learn(1,brain,stimulus)
end # def left
def goright(brain,stimulus)
    puts "              Right Turn"
    learn(2,brain,stimulus)
end # def right
# end defining behavioral methods

# begin MAIN PROGRAM
for c in (0..$Choices)
stimulus.each {|n| stimulus[n,0]=0 }
# SET ALL STIMS TO O
puts "Should by all 0s"
stimulus.to_a.each {|r| puts r.inspect} # aid in bug hunt

stimulus[rand(1..2),0]= 1
#add print stimulus vector for debugging
puts "Should by just a single 1"
stimulus.to_a.each {|r| puts r.inspect} # aid in bug hunt

# memory decay
#for i in (0..$Behavmax)
#for j in (7..$Stimmax)
#  if brain[i,j]>longmem[i,j] then brain[i,j]+=-(brain[i,j]-longmem[i,j])/decay_rate end
#  if brain[i,j]<longmem[i,j] then brain[i,j]+=-1*((brain[i,j]+longmem[i,j])/decay_rate) end
#end #for j
#end #for i
# memory decay commented out in search for bug

behavior=brain*stimulus
if behavior[0,0] > t then positive_fixer(brain, stimulus, longmem, energy) end
if behavior[1,0] > t then goleft(brain,stimulus) end
if behavior[2,0] > t then goright(brain,stimulus) end
end #for c
puts
brain.to_a.each {|r| puts r.inspect}
# end main program```
</code>```

答:
the line "stimulus.each {|n| stimulus[n,0]=0 }" does NOT reset all of the elements of the stimulus vector to 0 as it does otherwise

One of the way how to reset vector:

```<code>require 'matrix'

vector = Matrix.column_vector([1, 2, 3])
# => Matrix[[1], [2], [3]]

vector.each_with_index { |_, i| vector[i, 0] = 0 }
# => Matrix[[0], [0], [0]]
</code>```

So you need to use each_with_index instead of each

Body:
The program below is a substantial simplification of one that worked but in spite of hours of effort I can't identify why the following bug occurs:
Everything works as expected except that when the line "if behavior[2,0] > t then goright(brain,stimulus) end" is executed, the line "stimulus.each {|n| stimulus[n,0]=0 }" does NOT reset all of the elements of the stimulus vector to 0 as it does otherwise.  Instead the "1" placed there by the previous trip through the "for c in (0..$Choices)" remains thereby generating double behaviors (both a left and right turn) when only one is expected.  I've commented out everything that I believe is irrelevant yet it still happens.

class Matrix
  def []=(i, j, x)
    @rows[i][j] = x
  end
end #code to allow putting individual elements in matrix at i,j
brain=  Matrix[ [90,0,0,0,0,0,0,0,0,0,0],
                [0,90,0,10,10,10,10,0,0,0,0],
                [0,0,90,10,10,10,10,0,0,0,0] ]
longmem=Matrix[ [90,0,0,0,0,0,0,0,0,0,0],
                [0,90,0,10,10,10,10,0,0,0,0],
                [0,0,90,10,10,10,10,0,0,0,0] ]
stimulus=Matrix.column_vector([0,0,0,0,0,0,0,0,0,0,0])
behavior=Matrix.column_vector([0,0,0])
t=89 # t=threshold
# decay_rate=2
$Stimmax=10
$Behavmax=2
$Choices=2
# begin defining behavioral methods
def learn(ix, brain, stimulus)
    psp=20
    for j in (8..$Stimmax)
    if brain[ix,j] > 0 then brain[ix,j]+= 20 end #modified hunting for bug
    end # for j
end # learn
#def positive_fixer(brain,stimulus,longmem,energy)
#   reinf=0.9
#   for i in (0..$Behavmax)
#   for j in (7..$Stimmax)
#      if longmem[i,j]>0 then longmem[i,j]+=(reinf*(brain[i,j]-longmem[i,j])).round end
#    end
#    end
#    learn(0, brain, stimulus)
#end #positive fixer comment out in bug hunt
def goleft(brain,stimulus)
    puts "              Left Turn"
    learn(1,brain,stimulus)
end # def left
def goright(brain,stimulus)
    puts "              Right Turn"
    learn(2,brain,stimulus)
end # def right
# end defining behavioral methods

# begin MAIN PROGRAM
for c in (0..$Choices)
stimulus.each {|n| stimulus[n,0]=0 }
# SET ALL STIMS TO O
puts "Should by all 0s"
stimulus.to_a.each {|r| puts r.inspect} # aid in bug hunt

stimulus[rand(1..2),0]= 1
#add print stimulus vector for debugging
puts "Should by just a single 1"
stimulus.to_a.each {|r| puts r.inspect} # aid in bug hunt

# memory decay
#for i in (0..$Behavmax)
#for j in (7..$Stimmax)
#  if brain[i,j]>longmem[i,j] then brain[i,j]+=-(brain[i,j]-longmem[i,j])/decay_rate end
#  if brain[i,j]<longmem[i,j] then brain[i,j]+=-1*((brain[i,j]+longmem[i,j])/decay_rate) end
#end #for j
#end #for i
# memory decay commented out in search for bug

behavior=brain*stimulus
if behavior[0,0] > t then positive_fixer(brain, stimulus, longmem, energy) end
if behavior[1,0] > t then goleft(brain,stimulus) end
if behavior[2,0] > t then goright(brain,stimulus) end
end #for c
puts
brain.to_a.each {|r| puts r.inspect}
# end main program```

Body:
the line "stimulus.each {|n| stimulus[n,0]=0 }" does NOT reset all of the elements of the stimulus vector to 0 as it does otherwise

One of the way how to reset vector:

require 'matrix'

vector = Matrix.column_vector([1, 2, 3])
# => Matrix[[1], [2], [3]]

vector.each_with_index { |_, i| vector[i, 0] = 0 }
# => Matrix[[0], [0], [0]]

So you need to use each_with_index instead of each


问:
Create file from output on single line
I am currently stuck on a question which asks:

A ‘file’ in the /proc directory contains information about the processor. Use commands to search this file for information about the processor cache, and save the output in a file cache.txt

I have managed to get to the output part but cannot get the output to save to a file. Here is my sample code:

```<code>cat /proc/cpuinfo | grep -i 'cache'
</code>```

This display the desired output on the terminal

```<code>cat /proc/cpuinfo | grep -i 'cache' > cache.txt
</code>```

This is my modified command to save the output to a file called cache.txt but it says the file is not there. My only thoughts could be as I am running the command from inside /proc, do I need to specify the file path for the file cache.txt I want to create?

Sample code:

/proc $ cat /proc/cpuinfo | grep -i cache > cache.txt
bash: cache.txt: No such file or directory
```

答:
You're doing it in /proc directory which is a virtual filesystem,
you cannot create new files in it. You have to save output cache.txt
in a different directory. For example, to save it in your home
directory type cd with no arguments and then do:

```<code>grep -i cache /proc/cpuinfo > cache.txt
</code>```

cache.txt will look like that:

```<code>$ cat cache.txt
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
</code>```

Title: Create file from output on single line

Body:
I am currently stuck on a question which asks:

A ‘file’ in the /proc directory contains information about the processor. Use commands to search this file for information about the processor cache, and save the output in a file cache.txt

I have managed to get to the output part but cannot get the output to save to a file. Here is my sample code:

cat /proc/cpuinfo | grep -i 'cache'

This display the desired output on the terminal

cat /proc/cpuinfo | grep -i 'cache' > cache.txt

This is my modified command to save the output to a file called cache.txt but it says the file is not there. My only thoughts could be as I am running the command from inside /proc, do I need to specify the file path for the file cache.txt I want to create?

Sample code:

/proc $ cat /proc/cpuinfo | grep -i cache > cache.txt
bash: cache.txt: No such file or directory

Body:
You're doing it in /proc directory which is a virtual filesystem,
you cannot create new files in it. You have to save output cache.txt
in a different directory. For example, to save it in your home
directory type cd with no arguments and then do:

grep -i cache /proc/cpuinfo > cache.txt

cache.txt will look like that:

$ cat cache.txt
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64
cache size      : 8192 KB
cache_alignment : 64


问:
Bin folder is not visible in the explorer for a Maven project
I have crated a Maven project for my selenium test. I have added some testNG classes under src/test/java. The package name under which testNG classes are is named as "tests".

Now I have created a Project in Jenkins to build that project and I am using a .bat file to do that.

The .bat file looks like this:

set classpath=D:\Learning\Eclipse\Workspace\CabiGroup\target\test-classes;D:\Learning\Eclipse\Workspace\CabiGroup\lib\*

java -cp bin;D:\Learning\Eclipse\Workspace\CabiGroup\lib\* org.testng.TestNG XML\CabiDirect.xml XML\CabiHome.xml

In the classpath; I understand that I need to provide the path of bin folder of the Maven project; but I do not see any bin folder under the Maven Project in my Workspace.

That is why the build is failing with error:

Cannot find class in classpath: tests.VerifyAdvanceSearch

(VerifyAdvanceSearch.class is a testNG class under tests package).

How do I see the bin folder under workspace and provide the path in the .bat file properly?

Please help.

Edit: I have followed what can I do to make display the bin folder on eclipse? but it did not help.

答:
Try the following command for latest testNG :

java -cp C:\eclipse-workspace\EclipseProject\src\main\java\tests; C:\eclipse-workspace\EclipseProject\jars* org.testng.TestNG testng.xml

Also for the latest testNG you need to have atleast the following jars in the jars folder specified :
testng.jar
jcommander.jar


问:
How to use terminal color palette with curses
I can't get the terminal color palette to work with curses.

```<code>import curses

def main(stdscr):
    curses.use_default_colors()
    for i in range(0,7):
        stdscr.addstr("Hello", curses.color_pair(i))
    stdscr.getch()

curses.wrapper(main)
</code>```

This python script yields the following screen:

However, I do have more colors in my gnome-terminal palette. How can I access them within curses?

答:
Late answer, but might help out other curses newbies.

curses.start_color (called by curses.wrapper) initializes 8 basic colors, so one would assume you can just use curses.color_pair(i) to display colors. However, curses does not only have colors, it also has color_pairs, and only the later can be used to display color, but start_color only initializes colors, and use_default_colors only initializes color number -1.

This means that after this point you do not have any color pairs set up, only colors. You have to set up the color pairs manually before you can draw. You can also change the definitions of the induvidual colors if you wish, but as others have demonstrated you usually already have quite a few set up.

TL;DR:

If you struggle with no colors displayed after calling wrapper or start_color and use_default_colors, you might be missing the fact that you have to set up color pairs with init_pair before drawing in color.

Body:
I can't get the terminal color palette to work with curses.

import curses

def main(stdscr):
    curses.use_default_colors()
    for i in range(0,7):
        stdscr.addstr("Hello", curses.color_pair(i))
    stdscr.getch()

curses.wrapper(main)

This python script yields the following screen:

However, I do have more colors in my gnome-terminal palette. How can I access them within curses?


问:
GraphQL-Ruby : When executing a mutation, get error Variable $...... is declared by ....(mutation).... but not used
I'm cutting my teeth on GraphQL ruby here and this seems like it should be basic but the docs make this very difficult to grok. Where did I go wrong here?

My goal is simply to make a GraphQL mutation in my Ruby app.

app/graphql/types/mutation_type.rb

```<code>module Types
  class MutationType < Types::BaseObject

    field :name, String

    field :create_trip, mutation: Mutations::CreateTrip
  end
end
</code>```

Here's the mutation in
app/graphql/mutations/create_trip.rb

```<code>class Mutations::CreateTrip < Mutations::BaseMutation
  null true
  argument :leavingFrom, String

  field :name, String

  type Types::TripType

  def resolve(leavingFrom: )
    new_trip = Trip.create(leavingFrom: leavingFrom)

    # this doesn't really do anything--- this is proof-of-concept code only
    if new_trip.save
      # Successful creation, return the created object with no errors
      {
        trip: trip,
        errors: [],
      }
    else
      # Failed save, return the errors to the client
      {
        trip: nil,
        errors: trip.errors.full_messages
      }
    end
  end
end
</code>```

the app/graphql/types/trip_type.rb is

```<code># frozen_string_literal: true

module Types
  class TripType < Types::BaseObject
    field :id, ID, null: false
    field :traveling_party_id, Integer
    field :name, String
  end
end
</code>```

When I run this mutation:

```<code>mutation CreateTrip($leavingFrom: String) {
  name
}
</code>```

(with some data for leavingFrom)

I get this unexpected result: "Variable $leavingFrom is declared by CreateTrip but not used"

Expected result: My mutation calls through to the resolve on my GraphQL mutation.

I think the problem is in my query, because it does not look like the Ruby code ever called. Contrary to the message itself, the  leavingFrom is indeed used by the mutation in the resolve body.

答:
```<code>mutation CreateTrip($leavingFrom: String) {
  CreateTrip(leavingFrom: $leavingFrom) {
    name
  }
}
</code>```

Body:
I'm cutting my teeth on GraphQL ruby here and this seems like it should be basic but the docs make this very difficult to grok. Where did I go wrong here?

My goal is simply to make a GraphQL mutation in my Ruby app.

app/graphql/types/mutation_type.rb

module Types
  class MutationType < Types::BaseObject

    field :name, String

    field :create_trip, mutation: Mutations::CreateTrip
  end
end

Here's the mutation in
app/graphql/mutations/create_trip.rb

class Mutations::CreateTrip < Mutations::BaseMutation
  null true
  argument :leavingFrom, String

  field :name, String

  type Types::TripType

  def resolve(leavingFrom: )
    new_trip = Trip.create(leavingFrom: leavingFrom)

    # this doesn't really do anything--- this is proof-of-concept code only
    if new_trip.save
      # Successful creation, return the created object with no errors
      {
        trip: trip,
        errors: [],
      }
    else
      # Failed save, return the errors to the client
      {
        trip: nil,
        errors: trip.errors.full_messages
      }
    end
  end
end

the app/graphql/types/trip_type.rb is

# frozen_string_literal: true

module Types
  class TripType < Types::BaseObject
    field :id, ID, null: false
    field :traveling_party_id, Integer
    field :name, String
  end
end

When I run this mutation:

mutation CreateTrip($leavingFrom: String) {
  name
}

(with some data for leavingFrom)

I get this unexpected result: "Variable $leavingFrom is declared by CreateTrip but not used"

Expected result: My mutation calls through to the resolve on my GraphQL mutation.

I think the problem is in my query, because it does not look like the Ruby code ever called. Contrary to the message itself, the  leavingFrom is indeed used by the mutation in the resolve body.