问:
Calculations involving mixed type elements in columns - np.nan, float, string elements
I have a dataframe where columns include mixed type elements and I need to do some calculations among them. Assume this dataframe:

```<code>A=[20, np.nan, 10, 'give', np.nan, np.nan]
B=[10, np.nan, np.nan, np.nan, 10, 'given']

frame=pd.DataFrame(zip(A,B))
frame.columns=['A', 'B']
</code>```

I want to populate the difference of B from A. If I do frame['diff']=frame['A']-frame['B'] it does not give the result I need. Instead, the result I would want is in the 'desired diff' column.

Basically, if A or B has a number, then B or A should be 0. If a string is in A, while B is NaN, then it should write "positive" and, in the vice versa case, it should write "negative". See below:

```<code>frame
      A      B  diff  desired diff
0    20     10    10            10
1   NaN    NaN   NaN           NaN
2    10    NaN   NaN            10
3  give    NaN   NaN      positive
4   NaN     10   NaN           -10
5   NaN  given   NaN      negative
</code>```

Just for the record, I have tried to implement np.where and np.select and some conditions such as np.logical_and(frame['A'].apply(lambda x: isinstance(x, float)), frame['B'].isna()) to achieve the desired output, but without success.

Thanks in advance for your suggestions!

答:
Use to_numeric with errors='coerce' for check non numeric and no missing values and set new values by numpy.select and subtract values by Series.sub with fill_value=0 parameter:

```<code>a = pd.to_numeric(frame['A'], errors='coerce')
m1 = frame['A'].notna()
m2 = a.isna()

b = pd.to_numeric(frame['B'], errors='coerce')
m3 = frame['B'].notna()
m4 = b.isna()

frame['new'] = np.select([m1 & m2, m3 & m4],
                         ['positive', 'negative'],
                         default = a.sub(b, fill_value=0))
print (frame)
      A      B       new
0    20     10      10.0
1   NaN    NaN       nan
2    10    NaN      10.0
3  give    NaN  positive
4   NaN     10     -10.0
5   NaN  given  negative
</code>```

Body:
I have a dataframe where columns include mixed type elements and I need to do some calculations among them. Assume this dataframe:

A=[20, np.nan, 10, 'give', np.nan, np.nan]
B=[10, np.nan, np.nan, np.nan, 10, 'given']

frame=pd.DataFrame(zip(A,B))
frame.columns=['A', 'B']

I want to populate the difference of B from A. If I do frame['diff']=frame['A']-frame['B'] it does not give the result I need. Instead, the result I would want is in the 'desired diff' column.

Basically, if A or B has a number, then B or A should be 0. If a string is in A, while B is NaN, then it should write "positive" and, in the vice versa case, it should write "negative". See below:

frame
      A      B  diff  desired diff
0    20     10    10            10
1   NaN    NaN   NaN           NaN
2    10    NaN   NaN            10
3  give    NaN   NaN      positive
4   NaN     10   NaN           -10
5   NaN  given   NaN      negative

Just for the record, I have tried to implement np.where and np.select and some conditions such as np.logical_and(frame['A'].apply(lambda x: isinstance(x, float)), frame['B'].isna()) to achieve the desired output, but without success.

Thanks in advance for your suggestions!

Body:
Use to_numeric with errors='coerce' for check non numeric and no missing values and set new values by numpy.select and subtract values by Series.sub with fill_value=0 parameter:

a = pd.to_numeric(frame['A'], errors='coerce')
m1 = frame['A'].notna()
m2 = a.isna()

b = pd.to_numeric(frame['B'], errors='coerce')
m3 = frame['B'].notna()
m4 = b.isna()

frame['new'] = np.select([m1 & m2, m3 & m4],
                         ['positive', 'negative'],
                         default = a.sub(b, fill_value=0))
print (frame)
      A      B       new
0    20     10      10.0
1   NaN    NaN       nan
2    10    NaN      10.0
3  give    NaN  positive
4   NaN     10     -10.0
5   NaN  given  negative


来源: stackexchange

问:
Error unable to find the package name called v8-devel on RHEL8
I am trying to install v8-devel rpm package on RHEL 8.1 but unable to find it in all repositories of RHEL as well as in EPEL. I tried all the possibilities as shown below:

```<code>yum install v8-devel
yum install v8-devel
yum --enablerepo=* install v8*
yum search v8-devel
yum whatprovides v8-devel
dnf install v8-devel
dnf install v8-devel
dnf install v8*
</code>```

i do have following EPEL for RHEL8 installed on my server.

```<code> epel
 epel-modular
 epel-source
</code>```

I am also able to install similar package on RHEL 7 with the help of EPEL.

I am just curious to know whether name of (v8-devel) got changed for RHEL8 or not?

Can someone help me to find out v8-devel rpm and install it via EPEL on RHEL8.1.

Thanks in advance.

答:
If we talk about R package the way is to run R shell and exec command:

```<code>> install.packages("v8")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to install v8-devel rpm package on RHEL 8.1 but unable to find it in all repositories of RHEL as well as in EPEL. I tried all the possibilities as shown below:

yum install v8-devel
yum install v8-devel
yum --enablerepo=* install v8*
yum search v8-devel
yum whatprovides v8-devel
dnf install v8-devel
dnf install v8-devel
dnf install v8*

i do have following EPEL for RHEL8 installed on my server.

 epel
 epel-modular
 epel-source

I am also able to install similar package on RHEL 7 with the help of EPEL.

I am just curious to know whether name of (v8-devel) got changed for RHEL8 or not?

Can someone help me to find out v8-devel rpm and install it via EPEL on RHEL8.1.

Thanks in advance.

Body:
If we talk about R package the way is to run R shell and exec command:

> install.packages("v8")


问:
Apply a list of regular expressions in PHP
I have a long list of regular expressions in an ignore.txt, and another long list in an include.txt file.  What would be the quickest way to apply these using PHP against data contained in a sample.html file such that any matches found in include are captured, but then anything matching in ignore.txt is excluded?</p>

答:
If your include.txt and ignore.txt files are setup so that they're only regular expressions, and there's one expression per line, you can use PHP's file() function. That will load the files into an array where each individual line is an element in the array. You can use file_get_contents() to load the sample.html file in as a string.

preg_match() or preg_match_all() do not actually take arrays as input, like preg_replace() does. You will need to loop over your array of expressions using something like foreach and applying an individual call to one of the matching functions to get your results.

I think preg_match_all() will suit your needs best, because it sounds like you're wanting to pull all of the matches out of the entire file, not just the first one. Once you have your full list of matches, then you'd apply your filter using the data from ignore.txt in a similar manner.

ContentLicense: CC BY-SA 3.0


问:
What is the equivalent of AWS Dead Letter Queue in Google Cloud Platform?
What is the equivalent of AWS Dead Letter Queue in Google Cloud Platform? How is the failed records managed in Google Cloud Platform?</p>

答:
As of beginning 2020, Google Pub/Sub now supports configuring dead letter topic when creating a subscription (just like other major queueing systems):

```<code>$ gcloud pubsub subscriptions create SUBSCRIPTION \
  --topic=TOPIC \
  --topic_project=TOPIC_PROJECT \
  --max-delivery-attempts=NUMBER_OF_RETRIES \
  --dead-letter-topic=DEAD_LETTER_TOPIC \
  --dead-letter-topic-project=DEAD_LETTER_TOPIC_PROJECT
</code>```

After reaching the NUMBER_OF_RETRIES the message that failed to be delivered to TOPIC will be published to DEAD_LETTER_TOPIC instead (which can be useful for further analysis, triggering an alert or other automated action, etc.)

As stated in the docs, the Cloud Pub/Sub service account associated with the enclosing subscription's parent project (i.e., service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have permission to Publish() to this topic and Acknowledge() messages on this subscription.

Docs: https://cloud.google.com/sdk/gcloud/reference/pubsub/subscriptions/create#--max-delivery-attempts

Body:
As of beginning 2020, Google Pub/Sub now supports configuring dead letter topic when creating a subscription (just like other major queueing systems):

$ gcloud pubsub subscriptions create SUBSCRIPTION \
  --topic=TOPIC \
  --topic_project=TOPIC_PROJECT \
  --max-delivery-attempts=NUMBER_OF_RETRIES \
  --dead-letter-topic=DEAD_LETTER_TOPIC \
  --dead-letter-topic-project=DEAD_LETTER_TOPIC_PROJECT

After reaching the NUMBER_OF_RETRIES the message that failed to be delivered to TOPIC will be published to DEAD_LETTER_TOPIC instead (which can be useful for further analysis, triggering an alert or other automated action, etc.)

As stated in the docs, the Cloud Pub/Sub service account associated with the enclosing subscription's parent project (i.e., service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have permission to Publish() to this topic and Acknowledge() messages on this subscription.

Docs: https://cloud.google.com/sdk/gcloud/reference/pubsub/subscriptions/create#--max-delivery-attempts


问:
How do I find the base address of "NOR Flash/PSRAM/SRAM/ROM/LCD 1" on a STM32H743?
With the STM32F427, the generated code included a couple of different #defines which mapped to the address to which I needed to write:

e.g.

```<code>#define FMC_BANK3_BASE  ((uint32_t)(0x60000000 | 0x08000000))
</code>```

Where can I find similar #defines in a CubeMX generated project for the STM32H743?  (I think I need FMC_BANK1 here.)

I'm looking for the address at which the memory/lcd is mapped, not the address of the controller registers (which I already have).

答:
While I couldn't find any appropriate #defines, reading the manual I found:

Figure 95. FMC memory banks (default mapping)

This showed that Bank 1 is located at 0x6000 0000, as it is on the stm32f413.

Body:
With the STM32F427, the generated code included a couple of different #defines which mapped to the address to which I needed to write:

e.g.

#define FMC_BANK3_BASE  ((uint32_t)(0x60000000 | 0x08000000))

Where can I find similar #defines in a CubeMX generated project for the STM32H743?  (I think I need FMC_BANK1 here.)

I'm looking for the address at which the memory/lcd is mapped, not the address of the controller registers (which I already have).


问:
Get with Flutter a nested JSON from Firebase DataSnapshot
I use flutter with package firebase_database. With the code

```<code>final FirebaseDatabase _database = FirebaseDatabase.instance;

@override
void initState() {
  super.initState();
  _newsList = new List();

  _newsQuery = _database
     .reference()
     .child('news')
     .orderByChild('published')
     .limitToFirst(10);

  _newsQuery.onChildAdded.listen(_onEntryAdded);
}

_onEntryAdded(Event event) {
  setState(() {
    News n = News.fromSnapshot(event.snapshot);
    _newsList.add(n);
  });
}
</code>```

i get a perfect list _newsList of all queried items. The news class is

```<code> import 'package:firebase_database/firebase_database.dart';

 class News {
   String key;
   String image;
   String text;
   String title;
   String published;

   News(this.image, this.text, this.published);

   News.fromSnapshot(DataSnapshot snapshot) :
     key = snapshot.key,
     text = snapshot.value["text"],
     title = snapshot.value["title"],
     image = snapshot.value["image"],
     published = snapshot.value["published"];

   toJson() {
     return {
     "image": image,
     "text": text,
     "title": title,
     "published": published,
   };
  }
}
</code>```

The json-structure in the database is:

```<code>database
|__news
    |__post1
    |    |__text: "Lorem ipsum"
    |    |__title: "Title of post"
    |
    |__post2
         |__ ...
</code>```

Now i want to load a nested json-structure from the database with

```<code>database
|__news
    |__category1
    |    |
    |    |__post1
    |    |    |__text: "Lorem ipsum 1"
    |    |    |__title: "Title of post1"
    |    |__post2
    |    |    |__text: "Lorem ipsum 2"
    |    |    |__title: "Title of post2"
    |    |__description: "description text"
    |    |__id: "id of category"
    |    .
    |    .
    |
    |__category2
    |    |
    |    |__post34
    |    |    |__text: "Lorem ipsum 34"
    |    |    |__title: "Title of post34"
    |    .
    |    .
</code>```

I try to find a solution to load the nested DataSnapshots into  class, but i always get exceptions. The best code i tried so far is

```<code> class News {
   final List<Category> categories;

   News({this.categories});

   factory News.fromSnapshot(DataSnapshot snapshot) {

   List<dynamic> listS = snapshot.value;

   listS.forEach((value) =>
     print('V $value')
   );

   List<Category> list = listS.map((i) => Category.fromJson(i)).toList();

   return News(
     categories: list
   );

 }
</code>```

But this throws the exception

E/flutter ( 5882): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '_InternalLinkedHashMap' is not a subtype of type 'Map'
E/flutter ( 5882): #0      new News.fromSnapshot. (package:app/models/news.dart:23:55)
E/flutter ( 5882): #1      MappedListIterable.elementAt (dart:_internal/iterable.dart:414:29)
E/flutter ( 5882): #2      ListIterable.toList (dart:_internal/iterable.dart:219:19)

I found in flutter and dart no code-example to load nested json with DataSnapshot. Do you know any code-sample?

If you want to see my full code, then look at https://github.com/matthiaw/gbh_app. The not working part is the nested json in calendar at https://github.com/matthiaw/gbh_app/blob/4de0f20f6162801db86ef6644609829c27a4dd76/lib/models/calendar.dart

答:
I was also looking on how to handle nested json objects in Flutter with Cloud Firestore and found your post. As I solved my problem, maybe it helps you too: In the "fromJson"-factory of my model I had to parse every element in the list with jsonEncode and jsonDecode before adding it to the model.

in the DatabaseService:

```<code>Future<LocationRecordings> getLocationRecordings(String location) async {
 DocumentReference document = locationRecordingsCollection.document((location));

 DocumentSnapshot documentSnapshot =  await document.get();
 var data = LocationRecordings.fromJson(documentSnapshot.data);
 return data;
}
</code>```

in the model:

```<code>factory LocationRecordings.fromJson(Map<String, dynamic> json) {
 List<Recording> recList = [];

 List<dynamic>.from(json['recordings']).forEach((content) {
      Recording recording = Recording.fromJson(jsonDecode(jsonEncode(content)));
      recList.add(recording);
   });
 return new LocationRecordings(recordings: recList, state: json['state']);
}
</code>```

Body:
I use flutter with package firebase_database. With the code

final FirebaseDatabase _database = FirebaseDatabase.instance;

@override
void initState() {
  super.initState();
  _newsList = new List();

  _newsQuery = _database
     .reference()
     .child('news')
     .orderByChild('published')
     .limitToFirst(10);

  _newsQuery.onChildAdded.listen(_onEntryAdded);
}

_onEntryAdded(Event event) {
  setState(() {
    News n = News.fromSnapshot(event.snapshot);
    _newsList.add(n);
  });
}

i get a perfect list _newsList of all queried items. The news class is

 import 'package:firebase_database/firebase_database.dart';

 class News {
   String key;
   String image;
   String text;
   String title;
   String published;

   News(this.image, this.text, this.published);

   News.fromSnapshot(DataSnapshot snapshot) :
     key = snapshot.key,
     text = snapshot.value["text"],
     title = snapshot.value["title"],
     image = snapshot.value["image"],
     published = snapshot.value["published"];

   toJson() {
     return {
     "image": image,
     "text": text,
     "title": title,
     "published": published,
   };
  }
}

The json-structure in the database is:

database
|__news
    |__post1
    |    |__text: "Lorem ipsum"
    |    |__title: "Title of post"
    |
    |__post2
         |__ ...

Now i want to load a nested json-structure from the database with

database
|__news
    |__category1
    |    |
    |    |__post1
    |    |    |__text: "Lorem ipsum 1"
    |    |    |__title: "Title of post1"
    |    |__post2
    |    |    |__text: "Lorem ipsum 2"
    |    |    |__title: "Title of post2"
    |    |__description: "description text"
    |    |__id: "id of category"
    |    .
    |    .
    |
    |__category2
    |    |
    |    |__post34
    |    |    |__text: "Lorem ipsum 34"
    |    |    |__title: "Title of post34"
    |    .
    |    .

I try to find a solution to load the nested DataSnapshots into  class, but i always get exceptions. The best code i tried so far is

 class News {
   final List<Category> categories;

   News({this.categories});

   factory News.fromSnapshot(DataSnapshot snapshot) {

   List<dynamic> listS = snapshot.value;

   listS.forEach((value) =>
     print('V $value')
   );

   List<Category> list = listS.map((i) => Category.fromJson(i)).toList();

   return News(
     categories: list
   );

 }

But this throws the exception

E/flutter ( 5882): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '_InternalLinkedHashMap' is not a subtype of type 'Map'
E/flutter ( 5882): #0      new News.fromSnapshot. (package:app/models/news.dart:23:55)
E/flutter ( 5882): #1      MappedListIterable.elementAt (dart:_internal/iterable.dart:414:29)
E/flutter ( 5882): #2      ListIterable.toList (dart:_internal/iterable.dart:219:19)

I found in flutter and dart no code-example to load nested json with DataSnapshot. Do you know any code-sample?

If you want to see my full code, then look at https://github.com/matthiaw/gbh_app. The not working part is the nested json in calendar at https://github.com/matthiaw/gbh_app/blob/4de0f20f6162801db86ef6644609829c27a4dd76/lib/models/calendar.dart

Body:
I was also looking on how to handle nested json objects in Flutter with Cloud Firestore and found your post. As I solved my problem, maybe it helps you too: In the "fromJson"-factory of my model I had to parse every element in the list with jsonEncode and jsonDecode before adding it to the model.

in the DatabaseService:

Future<LocationRecordings> getLocationRecordings(String location) async {
 DocumentReference document = locationRecordingsCollection.document((location));

 DocumentSnapshot documentSnapshot =  await document.get();
 var data = LocationRecordings.fromJson(documentSnapshot.data);
 return data;
}

in the model:

factory LocationRecordings.fromJson(Map<String, dynamic> json) {
 List<Recording> recList = [];

 List<dynamic>.from(json['recordings']).forEach((content) {
      Recording recording = Recording.fromJson(jsonDecode(jsonEncode(content)));
      recList.add(recording);
   });
 return new LocationRecordings(recordings: recList, state: json['state']);
}


问:
svelte + express (without sapper) - how to send props/communicate with the server?
I am coding a little website to be my homepage.

So far I managed to do what I wanted with express and handlebars templates but I am doing this website to test my boundaries, and I lack using a frontend framework and working with web components.

so for the sake of challenge and learning, I settled on svelte

which is not exactly a framework, I read, but is a delight to write with and seems very promising on the performance side.

The problem is I want to keep the hand on my website, and sapper, the full framework that comes with svelte, is a bit too much of a black box for me.

(you put this file here and that file there,

compile with this complex configuration you shouldn't touch

and BOOM you got routes)

What I would like is to use express to manage the routes and then render the svelte app, either with a different page/app for a route, or the same app with different variables.

Could anybody point me in the right direction?
I considered using sessions or a socket, but I have no idea of how to listen to this client-side and the documentation/articles about svelte are sparse and all talk about sapper.

here are a few lines of code I wrote in a test app. I know it's not the way you do it but it was for curiosity's sake

// --------------server.js
// ...
app.set('view engine', 'hbs')
app.set('views', path.join(__dirname, '../views'))
// Using a view engine on TOP of svelte
// is certainly a bad choice

app.use(express.static('app/public'))
// to make the svelte compiled .js and .css available

app.get('/test', (req, res) => {
  res.render('home', {user:true})
  // I tried to send props like this
  // it did not get the props in svelte,
  // but what I found is that svelte ADDS itself to the page
  // and does not remove the HBS code, event though it is in the target container
})

```

edit

I will finally use sapper, thank you for the advices...
I really would like them to implement some sort of svelte middleware that allows to render/serve pages individually (once they are build of course)

答:
If you do it like that, splitting your web application into several independent svelte apps that are served from express, then you need to keep the (web-)application wide state on the backend or keep it in the local storage on the browser. You can't use the states provided by sveltes store (writeable, etc), because that's in-memory and destroyed whenever you navigate to a new page (via express).

If sapper is to much magic but you want to keep running a single-page-app, have a look at svelte-spa-router. That isn't configuration based.

Body:
I am coding a little website to be my homepage.

So far I managed to do what I wanted with express and handlebars templates but I am doing this website to test my boundaries, and I lack using a frontend framework and working with web components.

so for the sake of challenge and learning, I settled on svelte

which is not exactly a framework, I read, but is a delight to write with and seems very promising on the performance side.

The problem is I want to keep the hand on my website, and sapper, the full framework that comes with svelte, is a bit too much of a black box for me.

(you put this file here and that file there,

compile with this complex configuration you shouldn't touch

and BOOM you got routes)

What I would like is to use express to manage the routes and then render the svelte app, either with a different page/app for a route, or the same app with different variables.

Could anybody point me in the right direction?
I considered using sessions or a socket, but I have no idea of how to listen to this client-side and the documentation/articles about svelte are sparse and all talk about sapper.

here are a few lines of code I wrote in a test app. I know it's not the way you do it but it was for curiosity's sake

// --------------server.js
// ...
app.set('view engine', 'hbs')
app.set('views', path.join(__dirname, '../views'))
// Using a view engine on TOP of svelte
// is certainly a bad choice

app.use(express.static('app/public'))
// to make the svelte compiled .js and .css available

app.get('/test', (req, res) => {
  res.render('home', {user:true})
  // I tried to send props like this
  // it did not get the props in svelte,
  // but what I found is that svelte ADDS itself to the page
  // and does not remove the HBS code, event though it is in the target container
})

edit

I will finally use sapper, thank you for the advices...
I really would like them to implement some sort of svelte middleware that allows to render/serve pages individually (once they are build of course)


问:
How to avoid opening IE on every loop?
After the great help I got here over the past days, I managed to finish my code for downloading xlsm files by selecting a range in excel and looping through the range.
Now I used the IE method, which opens a new IE instance for every entry. How can I avoid that ? I have over 50 entries in my range.

Is there a way to not open IE but still scrape the online data I need for the objID ?

```<code>Sub DownloadUpdate_Reviews()

Dim i As Range
Dim Rng As Range
Dim versch As String
Dim ordner As String
Dim dlURL As String
Dim enumm As String
Dim objID As String
Dim HTMLDoc As MSHTML.HTMLDocument
Dim ie As InternetExplorerMedium
Dim ifrm As MSHTML.HTMLDocument
Dim ifrm2 As MSHTML.HTMLDocument
Dim HttpReq As Object

'Select range
On Error Resume Next
    Set Rng = Application.InputBox( _
      Title:="Select Range", _
      prompt:="Select cell range with the E-numbers to download", _
      Type:=8)
  On Error GoTo 0
  If Rng Is Nothing Then Exit Sub

  'Limit of allowed number of blank cells
  If WorksheetFunction.CountBlank(Rng) > 10 Then
  MsgBox "Too many blank cells in range.Limit is set to 10. Please dont select a whole column as range"
GoTo Toomanyblanks
End If

'Saving location
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select where to save"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath

If .Show = -1 Then
ordner = .SelectedItems(1)
End If
End With

Application.ScreenUpdating = False
Set ie = New InternetExplorerMedium

'Skip blank cells in range
For Each i In Rng
If i = "" Then
GoTo Blank_i
End If

versch = i.Offset(0, -1)

'Get the objID
enumm = i
'Set ie = New InternetExplorerMedium
ie.Visible = True
ie.navigate "https://plm.corp.int:10090/enovia/common/emxFullSearch.jsp?pageConfig=tvc:pageconfig//tvc/search/AutonomySearch.xml&tvcTable=true&showInitialResults=true&cancelLabel=Close&minRequiredChars=3&genericDelete=true&selection=multiple&txtTextSearch=" & [i] & "&targetLocation=popup"

While ie.readyState <> 4 Or ie.Busy: DoEvents: Wend

'choosing the right frame
Set HTMLDoc = ie.document
Set ifrm = HTMLDoc.frames(0).frames(1).frames(0).document
'Debug.Print HTMLDoc.frames(0).frames(1).frames(0).Name

'getting the specific object ID
objID = ifrm.getElementsByName("emxTableRowId")(0).Value
'Debug.Print objID

'start download
dlURL = "https://plm.corp.int:10090/enovia/tvc-action/downloadMultipleFiles?objectId=" & [objID] & ".xlsm"

Set HttpReq = CreateObject("Microsoft.XMLHTTP")
HttpReq.Open "GET", dlURL, False
HttpReq.send

dlURL = HttpReq.responseBody
If HttpReq.Status = 200 Then
    Set oStrm = CreateObject("ADODB.Stream")
    oStrm.Open
    oStrm.Type = 1
    oStrm.Write HttpReq.responseBody
    oStrm.SaveToFile [ordner] & "\" & [i] & "_" & [versch] & ".xlsm", 2 ' 1 = no overwrite, 2 = overwrite"
    oStrm.Close
End If

Blank_i:
Next

'quit InternetExplorer
ie.Quit
Set ie = Nothing

Toomanyblanks:
End Sub

</code>```

Error occurs in the following line: Member not found

```<code>Set ifrm = HTMLDoc.frames(0).frames(1).frames(0).document
</code>```

but it works if i manually navigate the code with F8. i guess, cause it has more execution time ?!

答:
Well, that can be if there is some javascript involved and that isn't ready yet, and needs some more time. A workaround for that can be to try

```<code>Set ifrm = HTMLDoc.frames(0).frames(1).frames(0).document
</code>```

until it works (and have a maximum time limit for like 5 seconds, so you don't get stuck in an endless loop).

```<code>Dim TmrStart As Single
TmrStart = Timer 'initialize timer

Set ifrm = Nothing 'absolutely necessary otherwise the old frame could stay referenced.

Do
    On Error Resume Next
    Set ifrm = HTMLDoc.frames(0).frames(1).frames(0).document
    On Error Goto 0

Loop While TmrStart + 5 > Timer AND ifrm Is Nothing

If ifrm Is Nothing Then
    Msgbox "The iframe was not found within 5 seconds. It finally failed."
End If
</code>```

So this will try to find the iframe until it is found but for maximum 5 seconds. If it finds it earlier then it proceeds.

Title: How to avoid opening IE on every loop?

Body:
After the great help I got here over the past days, I managed to finish my code for downloading xlsm files by selecting a range in excel and looping through the range.
Now I used the IE method, which opens a new IE instance for every entry. How can I avoid that ? I have over 50 entries in my range.

Is there a way to not open IE but still scrape the online data I need for the objID ?

Sub DownloadUpdate_Reviews()

Dim i As Range
Dim Rng As Range
Dim versch As String
Dim ordner As String
Dim dlURL As String
Dim enumm As String
Dim objID As String
Dim HTMLDoc As MSHTML.HTMLDocument
Dim ie As InternetExplorerMedium
Dim ifrm As MSHTML.HTMLDocument
Dim ifrm2 As MSHTML.HTMLDocument
Dim HttpReq As Object

'Select range
On Error Resume Next
    Set Rng = Application.InputBox( _
      Title:="Select Range", _
      prompt:="Select cell range with the E-numbers to download", _
      Type:=8)
  On Error GoTo 0
  If Rng Is Nothing Then Exit Sub

  'Limit of allowed number of blank cells
  If WorksheetFunction.CountBlank(Rng) > 10 Then
  MsgBox "Too many blank cells in range.Limit is set to 10. Please dont select a whole column as range"
GoTo Toomanyblanks
End If

'Saving location
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select where to save"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath

If .Show = -1 Then
ordner = .SelectedItems(1)
End If
End With

Application.ScreenUpdating = False
Set ie = New InternetExplorerMedium

'Skip blank cells in range
For Each i In Rng
If i = "" Then
GoTo Blank_i
End If

versch = i.Offset(0, -1)

'Get the objID
enumm = i
'Set ie = New InternetExplorerMedium
ie.Visible = True
ie.navigate "https://plm.corp.int:10090/enovia/common/emxFullSearch.jsp?pageConfig=tvc:pageconfig//tvc/search/AutonomySearch.xml&tvcTable=true&showInitialResults=true&cancelLabel=Close&minRequiredChars=3&genericDelete=true&selection=multiple&txtTextSearch=" & [i] & "&targetLocation=popup"

While ie.readyState <> 4 Or ie.Busy: DoEvents: Wend

'choosing the right frame
Set HTMLDoc = ie.document
Set ifrm = HTMLDoc.frames(0).frames(1).frames(0).document
'Debug.Print HTMLDoc.frames(0).frames(1).frames(0).Name

'getting the specific object ID
objID = ifrm.getElementsByName("emxTableRowId")(0).Value
'Debug.Print objID

'start download
dlURL = "https://plm.corp.int:10090/enovia/tvc-action/downloadMultipleFiles?objectId=" & [objID] & ".xlsm"

Set HttpReq = CreateObject("Microsoft.XMLHTTP")
HttpReq.Open "GET", dlURL, False
HttpReq.send

dlURL = HttpReq.responseBody
If HttpReq.Status = 200 Then
    Set oStrm = CreateObject("ADODB.Stream")
    oStrm.Open
    oStrm.Type = 1
    oStrm.Write HttpReq.responseBody
    oStrm.SaveToFile [ordner] & "\" & [i] & "_" & [versch] & ".xlsm", 2 ' 1 = no overwrite, 2 = overwrite"
    oStrm.Close
End If

Blank_i:
Next

'quit InternetExplorer
ie.Quit
Set ie = Nothing

Toomanyblanks:
End Sub

Error occurs in the following line: Member not found

Set ifrm = HTMLDoc.frames(0).frames(1).frames(0).document

but it works if i manually navigate the code with F8. i guess, cause it has more execution time ?!

Body:
Well, that can be if there is some javascript involved and that isn't ready yet, and needs some more time. A workaround for that can be to try

Set ifrm = HTMLDoc.frames(0).frames(1).frames(0).document

until it works (and have a maximum time limit for like 5 seconds, so you don't get stuck in an endless loop).

Dim TmrStart As Single
TmrStart = Timer 'initialize timer

Set ifrm = Nothing 'absolutely necessary otherwise the old frame could stay referenced.

Do
    On Error Resume Next
    Set ifrm = HTMLDoc.frames(0).frames(1).frames(0).document
    On Error Goto 0

Loop While TmrStart + 5 > Timer AND ifrm Is Nothing

If ifrm Is Nothing Then
    Msgbox "The iframe was not found within 5 seconds. It finally failed."
End If

So this will try to find the iframe until it is found but for maximum 5 seconds. If it finds it earlier then it proceeds.


问:
How is the process done by detecting all the data on the page using jQuery?
I want to make a progress bar that counts forward with the specified start date and end date line. I can perform the operation I want with the code I wrote. But since there is a lot of code, there is confusion.

I want to follow a more logical way. My current codes are listed below.

MY HTML:

```<code><div id="div1"></div>
<div id="div2"></div>
</code>```

MY jQuery + PHP:

```<code>progressBar(<?php echo strtotime("2020-02-20 10:00:00"); ?>, <?php echo strtotime("2020-02-20 15:00:00"); ?>, <?php echo time(); ?>, '#div1');
progressBar(<?php echo strtotime("2020-02-20 04:00:00"); ?>, <?php echo strtotime("2020-02-20 09:00:00"); ?>, <?php echo time(); ?>, '#div2');

/** Start Time, Stop Time, Now Time, Element Id **/
function progressBar(start, stop, now, element) {
    now++
    var timepast = now - start;
    var duration = stop - start;
    var percent  = ( 100 - ( timepast / duration ) *100 ).toFixed(2);

    $(element).text(percent);

    var timer = setTimeout(function(){
        progressBar(start, stop, now);
    }, 1000);

    if( percent < 0){
        clearInterval(timer);
    }
}
</code>```

Desired Method/Result:

I want it to automatically detect and count in real time all the elements that are set as follows.

I need jQuery (Javascript) codes to detect these HTML codes.

```<code><div id="div1" data-start="2020-02-20 10:00:00" data-stop="2020-02-20 15:00:00"></div>
<div id="div2" data-start="2020-02-20 04:00:00" data-stop="2020-02-20 09:00:00"></div>
</code>```

答:
To find the matching divs, use:

```<code> $("[data-start]")
</code>```

and to extra the data-start/data-stop, use

```<code>$(this).data("start")
</code>```

jquery attempts to type-coerce from .data(), so this should be enough, but you could wrap in new Date() to be sure

Giving an update to your existing code, add:

```<code>$(function() {
    $("[data-start")].each(function() {
        progressBar(
            new Date($(this).data("start")),
            new Date($(this).data("stop")),
            new Date(),
            this);
    });
});
</code>```

Body:
I want to make a progress bar that counts forward with the specified start date and end date line. I can perform the operation I want with the code I wrote. But since there is a lot of code, there is confusion.

I want to follow a more logical way. My current codes are listed below.

MY HTML:

MY jQuery + PHP:

progressBar(<?php echo strtotime("2020-02-20 10:00:00"); ?>, <?php echo strtotime("2020-02-20 15:00:00"); ?>, <?php echo time(); ?>, '#div1');
progressBar(<?php echo strtotime("2020-02-20 04:00:00"); ?>, <?php echo strtotime("2020-02-20 09:00:00"); ?>, <?php echo time(); ?>, '#div2');

/** Start Time, Stop Time, Now Time, Element Id **/
function progressBar(start, stop, now, element) {
    now++
    var timepast = now - start;
    var duration = stop - start;
    var percent  = ( 100 - ( timepast / duration ) *100 ).toFixed(2);

    $(element).text(percent);

    var timer = setTimeout(function(){
        progressBar(start, stop, now);
    }, 1000);

    if( percent < 0){
        clearInterval(timer);
    }
}

Desired Method/Result:

I want it to automatically detect and count in real time all the elements that are set as follows.

I need jQuery (Javascript) codes to detect these HTML codes.

Body:
To find the matching divs, use:

 $("[data-start]")

and to extra the data-start/data-stop, use

$(this).data("start")

jquery attempts to type-coerce from .data(), so this should be enough, but you could wrap in new Date() to be sure

Giving an update to your existing code, add:

$(function() {
    $("[data-start")].each(function() {
        progressBar(
            new Date($(this).data("start")),
            new Date($(this).data("stop")),
            new Date(),
            this);
    });
});


问:
Why nginx works with error 301 HTTP1.1/Moved permanently?
I'm trying to configure Location directive on my nginx web-server (Ubuntu).

I can have access to:
http://127.0.0.1/app1/
BUT when I'm trying to get access whitout slash in the end like:
http://127.0.0.1/app1
I get an error 301 HTTP1.1/Moved permanently

I have following nginx config:

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
}

http {

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}
</code>```

Looks like everything is OK.

And following default.conf:

```<code>server {
        listen 80 default_server;

        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        location /app1/ {
                root /var/www/html/;
                index index.html;
                try_files $uri $uri/ /app1/index.html;
        }
}
</code>```

Curl output
http://127.0.0.1/app1/

```<code>root@ubuntu-test:/etc/nginx/sites-available# curl 127.0.0.1/app1/ -Iv
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> HEAD /app1/ HTTP/1.1
> Host: 127.0.0.1
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Server: nginx/1.14.0 (Ubuntu)
Server: nginx/1.14.0 (Ubuntu)
< Date: Thu, 20 Feb 2020 09:14:12 GMT
Date: Thu, 20 Feb 2020 09:14:12 GMT
< Content-Type: text/html
Content-Type: text/html
< Content-Length: 5
Content-Length: 5
< Last-Modified: Tue, 18 Feb 2020 10:49:53 GMT
Last-Modified: Tue, 18 Feb 2020 10:49:53 GMT
< Connection: keep-alive
Connection: keep-alive
< ETag: "5e4bc151-5"
ETag: "5e4bc151-5"
< Accept-Ranges: bytes
Accept-Ranges: bytes
<
* Connection #0 to host 127.0.0.1 left intact
</code>```

http://127.0.0.1/app1

```<code>
root@ubuntu-test:/etc/nginx/sites-available# curl 127.0.0.1/app1 -Iv
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> HEAD /app1 HTTP/1.1
> Host: 127.0.0.1
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
HTTP/1.1 301 Moved Permanently
< Server: nginx/1.14.0 (Ubuntu)
Server: nginx/1.14.0 (Ubuntu)
< Date: Thu, 20 Feb 2020 09:19:31 GMT
Date: Thu, 20 Feb 2020 09:19:31 GMT
< Content-Type: text/html
Content-Type: text/html
< Content-Length: 194
Content-Length: 194
< Location: http://127.0.0.1/app1/
Location: http://127.0.0.1/app1/
< Connection: keep-alive
Connection: keep-alive
</code>```

Why does it happen?

答:
Nginx selects the location / block to process the URI /app1 as no other locations are a better match. See how Nginx processes a request.

The $uri/ term of the try_files statement informs Nginx to append a / to any URI that matches a directory. The directory /var/www/html/app1 matches this requirement, so a 301 redirection is generated to append a / to the URI. See this document for details.

In addition, the default behaviour for a URI which ends with a / and points to a directory is to search that directory for a file that matches the index directive. See this document for details.

It is possible to deviate from this default behaviour, but you will need to make a number of changes to your configuration. The location /app1/ needs to lose the trailing / if you want it to match /app1. Your try_files directives need to lose the $uri/ term, if you want to avoid the 301 redirect. You will also lose default index processing, so the index directive will be useless.

Body:
I'm trying to configure Location directive on my nginx web-server (Ubuntu).

I can have access to:
http://127.0.0.1/app1/
BUT when I'm trying to get access whitout slash in the end like:
http://127.0.0.1/app1
I get an error 301 HTTP1.1/Moved permanently

I have following nginx config:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
}

http {

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

Looks like everything is OK.

And following default.conf:

server {
        listen 80 default_server;

        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        location /app1/ {
                root /var/www/html/;
                index index.html;
                try_files $uri $uri/ /app1/index.html;
        }
}

Curl output
http://127.0.0.1/app1/

root@ubuntu-test:/etc/nginx/sites-available# curl 127.0.0.1/app1/ -Iv
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> HEAD /app1/ HTTP/1.1
> Host: 127.0.0.1
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Server: nginx/1.14.0 (Ubuntu)
Server: nginx/1.14.0 (Ubuntu)
< Date: Thu, 20 Feb 2020 09:14:12 GMT
Date: Thu, 20 Feb 2020 09:14:12 GMT
< Content-Type: text/html
Content-Type: text/html
< Content-Length: 5
Content-Length: 5
< Last-Modified: Tue, 18 Feb 2020 10:49:53 GMT
Last-Modified: Tue, 18 Feb 2020 10:49:53 GMT
< Connection: keep-alive
Connection: keep-alive
< ETag: "5e4bc151-5"
ETag: "5e4bc151-5"
< Accept-Ranges: bytes
Accept-Ranges: bytes
<
* Connection #0 to host 127.0.0.1 left intact

http://127.0.0.1/app1

root@ubuntu-test:/etc/nginx/sites-available# curl 127.0.0.1/app1 -Iv
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> HEAD /app1 HTTP/1.1
> Host: 127.0.0.1
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
HTTP/1.1 301 Moved Permanently
< Server: nginx/1.14.0 (Ubuntu)
Server: nginx/1.14.0 (Ubuntu)
< Date: Thu, 20 Feb 2020 09:19:31 GMT
Date: Thu, 20 Feb 2020 09:19:31 GMT
< Content-Type: text/html
Content-Type: text/html
< Content-Length: 194
Content-Length: 194
< Location: http://127.0.0.1/app1/
Location: http://127.0.0.1/app1/
< Connection: keep-alive
Connection: keep-alive

Why does it happen?


问:
Unknown cause of Write Access Violation in linked list
In a recent project, the purpose of which is to modify a linked list through a menu function, I'm coming across a single error that I can't seem to fix, as the line of code is purely vital, and, as far as I can tell, should be working as intended. The message I receive is, "Exception Thrown: write access violation. THIS was nullptr." My node class seems to be the source of the error, with the error being presented over the setNext functions body.

```<code>#include "pch.h"
#include <iostream>
#include <vector>
#include <string>

template<class ItemType>
class Node
{
private:
    ItemType value;
    Node<ItemType>* next;
public:
    Node() {
        next = nullptr;
    }
    Node(const ItemType& val) {
        value = val;
        next = nullptr;
    }
    Node(const ItemType& val, Node<ItemType>* nextVal)
    {
        value = val;
        next = nextVal;
    }
    void setVal(const ItemType& val)
    {
        value = val;
    }
    ItemType getVal() const {
        return value;
    }
    void setNext(Node<ItemType>* nextVal)
    {
        next = nextVal; //Exception thrown here.
    }
    Node<ItemType>* getNext() const
    {
        return next;
    }
};
</code>```

Meanwhile, in my linkedlist class, I narrowed down the line that this exception seemed to cause, as the code runs no further beyond it. It thankfully does not involve most of the other classes, but this specific instance seems to react as if the node I call is a null pointer.

```<code>template<class ItemType>
class linkChain {
private:
    Node<char>* head;
    int count;
    //Node<ItemType>* getPointerTo(const ItemType& target) const;
public:
    linkChain() {
        head = nullptr;
        count = 0;
    }
    linkChain(std::string phrase) : head(nullptr) {
        count = phrase.length();
        for (int i = count - 1; i >= 0; i--) {
            if (head == nullptr) {
                head = new Node<char>();
                head->setVal(phrase[i]);

            }
            else {
                Node<ItemType>* newNode = new Node<char>(phrase[i]);
                newNode->setNext(head);
                head = newNode;
            }
        }
    }
    void append(const linkChain& chain) {
        count += chain.length();
        Node<char>* newNode = head;
        while (newNode != nullptr) {

            newNode = newNode->getNext();
        }
        Node<char>* nextChain = chain.head;
        while (nextChain != nullptr) {
            char nextValu = nextChain->getVal();
            std::cout << nextValu;
            //May be nextVal
            Node<char>* tempNode = new Node<char>(nextValu);

            //THE LINE BELOW THIS
            newNode->setNext(tempNode);
            //THE LINE ABOVE THIS

            nextChain = nextChain->getNext();
            newNode = newNode->getNext();

        }
        newNode = newNode->getNext();
    }

};
</code>```

And here is the code used in the main function to call upon this, where charVal is a linkChain.

```<code>std::cout << "Please enter a string value to test: ";
            std::cin >> testing;
            linkChain<char> addThis = linkChain<char>(testing);
            std::cout << "Is the string inside: " << charVal->submatch(addThis) << "\n";
</code>```

I'm not the strongest with nodes, so any advice would be greatly appreciated on how I can fix this error that I am clueless about. Other online answers have given either vague or unrelated answers to this problem, so they have given me little help.

答:
The following while loop is one definite problem (without a full MCVE, as requested in the comments, I can't properly check for other errors):

    while (newNode != nullptr) {
        newNode = newNode->getNext();
    }
```

<p>When this loop has ended, then <code>newNode</code> <em>will</em> be <code>nullptr</code>! But then, in the next loop, a few lines later, you dereference that <code>nullptr</code> value:</p>

<pre class="lang-cpp prettyprint-override"><code>while (nextChain != nullptr) {
    //...
    //THE LINE BELOW THIS
    newNode->setNext(tempNode);
    //THE LINE ABOVE THIS
    //...
</code>```

What you should be doing, in the first while loop, is checking the next pointer:

    while (newNode>getNext() != nullptr) {
        newNode = newNode->getNext();
    }
```

this loop will exit when you are pointing to the last node in the list.

Body:
In a recent project, the purpose of which is to modify a linked list through a menu function, I'm coming across a single error that I can't seem to fix, as the line of code is purely vital, and, as far as I can tell, should be working as intended. The message I receive is, "Exception Thrown: write access violation. THIS was nullptr." My node class seems to be the source of the error, with the error being presented over the setNext functions body.

#include "pch.h"
#include <iostream>
#include <vector>
#include <string>

template<class ItemType>
class Node
{
private:
    ItemType value;
    Node<ItemType>* next;
public:
    Node() {
        next = nullptr;
    }
    Node(const ItemType& val) {
        value = val;
        next = nullptr;
    }
    Node(const ItemType& val, Node<ItemType>* nextVal)
    {
        value = val;
        next = nextVal;
    }
    void setVal(const ItemType& val)
    {
        value = val;
    }
    ItemType getVal() const {
        return value;
    }
    void setNext(Node<ItemType>* nextVal)
    {
        next = nextVal; //Exception thrown here.
    }
    Node<ItemType>* getNext() const
    {
        return next;
    }
};

Meanwhile, in my linkedlist class, I narrowed down the line that this exception seemed to cause, as the code runs no further beyond it. It thankfully does not involve most of the other classes, but this specific instance seems to react as if the node I call is a null pointer.

template<class ItemType>
class linkChain {
private:
    Node<char>* head;
    int count;
    //Node<ItemType>* getPointerTo(const ItemType& target) const;
public:
    linkChain() {
        head = nullptr;
        count = 0;
    }
    linkChain(std::string phrase) : head(nullptr) {
        count = phrase.length();
        for (int i = count - 1; i >= 0; i--) {
            if (head == nullptr) {
                head = new Node<char>();
                head->setVal(phrase[i]);

            }
            else {
                Node<ItemType>* newNode = new Node<char>(phrase[i]);
                newNode->setNext(head);
                head = newNode;
            }
        }
    }
    void append(const linkChain& chain) {
        count += chain.length();
        Node<char>* newNode = head;
        while (newNode != nullptr) {

            newNode = newNode->getNext();
        }
        Node<char>* nextChain = chain.head;
        while (nextChain != nullptr) {
            char nextValu = nextChain->getVal();
            std::cout << nextValu;
            //May be nextVal
            Node<char>* tempNode = new Node<char>(nextValu);

            //THE LINE BELOW THIS
            newNode->setNext(tempNode);
            //THE LINE ABOVE THIS

            nextChain = nextChain->getNext();
            newNode = newNode->getNext();

        }
        newNode = newNode->getNext();
    }

};

And here is the code used in the main function to call upon this, where charVal is a linkChain.

std::cout << "Please enter a string value to test: ";
            std::cin >> testing;
            linkChain<char> addThis = linkChain<char>(testing);
            std::cout << "Is the string inside: " << charVal->submatch(addThis) << "\n";

I'm not the strongest with nodes, so any advice would be greatly appreciated on how I can fix this error that I am clueless about. Other online answers have given either vague or unrelated answers to this problem, so they have given me little help.

Body:
The following while loop is one definite problem (without a full MCVE, as requested in the comments, I can't properly check for other errors):

    while (newNode != nullptr) {
        newNode = newNode->getNext();
    }

When this loop has ended, then newNode will be nullptr! But then, in the next loop, a few lines later, you dereference that nullptr value:

while (nextChain != nullptr) {
    //...
    //THE LINE BELOW THIS
    newNode->setNext(tempNode);
    //THE LINE ABOVE THIS
    //...

What you should be doing, in the first while loop, is checking the next pointer:

    while (newNode>getNext() != nullptr) {
        newNode = newNode->getNext();
    }

this loop will exit when you are pointing to the last node in the list.


问:
How to make the if statement without repetition of code?
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.</p>

```<code>    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }
</code>```

答:
Create a separate function for setting attribues to the element and the call it in a switch statement:

function setAttrs(element, status) {
  element.setAttribute("class", status);
  element.innerHTML = status;
  return element;
}

function yourFunction {
  // ...

  // since you call it every time, keep it at the top, it will be executed once
  arrow.setAttribute("class", "arrow2");

  switch (allTasks[t].status) {
    case "Completed":
      let tagUpdated = setAttrs(tag, "completed")
      taskCont.appendChild(tagUpdated);
      break;
    case "Past Due":
      let tagUpdated = setAttrs(tag, "pastdue")
      taskCont.appendChild(tagUpdated);
      break;
    case "Duetoday":
      let tagUpdated = setAttrs(tag, "duetoday")
      taskCont.appendChild(tagUpdated);
      break;
    case "Onhold":
      let tagUpdated = setAttrs(tag, "onhold")
      taskCont.appendChild(tagUpdated);
      break;
    case "Canceled":
      let tagUpdated = setAttrs(tag, "canceled")
      taskCont.appendChild(tagUpdated);
      break;
  }
}```

Body:
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.

    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }


问:
How to configure ruby on rails with Apache
i have strugle in connection between J2me and ruby on rails under Webrick server...
dats why i need configure with apache..i saw some tutorials about configuring..but it's not working..</p>

答:
What environment are you coming from? Unix, Mac, Windows? Let's assume you're using some Unix variant, as you should, and Apache2 is already properly installed:

1 - install phusion passenger:
 $ gem install passenger

2 - install passenger-apache2-module:
 $ passenger-install-apache2-module

Be sure to read what the passenger-install-apache2-module command output is telling you, in the end it will give you some lines you have to put in some apache configuration files, if you miss that, it won't work. At all.

3 - Edit your vhosts.conf file (under /etc/apache2/) to define a hostname for your application, point to your application's public folder, etc.
VirtualHost examples

4 - Profit.

Commands listed under 1. and 2. might need admin privileges, it all depends on how your environment is set.

WebRick is not for production environments at all, in fact, it's not really good for development either, if you intend on doing some slightly more complex stuff with your rails applications. Other than that, you didn't really give enough detail about your problem, so I hope this answer at least points you in the right direction.

ContentLicense: CC BY-SA 2.5


问:
Performantly render tens of thousands of spheres of variable size/color/position in Three.js?
This question is picking up from my last question where I found that using Points leads to problems: https://stackoverflow.com/a/60306638/4749956

To solve this you'll need to draw your points using quads instead of points. There are many ways to do that. Draw each quad as a separate mesh or sprite, or merge all the quads into another mesh, or use InstancedMesh where you'll need a matrix per point, or write custom shaders to do points (see the last example on this article)

I've been trying to figure this answer out. My questions are

What is 'instancing'? What is the difference between merging geometries and instancing? And, if I were to do either one of these, what geometry would I use and how would I vary color? I've been looking at this example:

https://github.com/mrdoob/three.js/blob/master/examples/webgl_instancing_performance.html

And I see that for each sphere you would have a geometry which would apply the position and the size (scale?). Would the underlying geometry be a SphereBufferGeometry of unit radius, then? But, how do you apply color?

Also, I read about the custom shader method, and it makes some vague sense. But, it seems more complex. Would the performance be any better than the above?

答:
Based on your previous quesiton...

First off, Instancing is a way to tell three.js to draw the same geometry multiple times but change one more more things for each "instance". IIRC the only thing three.js supports out-of-the-box is setting a different matrix (position, orientatin, scale) for each instance. Past that, like having different colors for example, you have to write custom shaders.

Instancing allows you to ask the system to draw many things with one "ask" instead of an "ask" per thing. That means it ends up being much faster. You can think of it like anything. If want 3 hambergers you could ask someone to make you 1. When they finished you could ask them to make another. When they finished you could ask them to make a 3rd. That would be much slower than just asking them to make 3 hambergers at the start. That's not a perfect analogy but it does point out how asking for multiple things one at a time is less efficient than asking for mulitple things all at once.

Merging meshes is yet another solution, following the bad analogy above , mergeing meshes is like making one big 1pound hamberger instead of three 1/3 pound hamburgers. Flipping one larger burger and putting toppings and buns on one large burger is marginally faster than doing the same to 3 small burgers.

As for which is the best solution for you that depends. In your original code you were just drawing textured quads using Points. Points always draw their quad in screen space. Meshes on the other hand rotate in world space by default so if you made instances of quads or a merged set of quads and try to rotate them they would turn and not face the camera like Points do. If you used sphere geometry then you'd have the issues that instead of only computing 6 vertices per quad with a circle drawn on it, you'd be computing 100s or 1000s of vertices per sphere which would be slower than 6 vertices per quad.

So again it requires a custom shader to keep the points facing the camera.

To do it with instancing the short version is you decide which vertex data are repeated each instance. For example for a textured quad we need 6 vertex positions and 6 uvs. For these you make the normal BufferAttribute

Then you decide which vertex data are unique to each instance. In your case the size, the color, and the center of the point. For each of these we make an InstancedBufferAttribute

We add all of those attributes to an InstancedBufferGeometry and as the last argument we tell it how many instances.

At draw time you can think of it like this

for each instance

set size to the next value in the size attribute

set color to the next value in the color attribute

set center to the next value in the center attribute

call the vertex shader 6 times, with position and uv set to the nth value in their attributes.

In this way you get the same geometry (the positions and uvs) used multiple times but each time a few values (size, color, center) change.

body {
  margin: 0;
}
#c {
  width: 100vw;
  height: 100vh;
  display: block;
}
#info {
  position: absolute;
  right: 0;
  bottom: 0;
  color: red;
  background: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c"></canvas>
<div id="info"></div>
<script type="module">
// Three.js - Picking - RayCaster w/Transparency
// from https://threejsfundamentals.org/threejs/threejs-picking-gpu.html

import * as THREE from "https://threejsfundamentals.org/threejs/resources/threejs/r113/build/three.module.js";

function main() {
  const infoElem = document.querySelector("#info");
  const canvas = document.querySelector("#c");
  const renderer = new THREE.WebGLRenderer({ canvas });

  const fov = 60;
  const aspect = 2; // the canvas default
  const near = 0.1;
  const far = 200;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.z = 30;

  const scene = new THREE.Scene();
  scene.background = new THREE.Color(0);
  const pickingScene = new THREE.Scene();
  pickingScene.background = new THREE.Color(0);

  // put the camera on a pole (parent it to an object)
  // so we can spin the pole to move the camera around the scene
  const cameraPole = new THREE.Object3D();
  scene.add(cameraPole);
  cameraPole.add(camera);

  function randomNormalizedColor() {
    return Math.random();
  }

  function getRandomInt(n) {
    return Math.floor(Math.random() * n);
  }

  function getCanvasRelativePosition(e) {
    const rect = canvas.getBoundingClientRect();
    return {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    };
  }

  const textureLoader = new THREE.TextureLoader();
  const particleTexture =
    "https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/ball.png";

  const vertexShader = `
    attribute float size;
    attribute vec3 customColor;
    attribute vec3 center;

    varying vec3 vColor;
    varying vec2 vUv;

    void main() {
        vColor = customColor;
        vUv = uv;
        vec3 viewOffset = position * size ;
        vec4 mvPosition = modelViewMatrix * vec4(center, 1) + vec4(viewOffset, 0);
        gl_Position = projectionMatrix * mvPosition;
    }
`;

  const fragmentShader = `
    uniform sampler2D texture;
    varying vec3 vColor;
    varying vec2 vUv;

    void main() {
        vec4 tColor = texture2D(texture, vUv);
        if (tColor.a < 0.5) discard;
        gl_FragColor = mix(vec4(vColor.rgb, 1.0), tColor, 0.1);
    }
`;

  const pickFragmentShader = `
    uniform sampler2D texture;
    varying vec3 vColor;
    varying vec2 vUv;

    void main() {
      vec4 tColor = texture2D(texture, vUv);
      if (tColor.a < 0.25) discard;
      gl_FragColor = vec4(vColor.rgb, 1.0);
    }
`;

  const materialSettings = {
    uniforms: {
      texture: {
        type: "t",
        value: textureLoader.load(particleTexture)
      }
    },
    vertexShader: vertexShader,
    fragmentShader: fragmentShader,
    blending: THREE.NormalBlending,
    depthTest: true,
    transparent: false
  };

  const createParticleMaterial = () => {
    const material = new THREE.ShaderMaterial(materialSettings);
    return material;
  };

  const createPickingMaterial = () => {
    const material = new THREE.ShaderMaterial({
      ...materialSettings,
      fragmentShader: pickFragmentShader,
      blending: THREE.NormalBlending
    });
    return material;
  };

  const geometry = new THREE.InstancedBufferGeometry();
  const pickingGeometry = new THREE.InstancedBufferGeometry();
  const colors = [];
  const sizes = [];
  const pickingColors = [];
  const pickingColor = new THREE.Color();
  const centers = [];
  const numSpheres = 30;

  const positions = [
    -0.5, -0.5,
     0.5, -0.5,
    -0.5,  0.5,
    -0.5,  0.5,
     0.5, -0.5,
     0.5,  0.5,
  ];

  const uvs = [
     0, 0,
     1, 0,
     0, 1,
     0, 1,
     1, 0,
     1, 1,
  ];

  for (let i = 0; i < numSpheres; i++) {
    colors[3 * i] = randomNormalizedColor();
    colors[3 * i + 1] = randomNormalizedColor();
    colors[3 * i + 2] = randomNormalizedColor();

    const rgbPickingColor = pickingColor.setHex(i + 1);
    pickingColors[3 * i] = rgbPickingColor.r;
    pickingColors[3 * i + 1] = rgbPickingColor.g;
    pickingColors[3 * i + 2] = rgbPickingColor.b;

    sizes[i] = getRandomInt(5);

    centers[3 * i] = getRandomInt(20);
    centers[3 * i + 1] = getRandomInt(20);
    centers[3 * i + 2] = getRandomInt(20);
  }

  geometry.setAttribute(
    "position",
    new THREE.Float32BufferAttribute(positions, 2)
  );
  geometry.setAttribute(
    "uv",
    new THREE.Float32BufferAttribute(uvs, 2)
  );
  geometry.setAttribute(
    "customColor",
    new THREE.InstancedBufferAttribute(new Float32Array(colors), 3)
  );
  geometry.setAttribute(
    "center",
    new THREE.InstancedBufferAttribute(new Float32Array(centers), 3)
  );
  geometry.setAttribute(
    "size",
    new THREE.InstancedBufferAttribute(new Float32Array(sizes), 1));

  const material = createParticleMaterial();
  const points = new THREE.InstancedMesh(geometry, material, numSpheres);

  // setup geometry and material for GPU picking
  pickingGeometry.setAttribute(
    "position",
    new THREE.Float32BufferAttribute(positions, 2)
  );
  pickingGeometry.setAttribute(
    "uv",
    new THREE.Float32BufferAttribute(uvs, 2)
  );
  pickingGeometry.setAttribute(
    "customColor",
    new THREE.InstancedBufferAttribute(new Float32Array(pickingColors), 3)
  );
  pickingGeometry.setAttribute(
    "center",
    new THREE.InstancedBufferAttribute(new Float32Array(centers), 3)
  );
  pickingGeometry.setAttribute(
    "size",
    new THREE.InstancedBufferAttribute(new Float32Array(sizes), 1)
  );

  const pickingMaterial = createPickingMaterial();
  const pickingPoints = new THREE.InstancedMesh(pickingGeometry, pickingMaterial, numSpheres);

  scene.add(points);
  pickingScene.add(pickingPoints);

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width, height, false);
    }
    return needResize;
  }

  class GPUPickHelper {
    constructor() {
      // create a 1x1 pixel render target
      this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
      this.pixelBuffer = new Uint8Array(4);
    }
    pick(cssPosition, pickingScene, camera) {
      const { pickingTexture, pixelBuffer } = this;

      // set the view offset to represent just a single pixel under the mouse
      const pixelRatio = renderer.getPixelRatio();
      camera.setViewOffset(
        renderer.getContext().drawingBufferWidth, // full width
        renderer.getContext().drawingBufferHeight, // full top
        (cssPosition.x * pixelRatio) | 0, // rect x
        (cssPosition.y * pixelRatio) | 0, // rect y
        1, // rect width
        1 // rect height
      );
      // render the scene
      renderer.setRenderTarget(pickingTexture);
      renderer.render(pickingScene, camera);
      renderer.setRenderTarget(null);
      // clear the view offset so rendering returns to normal
      camera.clearViewOffset();
      //read the pixel
      renderer.readRenderTargetPixels(
        pickingTexture,
        0, // x
        0, // y
        1, // width
        1, // height
        pixelBuffer
      );

      const id =
        (pixelBuffer[0] << 16) | (pixelBuffer[1] << 8) | pixelBuffer[2];

      infoElem.textContent = `You clicked sphere number ${id}`;

      return id;
    }
  }

  const pickHelper = new GPUPickHelper();

  function render(time) {
    time *= 0.001; // convert to seconds;

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement;
      camera.aspect = canvas.clientWidth / canvas.clientHeight;
      camera.updateProjectionMatrix();
    }

    cameraPole.rotation.y = time * 0.1;

    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);

  function onClick(e) {
    const pickPosition = getCanvasRelativePosition(e);
    const pickedID = pickHelper.pick(pickPosition, pickingScene, camera);
  }

  function onTouch(e) {
    const touch = e.touches[0];
    const pickPosition = getCanvasRelativePosition(touch);
    const pickedID = pickHelper.pick(pickPosition, pickingScene, camera);
  }

  window.addEventListener("mousedown", onClick);
  window.addEventListener("touchstart", onTouch);
}

main();
</script></code>```

Body:
Based on your previous quesiton...

First off, Instancing is a way to tell three.js to draw the same geometry multiple times but change one more more things for each "instance". IIRC the only thing three.js supports out-of-the-box is setting a different matrix (position, orientatin, scale) for each instance. Past that, like having different colors for example, you have to write custom shaders.

Instancing allows you to ask the system to draw many things with one "ask" instead of an "ask" per thing. That means it ends up being much faster. You can think of it like anything. If want 3 hambergers you could ask someone to make you 1. When they finished you could ask them to make another. When they finished you could ask them to make a 3rd. That would be much slower than just asking them to make 3 hambergers at the start. That's not a perfect analogy but it does point out how asking for multiple things one at a time is less efficient than asking for mulitple things all at once.

Merging meshes is yet another solution, following the bad analogy above , mergeing meshes is like making one big 1pound hamberger instead of three 1/3 pound hamburgers. Flipping one larger burger and putting toppings and buns on one large burger is marginally faster than doing the same to 3 small burgers.

As for which is the best solution for you that depends. In your original code you were just drawing textured quads using Points. Points always draw their quad in screen space. Meshes on the other hand rotate in world space by default so if you made instances of quads or a merged set of quads and try to rotate them they would turn and not face the camera like Points do. If you used sphere geometry then you'd have the issues that instead of only computing 6 vertices per quad with a circle drawn on it, you'd be computing 100s or 1000s of vertices per sphere which would be slower than 6 vertices per quad.

So again it requires a custom shader to keep the points facing the camera.

To do it with instancing the short version is you decide which vertex data are repeated each instance. For example for a textured quad we need 6 vertex positions and 6 uvs. For these you make the normal BufferAttribute

Then you decide which vertex data are unique to each instance. In your case the size, the color, and the center of the point. For each of these we make an InstancedBufferAttribute

We add all of those attributes to an InstancedBufferGeometry and as the last argument we tell it how many instances.

At draw time you can think of it like this

for each instance

set size to the next value in the size attribute

set color to the next value in the color attribute

set center to the next value in the center attribute

call the vertex shader 6 times, with position and uv set to the nth value in their attributes.

In this way you get the same geometry (the positions and uvs) used multiple times but each time a few values (size, color, center) change.

body {
  margin: 0;
}
#c {
  width: 100vw;
  height: 100vh;
  display: block;
}
#info {
  position: absolute;
  right: 0;
  bottom: 0;
  color: red;
  background: black;
}

<canvas id="c"></canvas>
<div id="info"></div>
<script type="module">
// Three.js - Picking - RayCaster w/Transparency
// from https://threejsfundamentals.org/threejs/threejs-picking-gpu.html

import * as THREE from "https://threejsfundamentals.org/threejs/resources/threejs/r113/build/three.module.js";

function main() {
  const infoElem = document.querySelector("#info");
  const canvas = document.querySelector("#c");
  const renderer = new THREE.WebGLRenderer({ canvas });

  const fov = 60;
  const aspect = 2; // the canvas default
  const near = 0.1;
  const far = 200;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.z = 30;

  const scene = new THREE.Scene();
  scene.background = new THREE.Color(0);
  const pickingScene = new THREE.Scene();
  pickingScene.background = new THREE.Color(0);

  // put the camera on a pole (parent it to an object)
  // so we can spin the pole to move the camera around the scene
  const cameraPole = new THREE.Object3D();
  scene.add(cameraPole);
  cameraPole.add(camera);

  function randomNormalizedColor() {
    return Math.random();
  }

  function getRandomInt(n) {
    return Math.floor(Math.random() * n);
  }

  function getCanvasRelativePosition(e) {
    const rect = canvas.getBoundingClientRect();
    return {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    };
  }

  const textureLoader = new THREE.TextureLoader();
  const particleTexture =
    "https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/ball.png";

  const vertexShader = `
    attribute float size;
    attribute vec3 customColor;
    attribute vec3 center;

    varying vec3 vColor;
    varying vec2 vUv;

    void main() {
        vColor = customColor;
        vUv = uv;
        vec3 viewOffset = position * size ;
        vec4 mvPosition = modelViewMatrix * vec4(center, 1) + vec4(viewOffset, 0);
        gl_Position = projectionMatrix * mvPosition;
    }
`;

  const fragmentShader = `
    uniform sampler2D texture;
    varying vec3 vColor;
    varying vec2 vUv;

    void main() {
        vec4 tColor = texture2D(texture, vUv);
        if (tColor.a < 0.5) discard;
        gl_FragColor = mix(vec4(vColor.rgb, 1.0), tColor, 0.1);
    }
`;

  const pickFragmentShader = `
    uniform sampler2D texture;
    varying vec3 vColor;
    varying vec2 vUv;

    void main() {
      vec4 tColor = texture2D(texture, vUv);
      if (tColor.a < 0.25) discard;
      gl_FragColor = vec4(vColor.rgb, 1.0);
    }
`;

  const materialSettings = {
    uniforms: {
      texture: {
        type: "t",
        value: textureLoader.load(particleTexture)
      }
    },
    vertexShader: vertexShader,
    fragmentShader: fragmentShader,
    blending: THREE.NormalBlending,
    depthTest: true,
    transparent: false
  };

  const createParticleMaterial = () => {
    const material = new THREE.ShaderMaterial(materialSettings);
    return material;
  };

  const createPickingMaterial = () => {
    const material = new THREE.ShaderMaterial({
      ...materialSettings,
      fragmentShader: pickFragmentShader,
      blending: THREE.NormalBlending
    });
    return material;
  };

  const geometry = new THREE.InstancedBufferGeometry();
  const pickingGeometry = new THREE.InstancedBufferGeometry();
  const colors = [];
  const sizes = [];
  const pickingColors = [];
  const pickingColor = new THREE.Color();
  const centers = [];
  const numSpheres = 30;

  const positions = [
    -0.5, -0.5,
     0.5, -0.5,
    -0.5,  0.5,
    -0.5,  0.5,
     0.5, -0.5,
     0.5,  0.5,
  ];

  const uvs = [
     0, 0,
     1, 0,
     0, 1,
     0, 1,
     1, 0,
     1, 1,
  ];

  for (let i = 0; i < numSpheres; i++) {
    colors[3 * i] = randomNormalizedColor();
    colors[3 * i + 1] = randomNormalizedColor();
    colors[3 * i + 2] = randomNormalizedColor();

    const rgbPickingColor = pickingColor.setHex(i + 1);
    pickingColors[3 * i] = rgbPickingColor.r;
    pickingColors[3 * i + 1] = rgbPickingColor.g;
    pickingColors[3 * i + 2] = rgbPickingColor.b;

    sizes[i] = getRandomInt(5);

    centers[3 * i] = getRandomInt(20);
    centers[3 * i + 1] = getRandomInt(20);
    centers[3 * i + 2] = getRandomInt(20);
  }

  geometry.setAttribute(
    "position",
    new THREE.Float32BufferAttribute(positions, 2)
  );
  geometry.setAttribute(
    "uv",
    new THREE.Float32BufferAttribute(uvs, 2)
  );
  geometry.setAttribute(
    "customColor",
    new THREE.InstancedBufferAttribute(new Float32Array(colors), 3)
  );
  geometry.setAttribute(
    "center",
    new THREE.InstancedBufferAttribute(new Float32Array(centers), 3)
  );
  geometry.setAttribute(
    "size",
    new THREE.InstancedBufferAttribute(new Float32Array(sizes), 1));

  const material = createParticleMaterial();
  const points = new THREE.InstancedMesh(geometry, material, numSpheres);

  // setup geometry and material for GPU picking
  pickingGeometry.setAttribute(
    "position",
    new THREE.Float32BufferAttribute(positions, 2)
  );
  pickingGeometry.setAttribute(
    "uv",
    new THREE.Float32BufferAttribute(uvs, 2)
  );
  pickingGeometry.setAttribute(
    "customColor",
    new THREE.InstancedBufferAttribute(new Float32Array(pickingColors), 3)
  );
  pickingGeometry.setAttribute(
    "center",
    new THREE.InstancedBufferAttribute(new Float32Array(centers), 3)
  );
  pickingGeometry.setAttribute(
    "size",
    new THREE.InstancedBufferAttribute(new Float32Array(sizes), 1)
  );

  const pickingMaterial = createPickingMaterial();
  const pickingPoints = new THREE.InstancedMesh(pickingGeometry, pickingMaterial, numSpheres);

  scene.add(points);
  pickingScene.add(pickingPoints);

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width, height, false);
    }
    return needResize;
  }

  class GPUPickHelper {
    constructor() {
      // create a 1x1 pixel render target
      this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
      this.pixelBuffer = new Uint8Array(4);
    }
    pick(cssPosition, pickingScene, camera) {
      const { pickingTexture, pixelBuffer } = this;

      // set the view offset to represent just a single pixel under the mouse
      const pixelRatio = renderer.getPixelRatio();
      camera.setViewOffset(
        renderer.getContext().drawingBufferWidth, // full width
        renderer.getContext().drawingBufferHeight, // full top
        (cssPosition.x * pixelRatio) | 0, // rect x
        (cssPosition.y * pixelRatio) | 0, // rect y
        1, // rect width
        1 // rect height
      );
      // render the scene
      renderer.setRenderTarget(pickingTexture);
      renderer.render(pickingScene, camera);
      renderer.setRenderTarget(null);
      // clear the view offset so rendering returns to normal
      camera.clearViewOffset();
      //read the pixel
      renderer.readRenderTargetPixels(
        pickingTexture,
        0, // x
        0, // y
        1, // width
        1, // height
        pixelBuffer
      );

      const id =
        (pixelBuffer[0] << 16) | (pixelBuffer[1] << 8) | pixelBuffer[2];

      infoElem.textContent = `You clicked sphere number ${id}`;

      return id;
    }
  }

  const pickHelper = new GPUPickHelper();

  function render(time) {
    time *= 0.001; // convert to seconds;

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement;
      camera.aspect = canvas.clientWidth / canvas.clientHeight;
      camera.updateProjectionMatrix();
    }

    cameraPole.rotation.y = time * 0.1;

    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);

  function onClick(e) {
    const pickPosition = getCanvasRelativePosition(e);
    const pickedID = pickHelper.pick(pickPosition, pickingScene, camera);
  }

  function onTouch(e) {
    const touch = e.touches[0];
    const pickPosition = getCanvasRelativePosition(touch);
    const pickedID = pickHelper.pick(pickPosition, pickingScene, camera);
  }

  window.addEventListener("mousedown", onClick);
  window.addEventListener("touchstart", onTouch);
}

main();
</script>


问:
Eureka cluster :org.apache.http.conn.ConnectTimeoutException
I'm getting an Exception when trying to build a Spring Cloud Eureka cluster

:org.apache.http.conn.ConnectTimeoutException

Here is the three application.yml of eureka server

server_7001

server_7002

server_7003

and the application.yml of the service provider

Service provider

I can start server_7001, server_7002 and server_7003 successfully. But while running the service provider, getting an exception as shown below

答:
In /etc/hosts of server_7001,
server_7002 and server_7003

Define :

```<code>ip_address_of_server_7001 eureka7001.com
ip_address_of_server_7002 eureka7002.com
ip_address_of_server_7003 eureka7003.com
</code>```

Body:
In /etc/hosts of server_7001,
server_7002 and server_7003

Define :

ip_address_of_server_7001 eureka7001.com
ip_address_of_server_7002 eureka7002.com
ip_address_of_server_7003 eureka7003.com


问:
virtualenv in python : can't create full files and activate not working
I am creating a new python environment by using command virtualenv myenv. The command gets executed successfully. But whenever I try activating the environment I get nothing (no activation is taking place) when I open the created folder, the files available in virtual env are libs, scripts and pyvenv.cfg only. Nothing else other than these 3.

答:
Try to create your environment with venv:

```<code>python3 -m venv /path/to/new/virtual/environment
</code>```

And activate it normally.

In windows, you can use in the cmd :

```<code>py -m venv env
</code>```

and activate it :

```<code>.\env\Scripts\activate
</code>```

Body:
Try to create your environment with venv:

python3 -m venv /path/to/new/virtual/environment

And activate it normally.

In windows, you can use in the cmd :

py -m venv env

and activate it :

.\env\Scripts\activate


问:
There is exception when install apk in android 10 by intent (android.content.ActivityNotFoundException)
I'm testing my android application to support android version 10.

When I test application in android 10 device,
there is some problem with the apk install process.

Here is my source code and test information:-

```<code>        File realFilePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/app-debug.apk");
        if(realFilePath.exists()) {

            Uri apkUri = Uri.fromFile(realFilePath);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
</code>```

error message

```<code>2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///storage/emulated/0/app-debug.apk typ=application/vnd.android.package-archive flg=0x10000000 }
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2058)
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1716)
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Activity.startActivityForResult(Activity.java:5192)
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Activity.startActivityForResult(Activity.java:5150)
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Activity.startActivity(Activity.java:5521)
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Activity.startActivity(Activity.java:5489)
</code>```

TEST information

```<code>================================
android {
    compileSdkVersion 28
    buildToolsVersion "28.0.3"
    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 15
        targetSdkVersion 22
================================
</code>```

Android 9: there is no exception.
Android 10: there is ActivityNotFoundException and fail to install apk.

I already know that I need to use a file provider to access an external file.
But, as you can see that I set the targetSdkVersion version to 22.

targetSdkVersion 22

Why does the error only occur on an Android 10 device?

答:
Try this:

```<code>if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
}
</code>```

If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it's safe to call startActivity(). If the result is null, you should not use the intent.

Body:
I'm testing my android application to support android version 10.

When I test application in android 10 device,
there is some problem with the apk install process.

Here is my source code and test information:-

        File realFilePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/app-debug.apk");
        if(realFilePath.exists()) {

            Uri apkUri = Uri.fromFile(realFilePath);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

error message

2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///storage/emulated/0/app-debug.apk typ=application/vnd.android.package-archive flg=0x10000000 }
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2058)
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1716)
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Activity.startActivityForResult(Activity.java:5192)
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Activity.startActivityForResult(Activity.java:5150)
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Activity.startActivity(Activity.java:5521)
2020-02-20 14:02:13.987 9572-9572/com.example.myapplication W/System.err:     at android.app.Activity.startActivity(Activity.java:5489)

TEST information

================================
android {
    compileSdkVersion 28
    buildToolsVersion "28.0.3"
    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 15
        targetSdkVersion 22
================================

Android 9: there is no exception.
Android 10: there is ActivityNotFoundException and fail to install apk.

I already know that I need to use a file provider to access an external file.
But, as you can see that I set the targetSdkVersion version to 22.

targetSdkVersion 22

Why does the error only occur on an Android 10 device?

Body:
Try this:

if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
}

If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it's safe to call startActivity(). If the result is null, you should not use the intent.


问:
How can I monitor objective-c method return value changes
I'm using Sparkle http://sparkle-project.org/ framework for autoupdates in my application. I have a UI item which enables/disables automatic updates downloads, but I can use neither Interface Builder bindings as stated in documentation for Sparkle, nor KVO, because there is no property for automatic updates download - only getter and setter methods. Can I hook the setter method and have a callback invoked when this option changes through Sparkle's interface interaction.

What can I do in this situation?

Thank you.

答:
If there are getter and setter methods, then there is implicitly a property, even if one is not declared. You can use KVO with it just fine. In fact, for many years, this was the only way to do KVO; there were no explicit properties. Cocoa treats anything with an appropriately named getter and setter as a property.

Bindings use the same mechanism, so you should be able to use bindings as well. Don't let the lack of a declared property scare you off.


问:
Beautifulsoup not finding the tag
im working on a project on beautifulsoup

```<code>from bs4 import BeautifulSoup as soup
from requests import get

url = "https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1"
clnt = get(url)
page=soup(clnt.text,"html.parser")
container = page.findAll("div",{"class":"lemon--div__373c0__1mboc container__373c0__ZB8u4 hoverable__373c0__3CcYQ margin-t3__373c0__1l90z margin-b3__373c0__q1DuY padding-t3__373c0__1gw9E padding-r3__373c0__57InZ padding-b3__373c0__342DA padding-l3__373c0__1scQ0 border--top__373c0__3gXLy border--right__373c0__1n3Iv border--bottom__373c0__3qNtD border--left__373c0__d1B7K border-color--default__373c0__3-ifU"})

container = container[1]
url2= "https://www.yelp.com"+container.a["href"]
clnt2 = get(url2)
page2 = soup(clnt2.text, 'html.parser')

info = page2.find("div",{"class":"lemon--div__373c0__1mboc island__373c0__3fs6U u-padding-t1 u-padding-r1 u-padding-b1 u-padding-l1 border--top__373c0__19Owr border--right__373c0__22AHO border--bottom__373c0__uPbXS border--left__373c0__1SjJs border-color--default__373c0__2oFDT background-color--white__373c0__GVEnp"})

contact=info.div (Example contact variable)
</code>```

In this "info" variable i am getting the div which has all the contact details, I want to grab the Contact number form this div

And as I print this "info" variable it also shows that contact no. is present in the variable including other details but as I traverse through the div's to get the Contact No. I couldn't find it.
I have also tried to get all the child div's and even including the class of the div itself I wasn't able to get that

First url given is this  :https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1

Second url "url2" is this : https://www.yelp.com/biz/levain-bakery-new-york Which has the Contact details

Any Solutions ???

答:
try this. I have tried for the second URL and it gives a contact number.

```<code>url = 'https://www.yelp.com/biz/levain-bakery-new-york'
page = requests.get(url)
soup1 = BeautifulSoup(page.content, "lxml")

info = soup1.find_all("div", {
    "class": "lemon--div__373c0__1mboc island-section__373c0__3vKXy border--top__373c0__19Owr border-color--default__373c0__2oFDT"})

contact_number = info[1].find("p", attrs={
    'class': 'lemon--p__373c0__3Qnnj text__373c0__2pB8f text-color--normal__373c0__K_MKN text-align--left__373c0__2pnx_'}).text

print(contact_number)
</code>```

approve the answer if useful. others might help it out.

Title: Beautifulsoup not finding the tag

Body:
im working on a project on beautifulsoup

from bs4 import BeautifulSoup as soup
from requests import get

url = "https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1"
clnt = get(url)
page=soup(clnt.text,"html.parser")
container = page.findAll("div",{"class":"lemon--div__373c0__1mboc container__373c0__ZB8u4 hoverable__373c0__3CcYQ margin-t3__373c0__1l90z margin-b3__373c0__q1DuY padding-t3__373c0__1gw9E padding-r3__373c0__57InZ padding-b3__373c0__342DA padding-l3__373c0__1scQ0 border--top__373c0__3gXLy border--right__373c0__1n3Iv border--bottom__373c0__3qNtD border--left__373c0__d1B7K border-color--default__373c0__3-ifU"})

container = container[1]
url2= "https://www.yelp.com"+container.a["href"]
clnt2 = get(url2)
page2 = soup(clnt2.text, 'html.parser')

info = page2.find("div",{"class":"lemon--div__373c0__1mboc island__373c0__3fs6U u-padding-t1 u-padding-r1 u-padding-b1 u-padding-l1 border--top__373c0__19Owr border--right__373c0__22AHO border--bottom__373c0__uPbXS border--left__373c0__1SjJs border-color--default__373c0__2oFDT background-color--white__373c0__GVEnp"})

contact=info.div (Example contact variable)

In this "info" variable i am getting the div which has all the contact details, I want to grab the Contact number form this div

And as I print this "info" variable it also shows that contact no. is present in the variable including other details but as I traverse through the div's to get the Contact No. I couldn't find it.
I have also tried to get all the child div's and even including the class of the div itself I wasn't able to get that

First url given is this  :https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1

Second url "url2" is this : https://www.yelp.com/biz/levain-bakery-new-york Which has the Contact details

Any Solutions ???

Body:
try this. I have tried for the second URL and it gives a contact number.

url = 'https://www.yelp.com/biz/levain-bakery-new-york'
page = requests.get(url)
soup1 = BeautifulSoup(page.content, "lxml")

info = soup1.find_all("div", {
    "class": "lemon--div__373c0__1mboc island-section__373c0__3vKXy border--top__373c0__19Owr border-color--default__373c0__2oFDT"})

contact_number = info[1].find("p", attrs={
    'class': 'lemon--p__373c0__3Qnnj text__373c0__2pB8f text-color--normal__373c0__K_MKN text-align--left__373c0__2pnx_'}).text

print(contact_number)

approve the answer if useful. others might help it out.


答:
If want first non missing values per columns per groups if exist use GroupBy.first:

```<code>df1 = df.groupby('date', as_index=False).first()
</code>```

Title: How to properly stack or unstack pandas dataframe?

Body:
I've been trying to stack or unstack the following dataframe:

       Eelde  Southend-On-Sea     Ulceby        date
   24.000000              NaN        NaN  2020-02-16
1  22.673913              NaN        NaN  2020-02-17
0        NaN              NaN  24.312500  2020-02-17
0        NaN        19.130435        NaN  2020-02-17
0  14.000000              NaN        NaN  2020-02-17
1  19.239130              NaN        NaN  2020-02-18
0        NaN              NaN  19.687500  2020-02-18
0        NaN        17.760870        NaN  2020-02-18
0  20.500000              NaN        NaN  2020-02-18
1  12.978261              NaN        NaN  2020-02-19
0        NaN              NaN  19.041667  2020-02-19
0        NaN        14.200000        NaN  2020-02-19

Let us not focus on the double index, but focusing on combining the rows.

The desired output should look like:

   index     Eelde  Southend-On-Sea      Ulceby     date
0         24.000000             NaN         NaN     2020-02-16
0      0  14.00000        19.130435     24.312500   2020-02-17
1      1  19.23913        17.76087      19.6875     2020-02-18
2      0  12.978261       14.200000     19.041667   2020-02-19

Body:
If want first non missing values per columns per groups if exist use GroupBy.first:

df1 = df.groupby('date', as_index=False).first()


问:
How to run batch SQL file using c#?
I want to run a big set of SQL statements in one go in c#; this SQL also contains numerous local variables. I tried to run that SQL using ADO.Net but I got an exception: "Cannot declare more than 10000 local variables". Can I run these SQL statements in a batch file (using c#) to avoid this exception/limitation? If yes, how? Is there any better approach?

I am using SQL Server 2008 R2 and C# 4.0.

Looking forward to assistance.

答: You could create a .bat file that runs sqlcmd and exec your batch sql file.  in c# you can then launch a cmd window as a process, sending the location of the .bat file as an argument.</p>

Title: How to run batch SQL file using c#?


问:
Missing category to be shown at bottom
I want category of 'Missing' to be shown at bottom in result after groupby. There can be any character value in column x. See example below.</p>

```<code>library(dplyr)
df <- data.frame(x = c('Ap','LA','MN', 'Missing','ZA'),
                 y = c('PA','NA','DN', 'Missing','ZD'),
                 z = 1:5,
                 stringsAsFactors = F)

df %>% group_by(x) %>% summarise(x1 = sum(z))
</code>```

答:
You can adjust the factor levels, keeping "missing" at the end.  </p>

```<code>librrary(dplyr)

levels <- c(setdiff(unique(df$x), 'Missing'), 'Missing')

df %>%
  mutate(x = factor(x, levels = levels)) %>%
  group_by(x) %>%
  summarise(x1 = sum(z))

# A tibble: 5 x 2
#  x          x1
#  <fct>   <int>
#1 Ap          1
#2 LA          2
#3 MN          3
#4 ZA          5
#5 Missing     4
</code>```

Title: Missing category to be shown at bottom

Body:
I want category of 'Missing' to be shown at bottom in result after groupby. There can be any character value in column x. See example below.

library(dplyr)
df <- data.frame(x = c('Ap','LA','MN', 'Missing','ZA'),
                 y = c('PA','NA','DN', 'Missing','ZD'),
                 z = 1:5,
                 stringsAsFactors = F)

df %>% group_by(x) %>% summarise(x1 = sum(z))

Body:
You can adjust the factor levels, keeping "missing" at the end.

librrary(dplyr)

levels <- c(setdiff(unique(df$x), 'Missing'), 'Missing')

df %>%
  mutate(x = factor(x, levels = levels)) %>%
  group_by(x) %>%
  summarise(x1 = sum(z))

# A tibble: 5 x 2
#  x          x1
#  <fct>   <int>
#1 Ap          1
#2 LA          2
#3 MN          3
#4 ZA          5
#5 Missing     4


问:
Poor icon graphics on windows excecutable app
Why my electron app has poor icon graphics

I recently create and electron app however when i package it with electron rebuild the icon graphics of the installer and installed app are really poor on windows.

The icon am using is 512x512 and i don't have the same problem when i package it to Linux executable .deb file.

As you can see the icon is not perfect.

Is there a way to improve the icon quality?

答:
It's because your 512x512 icon was scaled down to fit with windows desktop's icons's size.

I would suggest you to create an ico file from your icon, this file contains following multiple sizes: 16, 24, 32, 48, 64, 128, 256.

After that, put your icon under build directory with name as icon.ico